-
Notifications
You must be signed in to change notification settings - Fork 27
/
Quick.DAO.Query.pas
840 lines (792 loc) · 26.6 KB
/
Quick.DAO.Query.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
{ ***************************************************************************
Copyright (c) 2016-2020 Kike Pérez
Unit : Quick.DAO.Query
Description : DAODatabase Query
Author : Kike Pérez
Version : 1.1
Created : 31/08/2018
Modified : 07/04/2020
This file is part of QuickDAO: https://github.com/exilon/QuickDAO
***************************************************************************
Licensed under the Apache License, Version 2.0 (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.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*************************************************************************** }
unit Quick.DAO.Query;
{$i QuickDAO.inc}
interface
uses
Classes,
RTTI,
{$IFNDEF FPC}
System.SysUtils,
System.TypInfo,
Json,
System.Variants,
System.Generics.Collections,
System.Generics.Defaults,
{$ELSE}
SysUtils,
TypInfo,
Generics.Collections,
Generics.Defaults,
Variants,
Quick.Json.fpc.Compatibility,
Quick.Rtti.fpc.Compatibility,
{$ENDIF}
Quick.Commons,
Quick.RTTI.Utils,
Quick.Json.Serializer,
Quick.DAO,
Quick.DAO.Database;
type
TDAOQuery<T : class, constructor> = class(TInterfacedObject,IDAOQuery<T>,IDAOLinqQuery<T>)
private
fWhereClause : string;
fOrderClause : string;
fOrderAsc : Boolean;
fSelectedFields : TArray<string>;
function FormatParams(const aWhereClause : string; aWhereParams : array of const) : string;
protected
fDAODataBase : TDAODataBase;
fModel : TDAOModel;
fQueryGenerator : IDAOQueryGenerator;
fHasResults : Boolean;
fFirstIteration : Boolean;
function MoveNext : Boolean; virtual; abstract;
function GetCurrent : T; virtual; abstract;
function GetFieldValue(const aName : string) : Variant; virtual; abstract;
function GetFieldValues(aDAORecord : TDAORecord; aExcludeAutoIDFields : Boolean) : TStringList;
procedure FillRecordFromDB(aDAORecord : T);
function GetDBFieldValue(const aFieldName : string; aValue : TValue): TValue;
function GetFieldsPairs(aDAORecord : TDAORecord): string; overload;
function GetFieldsPairs(const aFieldNames : string; aFieldValues : array of const; aIsTimeStamped : Boolean): string; overload;
function GetRecordValue(const aFieldName : string; aValue : TValue) : string;
function GetModel : TDAOModel;
function OpenQuery(const aQuery : string) : Integer; virtual; abstract;
function ExecuteQuery(const aQuery : string) : Boolean; virtual; abstract;
public
constructor Create(aDAODataBase : TDAODataBase; aModel : TDAOModel; aQueryGenerator : IDAOQueryGenerator); virtual;
property Model : TDAOModel read fModel write fModel;
property HasResults : Boolean read fHasResults write fHasResults;
function Eof : Boolean; virtual; abstract;
function AddOrUpdate(aDAORecord : TDAORecord) : Boolean; virtual;
function Add(aDAORecord : TDAORecord) : Boolean; virtual;
function CountResults : Integer; virtual; abstract;
function Update(aDAORecord : TDAORecord) : Boolean; overload; virtual;
function Delete(aDAORecord : TDAORecord) : Boolean; overload; virtual;
function Delete(const aWhere : string) : Boolean; overload; virtual;
//LINQ queries
function Where(const aFormatSQLWhere: string; const aValuesSQLWhere: array of const) : IDAOLinqQuery<T>; overload;
function Where(const aWhereClause : string) : IDAOLinqQuery<T>; overload;
function SelectFirst : T;
function SelectLast : T;
function Select : IDAOResult<T>; overload;
function Select(const aFieldNames : string) : IDAOResult<T>; overload;
function SelectTop(aNumber : Integer) : IDAOResult<T>;
function Sum(const aFieldName : string) : Int64;
function Count : Int64;
function Update(const aFieldNames : string; const aFieldValues : array of const) : Boolean; overload;
function Delete : Boolean; overload;
function OrderBy(const aFieldValues : string) : IDAOLinqQuery<T>;
function OrderByDescending(const aFieldValues : string) : IDAOLinqQuery<T>;
end;
implementation
{ TDAOQuery }
constructor TDAOQuery<T>.Create(aDAODataBase : TDAODataBase; aModel : TDAOModel; aQueryGenerator : IDAOQueryGenerator);
begin
fFirstIteration := True;
fDAODataBase := aDAODataBase;
fModel := aModel;
fWhereClause := '1=1';
fSelectedFields := [];
fQueryGenerator := aQueryGenerator;
fHasResults := False;
end;
function TDAOQuery<T>.GetFieldValues(aDAORecord : TDAORecord; aExcludeAutoIDFields : Boolean) : TStringList;
var
ctx: TRttiContext;
{$IFNDEF FPC}
attr : TCustomAttribute;
{$ENDIF}
rType: TRttiType;
rProp: TRttiProperty;
propertyname : string;
propvalue : TValue;
skip : Boolean;
begin
Result := TStringList.Create;
Result.Delimiter := ',';
Result.StrictDelimiter := True;
try
rType := ctx.GetType(aDAORecord.ClassInfo);
try
for rProp in TRTTI.GetProperties(rType,roFirstBase) do
begin
propertyname := rProp.Name;
if IsPublishedProp(aDAORecord,propertyname) then
begin
{$IFNDEF FPC}
for attr in rProp.GetAttributes do
begin
if attr is TMapField then propertyname := TMapField(attr).Name;
end;
{$ENDIF}
skip := False;
propvalue := rProp.GetValue(aDAORecord);
if CompareText(rProp.Name,fModel.PrimaryKey.Name) = 0 then
begin
if not aExcludeAutoIDFields then
begin
if (rProp.PropertyType.Name = 'TAutoID') and ((propvalue.IsEmpty) or (propvalue.AsInt64 = 0)) then skip := True;
end
else skip := True;
end;
if not skip then Result.Add(GetRecordValue(propertyname,propvalue));
end;
end;
finally
ctx.Free;
end;
except
on E : Exception do
begin
raise Exception.CreateFmt('Error getting field values "%s" : %s',[Self.ClassName,e.Message]);
end;
end;
end;
function TDAOQuery<T>.GetModel: TDAOModel;
begin
Result := fModel;
end;
function TDAOQuery<T>.GetRecordValue(const aFieldName: string; aValue: TValue): string;
var
rttijson : TRTTIJson;
jpair : TJsonPair;
//a : TTypeKind;
begin
//a := aValue.Kind;
case aValue.Kind of
tkDynArray :
begin
rttijson := TRTTIJson.Create(TSerializeLevel.slPublishedProperty);
try
jpair := TJSONPair.Create(aFieldName,rttijson.SerializeValue(aValue));
try
{$IFNDEF FPC}
Result := QuotedStr(jpair.JsonValue.ToJson);
{$ELSE}
Result := QuotedStr(jpair.JsonValue.AsJson);
{$ENDIF}
finally
jpair.Free;
end;
finally
rttijson.Free;
end;
end;
tkString, tkLString, tkWString, tkUString{$IFDEF FPC}, tkAnsiString{$ENDIF} : Result := QuotedStr(aValue.AsString);
tkInteger : Result := aValue.AsInteger.ToString;
tkInt64 : Result := aValue.AsInt64.ToString;
{$IFDEF FPC}
tkBool : Result := aValue.AsBoolean.ToString;
{$ENDIF}
tkFloat :
begin
if ((aValue.TypeInfo = TypeInfo(TDateTime)) or
(aValue.TypeInfo = TypeInfo(TCreationDate)) or
(aValue.TypeInfo = TypeInfo(TModifiedDate))) then
begin
if aValue.AsExtended = 0.0 then Result := 'null'
else Result := QuotedStr(fQueryGenerator.DateTimeToDBField(aValue.AsExtended));
end
else if aValue.TypeInfo = TypeInfo(TDate) then
begin
Result := QuotedStr(aValue.AsExtended.ToString);
end
else if aValue.TypeInfo = TypeInfo(TTime) then
begin
Result := QuotedStr(aValue.AsExtended.ToString);
end
else Result := StringReplace(string(aValue.AsVariant),',','.',[]);
end;
tkEnumeration :
begin
if (aValue.TypeInfo = System.TypeInfo(Boolean)) then
begin
if CompareText(string(aValue.AsVariant),'true') = 0 then Result := '1'
else Result := '0';
end
else
begin
//value := value;
end;
end;
tkRecord, tkClass :
begin
rttijson := TRTTIJson.Create(TSerializeLevel.slPublishedProperty);
try
jpair := TJSONPair.Create(aFieldName,rttijson.SerializeRecord(aValue));
try
Result := QuotedStr(jpair.{$IFNDEF FPC}ToJSON{$ELSE}JsonString{$ENDIF});
finally
jpair.Free;
end;
finally
rttijson.Free;
end;
end;
else Result := 'null';
end;
end;
function TDAOQuery<T>.GetFieldsPairs(aDAORecord : TDAORecord): string;
var
ctx: TRttiContext;
{$IFNDEF FPC}
attr : TCustomAttribute;
{$ENDIF}
rType: TRttiType;
rProp: TRttiProperty;
propertyname : string;
propvalue : TValue;
value : string;
begin
Result := '';
try
rType := ctx.GetType(fModel.Table);
try
for rProp in TRTTI.GetProperties(rType,roFirstBase) do
begin
propertyname := rProp.Name;
if IsPublishedProp(aDAORecord,propertyname) then
begin
{$IFNDEF FPC}
for attr in rProp.GetAttributes do
begin
if attr is TMapField then propertyname := TMapField(attr).Name;
end;
{$ENDIF}
propvalue := rProp.GetValue(aDAORecord);
value := GetRecordValue(propertyname,propvalue);
if not ((CompareText(propertyname,fModel.PrimaryKey.Name) = 0) and (rProp.PropertyType.Name = 'TAutoID')) then Result := Result + Format('[%s]=%s,',[propertyname,value])
else if propvalue.TypeInfo = TypeInfo(TModifiedDate) then value := fQueryGenerator.DateTimeToDBField(Now());
//rProp.SetValue(Self,GetDBFieldValue(propertyname,rProp.GetValue(Self)));
end;
end;
Result := RemoveLastChar(Result);
finally
ctx.Free;
end;
except
on E : Exception do
begin
raise Exception.CreateFmt('Error getting fields "%s" : %s',[aDAORecord.ClassName,e.Message]);
end;
end;
end;
function TDAOQuery<T>.GetFieldsPairs(const aFieldNames : string; aFieldValues : array of const; aIsTimeStamped : Boolean): string;
var
fieldname : string;
value : string;
i : Integer;
begin
if aIsTimeStamped then Result := 'ModifiedDate = ' + fQueryGenerator.DateTimeToDBField(Now()) + ',';
i := 0;
for fieldname in aFieldNames.Split([',']) do
begin
case aFieldValues[i].VType of
vtInteger : value := IntToStr(aFieldValues[i].VInteger);
vtInt64 : value := IntToStr(aFieldValues[i].VInt64^);
vtExtended : value := FloatToStr(aFieldValues[i].VExtended^);
vtBoolean : value := BoolToStr(aFieldValues[i].VBoolean);
vtWideString : value := DbQuotedStr(string(aFieldValues[i].VWideString^));
{$IFNDEF NEXTGEN}
vtAnsiString : value := DbQuotedStr(AnsiString(aFieldValues[i].VAnsiString));
vtString : value := DbQuotedStr(aFieldValues[i].VString^);
{$ENDIF}
vtChar : value := DbQuotedStr(aFieldValues[i].VChar);
vtPChar : value := string(aFieldValues[i].VPChar).QuotedString;
else value := DbQuotedStr(string(aFieldValues[i].VUnicodeString));
end;
Result := Result + fieldname + '=' + value + ',';
Inc(i);
end;
RemoveLastChar(Result);
end;
procedure TDAOQuery<T>.FillRecordFromDB(aDAORecord : T);
var
ctx: TRttiContext;
{$IFNDEF FPC}
attr : TCustomAttribute;
{$ENDIF}
rType: TRttiType;
rProp: TRttiProperty;
propertyname : string;
rvalue : TValue;
dbfield : TDBField;
IsFilterSelect : Boolean;
skip : Boolean;
begin
try
IsFilterSelect := not IsEmptyArray(fSelectedFields);
rType := ctx.GetType(fModel.Table);
try
for rProp in TRTTI.GetProperties(rType,roFirstBase) do
begin
propertyname := rProp.Name;
if IsPublishedProp(aDAORecord,propertyname) then
begin
{$IFNDEF FPC}
for attr in rProp.GetAttributes do
begin
if attr is TMapField then propertyname := TMapField(attr).Name;
end;
{$ENDIF}
skip := False;
if (IsFilterSelect) and (not StrInArray(propertyname,fSelectedFields)) then skip := True;
if not skip then rvalue := GetDBFieldValue(propertyname,rProp.GetValue(TDAORecord(aDAORecord)))
else rvalue := nil;
if CompareText(propertyname,fModel.PrimaryKey.Name) = 0 then
begin
if not rvalue.IsEmpty then
begin
dbfield.FieldName := fModel.PrimaryKey.Name;
dbfield.Value := rValue.AsVariant;
TDAORecord(aDAORecord).PrimaryKey := dbfield;
end;
end;
if not rvalue.IsEmpty then rProp.SetValue(TDAORecord(aDAORecord),rvalue);
end;
end;
finally
ctx.Free;
end;
except
on E : Exception do
begin
raise Exception.CreateFmt('Error filling record "%s" field : %s',[fModel.TableName,e.Message]);
end;
end;
end;
function TDAOQuery<T>.GetDBFieldValue(const aFieldName : string; aValue : TValue): TValue;
var
IsNull : Boolean;
fieldvalue : variant;
rttijson : TRTTIJson;
json : TJsonObject;
jArray : TJSONArray;
//a : TTypeKind;
begin
fieldvalue := GetFieldValue(aFieldName);
IsNull := IsEmptyOrNull(fieldvalue);
//a := aValue.Kind;
try
case aValue.Kind of
tkDynArray :
begin
if IsNull then Exit(nil);
rttijson := TRTTIJson.Create(TSerializeLevel.slPublishedProperty);
try
jArray := TJSONObject.ParseJSONValue(fieldvalue) as TJSONArray;
try
{$IFNDEF FPC}
Result := rttijson.DeserializeDynArray(aValue.TypeInfo,Self,jArray);
{$ELSE}
rttijson.DeserializeDynArray(aValue.TypeInfo,aFieldName,aValue.AsObject,jArray);
{$ENDIF}
finally
jArray.Free;
end;
finally
rttijson.Free;
end;
end;
tkClass :
begin
if IsNull then Exit(nil);
rttijson := TRTTIJson.Create(TSerializeLevel.slPublishedProperty);
try
json := TJSONObject.ParseJSONValue('{'+fieldvalue+'}') as TJSONObject;
try
Result := rttijson.DeserializeObject(Self,json.GetValue(aFieldName) as TJSONObject);
finally
json.Free;
end;
finally
rttijson.Free;
end;
end;
tkString, tkLString, tkWString, tkUString{$IFDEF FPC}, tkAnsiString{$ENDIF} :
begin
if not IsNull then Result := string(fieldvalue)
else Result := '';
end;
tkChar, tkWChar :
begin
if not IsNull then Result := string(fieldvalue)
else Result := '';
end;
tkInteger :
begin
if not IsNull then Result := Integer(fieldvalue)
else Result := 0;
end;
tkInt64 :
begin
if not IsNull then Result := Int64(fieldvalue)
else Result := 0;
end;
{$IFDEF FPC}
tkBool :
begin
if not IsNull then Result := Boolean(fieldvalue)
else Result := False;
end;
{$ENDIF}
tkFloat :
begin
if ((aValue.TypeInfo = TypeInfo(TDateTime)) or
(aValue.TypeInfo = TypeInfo(TCreationDate)) or
(aValue.TypeInfo = TypeInfo(TModifiedDate))) then
begin
if not IsNull then
begin
{$IFNDEF FPC}
if not Self.ClassName.StartsWith('TDAOQueryFireDAC') then Result := fQueryGenerator.DBFieldToDateTime(fieldvalue)
{$ELSE}
if not string(Self.ClassName).StartsWith('TDAOQueryFireDAC') then Result := fQueryGenerator.DBFieldToDateTime(fieldvalue)
{$ENDIF}
else Result := StrToDateTime(fieldvalue);
end
else Result := 0;
end
else if aValue.TypeInfo = TypeInfo(TDate) then
begin
if not IsNull then Result := {$IFNDEF FPC}TDate{$ELSE}VarToDateTime{$ENDIF}(fieldvalue)
else Result := 0;
end
else if aValue.TypeInfo = TypeInfo(TTime) then
begin
if not IsNull then Result := {$IFNDEF FPC}TTime{$ELSE}VarToDateTime{$ENDIF}(fieldvalue)
else Result := 0;
end
else if not IsNull then Result := Extended(fieldvalue)
else Result := 0;
end;
tkEnumeration :
begin
if (aValue.TypeInfo = System.TypeInfo(Boolean)) then
begin
if not IsNull then Result := Boolean(fieldvalue)
else Result := False;
end
else
begin
if not IsNull then TValue.Make({$IFDEF FPC}@{$ENDIF}fieldvalue,aValue.TypeInfo,Result)
else TValue.Make(0,aValue.TypeInfo, Result);
end;
end;
tkSet :
begin
//Result.JsonValue := TJSONString.Create(aValue.ToString);
end;
tkRecord :
begin
if IsNull then Exit(nil);
{$IFNDEF FPC}
rttijson := TRTTIJson.Create(TSerializeLevel.slPublishedProperty);
try
json := TJSONObject.ParseJSONValue('{'+fieldvalue+'}') as TJSONObject;
try
Result := rttijson.DeserializeRecord(aValue,Self,json.GetValue(aFieldName) as TJSONObject);
finally
json.Free;
end;
finally
rttijson.Free;
end;
{$ENDIF}
end;
tkMethod, tkPointer, tkClassRef ,tkInterface, tkProcedure :
begin
//skip these properties
end
else
begin
{$IFNDEF FPC}
raise Exception.Create(Format('Error %s %s',[aFieldName,GetTypeName(aValue.TypeInfo)]));
{$ELSE}
Exit(nil);
raise Exception.CreateFmt('Error getting DB field "%s"',[aFieldName]);
{$ENDIF}
end;
end;
except
on E : Exception do
begin
if aValue.Kind = tkClass then raise Exception.CreateFmt('Serialize error class "%s.%s" : %s',[aFieldName,aValue.ToString,e.Message])
else raise Exception.CreateFmt('Serialize error property "%s=%s" : %s',[aFieldName,aValue.ToString,e.Message]);
end;
end;
end;
function TDAOQuery<T>.Add(aDAORecord: TDAORecord): Boolean;
var
sqlfields : TStringList;
sqlvalues : TStringList;
begin
Result := False;
try
if aDAORecord is TDAORecordTS then TDAORecordTS(aDAORecord).CreationDate := Now();
sqlfields := fModel.GetFieldNames(aDAORecord,False);
try
sqlvalues := GetFieldValues(aDAORecord,False);
try
Result := ExecuteQuery(fQueryGenerator.Add(fModel.TableName,sqlfields.CommaText,CommaText(sqlvalues)));
finally
sqlvalues.Free;
end;
finally
sqlfields.Free;
end;
except
on E : Exception do raise EDAOCreationError.CreateFmt('Insert error: %s',[e.message]);
end;
end;
function TDAOQuery<T>.AddOrUpdate(aDAORecord: TDAORecord): Boolean;
var
sqlfields : TStringList;
sqlvalues : TStringList;
begin
Result := False;
try
// if fQueryGenerator.Name <> 'MSSQL' then
// begin
if (aDAORecord.PrimaryKey.FieldName = '') or (VarIsEmpty(aDAORecord.PrimaryKey.Value))
or (Where(Format('%s = ?',[aDAORecord.PrimaryKey.FieldName]),[aDAORecord.PrimaryKey.Value]).Count = 0) then
begin
Result := Add(aDAORecord);
end
else
begin
Result := Update(aDAORecord);
end;
// end
// else
// begin
// sqlfields := fModel.GetFieldNames(aDAORecord,False);
// try
// sqlvalues := GetFieldValues(aDAORecord,False);
// try
// Result := ExecuteQuery(fQueryGenerator.AddOrUpdate(fModel.TableName,sqlfields.CommaText,CommaText(sqlvalues)));
// finally
// sqlvalues.Free;
// end;
// finally
// sqlfields.Free;
// end;
// end;
except
on E : Exception do raise EDAOCreationError.CreateFmt('AddOrUpdate error: %s',[e.message]);
end;
end;
function TDAOQuery<T>.Delete(aDAORecord : TDAORecord): Boolean;
begin
try
Result := ExecuteQuery(fQueryGenerator.Delete(fModel.TableName,Format('%s=%s',[aDAORecord.PrimaryKey.FieldName,aDAORecord.PrimaryKey.Value])));
except
on E : Exception do raise EDAODeleteError.CreateFmt('Delete error: %s',[e.message]);
end;
end;
function TDAOQuery<T>.Delete(const aWhere: string): Boolean;
begin
try
Result := ExecuteQuery(fQueryGenerator.Delete(fModel.TableName,aWhere));
except
on E : Exception do raise EDAODeleteError.CreateFmt('Delete error: %s',[e.message]);
end;
end;
{ LINQ queries }
function TDAOQuery<T>.Count: Int64;
begin
try
if OpenQuery(fQueryGenerator.Count(fModel.TableName,fWhereClause)) > 0 then Result := GetFieldValue('cnt')
else Result := 0;
HasResults := False;
except
on E : Exception do raise EDAOSelectError.CreateFmt('Select count error: %s',[e.message]);
end;
end;
function TDAOQuery<T>.FormatParams(const aWhereClause: string; aWhereParams: array of const): string;
var
i : Integer;
value : string;
vari : variant;
begin
Result := aWhereClause;
if aWhereClause = '' then
begin
Result := '1 = 1';
Exit;
end;
for i := 0 to aWhereClause.CountChar('?') - 1 do
begin
case aWhereParams[i].VType of
vtInteger : value := IntToStr(aWhereParams[i].VInteger);
vtInt64 : value := IntToStr(aWhereParams[i].VInt64^);
vtExtended : value := FloatToStr(aWhereParams[i].VExtended^);
vtBoolean : value := BoolToStr(aWhereParams[i].VBoolean);
vtWideString : value := fQueryGenerator.QuotedStr(string(aWhereParams[i].VWideString^));
{$IFNDEF NEXTGEN}
vtAnsiString : value := fQueryGenerator.QuotedStr(AnsiString(aWhereParams[i].VAnsiString));
vtString : value := fQueryGenerator.QuotedStr(aWhereParams[i].VString^);
{$ENDIF}
vtChar : value := fQueryGenerator.QuotedStr(aWhereParams[i].VChar);
vtPChar : value := fQueryGenerator.QuotedStr(string(aWhereParams[i].VPChar));
vtVariant :
begin
vari := aWhereParams[i].VVariant^;
case VarType(vari) of
varInteger,varInt64 : value := IntToStr(vari);
varDouble : value := FloatToStr(vari);
varDate : value := DateTimeToSQL(vari);
else value := string(vari);
end;
end
else value := fQueryGenerator.QuotedStr(string(aWhereParams[i].VUnicodeString));
end;
Result := StringReplace(Result,'?',value,[]);
end;
end;
function TDAOQuery<T>.OrderBy(const aFieldValues: string): IDAOLinqQuery<T>;
begin
Result := Self;
fOrderClause := aFieldValues;
fOrderAsc := True;
end;
function TDAOQuery<T>.OrderByDescending(const aFieldValues: string): IDAOLinqQuery<T>;
begin
Result := Self;
fOrderClause := aFieldValues;
fOrderAsc := False;
end;
function TDAOQuery<T>.Select: IDAOResult<T>;
var
query : string;
begin
try
query := fQueryGenerator.Select(fModel.TableName,'',0,fWhereClause,fOrderClause,fOrderAsc);
OpenQuery(query);
Result := TDAOResult<T>.Create(Self);
except
on E : Exception do raise EDAOSelectError.CreateFmt('Select error: %s',[e.message]);
end;
end;
function TDAOQuery<T>.Select(const aFieldNames: string): IDAOResult<T>;
var
query : string;
filter : string;
begin
try
for filter in aFieldNames.Split([',']) do fSelectedFields := fSelectedFields + [filter];
query := fQueryGenerator.Select(fModel.TableName,aFieldNames,0,fWhereClause,fOrderClause,fOrderAsc);
OpenQuery(query);
Result := TDAOResult<T>.Create(Self);
except
on E : Exception do raise EDAOSelectError.CreateFmt('Select error: %s',[e.message]);
end;
end;
function TDAOQuery<T>.SelectFirst: T;
var
query : string;
begin
try
query := fQueryGenerator.Select(fModel.TableName,'',1,fWhereClause,fOrderClause,fOrderAsc);
OpenQuery(query);
Self.Movenext;
Result := Self.GetCurrent;
except
on E : Exception do raise EDAOSelectError.CreateFmt('Select error: %s',[e.message]);
end;
end;
function TDAOQuery<T>.SelectLast: T;
var
query : string;
begin
try
query := fQueryGenerator.Select(fModel.TableName,'',1,fWhereClause,fOrderClause,not fOrderAsc);
OpenQuery(query);
Self.Movenext;
Result := Self.GetCurrent;
except
on E : Exception do raise EDAOSelectError.CreateFmt('Select error: %s',[e.message]);
end;
end;
function TDAOQuery<T>.SelectTop(aNumber: Integer): IDAOResult<T>;
var
query : string;
begin
try
query := fQueryGenerator.Select(fModel.TableName,'',aNumber,fWhereClause,fOrderClause,fOrderAsc);
OpenQuery(query);
Result := TDAOResult<T>.Create(Self);
except
on E : Exception do raise EDAOSelectError.CreateFmt('Select error: %s',[e.message]);
end;
end;
function TDAOQuery<T>.Sum(const aFieldName: string): Int64;
var
query : string;
begin
try
query := fQueryGenerator.Sum(fModel.TableName,aFieldName,fWhereClause);
if OpenQuery(query) > 0 then Result := GetFieldValue('cnt')
except
on E : Exception do raise EDAOSelectError.CreateFmt('Select error: %s',[e.message]);
end;
end;
function TDAOQuery<T>.Update(aDAORecord: TDAORecord): Boolean;
begin
try
if aDAORecord is TDAORecordTS then TDAORecordTS(aDAORecord).ModifiedDate := Now();
Result := ExecuteQuery(fQueryGenerator.Update(fModel.TableName,GetFieldsPairs(aDAORecord),
Format('%s=%s',[aDAORecord.PrimaryKey.FieldName,aDAORecord.PrimaryKey.Value])));
except
on E : Exception do raise EDAOUpdateError.CreateFmt('Update error: %s',[e.message]);
end;
end;
function TDAOQuery<T>.Update(const aFieldNames: string; const aFieldValues: array of const): Boolean;
var
stamped : Boolean;
begin
try
if TypeInfo(T) = TypeInfo(TDAORecordTS) then stamped := True;
Result := ExecuteQuery(fQueryGenerator.Update(fModel.TableName,GetFieldsPairs(aFieldNames,aFieldValues,stamped),fWhereClause));
except
on E : Exception do raise EDAOUpdateError.CreateFmt('Update error: %s',[e.message]);
end;
end;
function TDAOQuery<T>.Where(const aWhereClause: string): IDAOLinqQuery<T>;
begin
Result := Self;
fWhereClause := aWhereClause;
end;
function TDAOQuery<T>.Where(const aFormatSQLWhere: string; const aValuesSQLWhere: array of const): IDAOLinqQuery<T>;
begin
Result := Self;
fWhereClause := FormatParams(aFormatSQLWhere,aValuesSQLWhere);
end;
function TDAOQuery<T>.Delete: Boolean;
begin
try
Result := ExecuteQuery(fQueryGenerator.Delete(fModel.TableName,fWhereClause));
except
on E : Exception do raise EDAOUpdateError.CreateFmt('Delete error: %s',[e.message]);
end;
end;
end.