forked from rsenn/qjs-modules
-
Notifications
You must be signed in to change notification settings - Fork 0
/
quickjs-pgsql.c
2229 lines (1785 loc) · 60.2 KB
/
quickjs-pgsql.c
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
#include "defines.h"
#include "quickjs-pgsql.h"
#include "utils.h"
#include "buffer-utils.h"
#include "char-utils.h"
#include "js-utils.h"
/**
* \addtogroup quickjs-pgsql
* @{
*/
VISIBLE JSClassID js_pgsqlerror_class_id = 0, js_pgconn_class_id = 0, js_pgresult_class_id = 0;
VISIBLE JSValue pgsqlerror_proto = {{0}, JS_TAG_UNDEFINED}, pgsqlerror_ctor = {{0}, JS_TAG_UNDEFINED}, pgsql_proto = {{0}, JS_TAG_UNDEFINED},
pgsql_ctor = {{0}, JS_TAG_UNDEFINED}, pgresult_proto = {{0}, JS_TAG_UNDEFINED}, pgresult_ctor = {{0}, JS_TAG_UNDEFINED};
static JSValue js_pgresult_wrap(JSContext* ctx, PGresult* res);
static JSValue string_to_value(JSContext* ctx, const char* func_name, const char* s);
static JSValue string_to_object(JSContext* ctx, const char* ctor_name, const char* s);
static void result_free(JSRuntime* rt, void* opaque, void* ptr);
#define string_to_number(ctx, s) string_to_value(ctx, "Number", s);
#define string_to_date(ctx, s) string_to_object(ctx, "Date", s);
struct PGConnection;
struct PGResult;
struct PGResult {
int ref_count;
PGresult* result;
struct PGConnection* conn;
uint32_t row_index;
};
struct PGResultIterator {
JSContext* ctx;
struct PGResult* result;
uint32_t row_index;
};
struct PGConnection {
int ref_count;
PGconn* conn;
BOOL nonblocking;
struct PGResult* result;
};
struct PGConnectParameters {
const char **keywords, **values;
size_t num_params;
};
typedef struct PGConnection PGSQLConnection;
typedef struct PGResult PGSQLResult;
typedef struct PGResultIterator PGSQLResultIterator;
typedef struct PGConnectParameters PGSQLConnectParameters;
typedef char* FieldNameFunc(JSContext*, PGSQLResult*, int field);
typedef JSValue RowValueFunc(JSContext*, PGSQLResult*, int, int);
static char* field_id(JSContext* ctx, PGSQLResult*, int field);
static char* field_name(JSContext* ctx, PGSQLResult*, int field);
static FieldNameFunc* field_namefunc(PGresult* res);
static JSValue field_array(PGSQLResult*, int, JSContext*);
static BOOL field_is_integer(PGresult* res, int field);
static BOOL field_is_json(PGresult* res, int field);
static BOOL field_is_float(PGresult* res, int field);
static BOOL field_is_number(PGresult* res, int field);
static BOOL field_is_binary(PGresult* res, int field);
static BOOL field_is_boolean(PGresult* res, int field);
static BOOL field_is_null(PGresult* res, int field);
static BOOL field_is_date(PGresult* res, int field);
static BOOL field_is_string(PGresult* res, int field);
enum ResultFlags {
RESULT_OBJECT = 1,
RESULT_STRING = 2,
RESULT_TBLNAM = 4,
};
static PGSQLResult* pgresult_dup(PGSQLResult* ptr);
static void pgresult_free(JSRuntime* rt, void* ptr, void* mem);
static JSValue pgresult_row(PGSQLResult* opaque, uint32_t row, RowValueFunc*, JSContext* ctx);
static int64_t pgresult_cmdtuples(PGSQLResult* opaque);
static void pgresult_set_conn(PGSQLResult* opaque, PGSQLConnection* conn, JSContext* ctx);
static JSValue js_pgresult_new(JSContext* ctx, JSValueConst proto, PGresult* res);
static JSValue js_pgsqlerror_new(JSContext* ctx, const char* msg);
static void
connectparams_parse(JSContext* ctx, PGSQLConnectParameters* c, const char* params) {
char* err;
PQconninfoOption* options;
size_t i, j = 0, len = 0;
if((options = PQconninfoParse(params, &err))) {
for(i = 0; options[i].keyword; i++) {
if(options[i].val)
++len;
}
c->num_params = len;
c->keywords = js_malloc(ctx, sizeof(char*) * (len + 1));
c->values = js_malloc(ctx, sizeof(char*) * (len + 1));
for(i = 0; options[i].keyword; i++) {
if(options[i].val) {
c->keywords[j] = js_strdup(ctx, options[i].keyword);
c->values[j] = options[i].val ? js_strdup(ctx, options[i].val) : 0;
++j;
}
}
c->keywords[len] = c->values[len] = 0;
PQconninfoFree(options);
}
}
static void
connectparams_fromobj(JSContext* ctx, PGSQLConnectParameters* c, JSValueConst obj) {
JSPropertyEnum* tmp_tab;
uint32_t tmp_len, i;
if(JS_GetOwnPropertyNames(ctx, &tmp_tab, &tmp_len, obj, JS_GPN_STRING_MASK | JS_GPN_ENUM_ONLY)) {
JS_ThrowTypeError(ctx, "argument is must be an object");
return;
}
c->num_params = tmp_len;
c->keywords = js_malloc(ctx, sizeof(char*) * (tmp_len + 1));
c->values = js_malloc(ctx, sizeof(char*) * (tmp_len + 1));
for(i = 0; i < tmp_len; i++) {
c->keywords[i] = js_atom_tostring(ctx, tmp_tab[i].atom);
c->values[i] = js_get_property_string(ctx, obj, tmp_tab[i].atom);
}
js_propertyenums_free(ctx, tmp_tab, tmp_len);
}
static void
connectparams_init(JSContext* ctx, PGSQLConnectParameters* c, int argc, JSValueConst argv[]) {
if(argc == 1 && JS_IsString(argv[0])) {
const char* str = JS_ToCString(ctx, argv[0]);
connectparams_parse(ctx, c, str);
JS_FreeCString(ctx, str);
} else if(argc > 0 && JS_IsObject(argv[0])) {
connectparams_fromobj(ctx, c, argv[0]);
} else {
static const char* param_names[] = {
"host",
"user",
"password",
"dbname",
"port",
"connect_timeout",
};
int i;
if(argc > (int)countof(param_names))
argc = (int)countof(param_names);
c->num_params = argc;
c->keywords = js_malloc(ctx, sizeof(char*) * (argc + 1));
c->values = js_malloc(ctx, sizeof(char*) * (argc + 1));
for(i = 0; i < argc; i++) {
c->keywords[i] = js_strdup(ctx, param_names[i]);
c->values[i] = js_tostring(ctx, argv[i]);
}
c->keywords[argc] = c->values[argc] = 0;
}
}
static void
connectparams_free(JSContext* ctx, PGSQLConnectParameters* c) {
size_t i;
for(i = 0; i < c->num_params; i++) {
js_free(ctx, (void*)c->keywords[i]);
js_free(ctx, (void*)c->values[i]);
}
js_free(ctx, c->keywords);
js_free(ctx, c->values);
}
static void
js_pgconn_print_value(JSContext* ctx, PGSQLConnection* pq, DynBuf* out, JSValueConst value) {
if(JS_IsNull(value) || JS_IsUndefined(value) || js_is_nan(value)) {
dbuf_putstr(out, "NULL");
} else if(JS_IsBool(value)) {
dbuf_putstr(out, JS_ToBool(ctx, value) ? "TRUE" : "FALSE");
} else if(JS_IsString(value)) {
size_t len;
const char* src = JS_ToCStringLen(ctx, &len, value);
char* dst;
if(pq && pq->conn) {
dst = PQescapeLiteral(pq->conn, src, len);
dbuf_putstr(out, dst);
PQfreemem(dst);
} else {
dbuf_putc(out, '\'');
dst = (char*)dbuf_reserve(out, len * 2 + 1);
len = PQescapeString(dst, src, len);
out->size += len;
dbuf_putc(out, '\'');
}
} else if(js_is_date(ctx, value)) {
size_t len;
char* str;
JSValue val;
/*int64_t ut;
val = js_invoke(ctx, value, "valueOf", 0, 0);
JS_ToInt64(ctx, &ut, val);
JS_FreeValue(ctx, val);
dbuf_putstr(out, "FROM_UNIXTIME(");
dbuf_printf(out, "%" PRId64, ut / 1000);
if(ut % 1000) {
dbuf_putc(out, '.');
dbuf_printf(out, "%" PRId64, ut % 1000);
}
dbuf_putc(out, ')');*/
val = js_invoke(ctx, value, "toISOString", 0, 0);
str = js_tostringlen(ctx, &len, val);
if(len >= 24) {
if(str[23] == 'Z')
len = 23;
}
if(len >= 19) {
if(str[10] == 'T')
str[10] = ' ';
}
dbuf_putc(out, '\'');
dbuf_put(out, (const uint8_t*)str, len);
dbuf_putc(out, '\'');
js_free(ctx, str);
JS_FreeValue(ctx, val);
} else if(js_is_numeric(ctx, value)) {
JSValue val = JS_IsNumber(value) ? JS_DupValue(ctx, value) : js_value_coerce(ctx, "Number", value);
size_t len;
const char* src = JS_ToCStringLen(ctx, &len, val);
dbuf_put(out, (const uint8_t*)src, len);
// js_pgconn_print_value(ctx, pq, out, val);
JS_FreeValue(ctx, val);
} else if(js_is_arraybuffer(ctx, value)) {
InputBuffer input = js_input_buffer(ctx, value);
char buf[FMT_XLONG] = {'\\'};
dbuf_putstr(out, "'\\x");
for(size_t i = 0; i < input.size; i++)
dbuf_put(out, (const uint8_t*)buf, fmt_xlong0(buf, input.data[i], 2));
dbuf_putstr(out, "'::bytea");
input_buffer_free(&input, ctx);
} else {
JSValue str = JS_JSONStringify(ctx, value, JS_NULL, JS_NULL);
js_pgconn_print_value(ctx, pq, out, str);
JS_FreeValue(ctx, str);
}
}
static void
js_pgconn_print_field(JSContext* ctx, PGSQLConnection* pq, DynBuf* out, JSValueConst value) {
const char* name;
size_t namelen;
if((name = JS_ToCStringLen(ctx, &namelen, value))) {
char* escaped;
escaped = PQescapeIdentifier(pq->conn, name, namelen);
JS_FreeCString(ctx, name);
if(escaped) {
dbuf_putstr(out, escaped);
PQfreemem(escaped);
}
}
}
/*
static void
js_pgconn_print_fields(JSContext* ctx, DynBuf* out, JSPropertyEnum* tmp_tab, uint32_t tmp_len) {
for(uint32_t i = 0; i < tmp_len; i++) {
const char* str;
if(i > 0)
dbuf_putstr(out, ", ");
str = JS_AtomToCString(ctx, tmp_tab[i].atom);
dbuf_putc(out, '`');
dbuf_putstr(out, str);
dbuf_putc(out, '`');
JS_FreeCString(ctx, str);
}
}
*/
static void
js_pgconn_print_insert(JSContext* ctx, DynBuf* out) {
dbuf_putstr(out, "INSERT INTO ");
}
static void
js_pgconn_print_fields(JSContext* ctx, PGSQLConnection* pq, DynBuf* out, JSValueConst fields) {
JSValue item, iter = js_iterator_new(ctx, fields);
if(!JS_IsUndefined(iter)) {
BOOL done = FALSE;
dbuf_putc(out, '(');
for(int i = 0;; i++) {
item = js_iterator_next(ctx, iter, &done);
if(done)
break;
if(i > 0)
dbuf_putstr(out, ", ");
js_pgconn_print_field(ctx, pq, out, item);
JS_FreeValue(ctx, item);
}
dbuf_putc(out, ')');
}
}
static void
js_pgconn_print_values(JSContext* ctx, PGSQLConnection* pq, DynBuf* out, JSValueConst values) {
JSValue item, iter = js_iterator_new(ctx, values);
if(!JS_IsUndefined(iter)) {
BOOL done = FALSE;
dbuf_putc(out, '(');
for(int i = 0;; i++) {
item = js_iterator_next(ctx, iter, &done);
if(done)
break;
if(i > 0)
dbuf_putstr(out, ", ");
js_pgconn_print_value(ctx, pq, out, item);
JS_FreeValue(ctx, item);
}
dbuf_putc(out, ')');
} /*else {
JSPropertyEnum* tmp_tab;
uint32_t tmp_len;
if(JS_GetOwnPropertyNames(ctx, &tmp_tab, &tmp_len, values, JS_GPN_STRING_MASK | JS_GPN_ENUM_ONLY)) {
JS_FreeValue(ctx, iter);
JS_ThrowTypeError(ctx, "argument is must be an object");
return;
}
dbuf_putc(out, '(');
js_pgconn_print_fields(ctx, out, tmp_tab, tmp_len);
dbuf_putc(out, ')');
dbuf_putstr(out, " VALUES (");
for(uint32_t i = 0; i < tmp_len; i++) {
if(i > 0)
dbuf_putstr(out, ", ");
item = JS_GetProperty(ctx, values, tmp_tab[i].atom);
js_pgconn_print_value(ctx, out, item);
JS_FreeValue(ctx, item);
}
dbuf_putc(out, ')');
js_propertyenums_free(ctx, tmp_tab, tmp_len);
}*/
}
static void
value_yield(JSContext* ctx, JSValueConst resolve, JSValueConst value) {
JSValue ret = JS_Call(ctx, resolve, JS_UNDEFINED, 1, &value);
JS_FreeValue(ctx, ret);
}
static void
value_yield_free(JSContext* ctx, JSValueConst resolve, JSValueConst value) {
value_yield(ctx, resolve, value);
JS_FreeValue(ctx, value);
}
static PGSQLConnection*
pgconn_new(JSContext* ctx) {
PGSQLConnection* pq;
if(!(pq = js_malloc(ctx, sizeof(PGSQLConnection))))
return 0;
*pq = (PGSQLConnection){1, NULL, FALSE, NULL};
return pq;
}
static PGSQLConnection*
pgconn_dup(PGSQLConnection* pq) {
++pq->ref_count;
return pq;
}
static void
pgconn_free(PGSQLConnection* pq, JSRuntime* rt) {
if(--pq->ref_count == 0) {
if(pq->result) {
pgresult_free(rt, pq->result, 0);
pq->result = 0;
}
if(pq->conn) {
PQfinish(pq->conn);
pq->conn = 0;
}
js_free_rt(rt, pq);
}
}
static BOOL
pgconn_nonblock(PGSQLConnection* pq) {
return pq->conn ? PQisnonblocking(pq->conn) : pq->nonblocking;
}
static const char*
pgconn_error(PGSQLConnection* pq) {
return pgconn_error(pq);
}
static void
pgconn_set_result(PGSQLConnection* pq, PGSQLResult* opaque, JSContext* ctx) {
if(pq->result) {
pgresult_free(JS_GetRuntime(ctx), pq->result, 0);
pq->result = 0;
}
pq->result = opaque ? pgresult_dup(opaque) : 0;
}
static JSValue
pgconn_result(PGSQLConnection* pq, PGresult* res, JSContext* ctx) {
JSValue value = js_pgresult_new(ctx, pgresult_proto, res);
PGSQLResult* opaque = JS_GetOpaque(value, js_pgresult_class_id);
pgconn_set_result(pq, opaque, ctx);
pgresult_set_conn(opaque, pq, ctx);
return value;
}
static JSValue
pgconn_get_result(PGSQLConnection* pq, JSContext* ctx) {
PGresult* res;
if((res = PQgetResult(pq->conn)))
return pgconn_result(pq, res, ctx);
return JS_NULL;
}
static char*
pgconn_lookup_oid(PGSQLConnection* pq, Oid oid, JSContext* ctx) {
PGresult* res;
DynBuf buf;
char* ret = 0;
js_dbuf_init(ctx, &buf);
dbuf_putstr(&buf, "SELECT relname FROM pg_class WHERE oid=");
dbuf_put_uint32(&buf, oid);
dbuf_putc(&buf, ';');
dbuf_0(&buf);
if((res = PQexec(pq->conn, (const char*)buf.buf))) {
char* s;
if((s = PQgetvalue(res, 0, 0))) {
ret = js_strdup(ctx, s);
}
}
dbuf_free(&buf);
return ret;
}
PGSQLConnection*
js_pgconn_data2(JSContext* ctx, JSValueConst value) {
return JS_GetOpaque2(ctx, value, js_pgconn_class_id);
}
static JSValue
js_pgconn_new(JSContext* ctx, JSValueConst proto) {
JSValue obj;
if(js_pgconn_class_id == 0)
js_pgsql_init(ctx, 0);
if(JS_IsNull(proto) || JS_IsUndefined(proto))
proto = JS_DupValue(ctx, pgsql_proto);
/* using new_target to get the prototype is necessary when the class is extended. */
obj = JS_NewObjectProtoClass(ctx, proto, js_pgconn_class_id);
if(JS_IsException(obj))
goto fail;
return obj;
fail:
JS_FreeValue(ctx, obj);
return JS_EXCEPTION;
}
static JSValue
js_pgconn_wrap(JSContext* ctx, JSValueConst proto, PGconn* conn) {
PGSQLConnection* pq;
JSValue ret = JS_UNDEFINED;
if(!(pq = pgconn_new(ctx)))
return JS_EXCEPTION;
pq->conn = conn;
if(!JS_IsException((ret = js_pgconn_new(ctx, proto))))
JS_SetOpaque(ret, pq);
return ret;
}
static inline int
js_pgconn_rtype(JSContext* ctx, JSValueConst value) {
return js_get_propertystr_int32(ctx, value, "resultType");
}
enum {
METHOD_ESCAPE_STRING,
};
static JSValue
js_pgconn_methods(JSContext* ctx, JSValueConst this_val, int argc, JSValueConst argv[], int magic) {
PGSQLConnection* pq = 0;
JSValue ret = JS_UNDEFINED;
if(!(pq = js_pgconn_data2(ctx, this_val)))
return JS_EXCEPTION;
switch(magic) {
case METHOD_ESCAPE_STRING: {
char* dst;
const char* src;
size_t len;
if(!(src = JS_ToCStringLen(ctx, &len, argv[0]))) {
ret = JS_ThrowTypeError(ctx, "argument 1 must be string");
break;
}
if((!(dst = js_malloc(ctx, 2 * len + 1)))) {
ret = JS_EXCEPTION;
break;
}
len = pq && pq->conn ? PQescapeStringConn(pq->conn, dst, src, len, 0) : PQescapeString(dst, src, len);
ret = JS_NewStringLen(ctx, dst, len);
js_free(ctx, dst);
break;
}
}
return ret;
}
enum {
PROP_CMD_TUPLES,
PROP_NONBLOCKING,
PROP_FD,
PROP_OPTIONS,
PROP_ERRNO,
PROP_ERROR_MESSAGE,
PROP_INSERT_ID,
PROP_CLIENT_ENCODING,
PROP_PROTOCOL_VERSION,
PROP_SERVER_VERSION,
PROP_USER,
PROP_PASSWORD,
PROP_HOST,
PROP_DB,
PROP_PORT,
PROP_CONNINFO,
PROP_CLIENT_INFO,
PROP_CLIENT_VERSION,
PROP_THREAD_SAFE,
PROP_EOF,
PROP_NUM_ROWS,
PROP_NUM_FIELDS,
};
static JSValue
js_pgconn_get(JSContext* ctx, JSValueConst this_val, int magic) {
PGSQLConnection* pq;
JSValue ret = JS_UNDEFINED;
if(!(pq = js_pgconn_data2(ctx, this_val)))
return JS_EXCEPTION;
switch(magic) {
case PROP_CMD_TUPLES: {
if(pq->result)
ret = JS_NewInt64(ctx, pgresult_cmdtuples(pq->result));
break;
}
case PROP_NONBLOCKING: {
ret = JS_NewBool(ctx, pq->conn ? PQisnonblocking(pq->conn) : pq->nonblocking);
break;
}
case PROP_FD: {
ret = JS_NewInt32(ctx, PQsocket(pq->conn));
break;
}
case PROP_ERROR_MESSAGE: {
const char* error = pgconn_error(pq);
ret = error && *error ? JS_NewString(ctx, error) : JS_NULL;
break;
}
case PROP_OPTIONS: {
const char* options = PQoptions(pq->conn);
ret = options && *options ? JS_NewString(ctx, options) : JS_NULL;
break;
}
case PROP_INSERT_ID: {
PGresult* res;
int64_t id = -1;
if((res = PQexec(pq->conn, "SELECT lastval();"))) {
char* val;
if((val = PQgetvalue(res, 0, 0))) {
if(scan_longlong(val, &id) > 0)
ret = JS_NewInt64(ctx, id);
}
PQclear(res);
}
break;
}
case PROP_CLIENT_ENCODING: {
int encoding = PQclientEncoding(pq->conn);
const char* charset = pg_encoding_to_char(encoding);
ret = charset && *charset ? JS_NewString(ctx, charset) : JS_NULL;
break;
}
case PROP_PROTOCOL_VERSION: {
ret = JS_NewUint32(ctx, PQprotocolVersion(pq->conn));
break;
}
case PROP_SERVER_VERSION: {
ret = JS_NewUint32(ctx, PQserverVersion(pq->conn));
break;
}
case PROP_USER: {
char* user = PQuser(pq->conn);
ret = user ? JS_NewString(ctx, user) : JS_NULL;
break;
}
case PROP_PASSWORD: {
char* pass = PQpass(pq->conn);
ret = pass ? JS_NewString(ctx, pass) : JS_NULL;
break;
}
case PROP_HOST: {
char* host = PQhost(pq->conn);
ret = host ? JS_NewString(ctx, host) : JS_NULL;
break;
}
case PROP_PORT: {
char* port = PQport(pq->conn);
ret = port ? JS_NewString(ctx, port) : JS_NULL;
break;
}
case PROP_DB: {
char* db = PQdb(pq->conn);
ret = db ? JS_NewString(ctx, db) : JS_NULL;
break;
}
case PROP_CONNINFO: {
PQconninfoOption* info;
if((info = PQconninfo(pq->conn))) {
int i;
ret = JS_NewObject(ctx);
for(i = 0; info[i].keyword; i++)
if(info[i].val)
JS_SetPropertyStr(ctx, ret, info[i].keyword, info[i].val ? JS_NewString(ctx, info[i].val) : JS_NULL);
}
break;
}
}
return ret;
}
static JSValue
js_pgconn_set(JSContext* ctx, JSValueConst this_val, JSValueConst value, int magic) {
PGSQLConnection* pq;
if(!(pq = js_pgconn_data2(ctx, this_val)))
return JS_EXCEPTION;
switch(magic) {
case PROP_NONBLOCKING: {
pq->nonblocking = JS_ToBool(ctx, value);
if(pq->conn)
if(PQsetnonblocking(pq->conn, pq->nonblocking))
return JS_Throw(ctx, js_pgsqlerror_new(ctx, pgconn_error(pq)));
break;
}
case PROP_CLIENT_ENCODING: {
const char* charset;
if((charset = JS_ToCString(ctx, value))) {
int ret;
ret = PQsetClientEncoding(pq->conn, charset);
JS_FreeCString(ctx, charset);
if(ret)
return JS_Throw(ctx, js_pgsqlerror_new(ctx, pgconn_error(pq)));
}
break;
}
}
return JS_UNDEFINED;
}
static JSValue
js_pgconn_value_string(JSContext* ctx, JSValueConst this_val, int argc, JSValueConst argv[]) {
JSValue ret;
DynBuf buf;
PGSQLConnection* pq;
if(!(pq = js_pgconn_data2(ctx, this_val)))
return JS_EXCEPTION;
dbuf_init2(&buf, 0, 0);
for(int i = 0; i < argc; i++) {
if(i > 0)
dbuf_putstr(&buf, ", ");
js_pgconn_print_value(ctx, pq, &buf, argv[i]);
}
ret = JS_NewStringLen(ctx, (const char*)buf.buf, buf.size);
dbuf_free(&buf);
return ret;
}
static JSValue
js_pgconn_values_string(JSContext* ctx, JSValueConst this_val, int argc, JSValueConst argv[]) {
JSValue ret;
DynBuf buf;
PGSQLConnection* pq;
if(!(pq = js_pgconn_data2(ctx, this_val)))
return JS_EXCEPTION;
dbuf_init2(&buf, 0, 0);
for(int i = 0; i < argc; i++) {
if(i > 0)
dbuf_putstr(&buf, ", ");
js_pgconn_print_values(ctx, pq, &buf, argv[i]);
}
ret = JS_NewStringLen(ctx, (const char*)buf.buf, buf.size);
dbuf_free(&buf);
return ret;
}
static JSValue
js_pgconn_insert_query(JSContext* ctx, JSValueConst this_val, int argc, JSValueConst argv[]) {
JSValue ret;
DynBuf buf;
const char* tbl;
size_t tbl_len;
PGSQLConnection* pq;
int i = 1, j;
if(!(pq = js_pgconn_data2(ctx, this_val)))
return JS_EXCEPTION;
tbl = JS_ToCStringLen(ctx, &tbl_len, argv[0]);
dbuf_init2(&buf, 0, 0);
js_pgconn_print_insert(ctx, &buf);
dbuf_put(&buf, (const uint8_t*)tbl, tbl_len);
dbuf_putstr(&buf, " ");
if(i + 1 < argc) {
js_pgconn_print_fields(ctx, pq, &buf, argv[i++]);
}
dbuf_putstr(&buf, " VALUES ");
for(j = i; j < argc; j++) {
if(JS_IsString(argv[j]))
break;
if(i > j)
dbuf_putstr(&buf, ", ");
js_pgconn_print_values(ctx, pq, &buf, argv[j]);
}
if(j < argc) {
dbuf_putstr(&buf, " RETURNING ");
js_pgconn_print_field(ctx, pq, &buf, argv[j++]);
}
dbuf_putstr(&buf, ";");
ret = JS_NewStringLen(ctx, (const char*)buf.buf, buf.size);
dbuf_free(&buf);
return ret;
}
static JSValue
js_pgconn_escape_string(JSContext* ctx, JSValueConst this_val, int argc, JSValueConst argv[]) {
JSValue ret = JS_UNDEFINED;
PGSQLConnection* pq;
char* dst;
const char* src;
size_t len;
pq = JS_GetOpaque(this_val, js_pgconn_class_id);
if(!(src = JS_ToCStringLen(ctx, &len, argv[0])))
return JS_ThrowTypeError(ctx, "argument 1 must be string");
if((!(dst = js_malloc(ctx, 2 * len + 1)))) {
JS_FreeCString(ctx, src);
return JS_EXCEPTION;
}
len = pq && pq->conn ? PQescapeStringConn(pq->conn, dst, src, len, NULL) : PQescapeString(dst, src, len);
ret = JS_NewStringLen(ctx, dst, len);
js_free(ctx, dst);
return ret;
}
static JSValue
js_pgconn_escape_alloc(JSContext* ctx, JSValueConst this_val, int argc, JSValueConst argv[], int magic) {
JSValue ret = JS_UNDEFINED;
PGSQLConnection* pq;
char* dst;
const char* src;
size_t len;
if(!(pq = js_pgconn_data2(ctx, this_val)))
return JS_EXCEPTION;
if(!(src = JS_ToCStringLen(ctx, &len, argv[0])))
return JS_ThrowTypeError(ctx, "argument 1 must be string");
dst = magic ? PQescapeIdentifier(pq->conn, src, len) : PQescapeLiteral(pq->conn, src, len);
ret = JS_NewString(ctx, dst);
PQfreemem(dst);
return ret;
}
static JSValue
js_pgconn_constructor(JSContext* ctx, JSValueConst new_target, int argc, JSValueConst argv[]) {
JSValue proto, obj = JS_UNDEFINED;
/* using new_target to get the prototype is necessary when the class is extended. */
proto = JS_GetPropertyStr(ctx, new_target, "prototype");
if(JS_IsException(proto))
goto fail;
obj = js_pgconn_wrap(ctx, proto, 0);
JS_FreeValue(ctx, proto);
return obj;
fail:
JS_FreeValue(ctx, obj);
return JS_EXCEPTION;
}
static JSValue
js_pgconn_escape_bytea(JSContext* ctx, JSValueConst this_val, int argc, JSValueConst argv[]) {
JSValue ret = JS_UNDEFINED;
PGSQLConnection* pq;
char* dst;
size_t dlen = 0;
pq = JS_GetOpaque(this_val, js_pgconn_class_id);
InputBuffer src = js_input_chars(ctx, argv[0]);
if(!src.size)
return JS_ThrowTypeError(ctx, "argument 1 must be string or ArrayBuffer");
dst = (char*)(pq && pq->conn ? PQescapeByteaConn(pq->conn, (unsigned char*)src.data, src.size, &dlen) : PQescapeBytea((unsigned char*)src.data, src.size, &dlen));
if(dlen > 0 && dst[dlen - 1] == '\0')
dlen--;
ret = JS_NewStringLen(ctx, dst, dlen);
PQfreemem(dst);
input_buffer_free(&src, ctx);
return ret;
}
static JSValue
js_pgconn_unescape_bytea(JSContext* ctx, JSValueConst this_val, int argc, JSValueConst argv[]) {
char* dst;
size_t dlen = 0;
const char* src;
if(!(src = JS_ToCString(ctx, argv[0])))
return JS_ThrowTypeError(ctx, "argument 1 must be string");
dst = (char*)PQunescapeBytea((unsigned char*)src, &dlen);
JS_FreeCString(ctx, src);
return JS_NewArrayBuffer(ctx, (uint8_t*)dst, dlen, &result_free, 0, FALSE);
}
static JSValue
js_pgconn_connect_cont(JSContext* ctx, JSValueConst this_val, int argc, JSValueConst argv[], int magic, JSValue data[]) {
int32_t fd;
PGSQLConnection* pq;
PostgresPollingStatusType newstate, oldstate;
if(!(pq = js_pgconn_data2(ctx, data[0])))
return JS_EXCEPTION;
oldstate = magic;
newstate = PQconnectPoll(pq->conn);
fd = PQsocket(pq->conn);
if(newstate == PGRES_POLLING_OK) {
js_iohandler_set(ctx, data[1], fd, JS_NULL);
int ret;
if((ret = PQsetClientEncoding(pq->conn, "utf8"))) {
printf("failed setting PGSQL character set to utf8: %s", pgconn_error(pq));
}
JS_Call(ctx, data[2], JS_UNDEFINED, 1, &data[0]);
} else if(newstate != oldstate) {
JSValue handler, hdata[4] = {
JS_DupValue(ctx, data[0]),
js_iohandler_fn(ctx, newstate == PGRES_POLLING_WRITING),
JS_DupValue(ctx, data[2]),
JS_DupValue(ctx, data[3]),
};
handler = JS_NewCFunctionData(ctx, js_pgconn_connect_cont, 0, newstate, countof(hdata), hdata);
js_iohandler_set(ctx, data[1], fd, JS_NULL);
js_iohandler_set(ctx, hdata[1], fd, handler);
JS_FreeValue(ctx, handler);
JS_FreeValue(ctx, hdata[0]);
JS_FreeValue(ctx, hdata[1]);
JS_FreeValue(ctx, hdata[2]);
JS_FreeValue(ctx, hdata[3]);
}
#ifdef DEBUG_OUTPUT
printf("%s fd=%i newstate=%i pq=%p error='%s'\n", __func__, fd, newstate, pq, pgconn_error(pq));
#endif
return JS_UNDEFINED;
}