-
Notifications
You must be signed in to change notification settings - Fork 52
/
001-server.sql
1823 lines (1442 loc) · 66 KB
/
001-server.sql
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
/******************************************************************************
* ENDPOINT SERVER
* HTTP request handler for a datum REST interface
* HTTP arbitrary resource server
******************************************************************************/
/****************************************************************************************************
*
* FUNCTION suffix_clause
*
* Builds limit, offset, order by, and where clauses from json
*
****************************************************************************************************/
create or replace function endpoint.suffix_clause(
args json
) returns text as $$
declare
_limit text := '';
_offset text := '';
_order_by text := '';
_where text := 'where true';
r record;
begin
for r in select * from json_each(args) loop
-- Limit clause
-- URL
-- /endpoint?$limit=10
if r.key = 'limit' then
select ' limit ' || quote_literal(json_array_elements_text)
from json_array_elements_text(r.value::text::json)
into _limit;
-- Offset clause
-- URL
-- /endpoint?$offest=5
elsif r.key = 'offset' then
select ' offset ' || quote_literal(json_array_elements_text)
from json_array_elements_text(r.value::text::json)
into _offset;
-- Order by clause
-- URL
-- /endpoint?$order_by=city
-- /endpoint?$order_by=[city,-state,-full_name]
elsif r.key = 'order_by' then
if pg_typeof(r.value) = 'json'::regtype then
select ' order by ' ||
string_agg(case substring(q.val from 1 for 1)
when '-' then substring(q.val from 2) || ' desc'
else q.val end,
', ')
from (select json_array_elements_text as val from json_array_elements_text(r.value)) q
into _order_by;
else
select ' order by ' ||
case substring(r.value::text from 1 for 1)
when '-' then substring(r.value::text from 2) || ' desc'
else r.value::text
end
into _order_by;
end if;
-- Where clause
-- URL
-- /endpoint?$where={name=NAME1,op=like,value=VALUE1}
-- /endpoint?$where=[{name=NAME1,op=like,value=VALUE1},{name=NAME2,op='=',value=VALUE2}]
elsif r.key = 'where' then
if pg_typeof(r.value) = 'json'::regtype then
if json_typeof(r.value) = 'array' then -- { where: JSON array }
/*
select json->>'name' as name, json->>'op' as op, json->>'value' as value from
(select json_array_elements_text(value)::json as json from
(( select value from json_each('{"where": ["{\"name\":\"bundle_name\",\"op\":\"=\",\"value\":\"com.aquameta.core.ide\"}", "{\"name\":\"name\",\"op\":\"=\",\"value\":\"development\"}"]}'))
) v)
b;
*/
select _where || ' and ' || string_agg( name || '::text ' || op || ' ' ||
case when op = 'in' then
-- Value is array
case when json_typeof(json) = 'array' then
(select '(' || string_agg(quote_literal(array_val), ',') || ')'
from json_array_elements_text(json) as array_val)
-- Value is object
when json_typeof(json) = 'object' then
quote_literal(json) || '::json'
else
quote_literal(value)
end
else
quote_literal(value)
end
, '::text and ' )
from (
select element->>'name' as name, element->>'op' as op, element->'value' as json, element->>'value' as value
from (select json_array_elements_text::json as element from json_array_elements_text(r.value)) j
) v
into _where;
elsif json_typeof(r.value) = 'object' then -- { where: JSON object }
select _where || ' and ' || name || '::text ' || op || ' ' ||
case when op = 'in' then
-- Value is array
case when json_typeof(value::json) = 'array' then
(select '(' || string_agg(quote_literal(array_val), ',') || ')'
from json_array_elements_text(value::json) as array_val)
-- Value is object
when json_typeof(value::json) = 'object' then
quote_literal(value) || '::json'
else
quote_literal(value)
end
end
|| '::text'
from json_to_record(r.value::json) as x(name text, op text, value text)
into _where;
end if;
else -- Else { where: regular value } -- This is not used in the client
select _where || ' and ' || quote_ident(name) || '::text ' || op || ' ' || quote_literal(value) || '::text'
from json_to_record(r.value::json) as x(name text, op text, value text)
into _where;
end if;
else
end if;
end loop;
return _where || _order_by || _limit || _offset;
end;
$$
language plpgsql;
/******************************************************************************
* REQUEST HANDLERS
*
* Functions called by endpoint.request, returning JSON/REST responses
******************************************************************************/
/****************************************************************************************************
* FUNCTION multiple_row_insert *
****************************************************************************************************/
create or replace function endpoint.multiple_row_insert(
relation_id meta.relation_id,
args json
) returns setof json as $$
declare
_schema_name text;
_relation_name text;
r json;
q text;
begin
select (relation_id).schema_name into _schema_name;
select (relation_id).name into _relation_name;
select array_to_json(array_agg(t.json_array_elements))
from
(
select json_array_elements(endpoint.row_insert(relation_id, json_array_elements)->'result')
from json_array_elements(args)
) t
into r;
q := 'select (''{' ||
--"columns":'' || endpoint.columns_json($1, $2) || '',
'"result":'' || ($3) || ''
}'')::json';
return query execute q
using _schema_name,
_relation_name,
r;
end;
$$
language plpgsql;
/****************************************************************************************************
* FUNCTION rows_insert *
****************************************************************************************************/
create or replace function endpoint.rows_insert(
args json
) returns void as $$
declare
row_id meta.row_id;
--q text;
begin
-- raise notice 'ROWS INSERT!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!';
-- raise notice 'TOTAL ROWS: %', json_array_length(args);
-- raise notice 'da json: %', args;
-- insert rows
for i in 0..json_array_length(args) - 1 loop
row_id := (args->i->'row_id')::meta.row_id;
-- raise notice '########################### inserting row %: % @@@@@ %', i, row_id, args->i;
-- raise notice '% = %', row_id, args->i->'row';
-- disable triggers (except blob... hack hack)
if row_id::meta.relation_id != meta.relation_id('bundle','blob') then
execute 'alter table ' || quote_ident((row_id::meta.schema_id).name) || '.' || quote_ident((row_id::meta.relation_id).name) || ' disable trigger all';
end if;
-- Doesn't seem to be used
--q := 'insert into ' || quote_ident((row_id::meta.schema_id).name) || '.' || quote_ident((row_id::meta.relation_id).name) || ' select * from json_to_record (' || quote_literal(args->i->'row') || ')';
-- raise notice '(NOT) QUERY: %', q;
-- execute q;
perform endpoint.row_insert(row_id::meta.relation_id, args->i->'row');
--perform endpoint.row_insert((row_id::meta.schema_id).name, 'table', (row_id::meta.relation_id).name, args->i->'row');
end loop;
-- enable triggers
for i in 0..json_array_length(args) - 1 loop
row_id := (args->i->'row_id')::meta.row_id;
execute 'alter table ' || quote_ident((row_id::meta.schema_id).name) || '.' || quote_ident((row_id::meta.relation_id).name) || ' enable trigger all';
end loop;
end
$$
language plpgsql;
/****************************************************************************************************
* FUNCTION row_insert *
****************************************************************************************************/
create or replace function endpoint.row_insert(
relation_id meta.relation_id,
args json
) returns setof json as $$
declare
_schema_name text;
_relation_name text;
q text;
/*
TODO: This doesn't work with bytea columns because when you insert text
into a bytea column because it thinks it's the client_encoding instead of
hex. -- this function is entirely wrong anywya, it is detecting json not
by looking at the column type but by looking at the VALUE. WTF.
*/
begin
_schema_name := (relation_id::meta.schema_id).name;
_relation_name := (relation_id).name;
q := '
with inserted_row as (
insert into ' || quote_ident(_schema_name) || '.' || quote_ident(_relation_name) ||
case when args::text = '{}'::text then
' default values '
else
' (' || (
select string_agg(quote_ident(json_object_keys), ',' order by json_object_keys)
from json_object_keys(args)
) || ') values (' || (
select string_agg('
case when json_typeof($3->' || quote_literal(json_object_keys) || ') = ''array'' then ((
select ''{'' || string_agg(value::text, '', '') || ''}''
from json_array_elements(($3->>' || quote_literal(json_object_keys) || ')::json)
))
when json_typeof($3->' || quote_literal(json_object_keys) || ') = ''object'' then
($3->' || quote_literal(json_object_keys) || ')::text
else ($3->>' || quote_literal(json_object_keys) || ')::text
end::' || case when json_typeof((args->json_object_keys)) = 'object' then 'json::'
else ''
end || c.type_name, ',
'
order by json_object_keys
) from json_object_keys(args)
inner join meta.relation_column c
on c.schema_name = _schema_name and
c.relation_name = _relation_name and
c.name = json_object_keys
left join meta.type t on c.type_id = t.id
) || ') '
end ||
'returning *
)
select (''{
"columns": ' || endpoint.columns_json(_schema_name, _relation_name, null::text[], null::text[]) || ',
"pk":"' || coalesce(endpoint.pk_name(_schema_name, _relation_name), 'null') || '",
"result": [{ "row": '' || row_to_json(inserted_row.*, true) || '' }]
}'')::json
from inserted_row
';
-- raise notice 'ROW_INSERT ############: %', q;
return query execute q
using _schema_name,
_relation_name,
args;
end
$$
language plpgsql;
/****************************************************************************************************
* FUNCTION row_update *
****************************************************************************************************/
create or replace function endpoint.row_update(
row_id meta.row_id,
args json
) returns json as $$ -- FIXME: use json_to_row upon 9.4 release, alleviates all the destructuring below
declare
_schema_name text;
_relation_name text;
pk text;
begin
-- raise notice 'ROW_UPDATE ARGS: %, %, %, %, %', _schema_name, relation_type, _relation_name, pk, args::text;
select (row_id::meta.schema_id).name into _schema_name;
select (row_id::meta.relation_id).name into _relation_name;
select row_id.pk_value::text into pk;
execute (
select 'update ' || quote_ident(_schema_name) || '.' || quote_ident(_relation_name) || ' as r
set ' || (
select string_agg(
quote_ident(json_object_keys) || ' =
case when json_typeof($1->' || quote_literal(json_object_keys) || ') = ''array'' then ((
select ''{'' || string_agg(value::text, '', '') || ''}''
from json_array_elements(($1->>' || quote_literal(json_object_keys) || ')::json)
))
when json_typeof($1->' || quote_literal(json_object_keys) || ') = ''object'' then
($1->' || quote_literal(json_object_keys) || ')::text
else ($1->>' || quote_literal(json_object_keys) || ')::text
end::' || case when json_typeof((args->json_object_keys)) = 'object' then 'json::'
else ''
end || c.type_name, ',
'
) from json_object_keys(args)
inner join meta.relation_column c
on c.schema_name = _schema_name and
c.relation_name = _relation_name and
c.name = json_object_keys
) || ' where ' || (
select 'r.' || quote_ident((row_id).pk_column_name) || ' = ' || quote_literal((row_id).pk_value)
)
) using args;
return '{}';
end;
$$
language plpgsql;
/****************************************************************************************************
* FUNCTION rows_select *
****************************************************************************************************/
create or replace function endpoint.rows_select(
relation_id meta.relation_id,
args json
) returns json as $$
declare
schema_name text;
relation_name text;
row_query text;
rows_json text;
suffix text;
exclude text[];
include text[];
column_list text;
begin
select (relation_id).schema_name into schema_name;
select (relation_id).name into relation_name;
-- Suffix
select endpoint.suffix_clause(args) into suffix;
-- Column list
-- Exclude
select array_agg(val)
from ((
select json_array_elements_text(value::json) as val
from json_array_elements_text(args->'exclude')
)) q
into exclude;
-- Include
select array_agg(val)
from ((
select json_array_elements_text(value::json) as val
from json_array_elements_text(args->'include')
)) q
into include;
if exclude is not null or include is not null then
select endpoint.column_list(schema_name, relation_name, 'r'::text, exclude, include) into column_list;
else
select 'r.*' into column_list;
end if;
row_query := 'select ''['' || string_agg(q.js, '','') || '']'' from (
select ''{ "row":'' || row_to_json(t.*, true) || '' }'' js
from ((select ' || column_list || ' from ' || quote_ident(schema_name) || '.' || quote_ident(relation_name) || ' r ' || suffix || ')) as t
) q';
raise notice 'ROW QUERY: %', row_query;
execute row_query into rows_json;
return '{' ||
case when args->>'meta_data' = '["true"]' then
'"columns":' || endpoint.columns_json(schema_name, relation_name, exclude, include) || ',' ||
'"pk":"' || coalesce(endpoint.pk_name(schema_name, relation_name), 'null') || '",'
else ''
end ||
'"result":' || coalesce(rows_json, '[]') || '}';
end;
$$
language plpgsql;
/****************************************************************************************************
* FUNCTION row_select *
****************************************************************************************************/
create or replace function endpoint.row_select(
row_id meta.row_id,
args json
) returns json as $$
declare
_schema_name text;
_relation_name text;
pk_column_name text;
pk text;
row_query text;
row_json text;
columns_json text;
exclude text[];
include text[];
column_list text;
begin
-- raise notice 'ROW SELECT ARGS: %, %, %, %', schema_name, table_name, queryable_type, pk;
set local search_path = endpoint;
select (row_id::meta.schema_id).name into _schema_name;
select (row_id::meta.relation_id).name into _relation_name;
select (row_id).pk_column_name into pk_column_name;
select row_id.pk_value into pk;
-- Column list
-- Exclude
select array_agg(val)
from ((
select json_array_elements_text(value::json) as val
from json_array_elements_text(args->'exclude')
)) q
into exclude;
-- Include
select array_agg(val)
from ((
select json_array_elements_text(value::json) as val
from json_array_elements_text(args->'include')
)) q
into include;
if exclude is not null or include is not null then
select endpoint.column_list(_schema_name, _relation_name, '', exclude, include) into column_list;
else
select '*' into column_list;
end if;
row_query := 'select ''[{"row": '' || row_to_json(t.*, true) || ''}]'' from ' ||
'(select ' || column_list || ' from ' || quote_ident(_schema_name) || '.' || quote_ident(_relation_name) ||
' where ' || quote_ident(pk_column_name) || '=' || quote_literal(pk) ||
(
select '::' || c.type_name
from meta.relation_column c
where c.schema_name = _schema_name and
c.relation_name = _relation_name and
c.name = pk_column_name -- FIXME column integration
) ||
') t';
/*
-- This pk lookup only works if relation has a primary key in meta.column... what about foreign tables and views?
-- Also foreign data does not show up unless you use a subquery to get it to run first... Not sure why
row_query := 'select ''[{"row": '' || row_to_json(t.*) || ''}]'' from '
|| quote_ident(schema_name) || '.' || quote_ident(relation_name)
|| ' as t where ' || (
select quote_ident(pk_name) || ' = ' || quote_literal(pk) || '::' || pk_type
from endpoint.pk(schema_name, relation_name) p
);
*/
execute row_query into row_json;
--return '{"columns":' || columns_json(_schema_name, _relation_name) || ',"result":' || coalesce(row_json::text, '[]') || '}';
return '{' ||
case when args->>'meta_data' = '["true"]' then
'"columns":' || endpoint.columns_json(_schema_name, _relation_name, exclude, include) || ',' ||
'"pk":"' || endpoint.pk_name(_schema_name, _relation_name) || '",'
else ''
end ||
'"result":' || coalesce(row_json::text, '[]') || '}';
end;
$$
language plpgsql;
/****************************************************************************************************
* FUNCTION field_select *
****************************************************************************************************/
create or replace function endpoint.field_select(
field_id meta.field_id,
out field text,
out mimetype text
) returns record as $$
declare
_schema_name text;
_relation_name text;
pk text;
pk_column_name text;
pk_type text;
field_name text;
field_type text;
begin
raise notice 'FIELD SELECT ARGS: %', field_id;
set local search_path = endpoint;
select (field_id).schema_name into _schema_name;
select (field_id).relation_name into _relation_name;
select (field_id).pk_value into pk;
select (field_id).pk_column_name into pk_column_name;
select (field_id).column_name into field_name;
-- Find pk_type
select type_name
from meta.column
where id = field_id::meta.column_id
into pk_type;
-- Find field_type
select type_name
from meta.column
where schema_name = _schema_name
and relation_name = _relation_name
and name = field_name
into field_type;
if field_type <> 'endpoint.resource_bin' then
-- Find mimetype for this field
select m.mimetype
from endpoint.column_mimetype cm
join endpoint.mimetype m on m.id = cm.mimetype_id
where cm.column_id = field_id::meta.column_id
into mimetype;
end if;
-- Default mimetype
mimetype := coalesce(mimetype, 'application/json');
if field_type = 'endpoint.resource_bin' then
execute 'select (' || quote_ident(field_name) || ').mimetype, encode((' || quote_ident(field_name) || ').content, ''escape'')'
|| ' from ' || quote_ident(_schema_name) || '.' || quote_ident(_relation_name)
|| ' as t where ' || quote_ident(pk_column_name) || ' = ' || quote_literal(pk) || '::' || pk_type into mimetype, field;
elsif field_type = 'pg_catalog.bytea' then
execute 'select encode(' || quote_ident(field_name) || ', ''escape'') from ' || quote_ident(_schema_name) || '.' || quote_ident(_relation_name)
|| ' as t where ' || quote_ident(pk_column_name) || ' = ' || quote_literal(pk) || '::' || pk_type into field;
else
execute 'select ' || quote_ident(field_name) || ' from ' || quote_ident(_schema_name) || '.' || quote_ident(_relation_name)
|| ' as t where ' || quote_ident(pk_column_name) || '::text = ' || quote_literal(pk) || '::text' /* || pk_type */ into field;
end if;
-- implicitly returning field and mimetype
end;
$$
language plpgsql;
/******************************************************************************
* FUNCTION rows_select_function
some_function?args={ vals: [] } -- Array
some_function?args={ kwargs: {} } -- Key/value object
some_function?args={ kwargs: {} }&column=name
This function should do some much smarter stuff with return type
Should be able to select a single column when not returning SETOF
Some of the logic from the column-specific rows_select_function()
We also want to use column_mimetype if we are only sending one column back
*****************************************************************************/
create or replace function endpoint.rows_select_function(
function_id meta.function_id,
args json,
out result text,
out mimetype text
) returns record as $$
declare
_function_id alias for function_id;
function_return_type text;
row_is_composite boolean;
columns_json text;
function_args text;
_row record;
rows_json text[];
suffix text;
return_column text;
meta_data text;
result_type text;
begin
-- Get function row
select return_type
from meta.function f
where f.schema_name = (_function_id).schema_name
and f.name = (_function_id).name
and f.parameters = (_function_id).parameters
into function_return_type;
-- Meta data
meta_data := args->>'meta_data';
if meta_data = '["true"]' then
-- Find is return type is composite
select t.composite
from meta.function f
join meta.type t on t.id = f.return_type_id
where f.id = _function_id
into row_is_composite;
-- Build columns_json
if row_is_composite or result_type = 'record' then
select string_agg(row_to_json(q.*, true)::text, ',')
from (
select pga.attname as name,
pgt2.typname as "type"
from pg_catalog.pg_type pgt
inner join pg_class pgc
on pgc.oid = pgt.typrelid
inner join pg_attribute pga
on pga.attrelid = pgc.oid
inner join pg_type pgt2
on pgt2.oid = pga.atttypid
where pgt.oid = function_return_type::regtype
and pga.attname not in ('tableoid','cmax','xmax','cmin','xmin','ctid')
) q
into columns_json;
else
select row_to_json(q.*)
from (select (_function_id).name as name, function_return_type as "type") q
into columns_json;
end if;
end if;
-- Suffix clause: where, order by, offest, limit
suffix := endpoint.suffix_clause(args);
-- Return column
return_column := json_array_elements_text(args->'column');
-- Args
select json_array_elements_text::json
from json_array_elements_text(args->'args') into args;
-- Function Arguments
if args->'kwargs' is not null then
-- Build function arguments string
-- Cast to type_name found in meta.function_parameter
-- Using coalesce(function_args, '') so we can call function without arguments
select coalesce(
string_agg(quote_ident(r.key) || ':=' ||
case when -- pg_typeof(r.value) = 'json'::regtype and
json_typeof(r.value) = 'object' then
quote_literal(r.value) || '::json::'
else
quote_literal(btrim(r.value::text, '"')) || '::'
end ||
fp.type_name, ','),
'')
from json_each(args->'kwargs') r
join meta.function_parameter fp on
fp.schema_name = (_function_id).schema_name and -- Trick to speed up query
fp.function_id = _function_id and
fp.name = r.key
into function_args;
elsif args->'vals' is not null then
-- Transpose JSON array to comma-separated string
select string_agg(quote_literal(value), ',')
from json_array_elements_text(args->'vals') into function_args;
else
-- No arguments
select '' into function_args;
end if;
if return_column is null then
-- Default mimetype
mimetype := 'application/json';
/*** FIXME: this is broken */
-- Loop through function call results
for _row in execute 'select * from ' || quote_ident((_function_id).schema_name) || '.' || quote_ident((_function_id).name)
|| '(' || function_args || ') ' || suffix
loop
rows_json := array_append(rows_json, '{ "row": ' || row_to_json(_row, true) || ' }');
end loop;
-- Result JSON object
select '{' ||
case when meta_data = '["true"]' then
'"columns":[' || columns_json || '],'
else ''
end ||
'"result":' || coalesce('[' || array_to_string(rows_json,',') || ']', '[]') || '}'
into result;
else
execute 'select ' || return_column || ', pg_typeof(' || return_column || ') from ' ||
quote_ident((_function_id).schema_name) || '.' || quote_ident((_function_id).name) ||
'(' || function_args || ') ' || suffix into result, result_type;
if result_type <> 'resource_bin' and result_type <> 'endpoint.resource_bin' then
-- Get mimetype
select m.mimetype
from endpoint.function_field_mimetype ffm
join endpoint.mimetype m on m.id = ffm.mimetype_id
where ffm.schema_name = (_function_id).schema_name
and ffm.function_name = (_function_id).name
and field_name = return_column
into mimetype;
-- Default mimetype
mimetype := coalesce(mimetype, 'application/json');
if result_type = 'bytea' or result_type = 'pg_catalog.bytea' then
result := encode(result::bytea, 'escape');
end if;
else
mimetype := (result::endpoint.resource_bin).mimetype;
result := encode((result::endpoint.resource_bin).content, 'escape');
end if;
end if;
-- implicitly returning function result and mimetype
end;
$$
language plpgsql;
create or replace function endpoint.anonymous_rows_select_function(
_schema_name text,
_function_name text,
args json,
out result text,
out mimetype text
) returns record as $$
declare
_mimetype alias for mimetype;
columns_json text;
function_args text;
suffix text;
_row record;
rows_json text[];
return_column text;
result_type text;
begin
-- Build columns_json TODO ?
columns_json := '';
-- Return column
return_column := json_array_elements_text(args->'column');
-- Suffix clause: where, order by, offest, limit
suffix := endpoint.suffix_clause(args);
-- Args
select json_array_elements_text::json
from json_array_elements_text(args->'args') into args;
-- Function Arguments
if args->'vals' is not null then
-- Transpose JSON array to comma-separated string
select string_agg(quote_literal(value), ',') from json_array_elements_text(args->'vals') into function_args;
else
-- No arguments
function_args := '';
end if;
if return_column is null then
-- Default mimetype
mimetype := 'application/json';
-- Loop through function call results
for _row in execute 'select * from ' || quote_ident(_schema_name) || '.' || quote_ident(_function_name)
|| '(' || function_args || ') ' || suffix
loop
rows_json := array_append(rows_json, '{ "row": ' || row_to_json(_row, true) || ' }');
end loop;
-- Result JSON object
select '{"result":' || coalesce('[' || array_to_string(rows_json,',') || ']', '[]') || '}' into result;
else
execute 'select ' || return_column || ', pg_typeof(' || return_column || ') from ' || quote_ident(_schema_name) || '.' || quote_ident(_function_name)
|| '(' || function_args || ') ' || suffix into result, result_type;
if result_type <> 'resource_bin' and result_type <> 'endpoint.resource_bin' then
-- Get mimetype
select m.mimetype
from endpoint.function_field_mimetype ffm
join endpoint.mimetype m on m.id = ffm.mimetype_id
where ffm.schema_name = _schema_name
and ffm.function_name = _function_name
and field_name = return_column
into mimetype;
-- Default mimetype
mimetype := coalesce(mimetype, 'application/json');
if result_type = 'bytea' or result_type = 'pg_catalog.bytea' then
result := encode(result::bytea, 'escape');
end if;
else
mimetype := (result::endpoint.resource_bin).mimetype;
result := encode((result::endpoint.resource_bin).content, 'escape');
end if;
end if;
-- implicitly returning function result and mimetype
end;
$$
language plpgsql;
-- This function should disappear. Factor column selection into previous rows_select_function()
create or replace function endpoint.rows_select_function(
function_id meta.function_id,
args json,
column_name text
) returns text as $$
declare
row_type regtype;
row_is_composite boolean;
columns_json text;
function_args text;
result text;
begin
select case when substring(q.ret from 1 for 6) = 'SETOF ' then substring(q.ret from 6)
else q.ret
end::regtype
from (select pg_get_function_result(function_id.schema_name || '.' || (function_id.name)::regproc) as ret) q
into row_type;
-- Find is return type is composite
select t.composite
from meta.function f
join meta.type t on t.id = f.return_type_id
where f.id = function_id
into row_is_composite;
-- select typtype = 'c' from pg_type into row_is_composite where pg_type.oid = row_type;
-- Build columns_json
if row_is_composite then
select string_agg(row_to_json(q.*, true)::text, ',')
from (
select pga.attname as name,
pgt2.typname as "type"
from pg_type pgt
inner join pg_class pgc
on pgc.oid = pgt.typrelid
inner join pg_attribute pga
on pga.attrelid = pgc.oid
inner join pg_type pgt2
on pgt2.oid = pga.atttypid
where pgt.oid = row_type
and pga.attname not in ('tableoid','cmax','xmax','cmin','xmin','ctid')
) q
into columns_json;
else
select row_to_json(q.*, true)
from (select (function_id).name as name, row_type as "type") q
into columns_json;
end if;
-- Build function arguments string
select coalesce(
string_agg(quote_ident(r.key) || ':=' || quote_literal(r.value) || '::' || fp.type_name, ','),
'')
from json_each_text(args) r
join meta.function_parameters fp on
fp.function_id = function_id and
fp.name = r.key
into function_args;
-- Loop through function call results
execute 'select ' || quote_ident(column_name) || ' from ' || quote_ident(function_id.schema_name) || '.' || quote_ident(function_id.name)
|| '(' || function_args || ')' into result;
return result;
end;
$$
language plpgsql;
/******************************************************************************
* FUNCTION row_delete
*****************************************************************************/
create or replace function endpoint.row_delete(
row_id meta.row_id
) returns json as $$
declare
_schema_name text;
_table_name text;
pk text;
begin
select (row_id).schema_name into _schema_name;
select (row_id).relation_name into _table_name;
select row_id.pk_value::text into pk;
execute 'delete from ' || quote_ident(_schema_name) || '.' || quote_ident(_table_name) ||
' where ' || (