forked from synopse/mORMot2
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmormot.db.sql.postgres.pas
More file actions
1700 lines (1581 loc) · 59.1 KB
/
mormot.db.sql.postgres.pas
File metadata and controls
1700 lines (1581 loc) · 59.1 KB
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
/// Database Framework Direct PostgreSQL Connnection via libpq
// - this unit is a part of the Open Source Synopse mORMot framework 2,
// licensed under a MPL/GPL/LGPL three license - see LICENSE.md
unit mormot.db.sql.postgres;
{
*****************************************************************************
Direct PostgreSQL Client Access using the libpq Library
- TSqlDBPostgresConnection* and TSqlDBPostgreStatement Classes
- TSqlDBPostgresAsync Asynchronous Execution via Pipelines
*****************************************************************************
}
interface
{$I ..\mormot.defines.inc}
uses
sysutils,
classes,
variants,
mormot.core.base,
mormot.core.os,
mormot.core.unicode,
mormot.core.text,
mormot.core.buffers,
mormot.core.datetime,
mormot.core.data,
mormot.core.rtti,
mormot.core.json,
mormot.core.log,
mormot.core.threads,
mormot.net.sock,
mormot.db.core,
mormot.db.sql;
{ ************ TSqlDBPostgreConnection* and TSqlDBPostgreStatement Classes }
type
TSqlDBPostgresAsync = class;
/// connection properties which will implement an internal Thread-Safe
// connection pool for PostgreSQL using the official libpq API
TSqlDBPostgresConnectionProperties = class(TSqlDBConnectionPropertiesThreadSafe)
protected
fOids: TWordDynArray; // O(n) search in L1 cache - use SSE2 on FPC x86_64
fOidsFieldTypes: TSqlDBFieldTypeDynArray;
fOidsCount: integer;
procedure GetForeignKeys; override;
/// fill mapping of standard OID
// - at runtime mapping can be defined using Oid2FieldType() method
// - OIDs defined in DB can be retrieved using query
// "select oid, typname from pg_type where typtype = 'b' order by oid"
procedure FillOidMapping; virtual;
public
/// initialize the properties
// - raise an exception in case libpg is not thead-safe
// - aDatabaseName can be a Connection URI - see
// https://www.postgresql.org/docs/current/libpq-connect.html#LIBPQ-CONNSTRING
// - if aDatabaseName contains a connection URI with password, we recommend
// to repeat the password in aPassword parameter to prevent logging it
// (see TSqlDBConnectionProperties.DatabaseNameSafe)
// - it may be better to use environment variables and postgres config file
// for connection parameters
constructor Create(
const aServerName, aDatabaseName, aUserID, aPassword: RawUtf8); override;
/// create a new connection
// - caller is responsible of freeing this instance
// - this overridden method will create an TSqlDBPostgresConnection instance
function NewConnection: TSqlDBConnection; override;
/// add or replace mapping of OID into TSqlDBFieldType
// - in case mapping for OID is not defined, returns ftUtf8
function Oid2FieldType(cOID: cardinal): TSqlDBFieldType;
{$ifdef HASINLINE}inline;{$endif}
/// add new (or override existed) OID to FieldType mapping
procedure MapOid(cOid: cardinal; fieldType: TSqlDBFieldType);
/// get the asynchronous/pipelined engine associated with the current thread
// - to be used as Async.Prepare/PrepareLocked factory
function Async: TSqlDBPostgresAsync;
/// by default, array parameters will be sent as TEXT
// - set this property to true so that binary is sent over the wire for
// INT4ARRAYOID/INT8ARRAYOID parameters
property ArrayParamsAsBinary: boolean
index cpfArrayParamsAsBinary read GetFlag write SetFlag;
end;
/// implements a connection via the libpq access layer
// - is accessible from TSqlDBPostgresConnectionProperties
// - some additional PostgreSQL-specific pipelining methods are included
TSqlDBPostgresConnection = class(TSqlDBConnectionThreadSafe)
protected
// SQL of server-side prepared statements - name is index as hexadecimal
// - statements are already cached in TSqlDBConnection.NewStatementPrepared
fPrepared: TRawUtf8List;
fPGConn: pointer; // the associated low-level provider connection
fAsync: TSqlDBPostgresAsync;
// return statement index in fPrepared cache array
function PrepareCached(const aSql: RawUtf8; aParamCount: integer;
out aName: RawUtf8): integer;
/// direct execution of SQL statement what do not returns a result
// - statement should not contains parameters
// - raise an ESqlDBPostgres on error
procedure DirectExecSql(const SQL: RawUtf8); overload;
/// direct execution of SQL statement what do not returns a result
// - overloaded method to return a single value e.g. from a SELECT
procedure DirectExecSql(const SQL: RawUtf8; out Value: RawUtf8); overload;
/// query the pg_settings table for a given setting
function GetServerSetting(const Name: RawUtf8): RawUtf8;
public
/// finalize this connection
destructor Destroy; override;
/// connect to the specified server
// - should raise an ESqlDBPostgres on error
procedure Connect; override;
/// stop connection to the specified PostgreSQL database server
// - should raise an ESqlDBPostgres on error
procedure Disconnect; override;
/// return TRUE if Connect has been already successfully called
function IsConnected: boolean; override;
/// create a new statement instance
function NewStatement: TSqlDBStatement; override;
/// begin a Transaction for this connection
procedure StartTransaction; override;
/// commit changes of a Transaction for this connection
// - StartTransaction method must have been called before
procedure Commit; override;
/// discard changes of a Transaction for this connection
// - StartTransaction method must have been called before
procedure Rollback; override;
/// enter Pipelining mode
// - *Warning* - connection is in blocking mode, see notes about possible deadlock
// https://www.postgresql.org/docs/current/libpq-pipeline-mode.html#LIBPQ-PIPELINE-USING
procedure EnterPipelineMode;
/// exit Pipelining mode, raising an ESqlDBPostgres on error
procedure ExitPipelineMode;
/// exit Pipelining mode with no ESqlDBPostgres on error, but returning false
// - allow to retry later if needed
function TryExitPipelineMode: boolean;
/// marks a synchronization point in a pipeline by sending a sync message
// and flushing the send buffer
procedure PipelineSync;
/// flush any queued output data to the server
procedure Flush;
/// sends a request for the server to flush its output buffer
procedure SendFlushRequest;
/// return current pipeline status
function PipelineStatus: integer;
/// read PipelineSync result and check it's OK
procedure CheckPipelineSync;
/// direct access to the associated PPGconn connection
property Direct: pointer
read fPGConn;
/// how many prepared statements are currently cached for this connection
function PreparedCount: integer;
/// access to the raw socket of this connection
// - warning: over TLS, the socket state may not match the actual data state
function Socket: TNetSocket;
/// check if there is some pending input at the raw socket of this connection
// - warning: over TLS, the socket state may not match the actual data state
function SocketHasData: boolean;
end;
/// implements a statement via a Postgres database connection
TSqlDBPostgresStatement = class(TSqlDBStatementWithParamsAndColumns)
protected
fPreparedStmtName: RawUtf8; // = hexadecimal of the SQL cached index
fRes: pointer;
fResStatus: integer;
fPreparedParamsCount: integer;
// pointers to query parameters: allocated in Prepare, filled in BindParams
fPGParams: TPointerDynArray;
// PGFMT_TEXT or PGFMT_BIN: allocated in Prepare, filled in BindParams
fPGParamFormats: TIntegerDynArray;
// non zero for PGFMT_BIN params
fPGParamLengths: TIntegerDynArray;
/// define the result columns name and content - called once if cached
procedure BindColumns;
/// set parameters as expected by PostgresSQL
procedure BindParams;
/// raise an exception if Col is out of range according to fColumnCount
// or rowset is not initialized
procedure CheckColAndRowset(Col: integer);
{$ifdef HASINLINE} inline; {$endif}
public
/// finalize the statement for a given connection
destructor Destroy; override;
/// prepare an UTF-8 encoded SQL statement
// - parameters marked as ? will be bound later, before ExecutePrepared call
// - if ExpectResults is TRUE, then Step() and Column*() methods are available
// to retrieve the data rows
// - raise an ESqlDBPostgres on any error
procedure Prepare(const aSql: RawUtf8; ExpectResults: boolean = false); overload; override;
/// execute a prepared SQL statement
// - parameters marked as ? should have been already bound with Bind*() functions
// - this implementation will also handle bound array of values (if any)
// - this overridden method will log the SQL statement if sllSQL has been
// enabled in SynDBLog.Family.Level
// - raise an ESqlDBPostgres on any error
procedure ExecutePrepared; override;
/// execute a prepared SQL statement, for connection in pipelining mode
// - sends a request to execute a prepared statement with given parameters,
// without waiting for the result(s)
// - after all statements are sent, conn.SendFlushRequest should be called,
// then GetPipelineResult is able to read results in order they were sent
procedure SendPipelinePrepared;
/// retrieve next result for pipelined statement
procedure GetPipelineResult;
/// bind an array of 64-bit integer values to a parameter
// - the leftmost SQL parameter has an index of 1
// - overriden for direct assignment to the PostgreSQL client as fake JSON
procedure BindArray(Param: integer;
const Values: array of Int64); overload; override;
/// bind an array of 32-bit integer values to a parameter
// - the leftmost SQL parameter has an index of 1
// - for direct assignment to the PostgreSQL client as fake JSON
procedure BindArrayInt32(Param: integer; const Values: TIntegerDynArray);
/// bind an array of JSON values to a parameter
// - overriden for direct assignment to the PostgreSQL client
// - warning: input JSON should already be in the expected format (ftDate)
procedure BindArrayJson(Param: integer; ParamType: TSqlDBFieldType;
var JsonArray: RawUtf8; ValuesCount: integer); override;
/// gets a number of updates made by latest executed statement
function UpdateCount: integer; override;
/// reset the previous prepared statement
// - this overridden implementation will reset all bindings and the cursor state
// - raise an ESqlDBPostgres on any error
procedure Reset; override;
/// access the next or first row of data from the SQL Statement result
// - return true on success, with data ready to be retrieved by Column*() methods
// - return false if no more row is available (e.g. if the SQL statement
// is not a SELECT but an UPDATE or INSERT command)
// - if SeekFirst is TRUE, will put the cursor on the first row of results
// - raise an ESqlDBPostgres on any error
function Step(SeekFirst: boolean = false): boolean; override;
/// clear(fRes) when ISqlDBStatement is back in cache
procedure ReleaseRows; override;
/// return a Column integer value of the current Row, first Col is 0
function ColumnInt(Col: integer): int64; override;
/// returns TRUE if the column contains NULL
function ColumnNull(Col: integer): boolean; override;
/// return a Column floating point value of the current Row, first Col is 0
function ColumnDouble(Col: integer): double; override;
/// return a Column date and time value of the current Row, first Col is 0
function ColumnDateTime(Col: integer): TDateTime; override;
/// return a Column currency value of the current Row, first Col is 0
function ColumnCurrency(Col: integer): currency; override;
/// return a Column UTF-8 encoded text value of the current Row, first Col is 0
function ColumnUtf8(Col: integer): RawUtf8; override;
/// return a Column UTF-8 text buffer of the current Row, first Col is 0
// - returned pointer is likely to last only until next Reset call
function ColumnPUtf8(Col: integer): PUtf8Char; override;
/// return a Column as a blob value of the current Row, first Col is 0
function ColumnBlob(Col: integer): RawByteString; override;
/// return a Column as a variant, first Col is 0
function ColumnToVariant(Col: integer; var Value: Variant;
ForceUtf8: boolean = false): TSqlDBFieldType; override;
/// return one column value into JSON content
procedure ColumnToJson(Col: integer; W: TJsonWriter); override;
/// how many parameters founded during prepare stage
property PreparedParamsCount: integer
read fPreparedParamsCount;
end;
{ ************ TSqlDBPostgresAsync Asynchronous Execution via Pipelines }
TSqlDBPostgresAsyncStatement = class;
ESqlDBPostgresAsync = class(ESynException);
/// tune TSqlDBPostgresConnectionProperties.NewAsyncStatementPrepared()
// - asoForcePipelineSync will call PipelineSync for each ExecuteAsync
// - asoForceConnectionFlush will call Connection.Flush (for modified libpq)
TSqlDBPostgresAsyncStatementOptions = set of (
asoForcePipelineSync,
asoForceConnectionFlush);
PSqlDBPostgresAsyncStatementOptions = ^TSqlDBPostgresAsyncStatementOptions;
/// event signature for TSqlDBPostgresAsyncStatement.ExecuteAsync() callback
// - implementation should retrieve the data from Statement.Column*(), then
// process it using the opaque Context - typically a TConnectionAsyncHandle
// - is called with Statement = nil on any DB fatal error
TOnSqlDBPostgresAsyncEvent = procedure(
Statement: TSqlDBPostgresAsyncStatement; Context: PtrInt) of object;
TSqlDBPostgresAsyncTask = record
Statement: TSqlDBPostgresAsyncStatement;
Context: PtrInt;
OnFinished: TOnSqlDBPostgresAsyncEvent;
Options: TSqlDBPostgresAsyncStatementOptions;
end;
TSqlDBPostgresAsyncTasks = array of TSqlDBPostgresAsyncTask;
/// one asynchronous SQL statement as owned by TSqlDBPostgresAsync
// - this is the main entry point for pipelined process on PostgreSQL
// - within PrepareLocked/Lock and Unlock, should call Bind() then ExecuteAsync()
TSqlDBPostgresAsyncStatement = class(TSqlDBPostgresStatement)
protected
fOwner: TSqlDBPostgresAsync;
fAsyncOptions: TSqlDBPostgresAsyncStatementOptions;
public
/// ExecutePrepared-like method for asynchronous process
// - to be called within PrepareLocked/Lock and UnLock, after Bind():
// - typical usecase is e.g. from ex/techempower-bench/raw.pas
// ! function TRawAsyncServer.asyncdb(ctxt: THttpServerRequest): cardinal;
// ! begin
// ! with fDbPool.Async.PrepareLocked(WORLD_READ_SQL) do
// ! try
// ! Bind(1, ComputeRandomWorld);
// ! ExecuteAsync(ctxt.AsyncHandle, OnAsyncDb);
// ! finally
// ! UnLock;
// ! end;
// ! result := HTTP_ASYNCRESPONSE;
// ! end;
// !
// ! procedure TRawAsyncServer.OnAsyncDb(Statement: TSqlDBPostgresAsyncStatement;
// ! Context: PtrInt);
// ! begin
// ! fHttpServer.AsyncResponseFmt(Context, '{"id":%,"randomNumber":%}',
// ! [Statement.ColumnInt(0), Statement.ColumnInt(1)]);
// ! end;
procedure ExecuteAsync(Context: PtrInt;
const OnFinished: TOnSqlDBPostgresAsyncEvent;
ForcedOptions: PSqlDBPostgresAsyncStatementOptions = nil);
/// ExecutePrepared-like method for asynchronous process
// - just wrap ExecuteAsync + UnLock
procedure ExecuteAsyncNoParam(Context: PtrInt;
const OnFinished: TOnSqlDBPostgresAsyncEvent;
ForcedOptions: PSqlDBPostgresAsyncStatementOptions = nil);
/// could be used as a short-cut to Owner.Safe.Lock
procedure Lock;
{$ifdef HASINLINE}inline;{$endif}
/// could be used as a short-cut to Owner.Safe.UnLock
procedure Unlock;
{$ifdef HASINLINE}inline;{$endif}
/// the TSqlDBPostgresAsync instance owner
property Owner: TSqlDBPostgresAsync
read fOwner;
/// how this statement should behave in asynchronous mode
property AsyncOptions: TSqlDBPostgresAsyncStatementOptions
read fAsyncOptions;
end;
/// background thread in which all TSqlDBPostgresAsync results are processed
TSqlDBPostgresAsyncThread = class(TSynThread)
protected
fOwner: TSqlDBPostgresAsync;
fName: RawUtf8;
fOnThreadStart: TOnNotifyThread;
fProcessing: boolean;
procedure Execute; override;
public
/// initialize the thread
constructor Create(aOwner: TSqlDBPostgresAsync); reintroduce;
/// some event which will be called then nil in the main Execute loop
property OnThreadStart: TOnNotifyThread
read fOnThreadStart write fOnThreadStart;
end;
/// asynchronous execution engine
// - allow to execute several statements within an PostgreSQL pipeline, and
// return the results using asynchronous callbacks from a background thread
// - inherits from TSynLocked so you can use Lock/UnLock
TSqlDBPostgresAsync = class(TObjectOSLock)
protected
fConnection: TSqlDBPostgresConnection;
fStatements: array of TSqlDBPostgresAsyncStatement;
fThread: TSqlDBPostgresAsyncThread;
fTasks: TSynQueue;
procedure DoExecuteAsyncError;
public
/// initialize the execution engine
constructor Create(Owner: TSqlDBPostgresConnection); reintroduce;
/// finalize the execution engine
destructor Destroy; override;
/// return a TSqlDBPostgresAsyncStatement instance tied to this engine
// - the returned instance will be cached and owned by this TSqlDBPostgresAsync
function Prepare(const Sql: RawUtf8; ExpectResults: boolean = true;
Options: TSqlDBPostgresAsyncStatementOptions = []): TSqlDBPostgresAsyncStatement;
/// lock and return a TSqlDBPostgresAsyncStatement instance tied to this engine
// - the returned instance will be cached and owned by this TSqlDBPostgresAsync
function PrepareLocked(const Sql: RawUtf8; ExpectResults: boolean = true;
Options: TSqlDBPostgresAsyncStatementOptions = []): TSqlDBPostgresAsyncStatement;
/// the TSqlDBPostgresConnection in pipelined mode owned by this engine
// - a single dedicated connection will be used for all async statements
property Connection: TSqlDBPostgresConnection
read fConnection;
/// raw level to the background thread processing the results
property Thread: TSqlDBPostgresAsyncThread
read fThread;
end;
implementation
uses
mormot.db.raw.postgres; // raw libpq library API access
{ ************ TSqlDBPostgreConnection* and TSqlDBPostgreStatement Classes }
{ TSqlDBPostgresConnection }
destructor TSqlDBPostgresConnection.Destroy;
begin
FreeAndNil(fAsync);
inherited Destroy;
fPrepared.Free;
end;
function TSqlDBPostgresConnection.PrepareCached(
const aSql: RawUtf8; aParamCount: integer; out aName: RawUtf8): integer;
begin
if fPrepared = nil then
begin
fPrepared := TRawUtf8List.CreateEx([fCaseSensitive, fNoDuplicate]);
result := -1;
end
else
begin
result := fPrepared.IndexOf(aSql);
if result >= 0 then
begin
// never called in practice: already cached in TSqlDBConnection
aName := Int64ToHexLower(result); // statement name is index as hexa
exit; // already prepared -> we will just give the statement name to PQ
end;
end;
result := fPrepared.Add(aSql);
aName := Int64ToHexLower(result);
PQ.Check(fPGConn, 'Prepare',
PQ.Prepare(fPGConn, pointer(aName), pointer(aSql), aParamCount, nil));
end;
procedure TSqlDBPostgresConnection.DirectExecSql(const SQL: RawUtf8);
begin
PQ.Check(fPGConn, 'Exec',
PQ.Exec(fPGConn, pointer(SQL)));
end;
procedure TSqlDBPostgresConnection.DirectExecSql(
const SQL: RawUtf8; out Value: RawUtf8);
var
res: PPGresult;
begin
res := PQ.Exec(fPGConn, pointer(SQL));
PQ.Check(fPGConn, 'Exec', res, nil, {andclear=}false);
PQ.GetRawUtf8(res, 0, 0, Value);
PQ.Clear(res);
end;
function TSqlDBPostgresConnection.GetServerSetting(const Name: RawUtf8): RawUtf8;
var
sql: RawUtf8;
begin
FormatUtf8('select setting from pg_settings where name=''%''', [Name], sql);
DirectExecSql(sql, result);
end;
// our conversion is faster than PQUnescapeByteA - which requires libpq 8.3+
// and calls malloc()
// https://github.com/postgres/postgres/blob/master/src/interfaces/libpq/fe-exec.c
// checking \x for hexadecimal encoding is what UnescapeByteA() does
// -> no need to ask server settings
// note: bytea_output is HEX by default (at least since PostgreSQL 9.0)
function BlobInPlaceDecode(P: PAnsiChar; PLen: integer): integer;
begin
if (P = nil) or
(PLen <= 0) then
result := 0
else if PWord(P)^ = ord('\') + ord('x') shl 8 then {ssByteAasHex in fServerSettings}
begin
result := (PLen - 2) shr 1; // skip trailing \x and compute number of bytes
if result > 0 then
HexToBinFast(P + 2, PByte(P), result); // in-place conversion
end
else
// oldest PostgreSQL versions may stil use octal encoding (unlikely)
result := OctToBin(P, pointer(P)); // in-place conversion
end;
procedure SynLogNoticeProcessor({%H-}arg: pointer; message: PUtf8Char); cdecl;
begin
SynDBLog.Add.Log(sllTrace, 'PGINFO: %', [message], TObject(arg));
end;
procedure DummyNoticeProcessor({%H-}arg: pointer; message: PUtf8Char); cdecl;
begin
end;
procedure TSqlDBPostgresConnection.Connect;
var
log: ISynLog;
host, port: RawUtf8;
begin
SynDBLog.EnterLocal(log, self, 'Connect');
Disconnect; // force fTrans=fError=fServer=fContext=nil
try
Split(Properties.ServerName, ':', host, port);
fPGConn := PQ.SetDBLogin(pointer(host), pointer(port), nil, nil,
pointer(Properties.DatabaseName), pointer(Properties.UserID),
pointer(Properties.PassWord));
if PQ.Status(fPGConn) = CONNECTION_BAD then
ESqlDBPostgres.RaiseUtf8('Connection to database % failed [%]',
[Properties.DatabaseNameSafe, PQ.ErrorMessage(fPGConn)]);
// if GetServerSetting('bytea_output') = 'HEX' then
// include(fServerSettings, ssByteAasHex);
if log <> nil then
begin
PQ.SetNoticeProcessor(fPGConn, SynLogNoticeProcessor, pointer(self));
log.Log(sllDB, 'Connected to % % using % v%', [fProperties.ServerName,
fProperties.DatabaseNameSafe, PQ.LibraryPath, PQ.LibVersion], self);
end
else
// to ensure no performance drop due to notice to console
PQ.SetNoticeProcessor(fPGConn, DummyNoticeProcessor, nil);
inherited Connect; // notify any re-connection
except
on E: Exception do
begin
if log <> nil then
log.Log(sllError, 'Connect: % on %',
[E, Properties.DatabaseNameSafe], self);
Disconnect; // clean up on fail
raise;
end;
end;
end;
procedure TSqlDBPostgresConnection.Disconnect;
begin
try
inherited Disconnect;
finally
// any prepared statements will be released with this connection
if fPrepared <> nil then
fPrepared.Clear;
// let PG driver finish the connection
if fPGConn <> nil then
begin
PQ.Finish(fPGConn);
fPGConn := nil;
end;
end;
end;
function TSqlDBPostgresConnection.IsConnected: boolean;
begin
result := (fPGConn <> nil);
end;
function TSqlDBPostgresConnection.NewStatement: TSqlDBStatement;
begin
result := TSqlDBPostgresStatement.Create(self);
end;
procedure TSqlDBPostgresConnection.StartTransaction;
var
log: ISynLog;
begin
SynDBLog.EnterLocal(log, self, 'StartTransaction');
if TransactionCount > 0 then
ESqlDBPostgres.RaiseUtf8('Invalid %.StartTransaction: nested transactions' +
' are not supported by Postgres - use SAVEPOINT instead', [self]);
try
inherited StartTransaction;
DirectExecSql('START TRANSACTION');
except
on E: Exception do
begin
if log <> nil then
log.Log(sllError, 'StartTransaction: % on %',
[E, Properties.DatabaseNameSafe], self);
if fTransactionCount > 0 then
Dec(fTransactionCount);
raise;
end;
end;
end;
procedure TSqlDBPostgresConnection.Commit;
begin
inherited Commit;
try
DirectExecSql('COMMIT');
except
inc(fTransactionCount); // the transaction is still active
raise;
end;
end;
procedure TSqlDBPostgresConnection.Rollback;
begin
inherited;
DirectExecSql('ROLLBACK');
end;
procedure TSqlDBPostgresConnection.EnterPipelineMode;
begin
if not Assigned(PQ.enterPipelineMode) then
ESqlDBPostgres.RaiseUtf8('%.EnterPipelineMonde: pipelining unsupported in % v%',
[self, PQ.LibraryPath, PQ.LibVersion]);
if PQ.enterPipelineMode(fPGConn) <> PGRES_COMMAND_OK then
PQ.RaiseError(fPGConn, 'EnterPipelineMonde');
end;
procedure TSqlDBPostgresConnection.ExitPipelineMode;
begin
if PQ.exitPipelineMode(fPGConn) <> PGRES_COMMAND_OK then
PQ.RaiseError(fPGConn, 'ExitPipelineMode');
if PQ.pipelineStatus(fPGConn) <> PQ_PIPELINE_OFF then
PQ.RaiseError(fPGConn, 'ExitPipelineMode status');
end;
function TSqlDBPostgresConnection.TryExitPipelineMode: boolean;
begin
result := (PQ.exitPipelineMode(fPGConn) = PGRES_COMMAND_OK) and
(PQ.pipelineStatus(fPGConn) = PQ_PIPELINE_OFF);
end;
procedure TSqlDBPostgresConnection.PipelineSync;
begin
if PQ.pipelineSync(fPGConn) <> PGRES_COMMAND_OK then
PQ.RaiseError(fPGConn, 'PipelineSync');
end;
procedure TSqlDBPostgresConnection.Flush;
begin
PQ.flush(fPGConn);
end;
procedure TSqlDBPostgresConnection.SendFlushRequest;
begin
if PQ.sendFlushRequest(fPGConn) <> PGRES_COMMAND_OK then
PQ.RaiseError(fPGConn, 'SendFlushRequest');
end;
function TSqlDBPostgresConnection.PipelineStatus: integer;
begin
Result := PQ.pipelineStatus(fPGConn);
end;
procedure TSqlDBPostgresConnection.CheckPipelineSync;
var
res: pointer;
err: integer;
begin
res := PQ.getResult(fPGConn);
PQ.Check(fPGConn, 'GetResult', res, @res, {andclear=}false);
err := PQ.ResultStatus(res);
if err <> PGRES_PIPELINE_SYNC then
ESqlDBPostgres.RaiseUtf8(
'%.CheckPipelineSync returned % instead of PGRES_PIPELINE_SYNC [%] ',
[self, err, PQ.ErrorMessage(fPGConn)])
else
PQ.Clear(res);
end;
function TSqlDBPostgresConnection.PreparedCount: integer;
begin
if (self = nil) or
(fPrepared = nil) then
result := 0
else
result := fPrepared.Count;
end;
function TSqlDBPostgresConnection.Socket: TNetSocket;
begin
if (self = nil) or
not Assigned(PQ.socket) then
result := nil
else
result := pointer(PtrUInt(PQ.socket(fPGConn))); // transtype to our wrapper
end;
function TSqlDBPostgresConnection.SocketHasData: boolean;
begin
result := Socket.HasData > 0;
end;
{ TSqlDBPostgresConnectionProperties }
procedure TSqlDBPostgresConnectionProperties.GetForeignKeys;
begin
// TODO - how to get field we reference to? (currently consider this is "ID")
with Execute('SELECT ct.conname as foreign_key_name, ' +
' case when ct.condeferred then 1 else 0 end as is_disabled, ' +
'(SELECT tc.relname from pg_class tc ' +
'where tc.oid = ct.conrelid) || ''.'' || ' +
'(SELECT a.attname FROM pg_attribute a WHERE a.attnum = ' +
'ct.conkey[1] AND a.attrelid = ct.conrelid) as from_ref, ' +
'(SELECT tc.relname from pg_class tc where tc.oid = ' +
'ct.confrelid) || ''.id'' as referenced_object ' +
'FROM pg_constraint ct WHERE contype = ''f''', []) do
while Step do
fForeignKeys.Add(ColumnUtf8(2), ColumnUtf8(3));
end;
procedure TSqlDBPostgresConnectionProperties.FillOidMapping;
begin
// see pg_type.h (most used first)
MapOid(INT4OID, ftInt64);
MapOid(INT8OID, ftInt64);
MapOid(TEXTOID, ftUtf8); // other char types will be ftUtf8 as fallback
MapOid(FLOAT8OID, ftDouble);
MapOid(TIMESTAMPOID, ftDate);
MapOid(BYTEAOID, ftBlob);
MapOid(NUMERICOID, ftCurrency); // our ORM uses NUMERIC(19,4) for currency
MapOid(BOOLOID, ftInt64);
MapOid(INT2OID, ftInt64);
MapOid(CASHOID, ftCurrency);
MapOid(TIMESTAMPTZOID, ftDate);
MapOid(ABSTIMEOID, ftDate);
MapOid(DATEOID, ftDate);
MapOid(TIMEOID, ftDate);
MapOid(TIMETZOID, ftDate);
MapOid(REGPROCOID, ftInt64);
MapOid(OIDOID, ftInt64);
MapOid(FLOAT4OID, ftDouble);
// note: any other unregistered OID will be handled as ftUtf8 to keep the data
end;
constructor TSqlDBPostgresConnectionProperties.Create(
const aServerName, aDatabaseName, aUserID, aPassword: RawUtf8);
begin
PostgresLibraryInitialize; // raise an ESqlDBPostgres on loading failure
if PQ.IsThreadSafe <> 1 then
ESqlDBPostgres.RaiseU('libpq should be compiled in threadsafe mode');
fDbms := dPostgreSQL;
FillOidMapping;
inherited Create(aServerName, aDatabaseName, aUserID, aPassWord);
// JsonDecodedPrepareToSql will detect cPostgreBulkArray and set
// DecodedFieldTypesToUnnest -> fast bulk insert/delete/update
fBatchSendingAbilities := [cCreate, cDelete, cUpdate, cPostgreBulkArray];
NoBlobBindArray := true; // no BindArray() on ftBlob
// disable MultiInsert SQL and rely on cPostgreBulkArray process for cCreate
fOnBatchInsert := nil; // see TRestStorageExternal.InternalBatchStop
end;
function TSqlDBPostgresConnectionProperties.NewConnection: TSqlDBConnection;
var
conn: TSqlDBPostgresConnection;
begin
conn := TSqlDBPostgresConnection.Create(self);
conn.InternalProcess(speCreated);
result := conn;
end;
function TSqlDBPostgresConnectionProperties.Oid2FieldType(
cOID: cardinal): TSqlDBFieldType;
var
i: PtrInt;
begin
if cOID <= 65535 then
begin
// fast brute force search within L1 CPU cache (use SSE2 asm on Intel/AMD)
i := WordScanIndex(pointer(fOids), fOidsCount, cOID);
if i >= 0 then
result := fOidsFieldTypes[i]
else
result := ftUtf8;
end
else
result := ftUtf8;
end;
procedure TSqlDBPostgresConnectionProperties.MapOid(cOid: cardinal;
fieldType: TSqlDBFieldType);
var
i: PtrInt;
begin
if cOID > 65535 then
ESqlDBPostgres.RaiseUtf8('Out of range %.MapOid(%)', [self, cOID]);
i := WordScanIndex(pointer(fOids), fOidsCount, cOID); // may use SSE2
if i < 0 then
begin
i := FOidsCount;
inc(FOidsCount);
if i = length(FOids) then
begin
SetLength(fOids, i + 32);
SetLength(fOidsFieldTypes, i + 32);
end;
fOids[i] := cOid;
end;
fOidsFieldTypes[i] := fieldType // set or replace
end;
function TSqlDBPostgresConnectionProperties.Async: TSqlDBPostgresAsync;
var
main: TSqlDBPostgresConnection;
begin
main := pointer(ThreadSafeConnection);
if main.fAsync = nil then // no lock needed since it is a per-thread instance
main.fAsync := TSqlDBPostgresAsync.Create(main); // it is time to setup
result := main.fAsync;
end;
{ TSqlDBPostgresStatement }
procedure TSqlDBPostgresStatement.BindColumns;
var
nCols, c: integer;
cName: RawUtf8;
p: PUtf8Char;
begin
ClearColumns;
nCols := PQ.nfields(fRes);
fColumn.Capacity := nCols;
for c := 0 to nCols - 1 do
begin
p := PQ.fname(fRes, c);
FastSetString(cName, p, mormot.core.base.StrLen(p));
with AddColumn(cName)^ do
begin
ColumnAttr := PQ.ftype(fRes, c);
ColumnType := TSqlDBPostgresConnectionProperties(Connection.Properties).
Oid2FieldType(ColumnAttr);
end;
end;
end;
var // fake VArray markers
_BindArrayJson, _BindArrayBin4, _BindArrayBin8: TRawUtf8DynArray;
function ComputeBinaryArray(p: PSqlDBParam; size: integer): boolean;
var
bin: RawByteString;
begin
result := ToArrayOid(pointer(p^.VData), p^.VDBType, p^.VInt64, size, bin);
if result then
p^.VData := bin;
end;
procedure TSqlDBPostgresStatement.BindParams;
var
i: PtrInt;
p: PSqlDBParam;
begin
// mark parameter as textual by default, with no blob length
FillCharFast(pointer(fPGParams)^, fParamCount shl POINTERSHR, 0);
FillCharFast(pointer(fPGParamFormats)^, fParamCount shl 2, PGFMT_TEXT);
FillCharFast(pointer(fPGParamLengths)^, fParamCount shl 2, 0);
// bind fParams[] as expected by PostgreSQL - potentially as array
p := pointer(fParams);
for i := 0 to fParamCount - 1 do
begin
if p^.VArray <> nil then
begin
// convert array parameter values into p^.VData text or bin
if not (p^.VType in [
ftInt64,
ftDouble,
ftCurrency,
ftDate,
ftUtf8]) then
ESqlDBPostgres.RaiseUtf8('%.ExecutePrepared: Invalid array ' +
'type % on bound parameter #%', [self, ToText(p^.VType)^, i]);
if p^.VArray[0] <> _BindArrayJson[0] then
// p^.VData is not the array encoded as PostgreSQL pseudo-JSON {....}
if (p^.VArray[0] = _BindArrayBin4[0]) and
ComputeBinaryArray(p, ord(p^.VArray[1][1]) - ord('0')) then
begin
// p^.VData is the raw integer/Int64 array as Postgres binary
fPGParamFormats[i] := PGFMT_BIN;
fPGParamLengths[i] := length(p^.VData);
end
else
// p^.VData was not already set by BindArrayJson() -> convert now
BoundArrayToJsonArray(p^.VArray, RawUtf8(p^.VData)); // e.g. '{1,2,3}'
end
else
// single value parameter
case p^.VType of
ftNull:
p^.VData := '';
ftInt64:
case p^.VDBType of
INT4OID: // ORM create such fields for 32-bit values (ftUnknown)
begin
fPGParamFormats[i] := PGFMT_BIN;
fPGParamLengths[i] := 4;
p^.VInt64 := bswap32(p^.VInt64); // libpq expects network order
fPGParams[i] := @p^.VInt64;
end;
INT8OID: // ORM create such fields for 64-bit values (ftInt64)
begin
fPGParamFormats[i] := PGFMT_BIN;
fPGParamLengths[i] := 8;
p^.VInt64 := bswap64(p^.VInt64);
fPGParams[i] := @p^.VInt64;
end;
else
Int64ToUtf8(p^.VInt64, RawUtf8(p^.VData));
end;
ftCurrency:
Curr64ToStr(p^.VInt64, RawUtf8(p^.VData));
ftDouble:
if p^.VDBType = FLOAT8OID then // ORM create such fields for ftDouble
begin
fPGParamFormats[i] := PGFMT_BIN;
fPGParamLengths[i] := 8;
p^.VInt64 := bswap64(p^.VInt64); // double also in network order!
fPGParams[i] := @p^.VInt64;
end
else
DoubleToStr(PDouble(@p^.VInt64)^, RawUtf8(p^.VData));
ftDate:
// libpq expects space instead of T in ISO-8601 expanded format
DateTimeToIso8601Var(PDateTime(@p^.VInt64)^, {expand=}true,
dsfForceDateWithMS in fFlags, ' ', #0, RawUtf8(p^.VData));
ftUtf8:
; // UTF-8 text already in p^.VData buffer
ftBlob:
begin
fPGParamFormats[i] := PGFMT_BIN;
fPGParamLengths[i] := length(p^.VData);
end;
else
ESqlDBPostgres.RaiseUtf8('%.ExecutePrepared: cannot bind ' +
'parameter #% of type %', [self, i, ToText(p^.VType)^]);
end;
if fPGParams[i] = nil then
fPGParams[i] := pointer(p^.VData);
inc(p);
end;
end;
procedure TSqlDBPostgresStatement.CheckColAndRowset(Col: integer);
begin
if (cardinal(Col) >= cardinal(fColumnCount)) or
(fRes = nil) or
(fResStatus <> PGRES_TUPLES_OK) then
CheckColInvalid(Col);
end;
destructor TSqlDBPostgresStatement.Destroy;
begin
try
Reset; // close result if any
finally
inherited;
end;
end;
// see https://www.postgresql.org/docs/current/libpq-exec.html
procedure TSqlDBPostgresStatement.Prepare(
const aSql: RawUtf8; ExpectResults: boolean);
var
i: PtrInt;
res: PPGresult;
c: TSqlDBPostgresConnection;
begin
// it is called once: already cached in TSqlDBConnection.NewStatementPrepared
SqlLogBegin(sllDB);
if aSql = '' then
ESqlDBPostgres.RaiseUtf8('%.Prepare: empty statement', [self]);
inherited Prepare(aSql, ExpectResults); // will strip last ;
fPreparedParamsCount := ReplaceParamsByNumbers(fSql, fSqlPrepared, '$');
if scPossible in fCache then
begin
// preparable statements will be cached server-side by index hexa as name
include(fCache, scOnServer);
c := TSqlDBPostgresConnection(fConnection);
c.PrepareCached(fSqlPrepared, fPreparedParamsCount, fPreparedStmtName);
// get param types into VDBType for possible binary binding in BindParams
if fPreparedParamsCount > 0 then
begin
fParam.Count := fPreparedParamsCount;
res := PQ.DescribePrepared(c.fPGConn, pointer(fPreparedStmtName));
PQ.Check(c.fPGConn, 'DescribePrepared', res, nil, {andclear=}false);
for i := 0 to fPreparedParamsCount - 1 do
fParams[i].VDBType := PQ.ParamType(res, i);
PQ.Clear(res);
end;
SqlLogEnd(' c=%', [fPreparedStmtName]);
end
else
SqlLogEnd;
// allocate libpq parameter buffers as dynamic arrays - reused when cached
SetLength(fPGParams, fPreparedParamsCount);
SetLength(fPGParamFormats, fPreparedParamsCount);
SetLength(fPGParamLengths, fPreparedParamsCount);
end;
procedure TSqlDBPostgresStatement.ExecutePrepared;
var
c: TSqlDBPostgresConnection;
begin