-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsql.py
More file actions
3109 lines (2312 loc) · 97.2 KB
/
Copy pathsql.py
File metadata and controls
3109 lines (2312 loc) · 97.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
##########################################################
#
# Copyright (c) 2005, Southpaw Technology
# All Rights Reserved
#
# PROPRIETARY INFORMATION. This software is proprietary to
# Southpaw Technology, and is not to be reproduced, transmitted,
# or disclosed in any way without written permission.
#
#
#
__all__ = ["SqlException", "DatabaseException", "Sql", "DbContainer", "DbResource", "DbPasswordUtil", "Select", "Insert", "Update", "CreateTable", "DropTable", "AlterTable"]
import os, types, thread, sys
import re, datetime
from threading import Lock
from pyasm.common import Config, TacticException, Environment
# import database libraries
DATABASE_DICT = {}
try:
import pyodbc
DATABASE_DICT["SQLServer"] = pyodbc
#Config.set_value("database", "vendor", "SQLServer")
except ImportError, e:
pass
try:
import psycopg2
# set to return only unicode
import psycopg2.extensions
psycopg2.extensions.register_type(psycopg2.extensions.UNICODE)
#psycopg2.extensions.register_type(psycopg2.extensions.UNICODEARRAY)
DATABASE_DICT["PostgreSQL"] = psycopg2
except ImportError, e:
pass
try:
ORACLE_HOME = Config.get_value("database", "ORACLE_HOME")
if ORACLE_HOME:
os.environ['ORACLE_HOME'] = str(ORACLE_HOME)
NLS_LANG = Config.get_value("database", "NLS_LANG")
if not NLS_LANG:
NLS_LANG = 'american_america.us7ascii'
os.environ['NLS_LANG'] = str(NLS_LANG)
import cx_Oracle
DATABASE_DICT["Oracle"] = cx_Oracle
except ImportError, e:
pass
# MySQL
try:
import MySQLdb
DATABASE_DICT["MySQL"] = MySQLdb
except ImportError, e:
pass
# Sqlite
try:
import sqlite3 as sqlite
DATABASE_DICT["Sqlite"] = sqlite
except ImportError, e:
pass
# TACTIC Database
try:
from database_impl import TacticImpl
DATABASE_DICT["TACTIC"] = TacticImpl
except ImportError, e:
pass
VENDORS = ['PostgreSQL', 'SQLServer', 'Oracle', 'Sqlite', 'MySQL', 'TACTIC']
# Get the configured Db.
DATABASE = None
pgdb = None
def set_default_vendor(vendor=None):
global DATABASE
global pgdb
if vendor:
DATABASE = vendor
return
DATABASE = Config.get_value("database", "vendor")
if not DATABASE:
DATABASE = "PostgreSQL"
assert DATABASE in VENDORS
pgdb = DATABASE_DICT.get(DATABASE)
if not pgdb:
raise TacticException("ERROR: database library for [%s] is not installed" % DATABASE)
set_default_vendor()
from pyasm.common import *
from database_impl import *
from transaction import *
class SqlException(TacticException):
pass
class DatabaseException(TacticException):
pass
class Sql(Base):
'''Class that handles all access to the database'''
DO_QUERY_ERR = "do_query error"
def __init__(my, database_name, host=None, user=None, password=None, vendor=None, port=None):
if DbResource.is_instance(database_name):
db_resource = database_name
host = db_resource.get_host()
port = db_resource.get_port()
database_name = db_resource.get_database()
vendor = db_resource.get_vendor()
user = db_resource.get_user()
password = db_resource.get_password()
else:
#assert type(database_name) in types.StringTypes
# allow unicode
assert isinstance(database_name, basestring)
my.database_name = database_name
# get the database from the config file
if host:
my.host = host
else:
my.host = Config.get_value("database", "server")
if user:
my.user = user
else:
my.user = Config.get_value("database", "user")
if port: my.port = port
else: my.port = Config.get_value("database", "port")
if password:
my.password = password
# get from encrypted file
else:
my.password = DbPasswordUtil.get_password()
if not my.host:
my.host = "localhost"
my.vendor = vendor
if not my.vendor:
my.vendor = Config.get_value("database", "vendor")
my.database_impl = DatabaseImpl.get(my.vendor)
my.pgdb = DATABASE_DICT.get(my.vendor)
if not my.pgdb:
raise TacticException("ERROR: database library for [%s] is not installed" % my.vendor)
my.cursor = None
my.results = ()
my.conn = None
my.last_query = None
my.row_count = -1
my.transaction_count = 0
my.description = None
my.impl = DatabaseImpl.get()
def get_db_resource(my):
db_resource = DbResource(my.database_name, host=my.host, port=my.port, vendor=my.vendor, user=my.user, password=my.password)
return db_resource
def set_default_vendor(vendor):
set_default_vendor(vendor)
set_default_vendor = staticmethod(set_default_vendor)
#def __del__(my):
# print "CONNECT: delete: ", my
### These are for the default .. most often for the sthpw database
def default_database_exists(cls, database):
'''test if a table exists in a db'''
impl = Sql.get_database_impl()
return impl.database_exists(database)
default_database_exists = classmethod(default_database_exists)
def get_default_database_version(cls):
return cls.get_default_database_impl().get_version()
get_default_database_version = classmethod(get_default_database_version)
def get_default_database_type():
return Config.get_value("database", "vendor")
get_default_database_type = staticmethod(get_default_database_type)
def get_default_database_impl():
return DatabaseImpl.get()
get_default_database_impl = staticmethod(get_default_database_impl)
def get_default_timestamp_now():
return DatabaseImpl.get().get_timestamp_now()
get_default_timestamp_now = staticmethod(get_default_timestamp_now)
#####
def get_database_version(my):
return my.get_database_impl().get_version()
def get_database_type(my):
return my.vendor
def get_database_impl(my):
return my.database_impl
def get_timestamp_now(my):
return my.database_impl.get_timestamp_now()
def get_table_description(my):
return my.description
def get_database_name(my):
return my.database_name
def get_host(my):
return my.host
def get_user(my):
return my.user
def get_password(my):
return my.password
def get_connection(my):
'''get the underlying database connection'''
return my.conn
def get_columns_from_description(my):
columns = []
for description in my.description:
columns.append( description[0] )
# In some versions of sqlite, the full name is returned with quotes
# and table, so just process this
fixed_columns = []
for column in columns:
parts = column.split(".")
column = parts[-1]
column = column.strip('"')
fixed_columns.append(column)
return fixed_columns
def get_columns(my,table=None,use_cache=True):
'''Returns a list of string ordered columns contained in this table
'''
db_resource = my.get_db_resource()
database = my.get_database_name()
key = '%s:%s' %(db_resource, table)
if use_cache:
columns = Container.get_dict("Sql:table_columns", key)
if columns:
return columns[:]
#return columns
# use global cache
if database == 'sthpw':
from pyasm.biz import CacheContainer
cache = CacheContainer.get("sthpw_column_info")
if cache:
columns = cache.get_value_by_key("columns", table)
if columns != None:
return columns[:]
#return columns
impl = my.get_database_impl()
columns = impl.get_columns(db_resource, table)
if use_cache:
Container.put_dict("Sql:table_columns", key, columns)
return columns[:]
def get_table_info(my):
impl = my.get_database_impl()
info = impl.get_table_info(my.get_db_resource())
return info
def get_column_info(my, table, column=None, use_cache=True):
impl = my.get_database_impl()
info = impl.get_column_info(my.get_db_resource(), table)
if not column:
return info
else:
return info.get(column)
def get_column_types(my, table):
impl = my.get_database_impl()
return impl.get_column_types(my.get_db_resource(), table)
def get_column_nullables(my, table):
impl = my.get_database_impl()
return impl.get_column_nullables(my.get_db_resource(), table)
def is_in_transaction(my):
'''Returns a boolean showing whether the database is in transaction
or not'''
if my.transaction_count <= 0:
return False
else:
return True
def get_row_count(my):
'''returns the number of rows effected in the last update'''
return my.row_count
def start(my):
'''start a transaction'''
my.transaction_count += 1
def set_savepoint(my, name='save_pt'):
'''set a savepoint'''
stmt = my.impl.set_savepoint(name)
if stmt:
cursor = my.conn.cursor()
cursor.execute(stmt)
def rollback_savepoint(my, name='save_pt', release=True):
'''rollback to a savepoint'''
my.cursor = my.conn.cursor()
stmt = my.impl.rollback_savepoint(name)
if not stmt:
return
my.cursor.execute(stmt)
if release:
my.release_savepoint(name)
def release_savepoint(my, name='save_pt'):
release_stmt = my.impl.release_savepoint(name)
if not release_stmt:
return
if release_stmt:
my.cursor.execute(release_stmt)
def commit(my):
'''commit the transaction'''
my.transaction_count -= 1
# only commit if transaction count = 0 to support embedded
# transactions
#if my.transaction_count == 0:
if my.transaction_count <= 0:
try:
my.transaction_count = 0
# NOTE: protect against database being already closed.
# Note sure why it is being closed, but there are some
# extreme circumstances where this will occur
if not my.conn:
# reconnect
my.connect()
else:
my.conn.commit()
# DEPRECATED!
# once this connection has been commited, then release it back
# to sql_dict
#DbContainer.return_to_pool(my)
sql_dict = DbContainer._get_sql_dict()
database_name = my.get_database_name()
sql_dict[database_name] = my
except my.pgdb.OperationalError, e:
raise SqlException(e.__str__())
def rollback(my, force=False):
'''rollback the transaction'''
if force or my.transaction_count > 0:
if my.conn:
my.conn.rollback()
my.transaction_count = 0
def connect(my):
'''connect to the database'''
if not my.host:
raise DatabaseException("Server setting is empty")
# pgdb connection code
auth = None
try:
if my.vendor == "PostgreSQL":
# psycopg connection code
if my.password == "" or my.password == "none":
password_str = ""
else:
password_str = "password=%s" % my.password
if not my.port:
my.port = 5432
sslmode = "require"
sslmode = "disable"
auth = "host=%s port=%s dbname=%s sslmode=%s user=%s %s" % \
(my.host, my.port, my.database_name, sslmode, my.user, password_str)
my.conn = my.pgdb.connect(auth)
elif my.vendor == "Sqlite":
db_dir = Config.get_value("database", "sqlite_db_dir")
if not db_dir:
#install_dir = Environment.get_install_dir()
#db_dir = "%s/src/install/start/db" % install_dir
data_dir = Environment.get_data_dir()
db_dir = "%s/db" % data_dir
# DEBUG: this -1 database seems to popup
if my.database_name in [-1, '-1']:
raise DatabaseException("Database '-1' is not valid")
auth = "%s/%s.db" % (db_dir, my.database_name)
my.conn = sqlite.connect(auth, isolation_level="DEFERRED" )
# immediately cache all of the columns in the database. This
# is because get_column_info in Sqlite requires a PRAGMA
# statement which forces a transaction to commit
from database_impl import SqliteImpl
SqliteImpl.cache_database_info(my)
elif my.vendor == "MySQL":
my.conn = MySQLdb.connect( db=my.database_name,
host=my.host,
user=my.user,
passwd=my.password )
my.do_query("SET sql_mode='ANSI_QUOTES'");
elif my.vendor == "Oracle":
# if we connect as a single user (like most databases, then
# use the user name), otherwise if we connect by schema,
# we use the database name. This is determined by whether
# or not the user field is empty
if not my.user:
auth = '%s/%s@%s' % (my.database_name, my.password, my.host)
else:
auth = '%s/%s@%s' % (my.user, my.password, my.host)
my.conn = my.pgdb.connect(str(auth))
elif my.vendor == "SQLServer":
sqlserver_driver = '{SQL Server}'
# pyodbc connection code
if my.password == "" or my.password == "none":
password_str = ""
else:
password_str = my.password
# >>> cnxn = pyodbc.connect('DRIVER={SQL Server};SERVER=localhost,1433;DATABASE=my_db;UID=tactic;PWD=south123paw')
#
auth = "DRIVER=%s; SERVER=%s,%s; DATABASE=%s; UID=%s; PWD=%s" % \
(sqlserver_driver, my.host, my.port, my.database_name, my.user, password_str)
my.conn = pyodbc.connect(auth)
elif my.vendor == "TACTIC":
from pyasm.search import TacticImpl
my.conn = TacticImpl()
#raise DatabaseException("Database TACTIC not yet implemented")
else:
raise DatabaseException("Unsupported Database [%s]" % my.vendor)
except Exception, e:
#print "ERROR: connecting to database [%s, %s]" % (my.host, my.database_name), e.__str__()
raise
raise DatabaseException(e)
assert my.conn
return my
# Resets sequence so that the next available ID number is exactly one greater than the highest existing ID
# number of the given table
#
def reset_sequence_for_table(my, table, database=None):
# FIXME: currently only available for the Oracle database
impl = my.get_database_impl()
stmt = impl.get_reset_table_sequence_statement(table, database)
from sql import DbContainer
sql = DbContainer.get(my.get_database_name())
results = sql.do_update(stmt)
def modify_column(my, table, column, type, not_null=None):
impl = my.get_database_impl()
statements = impl.get_modify_column(table, column, type, not_null)
from sql import DbContainer
sql = DbContainer.get(my.get_database_name())
for statement in statements:
sql.do_update(statement)
def clear_results(my):
# MySQL uses tuples
impl = my.get_database_impl()
if impl.get_database_type() not in ['MySQL']:
for i in range(0, len(my.results)):
my.results[i] = None
my.results = []
# FIXME: is there any reason to have this function. This should be
# incorporated into do_query.
def execute(my, query, num_attempts=0):
"""execute a query"""
#raise SqlException("FIXME: Incorporate into do_query")
try:
# in case of accidental loss of connection
if not my.conn:
# reconnect
my.connect()
my.query = query
my.cursor = my.conn.cursor()
my.cursor.execute(query)
my.description = my.cursor.description
return
except pgdb.OperationalError, e:
# A reconnect will only be attempted on the first query.
# This is because subsequent could be in a transaction and
# closing and reconnecting will completely mess up the transaction
#
first_query = Container.get("Sql::%s::first_query" % my.database_name)
if first_query == False:
raise SqlException("%s: %s\n%s" % (my.DO_QUERY_ERR, query,e.__str__()) )
if num_attempts >= 3:
print "ERROR: three failed attempts have been made to access [%s]" % my.database_name
raise SqlException("%s: %s\n%s" % (my.DO_QUERY_ERR, query,e.__str__()) )
Container.put("Sql::first_query", False)
# try to reconnect
print "WARNING: a database error [%s] has been encountered: " % e.__class__.__name__
print str(e)
print "Attempting to reconnect and reissue query"
# try closing: oracle throws an exception if you try to close
# on an already closed connection
try:
my.close()
except:
pass
my.connect()
return my.do_query(query, num_attempts=num_attempts+1)
except pgdb.Error, e:
error_msg = str(e)
print "ERROR: %s: "%my.DO_QUERY_ERR, error_msg, str(query)
# don't include the error_msg in Exception to avoid decoding error
raise SqlException("%s: %s\n" % (my.DO_QUERY_ERR, query))
def do_query(my, query, num_attempts=0):
"""execute a query"""
my.clear_results()
try:
# in case of accidental loss of connection
if not my.conn:
# reconnect
my.connect()
#import time
#start = time.time()
#print my.database_name, query
my.query = query
my.cursor = my.conn.cursor()
#import time
#start = time.time()
my.cursor.execute(query)
my.description = my.cursor.description
# copy the data structure because LOBs in Oracle become stale
if my.get_database_type() == "Oracle":
import cx_Oracle
my.results = []
for x in my.cursor:
result = []
for y in x:
if isinstance(y, cx_Oracle.LOB):
result.append(str(y))
else:
result.append(y)
my.results.append(result)
else:
my.results = my.cursor.fetchall()
my.cursor.close()
#print time.time() - start
return my.results
except my.pgdb.OperationalError, e:
# A reconnect will only be attempted on the first query.
# This is because subsequent could be in a transaction and
# closing and reconnecting will completely mess up the transaction
#
key = "Sql::%s::%s::first_query" % (my.vendor, my.database_name)
first_query = Container.get(key)
if first_query == False:
raise SqlException("%s: %s\n%s" % (my.DO_QUERY_ERR, query,e.__str__()) )
if num_attempts >= 3:
print "ERROR: three failed attempts have been made to access [%s]" % my.database_name
raise SqlException("%s: %s\n%s" % (my.DO_QUERY_ERR, query,e.__str__()) )
Container.put("Sql::first_query", False)
# try to reconnect
print "WARNING: a database error [%s] has been encountered: " % e.__class__.__name__
print str(e)
print "Attempting to reconnect and reissue query"
# try closing: oracle throws an exception if you try to close
# on an already closed connection
try:
my.close()
except:
pass
my.connect()
return my.do_query(query, num_attempts=num_attempts+1)
except my.pgdb.Error, e:
error_msg = str(e)
print "ERROR: %s: "%my.DO_QUERY_ERR, error_msg, str(query)
# don't include the error_msg in Exception to avoid decoding error
raise SqlException("%s: %s\n" % (my.DO_QUERY_ERR, query))
def get_value(my, query):
'''convenience function when you know there will be only one result'''
result = my.do_query(query)
if len(result) > 0:
value = result[0][0]
if value == None:
value = ""
else:
value = ""
return value
def get_int(my, query):
return int(my.get_value(query))
def do_update(my, query, quiet=False):
"""execute an update. If quiet = True, it doesn't print error causing sql"""
if query =="":
return
try:
if not my.conn:
my.connect()
# store the last query
#Environment.log().debug(query)
#print "[%s]" % my.database_name, query
my.query = query
my.cursor = my.conn.cursor()
#my.execute(query)
#print "update: ", query
my.cursor.execute(query)
# remember the row count
my.row_count = my.cursor.rowcount
if my.vendor == 'Sqlite':
my.last_row_id = my.cursor.lastrowid
elif my.vendor == 'MySQL':
my.last_row_id = my.conn.insert_id()
else:
my.last_row_id = 0
my.cursor.close()
# commit the transaction if there is no transaction
if my.transaction_count == 0:
my.transaction_count = 1
my.commit()
except my.pgdb.ProgrammingError, e:
if str(e).find("already exists") != -1:
return
print "Error with query (ProgrammingError): ", my.database_name, query
print str(e)
raise SqlException(str(e))
except my.pgdb.Error, e:
if not quiet:
print "Error with query (Error): ", my.database_name, query
raise SqlException(e.__str__())
def update_single(my, statement_obj):
'''insert/updates a single statement. This is a convenience function
which returns the id of the update row. It also checks that
only one row was actually affected'''
id = 0
is_insert = None
if isinstance(statement_obj, Insert):
is_insert = True
elif isinstance(statement_obj, Update):
is_insert = False
else:
raise SqlException("Cannot determine if this is an INSERT or and UPDATE [%s]" % statement_obj.statement)
# get the update id
if not is_insert:
id_statement = statement_obj.get_id_statement()
id = my.get_value(id_statement)
# do the update
statement = statement_obj.get_statement()
my.do_update(statement)
# check that one row and only one raw was affected
if my.row_count == 0:
raise SqlException("Statement [%s] did not affect any rows")
if my.row_count > 1:
raise SqlException("Statement [%s] affected any [%s] rows" % (statement, my.row_count) )
# get the insert id
if is_insert:
id_statement = statement_obj.get_id_statement()
id = my.get_value(id_statement)
if id > 0:
return id
raise SqlException("Improper id return with statement [%s]" % statement)
def close(my):
if my.conn == None:
return
#print "CONNECT: close: ", my
my.conn.close()
my.conn = None
def dump(my):
print(my.results)
# static functions
def quote(value, has_outside_quotes=True, escape=False):
'''prepares a value so that it can be entered as a value in the
database
@param:
has_outside_quotes - refer to having single_quotes
escape - if escape=True, set has_outsite_quotes=False'''
if value == None:
return "NULL"
# replace all single quotes with two single quotes
value_type = type(value)
if value_type in [types.ListType, types.TupleType]:
# [MIKE-FIX]
if len(value) == 0:
# Previously no check if list is empty, which is an issue for trying to get 'value[0]' as it's
# not defined. Assuming that if the list is empty, the intended value is NULL
return "NULL"
value = value[0]
value_type = type(value)
if value_type == types.IntType or value_type == types.LongType:
value = str(value)
elif value_type == types.BooleanType:
if value == True:
value = "1"
else:
value = "0"
elif value_type == types.ListType:
value = value[0]
value = value.replace("'", "''")
elif value_type == types.MethodType:
raise SqlException("Value passed in was an <instancemethod>")
elif value_type in [types.FloatType, types.IntType]:
pass
elif value_type in [types.StringTypes]:
value = value.replace("'", "''")
elif isinstance(value, datetime.datetime) or isinstance(value, datetime.date):
value = str(value)
else:
try:
value = value.replace("'", "''")
except Exception:
#raise SqlException("Error with quoting [%s]" % value)
print "WARNING: set_value(): ", value
print "type: ", type(value)
raise
if has_outside_quotes:
return "'%s'" % value
elif escape:
# this is more for postgres.. If other db impl needs it, it can be added to DatabaseImpl
return "E'%s'"% value
else:
return value
quote = staticmethod(quote)
# FIXME: this is highly PostgreSQL dependent
def copy_table_schema(my, from_table, to_table):
'''dump the table to a file. This is pretty messy, but I couldn't
find a better way to do this'''
tmp_dir = Environment.get_tmp_dir()
file_path = "%s/temp/%s__%s.sql" % (tmp_dir,my.database_name,from_table)
if os.path.exists(file_path):
os.unlink(file_path)
if os.path.exists(file_path+".tmp"):
os.unlink(file_path+".tmp")
# find the schema
if from_table.find(".") != -1:
from_schema, from_table = from_table.split(".")
else:
from_schema = "public"
if to_table.find(".") != -1:
to_schema, to_table = to_table.split(".")
else:
to_schema = "public"
# dump the table to a file
cmd ="pg_dump -h %s -U %s -p %s -s --schema %s -t %s %s > %s" % \
(my.host, my.user, my.port, from_schema, from_table, \
my.database_name, file_path)
os.system(cmd)
# convert the name of the from table to the to_table
file1 = open(file_path, "r")
file2 = open(file_path+".tmp", "w")
for line in file1.readlines():
line = line.replace("search_path = %s" % from_schema, \
"search_path = %s" % to_schema)
line = line.replace(from_table, to_table)
file2.write(line)
file1.close()
file2.close()
# read the file back in
os.system("psql -e -h %s -U %s -p %s %s < %s" % \
(my.host, my.user, my.port, my.database_name, file_path+".tmp") )
os.unlink(file_path)
os.unlink(file_path+".tmp")
# some database introspection tools: note that a different module
# is used here because it appears that pgdb (which is DB-API 2.0 compliant)
# does not support database introspection (not sure why not)
def get_tables(my):
db_resource = my.get_db_resource()
#key = "Sql:%s:tables"% db_resource
#tables = Container.get(key)
#if tables != None:
# return tables
table_info = my.database_impl.get_table_info(db_resource)
tables = table_info.keys()
#Container.put(key, tables)
return tables
def clear_table_cache(cls, database=None):
#if not database:
# database = Project.get().get_database_name()
#key = "Sql:%s:tables"% database
#Container.remove(key)
DatabaseImpl.clear_table_cache()
clear_table_cache = classmethod(clear_table_cache)
def table_exists(my, table):
db_resource = my.get_db_resource()
return my.impl.table_exists(db_resource, table)
class DbResource(Base):
'''Define a database resource. It contains the necessary
information required to connect to a particular database'''
DBRESOURCE_ID = 'DbResource'
def __init__(my, database, host=None, port=None, vendor=None, user=None, password=None, **options):
# MySQL does allow empty. This is needed to create a database
if vendor != "MySQL":
assert database
my.database = database
my.host = host
my.port = port
my.vendor = vendor
if not my.vendor:
my.vendor = Sql.get_default_database_type()
assert my.vendor in VENDORS
my.user = user
my.password = password
# database specific extra options
my.options = options
if not my.host:
my.host = Config.get_value("database", "server")
if not my.host:
my.host = 'localhost'
# Fill in the defaults
if my.vendor == 'MySQL':