forked from DanielaSe/Delphi-EasyLINQ
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathEasyLinq.pas
1579 lines (1342 loc) · 47.3 KB
/
EasyLinq.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
(**************************************************************************************************)
(*
(* Copyright (c) 2010-2014 Daniela Sefzig
(*
(* Description A generic list which is able to execute basic SQL commands similar to Linq
(* Filename EasyLINQ.pas
(* Version v1.41
(* Date 04.Sep.2014
(* Project EasyLINQ
(* Info / Help contact author at daniela.sefzig(a)alien.at
(* Support contact author at daniela.sefzig(a)alien.at
(*
(* License MPL v1.1 , GPL v3.0 or LGPL v3.0
(*
(* Mozilla Public License (MPL) v1.1
(* GNU General Public License (GPL) v3.0
(* GNU Lesser General Public License (LGPL) v3.0
(*
(* 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/MPL .
(*
(* 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 "EasyLINQ.pas".
(*
(* The Initial Developer of the Original Code is "Daniela Sefzig".
(* Portions created by Initial Developer are Copyright (C) 2011.
(* All Rights Reserved.
(*
(* Contributor(s): -
(*
(* Alternatively, the contents of this file may be used under the terms
(* of the GNU General Public License Version 3.0 or later (the "GPL"), or the
(* GNU Lesser General Public License Version 3.0 or later (the "LGPL"),
(* in which case the provisions of GPL or the LGPL are applicable instead of
(* those above. If you wish to allow use of your version of this file only
(* under the terms of the GPL or the LGPL and not to allow others to use
(* your version of this file under the MPL, indicate your decision by
(* deleting the provisions above and replace them with the notice and
(* other provisions required by the GPL or the LGPL. If you do not delete
(* the provisions above, a recipient may use your version of this file
(* under either the MPL, the GPL or the LGPL.
(*
(*
(*
(* HTML: PlainText:
(* www.mozilla.org/MPL/MPL-1.1.html www.mozilla.org/MPL/MPL-1.1.txt
(* www.gnu.org/licenses/gpl-3.0.html www.gnu.org/licenses/gpl-3.0.txt
(* www.gnu.org/licenses/lgpl-3.0.html www.gnu.org/licenses/lgpl-3.0.txt
(*
(*
(*
(*
(* Supported commands:
(*
(* SELECT Optional
(* DISTINCT Fieldname Genereates groups
(* TOP(x) Returns only the first x objects
(* CALC(x) calculates an expression, supports:
(* -+/*^() sin cos tan sqr log cot sec csc
(* WHERE (...) AND/OR/XOR (...) Filter, combine with AND, OR, XOR
(* UPPER(field), LOWER(field), LIKE %x%
(* GROUP BY field1, field2... same as distinct
(* ORDER BY field1, field2,... sort order
(* DESC, ASC
(*
(* UPDATE SET (x = x, x = x) update, writes new values into the fields
(* UPDATE SET (x=CALC(x))
(*
(*
(* History:
(* v1.1 | 6.Sep.2011
(* - Added CALC command
(* v1.2 | 12.Sep.2011
(* - parser (gettoken, wherecmd) changed
(* - second "where" parameter can be a field
(* - supports subclasses
(* - UPDATE command added, second parameter can be a calculated field
(* v1.2b | 13.Sep.2011
(* - some minor bug fixes
(* - support records in classes and records
(* v1.3 | 29.Jan.2013
(* - kompatible with Delphi XE3
(* - 64Bit kompatible
(* - "Where" function added
(* - "OrderBy" function added
(* - "Distinct" function added
(* - "Move" function added
(* v1.4 | 14.Aug.2014
(* - tested with Delphi XE6 (Not on mac compiler)
(* - Element Operators: First, Last
(* - Custom Sequence Operators: Combine
(* - Partitioning Operators: Take, Skip, Odd, Even
(* - Generation Operators: Range, Repeat
(* - Aggregate Operators: Aggregate, Average, Min, Max, Sum
(* v1.41 | 4.Sep.2014
(* - Bug in GetCMD with delete characters of like command (thanks to Bruno)
(*
(*
(**************************************************************************************************)
unit EasyLINQ;
interface
uses Windows, Classes, Generics.Defaults, Generics.Collections, Rtti,
Calculator, TypInfo, RTLConsts, SysUtils;
{$TYPEINFO ON}
{$M+}
{$i EasyLINQ.inc}
type
ELinQException = class(Exception);
(*** lässt sich Aufgrund eines Internen Fehlers bei < XE2 nicht in die Klasse verschieben ***)
{$ifndef DELPHI_XE2}
TTokenTpye = (ttField, ttString, ttConst );
TCombine = ( _AND, _OR, _XOR );
TCharCase = (ccDefault, ccToUpper, ccToLower);
TCommandMode = (wmIS, wmLess, wmUpper, wmIsLess, wmIsUpper, wmIsNot, wmLike );
{$endif}
TEasyLINQ<T> = class(TEnumerable<T>)
type
{$ifdef DELPHI_XE2}
TTokenTpye = (ttField, ttString, ttConst, ttCalculation );
TCombine = ( _AND, _OR, _XOR );
TCharCase = (ccDefault, ccToUpper, ccToLower);
TCommandMode = (wmIS, wmLess, wmUpper, wmIsLess, wmIsUpper, wmIsNot, wmLike );
{$endif}
TFieldInfo = record
Exists : Boolean;
TypeInfo : TRttiType;
Value : TValue;
TypeKind : TTypeKind;
FieldName : String;
end;
TWhereCMD = record
Field : String;
Value : String;
Mode : TCommandMode;
TypeKind : TTypeKind;
Combine : TCombine;
CharCase : TCharCase;
Field2 : String;
TypeKind2 : TTypeKind;
end;
TSortIndex = record
obj : TObject;
value : String;
end;
const
StopAt : TSysCharSet = ['<', '>', '=', ' ', '(', ')'];
private
fSortOrderDesc : Boolean;
fCalculator : TCalculator;
fLookupTable : Boolean;
fContext : TRttiContext;
fTypeInfo : TRttiType;
fItems : TList<T>;
fOnNotify : TCollectionNotifyEvent<T>;
function GetItem(Index: Integer): T;
procedure SetItem(Index: Integer; const Value: T);
function GetCount: Integer;
function Compare(const L, R: T; prop: String): integer;
function UnquoteStr( str: String ): String;
function GetCMD(var txt: String; fTypeInfo: TRttiType): TWhereCMD;
function IsValid(item: T; cmd: TWhereCMD): Boolean;
function GetToken(var str: String): String;
procedure DoDistinct( FieldNames: String );
procedure ExecOrderBy( const FieldNames: String );
procedure ExecUpdate( const Commands: String );
procedure GetFieldValue( FieldName: String; var Value: Double );
procedure Calculate( txt: String );
function GetValue( item: Pointer; FieldName: String ): TValue;
procedure SetValue( const item: Pointer; FieldName: String; Value: Variant );
function GetFieldInfo( item: Pointer; FieldName: String ): TFieldInfo;
function GetTypOfToken( str: String ): TTokenTpye;
protected
function DoGetEnumerator: TEnumerator<T>; override;
procedure Notify(const Item: T; Action: TCollectionNotification); virtual;
public
constructor Create( LookupTable: Boolean = False );
destructor Destroy; override;
function Add( const Value: T ): Integer;
procedure Remove( index :Integer );
function Insert( index :Integer; const Value: T ): Integer;
procedure Move(CurIndex, NewIndex: Integer);
procedure Clear;
function Execute( command: String ): TEasyLINQ<T>;
function Where( command: String ): TEasyLINQ<T>;
function OrderBy( field: String ): TEasyLINQ<T>;
function Distinct( field: String ): TStringList;
(* Element Operators *)
property Items[Index: Integer]: T read GetItem write SetItem; default;
function First: T;
function Last: T;
(* Custom Sequence Operators *)
function Combine( source: TEasyLINQ<T> ): TEasyLINQ<T>;
(* Partitioning Operators *)
function Take( n: Integer ): TEasyLINQ<T>;
function Skip( n: Integer ): TEasyLINQ<T>;
function Odd: TEasyLINQ<T>;
function Even: TEasyLINQ<T>;
(* Generation Operators *)
function Range( fromIndex, toIndex: Integer ): TEasyLINQ<T>;
function &Repeat( Index, n: Integer ): TEasyLINQ<T>;
(* Aggregate Operators *)
function Aggregate( field: String ): Extended;
function Average( field: String ): Extended;
function Max( field: String ): Extended;
function Min( field: String ): Extended;
function Sum( field: String ): Extended;
type
TEnumerator = class(TEnumerator<T>)
private
FList: TEasyLINQ<T>;
FIndex: Integer;
function GetCurrent: T;
protected
function DoGetCurrent: T; override;
function DoMoveNext: Boolean; override;
public
constructor Create(AList: TEasyLINQ<T>);
property Current: T read GetCurrent;
function MoveNext: Boolean;
end;
function GetEnumerator: TEnumerator; reintroduce;
published
property Count: Integer read GetCount;
property IsLookupTable: Boolean read fLookupTable;
end;
implementation
uses Dialogs, Controls, math, StrUtils;
{$region '----> constructor / destructor'}
(**************************************************************************************************)
(* Create
(*
(**************************************************************************************************)
constructor TEasyLINQ<T>.Create( LookupTable: Boolean = False );
begin
fLookupTable := LookupTable;
fCalculator := TCalculator.Create;
fCalculator.OnCalculatorGetFieldValue := GetFieldValue;
fItems := TList<T>.Create;
fContext := TRttiContext.Create;
fTypeInfo := fContext.GetType( System.TypeInfo(T) );
end;
(**************************************************************************************************)
(* Destroy
(*
(**************************************************************************************************)
destructor TEasyLINQ<T>.Destroy;
begin
Clear;
fItems.Free;
fItems := nil;
fCalculator.Free;
inherited;
end;
{$endregion}
{$region '----> Enumerator'}
function TEasyLINQ<T>.GetEnumerator: TEnumerator;
begin
Result := TEnumerator.Create(Self);
end;
function TEasyLINQ<T>.DoGetEnumerator: TEnumerator<T>;
begin
Result := GetEnumerator;
end;
constructor TEasyLINQ<T>.TEnumerator.Create(AList: TEasyLINQ<T>);
begin
inherited Create;
fList := AList;
fIndex := -1;
end;
function TEasyLINQ<T>.TEnumerator.DoGetCurrent: T;
begin
Result := GetCurrent;
end;
function TEasyLINQ<T>.TEnumerator.DoMoveNext: Boolean;
begin
Result := MoveNext;
end;
function TEasyLINQ<T>.TEnumerator.GetCurrent: T;
begin
Result := fList[fIndex];
end;
function TEasyLINQ<T>.TEnumerator.MoveNext: Boolean;
begin
if fIndex >= fList.Count then
Exit(False);
Inc(fIndex);
Result := fIndex < fList.Count;
end;
{$endregion}
{$region '----> default list operations'}
(**************************************************************************************************)
(* Remove
(*
(**************************************************************************************************)
procedure TEasyLINQ<T>.Remove( index :Integer );
var
item : T;
begin
if (index < 0) or (index > Count) then
raise EArgumentOutOfRangeException.CreateRes(@SArgumentOutOfRange);
if (not fLookupTable) and (fTypeInfo.TypeKind = tkClass) then begin
item := fItems[index];
FreeAndNil( item );
end;
fItems.Delete( index );
end;
(**************************************************************************************************)
(* Add
(*
(**************************************************************************************************)
function TEasyLINQ<T>.Add( const Value: T ): Integer;
begin
Result := fItems.Add( Value );
end;
(**************************************************************************************************)
(* Move
(*
(**************************************************************************************************)
procedure TEasyLINQ<T>.Move(CurIndex, NewIndex: Integer);
begin
fItems.Move( CurIndex, NewIndex );
end;
(**************************************************************************************************)
(* Insert
(*
(**************************************************************************************************)
function TEasyLINQ<T>.Insert(index: Integer; const Value: T): Integer;
begin
if (index < 0) or (index > Count) then
raise EArgumentOutOfRangeException.CreateRes(@SArgumentOutOfRange);
fItems.Insert( index, value );
end;
(**************************************************************************************************)
(* GetCount
(*
(**************************************************************************************************)
function TEasyLINQ<T>.GetCount: Integer;
begin
Result := fItems.Count;
end;
(**************************************************************************************************)
(* GetItem
(*
(**************************************************************************************************)
function TEasyLINQ<T>.GetItem(index: Integer): T;
begin
if (index < 0) or (index >= Count) then
raise EArgumentOutOfRangeException.CreateRes(@SArgumentOutOfRange);
Result := fItems[index]
end;
(**************************************************************************************************)
(* Notify
(*
(**************************************************************************************************)
procedure TEasyLINQ<T>.Notify(const Item: T; Action: TCollectionNotification);
begin
if Assigned(fOnNotify) then
fOnNotify(Self, Item, Action);
end;
(**************************************************************************************************)
(* SetItem
(*
(**************************************************************************************************)
procedure TEasyLINQ<T>.SetItem(Index: Integer; const Value: T);
var
oldItem: T;
begin
if (index < 0) or (index >= Count) then
raise EArgumentOutOfRangeException.CreateRes(@SArgumentOutOfRange);
oldItem := fItems[Index];
fItems[Index] := Value;
Notify(oldItem, cnRemoved);
Notify(Value, cnAdded);
end;
(**************************************************************************************************)
(* Clear
(*
(**************************************************************************************************)
procedure TEasyLINQ<T>.Clear;
var
item : T;
i : Integer;
begin
if (not fLookupTable) and (fTypeInfo.TypeKind = tkClass) then
for i := 0 to fItems.Count - 1 do begin
item := fItems[i];
FreeAndNil( item );
end;
fItems.Clear;
end;
{$endregion}
{$region '----> Functions'}
(**************************************************************************************************)
(* GetFieldInfo
(* Returns the Field Informations
(**************************************************************************************************)
function TEasyLINQ<T>.GetFieldInfo( item: Pointer; FieldName: String ): TFieldInfo;
var
f : String;
x : Integer;
ft : TRttiType;
_f : TRttiField;
field : TRttiField;
_p : TRttiProperty;
prop : TRttiProperty;
a : TArray<TRttiField>;
v : TValue;
it : T;
p : Pointer;
begin
(*** reference to first entry, needed to search subclasses ***)
if item = nil then begin
it := fItems[0];
item := @it;
end;
v := TValue.Empty;
result.Exists := False;
ft := fContext.GetType( System.TypeInfo(T) );
repeat
x := Pos( '.', FieldName );
if x > 0 then begin
f := Copy( FieldName, 1, x - 1 );
Delete( FieldName, 1, x );
field := ft.GetField( f );
if field <> nil then v := field.GetValue( TObject(item^) )
else begin
prop := ft.GetProperty( f );
if prop = nil then Exit;
v := prop.GetValue( TObject(item^) );
end;
case v.Kind of
tkClass: ft := fContext.GetType( v.AsObject.ClassType );
tkRecord: ft := fContext.GetType( v.TypeInfo );
end;
end;
until x = 0;
result.FieldName := FieldName;
result.TypeInfo := ft;
prop := ft.GetProperty( FieldName );
if prop <> nil then begin
if v.IsEmpty then result.Value := prop.GetValue( TObject(item^) )
else result.Value := prop.GetValue( v.AsObject );
result.TypeKind := prop.PropertyType.TypeKind;
result.Exists := True;
end
else begin
field := ft.GetField( FieldName );
if field <> nil then begin
if v.IsEmpty then result.Value := field.GetValue( item )
else result.Value := field.GetValue( v.GetReferenceToRawData );
result.TypeKind := field.FieldType.TypeKind;
result.Exists := True;
end;
end
end;
(**************************************************************************************************)
(* GetValue
(* helper for getting values
(**************************************************************************************************)
function TEasyLINQ<T>.GetValue( item: Pointer; FieldName: String ): TValue;
var
FieldInfo : TFieldInfo;
begin
result := TValue.Empty;
FieldInfo := GetFieldInfo( item, FieldName );
if not FieldInfo.Exists then Exit;
case FieldInfo.TypeKind of
tkChar, tkWString,
tkUString, tkString : result := UnquoteStr( FieldInfo.Value.AsString );
else result := FieldInfo.Value;
end;
end;
(**************************************************************************************************)
(* SetValue
(* helper for settings values
(**************************************************************************************************)
procedure TEasyLINQ<T>.SetValue( const item: Pointer; FieldName: String; Value: Variant );
var
prop : TRttiProperty;
field : TRttiField;
v : TValue;
FieldInfo : TFieldInfo;
begin
FieldInfo := GetFieldInfo( item, FieldName );
if FieldInfo.Exists then begin
prop := FieldInfo.TypeInfo.GetProperty( FieldInfo.FieldName );
if prop = nil then
raise ELinQException.Create('TLinQ: Read only fields. Only properties are writeable');
case prop.PropertyType.TypeKind of
tkChar, tkWString,
tkUString, tkString : prop.SetValue( TObject(item^), TValue.From<String>( Value ) );
tkInt64, tkInteger : prop.SetValue( TObject(item^), TValue.From<Integer>( Value ) );
tkFloat : prop.SetValue( TObject(item^), TValue.From<Double>( Value ) );
end;
end;
end;
(**************************************************************************************************)
(* GetFieldValue
(* Callback for TCalculator, loads the value of a field
(**************************************************************************************************)
procedure TEasyLINQ<T>.GetFieldValue( FieldName: String; var Value: Double );
var
v : TValue;
begin
v := GetValue( fCalculator.ActiveItem, FieldName );
if v.IsEmpty then Value := 0
else
case v.Kind of
tkFloat,
tkInt64,
tkInteger : Value := v.AsCurrency;
end;
end;
(**************************************************************************************************)
(* Compare
(*
(**************************************************************************************************)
function TEasyLINQ<T>.Compare(const L, R: T; prop: String ): integer;
var
vL : TFieldInfo;
vR : TFieldInfo;
begin
result := 0;
vL := GetFieldInfo( @L, prop );
vR := GetFieldInfo( @R, prop );
case vL.TypeKind of
tkChar, tkWString, tkUString, tkString : result := CompareText( vL.Value.AsString, vR.Value.AsString );
tkInt64, tkInteger : if vL.Value.AsInteger < vR.Value.AsInteger then result := -1
else if vL.Value.AsInteger > vR.Value.AsInteger then result := 1;
tkFloat : if vL.Value.AsCurrency < vR.Value.AsCurrency then result := -1
else if vL.Value.AsCurrency > vR.Value.AsCurrency then result := 1;
end;
end;
(**************************************************************************************************)
(* OrderBy
(* creates the sort order of the list
(**************************************************************************************************)
procedure TEasyLINQ<T>.ExecOrderBy(const FieldNames: String );
var
sl : TStringList;
begin
sl := TStringList.Create;
try
sl.StrictDelimiter := True;
sl.Delimiter := ',';
sl.DelimitedText := FieldNames;
fItems.Sort( TComparer<T>.Construct( {$region '...'}
function (const L, R: T ): integer
var
str : String;
begin
result := 0;
for str in sl do begin
Result := Compare( L, R, Trim( str ) );
if Result <> 0 then Break;
end;
if fSortOrderDesc then Result := Result * -1;
end {$endregion} ) );
finally
sl.Free;
end;
end;
(**************************************************************************************************)
(* ExecUpdate
(* executes the UPDATE command
(**************************************************************************************************)
procedure TEasyLINQ<T>.ExecUpdate( const Commands: String );
var
cmd : String;
tmp : String;
param1 : String;
param2 : Variant;
value : TValue;
FieldInfo : TFieldInfo;
item : T;
begin
for item in fItems do begin
cmd := Trim( Commands );
while cmd <> '' do begin
param1 := GetToken( cmd );
if Pos( '=', cmd ) <> 1 then
raise ELinQException.Create('TLinQ: = required in Update expression');
Delete( cmd, 1, 1 );
param2 := GetToken( cmd );
if LowerCase( param2 ) = 'calc' then begin
tmp := GetToken( cmd );
fCalculator.ActiveItem := @item;
fCalculator.Expression( tmp );
if fCalculator.Valid then Param2 := fCalculator.Result;
end
else
case GetTypOfToken( param2 ) of
ttString : Param2 := UnquoteStr( Param2 );
ttField : begin
value := GetValue( @item, Param2 );
if value.IsEmpty then
raise ELinQException.Create('TLinQ: unknown parameter ' + Param2);
Param2 := FieldInfo.Value.AsVariant;
end;
end;
SetValue( @item, param1, param2 );
Delete( cmd, 1, 1 );
end;
end;
end;
(**************************************************************************************************)
(* Calculate
(* executes the calculator
(**************************************************************************************************)
procedure TEasyLINQ<T>.Calculate( txt: String );
var
field : String;
res : Double;
prop : TRttiProperty;
item : T;
i : Integer;
begin
field := GetToken( txt );
if field = '' then Exit;
Delete( txt, 1, 1 );
for item in fItems do begin
fCalculator.ActiveItem := @item;
fCalculator.Expression( txt );
if fCalculator.Valid then res := fCalculator.Result
else res := 0;
SetValue( @item, field, res );
end;
end;
(**************************************************************************************************)
(* Distinct
(* uses TStringList as helper to create a disinct list
(**************************************************************************************************)
procedure TEasyLINQ<T>.DoDistinct( FieldNames: String );
var
item : T;
sl : TStringList;
res : TStringList;
field : String;
str : String;
prop : TRttiProperty;
x : Integer;
begin
sl := TStringList.Create;
res := TStringList.Create;
try
sl.StrictDelimiter := True;
sl.Delimiter := ',';
sl.DelimitedText := FieldNames;
res.Duplicates := dupIgnore;
res.Sorted := True;
x := 0;
while x < fItems.Count do begin
str := '';
item := fItems[x];
for field in sl do str := str + GetValue( @item, field ).AsString;
if res.IndexOf( str ) < 0 then begin
res.Add( str );
Inc( x );
end
else Remove( x );
end;
finally
sl.Free;
res.Free;
end;
end;
(**************************************************************************************************)
(* IsValid
(* verify the values
(**************************************************************************************************)
function TEasyLINQ<T>.IsValid( item: T; cmd: TWhereCMD ): Boolean;
var
v1 : Variant;
v2 : Variant;
str1 : String;
str2 : String;
m : Integer;
begin
Result := False;
if cmd.Field2 <> '' then begin
(*** second parameter is also a field ***)
v1 := GetValue( @item, cmd.Field2 ).AsVariant;
end
else
case cmd.TypeKind of
tkChar, tkWString, tkUString, tkString : v1 := cmd.Value;
tkInt64, tkInteger : v1 := StrToIntDef( cmd.Value, 0 );
tkFloat : v1 := StrToFloat( cmd.Value );
else Exit( True );
end;
v2 := GetValue( @item, cmd.Field ).AsVariant;
case cmd.CharCase of
ccToUpper : v2 := WideUpperCase( v2 );
ccToLower : v2 := WideLowerCase( v2 );
end;
case cmd.Mode of
wmIS : Result := v2 = v1;
wmLess : Result := v2 < v1;
wmUpper : Result := v2 > v1;
wmIsLess : Result := v2 <= v1;
wmIsUpper : Result := v2 >= v1;
wmIsNot : Result := v2 <> v1;
wmLike : begin
str1 := v1;
str2 := v2;
m := 0;
if Pos( '%', str1 ) = 1 then begin
m := m or 1;
Delete( str1, 1, 1 );
end;
if Pos( '%', str1 ) = Length( str1 ) then begin
m := m or 2;
Delete( str1, Length( str1 ), 1 );
end;
case m of
0 : Result := CompareText( str1, str2 ) = 0;
1 : Result := Pos( str1, str2 ) = Length( str2 ) - Length( str1 ) + 1;
2 : Result := Pos( str1, str2 ) = 1;
3 : Result := Pos( str1, str2 ) > 0;
end;
end;
end;
end;
{$endregion}
{$region '----> Parser'}
(**************************************************************************************************)
(* GetToken
(* loads the next token from the string
(**************************************************************************************************)
function TEasyLINQ<T>.GetToken( var str: String ): String;
var
i : Integer;
j : Integer;
x : Integer;
start : Integer;
ext : Boolean;
count : Integer;
fExtractCount : Integer;
begin
str := TrimLeft( str );
result := '';
if str = '' then Exit;
case IndexStr( str[1], ['"','''', '('] ) of
0 : begin
x := PosEx( '"', str, 2 );
if x > 0 then begin
Result := Trim( Copy( str, 1, x ) );
Delete( str, 1, x );
end
else raise Exception.Create('TEasyLINQ: " missing');
end;
1 : begin
x := PosEx( '''', str, 2 );
if x > 0 then begin
Result := Trim( Copy( str, 1, x - 1 ) );
Delete( str, 1, x );
end
else raise Exception.Create('TEasyLINQ: '' missing');
end;
2 : begin
count := 1;
for x := 2 to Length( str ) do begin
if str[x] = '(' then begin
Inc( count );
Continue;
end;
if str[x] = ')' then begin
Dec( count );
if count = 0 then begin
Result := Trim( Copy( str, 2, x - 2 ) );
Delete( str, 1, x );
Exit;
end;
end;
end;
raise Exception.Create('TEasyLINQ: ) missing');
end;
else begin
for x := 1 to Length( str ) do begin
if CharInSet( str[x], StopAt ) then begin
Result := Trim( Copy( str, 1, x - 1 ) );
Delete( str, 1, x - 1 );
str := TrimLeft( str );
Exit;
end;
end;
result := str;
str := '';
end;
end;
str := TrimLeft( str );
end;
(**************************************************************************************************)
(* GetTypOfToken
(*
(**************************************************************************************************)
function TEasyLINQ<T>.GetTypOfToken( str: String ): TTokenTpye;
var
s : String;
i : Integer;
calc : Boolean;
begin
Result := ttField;
if str = '' then Exit;
if (str[1] = '"') or (str[1] = '''') then Result := ttString;
calc := False;
for i := 1 to Length( str ) do begin
if not CharInSet( str[i], ['0'..'9','.'] ) then Exit;
end;
Result := ttConst;
end;
(**************************************************************************************************)
(* UnquoteStr
(* remove quotes from string
(**************************************************************************************************)
function TEasyLINQ<T>.UnquoteStr( str: String ): String;
begin
result := Trim( str );
if result <> '' then
if (result[1] = '''') or (result[1] = '"') or (result[1] = '(') then
result := Copy( result, 2, Length( Result ) - 2 );
end;
(**************************************************************************************************)
(* GetCMD
(* parse commands for "where"
(**************************************************************************************************)
function TEasyLINQ<T>.GetCMD( var txt: String; fTypeInfo: TRttiType ): TWhereCMD;
var
smode : String;
str : String;
tmp : String;
i : Integer;
x : Integer;
p : Integer;
FieldInfo : TFieldInfo;
begin
str := TrimLeft( txt );
tmp := str;
FillChar( result, SizeOf( result ), 0 );
(*** expressions in round brackerts makes parsing easier ***)
if str[1] <> '(' then begin
if Pos( 'order', LowerCase( str ) ) = 0 then
raise ELinQException.Create('TEasyLINQ: WHERE requires expressions in brackets (...)');