-
Notifications
You must be signed in to change notification settings - Fork 10
/
Copy pathjanSQL.pas
3327 lines (3062 loc) · 84.3 KB
/
janSQL.pas
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
{-----------------------------------------------------------------------------
The contents of this file are subject to the Mozilla Public License Version
1.1 (the "License"); you may not use this file except in compliance with the
License. You may obtain a copy of the License at
http://www.mozilla.org/NPL/NPL-1_1Final.html
Software distributed under the License is distributed on an "AS IS" basis,
WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License for
the specific language governing rights and limitations under the License.
The Original Code is: janSQL.pas, released March 24, 2002.
The Initial Developer of the Original Code is Jan Verhoeven
(jan1.verhoeven@wxs.nl or http://jansfreeware.com).
Portions created by Jan Verhoeven are Copyright (C) 2002 Jan Verhoeven.
All Rights Reserved.
Contributor(s): ___________________.
Last Modified: 22.01.2014
Current Version: 1.2
Notes: This is a very fast single user SQL engine for text based tables
Known Issues:
History:
1.1 25-mar-2002
release recordset in subquery
release sqloutput in selectfromjoin
allow "unlimited" number of tables in join
allow calculated updates: set field=expression
modified TjanSQLRecord: fields are now objects (for future enhancements)
1.0 24-mar-2002 : original release
-----------------------------------------------------------------------------}
//Changes by Rene Tegel
//* Added RollBack method
//* Modified "delete from" to accept "delete from <tablename>" syntax.
{Change log:
05.02.2011: By Zlatko Matić
*In JanSQL.Create method added: DecimalSeparator:=SysUtils.DefaultFormatSettings.DecimalSeparator added,
so that Jansql uses system decimal separator.
26.12.2013: By Zlatko Matić
*.txt replaced with .csv, so that JanSQL now works with .csv extension instead .txt.
}
{$ifdef fpc}
{$mode delphi} {$H+}
{$endif}
unit janSQL;
interface
uses
SysUtils, Classes, Variants,
janSQLStrings, janSQLExpression2, janSQLTokenizer, mwStringHashList;
type
TCompareProc = procedure( Sender : TObject; i, j : Integer; var Result : Integer ) of object ;
TSwapProc = procedure( Sender : TObject; i, j : Integer ) of object ;
TjanSQLOperator=(jsunknown,jseq,jsne,jsgt,jsge,jslt,jsle);
TjanSQLBoolean=(jsnone,jsand,jsor);
TjanSQLSort=record
FieldIndex:integer;
SortAscending:boolean;
SortNumeric:boolean;
end;
TjanSQLJoinIterator=record
TableName:string;
TableAlias:string;
RecordSetIndex:integer;
RecordCount:integer;
CurrentRecord:integer;
end;
TjanSQLCalcField=class(TObject)
private
FCalc:TjanSQLExpression2;
Fexpression: string;
Fname: string;
FFieldIndex: integer;
procedure Setexpression(const Value: string);
procedure Setname(const Value: string);
function getValue: variant;
procedure SetFieldIndex(const Value: integer);
public
constructor create;
destructor destroy;override;
property expression:string read Fexpression write Setexpression;
property name:string read Fname write Setname;
property value:variant read getValue;
property Calculator:TjanSQLExpression2 read FCalc;
property FieldIndex:integer read FFieldIndex write SetFieldIndex;
end;
TjanSQLOutput=class(TObject)
private
FFields:TList;
function getFieldCount: integer;
function getField(index: integer): TjanSQLCalcField;
function getFieldNames: string;
public
constructor create;
destructor destroy;override;
procedure ClearFields;
function AddField:TjanSQLCalcField;
property FieldNames:string read getFieldNames;
property FieldCount:integer read getFieldCount;
property Fields[index:integer]:TjanSQLCalcField read getField;
end;
TjanSQLField=record
FieldName:string;
FieldIndex:integer;
FieldValue:string;
end;
TjanSQLFields=array of TjanSQLField;
TjanSQLRecordField=class(TObject)
private
Fsum: double;
Fsum2: double;
Fcount: integer;
Fvalue: variant;
procedure Setcount(const Value: integer);
procedure Setsum(const Value: double);
procedure Setsum2(const Value: double);
procedure Setvalue(const Value: variant);
published
property value:variant read Fvalue write Setvalue;
property count:integer read Fcount write Setcount;
property sum:double read Fsum write Setsum;
property sum2:double read Fsum2 write Setsum2;
end;
TjanRecord=class(TObject)
private
FFields:TList;
Fmark: boolean;
Fcounter: integer;
function getrow: string;
procedure setrow(const Value: string);
function getfield(index: integer): TjanSQLRecordField;
procedure setfield(index: integer; const Value: string);
procedure Setmark(const Value: boolean);
procedure Setcounter(const Value: integer);
procedure ClearFields;
public
constructor create;
destructor destroy; override;
procedure AddField(value:string);
function DeleteField(index:integer):boolean;
property row:string read getrow write setrow;
property fields[index:integer]:TjanSQLRecordField read getfield;
property mark:boolean read Fmark write Setmark;
property counter:integer read Fcounter write Setcounter;
end;
TjanRecordList=class(TList)
private
public
destructor destroy; override;
procedure Clear; override;
procedure delete(index:integer);
end;
TjanRecordSetList=class(TStringList)
public
destructor destroy; override;
procedure delete(index:integer);override;
end;
TjanRecordSet=class(TObject)
private
FRecordCursor:integer;
Fname: string;
FFieldNames:TStringList;
FFieldFuncs:array of TTokenOperator;
FRecords:TjanRecordList;
Fpersistent: boolean;
Fmodified: boolean;
Fmatchrecord: integer;
Falias: string;
Fintermediate: boolean;
procedure Setname(const Value: string);
function getrecord(index: integer): TjanRecord;
function getfieldvalue(index: variant): string;
procedure setfieldvalue(index: variant; const Value: string);
procedure Setpersistent(const Value: boolean);
function getrecordcount: integer;
procedure Setmodified(const Value: boolean);
function getfieldcount: integer;
procedure Setmatchrecord(const Value: integer);
function getLongFieldList: string;
function getShortFieldList: string;
procedure Setalias(const Value: string);
procedure Setintermediate(const Value: boolean);
public
constructor create;
destructor destroy; override;
function LoadFromFile(filename:string):boolean;
function SaveToFile(filename:string):boolean;
function AddRecord:integer;
function DeleteRecord(index:integer):boolean;
function AddField(fieldname,value:string):integer;
function DeleteField(index:variant):integer;
function IndexOfField(fieldname:string):integer;
function FindFieldValue(fieldindex:integer;fieldvalue:string):integer;
procedure Clear;
property Cursor: Integer read FRecordCursor write FRecordCursor;
property name:string read Fname write Setname;
property alias:string read Falias write Setalias;
property persistent:boolean read Fpersistent write Setpersistent;
property intermediate:boolean read Fintermediate write Setintermediate;
property modified:boolean read Fmodified write Setmodified;
property FieldNames:TStringList read FFieldNames;
property ShortFieldList:string read getShortFieldList;
property LongFieldList:string read getLongFieldList;
property records[index:integer]:TjanRecord read getrecord;
property fields[index:variant]:string read getfieldvalue write setfieldvalue;
property recordcount:integer read getrecordcount;
property fieldcount:integer read getfieldcount;
property matchrecord:integer read Fmatchrecord write Setmatchrecord;
end;
TjanSQL=class;
TjanSQLQuery=class(TObject)
private
FTokens:TList;
FParser:TjanSQLExpression2;
FEngine: TjanSQL;
procedure SetEngine(const Value: TjanSQL);
procedure ClearTokenList;
function GetToken(index: integer): TToken;
function getParser: TjanSQLExpression2;
protected
public
constructor create;
destructor destroy;override;
property Engine:TjanSQL read FEngine write SetEngine;
property Tokens[index:integer]:TToken read GetToken;
property Parser:TjanSQLExpression2 read getParser;
end;
TjanSQL = class(TObject)
private
FQueries:TList;
gen:TStringList;
FSQL:TstringList;
FEparser:TjanSQLExpression2;
FNameSpace:TmwStringHashList;
FNameCounter:integer;
Fcatalog: string;
FInMemoryDatabase: Boolean;
FRecordSets:TjanRecordSetList;
FMatchrecordSet: integer;
FMatchingHaving: boolean;
function getrecordset(index: integer): TjanRecordSet;
function getRecordSetCount: integer;
procedure getvariable(sender:Tobject;const VariableName:string;var VariableValue:variant;var handled:boolean);
procedure procsubexpression(sender:Tobject;const subexpression:string;var subexpressionValue:variant;var handled:boolean);
function SQLDirectStatement(query:TjanSQLQuery;value: string): integer;
procedure Sort(aRecordset,From, Count : Integer;orderby:array of TjanSQLSort);
procedure SortRecordSet(arecordset,From, Count : Integer;orderbylist:string;ascending:boolean);
procedure GroupBy(arecordset:TjanRecordset;grouplist:string);
function Compare(arecordset,i, j : Integer;orderby:array of TjanSQLSort): Integer;
procedure Swap(arecordset,i,j:Integer);
procedure ClearQueries;
function ISQL(value:string):integer;
function uniqueName:string;
function addRecordSet(aname:string):integer;
function CreateTable(tablename,fields:string):integer;
function DropTable(tablename:string):integer;
function SaveTable(tablename:string):integer;
function ReleaseTable(tablename:string):integer;
function AddTableColumn(tablename,column,value:string):integer;
function DropTableColumn(tablename,column:string):integer;
function IndexOfTable(tablename:string):integer;
function openTable(value:string;persistent:boolean):boolean;
function InCatalog(value:string):boolean;
function openCatalog(value:string):integer;
function SelectFromJoin(query:TjanSQLQuery;selectfields,tablelist,wherecondition,orderbylist:string;ascending:boolean;wfrom,wtill:integer;grouplist,having,resultname:string):integer;
function SelectFrom(query:TjanSQLQuery;tablename1,selectfields,wherecondition,orderbylist:string;ascending:boolean;wfrom,wtill:integer;grouplist,having,resultname:string):integer;
function DeleteFrom(tablename1,wherecondition:string):integer;
function InsertInto(tablename1,columns,values:string):integer;
function Update(query:TjanSQLQuery;tablename1,updatelist,wherecondition:string):integer;
function Commit(query:TjanSQLQuery):integer;
function RollBack(query:TjanSQLQuery):integer;
function AddQuery:TjanSQLQuery;
function DeleteQuery(query:TjanSQLQuery):boolean;
{ Private declarations }
protected
{ Protected declarations }
function SQLSelect(query:TjanSQLQuery;aline,aname:string):integer;
function SQLAssign(query:TjanSQLQuery;aline:string):integer;
function SQLDelete(query:TjanSQLQuery;aline:string):integer;
function SQLInsert(query:TjanSQLQuery;aline:string):integer;
function SQLInsertSelect(query:TjanSQLQuery;aline:string):integer;
function SQLUpdate(query:TjanSQLQuery;aline:string):integer;
function SQLCreate(query:TjanSQLQuery;aline:string):integer;
function SQLDrop(query:TjanSQLQuery;aline:string):integer;
function SQLSaveTable(query:TjanSQLQuery;aline:string):integer;
function SQLReleaseTable(query:TjanSQLQuery;aline:string):integer;
function SQLAlter(query:TjanSQLQuery;aline:string):integer;
function SQLCommit(query:TjanSQLQuery;aline:string):integer;
function SQLRollBack(query:TjanSQLQuery;aline:string):integer;
function SQLConnect(query:TjanSQLQuery;aline:string):integer;
public
{ Public declarations }
constructor create;
destructor destroy; override;
function SQLDirect(value:string):integer;
function ReleaseRecordset(arecordset:integer):boolean;
function Error:string;
property RecordSets[index:integer]:TjanRecordSet read getrecordset;
property RecordSetCount:integer read getRecordSetCount;
property NameSpace:TmwStringHashList read FNameSpace;
published
{ Published declarations }
end;
implementation
const
cr = #13#10; //// cr = chr(13)+chr(10);
var
FError: string;
//FDebug: string;
procedure err(value:string);
begin
Ferror:=value;
end;
procedure chop(var value:string;from:integer);
begin
value:=trim(copy(value,from,maxint));
end;
{soner never used
function tokeninset(token,aset:string):boolean;
begin
end;}
function parsetoken(const source:string;var token:string;var delimpos:integer;var delim:string):boolean;
var
p,L:integer;
begin
result:=false;
L:=length(source);
if L=0 then exit;
p:=1;
while (p<=L) and (not (source[p] in [',',' ',';','=','<','>','(',')'])) do
inc(p);
if p>L then begin
token:=source;
delim:='';
delimpos:=0;
end
else begin
token:=copy(source,1,p-1);
delim:=copy(source,p,1);
delimpos:=p;
end;
result:=true;
end;
function checktoken(source,token:string;var delimpos:integer;var delim:string):boolean;
var
p,LS,LT:integer;
begin
result:=false;
p:=postext(token,source);
if p<>1 then exit;
LS:=length(source);
LT:=length(token);
if LS=LT then begin
delim:='';
delimpos:=0;
result:=true;
exit;
end;
if not (source[LT+1] in [' ',',',';','=','<','>']) then exit;
result:=true;
delim:=source[LT+1];
delimpos:=LT+1;
end;
function string2operator(value:string):TjanSQLOperator;
begin
result:=jsunknown;
if value='=' then
result:=jseq
else if value='<>' then
result:=jsne
else if value='>' then
result:=jsgt
else if value='>=' then
result:=jsge
else if value='<' then
result:=jslt
else if value='<+' then
result:=jsle;
end;
// split atext at ; into lines
procedure split(atext:string;alist:TStrings);
//make semicosumn not holy, allow it in quoted values (rene):
function posskipquoted (sep: char; text: String; offset: Integer): Integer;
var quoted: char;
begin
result := 0;
quoted := #0;
while offset <= length(text) do
begin
if (quoted=#0) and (text[offset]=sep) then
begin
Result := offset;
break;
end;
//Detect end of quoted values
if (quoted <> #0) and (text[offset]=quoted) then
begin
quoted := #0;
inc (offset); //Dak_Alpha
Continue; //Dak_Alpha
end;
//Detect begin of quoted values
if (quoted=#0) and (text[offset] in ['''', '"', '`']) then
quoted := text[offset];
if text[offset] = PathDelim then
//additional step
inc(offset);
inc (offset);
end;
end;
var
tmp:string;
p1,p2,L:integer;
begin
alist.Clear;
L:=length(atext);
if L=0 then exit;
p1:=1;
repeat
//p2:=PosStr(';',atext,p1);
p2 := posskipquoted(';', atext, p1);
if p2>0 then begin
tmp:=copy(atext,p1,p2-p1);
alist.Append(tmp);
if p2=L then
alist.append('');
p1:=p2+1;
if p1>L then
p1:=0;
end
else begin
alist.append(copy(atext,p1,maxint));
p1:=0;
end;
until p1=0;
end;
function join(alist:TStrings):string;
var
i,c:integer;
begin
result:='';
c:=alist.count;
if c=0 then exit;
for i:=0 to c-1 do
if i=0 then
result:=alist[i]
else
result := result + ';' + alist[i];
end;
{ TjanSQL }
function TjanSQL.addRecordSet(aname: string): integer;
var
rs:TjanRecordSet;
begin
rs:=TjanRecordSet.create;
rs.name:=aname;
result:=FRecordSets.AddObject(aname,rs)+1;
end;
constructor TjanSQL.create;
begin
inherited;
{ TODO : This should be completely removed. jansql should behave
{ as rest of zmsql package... }
//Set decimal separator.
DecimalSeparator:='.'; //This was original value.
// DecimalSeparator:=SysUtils.DefaultFormatSettings.DecimalSeparator // by Z.Matić.
FQueries:=TList.create;
gen:=TStringList.create;
FSQL:=TStringList.create;
FNameSpace:=TmwStringHashList.create(tinyhash,HashSecondaryOne,HashCompare);
FEParser:=TjanSQLExpression2.create;
FEParser.onGetVariable:=getvariable;
FrecordSets:=TjanRecordSetList.Create;
end;
destructor TjanSQL.destroy;
begin
ClearQueries;
FQueries.free;
gen.free;
FSQL.free;
FEParser.free;
FrecordSets.free;
FNameSpace.free;
inherited;
end;
// join 2 tables on fields in fieldset
// return index of resultset
// result -1 means failure
// fieldset has format field1=field2;field3=field3
function TjanSQL.getrecordset(index: integer): TjanRecordSet;
// 1 based
begin
result:=nil;
if (index<1) or (index>Frecordsets.Count) then exit;
result:=TjanRecordset(FRecordsets.objects[index-1]);
end;
// joinfields are of format field1=field2;field3=field4
// all fields must be in table.field format
function TjanSQL.selectFromJoin(query:TjanSQLQuery;selectfields,tablelist,wherecondition,orderbylist:string;ascending:boolean;wfrom,wtill:integer;grouplist,having,resultname:string):integer;
var
t1,t2,t3:integer;
i,c,i3,c3:integer;
idx:integer;
bAggregate:boolean;
selectfieldfunctions:array of TTokenOperator;
tablecount, outputfieldcount:integer;
sqloutput:TjanSQLOutput;
tables:array of TjanSQLJoinIterator;
function setgroupfunc(avalue:string;ii:integer):string;
var
ppo,ppc:integer;
sfun:string;
begin
selectfieldfunctions[ii]:=toNone;
result:=avalue;
ppo:=posstr('(',avalue);
if ppo>0 then begin
ppc:=posstr(')',avalue,ppo);
if ppc=0 then exit;
sfun:=lowercase(trim(copy(avalue,1,ppo-1)));
result:=copy(avalue,ppo+1,ppc-ppo-1);
if sfun='count' then begin
selectfieldfunctions[ii]:=tosqlCount;
bAggregate:=true;
end
else if sfun='sum' then begin
selectfieldfunctions[ii]:=tosqlSum;
bAggregate:=true;
end
else if sfun='avg' then begin
selectfieldfunctions[ii]:=tosqlAvg;
bAggregate:=true;
end
else if sfun='max' then begin
selectfieldfunctions[ii]:=tosqlMax;
bAggregate:=true;
end
else if sfun='min' then begin
selectfieldfunctions[ii]:=tosqlMin;
bAggregate:=true;
end
else
result:=avalue;
end;
end;
function setoutputfields:boolean;
var
ii,cc:integer;
ofld:TjanSQLCalcField;
ppa:integer;
sfield,prefield:string;
begin
result:=false;
split(selectfields,gen);
cc:=gen.count;
outputfieldcount:=cc;
setlength(selectfieldfunctions,cc);
sqloutput:=TjanSQLOutput.create;
for ii:=0 to cc-1 do begin
ofld:=sqloutput.AddField;
ofld.Calculator.onGetVariable:=GetVariable;
sfield:=gen[ii];
ppa:=pos('|',sfield);
if ppa>0 then begin
prefield:=copy(sfield,1,ppa-1);
prefield:=setgroupfunc(prefield,ii);
ofld.name:=copy(sfield,ppa+1,maxint);
try
ofld.expression:=prefield;
except
exit;
end;
end
else begin
ofld.name:=setgroupfunc(sfield,ii);
try
ofld.expression:=sfield;
except
exit;
end;
end;
end;
result:=true;
end;
procedure addresultoutput(r1,r2:integer);
var
ii,cc,ir:integer;
ss:string;
v:variant;
begin
ir:=recordsets[t3].AddRecord;
cc:=sqloutput.FieldCount;
FMatchrecordSet:=t1;
recordsets[t1].matchrecord:=r1;
recordsets[t2].matchrecord:=r2;
for ii:=0 to cc-1 do begin
v:=sqloutput.Fields[ii].value;
ss:=v;
recordsets[t3].records[ir].fields[ii].value:=ss;
end;
end;
procedure addResultOutputEx;
var
ii,cc,ir: integer;
ss: string;
v: variant;
begin
ir:=recordsets[t3].AddRecord;
cc:=sqloutput.FieldCount;
FMatchrecordSet:=t1;
for ii:=0 to tablecount-1 do
recordsets[tables[ii].RecordSetIndex].matchrecord:=tables[ii].CurrentRecord;
for ii:=0 to cc-1 do begin
v:=sqloutput.Fields[ii].value;
ss:=v;
recordsets[t3].records[ir].fields[ii].value:=ss;
end;
end;
function matchrecords(r1,r2:integer):boolean;
begin
recordsets[t1].matchrecord:=r1;
recordsets[t2].matchrecord:=r2;
result:=query.parser.Evaluate;
end;
function matchrecordsEx:boolean;
var
ii:integer;
begin
for ii:=0 to tablecount-1 do
recordsets[tables[ii].RecordSetIndex].matchrecord:=tables[ii].CurrentRecord;
result:=query.parser.Evaluate;
end;
function matchhaving(arecord:integer):boolean;
begin
recordsets[t3].matchrecord:=arecord;
result:=query.Parser.evaluate;
end;
function expandall:string;
begin
result:=recordsets[t1].LongFieldList+';'+recordsets[t2].LongFieldList;
end;
function settables:boolean; // JV 25-03-2002
// added alias option JV 27-03-2002
var
ii,tii,rrc,pp:integer;
atom, atomalias:string;
begin
result:=false;
setlength(tables,tablecount);
for ii:=0 to tablecount-1 do begin
atom:=gen[ii];
pp:=pos('|',atom);
if pp=0 then
atomalias:=atom
else begin
atomalias:=copy(atom,pp+1,maxint);
atom:=copy(atom,1,pp-1);
end;
tii:=indexoftable(atom);
if tii=-1 then begin
err('SELECT: can not find table '+atom); //soner moved here
exit;
end;
rrc:=recordsets[tii].recordcount;
if rrc=0 then begin
err('SELECT: table '+atom+' has no records'); //soner moved here
exit;
end;
recordsets[tii].alias:=atomalias;
tables[ii].TableName:=atom;
tables[ii].TableAlias:=atomalias;
NameSpace.AddString(atom,tii,0);
NameSpace.AddString(atomalias,tii,0);
tables[ii].RecordSetIndex:=tii;
tables[ii].CurrentRecord:=0;
tables[ii].RecordCount:=rrc;
end;
result:=true;
end;
procedure matchtables(t:integer);
var
ii:integer;
begin
if t=tablecount-1 then
for ii:=0 to tables[t].RecordCount-1 do begin
tables[t].CurrentRecord:=ii;
if matchrecordsEx then begin
addresultoutputEx;
end;
end
else
for ii:=0 to tables[t].RecordCount-1 do begin
tables[t].CurrentRecord:=ii;
matchtables(t+1);
end;
end;
begin
result:=0;
Fmatchinghaving:=false;
bAggregate:=False; //fixed for FPC theo
split(tablelist,gen);
//soner: err('SELECT: join table missing');
tablecount:=gen.count;
{soner original:
if tablecount<2 then exit;
if not settables then exit;
}
if (tablecount<2)or(not settables) then begin
err('SELECT: join table missing');
exit;
end;
if selectfields='' then begin
err('SELECT: missing field list'); //soner moved here
exit;
end;
if selectfields='*' then selectfields:=expandall;
{new code}
if not setoutputfields then begin
sqloutput.free;
err('SELECT dev: can not set output fields'); //soner moved here
exit;
end;
// join fields are present, now join
if resultname<>'' then begin
// check if this is a persistent table
if InCatalog(resultname) then begin
sqloutput.free;
err('SELECT INTO: table '+resultname+' allready exists.'); //soner moved here
exit;
end;
// check index
idx:=Frecordsets.IndexOf(resultname);
if idx=-1 then begin
t3:=AddRecordSet(resultname);
Recordsets[t3].intermediate:=true;
end
else begin
// check if this is a intermediate one
if recordsets[idx+1].intermediate then begin
FRecordsets.delete(idx);
t3:=AddRecordSet(resultname);
Recordsets[t3].intermediate:=true;
end
else begin
err('ASSIGN: table '+resultname+' is not a variable');
sqloutput.free;
exit;
end;
end;
end
else
t3:=AddRecordSet(uniquename);
result:=t3;
// assign selectfields
split(sqloutput.FieldNames, recordsets[t3].FieldNames);
// copy field funcs
c:=recordsets[t3].FieldNames.Count;
setlength(recordsets[t3].FFieldFuncs,c);
for i:=0 to c-1 do
recordsets[t3].FFieldFuncs[i]:=selectfieldfunctions[i];
if wfrom<>0 then begin
query.Parser.GetTokenList(query.Ftokens,wfrom,wtill);
end;
matchtables(0);
// process any group by clause
if bAggregate and (recordsets[t3].recordcount>1) then
groupby(recordsets[t3],grouplist);
FMatchrecordSet:=t3;
Fmatchinghaving:=true;
c3:=recordsets[t3].recordcount;
// process any having clause
if (having<>'') and (c3<>0) then begin
query.Parser.Expression:=having;
for i3:=0 to c3-1 do
recordsets[t3].records[i3].mark:=false;
for i3:=0 to c3-1 do
if not matchhaving(i3) then
recordsets[t3].records[i3].mark:=true;
for i3:=c3-1 downto 0 do
if recordsets[t3].records[i3].mark then
recordsets[t3].DeleteRecord(i3);
end;
// process any order by clause
if (orderbylist<>'') and (recordsets[t3].recordcount>1) then
sortRecordset(t3,0,recordsets[t3].recordcount,orderbylist,ascending);
sqloutput.free; // JV 25-03-2002
end;
function TjanSQL.openCatalog(value: string): integer;
begin
result:=0;
FInMemoryDatabase := trim(lowercase(value))=':memory:';
if not (FInMemoryDatabase or directoryexists(value)) then begin
err('Catalog '+value+' does not exist'); //soner moved here
exit;
end;
FCatalog:=value;
result:=-1;
end;
function TjanSQL.openTable(value: string;persistent:boolean): boolean;
var
fn:string;
rs:TjanRecordSet;
begin
result:=false;
if FInMemoryDatabase then //override
persistent := false;
if persistent then
if not directoryexists(FCatalog) then exit;
if FRecordSets.IndexOf(value)<>-1 then exit;
{fn:=Fcatalog+PathDelim+value+'.txt';}
fn:=Fcatalog+PathDelim+value+'.csv'; //Changed by Zlatko Matić, 26.12.2003
if persistent then
if not fileexists(fn) then exit;
rs:=TjanRecordSet.create;
rs.name:=value;
rs.persistent:=persistent;
FRecordSets.AddObject(value,rs);
if persistent then result:=rs.LoadFromFile(fn);
end;
function TjanSQL.uniqueName: string;
begin
result:='$$$'+inttostr(FNameCounter);
inc(FNameCounter);
end;
function TjanSQL.SelectFrom(query:TjanSQLQuery;tablename1, selectfields,
wherecondition,orderbylist: string;ascending:boolean;wfrom,wtill:integer;grouplist,having,resultname:string): integer;
var
t1,t3:integer;
i,c,i1,c1,i3,c3:integer;
idx:integer;
outputfieldcount:integer;
selectfieldfunctions:array of TTokenOperator;
bAggregate:boolean;
sqloutput:TjanSQLOutput;
function setgroupfunc(avalue:string;ii:integer):string;
var
ppo,ppc:integer;
sfun:string;
begin
result:=avalue;
selectfieldfunctions[ii]:=toNone;
ppo:=posstr('(',avalue);
if ppo>0 then begin
ppc:=posstr(')',avalue,ppo);
if ppc=0 then exit;
sfun:=lowercase(trim(copy(avalue,1,ppo-1)));
result:=copy(avalue,ppo+1,ppc-ppo-1);
if sfun='count' then begin
selectfieldfunctions[ii]:=tosqlCount;
bAggregate:=true;
end
else if sfun='sum' then begin
selectfieldfunctions[ii]:=tosqlSum;
bAggregate:=true;
end
else if sfun='avg' then begin
selectfieldfunctions[ii]:=tosqlAvg;
bAggregate:=true;
end
else if sfun='max' then begin
selectfieldfunctions[ii]:=tosqlMax;
bAggregate:=true;
end
else if sfun='min' then begin
selectfieldfunctions[ii]:=tosqlMin;
bAggregate:=true;
end
else if sfun='stddev' then begin
selectfieldfunctions[ii]:=tosqlStdDev;
bAggregate:=true;
end
else
result:=avalue;
end;
end;
function setoutputfields:boolean;
var
ii,cc:integer;
ofld:TjanSQLCalcField;
ppa:integer;
sfield,prefield:string;
begin
result:=false;
split(selectfields,gen);
cc:=gen.count;
outputfieldcount:=cc;
setlength(selectfieldfunctions,cc);
sqloutput:=TjanSQLOutput.create;
for ii:=0 to cc-1 do begin
ofld:=sqloutput.AddField;
ofld.Calculator.onGetVariable:=GetVariable;
sfield:=gen[ii];
ppa:=pos('|',sfield);
if ppa>0 then begin
prefield:=copy(sfield,1,ppa-1);
prefield:=setgroupfunc(prefield,ii);
ofld.name:=copy(sfield,ppa+1,maxint);
try
ofld.expression:=prefield;
except
exit;
end;
end
else begin
ofld.name:=setgroupfunc(sfield,ii);
try
ofld.expression:=sfield;
except
exit;
end;
end;
end;
result:=true;
end;
function matchwhere(arecord:integer):boolean;