forked from aquametalabs/aquameta
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path001-server.sql
2225 lines (1754 loc) · 80.9 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
* Join graph thing
* Authentication handlers
*
* Copyriright (c) 2019 - Aquameta - http://aquameta.org/
******************************************************************************/
/******************************************************************************
*
*
* MIMETYPED RESOURCE TYPES
*
*
******************************************************************************/
create type endpoint.resource_bin as
(mimetype text, content bytea);
create type endpoint.resource_txt as
(mimetype text, content text);
create function endpoint.resource_bin(value json) returns endpoint.resource_bin as $$
select row(value->>'mimetype', value->>'content')::endpoint.resource_bin
$$ immutable language sql;
create cast (json as endpoint.resource_bin)
with function endpoint.resource_bin(json)
as assignment;
create function endpoint.resource_txt(value json) returns endpoint.resource_txt as $$
select row(value->>'mimetype', value->>'content')::endpoint.resource_txt
$$ immutable language sql;
create cast (json as endpoint.resource_txt)
with function endpoint.resource_txt(json)
as assignment;
/******************************************************************************
*
*
* DATA MODEL
*
*
******************************************************************************/
/******************************************************************************
* endpoint.mimetype
******************************************************************************/
create table mimetype (
id uuid not null default public.uuid_generate_v4() primary key,
mimetype text not null unique
);
/******************************************************************************
* endpoint.mimetype_extension
******************************************************************************/
create table endpoint.mimetype_extension (
id uuid not null default public.uuid_generate_v4() primary key,
mimetype_id uuid not null references endpoint.mimetype(id),
extension text unique
);
create table endpoint.column_mimetype (
id uuid not null default public.uuid_generate_v4() primary key,
column_id meta.column_id not null,
mimetype_id uuid not null references endpoint.mimetype(id)
);
create table endpoint.function_field_mimetype (
id uuid not null default public.uuid_generate_v4() primary key,
schema_name text,
function_name text,
field_name text,
mimetype_id uuid not null references endpoint.mimetype(id)
);
/******************************************************************************
* endpoint.resource
******************************************************************************/
create table endpoint."resource_binary" (
id uuid not null default public.uuid_generate_v4() primary key,
path text not null /* unique */,
mimetype_id uuid not null references endpoint.mimetype(id) on delete restrict on update cascade,
active boolean default true,
content bytea not null
);
create table endpoint."resource_text" (
id uuid not null default public.uuid_generate_v4() primary key,
path text not null /* unique */,
mimetype_id uuid not null references endpoint.mimetype(id) on delete restrict on update cascade,
active boolean default true,
content text not null
);
create table endpoint.resource_file (
id uuid not null default public.uuid_generate_v4() primary key,
file_id text not null,
active boolean default true,
path text not null /* unique */
);
create table endpoint.resource_directory (
id uuid not null default public.uuid_generate_v4() primary key,
directory_id text,
path text,
indexes boolean
);
create table endpoint.resource (
id uuid not null default public.uuid_generate_v4() primary key,
path text not null,
mimetype_id uuid not null references mimetype(id) on delete restrict on update cascade,
active boolean default true,
content text not null default ''
);
create table endpoint.template (
id uuid not null default public.uuid_generate_v4() primary key,
name text not null default '',
mimetype_id uuid not null references mimetype(id) on delete restrict on update cascade, -- why on update cascade??
content text not null default ''
);
create table endpoint.template_route (
id uuid not null default public.uuid_generate_v4() primary key,
template_id uuid not null references endpoint.template(id),
url_pattern text not null default '', -- matching paths may contain arguments from the url to be passed into the template
args text not null default '{}' -- this route's static arguments to be passed into the template
);
/******************************************************************************
* endpoint.site_settings
******************************************************************************/
create table endpoint.site_settings (
id uuid not null default public.uuid_generate_v4() primary key,
name text,
active boolean default false,
site_title text,
site_url text,
smtp_server_id uuid not null references email.smtp_server(id),
auth_from_email text
);
/*
insert into endpoint.site_settings (name, active, site_title, site_url, smtp_server_id, auth_from_email)
values ('development', true, '[ default site title ]', 'http://localhost/','ffb6e431-daa7-4a87-b3c5-1566fe73177c', 'noreply@localhost');
*/
create function endpoint.is_indexed(_path text) returns boolean as $$
begin
return true;
/*
select *
from (
select path, parent_id, 'directory' as type
from filesystem.directory
where id=_path
union
select path, directory_id as parent_id, 'file' as type
from filesystem.file
where id=_path;
) a;
with recursive t as (
select indexes, path
from endpoint.resource_directory
where path = _path
union all
select t.indexes, d.parent_id as path from t
join filesystem.directory d on d.path = t.path
)
select indexes from t;
*/
/*
select indexes from endpoint.resource_directory where directory_id=_path;
if indexes then
return true;
else
select indexes from endpoint.resource_directory where directory_id=(select parent_id from filesystem.directory where path=_path);
end if;
*/
/*
we start with a single url
*/
end;
$$ language plpgsql;
/******************************************************************************
*
*
* UTIL FUNCTIONS
*
*
******************************************************************************/
create function endpoint.set_mimetype(
_schema name,
_table name,
_column name,
_mimetype text
) returns void as $$
insert into endpoint.column_mimetype (column_id, mimetype_id)
select c.id, m.id
from meta.relation_column c
cross join endpoint.mimetype m
where c.schema_name = _schema and
c.relation_name = _table and
c.name = _column and
m.mimetype = _mimetype
$$
language sql;
/******************************************************************************
* FUNCTION columns_json
*****************************************************************************/
create type column_type as (
name text,
"type" text
);
-- returns the columns for a provided schema.relation as a json object
create function endpoint.columns_json(
_schema_name text,
_relation_name text,
exclude text[],
include text[],
out json json
) returns json as $$
begin
execute
'select (''['' || string_agg(row_to_json(row(c2.name, c2.type_name)::endpoint.column_type, true)::text, '','') || '']'')::json
from (select * from meta.relation_column c
where c.schema_name = ' || quote_literal(_schema_name) || ' and
c.relation_name = ' || quote_literal(_relation_name) ||
case when include is not null then
' and c.name = any(' || quote_literal(include) || ')'
else '' end ||
case when exclude is not null then
' and not c.name = any(' || quote_literal(exclude) || ')'
else '' end ||
' order by position) c2'
into json;
end;
$$
language plpgsql;
/****************************************************************************************************
* FUNCTION pk *
****************************************************************************************************/
-- returns the primary key name and type of the provided schema.relation
create function pk(
_schema_name name,
_relation_name name,
out pk_name text,
out pk_type text
) returns record as $$
select c.name, c.type_name
from meta.relation_column c --TODO: either use relation_column maybe? Or go look up the pk of a view somewhere else if we ever add that
where c.schema_name = _schema_name and
c.relation_name = _relation_name and
c.primary_key
$$
language sql;
/****************************************************************************************************
* FUNCTION pk_name *
****************************************************************************************************/
create function pk_name(
_schema_name name,
_relation_name name
) returns text as $$
select c.name
from meta.relation_column c --TODO: either use relation_column maybe? Or go look up the pk of a view somewhere else if we ever add that
where c.schema_name = _schema_name and
c.relation_name = _relation_name and
c.primary_key
$$
language sql security definer;
/*******************************************************************************
*
*
* JOIN GRAPH
*
* A multidimensional structure made up of rows from various tables connected
* by their foreign keys, for non-tabular query results made up of rows, but
* serialized into a table of type join_graph_row.
*
*
*
*******************************************************************************/
/*******************************************************************************
* TYPE join_graph_row
*
* label - the table being joined on's label/alias -- customers c
* row_id - the meta.row_id for this row
* row - the jsonb serialized row, whatever row_to_json outputs
* position - the order in which the rows are inserted, if applicable
* exclude - when true, these rows are excluded from the join graph
*******************************************************************************/
create type join_graph_row as (
label text,
row_id meta.row_id,
row jsonb,
position integer,
exclude boolean
);
/*******************************************************************************
* FUNCTION endpoint.construct_join_graph
*
* constructs a join graph table containing any rows matching the specified
* JOIN pattern
*******************************************************************************/
/*
sample usage:
select endpoint.construct_join_graph('foo',
'{ "schema_name": "bundle", "relation_name": "bundle", "label": "b", "join_local_field": "id", "where_clause": "b.id = ''e2edb6c9-cb76-4b57-9898-2e08debe99ee''" }',
'[
{"schema_name": "bundle", "relation_name": "commit", "label": "c", "join_local_field": "bundle_id", "related_label": "b", "related_field": "id"},
{"schema_name": "bundle", "relation_name": "rowset", "label": "r", "join_local_field": "id", "related_label": "c", "related_field": "rowset_id"},
{"schema_name": "bundle", "relation_name": "rowset_row", "label": "rr", "join_local_field": "rowset_id", "related_label": "r", "related_field": "id"},
{"schema_name": "bundle", "relation_name": "rowset_row_field", "label": "rrf", "join_local_field": "rowset_row_id", "related_label": "rr", "related_field": "id"},
{"schema_name": "bundle", "relation_name": "blob", "label": "blb", "join_local_field": "hash", "related_label": "rrf", "related_field": "value_hash"}
]');
*/
create or replace function endpoint.construct_join_graph (temp_table_name text, start_rowset json, subrowsets json) returns setof endpoint.join_graph_row
as $$
declare
tmp text;
schema_name text;
relation_name text;
label text;
pk_field text;
join_pk_field text;
join_local_field text;
related_label text;
related_field text;
where_clause text;
position integer;
exclude boolean;
rowset json;
q text;
ct integer;
begin
-- raise notice '######## CONSTRUCT_JSON_GRAPH % % %', temp_table_name, start_rowset, subrowsets;
-- create temp table
tmp := quote_ident(temp_table_name);
execute 'create temp table '
|| tmp
|| ' of endpoint.join_graph_row';
-- load up the starting relation
schema_name := quote_ident(start_rowset->>'schema_name');
relation_name := quote_ident(start_rowset->>'relation_name');
label := quote_ident(start_rowset->>'label');
join_local_field := quote_ident(start_rowset->>'join_local_field');
pk_field:= quote_ident(start_rowset->>'pk_field');
exclude:= coalesce(start_rowset->>'exclude', 'false');
position := coalesce(start_rowset->>'position', '0');
where_clause := coalesce ('where ' || (start_rowset->>'where_clause')::text, '');
-- raise notice '#### construct_join_graph PHASE 1: label: %, schema_name: %, relation_name: %, join_local_field: %, where_clause: %',
-- label, schema_name, relation_name, join_local_field, where_clause;
q := 'insert into ' || tmp || ' (label, row_id, row, position, exclude) '
|| ' select distinct ''' || label || ''','
|| ' meta.row_id(''' || schema_name || ''',''' || relation_name || ''',''' || pk_field || ''',' || label || '.' || pk_field || '::text), '
|| ' row_to_json(' || label || ', true)::jsonb, '
|| ' ' || position || ', '
|| ' ' || exclude
|| ' from ' || schema_name || '.' || relation_name || ' ' || label
|| ' ' || where_clause;
-- raise notice 'QUERY PHASE 1: %', q;
execute q;
-- load up sub-relations
for i in 0..(json_array_length(subrowsets) - 1) loop
rowset := subrowsets->i;
schema_name := quote_ident(rowset->>'schema_name');
relation_name := quote_ident(rowset->>'relation_name');
label := quote_ident(rowset->>'label');
join_local_field:= quote_ident(rowset->>'join_local_field');
join_pk_field:= quote_ident(rowset->>'join_local_field');
related_label := quote_ident(rowset->>'related_label');
related_field := quote_ident(rowset->>'related_field');
where_clause := coalesce ('where ' || (rowset->>'where_clause')::text, '');
exclude:= coalesce(rowset->>'exclude', 'false');
position := coalesce(rowset->>'position', '0');
-- raise notice '#### construct_join_graph PHASE 2: label: %, schema_name: %, relation_name: %, join_local_field: %, related_label: %, related_field: %, where_clause: %',
-- label, schema_name, relation_name, join_local_field, related_label, related_field, where_clause;
q := 'insert into ' || tmp || ' ( label, row_id, row, position, exclude) '
|| ' select distinct ''' || label || ''','
|| ' meta.row_id(''' || schema_name || ''',''' || relation_name || ''',''' || join_pk_field || ''',' || label || '.' || join_pk_field || '::text), '
|| ' row_to_json(' || label || ', true)::jsonb, '
|| ' ' || position || ', '
|| ' ' || exclude
|| ' from ' || schema_name || '.' || relation_name || ' ' || label
|| ' join ' || tmp || ' on ' || tmp || '.label = ''' || related_label || ''''
|| ' and (' || tmp || '.row)->>''' || related_field || ''' = ' || label || '.' || join_local_field || '::text'
|| ' ' || where_clause;
-- raise notice 'QUERY PHASE 2: %', q;
execute q;
end loop;
execute 'delete from ' || tmp || ' where exclude = true';
execute 'select * from ' || tmp || ' order by position';
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_id.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;
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 is_composite_type
****************************************************************************************************/
/*
when endpoint.is_composite_type($4->>' || quote_literal(json_object_keys) || ') then
($4->' || quote_literal(json_object_keys) || ')::text
create function endpoint.is_composite_type(value text) returns boolean as $$
begin
perform json_object_keys(value::json);
return true;
exception when invalid_parameter_value then
return false;
when invalid_text_representation then
return false;
end;
$$
immutable language plpgsql;
*/
/****************************************************************************************************
* FUNCTION is_json_object *
****************************************************************************************************/
create or replace function endpoint.is_json_object(
value text
) returns boolean as $$
begin
if value is null then return false; end if;
perform json_object_keys(value::json);
return true;
exception when invalid_parameter_value then
return false;
when invalid_text_representation then
return false;
end;
$$
immutable language plpgsql;
/****************************************************************************************************
* FUNCTION is_json_array *
****************************************************************************************************/
create function endpoint.is_json_array(
value text
) returns boolean as $$
begin
perform json_array_length(value::json);
return true;
exception when invalid_parameter_value then
return false;
when invalid_text_representation then
return false;
end;
$$
immutable 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_id.name) || ' = ' || quote_literal((row_id).pk_value)
)
) using args;
return '{}';
end;
$$
language plpgsql;
/****************************************************************************************************
* FUNCTION row_select *
****************************************************************************************************/
create 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_id.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: %, %, %, %, %', schema_name, table_name, queryable_type, pk, field_name;
set local search_path = endpoint;
select (field_id).column_id.relation_id.schema_id.name into _schema_name;
select (field_id).column_id.relation_id.name into _relation_name;
select (field_id).row_id.pk_value into pk;
select (field_id).row_id.pk_column_id.name into pk_column_name;
select (field_id).column_id.name into field_name;
-- Find pk_type
select type_name
from meta.column
where id = (field_id).row_id.pk_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).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) || ' = ' || quote_literal(pk) || '::' || pk_type into field;
end if;
-- implicitly returning field and mimetype
end;
$$
language plpgsql;
/****************************************************************************************************
*
* 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 }