This repository has been archived by the owner on Dec 11, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathpileschema.py
1409 lines (1217 loc) · 48.9 KB
/
pileschema.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
#!/usr/bin/env python
'''
Script implementing all top level commands.
Basic usage:
.. code-block:: none
pileschema.py command
'''
import argparse
from collections import OrderedDict
import datetime
import logging
from lxml import etree
import os
import platform
import pile_schema_api
if platform.system() == 'Windows':
import win32api
def username():
'''Retrieves the name oif the current user'''
result = win32api.GetUserNameEx(2).split('\\')[-1]
return result
else:
import pwd
def username():
'''Retrieves the name of the current user'''
return pwd.getpwuid(os.getuid())[0]
PARSER = None
SCHEMA_FILE = None
AUTHOR = None
META_TABLE_BASE = 'DbTable' # The base class for Meta Tables
RECORD_BASE = 'DbRecord' # The base class for Tables
META_TABLE_BASE_FILE = '#include <dbstruct/dbtable.h>' # include files for Meta Table file
DEFAULT_SCHEMA_FILE = './PileSchema.xsd'
NSPACESTR = None
LOGGER = logging.getLogger('PileSchema')
FROM_VARIANT = {
'QString': 'toString ()',
'bool': 'toBool ()',
'long': 'toLongLong (&b_one); b_ret = b_ret & b_one',
'char': 'toInt (&b_one); b_ret = b_ret & b_one',
'short': 'toInt (&b_one); b_ret = b_ret & b_one',
'int': 'toInt (&b_one); b_ret = b_ret & b_one',
'double': 'toDouble (&b_one); b_ret = b_ret & b_one',
'float': 'toDouble (&b_one); b_ret = b_ret & b_one',
'QDateTime': 'toDateTime ()',
'QDate': 'toDate ()',
'QTime': 'toTime ()',
'QByteArray': 'toByteArray ()',
'void *': 'value<void *>()'
}
TO_CAST = {
'QString': '',
'bool': '',
'long': '(long)',
'char': '(char)',
'short': '(short)',
'int': '',
'double': '',
'float': '(float)',
'QDateTime': '',
'QDate': '',
'QTime': '',
'QByteArray': '',
'void *': ''
}
SQL_DATATYPES = {
# Exact numerics
'bit': 'BOOLEAN',
'tristate': 'tinyint',
'int': 'INTEGER',
'integer': 'INTEGER',
'bigint': 'BIGINT',
'smallint': 'SMALLINT',
'tinyint': 'tinyint',
'choice': 'INTEGER',
'numeric': 'DECIMAL',
'decimal': 'DECIMAL',
'numericScale0': 'DECIMAL',
'decimalScale0': 'DECIMAL',
'smallmoney': 'DECIMAL',
'money': 'DECIMAL',
# Approximate numerics
'float': 'FLOAT',
'real': 'FLOAT',
# Date and time
'date': 'DATE',
'datetime': 'DATETIME',
'time': 'TIME',
'datetimeoffset': 'TIME',
'datetime2': 'TIME',
'smalldatetime': 'VARCHAR',
# Character strings
'char': 'VARCHAR',
'varchar': 'VARCHAR',
'text': 'TEXT',
# Unicode character strings
'nchar': 'VARCHAR',
'nvarchar': 'VARCHAR',
'ntext': 'TEXT',
# Binary strings
'binary': 'BLOB',
'varbinary': 'BLOB',
'image': 'BLOB',
# Other data types
'rowversion': 'INTEGER',
'hierarchyid': 'INTEGER',
'sql_variant': 'VARCHAR',
'xml': 'VARCHAR',
'uniqueidentifier': 'INTEGER',
'': '',
'vrtcol': ''
}
# ----------------------------------------------------------------------------
class Driver(object):
'''
Default implementation with regard to the underlying
Sql variant.
'''
def __init__(self):
self.views = {}
self.tables = {}
super(Driver, self).__init__()
def database_start(self, name, node):
'''Starting to process database `name`'''
pass
def database_end(self, name, node):
'''Done processing database `name`'''
pass
def table_start(self, name, node):
'''Starting to process table `name`'''
pass
def table_end(self, name, node):
'''Done processing table `name`'''
pass
def column(self, name, label, datatype, nulls, node, dtnode):
'''Processing a column'''
pass
def view_start(self, name, node):
'''Starting to process view `name`'''
pass
def view_end(self, name, node):
'''Done processing view `name`'''
pass
def view_subset(self, node, subset):
'''Process a subset in a view'''
pass
@staticmethod
def get_foreign_key(node):
'''
Extracts foreign key data from an xml node
The result is None if no foreign key exists of a list of three elements:
the table, the key column and the columns that should replace
original key in a presentation to the user.
'''
# Is this column a foreign key into another table?
ftable = node.foreignTable
fcolumn = node.foreignColumn
finsert = node.foreignInsert
fbehavior = node.foreignBehavior
if ftable is not None:
return [ftable, fcolumn, finsert, fbehavior]
else:
return None
def check_foreign_keys(self):
'''Make sure that all columns referenced in foreign keys actually exist.'''
for tbl in self.tables:
tbldata = self.tables[tbl]
for col in tbldata['columns']:
coldata = tbldata['columns'][col]['fkey']
if coldata:
# the column is a foreign key
ftable, fcolumn, finsert, fbehavior = coldata
try:
f_actual = self.tables[ftable]
except KeyError:
try:
f_actual = self.views[ftable]
except KeyError:
LOGGER.warning(
'Column %s of table %s references table '
'%s that does not exist', col, tbl, ftable)
raise
try:
f_actual['columns'][fcolumn]
except KeyError:
LOGGER.warning(
'Column %s of table %s references column '
'%s in table %s that does not exist',
col, tbl, fcolumn, ftable)
raise
if finsert:
try:
f_actual['columns'][finsert]
except KeyError:
LOGGER.warning(
'Column %s of table %s uses column '
'%s in table %s that does not exist',
col, tbl, finsert, ftable)
raise
# ----------------------------------------------------------------------------
class SqlDriver(Driver):
'''
Default implementation with regard to the underlying
Sql variant.
'''
def __init__(self):
self.sql_string = ''
self.foreign_keys = {}
super(SqlDriver, self).__init__()
def table_start(self, name, node):
'''Starting to process table `name`'''
self.sql_string += 'CREATE TABLE IF NOT EXISTS `' + name + '` (\n'
self.foreign_keys = {}
def database_end(self, name, node):
'''Done processing database `name.`'''
#print node.sqlPrefix
#print node.sqlSuffix
self.sql_string = node.sqlPrefix + self.sql_string + node.sqlSuffix
def table_end(self, name, node):
'''Done processing table `name`'''
try:
pkey = node.primaryKey.key.column[0]
except AttributeError:
pkey = None
if pkey is not None:
self.sql_string += ' PRIMARY KEY (`' + pkey.name + '`),\n'
for fkey in self.foreign_keys:
fdata = self.foreign_keys[fkey]
self.sql_string += ' FOREIGN KEY(' + fkey + ') REFERENCES ' + \
fdata[0] + '(' + fdata[1] + '),\n'
if (self.sql_string[-2] == ',') and (self.sql_string[-1] == '\n'):
# get rid of last comma
self.sql_string = self.sql_string[:-2] + '\n'
self.sql_string += ');\n'
def column(self, name, label, datatype, nulls, node, dtnode):
'''Processing a column'''
# skip virtual columns
if datatype == 'vrtcol':
return
# first comes the name
self.sql_string += ' `' + name + '` '
# then the datatype
try:
length = dtnode.length
except AttributeError:
length = None
if length:
self.sql_string += SQL_DATATYPES[datatype] + '(' + length + ') '
else:
self.sql_string += SQL_DATATYPES[datatype] + ' '
# any defaults
try:
defval = dtnode.default
except AttributeError:
defval = None
try:
defexpr = dtnode.defaultExpression
except AttributeError:
defexpr = defval
if defval:
self.sql_string += 'DEFAULT ' + str(defval) + ' '
elif defexpr:
self.sql_string += 'DEFAULT ' + defexpr + ' '
# null constraint
if not nulls:
self.sql_string += 'NOT NULL '
# auto-incrementing
try:
identity = dtnode.identity
except AttributeError:
identity = None
if not identity is None:
self.sql_string += 'AUTO_INCREMENT '
if self.sql_string[-1] == ' ':
self.sql_string = self.sql_string[:-1]
# and that's it folks
self.sql_string += ',\n'
# Is this column a foreign key into another table?
ftable = Driver.get_foreign_key(node)
if ftable is not None:
self.foreign_keys[name] = ftable
def view_start(self, name, node):
'''Starting to process view `name`'''
self.sql_string += 'CREATE VIEW IF NOT EXISTS `' + name + '` AS\n'
def view_end(self, name, node):
'''Done processing view `name`'''
self.sql_string += ';\n'
def view_subset(self, node, subset):
'''Process a subset in a view'''
name1 = subset.name1
col1 = subset.col1
name_in = subset.in_
incol = subset.incol
where = subset.where
constraint = subset.constraint
value = subset.value
if name_in is None:
# only a primary table
self.sql_string += ' SELECT * FROM ' + name1 + ' WHERE ' + \
col1 + constraint + value + '\n'
else:
# a primary and a secondary
self.sql_string += ' SELECT * FROM ' + name1 + ' WHERE ' + \
col1 + ' IN (\n' + \
' SELECT ' + incol + ' FROM ' + name_in + ' WHERE ' + \
where + constraint + value + ')\n'
# ----------------------------------------------------------------------------
class QtDriver(Driver):
'''
Build C++ classes with Qt support.
'''
def __init__(self, out_dir, template_dir,
namespace='', export_macro='',
import_header='',
base_class=META_TABLE_BASE):
self.out_dir = out_dir
self.template_dir = template_dir
self.data = {}
self.templates = {}
self.db_name = ''
self.import_header = import_header
self.namespace = namespace
self.export_macro = export_macro
self.base_class = base_class
self.tables = OrderedDict()
self.views = OrderedDict()
self.columns = OrderedDict()
self.vrtcols = [] # the names of the columns that are virtual
super(QtDriver, self).__init__()
def database_start(self, name, node):
'''Starting to process database `name`'''
self.db_name = name
def database_end(self, name, node):
'''Done processing database `name.`'''
self.check_foreign_keys()
all_hdr = ''
all_meta_hdr = ''
db_comp_id = ''
db_table_id = ''
db_tables_constr = ''
db_comp_name_case = ''
db_table_name_case = ''
db_name_to_id = ''
db_new_components = ''
nspace_prefix = self.db_name.lower() + '::meta::'
for tbl in self.tables:
with_nspace = nspace_prefix + tbl
dbc_name = 'DBC_' + tbl.upper()
dbt_name = 'DBT_' + tbl.upper()
all_hdr += '#include "' + tbl.lower() + '.h"\n'
all_meta_hdr += '#include "' + tbl.lower() + '-meta.h"\n'
db_comp_id += ' ' * 8 + dbc_name + ',\n'
db_table_id += ' ' * 8 + dbt_name + ',\n'
db_tables_constr += ' static ' + with_nspace + ' ' + \
tbl.lower() + ' () { return ' + with_nspace + '(); }\n'
db_comp_name_case += ' ' * 8 + 'case ' + dbc_name + \
': return QLatin1String("' + tbl + '");\n'
db_table_name_case += ' ' * 8 + 'case ' + dbt_name + \
': return QLatin1String("' + tbl + '");\n'
db_name_to_id += ' ' * 8 + 'if (!value.compare(QLatin1String("' + \
tbl + '"), Qt::CaseInsensitive)) return ' + dbc_name + ';\n'
db_new_components += ' ' * 8 + 'case ' + dbc_name + \
': return new ' + with_nspace + '();\n'
db_view_id = ''
db_views_constr = ''
db_view_name_case = ''
for view in self.views:
with_nspace = nspace_prefix + view
dbc_name = 'DBC_' + view.upper()
dbv_name = 'DBV_' + view.upper()
db_comp_id += ' ' * 8 + dbc_name + ',\n'
db_view_id += ' ' * 8 + dbv_name + ',\n'
db_views_constr += ' static ' + with_nspace + ' ' + \
view.lower() + ' () { return ' + with_nspace + \
'(); }\n'
db_comp_name_case += ' ' * 8 + 'case ' + dbc_name + \
': return QLatin1String("' + view + '");\n'
db_view_name_case += ' ' * 8 + 'case ' + dbv_name + \
': return QLatin1String("' + view + '");\n'
db_name_to_id += ' ' * 8 + 'if (!value.compare(QLatin1String("' + \
view + '"), Qt::CaseInsensitive)) return ' + dbc_name + ';\n'
all_hdr += '#include "' + view.lower() + '.h"\n'
all_meta_hdr += '#include "' + view.lower() + '-meta.h"\n'
db_new_components += ' ' * 8 + 'case ' + dbc_name + \
': return new ' + with_nspace + '();\n'
self.data['BaseClass'] = 'DbStructMeta'
self.data['baseclass'] = 'dbstructmeta'
self.data['BASECLASS'] = 'DBSTRUCTMETA'
self.data['INCLUDE_ALL_HEADERS'] = all_hdr
self.data['INCLUDE_ALL_META_HEADERS'] = all_meta_hdr
self.data['DBC_IDS'] = db_comp_id
self.data['DB_TABLE_IDS'] = db_table_id
self.data['DB_VIEW_IDS'] = db_view_id
self.data['DB_TABLES_CONSTR'] = db_tables_constr
self.data['DB_VIEWS_CONSTR'] = db_views_constr
self.data['DB_COMPONENTS_NAME_CASE'] = db_comp_name_case
self.data['DB_TABLES_NAME_CASE'] = db_table_name_case
self.data['DB_VIEWS_NAME_CASE'] = db_view_name_case
self.data['DB_COMPONENTS_NAME_TO_ID'] = db_name_to_id
self.data['DB_NEW_COMPONENTS'] = db_new_components
self.data['DB_CHANGED_COMPONENTS'] = db_new_components
fname = os.path.join(self.out_dir, self.data['database'] + '.h')
with open(fname, 'w') as foutp:
file.write(
foutp, self.get_template('database.h.template') % self.data)
fname = os.path.join(self.out_dir, self.data['database'] + '.cc')
with open(fname, 'w') as foutp:
file.write(
foutp, self.get_template('database.cc.template') % self.data)
fname = os.path.join(self.out_dir, 'all-meta-tables.h')
with open(fname, 'w') as foutp:
file.write(
foutp,
self.get_template('all-meta-tables.h.template') % self.data)
fname = os.path.join(self.out_dir, 'all-tables.h')
with open(fname, 'w') as foutp:
file.write(
foutp, self.get_template('all-tables.h.template') % self.data)
self.db_name = ''
def bootstrap_data(self, name):
'''Add common data in the variable map'''
now = datetime.datetime.now()
self.data = {
'Database': self.db_name,
'database': self.db_name.lower(),
'DATABASE': self.db_name.upper(),
'Table': name,
'table': name.lower(),
'TABLE': name.upper(),
'Namespace': self.namespace,
'namespace': self.namespace.lower(),
'NAMESPACE': self.namespace.upper(),
'BaseClass': self.base_class,
'baseclass': self.base_class.lower(),
'BASECLASS': self.base_class.upper(),
'MetaClassInclude': META_TABLE_BASE_FILE,
'RecordBaseClass': RECORD_BASE,
'EXPORT': self.export_macro,
'IMPORTH': '#include <%s>' % self.import_header,
'Year': str(now.year),
'Month': now.strftime("%B"),
'Author': AUTHOR
}
def table_start(self, name, node):
'''Starting to process table `name`'''
self.tables[name] = {}
self.columns = OrderedDict()
self.bootstrap_data(name)
self.vrtcols = []
def fill_table_data(self, name):
'''Prepare values for variables in the context of this table'''
id_column = -1
pipe_columns = ''
case_columns = ''
case_label = ''
model_label = ''
bind_columns = ''
bind_one_column = ''
changed_column = ''
comma_columns = ''
column_columns = ''
assign_columns = ''
comma_columns_no_id = ''
retrieve_columns = ''
record_columns = ''
rec_to_map = ''
rec_from_map = ''
column_getters = ''
column_index_getters = ''
table_data_members = ''
default_constr = ''
assign_constr = ''
copy_constr = ''
real_column_mapping = ''
virtual_column_mapping = ''
set_table_defaults = ''
i = -1
real_id = 0
column_ids = ''
for i, col in enumerate(self.columns):
coldata = self.columns[col]
col_var_name = col.lower()
qtype = coldata['qtype']
defval = coldata['defval']
dynamic = coldata['dynamic']
to_cast = TO_CAST[qtype]
to_converter = FROM_VARIANT[qtype]
dbc_name = 'COLID_' + col.upper()
column_ids += ' ' * 8 + dbc_name + ',\n'
column_label = 'QCoreApplication::translate("' + self.db_name + \
'::' + name + '", "' + coldata['label'] + '")'
col_mapping_nicety = '/* ' + dbc_name + ' -> */ '
col_mapping_nicety += ' ' * (64 - len(col_mapping_nicety))
real_column_mapping += 4*' ' + col_mapping_nicety
pipe_columns += ' ' * 8 + '<< QLatin1String("' + col + '")\n'
if not coldata['virtual']:
real_column_mapping += str(real_id) + ',\n'
virtual_column_mapping += 4*' ' + col_mapping_nicety + str(i) + ',\n'
if col == 'id':
id_column = i
if coldata['autoincrement']:
default_constr = default_constr + ' ' * 8 + col_var_name + \
'(COLID_INVALID),\n'
elif qtype == 'QString':
default_constr = default_constr + ' ' * 8 + col_var_name + \
'(QLatin1String("-1")),\n'
else:
default_constr = default_constr + ' ' * 8 + col_var_name + \
'(),\n'
else:
default_constr = default_constr + ' ' * 8 + \
col_var_name + '(),\n'
comma_columns_no_id += ' ' * 12 + '"' + col + ',"\n'
column_columns += ' ' * 12 + '":' + col + ',"\n'
assign_columns += ' ' * 12 + '"' + col + '=:' + col + ',"\n'
bind_one_column += ' ' * 4 + 'case ' + dbc_name + \
': query.bindValue (QLatin1String(":' + col + '"), ' + \
col_var_name + '); break;\n'
changed_column += ' ' * 4 + 'if (other.' + col_var_name + \
' != ' + col_var_name + ') result << ' +\
dbc_name + ';\n'
bind_columns += ' ' * 4 + 'query.bindValue (QLatin1String(":' + \
col + '"), ' + col_var_name + ');\n'
comma_columns += ' ' * 12 + '"' + col + ',"\n'
retrieve_columns += \
' %-26s = %10squery.value (/* %33s */ %4d).%s;\n' % (
col_var_name, to_cast, dbc_name, real_id, to_converter)
record_columns += \
' %-20s = %10srec.value (%40s).%s;\n' % (
col_var_name, to_cast,
'QLatin1String("%s")' % col,
to_converter)
else: # is virtual
real_column_mapping += '-1,\n'
default_constr = default_constr + ' ' * 8 + \
col_var_name + '(),\n'
assign_constr = assign_constr + ' ' * 8 + col_var_name + \
' = other.' + col_var_name + ';\n'
copy_constr = copy_constr + ' ' * 8 + col_var_name + \
' (other.' + col_var_name + '),\n'
table_data_members += ' ' * 4 + qtype + ' ' + col.lower() + ';\n'
case_label += ' ' * 4 + 'case ' + dbc_name + ': result = ' + \
column_label + '; break;\n'
case_columns += ' ' * 4 + 'case ' + dbc_name + \
': result = QLatin1String("' + col + '"); break;\n'
model_label += ' ' * 4 + 'model->setHeaderData (' + dbc_name + \
', Qt::Horizontal, ' + column_label + ');\n'
# definition related to foreign keys
fkey_data = coldata['fkey']
if fkey_data:
if 'foreignInsert' in coldata:
fkey_data[2] = coldata['foreignInsert']
fkey_col = '%-40s, %-30s, %-30s, %-15s' % (
'QLatin1String("%s")' % fkey_data[0],
'QLatin1String("%s")' % fkey_data[1],
'QLatin1String("%s")' % fkey_data[2]
if fkey_data[2] else 'QString()',
'DbColumn::FB_CHOOSE'
if fkey_data[3] == '' or fkey_data[3] == 'choose'
else 'DbColumn::FB_CHOOSE_ADD')
# fkey_col = 'QLatin1String("' + fkey_data[0] + \
# '"), QLatin1String("' + fkey_data[1] + '"), '
# if fkey_data[2]:
# fkey_col += 'QLatin1String("' + fkey_data[2] + '")'
# else:
# fkey_col += 'QString()'
# if fkey_data[3] == '' or fkey_data[3] == 'choose':
# fkey_col += ', DbColumn::FB_CHOOSE'
# else:
# fkey_col += ', DbColumn::FB_CHOOSE_ADD'
else:
fkey_col = '%-40s, %-30s, %-30s, %-15s' % (
'QString()', 'QString()',
'QString()', 'DbColumn::FB_CHOOSE')
# the other column for virtual columns
try:
virt_ref_col = 'COLID_' + coldata['reference'].upper()
except (KeyError, AttributeError):
virt_ref_col = -1
# constructor for column
column_create = 'DbColumn (%-40s,%-25s,%-6d,%-6d,%-80s,%-30s,%-7s,%-7s,' \
'%-25s,%-40s,%-7s,%-16s,%s)' % (
'QLatin1String("%s")' % col,
dbc_name,
real_id,
int(coldata['length']) if coldata['length'] else -1,
column_label,
'DbColumn::DTY_%s' % coldata['datatype'].upper(),
'true' if coldata['nulls'] else 'false',
'true' if coldata['autoincrement'] else 'false',
'QLatin1String("%s")' % coldata['defexpr']
if coldata['defexpr'] else 'QString()',
'QLatin1String("%s")' % coldata['format']
if coldata['format'] else 'QString()',
'true' if coldata['ronly'] else 'false',
virt_ref_col,
fkey_col
)
# column_create = 'DbColumn("' + \
# col + '", ' + \
# dbc_name + ', '+ \
# str(real_id) + ', '+ \
# string_choice(coldata['length'], '-1', coldata['length']) + \
# ', ' + column_label + ', ' + \
# 'DbColumn::DTY_' + coldata['datatype'].upper() + ', ' + \
# string_choice('true', 'false', coldata['nulls']) + ', ' + \
# string_choice('true', 'false', coldata['autoincrement']) + \
# ', QLatin1String("' + string_choice('', coldata['defexpr'],
# coldata['defexpr'] is None) + '")' + \
# ', QLatin1String("' + string_choice('', coldata['format'],
# coldata['format'] is None) + '"), ' + \
# string_choice('true', 'false', coldata['ronly']) + ', ' + \
# string_choice(virt_ref_col, '-1', coldata['virtual']) + \
# ', ' + fkey_col + ')'
column_getters += \
' static DbColumn %30sColCtor () { return %s; }\n' % (
col.lower(), column_create)
column_index_getters += \
' case %20s: return %s;\n' % (dbc_name, column_create)
rec_to_map += \
' result.insert(%-40s, %-30s);\n' % (
'QLatin1String ("%s")' % col,
('qVariantFromValue (%s)' % col_var_name)
if dynamic else 'QVariant (%s)' % col_var_name)
rec_from_map += \
' if (!i.key ().compare (%40s)) { ' \
'%-20s = i.value ().%s; }\n' % (
'QLatin1String ("%s")' % col,
col_var_name,
to_converter)
if defval:
set_table_defaults += make_value_setter(
col_var_name, defval, qtype)
real_id = real_id + (not coldata['virtual'])
int_types = ['long', 'integer', 'bigint', 'smallint', 'tinyint']
if id_column == -1:
id_column = 'COLID_INVALID'
get_id_result = 'COLID_INVALID'
set_id = '// id unavailable in this model'
elif self.columns['id']['datatype'] in int_types:
get_id_result = 'id'
set_id = 'id = value'
else:
get_id_result = 'COLID_INVALID'
set_id = '// id unavailable in this model'
default_constr = default_constr[:-2]
copy_constr = copy_constr[:-2]
assign_constr = assign_constr[:-1]
pipe_columns = pipe_columns[:-1]
case_columns = case_columns[:-1]
bind_columns = bind_columns[:-1]
bind_one_column = bind_one_column[:-1]
comma_columns = comma_columns[:-3] + '"'
comma_columns_no_id = comma_columns_no_id[:-3] + '"'
column_columns = column_columns[:-3] + '"'
assign_columns = assign_columns[:-3] + '"'
real_column_mapping = real_column_mapping[:-2]
virtual_column_mapping = virtual_column_mapping[:-2]
self.data['COLUMN_COUNT'] = str(len(self.columns))
self.data['PIPE_COLUMNS'] = pipe_columns
self.data['CASE_COLUMNS'] = case_columns
self.data['CASE_LABELS'] = case_label
self.data['MODEL_LABELS'] = model_label
self.data['BIND_COLUMNS'] = bind_columns
self.data['RETREIVE_COLUMNS'] = retrieve_columns
self.data['RECORD_COLUMNS'] = record_columns
self.data['BIND_ONE_COLUMN'] = bind_one_column
self.data['CHANGED_COLUMNS'] = changed_column
self.data['ID_COLUMN'] = str(id_column)
self.data['GET_ID_RESULT'] = str(get_id_result)
self.data['SET_ID_RESULT'] = str(set_id)
self.data['COMMA_COLUMNS'] = comma_columns
self.data['COMMA_COLUMNS_NO_ID'] = comma_columns_no_id
self.data['COLUMN_COLUMNS'] = column_columns
self.data['ASSIGN_COLUMNS'] = assign_columns
self.data['COLUMN_IDS'] = column_ids
self.data['TableColumnConstr'] = column_getters
self.data['TableColumnsIndexCtor'] = column_index_getters
self.data['TableDataMembers'] = table_data_members
self.data['CopyConstructor'] = copy_constr
self.data['AssignConstructor'] = assign_constr
self.data['DefaultConstructor'] = default_constr
self.data['RecToMap'] = rec_to_map
self.data['RecFromMap'] = rec_from_map
self.data['SetTableDefaults'] = set_table_defaults
self.data['SetTableOverrides'] = ''
self.data['RealColumnMapping'] = real_column_mapping
self.data['VirtualColumnMapping'] = virtual_column_mapping
def table_end(self, name, node):
'''Done processing table `name`'''
self.tables[name]['columns'] = self.columns
for vrtcol in self.vrtcols:
vrtdata = self.columns[vrtcol]
if not vrtdata['dynamic']:
coldata = self.columns[vrtdata['reference']]
for okey in coldata:
if not okey in vrtdata:
vrtdata[okey] = coldata[okey]
else:
vrtdata['qtype'] = 'void *'
vrtdata['defval'] = 'NULL'
vrtdata['defexpr'] = 'NULL'
vrtdata['fkey'] = ''
vrtdata['length'] = 0
vrtdata['datatype'] = 'CALLBACK'
vrtdata['nulls'] = False
vrtdata['autoincrement'] = False
vrtdata['format'] = False
#for vrtcol in self.vrtcols:
# if (vrtcol == 'area'):
# print ';;;;;', vrtcol, '------------------------------'
# # retrieve the dictionary associated with this column
# vrtdata = self.columns[vrtcol]
# # get the column in this table that actually ties to a foreign
# # table and obtain the name of the table and other info in its fkey
# ftable, fcolumn, finsert, fbehavior = \
# self.columns[vrtdata['reference']]['fkey']
# # get the column from the foreign table that we're going
# # to mirror here
# coldata = self.tables[ftable][vrtdata['foreignInsert']]
# # and import its properties
# for okey in coldata:
# print '***', vrtdata['reference'], okey, coldata[okey]
# if not okey in vrtdata:
# vrtdata[okey] = coldata[okey]
# print ';;;;;', vrtcol
# if (vrtcol == 'area'):
# print ';;;;;', vrtcol, '----', self.columns[vrtcol]['datatype']
self.fill_table_data(name)
if len(self.data['SetTableOverrides']) == 0:
self.data['SetTableOverrides'] = ' Q_UNUSED(result);'
fname = os.path.join(self.out_dir, self.data['table'] + '.h')
with open(fname, 'w') as foutp:
file.write(
foutp, self.get_template('table.h.template') % self.data)
fname = os.path.join(self.out_dir, self.data['table'] + '-meta.h')
with open(fname, 'w') as foutp:
file.write(
foutp, self.get_template('table-meta.h.template') % self.data)
fname = os.path.join(self.out_dir, self.data['table'] + '.cc')
with open(fname, 'w') as foutp:
file.write(
foutp, self.get_template('table.cc.template') % self.data)
fname = os.path.join(self.out_dir, self.data['table'] + '-meta.cc')
with open(fname, 'w') as foutp:
file.write(
foutp, self.get_template('table-meta.cc.template') % self.data)
def column(self, name, label, datatype, nulls, node, dtnode):
'''Processing a column'''
# see if this is one of those virtual columns
if datatype == 'vrtcol':
# we should not expect the reference column
# to be already defined so we defer the processing
# for the end of the table
self.columns[name] = {
'virtual': True,
'label': label,
'ronly': True,
'reference': dtnode.references,
'dynamic': dtnode.dynamic,
'foreignInsert': node.foreignInsert
}
self.vrtcols.append(name)
else:
# the datatype
try:
length = dtnode.length
except AttributeError:
length = None
# any defaults?
try:
defval = dtnode.default
except AttributeError:
defval = None
try:
defexpr = dtnode.defaultExpression
except AttributeError:
defexpr = None
if defval:
defexpr = defval
# auto-incrementing
try:
identity = dtnode.identity
except AttributeError:
identity = None
try:
read_only = node.readOnly
except AttributeError:
read_only = False
try:
format_str = node.userformat
except AttributeError:
format_str = None
qtype = dtnode.qtype
if not qtype:
qtype = datatype
self.columns[name] = {
'virtual': False,
'qtype': qtype,
'label': label,
'length': length,
'nulls': nulls,
'defexpr': defexpr,
'defval': defval,
'autoincrement': not identity is None,
'datatype': datatype,
'fkey': Driver.get_foreign_key(node),
'format': format_str,
'ronly': read_only,
'dynamic': False
}
def view_start(self, name, node):
'''Starting to process view `name`'''
self.views[name] = {}
self.bootstrap_data(name)
self.columns = OrderedDict()
def view_end(self, name, node):
'''Done processing view `name`'''
self.views[name]['columns'] = self.columns
name = name.lower()
if len(self.data['SetTableOverrides']) == 0:
self.data['SetTableOverrides'] = ' Q_UNUSED(result);'
fname = os.path.join(self.out_dir, name + '.h')
with open(fname, 'w') as foutp:
file.write(
foutp, self.get_template('view.h.template') % self.data)
fname = os.path.join(self.out_dir, name + '-meta.h')
with open(fname, 'w') as foutp:
file.write(
foutp, self.get_template('view-meta.h.template') % self.data)
fname = os.path.join(self.out_dir, name + '.cc')
with open(fname, 'w') as foutp:
file.write(
foutp, self.get_template('view.cc.template') % self.data)
fname = os.path.join(self.out_dir, name + '-meta.cc')
with open(fname, 'w') as foutp:
file.write(
foutp, self.get_template('view-meta.cc.template') % self.data)
def view_subset(self, node, subset):
'''Process a subset in a view'''
name1 = subset.name1
#col1 = subset.col1
name_in = subset.in_
#incol = subset.incol
#where = subset.where
#constraint = subset.constraint
#value = subset.value
self.columns = self.tables[name1]['columns']
self.fill_table_data(name1)
defaults = {}
for col in self.columns:
coldata = self.columns[col]
defaults[col] = coldata['defval']
self.data['TableModify'] = name1
self.data['BaseClass'] = 'DbView'
self.data['baseclass'] = 'dbview'
self.data['BASECLASS'] = 'DBVIEW'
force_values = {}
if hasattr(node, 'writeback'):
self.data['TableModify'] = node.writeback.table
if hasattr(node.writeback, 'column'):
for column in node.writeback.column:
if hasattr(column, 'value'):
force_values[column.name] = column.value
if hasattr(column, 'default'):
defaults[column.name] = column.default
set_table_overrides = ''
for col in force_values:
col_var_name = col.lower()
colval = force_values[col]
if colval is not None:
set_table_overrides += make_value_setter(col_var_name, colval, \
self.columns[col]['qtype'])
set_table_defaults = ''
for col in defaults:
col_var_name = col.lower()
colval = defaults[col]
if colval is not None:
set_table_defaults += make_value_setter(col_var_name, colval, \