This repository has been archived by the owner on Jul 20, 2023. It is now read-only.
-
-
Notifications
You must be signed in to change notification settings - Fork 19
/
PostgreSQLClient.gd
1911 lines (1405 loc) · 64.6 KB
/
PostgreSQLClient.gd
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
# Lience MIT
# Written by Samuel MARZIN
# Detailed documentation: https://github.com/Marzin-bot/PostgreSQLClient/wiki/Documentation
extends Object
## Godot PostgreSQL Client is a GDscript script/class that allows you to connect to a Postgres backend and run SQL commands there.
## It is able to send data and receive it from the backend. Useful for managing player user data on a multiplayer game, by saving a large amount of data on a dedicated Postgres server from GDscript.
## The class is written in pure GDScript which allows it not to depend on GDNative. This makes it ultra portable for many platforms.
class_name PostgreSQLClient
## Version number (minor.major) of the PostgreSQL protocol used when connecting to the backend.
const PROTOCOL_VERSION := 3.0
## Backend runtime parameters
## A dictionary that contains various information about the state of the server.
## For security reasons the dictionary is always empty if the frontend is disconnected from the backend and updates once the connection is established.
var parameter_status := {}
## Enemeration the statuts of the connection.
enum Status {
STATUS_DISCONNECTED, ## A status representing a PostgreSQLClient that is disconnected.
STATUS_CONNECTING, ## A status representing a PostgreSQLClient that is connecting to a host.
STATUS_CONNECTED, ## A status representing a PostgreSQLClient that is connected to a host.
STATUS_ERROR ## A status representing a PostgreSQLClient in error state.
}
# The statut of the connection.
var status = Status.STATUS_DISCONNECTED setget set_status, get_status
## Returns the status of the connection (see the Status enumeration).
func get_status() -> int:
return status
func set_status(_value) -> void:
# The value of the "status" variable can only be modified locally.
pass
var password_global: String
var user_global: String
var client := StreamPeerTCP.new()
var peerstream := PacketPeerStream.new()
var stream_peer_ssl = StreamPeerSSL.new()
var peer: StreamPeer
func _init() -> void:
peerstream.set_stream_peer(client)
peer = peerstream.stream_peer
## Fires when the connection to the backend closes.
## was_clean_close is true if the connection was closed correctly otherwise false.
signal connection_closed(was_clean_close)
# No use
#signal connection_error() # del /!\
## Triggered when the authentication process failed during contact with the target backend.
## The error_object parameter is a dictionary that contains various information during the nature of the error.
signal authentication_error(error_object)
## Trigger when the connection between the frontend and the backend is established.
## This is usually a good time to start making requests to the backend with execute ().
signal connection_established
#signal data_received
################## No use at the moment ###############
## The process ID of this backend.
var process_backend_id: int
################## No use at the moment ###############
## The secret key of this backend.
var process_backend_secret_key: int
var status_ssl = 0
var global_url = ""
var startup_message: PoolByteArray
var next_etape := false
var con_ssl: bool
## Allows you to connect to a Postgresql backend at the specified url.
func connect_to_host(url: String, ssl := false, connect_timeout := 30) -> int:
global_url = url
con_ssl = ssl
var error := 1
# If the fontend was already connected to the backend, we disconnect it before reconnecting.
if status == Status.STATUS_CONNECTED:
close(false)
var regex = RegEx.new()
# https://www.postgresql.org/docs/current/libpq-connect.html#LIBPQ-CONNSTRING
regex.compile("^(?:postgresql|postgres)://(.+):(.+)@(.+):(\\d*)/(.+)")
var result = regex.search(url)
if result:
### StartupMessage ###
# "postgres" is the database and user by default.
startup_message = request("", "user".to_ascii() + PoolByteArray([0]) + result.strings[1].to_utf8() + PoolByteArray([0]) + "database".to_ascii() + PoolByteArray([0]) + result.strings[5].to_utf8() + PoolByteArray([0, 0]))
password_global = result.strings[2]
user_global = result.strings[1]
# The default port for postgresql.
var port = 5432
if result.strings[4]:
port = int(result.strings[4])
if stream_peer_ssl.get_status() == stream_peer_ssl.STATUS_CONNECTED:
stream_peer_ssl.put_data(startup_message)
else:
if not client.is_connected_to_host() and client.get_status() == StreamPeerTCP.STATUS_NONE:
error = client.connect_to_host(result.strings[3], port)
#if (error == OK)
# Get the fist message of server.
if error == OK:
next_etape = true
else:
print("[PostgreSQLClient:%d] Invalid host Postgres." % [get_instance_id()])
else:
status = Status.STATUS_ERROR
push_error("[PostgreSQLClient:%d] Invalid Postgres URL." % [get_instance_id()])
return error
## A dictionary which contains various information on the execution errors of the last requests made on the backend (usually after using the execute() method).
## If the dictionary is empty, it means that the backend did not detect any error in the query.
## Should be used ideally after each use of the execute() method.
## For security reasons, the dictionary is empty when the frontend is not connected to the backend.
var error_object := {}
## Allows you to close the connection with the backend.
## If clean_closure is true, the frontend will notify the backend that it requests to close the connection.
## If false, the frontend forcibly closes the connection without notifying the backend (not recommended sof in exceptional cases).
## Has no effect if the frontend is not already connected to the backend.
func close(clean_closure := true) -> void:
if status == Status.STATUS_CONNECTED:
### Terminate ###
# Identifies the message as a termination.
if stream_peer_ssl.get_status() == stream_peer_ssl.STATUS_HANDSHAKING or stream_peer_ssl.get_status() == stream_peer_ssl.STATUS_CONNECTED:
# Deconnection ssl
if clean_closure:
stream_peer_ssl.put_data(request('X', PoolByteArray()))
stream_peer_ssl.disconnect_from_stream()
else:
if clean_closure:
var _unused = peer.put_data(request('X', PoolByteArray()))
client.disconnect_from_host()
# For security reasons, the dictionary is empty when the frontend is not connected to the backend.
parameter_status = {}
# For security reasons, the dictionary is empty when the frontend is not connected to the backend.
error_object = {}
status = Status.STATUS_DISCONNECTED
next_etape = false
status_ssl = 0
emit_signal("connection_closed", clean_closure)
else:
push_warning("[PostgreSQLClient:%d] The fontend was already disconnected from the backend when calling close()." % [get_instance_id()])
## Allows to send an SQL string to the backend that should run.
## The sql parameter can contain one or more valid SQL statements.
## Returns an Array of PostgreSQLQueryResult. (Can be empty)
## There are as many PostgreSQLQueryResult elements in the array as there are SQL statements in sql (sof in exceptional cases).
func execute(sql: String) -> Array:
if status == Status.STATUS_CONNECTED:
var _unused
var request := request('Q', sql.to_utf8() + PoolByteArray([0]))
if stream_peer_ssl.get_status() == stream_peer_ssl.STATUS_CONNECTED:
stream_peer_ssl.put_data(request)
else:
_unused = peer.put_data(request)
while client.is_connected_to_host() and client.get_status() == StreamPeerTCP.STATUS_CONNECTED and status == Status.STATUS_CONNECTED:
var reponce := [OK, PoolByteArray()]
if stream_peer_ssl.get_status() == stream_peer_ssl.STATUS_CONNECTED:
stream_peer_ssl.poll()
if stream_peer_ssl.get_available_bytes():
reponce = stream_peer_ssl.get_data(stream_peer_ssl.get_available_bytes()) # I don't know why it crashes when this value (stream_peer_ssl.get_available_bytes()) is equal to 0 so I pass it a condition. It is probably a Godot bug.
else:
continue
else:
reponce = peer.get_data(peer.get_available_bytes())
if reponce[0] == OK:
var result = reponce_parser(reponce[1])
if result != null:
return result
else:
push_warning("[PostgreSQLClient:%d] The backend did not send any data or there must have been a problem while the backend sent a response to the request." % [get_instance_id()])
else:
push_error("[PostgreSQLClient:%d] The frontend is not connected to backend." % [get_instance_id()])
return []
## Upgrade the connexion to SSL.
func set_ssl_connection() -> void:
var _unused
if stream_peer_ssl.get_status() == StreamPeerSSL.STATUS_HANDSHAKING or stream_peer_ssl.get_status() == StreamPeerSSL.STATUS_CONNECTED:
push_warning("[PostgreSQLClient:%d] The connection is already secured with TLS/SSL." % [get_instance_id()])
elif client.get_status() == StreamPeerTCP.STATUS_CONNECTED:
### SSLRequest ###
var buffer := StreamPeerBuffer.new()
# Length of message contents in bytes, including self.
_unused = buffer.put_data(get_32byte_invert(8, true))
# The SSL request code.
# The value is chosen to contain 1234 in the most significant 16 bits, and 5679 in the least significant 16 bits. (To avoid confusion, this code must not be the same as any protocol version number.)
_unused = buffer.put_data(get_32byte_invert(80877103))
_unused = peer.put_data(buffer.data_array)
status_ssl = 1
else:
push_error("[PostgreSQLClient:%d] The frontend is not connected to backend." % [get_instance_id()])
##### No use #####
## Upgrade the connexion to GSSAPI.
func set_gssapi_connection() -> void:
var _unused
if client.get_status() == StreamPeerTCP.STATUS_CONNECTED:
### GSSENCRequest ###
var buffer := StreamPeerBuffer.new()
# Length of message contents in bytes, including self.
_unused = buffer.put_data(get_32byte_invert(8, true))
# The GSSAPI Encryption request code.
# The value is chosen to contain 1234 in the most significant 16 bits, and 5680 in the least significant 16 bits. (To avoid confusion, this code must not be the same as any protocol version number.)
_unused = buffer.put_data(get_32byte_invert(80877104))
_unused = peer.put_data(buffer.data_array)
else:
push_error("[PostgreSQLClient:%d] The frontend is not connected to backend." % [get_instance_id()])
## This function undoes all changes made to the database since the last Commit.
func rollback(process_id: int, process_key: int) -> void:
### CancelRequest ###
var _unused
if status == Status.STATUS_CONNECTED:
var buffer := StreamPeerBuffer.new()
# Length of message contents in bytes, including self.
buffer.put_u32(16)
var message_length := buffer.data_array
message_length.invert()
_unused = buffer.put_data(message_length)
# The cancel request code.
# The value is chosen to contain 1234 in the most significant 16 bits, and 5678 in the least 16 significant bits. (To avoid confusion, this code must not be the same as any protocol version number.)
_unused = buffer.put_data(get_32byte_invert(80877102))
# The process ID of the target backend.
buffer.put_u32(process_id)
# The secret key for the target backend.
buffer.put_u32(process_key)
_unused = peer.put_data(buffer.data_array.subarray(4, -1))
else:
push_error("[PostgreSQLClient:%d] The frontend is not connected to backend." % [get_instance_id()])
## Poll the connection to check for incoming messages.
## Ideally, it should be called before PostgreSQLClient.execute() for it to work properly and called frequently in a loop.
func poll() -> void:
var _unused
if stream_peer_ssl.get_status() == stream_peer_ssl.STATUS_HANDSHAKING or stream_peer_ssl.get_status() == stream_peer_ssl.STATUS_CONNECTED:
stream_peer_ssl.poll()
if client.is_connected_to_host():
if client.get_status() == StreamPeerTCP.STATUS_CONNECTED:
if next_etape:
if con_ssl:
### SSLRequest ###
set_ssl_connection()
else:
_unused = peer.put_data(startup_message)
startup_message = PoolByteArray()
next_etape = false
if status_ssl == 1:
var response = peer.get_data(peer.get_available_bytes())
if response[0] == OK:
if not response[1].empty():
match char(response[1][0]):
'S':
#var crypto = Crypto.new()
#var ssl_key = crypto.generate_rsa(4096)
#var ssl_cert = crypto.generate_self_signed_certificate(ssl_key)
stream_peer_ssl.connect_to_stream(peer)
# stream_peer_ssl.blocking_handshake = false
status_ssl = 2
'N':
status = Status.STATUS_ERROR
push_error("[PostgreSQLClient:%d] The connection attempt failed. The backend does not want to establish a secure SSL/TLS connection." % [get_instance_id()])
close(false)
var value:
status = Status.STATUS_ERROR
push_error("[PostgreSQLClient:%d] The backend sent an unknown response to the request to establish a secure connection. Response is not recognized: '%c'." % [get_instance_id(), value])
close(false)
else:
push_warning("[PostgreSQLClient:%d] The backend did not send any data or there must have been a problem while the backend sent a response to the request." % [get_instance_id()])
if status_ssl == 2 and stream_peer_ssl.get_status() == stream_peer_ssl.STATUS_CONNECTED:
_unused = connect_to_host(global_url, false)
status_ssl = 3
if status_ssl != 1 and status_ssl != 2 and not status == Status.STATUS_CONNECTED and client.get_status() == StreamPeerTCP.STATUS_CONNECTED:
var reponce: Array
if status_ssl == 0:
reponce = peer.get_data(peer.get_available_bytes())
else:
reponce = stream_peer_ssl.get_data(stream_peer_ssl.get_available_bytes())
if reponce[0] == OK and reponce[1].size():
var servire = reponce_parser(reponce[1])
if servire:
if status_ssl == 0:
_unused = peer.put_data(servire)
else:
stream_peer_ssl.put_data(servire)
func request(type_message: String, message := PoolByteArray()) -> PoolByteArray:
var _unused
# Get the size of message.
var buffer := StreamPeerBuffer.new()
buffer.put_u32(message.size() + (4 if type_message else 8))
var message_length := buffer.data_array
message_length.invert()
# If the message is not StartupMessage...
if type_message:
buffer.put_u8(ord(type_message))
_unused = buffer.put_data(message_length)
# If the message is StartupMessage...
if not type_message:
# Version parsing
var protocol_major_version = int(PROTOCOL_VERSION)
var protocol_minor_version = protocol_major_version - PROTOCOL_VERSION
for char_number in str(protocol_major_version).pad_zeros(2) + str(protocol_minor_version).pad_zeros(2):
_unused = buffer.put_data(PoolByteArray([int(char_number)]))
_unused = buffer.put_data(message)
error_object = {}
return buffer.data_array.subarray(4, -1)
static func get_32byte_invert(integer: int, unsigned := false) -> PoolByteArray:
var buffer := StreamPeerBuffer.new()
if unsigned:
buffer.put_u32(integer)
else:
buffer.put_32(integer)
var bytes := buffer.data_array
bytes.invert()
return bytes
static func split_pool_byte_array(pool_byte_array: PoolByteArray, delimiter: int) -> Array:
var array := []
var from := 0
var to := 0
for byte in pool_byte_array:
if byte == delimiter:
array.append(pool_byte_array.subarray(from, to))
from = to + 1
to += 1
return array
static func pbkdf2(hash_type: int, password: PoolByteArray, salt: PoolByteArray, iterations := 4096, length := 0) -> PoolByteArray:
var crypto := Crypto.new()
var hash_length := len(crypto.hmac_digest(hash_type, salt, password))
if length == 0:
length = hash_length
var output := PoolByteArray()
var block_count := ceil(float(length) / hash_length)
var buffer := PoolByteArray()
buffer.resize(4)
var block := 1
while block <= block_count:
buffer[0] = (block >> 24) & 0xFF
buffer[1] = (block >> 16) & 0xFF
buffer[2] = (block >> 8) & 0xFF
buffer[3] = block & 0xFF
var key_1 := crypto.hmac_digest(hash_type, password, salt + buffer)
var key_2 := key_1
for _index in iterations - 1:
key_1 = crypto.hmac_digest(hash_type, password, key_1)
for index in key_1.size():
key_2[index] ^= key_1[index]
output += key_2
block += 1
return output.subarray(0, hash_length - 1)
enum DataTypePostgreSQL {
BOOLEAN = 16,
SMALLINT = 21,
INTEGER = 23,
BIGINT = 20,
REAL = 700,
DOUBLE_PRECISION = 701,
TEXT = 25,
CHARACTER = 1042, # Alias CHAR.
CHARACTER_VARYING = 1043, # Alias VARCHAR.
JSON = 114,
JSONB = 3802,
XML = 142,
BITEA = 17,
CIDR = 650,
INET = 869,
MACADDR = 829,
MACADDR8 = 774,
BIT = 1560,
BIT_VARYING = 1562,
UUID = 2950,
POINT = 600,
BOX = 603,
LSEG = 601,
LINE = 628,
CIRCLE = 718,
DATE = 1082,
TIME = 1266
}
## The PostgreSQLQueryResult class is a subclass of PostgreSQLClient which is not intended to be created manually.
## It represents the result of an SQL query and provides an information and method report to use the result of the query.
## It is usually returned by the PostgreSQLClient.execute() method in an array of PostgreSQLQueryResult.
class PostgreSQLQueryResult:
## Specifies the number of fields in a row (can be zero).
var number_of_fields_in_a_row := 0
## An array that contains dictionaries.
## These dictionaries represent the description of the rows where the query was executed.
## The number of dictionary depends on the number of fields resulting from the result of the query which was executed.
var row_description := []
## An Array that contains sub-arrays.
## These sub-arrays represent for most of the queries the rows of the table where the query was executed.
## The number of sub-tables depends on the query that has been made.
## These sub-arrays contain as many elements as number_of_fields_in_a_row.
## These elements are native GDscript types that represent the data resulting from the query.
var data_row := []
## An Array that contains sub-arrays.
## These sub-arrays represent for most of the queries the rows of the table where the query was executed.
## The number of sub-tables depends on the query that has been made.
## These sub-arrays contain as many elements as number_of_fields_in_a_row.
var raw_data_row := []
## This is usually a single word that identifies which SQL command was completed.
var command_tag: String
## Represents various information about the execution status of the query notified by the backend. Can be empty.
var notice := {}
## Returns all the values of a field.
## field_name is the name of the field on which we get the values.
## Can be empty if the field name is unknown.
## The field_name parameter is case sensitive.
func get_field_values(field_name: String) -> Array:
var values := []
var fields_index: int
for i in number_of_fields_in_a_row:
if row_description[i]["field_name"] == field_name:
fields_index = i
break
if fields_index == null:
return values
for data in data_row:
values.append(data[fields_index])
return values
## Returns the object ID of the data type of the field.
## field_name is the name of the field whose type we get.
## Can return -1 if the field name is unknown.
## The field_name parameter is case sensitive.
func field_data_type(field_name: String) -> int:
for i in number_of_fields_in_a_row:
if row_description[i]["field_name"] == field_name:
return row_description[i]["type_object_id"]
return -1
var postgresql_query_result_instance := PostgreSQLQueryResult.new()
var datas_command_sql := []
var response_buffer: PoolByteArray
var client_first_message: String # Authentication SASL
var salted_password: PoolByteArray # Authentication SASL
var auth_message: String # Authentication SASL
func reponce_parser(response: PoolByteArray):
var _unused
response_buffer += response
while response_buffer.size() > 4:
# Get the length of the response.
var data_length = response_buffer.subarray(1, 4)
data_length.invert()
var buffer := StreamPeerBuffer.new()
_unused = buffer.put_data(data_length)
buffer.seek(0)
# Message length.
var message_length = buffer.get_u32()
# If the size of the buffer is not equal to the length of the message, the request is not processed immediately.
# The server may send a fragmented response.
# We must therefore wait to receive the full response.
if response_buffer.size() < message_length + 1:
break
# Message type.
match char(response_buffer[0]):
'A':
### NotificationResponse ###
# Get the process ID of the notifying backend process.
var process_id = response_buffer.subarray(5, 8)
process_id.invert()
_unused = buffer.put_data(process_id)
buffer.seek(4)
process_id = buffer.get_32()
# We get the following parameters.
var situation_report_data := split_pool_byte_array(response_buffer.subarray(5, message_length), 0)
# Get the name of the channel that the notify has been raised on.
var name_of_channel: String = situation_report_data[0].get_string_from_utf8()
# Get the "payload" string passed from the notifying process.
var payload: String = situation_report_data[1].get_string_from_utf8()
# The result.
prints(process_id, name_of_channel, payload)
'C':
### CommandComplete ###
# Identifies the message as a command-completed response.
# Get the command tag. This is usually a single word that identifies which SQL command was completed.
var command_tag = response_buffer.subarray(5, message_length).get_string_from_ascii()
# The result.
postgresql_query_result_instance.command_tag = command_tag
datas_command_sql.append(postgresql_query_result_instance)
# Now is a good time to create a new return object for a possible next request.
postgresql_query_result_instance = PostgreSQLQueryResult.new()
'D':
### DataRow ###
# Identifies the message as a data row.
# Number of column values that follow (can be zero).
var number_of_columns = response_buffer.subarray(5, 6)
number_of_columns.invert()
_unused = buffer.put_data(number_of_columns)
buffer.seek(4)
number_of_columns = buffer.get_16()
var cursor := 0
var row := []
var raw_row := []
# Next, the following pair of fields appear for each column.
for i in number_of_columns:
var value_length = response_buffer.subarray(cursor + 7, cursor + 10)
value_length.invert()
buffer = StreamPeerBuffer.new()
_unused = buffer.put_data(value_length)
buffer.seek(0)
value_length = buffer.get_32()
if value_length == -1:
### NULL ###
# The result.
row.append(null)
match postgresql_query_result_instance.row_description[i].format_code:
0:
raw_row.append("")
1:
raw_row.append(PoolByteArray())
_:
print("error")
value_length = 0
else:
var value_data := response_buffer.subarray(cursor + 11, cursor + value_length + 10)
match postgresql_query_result_instance.row_description[i].format_code:
0:
raw_row.append(value_data.get_string_from_ascii())
1:
raw_row.append(value_data)
_:
print("error")
var error: int
match postgresql_query_result_instance.row_description[i].type_object_id:
DataTypePostgreSQL.BOOLEAN:
### BOOLEAN ###
# The type returned is bool.
match char(value_data[0]):
't':
### TRUE ###
# The result.
row.append(true)
'f':
### FALSE ###
# The result.
row.append(false)
var value_column:
push_error("[PostgreSQLClient:%d] The backend sent an invalid BOOLEAN object. Column value is not recognized: '%c'." % [get_instance_id(), value_column])
close(false)
return
DataTypePostgreSQL.SMALLINT:
### SMALLINT ###
# The type returned is int.
# The result.
row.append(int(value_data.get_string_from_ascii()))
DataTypePostgreSQL.INTEGER:
### INTEGER ###
# The type returned is int.
# The result.
row.append(int(value_data.get_string_from_ascii()))
DataTypePostgreSQL.BIGINT:
### BIGINT ###
# The type returned is int.
# The result.
row.append(int(value_data.get_string_from_ascii()))
DataTypePostgreSQL.REAL:
### REAL ###
# The type returned is float.
# The result.
row.append(float(value_data.get_string_from_ascii()))
DataTypePostgreSQL.DOUBLE_PRECISION:
### DOUBLE PRECISION ###
# The type returned is float.
# The result.
row.append(float(value_data.get_string_from_ascii()))
DataTypePostgreSQL.TEXT:
### TEXT ###
# The type returned is String.
# The result.
row.append(value_data.get_string_from_utf8())
DataTypePostgreSQL.CHARACTER:
### CHARACTER ###
# The type returned is String.
# The result.
row.append(value_data.get_string_from_utf8())
DataTypePostgreSQL.CHARACTER_VARYING:
### CHARACTER_VARYING ###
# The type returned is String.
# The result.
row.append(value_data.get_string_from_utf8())
"tsvector":
### TSVECTOR ###
pass
"tsquery":
### TSQUERY ###
pass
DataTypePostgreSQL.XML:
### XML ###
# The type returned is String.
var xml := XMLParser.new()
error = xml.open_buffer(value_data)
if error == OK:
# The result.
row.append(value_data.get_string_from_utf8())
else:
push_error("[PostgreSQLClient:%d] The backend sent an invalid XML object. (Error: %d)" % [get_instance_id(), error])
close(false)
response_buffer = PoolByteArray()
return
DataTypePostgreSQL.JSON:
### JSON ###
# The type returned is String.
var json = value_data.get_string_from_utf8()
var json_error := validate_json(json)
if json_error:
push_error("[PostgreSQLClient:%d] The backend sent an invalid JSON object: (Error: %d)" % [get_instance_id(), json_error])
close(false)
response_buffer = PoolByteArray()
return
else:
# The result.
row.append(json)
DataTypePostgreSQL.JSONB:
### JSONB ###
# The type returned is String.
var json = value_data.get_string_from_utf8()
var json_error := validate_json(json)
if json_error:
push_error("[PostgreSQLClient:%d] The backend sent an invalid JSONB object: (Error: %d)" % [get_instance_id(), json_error])
close(false)
response_buffer = PoolByteArray()
return
else:
# The result.
row.append(json)
DataTypePostgreSQL.BIT:
### BIT ###
# The type returned is String.
# Ideally we should validate the value sent by the backend...
# The result.
row.append(value_data.get_string_from_ascii())
DataTypePostgreSQL.BIT_VARYING:
### BIT VARYING ###
# The type returned is String.
# Ideally we should validate the value sent by the backend...
# The result.
row.append(value_data.get_string_from_ascii())
DataTypePostgreSQL.BITEA:
### BITEA ###
# /!\ Support not complet (not end). /!\
# The type returned is PoolByteArray.
var bitea_data := value_data.get_string_from_ascii()
if bitea_data.substr(2).is_valid_hex_number():
var bitea := PoolByteArray()
for i_hex in value_data.size() * 0.5 - 1:
bitea.append(("0x" + bitea_data[i_hex + 2] + bitea_data[i_hex + 2]).hex_to_int())
# The result.
row.append(bitea)
else:
push_error("[PostgreSQLClient:%d] The backend sent an invalid BITEA object." % [get_instance_id()])
close(false)
response_buffer = PoolByteArray()
return
"timestamp":
### TIMESTAMP ###
pass
"date":
### DATE ###
pass
"interval":
### INTERVAL ###
pass
DataTypePostgreSQL.UUID:
### UUID ###
# The type returned is String.
# Ideally we should validate the value sent by the backend...
# The result.
row.append(value_data.get_string_from_ascii())
DataTypePostgreSQL.CIDR:
### CIDR ###
# The type returned is String.
# Ideally we should validate the value sent by the backend with the line if below...
#value_data.get_string_from_ascii().is_valid_ip_address()
# The result.
row.append(value_data.get_string_from_ascii())
DataTypePostgreSQL.INET:
### INET ###
# The type returned is String.
# Ideally we should validate the value sent by the backend with the line if below...
#value_data.get_string_from_ascii().is_valid_ip_address()
# The result.
row.append(value_data.get_string_from_ascii())
DataTypePostgreSQL.MACADDR:
### MACADDR ###
# The type returned is String.
# Ideally we should validate the value sent by the backend...
# The result.
row.append(value_data.get_string_from_ascii())
DataTypePostgreSQL.MACADDR8:
### MACADDR8 ###
# The type returned is String.
# Ideally we should validate the value sent by the backend...
# The result.
row.append(value_data.get_string_from_ascii())
DataTypePostgreSQL.POINT:
### POINT ###
# The type returned is Vector2.
var regex = RegEx.new()
error = regex.compile("^\\((-?\\d+(?:\\.\\d+)?),(-?\\d+(?:\\.\\d+)?)\\)")
if error:
push_error("[PostgreSQLClient:%d] RegEx compilation of POINT object failed. (Error: %d)" % [get_instance_id(), error])
close(false)
response_buffer = PoolByteArray()
return
var result = regex.search(value_data.get_string_from_ascii())
if result:
# The result.
row.append(Vector2(float(result.strings[1]), float(result.strings[2])))
else:
push_error("[PostgreSQLClient:%d] The backend sent an invalid POINT object." % [get_instance_id()])
close(false)
response_buffer = PoolByteArray()
return
DataTypePostgreSQL.BOX:
### BOX ###
# The type returned is Rect2.
var regex = RegEx.new()
error = regex.compile("^\\((-?\\d+(?:\\.\\d+)?),(-?\\d+(?:\\.\\d+)?)\\),\\((-?\\d+(?:\\.\\d+)?),(-?\\d+(?:\\.\\d+)?)\\)")
if error:
push_error("[PostgreSQLClient:%d] RegEx compilation of BOX object failed. (Error: %d)" % [get_instance_id(), error])
close(false)
response_buffer = PoolByteArray()
return
var result = regex.search(value_data.get_string_from_ascii())
if result:
# The result.
row.append(Rect2(float(result.strings[3]), float(result.strings[4]), float(result.strings[1]), float(result.strings[2])))
else:
push_error("[PostgreSQLClient:%d] The backend sent an invalid BOX object." % [get_instance_id()])
close(false)
response_buffer = PoolByteArray()
return
DataTypePostgreSQL.LSEG:
### LSEG ###
# The type returned is PoolVector2Array.
var regex = RegEx.new()
error = regex.compile("^\\[\\((-?\\d+(?:\\.\\d+)?),(-?\\d+(?:\\.\\d+)?)\\),\\((-?\\d+(?:\\.\\d+)?),(-?\\d+(?:\\.\\d+)?)\\)\\]")
if error:
push_error("[PostgreSQLClient:%d] RegEx compilation of LSEG object failed. (Error: %d)" % [get_instance_id(), error])
close(false)
response_buffer = PoolByteArray()
return
var result = regex.search(value_data.get_string_from_ascii())
if result:
# The result.
row.append(PoolVector2Array([
Vector2(float(result.strings[1]), float(result.strings[2])),
Vector2(float(result.strings[3]), float(result.strings[4]))
]))
else:
push_error("[PostgreSQLClient:%d] The backend sent an invalid LSEG object." % [get_instance_id()])
close(false)
response_buffer = PoolByteArray()
return
"polygon":