-
Notifications
You must be signed in to change notification settings - Fork 3
/
Jet.dpr
1876 lines (1638 loc) · 56.4 KB
/
Jet.dpr
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
program Jet;
{$APPTYPE CONSOLE}
uses
SysUtils,
Windows,
ActiveX,
Variants,
AdoDb,
OleDb,
AdoInt,
ComObj,
DAO_TLB,
ADOX_TLB,
StreamUtils in 'StreamUtils.pas',
StringUtils in 'StringUtils.pas',
DaoDumper in 'DaoDumper.pas',
JetCommon in 'JetCommon.pas',
AdoxDumper in 'AdoxDumper.pas',
JetDataFormats in 'JetDataFormats.pas',
Jet.IO in 'Jet.IO.pas',
Jet.Connection in 'Jet.Connection.pas',
Jet.CommandLine in 'Jet.CommandLine.pas';
//{$DEFINE DUMP_CHECK_CONSTRAINTS}
//Feature under development.
(*
Supported propietary extension comments:
/**COMMENT* [comment text] */ - table, field or view comment
/**WEAK**/ - ignore errors for this command (handy for DROP TABLE/VIEW)
By default when reading from keyboard these are set:
--ignore-errors
--crlf-break
--verbose
These are dumped by default:
--tables
--views
--relations
--comments
--private-extensions
Returns error codes:
1 :: Generic error
2 :: Usage error
3 :: OLE Error
What this thing dumps:
Tables
Comments
Fields
Standard field markers [not null, default]
Auto-increment
Comments
Indexes
Multi- and single-type indexes
Standard markers [unique, disallow null, ignore null, primary key]
Foreign keys
Views
Procedures
Data from tables and queries
What can be added in the future:
Check constraints
Rest of the "table constraints"
A note about constraints. There are:
Check constraints :: added through SQL, unrelated to anything else
Referential constraints :: automatically generated for foreign keys
Unique index constraints :: automatically added for every UNIQUE index
Manual table constraints :: any other constraints added manually through
ADD CONSTRAINT which are not CHECK CONSTRAINT.
All of these compose "Table constraints".
Documentation:
http://msdn.microsoft.com/en-us/library/ms714540(VS.85).aspx :: Access data types
http://msdn.microsoft.com/en-us/library/bb267262(office.12).aspx :: Access 2007 DDL
Schema documentation:
http://msdn.microsoft.com/en-us/library/ms675274(VS.85).aspx :: Schema identifiers
http://msdn.microsoft.com/en-us/library/ee265709(BTS.10).aspx :: Some of the schemas, documented
Adding and modifying check constraints (not documented in MSDN):
http://www.w3schools.com/Sql/sql_check.asp
*)
{$UNDEF DEBUG}
type
PWideCharArray = ^TWideCharArray;
TWideCharArray = array[0..16383] of WideChar;
OemString = type AnsiString(CP_OEMCP);
procedure PrintShortUsage;
begin
err('Do "jet help" for extended info.');
end;
procedure PrintUsage;
begin
err('Usage:');
err(' jet <command> [params]');
err('');
err('Commands:');
err(' jet touch :: connect to database and quit');
err(' jet dump :: dump sql schema / data');
err(' jet exec :: parse sql from input');
err(' jet schema :: output internal jet schema reports');
err(' jet daoschema :: output DAO schema report');
err(' jet adoxschema :: output ADOX schema report');
err('');
ConnectionSettings.PrintUsage;
err('What to include in the dump:');
err(' --tables, --no-tables');
err(' --views, --no-views');
err(' --procedures, --no-procedures');
err(' --relations, --no-relations');
{$IFDEF DUMP_CHECK_CONSTRAINTS}
err(' --check-constraints, --no-check-constraints');
{$ENDIF}
err(' --data, --no-data');
err(' --query "SQL QUERY" TableName :: data from this SQL query (each subsequent usage adds a query to the list)');
err('If none of these are explicitly given, the default set MAY be used. If any is given, only that is exported.');
err('Shortcuts: --all, --none, --default');
err('');
err(' --comments, --no-comments :: how comments are dumped depends on if private extensions are enabled');
err(' --drop, --no-drop :: DROP tables etc before creating');
err(' --create, --no-create :: CREATE tables etc (on by default)');
err(' --enable-if-exists, --disable-if-exists :: enables IF EXISTS option for DROP commands (not supported by Jet)');
err('');
err('With --tables, --views and --data you can specify individual names:');
err(' --tables [tablename],[tablename]');
err(' --views [viewname],[viewname]');
err(' --data [tablename],[tablename] :: defaults to same as --tables');
err('Specify --case-sensitive-ids or --case-insensitive-ids if needed (default: sensitive).');
err('');
err('Works both for dumping and executing:');
err(' --no-private-extensions, --private-extensions :: disables dumping/parsing private extensions (see help)');
err('');
IoSettings.PrintUsage;
end;
var
Command: UniString;
//Database options
CaseInsensitiveIDs: boolean;
Supports_IfExists: boolean; //database supports IF EXISTS syntax
//Dump contents
DumpDefaultSourceSet: boolean = true; //cleared if the user has explicitly said what to dump
NeedDumpTables: boolean = false;
DumpTableList: TUniStringArray; //empty = all
NeedDumpViews: boolean = false;
DumpViewList: TUniStringArray;
NeedDumpProcedures: boolean = false;
NeedDumpRelations: boolean = false;
{$IFDEF DUMP_CHECK_CONSTRAINTS}
NeedDumpCheckConstraints: boolean = false;
{$ENDIF}
NeedDumpData: boolean = false;
DumpDataList: TUniStringArray; //empty = use DumpTableList
DumpQueryList: array of record
Query: string;
TableName: string;
end;
//Dump options
HandleComments: boolean = true;
PrivateExtensions: boolean = true;
DropObjects: boolean = true; //add DROP commands
CreateObjects: boolean = true; //add CREATE commands
procedure ConfigureDumpAllSources;
begin
NeedDumpTables := true;
SetLength(DumpTableList, 0);
NeedDumpViews := true;
SetLength(DumpViewList, 0);
NeedDumpProcedures := true;
NeedDumpRelations := true;
{$IFDEF DUMP_CHECK_CONSTRAINTS}
NeedDumpCheckConstraints := true;
{$ENDIF}
NeedDumpData := true;
SetLength(DumpDataList, 0);
end;
procedure ConfigureDumpNoSources;
begin
NeedDumpTables := false;
SetLength(DumpTableList, 0);
NeedDumpViews := false;
SetLength(DumpViewList, 0);
NeedDumpProcedures := false;
NeedDumpRelations := false;
{$IFDEF DUMP_CHECK_CONSTRAINTS}
NeedDumpCheckConstraints := false;
{$ENDIF}
NeedDumpData := false;
SetLength(DumpDataList, 0);
end;
procedure ConfigureDumpDefaultSources;
begin
NeedDumpTables := true;
SetLength(DumpTableList, 0);
NeedDumpViews := true;
SetLength(DumpViewList, 0);
NeedDumpProcedures := true;
NeedDumpRelations := true;
{$IFDEF DUMP_CHECK_CONSTRAINTS}
NeedDumpCheckConstraints := true;
{$ENDIF}
NeedDumpData := false;
SetLength(DumpDataList, 0);
end;
procedure ParseCommandLine;
var ctx: TParsingContext;
s, list: UniString;
begin
ctx.Reset;
while ctx.TryNextArg(s) do begin
if Length(s) <= 0 then
continue;
if s[1] <> '-' then begin
Define(Command, 'Command', s);
end else
if ConnectionSettings.HandleOption(@ctx, s) then begin
end else
//Database options
if WideSameText(s, '--case-sensitive-ids') then begin
CaseInsensitiveIDs := false;
end else
if WideSameText(s, '--case-insensitive-ids') then begin
CaseInsensitiveIDs := true;
end else
//What to dump
if WideSameText(s, '--tables') then begin
DumpDefaultSourceSet := false; //override default
NeedDumpTables := true;
if ctx.TryNextParam(s, 'table list', list) then begin
DumpTableList := Split(list, ',');
if Length(DumpTableList) <= 0 then
//Empty DumpTableList internally means dump all, so just disable dump if asked for none
NeedDumpTables := false;
end;
end else
if WideSameText(s, '--no-tables') then begin
DumpDefaultSourceSet := false;
NeedDumpTables := false;
end else
if WideSameText(s, '--views') then begin
DumpDefaultSourceSet := false; //override default
NeedDumpViews := true;
if ctx.TryNextParam(s, 'view list', list) then begin
DumpViewList := Split(list, ',');
if Length(DumpViewList) <= 0 then
NeedDumpViews := false;
end;
end else
if WideSameText(s, '--no-views') then begin
DumpDefaultSourceSet := false;
NeedDumpViews := false;
end else
if WideSameText(s, '--procedures') then begin
DumpDefaultSourceSet := false; //override default
NeedDumpProcedures := true;
end else
if WideSameText(s, '--no-procedures') then begin
DumpDefaultSourceSet := false;
NeedDumpProcedures := false;
end else
if WideSameText(s, '--relations') then begin
DumpDefaultSourceSet := false; //override default
NeedDumpRelations := true;
end else
if WideSameText(s, '--no-relations') then begin
DumpDefaultSourceSet := false;
NeedDumpRelations := false;
end else
{$IFDEF DUMP_CHECK_CONSTRAINTS}
if WideSameText(s, '--check-constraints') then begin
DumpDefaultSourceSet := false; //override default
NeedDumpCheckConstraints := true;
end else
if WideSameText(s, '--no-check-constraints') then begin
DumpDefaultSourceSet := false;
NeedDumpCheckConstraints := false;
end else
{$ENDIF}
if WideSameText(s, '--data') then begin
DumpDefaultSourceSet := false;
NeedDumpData := true;
if ctx.TryNextParam(s, 'table list', list) then begin
DumpDataList := Split(list, ',');
if Length(DumpDataList) <= 0 then
//Empty DumpDataList internally means dump all, so just disable dump if asked for none
NeedDumpData := false;
end;
end else
if WideSameText(s, '--no-data') then begin
DumpDefaultSourceSet := false;
NeedDumpData := false;
end else
if WideSameText(s, '--query') then begin
DumpDefaultSourceSet := false;
SetLength(DumpQueryList, Length(DumpQueryList)+1);
DumpQueryList[Length(DumpQueryList)-1].Query := ctx.NextParam(s, 'SQL query text');
DumpQueryList[Length(DumpQueryList)-1].TableName := ctx.NextParam(s, 'Table name');
end else
//Shortcuts
//Use to explicitly set the playing field before modifying
if WideSameText(s, '--all') then begin
DumpDefaultSourceSet := false;
ConfigureDumpAllSources();
end else
if WideSameText(s, '--none') then begin
DumpDefaultSourceSet := false;
ConfigureDumpNoSources();
end else
if WideSameText(s, '--default') then begin
DumpDefaultSourceSet := false;
ConfigureDumpDefaultSources(); //configure right now, so it can be overriden
end else
//Dump options
if WideSameText(s, '--comments') then begin
HandleComments := true; {when dumping this means DUMP comments, else PARSE comments - requires PrivateExt}
end else
if WideSameText(s, '--no-comments') then begin
HandleComments := false;
end else
if WideSameText(s, '--private-extensions') then begin
PrivateExtensions := true;
end else
if WideSameText(s, '--no-private-extensions') then begin
PrivateExtensions := false;
end else
if WideSameText(s, '--drop') then begin
DropObjects := true;
end else
if WideSameText(s, '--no-drop') then begin
DropObjects := false;
end else
if WideSameText(s, '--create') then begin
CreateObjects := true;
end else
if WideSameText(s, '--no-create') then begin
CreateObjects := false;
end else
if WideSameText(s, '--enable-if-exists') then begin
Supports_IfExists := true;
end else
if WideSameText(s, '--disable-if-exists') then begin
Supports_IfExists := false;
end else
if IoSettings.HandleOption(@ctx, s) then begin
end else
//Default case
BadUsage('Unsupported option: '+s);
end;
//If asked for help, there's nothing to check
if WideSameText(Command, 'help') then exit;
ConnectionSettings.Finalize;
//To parse comments we need DAO, i.e. filename connection
if WideSameText(Command, 'exec') and HandleComments then begin
if not PrivateExtensions then
BadUsage('You need --private-extensions to handle --comments when doing "exec".');
if (Filename='') and (DataSourceName='') then
BadUsage('You cannot use ConnectionString source with --comments when doing "exec"');
end;
if NewDb and (WideSameText(Command, 'dump')
or WideSameText(Command, 'schema') or WideSameText(Command, 'daoschema')
or WideSameText(Command, 'adoxschema'))
and (LoggingMode=lmVerbose) then begin
err('NOTE: You asked to create a database and then dump its contents.');
err('What the hell are you trying to do?');
end;
//If no modifications have been made, dump default set of stuff
if DumpDefaultSourceSet then
ConfigureDumpDefaultSources;
//If asked for case-insensitive IDs, lowercase all relevant cached info
if CaseInsensitiveIDs then begin
DumpTableList := ToLowercase(DumpTableList);
DumpViewList := ToLowercase(DumpViewList);
end;
IoSettings.Finalize;
end;
////////////////////////////////////////////////////////////////////////////////
/// Touch --- establishes connection and quits
procedure Touch();
var conn: _Connection;
begin
conn := GetAdoConnection;
end;
////////////////////////////////////////////////////////////////////////////////
//// Schema --- Dumps many schema tables returned by Access
procedure DumpRecordset(rs: _Recordset);
var i: integer;
begin
while not rs.EOF do begin
for i := 0 to rs.Fields.Count - 1 do
writeln(rs.Fields[i].Name+'='+str(rs.Fields[i].Value));
writeln('');
rs.MoveNext();
end;
end;
procedure DumpSchema(conn: _Connection; Schema: integer);
var rs: _Recordset;
begin
rs := conn.OpenSchema(Schema, EmptyParam, EmptyParam);
DumpRecordset(rs);
end;
procedure Dump(conn: _Connection; SectionName: string; Schema: integer);
begin
Section(SectionName);
DumpSchema(conn, Schema);
end;
procedure PrintSchema();
var conn: _Connection;
begin
conn := GetAdoConnection;
// Dump(conn, 'Catalogs', adSchemaCatalogs); ---not supported by Access
Dump(conn, 'Tables', adSchemaTables);
Dump(conn, 'Columns', adSchemaColumns);
// Dump(conn, 'Asserts', adSchemaAsserts); ---not supported by Access
Dump(conn, 'Check constraints', adSchemaCheckConstraints);
Dump(conn, 'Referential constraints', adSchemaReferentialConstraints);
Dump(conn, 'Table constraints', adSchemaTableConstraints);
Dump(conn, 'Column usage', adSchemaConstraintColumnUsage);
Dump(conn, 'Key column usage', adSchemaKeyColumnUsage);
// Dump(conn, 'Table usage', adSchemaConstraintTableUsage); --- not supported by Access
Dump(conn, 'Indexes', adSchemaIndexes);
Dump(conn, 'Primary keys', adSchemaPrimaryKeys);
Dump(conn, 'Foreign keys', adSchemaForeignKeys);
// Dump(conn, 'Properties', adSchemaProperties); ---not supported by Access
// Dump(conn, 'Procedure columns', adSchemaProcedureColumns); -- not supported by Access
// Dump(conn, 'Procedure parameters', adSchemaProcedureParameters); -- not supported by Access
Dump(conn, 'Procedures', adSchemaProcedures);
// Dump(conn, 'Provider types', adSchemaProviderTypes); -- nothing of interest
end;
////////////////////////////////////////////////////////////////////////////////
//// DaoSchema -- dumps DAO structure
procedure PrintDaoSchema();
begin
DaoDumper.PrintDaoSchema(GetDaoConnection);
end;
////////////////////////////////////////////////////////////////////////////////
//// AdoxSchema -- dumps ADOX structure
procedure PrintAdoxSchema();
begin
AdoxDumper.PrintAdoxSchema(GetAdoxCatalog);
GetAdoxCatalog.Tables[0].Properties
end;
////////////////////////////////////////////////////////////////////////////////
/// DumpSql --- Dumps database contents
(*
Writes a warning to a generated file. If we're not in silent mode, outputs it as an error too.
This should be used in cases where the warning is really important (something cannot be done,
some information ommited). If you just want to give a hint, use "err(msg)";
*)
procedure Warning(msg: UniString);
begin
writeln('/* !!! Warning: '+msg+' */');
warn('Warning: '+msg);
end;
{$REGION 'Columns'}
type
TColumnDesc = record
Name: WideString;
Description: WideString;
Flags: integer;
OrdinalPosition: integer;
DataType: integer;
IsNullable: OleVariant;
HasDefault: OleVariant;
Default: OleVariant;
NumericScale: OleVariant;
NumericPrecision: OleVariant;
CharacterMaximumLength: OleVariant;
AutoIncrement: boolean;
end;
PColumnDesc = ^TColumnDesc;
TColumns = record
data: array of TColumnDesc;
procedure Clear;
procedure Add(Column: TColumnDesc);
procedure Sort;
end;
procedure TColumns.Clear;
begin
SetLength(data, 0);
end;
procedure TColumns.Add(Column: TColumnDesc);
begin
SetLength(data, Length(data)+1);
data[Length(data)-1] := Column;
end;
procedure TColumns.Sort;
var i, j, k: integer;
tmp: TColumnDesc;
begin
for i := 1 to Length(data) - 1 do begin
j := i-1;
while (j >= 0) and (data[i].OrdinalPosition < data[j].OrdinalPosition) do
Dec(j);
Inc(j);
if j<>i then begin
tmp := data[i];
for k := i downto j+1 do
data[k] := data[k-1];
data[j] := tmp;
end;
end;
end;
{$ENDREGION}
function GetTableText(conn: _Connection; Table: UniString): UniString;
var rs: _Recordset;
Columns: TColumns;
Column: TColumnDesc;
s, dts: string;
tmp: OleVariant;
pre, scal: OleVariant;
AdoxTable: ADOX_TLB.Table;
DaoTable: DAO_TLB.TableDef;
begin
//Doing this through DAO is slightly faster (OH GOD HOW MUCH DOES ADOX SUCK),
//but DAO can only be used with -f, so effectively we just strip out all
//the other options.
if CanUseDao then //filename connection
DaoTable := GetDaoConnection.TableDefs[Table]
else
AdoxTable := GetAdoxCatalog.Tables[Table];
rs := conn.OpenSchema(adSchemaColumns,
VarArrayOf([Unassigned, Unassigned, Table, Unassigned]), EmptyParam);
//Reading data
Columns.Clear;
while not rs.EOF do begin
Column.Name := str(rs.Fields['COLUMN_NAME'].Value);
Column.Description := str(rs.Fields['DESCRIPTION'].Value);
Column.Flags := int(rs.Fields['COLUMN_FLAGS'].Value);
Column.OrdinalPosition := int(rs.Fields['ORDINAL_POSITION'].Value);
tmp := rs.Fields['DATA_TYPE'].Value;
if VarIsNil(tmp) then begin
Warning('Empty data type for column '+Column.Name);
rs.MoveNext();
continue;
end;
Column.DataType := integer(tmp);
Column.IsNullable := rs.Fields['IS_NULLABLE'].Value;
Column.HasDefault := rs.Fields['COLUMN_HASDEFAULT'].Value;
Column.Default := rs.Fields['COLUMN_DEFAULT'].Value;
Column.NumericPrecision := rs.Fields['NUMERIC_PRECISION'].Value;
Column.NumericScale := rs.Fields['NUMERIC_SCALE'].Value;
Column.CharacterMaximumLength := rs.Fields['CHARACTER_MAXIMUM_LENGTH'].Value;
if CanUseDao then
Column.AutoIncrement := Includes(cardinal(DaoTable.Fields[Column.Name].Attributes), dbAutoIncrField)
else
Column.AutoIncrement := AdoxTable.Columns[Column.Name].Properties['AutoIncrement'].Value;
Columns.Add(Column);
rs.MoveNext;
end;
Columns.Sort;
//Building string
Result := '';
for Column in Columns.data do begin
//Data type
if Column.AutoIncrement then
dts := 'COUNTER' //special access data type, also known as AUTOINCREMENT
else
case Column.DataType of
DBTYPE_I1: dts := 'TINYINT';
DBTYPE_I2: dts := 'SMALLINT';
DBTYPE_I4: dts := 'INTEGER';
DBTYPE_I8: dts := 'BIGINT';
DBTYPE_UI1: dts := 'BYTE';
DBTYPE_UI2: dts := 'SMALLINT UNSIGNED';
DBTYPE_UI4: dts := 'INTEGER UNSIGNED';
DBTYPE_UI8: dts := 'BIGINT UNSIGNED';
DBTYPE_CY: dts := 'MONEY';
DBTYPE_R4: dts := 'REAL';
DBTYPE_R8: dts := 'FLOAT';
DBTYPE_GUID: dts := 'UNIQUEIDENTIFIER';
DBTYPE_DATE: dts := 'DATETIME';
DBTYPE_NUMERIC,
DBTYPE_DECIMAL: begin
pre := Column.NumericPrecision;
scal := Column.NumericScale;
if not VarIsNil(pre) and not VarIsNil(Scal) then begin
dts := 'DECIMAL('+string(pre)+', '+string(scal)+')';
end else
if not VarIsNil(pre) then begin
dts := 'DECIMAL('+string(pre)+')';
end else
if not VarIsNil(scal) then begin
dts := 'DECIMAL(18, '+string(scal)+')'; //default pre
end else
dts := 'DECIMAL';
end;
DBTYPE_BOOL: dts := 'BIT';
DBTYPE_BYTES:
if Includes(Column.Flags, DBCOLUMNFLAGS_ISLONG) then
dts := 'LONGBINARY'
else
dts := 'BINARY';
DBTYPE_WSTR:
//If you specify TEXT, Access makes LONGTEXT (Memo) field, if TEXT(len) then the usual limited text.
//But we'll go the safe route.
if Includes(Column.Flags, DBCOLUMNFLAGS_ISLONG) then
dts := 'LONGTEXT' //"Memo field"
else begin
if VarIsNil(Column.CharacterMaximumLength) then begin
Warning('Null CHARACTER_MAXIMUM_LENGTH although DBCOLUMNFLAGS_ISLONG '
+'is not set on TEXT field');
tmp := 0;
end;
dts := 'TEXT('+string(Column.CharacterMaximumLength)+')';
end
else
Warning('Unsupported data type '+IntToStr(Column.DataType)+' for column '+Column.Name);
rs.MoveNext();
continue;
end;
//Main
s := '['+Column.Name + '] ' + dts;
if not bool(Column.IsNullable) then
s := s + ' NOT NULL';
if bool(Column.HasDefault) then
if VarIsNil(Column.Default) then
s := s + ' DEFAULT NULL'
else
//Default values do not need to be encoded, they're stored in an encoded way.
//String values are properly escaped and quoted, Function() ones aren't, it's all fine.
s := s + ' DEFAULT ' + str(Column.Default);
//Access does not support comments, therefore we just output them in our propietary format.
//If you use this importer, it'll understand them.
if HandleComments and (Column.Description <> '') then
if PrivateExtensions then
s := s + ' /**COMMENT* '+EncodeComment(Column.Description)+' */'
else
s := s + ' /* '+EncodeComment(Column.Description)+' */';
if Result <> '' then
Result := Result + ','#13#10+s
else
Result := s;
end;
end;
{$REGION 'Indexes'}
type
TIndexColumnDesc = record
Name: UniString;
Collation: integer;
OrdinalPosition: integer;
end;
PIndexColumnDesc = ^TIndexColumnDesc;
TIndexDesc = record
Name: UniString;
PrimaryKey: boolean;
Unique: boolean;
Nulls: integer; //DBPROP_IN_*
Columns: array of TIndexColumnDesc;
_Initialized: boolean; //indicates that the object properties has been set
_Declared: boolean; //set after index has been declared inline [field definition]
function ContainsColumn(ColumnName: UniString): boolean;
function AddColumn(ColumnName: UniString): PIndexColumnDesc;
procedure SortColumns;
end;
PIndexDesc = ^TIndexDesc;
TIndexes = record
data: array of TIndexDesc;
procedure Clear;
function Find(IndexName: UniString): PIndexDesc;
function Get(IndexName: UniString): PIndexDesc;
end;
function TIndexDesc.ContainsColumn(ColumnName: UniString): boolean;
var i: integer;
begin
Result := false;
for i := 0 to Length(Columns) - 1 do
if WideSameText(ColumnName, Columns[i].Name) then begin
Result := true;
break;
end;
end;
function TIndexDesc.AddColumn(ColumnName: UniString): PIndexColumnDesc;
begin
if ContainsColumn(ColumnName) then begin
Result := nil;
exit;
end;
SetLength(Columns, Length(Columns)+1);
Result := @Columns[Length(Columns)-1];
Result.Name := ColumnName;
Result.Collation := 0;
end;
procedure TIndexDesc.SortColumns;
var i, j, k: integer;
tmp: TIndexColumnDesc;
begin
for i := 1 to Length(Columns) - 1 do begin
j := i-1;
while (j >= 0) and (Columns[i].OrdinalPosition < Columns[j].OrdinalPosition) do
Dec(j);
Inc(j);
if j<>i then begin
tmp := Columns[i];
for k := i downto j+1 do
Columns[k] := Columns[k-1];
Columns[j] := tmp;
end;
end;
end;
procedure TIndexes.Clear;
begin
SetLength(data, 0);
end;
function TIndexes.Find(IndexName: UniString): PIndexDesc;
var i: integer;
begin
Result := nil;
for i := 0 to Length(data) - 1 do
if WideSameText(IndexName, data[i].Name) then begin
Result := @data[i];
break;
end;
end;
function TIndexes.Get(IndexName: UniString): PIndexDesc;
begin
Result := Find(IndexName);
if Result<>nil then exit;
SetLength(data, Length(data)+1);
Result := @data[Length(data)-1];
Result^.Name := IndexName;
Result._Initialized := false;
Result._Declared := false;
end;
{$ENDREGION}
{$REGION 'Constraints'}
type
TConstraintDesc = record
Name: UniString;
end;
PConstraintDesc = ^TConstraintDesc;
TConstraints = record
data: array of TConstraintDesc;
procedure Clear;
function Find(ConstraintName: UniString): PConstraintDesc;
procedure Add(ConstraintName: UniString);
end;
procedure TConstraints.Clear;
begin
SetLength(Data, 0);
end;
function TConstraints.Find(ConstraintName: UniString): PConstraintDesc;
var i: integer;
begin
Result := nil;
for i := 0 to Length(data) - 1 do
if WideSameText(ConstraintName, data[i].Name) then begin
Result := @data[i];
break;
end;
end;
procedure TConstraints.Add(ConstraintName: UniString);
var Constraint: PConstraintDesc;
begin
Constraint := Find(ConstraintName);
if Constraint <> nil then exit;
SetLength(data, Length(data)+1);
data[Length(data)-1].Name := ConstraintName;
end;
{$ENDREGION}
//Returns CONSTRAINT list for a given table.
function GetTableIndexes(conn: _Connection; Table: UniString): TIndexes;
var rs: _Recordset;
Index: PIndexDesc;
IndexName: UniString;
Column: PIndexColumnDesc;
Constraints: TConstraints;
begin
//First we read table constraints to filter out those indexes which are constraint-related
rs := conn.OpenSchema(adSchemaTableConstraints,
VarArrayOf([Unassigned, Unassigned, Unassigned, Unassigned,
Unassigned, Table, 'FOREIGN KEY']), EmptyParam);
Constraints.Clear;
while not rs.EOF do begin
Constraints.Add(str(rs.Fields['CONSTRAINT_NAME'].Value));
rs.MoveNext();
end;
//Indexes
rs := conn.OpenSchema(adSchemaIndexes,
VarArrayOf([Unassigned, Unassigned, Unassigned, Unassigned, Table]), EmptyParam);
//Reading data
Result.Clear;
while not rs.EOF do begin
IndexName := str(rs.Fields['INDEX_NAME'].Value);
//Ignore constraint-related indexes
if Constraints.Find(IndexName)<>nil then begin
rs.MoveNext;
continue;
end;
Index := Result.Get(IndexName);
if not Index._Initialized then begin
//Supposedly these values should be the same for all the records belonging to the same index
Index.PrimaryKey := rs.Fields['PRIMARY_KEY'].Value;
Index.Unique := rs.Fields['UNIQUE'].Value;
Index.Nulls := int(rs.Fields['NULLS'].Value);
Index._Initialized := true;
end;
Column := Index.AddColumn(str(rs.Fields['COLUMN_NAME'].Value));
if Column<>nil then begin //wasn't defined yet -- the usual case
Column.Collation := int(rs.Fields['COLLATION'].Value);
Column.OrdinalPosition := int(rs.Fields['ORDINAL_POSITION'].Value);
end;
rs.MoveNext;
end;
end;
//Dumps index creation commands for a given table
procedure DumpIndexes(conn: _Connection; TableName: string);
var Indexes: TIndexes;
Index: PIndexDesc;
i, j: integer;
s, fl, tmp: UniString;
Multiline: boolean;
begin
Indexes := GetTableIndexes(conn, TableName);
for i := 0 to Length(Indexes.data) - 1 do begin
Index := @Indexes.data[i];
Index.SortColumns;
if Index.Unique then
s := 'CREATE UNIQUE INDEX ['
else
s := 'CREATE INDEX [';
s := s + Index.Name + '] ON [' + TableName + ']';
fl := '';
Multiline := false;
for j := 0 to Length(Index.Columns) - 1 do begin
tmp := '['+Index.Columns[j].Name+']';
case Index.Columns[j].Collation of
DB_COLLATION_ASC: tmp := tmp + ' ASC';
DB_COLLATION_DESC: tmp := tmp + ' DESC';
end;
if fl<>'' then begin
fl := fl + ','#13#10 + tmp;
Multiline := true;
end else
fl := tmp;
end;
if Multiline then
s := s + ' ('#13#10 + fl + #13#10 + ')'
else
s := s + ' (' + fl + ')';
if Index.PrimaryKey or (Index.Nulls=DBPROPVAL_IN_DISALLOWNULL)
or (Index.Nulls=DBPROPVAL_IN_IGNORENULL) then begin
s := s + ' WITH';
if Index.PrimaryKey then
s := s + ' PRIMARY';
if Index.Nulls=DBPROPVAL_IN_DISALLOWNULL then
s := s + ' DISALLOW NULL'
else
if Index.Nulls=DBPROPVAL_IN_IGNORENULL then
s := s + ' IGNORE NULL';
end;
s := s + ';';
writeln(s);
end;
end;
//Lowercases a database ID only if IDs are configured as case-insensitive
function LowercaseID(const AId: UniString): UniString;
begin
if CaseInsensitiveIDs then
Result := ToLowercase(AId)
else
Result := AId;
end;
function GetDropCmdSql(const AType, ATableName: string): string;
begin
Result := 'DROP '+AType;
if Supports_IfExists then
Result := Result + ' IF EXISTS';
Result := Result + ' ['+ATableName+']';
if PrivateExtensions then
Result := Result + ' /**WEAK**/';
Result := Result + ';';
end;
//Dumps table creation commands
procedure DumpTables(conn: _Connection);
var rs: _Recordset;
TableName: UniString;
Description: UniString;
begin
rs := conn.OpenSchema(adSchemaTables,
VarArrayOf([Unassigned, Unassigned, Unassigned, 'TABLE']), EmptyParam);
while not rs.EOF do begin
TableName := str(rs.Fields['TABLE_NAME'].Value);
Description := str(rs.Fields['DESCRIPTION'].Value);
if (Length(DumpTableList) > 0) and not Contains(DumpTableList, LowercaseID(TableName)) then begin
rs.MoveNext;
continue;
end;
if DropObjects then
writeln(GetDropCmdSql('TABLE', TableName));