-
Notifications
You must be signed in to change notification settings - Fork 17
/
DBInterface.py
6147 lines (5735 loc) · 291 KB
/
DBInterface.py
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) 2003 - 2015 The Board of Regents of the University of Wisconsin System
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of version 2 of the GNU General Public License as
# published by the Free Software Foundation.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
#
"""This module contains functions for encapsulating access to the database
for Transana."""
__author__ = 'David K. Woods <[email protected]>, Nathaniel Case, Rajas Sambhare'
DEBUG = False
if DEBUG:
print "DBInterface DEBUG is ON!"
# import Transana's Constants
import TransanaConstants
if TransanaConstants.DBInstalled in ['MySQLdb-embedded', 'MySQLdb-server']:
# import MySQLdb
import MySQLdb
# We also need the MySQL exceptions!
import _mysql_exceptions
elif TransanaConstants.DBInstalled in ['PyMySQL']:
# import PyMySQL
import pymysql as MySQLdb
elif TransanaConstants.DBInstalled in ['sqlite3']:
# import sqlite
import sqlite3
# import the python DateTime module
import datetime
else:
import TransanaExceptions
raise TransanaExceptions.ProgrammingError('No Database Module loaded in DBInterface.py.')
if DEBUG:
if TransanaConstants.DBInstalled in ['MySQLdb-embedded', 'MySQLdb-server']:
print "MySQLdb version =", MySQLdb.version_info, MySQLdb.__version__
elif TransanaConstants.DBInstalled in ['PyMySQL']:
print "PyMySQL version =", MySQLdb.version_info
elif TransanaConstants.DBInstalled in ['sqlite3']:
print "sqlite 3 version =", sqlite3.version
# import wxPython
import wx
# import Python's exceptions module
from exceptions import *
# import Python's array module
import array
# import Python's fast cPickle
import cPickle
# import Python's os module
import os
# import Python's sys module
import sys
# import Python's string module
import string
# import Transana's Clip object
import Clip
# import Transana's Collection Object
import Collection
# import Transana's Core Data Object
import CoreData
# import Transana's Dialog Boxes
import Dialogs
# import Transana's Episode Object
import Episode
# import Transana's Keyword Object
import KeywordObject
# import Transana's Note Object
import Note
# import Transana's Library Object
import Library
# import Transana's Snapshot Object
import Snapshot
# import Transana's Global Variables
import TransanaGlobal
# import Transana's Exceptions
import TransanaExceptions
# Import Transana's Transcript Object
import Transcript
# Declare Global Variables
# Database Reference
_dbref = None
def InitializeSingleUserDatabase():
""" For single-user Transana only, this initializes (starts) the embedded MySQL Server. """
# See if the "databases" path exists off the Transana Program folder
databasePath = TransanaGlobal.configData.databaseDir
# If the Database Path doesn't exist ...
if not os.path.exists(databasePath):
# If not, create it
os.makedirs(databasePath)
if TransanaConstants.DBInstalled in ['MySQLdb-embedded']:
# Start the embedded MySQL Server, using the "databases" folder off the Transana Program
# folder for the root Data folder.
datadir = "--datadir=" + databasePath
# Default to English
lang = '--language=./share/english'
# Change the language if it is supported
# Danish
if (TransanaGlobal.configData.language == 'da'):
lang = '--language=./share/danish'
# German
elif (TransanaGlobal.configData.language == 'de'):
lang = '--language=./share/german'
# Greek
elif (TransanaGlobal.configData.language == 'el'):
lang = '--language=./share/greek'
# Spanish
elif (TransanaGlobal.configData.language == 'es'):
lang = '--language=./share/spanish'
# French
elif (TransanaGlobal.configData.language == 'fr'):
lang = '--language=./share/french'
# Italian
elif (TransanaGlobal.configData.language == 'it'):
lang = '--language=./share/italian'
# Dutch
elif (TransanaGlobal.configData.language == 'nl'):
lang = '--language=./share/dutch'
# Norwegian Bokmal
elif (TransanaGlobal.configData.language == 'nb'):
lang = '--language=./share/norwegian'
# Norwegian Ny-norsk
elif (TransanaGlobal.configData.language == 'nn'):
lang = '--language=./share/norwegian-ny'
# Polish
elif (TransanaGlobal.configData.language == 'pl'):
lang = '--language=./share/polish'
# Portuguese
elif (TransanaGlobal.configData.language == 'pt'):
lang = '--language=./share/portuguese'
#
elif (TransanaGlobal.configData.language == 'ru'):
lang = '--language=./share/russian'
# Swedish
elif (TransanaGlobal.configData.language == 'sv'):
lang = '--language=./share/swedish'
# MySQLdb.server_init parameters MUST be strings, but paths with encoded characters aren't.
if isinstance(datadir, unicode):
# On Windows ...
if 'wxMSW' in wx.PlatformInfo:
# ... we seem to be able to fix this by using "CP1250" encoding
datadir = datadir.encode('cp1250')
# On non-Windows platforms, maybe we can use UTF8.
else:
datadir = datadir.encode('utf8')
MySQLdb.server_init(args=['Transana', datadir, '--basedir=.', lang])
def EndSingleUserDatabase():
""" For single-user Transana only, this ends (exits) the embedded MySQL Server. """
if TransanaConstants.DBInstalled in ['MySQLdb-embedded']:
# End the embedded MySQL Server
MySQLdb.server_end()
def SetTableType(hasInnoDB, query):
""" Set Table Type and Character Set Information for the database as appropriate """
# If we're using MySQL ...
if TransanaConstants.DBInstalled in ['MySQLdb-embedded', 'MySQLdb-server', 'PyMySQL']:
# NOTE: Default Table Type switched from BDB to InnoDB for version 2.10. BDB tables were having trouble importing
# a German Transana XML database someone sent to me, and switching databases was the only way I could find to
# fix the problem. Therefore, the BDB tables will probably never be used, as I think they're always present
# if the BDB tables are.
if TransanaGlobal.DBVersion >= u'5.0':
if hasInnoDB:
query = query + 'ENGINE=InnoDB'
else:
query = query + 'ENGINE=BDB'
else:
if hasInnoDB:
query = query + 'TYPE=InnoDB'
else:
query = query + 'TYPE=BDB'
if TransanaGlobal.DBVersion >= u'4.1':
# Add the Character Set specification
query += ' CHARACTER SET %s' % TransanaGlobal.encoding
return query
def is_db_open():
""" Quick and dirty test to see if the database is currently open """
return _dbref != None
def CreateLibraryTableQuery(num):
""" Create query for the Library Table """
# Different databases have slightly different syntaxes for handling auto-increment fields
# If we are using a MySQL database ...
if TransanaConstants.DBInstalled in ['MySQLdb-embedded', 'MySQLdb-server', 'PyMySQL']:
# ... use the MySQL syntax
autoIncrementSyntax = 'auto_increment'
# If we are using the sqlite database ...
elif TransanaConstants.DBInstalled in ['sqlite3']:
# ... use the sqlite syntax
autoIncrementSyntax = 'PRIMARY KEY AUTOINCREMENT'
# NOTE: If you change this, you need to change the INSERT queries in the Library object
# AND in the UpdateEncoding250() method below in this file!
# Library Table: Test for existence and create if needed
query = """
CREATE TABLE IF NOT EXISTS Series%d
(SeriesNum INTEGER %s,
SeriesID VARCHAR(100),
SeriesComment VARCHAR(255),
SeriesOwner VARCHAR(100),
DefaultKeywordGroup VARCHAR(50),
RecordLock VARCHAR(25),
LockTime DATETIME"""
# Add MySQL-specific SQL if appropriate
if TransanaConstants.DBInstalled in ['MySQLdb-embedded', 'MySQLdb-server', 'PyMySQL']:
query += """,
PRIMARY KEY (SeriesNum))
DEFAULT CHARACTER SET utf8
COLLATE utf8_bin
"""
# Add the appropriate Table Type to the CREATE Query
query = SetTableType(TransanaGlobal.hasInnoDB, query)
elif TransanaConstants.DBInstalled in ['sqlite3']:
query += ')'
# Return the query to the calling routine
return query % (num, autoIncrementSyntax)
def CreateEpisodesTableQuery(num):
""" Create query for the Episode Table """
# Different databases have slightly different syntaxes for handling auto-increment fields
# If we are using a MySQL database ...
if TransanaConstants.DBInstalled in ['MySQLdb-embedded', 'MySQLdb-server', 'PyMySQL']:
# ... use the MySQL syntax
autoIncrementSyntax = 'auto_increment'
# If we are using the sqlite database ...
elif TransanaConstants.DBInstalled in ['sqlite3']:
# ... use the sqlite syntax
autoIncrementSyntax = 'PRIMARY KEY AUTOINCREMENT'
# NOTE: If you change this, you need to change the INSERT queries in the EPISODE object
# AND in the UpdateEncoding250() method below in this file!
# Episode Table: Test for existence and create if needed
query = """
CREATE TABLE IF NOT EXISTS Episodes%d
(EpisodeNum INTEGER %s,
EpisodeID VARCHAR(100),
SeriesNum INTEGER,
TapingDate DATE,
MediaFile VARCHAR(255),
EpLength INTEGER,
EpComment VARCHAR(255),
RecordLock VARCHAR(25),
LockTime DATETIME"""
# Add MySQL-specific SQL if appropriate
if TransanaConstants.DBInstalled in ['MySQLdb-embedded', 'MySQLdb-server', 'PyMySQL']:
query += """,
PRIMARY KEY (EpisodeNum))
DEFAULT CHARACTER SET utf8
COLLATE utf8_bin
"""
# Add the appropriate Table Type to the CREATE Query
query = SetTableType(TransanaGlobal.hasInnoDB, query)
elif TransanaConstants.DBInstalled in ['sqlite3']:
query += ')'
# Return the query to the calling routine
return query % (num, autoIncrementSyntax)
def CreateTranscriptsTableQuery(num):
""" Create query for the Transcripts Table """
# Different databases have slightly different syntaxes for handling auto-increment fields
# If we are using a MySQL database ...
if TransanaConstants.DBInstalled in ['MySQLdb-embedded', 'MySQLdb-server', 'PyMySQL']:
# ... use the MySQL syntax
autoIncrementSyntax = 'auto_increment'
# If we are using the sqlite database ...
elif TransanaConstants.DBInstalled in ['sqlite3']:
# ... use the sqlite syntax
autoIncrementSyntax = 'PRIMARY KEY AUTOINCREMENT'
# NOTE: If you change this, you need to change the INSERT queries in the TRANSCRIPT object
# AND in the UpdateEncoding250() method below in this file!
# Transcripts Table: Test for existence and create if needed
query = """
CREATE TABLE IF NOT EXISTS Transcripts%d
(TranscriptNum INTEGER %s,
TranscriptID VARCHAR(100),
EpisodeNum INTEGER,
SourceTranscriptNum INTEGER,
ClipNum INTEGER,
SortOrder INTEGER,
Transcriber VARCHAR(100),
ClipStart INTEGER,
ClipStop INTEGER,
Comment VARCHAR(255),
MinTranscriptWidth INTEGER,
RTFText LONGBLOB,
RecordLock VARCHAR(25),
LockTime DATETIME,
LastSaveTime DATETIME"""
# Add MySQL-specific SQL if appropriate
if TransanaConstants.DBInstalled in ['MySQLdb-embedded', 'MySQLdb-server', 'PyMySQL']:
query += """,
PRIMARY KEY (TranscriptNum))
DEFAULT CHARACTER SET utf8
COLLATE utf8_bin
"""
# Add the appropriate Table Type to the CREATE Query
query = SetTableType(TransanaGlobal.hasInnoDB, query)
elif TransanaConstants.DBInstalled in ['sqlite3']:
query += ')'
# Return the query to the calling routine
return query % (num, autoIncrementSyntax)
def CreateCollectionsTableQuery(num):
""" Create query for the Collections Table """
# Different databases have slightly different syntaxes for handling auto-increment fields
# If we are using a MySQL database ...
if TransanaConstants.DBInstalled in ['MySQLdb-embedded', 'MySQLdb-server', 'PyMySQL']:
# ... use the MySQL syntax
autoIncrementSyntax = 'auto_increment'
# If we are using the sqlite database ...
elif TransanaConstants.DBInstalled in ['sqlite3']:
# ... use the sqlite syntax
autoIncrementSyntax = 'PRIMARY KEY AUTOINCREMENT'
# NOTE: If you change this, you need to change the INSERT queries in the COLLECTIONS object
# AND in the UpdateEncoding250() method below in this file!
# Collections Table: Test for existence and create if needed
query = """
CREATE TABLE IF NOT EXISTS Collections%d
(CollectNum INTEGER %s,
CollectID VARCHAR(100),
ParentCollectNum INTEGER,
CollectComment VARCHAR(255),
CollectOwner VARCHAR(100),
DefaultKeywordGroup VARCHAR(50),
RecordLock VARCHAR(25),
LockTime DATETIME"""
# Add MySQL-specific SQL if appropriate
if TransanaConstants.DBInstalled in ['MySQLdb-embedded', 'MySQLdb-server', 'PyMySQL']:
query += """,
PRIMARY KEY (CollectNum))
DEFAULT CHARACTER SET utf8
COLLATE utf8_bin
"""
# Add the appropriate Table Type to the CREATE Query
query = SetTableType(TransanaGlobal.hasInnoDB, query)
elif TransanaConstants.DBInstalled in ['sqlite3']:
query += ')'
# Return the query to the calling routine
return query % (num, autoIncrementSyntax)
def CreateClipsTableQuery(num):
""" Create query for the Clips Table """
# Different databases have slightly different syntaxes for handling auto-increment fields
# If we are using a MySQL database ...
if TransanaConstants.DBInstalled in ['MySQLdb-embedded', 'MySQLdb-server', 'PyMySQL']:
# ... use the MySQL syntax
autoIncrementSyntax = 'auto_increment'
# If we are using the sqlite database ...
elif TransanaConstants.DBInstalled in ['sqlite3']:
# ... use the sqlite syntax
autoIncrementSyntax = 'PRIMARY KEY AUTOINCREMENT'
# NOTE: If you change this, you need to change the INSERT queries in the CLIPS object
# AND in the UpdateEncoding250() method below in this file!
# Clips Table: Test for existence and create if needed
query = """
CREATE TABLE IF NOT EXISTS Clips%d
(ClipNum INTEGER %s,
ClipID VARCHAR(100),
CollectNum INTEGER,
EpisodeNum INTEGER,
MediaFile VARCHAR(255),
ClipStart INTEGER,
ClipStop INTEGER,
ClipOffset INTEGER,
Audio INTEGER,
ClipComment VARCHAR(255),
SortOrder INTEGER,
RecordLock VARCHAR(25),
LockTime DATETIME"""
# Add MySQL-specific SQL if appropriate
if TransanaConstants.DBInstalled in ['MySQLdb-embedded', 'MySQLdb-server', 'PyMySQL']:
query += """,
PRIMARY KEY (ClipNum))
DEFAULT CHARACTER SET utf8
COLLATE utf8_bin
"""
# Add the appropriate Table Type to the CREATE Query
query = SetTableType(TransanaGlobal.hasInnoDB, query)
elif TransanaConstants.DBInstalled in ['sqlite3']:
query += ')'
# Return the query to the calling routine
return query % (num, autoIncrementSyntax)
def CreateSnapshotsTableQuery(num):
""" Create query for the Snapshots Table """
# Different databases have slightly different syntaxes for handling auto-increment fields
# If we are using a MySQL database ...
if TransanaConstants.DBInstalled in ['MySQLdb-embedded', 'MySQLdb-server', 'PyMySQL']:
# ... use the MySQL syntax
autoIncrementSyntax = 'auto_increment'
# If we are using the sqlite database ...
elif TransanaConstants.DBInstalled in ['sqlite3']:
# ... use the sqlite syntax
autoIncrementSyntax = 'PRIMARY KEY AUTOINCREMENT'
# NOTE: If you change this, you need to change the INSERT queries in the SNAPSHOTS object
# Snapshots Table: Test for existence and create if needed
query = """
CREATE TABLE IF NOT EXISTS Snapshots%d
(SnapshotNum INTEGER %s,
SnapshotID VARCHAR(100),
CollectNum INTEGER,
ImageFile VARCHAR(255),
ImageScale DOUBLE,
ImageCoordsX DOUBLE,
ImageCoordsY DOUBLE,
ImageSizeW INTEGER,
ImageSizeH INTEGER,
EpisodeNum INTEGER,
TranscriptNum INTEGER,
SnapshotTimeCode INTEGER,
SnapshotDuration INTEGER,
SnapshotComment VARCHAR(255),
SortOrder INTEGER,
LastSaveTime DATETIME,
RecordLock VARCHAR(25),
LockTime DATETIME"""
# Add MySQL-specific SQL if appropriate
if TransanaConstants.DBInstalled in ['MySQLdb-embedded', 'MySQLdb-server', 'PyMySQL']:
query += """,
PRIMARY KEY (SnapshotNum))
DEFAULT CHARACTER SET utf8
COLLATE utf8_bin
"""
# Add the appropriate Table Type to the CREATE Query
query = SetTableType(TransanaGlobal.hasInnoDB, query)
elif TransanaConstants.DBInstalled in ['sqlite3']:
query += ')'
# Return the query to the calling routine
return query % (num, autoIncrementSyntax)
def CreateDocumentsTableQuery(num):
""" Create query for the Documents Table """
# Different databases have slightly different syntaxes for handling auto-increment fields
# If we are using a MySQL database ...
if TransanaConstants.DBInstalled in ['MySQLdb-embedded', 'MySQLdb-server', 'PyMySQL']:
# ... use the MySQL syntax
autoIncrementSyntax = 'auto_increment'
# If we are using the sqlite database ...
elif TransanaConstants.DBInstalled in ['sqlite3']:
# ... use the sqlite syntax
autoIncrementSyntax = 'PRIMARY KEY AUTOINCREMENT'
# NOTE: If you change this, you need to change the INSERT queries in the DOCUMENT objects
# Documents Table: Test for existence and create if needed
query = """
CREATE TABLE IF NOT EXISTS Documents%d
(DocumentNum INTEGER %s,
DocumentID VARCHAR(100),
LibraryNum INTEGER,
Author VARCHAR(100),
Comment VARCHAR(255),
ImportedFile VARCHAR(255),
ImportDate DATETIME,
DocumentLength INTEGER,
XMLText LONGBLOB,
RecordLock VARCHAR(25),
LockTime DATETIME,
LastSaveTime DATETIME"""
# Add MySQL-specific SQL if appropriate
if TransanaConstants.DBInstalled in ['MySQLdb-embedded', 'MySQLdb-server', 'PyMySQL']:
query += """,
PRIMARY KEY (DocumentNum))
DEFAULT CHARACTER SET utf8
COLLATE utf8_bin
"""
# Add the appropriate Table Type to the CREATE Query
query = SetTableType(TransanaGlobal.hasInnoDB, query)
elif TransanaConstants.DBInstalled in ['sqlite3']:
query += ')'
# Return the query to the calling routine
return query % (num, autoIncrementSyntax)
def CreateQuotesTableQuery(num):
""" Create query for the Quotes Table """
# Different databases have slightly different syntaxes for handling auto-increment fields
# If we are using a MySQL database ...
if TransanaConstants.DBInstalled in ['MySQLdb-embedded', 'MySQLdb-server', 'PyMySQL']:
# ... use the MySQL syntax
autoIncrementSyntax = 'auto_increment'
# If we are using the sqlite database ...
elif TransanaConstants.DBInstalled in ['sqlite3']:
# ... use the sqlite syntax
autoIncrementSyntax = 'PRIMARY KEY AUTOINCREMENT'
# NOTE: If you change this, you need to change the INSERT queries in the QUOTE objects
# Documents Table: Test for existence and create if needed
query = """
CREATE TABLE IF NOT EXISTS Quotes%d
(QuoteNum INTEGER %s,
QuoteID VARCHAR(100),
CollectNum INTEGER,
SourceDocumentNum INTEGER,
SortOrder INTEGER,
Comment VARCHAR(255),
XMLText LONGBLOB,
RecordLock VARCHAR(25),
LockTime DATETIME,
LastSaveTime DATETIME"""
# Add MySQL-specific SQL if appropriate
if TransanaConstants.DBInstalled in ['MySQLdb-embedded', 'MySQLdb-server', 'PyMySQL']:
query += """,
PRIMARY KEY (QuoteNum))
DEFAULT CHARACTER SET utf8
COLLATE utf8_bin
"""
# Add the appropriate Table Type to the CREATE Query
query = SetTableType(TransanaGlobal.hasInnoDB, query)
elif TransanaConstants.DBInstalled in ['sqlite3']:
query += ')'
# Return the query to the calling routine
return query % (num, autoIncrementSyntax)
def CreateQuotePositionsTableQuery(num):
""" Create query for the Quote Positions Table """
# Different databases have slightly different syntaxes for handling auto-increment fields
# If we are using a MySQL database ...
if TransanaConstants.DBInstalled in ['MySQLdb-embedded', 'MySQLdb-server', 'PyMySQL']:
# ... use the MySQL syntax
autoIncrementSyntax = 'auto_increment'
# If we are using the sqlite database ...
elif TransanaConstants.DBInstalled in ['sqlite3']:
# ... use the sqlite syntax
autoIncrementSyntax = 'PRIMARY KEY AUTOINCREMENT'
# NOTE: If you change this, you need to change the INSERT queries in the DOCUMENT and QUOTE objects
# Documents Table: Test for existence and create if needed
query = """
CREATE TABLE IF NOT EXISTS QuotePositions%d
(QuoteNum INTEGER %s,
DocumentNum INTEGER,
StartChar INTEGER,
EndChar INTEGER"""
# Add MySQL-specific SQL if appropriate
if TransanaConstants.DBInstalled in ['MySQLdb-embedded', 'MySQLdb-server', 'PyMySQL']:
query += """,
PRIMARY KEY (QuoteNum))
DEFAULT CHARACTER SET utf8
COLLATE utf8_bin
"""
# Add the appropriate Table Type to the CREATE Query
query = SetTableType(TransanaGlobal.hasInnoDB, query)
elif TransanaConstants.DBInstalled in ['sqlite3']:
query += ')'
# Return the query to the calling routine
return query % (num, autoIncrementSyntax)
def CreateNotesTableQuery(num):
""" Create query for the Notes Table """
# Different databases have slightly different syntaxes for handling auto-increment fields
# If we are using a MySQL database ...
if TransanaConstants.DBInstalled in ['MySQLdb-embedded', 'MySQLdb-server', 'PyMySQL']:
# ... use the MySQL syntax
autoIncrementSyntax = 'auto_increment'
# If we are using the sqlite database ...
elif TransanaConstants.DBInstalled in ['sqlite3']:
# ... use the sqlite syntax
autoIncrementSyntax = 'PRIMARY KEY AUTOINCREMENT'
# NOTE: If you change this, you need to change the INSERT queries in the NOTES object
# AND in the UpdateEncoding250() method below in this file!
# Notes Table: Test for existence and create if needed
query = """
CREATE TABLE IF NOT EXISTS Notes%d
(NoteNum INTEGER %s,
NoteID VARCHAR(100),
SeriesNum INTEGER,
EpisodeNum INTEGER,
CollectNum INTEGER,
ClipNum INTEGER,
SnapshotNum INTEGER,
TranscriptNum INTEGER,
DocumentNum INTEGER,
QuoteNum INTEGER,
NoteTaker VARCHAR(100),
NoteText LONGBLOB,
RecordLock VARCHAR(25),
LockTime DATETIME"""
# Add MySQL-specific SQL if appropriate
if TransanaConstants.DBInstalled in ['MySQLdb-embedded', 'MySQLdb-server', 'PyMySQL']:
query += """,
PRIMARY KEY (NoteNum))
DEFAULT CHARACTER SET utf8
COLLATE utf8_bin
"""
# Add the appropriate Table Type to the CREATE Query
query = SetTableType(TransanaGlobal.hasInnoDB, query)
elif TransanaConstants.DBInstalled in ['sqlite3']:
query += ')'
# Return the query to the calling routine
return query % (num, autoIncrementSyntax)
def CreateKeywordsTableQuery(num):
""" Create query for the Keywords Table """
# NOTE: If you change this, you need to change the INSERT queries in the KEYWORD object
# AND in the UpdateEncoding250() method below in this file!
# Keywords Table: Test for existence and create if needed
query = """
CREATE TABLE IF NOT EXISTS Keywords%d
(KeywordGroup VARCHAR(50) NOT NULL,
Keyword VARCHAR(85) NOT NULL,
Definition LONGBLOB,
LineColorName VARCHAR(50),
LineColorDef VARCHAR(10),
DrawMode VARCHAR(20),
LineWidth INTEGER,
LineStyle VARCHAR(20),
RecordLock VARCHAR(25),
LockTime DATETIME,
PRIMARY KEY (KeywordGroup, Keyword))
"""
# Add MySQL-specific SQL if appropriate
if TransanaConstants.DBInstalled in ['MySQLdb-embedded', 'MySQLdb-server', 'PyMySQL']:
query += """
DEFAULT CHARACTER SET utf8
COLLATE utf8_bin
"""
# Add the appropriate Table Type to the CREATE Query
query = SetTableType(TransanaGlobal.hasInnoDB, query)
# Return the query to the calling routine
return query % num
def CreateClipKeywordsTableQuery(num):
""" Create query for the Clip Keywords Table """
# NOTE: If you change this, you need to change the INSERT queries in the EPISODE and CLIP object
# AND in the UpdateEncoding250() method below in this file!
# If we're using MySQL ...
if TransanaConstants.DBInstalled in ['MySQLdb-embedded', 'MySQLdb-server', 'PyMySQL']:
# Clip Keywords Table: Test for existence and create if needed
# MySQL Primary Keys cannot contain NULL values, and either EpisodeNum
# or ClipNum will always be NULL! Therefore, use a UNIQUE KEY rather
# than a PRIMARY KEY for this table.
query = """
CREATE TABLE IF NOT EXISTS ClipKeywords%d
(EpisodeNum INTEGER,
DocumentNum INTEGER,
ClipNum INTEGER,
QuoteNum INTEGER,
SnapshotNum INTEGER,
KeywordGroup VARCHAR(50),
Keyword VARCHAR(85),
Example CHAR(1),
UNIQUE KEY EpisodeNum (EpisodeNum, DocumentNum, ClipNum, QuoteNum, SnapshotNum, KeywordGroup, Keyword))
DEFAULT CHARACTER SET utf8
COLLATE utf8_bin
"""
# If we're using sqlite, we need a Primary Key
else:
# Clip Keywords Table: Test for existence and create if needed
# The MySQL Unique Key syntax is not supported. Therefore, we'll give this table it's own unique key.
query = """
CREATE TABLE IF NOT EXISTS ClipKeywords%d
(number INTEGER PRIMARY KEY AUTOINCREMENT,
EpisodeNum INTEGER,
DocumentNum INTEGER,
ClipNum INTEGER,
QuoteNum INTEGER,
SnapshotNum INTEGER,
KeywordGroup VARCHAR(50),
Keyword VARCHAR(85),
Example CHAR(1))
"""
# Add the appropriate Table Type to the CREATE Query
query = SetTableType(TransanaGlobal.hasInnoDB, query)
# Return the query to the calling routine
return query % num
def CreateSnapshotKeywordsTableQuery(num):
""" Create query for the Snapshot Keywords Table """
# NOTE: If you change this, you need to change the INSERT queries in the SNAPSHOT object
# Snapshot Keywords Table: Test for existence and create if needed
# Because there will be multiple uses of the same keyword on the same snapshot, no Unique Key is defined.
query = """
CREATE TABLE IF NOT EXISTS SnapshotKeywords%d
(SnapshotNum INTEGER,
KeywordGroup VARCHAR(50),
Keyword VARCHAR(85),
x1 INTEGER,
y1 INTEGER,
x2 INTEGER,
y2 INTEGER,
visible CHAR(1))
"""
# Add MySQL-specific SQL if appropriate
if TransanaConstants.DBInstalled in ['MySQLdb-embedded', 'MySQLdb-server', 'PyMySQL']:
query += """
DEFAULT CHARACTER SET utf8
COLLATE utf8_bin
"""
# Add the appropriate Table Type to the CREATE Query
query = SetTableType(TransanaGlobal.hasInnoDB, query)
# Return the query to the calling routine
return query % num
def CreateSnapshotKeywordStylesTableQuery(num):
""" Create query for the Snapshot Keyword Styles Table """
# NOTE: If you change this, you need to change the INSERT queries in the SNAPSHOT object
# Snapshot Keyword Styles Table: Test for existence and create if needed
query = """
CREATE TABLE IF NOT EXISTS SnapshotKeywordStyles%d
(SnapshotNum INTEGER,
KeywordGroup VARCHAR(50),
Keyword VARCHAR(85),
DrawMode VARCHAR(20),
LineColorName VARCHAR(50),
LineColorDef VARCHAR(10),
LineWidth INTEGER,
LineStyle VARCHAR(20),
PRIMARY KEY (SnapshotNum, KeywordGroup, Keyword))
"""
# Add MySQL-specific SQL if appropriate
if TransanaConstants.DBInstalled in ['MySQLdb-embedded', 'MySQLdb-server', 'PyMySQL']:
query += """
DEFAULT CHARACTER SET utf8
COLLATE utf8_bin
"""
# Add the appropriate Table Type to the CREATE Query
query = SetTableType(TransanaGlobal.hasInnoDB, query)
# Return the query to the calling routine
return query % num
def CreateCoreDataTableQuery(num):
""" Create query for the Core Data table """
# Different databases have slightly different syntaxes for handling auto-increment fields
# If we are using a MySQL database ...
if TransanaConstants.DBInstalled in ['MySQLdb-embedded', 'MySQLdb-server', 'PyMySQL']:
# ... use the MySQL syntax
autoIncrementSyntax = 'auto_increment'
# If we are using the sqlite database ...
elif TransanaConstants.DBInstalled in ['sqlite3']:
# ... use the sqlite syntax
autoIncrementSyntax = 'PRIMARY KEY AUTOINCREMENT'
# NOTE: If you change this, you need to change the INSERT queries in the CORE DATA object
# AND in the UpdateEncoding250() method below in this file!
# Core Data Table: Test for existence and create if needed
query = """
CREATE TABLE IF NOT EXISTS CoreData%d
(CoreDataNum INTEGER %s,
Identifier VARCHAR(255),
Title VARCHAR(255),
Creator VARCHAR(255),
Subject VARCHAR(255),
Description VARCHAR(255),
Publisher VARCHAR(255),
Contributor VARCHAR(255),
DCDate DATE,
DCType VARCHAR(50),
Format VARCHAR(100),
Source VARCHAR(255),
Language VARCHAR(25),
Relation VARCHAR(255),
Coverage VARCHAR(255),
Rights VARCHAR(255),
RecordLock VARCHAR(25),
LockTime DATETIME"""
# Add MySQL-specific SQL if appropriate
if TransanaConstants.DBInstalled in ['MySQLdb-embedded', 'MySQLdb-server', 'PyMySQL']:
query += """,
PRIMARY KEY (CoreDataNum))
DEFAULT CHARACTER SET utf8
COLLATE utf8_bin
"""
# Add the appropriate Table Type to the CREATE Query
query = SetTableType(TransanaGlobal.hasInnoDB, query)
elif TransanaConstants.DBInstalled in ['sqlite3']:
query += ')'
# Return the query to the calling routine
return query % (num, autoIncrementSyntax)
def CreateFiltersTableQuery(num):
""" Create query for the Filters table """
# NOTE: If you change this, you need to change the INSERT queries in the Filter Dialog form file
# AND in the UpdateEncoding250() method below in this file!
# Filters Table: Test for existence and create if needed
query = """
CREATE TABLE IF NOT EXISTS Filters%d
(ReportType INTEGER,
ReportScope INTEGER,
ConfigName VARCHAR(100),
FilterDataType INTEGER,
FilterData LONGBLOB,
PRIMARY KEY (ReportType, ReportScope, ConfigName, FilterDataType))
"""
# Add MySQL-specific SQL if appropriate
if TransanaConstants.DBInstalled in ['MySQLdb-embedded', 'MySQLdb-server', 'PyMySQL']:
query += """
DEFAULT CHARACTER SET utf8
COLLATE utf8_bin
"""
# Add the appropriate Table Type to the CREATE Query
query = SetTableType(TransanaGlobal.hasInnoDB, query)
# Return the query to the calling routine
return query % num
def CreateAdditionalVidsTableQuery(num):
""" Create query for the Additional Videos table """
# Different databases have slightly different syntaxes for handling auto-increment fields
# If we are using a MySQL database ...
if TransanaConstants.DBInstalled in ['MySQLdb-embedded', 'MySQLdb-server', 'PyMySQL']:
# ... use the MySQL syntax
autoIncrementSyntax = 'auto_increment'
# If we are using the sqlite database ...
elif TransanaConstants.DBInstalled in ['sqlite3']:
# ... use the sqlite syntax
autoIncrementSyntax = 'PRIMARY KEY AUTOINCREMENT'
# NOTE: If you change this, you need to change the INSERT queries in the EPISODE and Clip objects
# AND in the UpdateEncoding250() method below in this file!
# Additional Videos Table: Test for existence and create if needed
query = """
CREATE TABLE IF NOT EXISTS AdditionalVids%d
(AddVidNum INTEGER %s,
EpisodeNum INTEGER,
ClipNum INTEGER,
MediaFile VARCHAR(255),
VidLength INTEGER,
Offset INTEGER,
Audio INTEGER"""
# Add MySQL-specific SQL if appropriate
if TransanaConstants.DBInstalled in ['MySQLdb-embedded', 'MySQLdb-server', 'PyMySQL']:
query += """,
PRIMARY KEY (AddVidNum))
DEFAULT CHARACTER SET utf8
COLLATE utf8_bin
"""
# Add the appropriate Table Type to the CREATE Query
query = SetTableType(TransanaGlobal.hasInnoDB, query)
elif TransanaConstants.DBInstalled in ['sqlite3']:
query += ')'
# Return the query to the calling routine
return query % (num, autoIncrementSyntax)
def establish_db_exists(dbToOpen=None, usePrompt=True):
""" Check for the existence of all database tables and create them
if necessary. dbToOpen is passed if we are automatically importing a database
following 2.42 to 2.50 Data Conversion. """
# NOTE: Syntax for updating tables from MySQL 4.0 to MySQL 4.1 with Unicode UTF8 Characters Set:
# ALTER TABLE xxxx2 default character set utf8
# Obtain a Database
db = get_db(dbToOpen, usePrompt=usePrompt)
# If this fails, return "False" to indicate failure
if db == None:
return False
# Obtain a Database Cursor
dbCursor = db.cursor()
# If we're using MySQL ...
if TransanaConstants.DBInstalled in ['MySQLdb-embedded', 'MySQLdb-server', 'PyMySQL']:
# MySQL for Python 1.2.0 and later defaults to turning off AUTOCOMMIT. We want AutoCommit to be ON.
# query = "SET AUTOCOMMIT = 1"
# Execute the Query
# dbCursor.execute(query)
db.autocommit(1)
# MySQLdb 1.2.2 displays Warnings if the tables already exist as they are created. We don't want this!
if not MySQLdb.version_info in [(1, 2, 0, 'final', 1)]:
dbCursor._defer_warnings = True
# Initialize BDB and InnoDB Table Flags to false
hasBDB = False
hasInnoDB = False
# First, let's find out if the InnoDB and BDB Tables are supported on the MySQL Instance we are using.
# Define a "SHOW VARIABLES" Query
query = "SHOW VARIABLES LIKE 'have%'"
# Execute the Query
dbCursor.execute(query)
# Look at the Results Set
for pair in dbCursor.fetchall():
# If there is a pair in the Results that indicates that the value for "have_bdb" is "YES",
# set the DBD Flag to True
if pair[0] == 'have_bdb':
if type(pair[1]).__name__ == 'array':
p1 = pair[1].tostring()
else:
p1 = pair[1]
if p1 == 'YES':
hasBDB = True
# If there is a pair in the Results that indicates that the value for "have_innodb" is "YES",
# set the InnoDB Flag to True
if pair[0] == 'have_innodb':
if type(pair[1]).__name__ == 'array':
p1 = pair[1].tostring()
else:
p1 = pair[1]
if p1 == 'YES':
hasInnoDB = True
# Then let's check the MySQL version. MySQL dropped have_bdb a long time ago, and have_innodb with 5.6.x
# Define a "SHOW VARIABLES" Query
query = "SHOW VARIABLES LIKE 'version'"
# Execute the Query
dbCursor.execute(query)
# Look at the Results Set
version = dbCursor.fetchone()[1]
# Break the MySQL version into major, minor, and sub-minor sections based on decimal points in the version number
version = version.split('.')
# If we have MySQL version 5.6 or higher ...
if (int(version[0]) >= 5) and (int(version[1]) >= 6):
# ... then InnoDB IS built in, even though there's no longer a variable for it!
hasInnoDB = True
# If we're using sqlite ...
else:
# ... this has no meaning, so we cannot fail the test!
hasBDB = True
hasInnoDB = True
# If neither BDB nor InnoDB are supported, display an error message.
if not (hasBDB or hasInnoDB):
dlg = Dialogs.ErrorDialog(None, _("This MySQL Server is not configured to use BDB or InnoDB Tables. Transana requires a MySQL-max Server."))
dlg.ShowModal()
dlg.Destroy
# If either DBD or InnoDB is supported ...
else:
# If we're using MySQL ...
if TransanaConstants.DBInstalled in ['MySQLdb-embedded', 'MySQLdb-server', 'PyMySQL']:
# See if any database tables exist
query = "SHOW TABLES"
# Execute the Query
dbCursor.execute(query)
# If no tables exists ...
if dbCursor.rowcount == 0:
# ... initialize database version to 0
DBVersion = 0
# if tables DO exists ...
else:
# ... set the Database Version Number to reflect the version that didn't yet have this feature
DBVersion = 242
# If we're using sqlite ...
else:
# ... initialize database version to 0
DBVersion = 0
TransanaGlobal.hasInnoDB = hasInnoDB
# Create the Configuration Information table if it doesn't exist
query = """
CREATE TABLE IF NOT EXISTS ConfigInfo
(KeyVal VARCHAR(25),