-
-
Notifications
You must be signed in to change notification settings - Fork 372
/
Copy path05_msar.sql
5680 lines (4875 loc) · 192 KB
/
05_msar.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
SELECT msar.drop_all_msar_objects(
schemas_to_remove => ARRAY['msar', '__msar', 'mathesar_types'],
remove_custom_types => false,
strict => false
);
CREATE SCHEMA IF NOT EXISTS __msar;
CREATE SCHEMA IF NOT EXISTS msar;
----------------------------------------------------------------------------------------------------
----------------------------------------------------------------------------------------------------
-- HELPER FUNCTIONS
--
-- Low-level utils functions used by other functions.
----------------------------------------------------------------------------------------------------
----------------------------------------------------------------------------------------------------
CREATE OR REPLACE FUNCTION msar.mathesar_system_schemas() RETURNS text[] AS $$/*
Return a text array of the Mathesar System schemas.
Update this function whenever the list changes.
*/
SELECT ARRAY['msar', '__msar', 'mathesar_types']
$$ LANGUAGE SQL STABLE;
CREATE OR REPLACE FUNCTION msar.extract_smallints(v jsonb) RETURNS smallint[] AS $$/*
From the supplied JSONB value, extract all top-level JSONB array elements which can be successfully
cast to PostgreSQL smallint values. Return the resulting array of smallint values.
If the supplied jsonb value is not an array, this function will return an empty array.
If any jsonb array element cannot be cast to a smallint, it will be silently ignored.
This function does not raise any exceptions. It will always return an array.
This function should not be used on large arrays. It will be slow due to the performance
limitations[1] of EXCEPTION blocks.
[1]: https://www.postgresql.org/docs/current/plpgsql-control-structures.html#PLPGSQL-ERROR-TRAPPING
Args:
v: any JSONB value.
*/
DECLARE
result smallint[];
element jsonb;
BEGIN
FOR element IN SELECT jsonb_array_elements(v)
LOOP
BEGIN
result := result || (element::smallint);
EXCEPTION
-- Ignore any elements that can't be cast to smallint.
WHEN others THEN
CONTINUE;
END;
END LOOP;
RETURN result;
EXCEPTION
WHEN others THEN
RETURN '{}'::smallint[]; -- Return an empty array if the input is not an array.
END;
$$ LANGUAGE plpgsql IMMUTABLE RETURNS NULL ON NULL INPUT PARALLEL SAFE;
CREATE OR REPLACE FUNCTION msar.jsonb_keys_to_array(obj jsonb) RETURNS text[] AS $$/*
Similar to jsonb_object_keys but returns text[] instead of setof text.
*/
SELECT array_agg(x) FROM jsonb_object_keys(obj) as x;
$$ LANGUAGE SQL STABLE;
----------------------------------------------------------------------------------------------------
----------------------------------------------------------------------------------------------------
-- GENERAL DDL FUNCTIONS
--
-- Functions in this section are quite general, and are the basis of the others.
----------------------------------------------------------------------------------------------------
----------------------------------------------------------------------------------------------------
CREATE OR REPLACE FUNCTION
__msar.exec_ddl(command text) RETURNS text AS $$/*
Execute the given command, returning the command executed.
Not useful for SELECTing from tables. Most useful when you're performing DDL.
Args:
command: Raw string that will be executed as a command.
*/
BEGIN
EXECUTE command;
RETURN command;
END;
$$ LANGUAGE plpgsql RETURNS NULL ON NULL INPUT;
CREATE OR REPLACE FUNCTION
__msar.exec_ddl(command_template text, arguments variadic anyarray) RETURNS text AS $$/*
Execute a templated command, returning the command executed.
The template is given in the first argument, and all further arguments are used to fill in the
template. Not useful for SELECTing from tables. Most useful when you're performing DDL.
Args:
command_template: Raw string that will be executed as a command.
arguments: arguments that will be used to fill in the template.
*/
DECLARE formatted_command TEXT;
BEGIN
formatted_command := format(command_template, VARIADIC arguments);
RETURN __msar.exec_ddl(formatted_command);
END;
$$ LANGUAGE plpgsql RETURNS NULL ON NULL INPUT;
CREATE OR REPLACE FUNCTION
__msar.build_text_tuple(text[]) RETURNS text AS $$
SELECT '(' || string_agg(col, ', ') || ')' FROM unnest($1) x(col);
$$ LANGUAGE sql RETURNS NULL ON NULL INPUT;
----------------------------------------------------------------------------------------------------
----------------------------------------------------------------------------------------------------
-- GENERAL DQL FUNCTIONS
--
-- Functions in this section are quite general, and are the basis of the others.
----------------------------------------------------------------------------------------------------
----------------------------------------------------------------------------------------------------
CREATE OR REPLACE FUNCTION
__msar.exec_dql(command text) RETURNS jsonb AS $$/*
Execute the given command, returning a JSON object describing the records in the following form:
[
{"id": 1, "col1_name": "value1", "col2_name": "value2"},
{"id": 2, "col1_name": "value1", "col2_name": "value2"},
{"id": 3, "col1_name": "value1", "col2_name": "value2"},
...
]
Useful for SELECTing from tables. Most useful when you're performing DQL.
Note that you must include the primary key column(`id` in case of a Mathesar table) in the
command_template if you want the returned records to be uniquely identifiable.
Args:
command: Raw string that will be executed as a command.
*/
DECLARE
records jsonb;
BEGIN
EXECUTE 'WITH cte AS (' || command || ')
SELECT jsonb_agg(row_to_json(cte.*)) FROM cte' INTO records;
RETURN records;
END;
$$ LANGUAGE plpgsql RETURNS NULL ON NULL INPUT;
CREATE OR REPLACE FUNCTION
__msar.exec_dql(command_template text, arguments variadic anyarray) RETURNS jsonb AS $$/*
Execute a templated command, returning a JSON object describing the records in the following form:
[
{"id": 1, "col1_name": "value1", "col2_name": "value2"},
{"id": 2, "col1_name": "value1", "col2_name": "value2"},
{"id": 3, "col1_name": "value1", "col2_name": "value2"},
...
]
The template is given in the first argument, and all further arguments are used to fill in the
template. Useful for SELECTing from tables. Most useful when you're performing DQL.
Note that you must include the primary key column(`id` in case of a Mathesar table) in the
command_template if you want the returned records to be uniquely identifiable.
Args:
command_template: Raw string that will be executed as a command.
arguments: arguments that will be used to fill in the template.
*/
DECLARE formatted_command TEXT;
BEGIN
formatted_command := format(command_template, VARIADIC arguments);
RETURN __msar.exec_dql(formatted_command);
END;
$$ LANGUAGE plpgsql RETURNS NULL ON NULL INPUT;
----------------------------------------------------------------------------------------------------
----------------------------------------------------------------------------------------------------
-- INFO FUNCTIONS
--
-- Functions in this section get information about a given schema, table or column.
----------------------------------------------------------------------------------------------------
----------------------------------------------------------------------------------------------------
CREATE OR REPLACE FUNCTION msar.col_description(tab_id oid, col_id integer) RETURNS text AS $$/*
Transparent wrapper for col_description. Putting it in the `msar` namespace helps route all DB calls
from Python through a single Python module.
*/
BEGIN
RETURN col_description(tab_id, col_id);
END
$$ LANGUAGE plpgsql;
CREATE OR REPLACE FUNCTION msar.obj_description(obj_id oid, catalog_name text) RETURNS text AS $$/*
Transparent wrapper for obj_description. Putting it in the `msar` namespace helps route all DB calls
from Python through a single Python module.
*/
BEGIN
RETURN obj_description(obj_id, catalog_name);
END
$$ LANGUAGE plpgsql;
CREATE OR REPLACE FUNCTION __msar.jsonb_key_exists(data jsonb, key text) RETURNS boolean AS $$/*
Wraps the `?` jsonb operator for improved readability.
*/
BEGIN
RETURN data ? key;
END;
$$ LANGUAGE plpgsql;
CREATE OR REPLACE FUNCTION msar.schema_exists(schema_name text) RETURNS boolean AS $$/*
Return true if the schema exists, false otherwise.
Args :
sch_name: The name of the schema, UNQUOTED.
*/
SELECT EXISTS (SELECT 1 FROM pg_namespace WHERE nspname=schema_name);
$$ LANGUAGE SQL RETURNS NULL ON NULL INPUT;
CREATE OR REPLACE FUNCTION msar.get_schema_oid(sch_name text) RETURNS oid AS $$/*
Return the OID of a schema, or NULL if the schema does not exist.
Args :
sch_name: The name of the schema, UNQUOTED.
*/
SELECT oid FROM pg_namespace WHERE nspname=sch_name;
$$ LANGUAGE SQL RETURNS NULL ON NULL INPUT;
CREATE OR REPLACE FUNCTION msar.get_schema_name(sch_id oid) RETURNS TEXT AS $$/*
Return the UNQUOTED name for a given schema.
Raises an exception if the schema is not found.
Args:
sch_id: The OID of the schema.
*/
DECLARE sch_name text;
BEGIN
SELECT nspname INTO sch_name FROM pg_namespace WHERE oid=sch_id;
IF sch_name IS NULL THEN
RAISE EXCEPTION 'No schema with OID % exists.', sch_id
USING ERRCODE = '3F000'; -- invalid_schema_name
END IF;
RETURN sch_name;
END;
$$ LANGUAGE plpgsql;
CREATE OR REPLACE FUNCTION
__msar.build_qualified_name_sql(sch_name text, obj_name text) RETURNS text AS $$/*
Return the fully-qualified, properly quoted, name for a given database object (e.g., table).
Args:
sch_name: The schema of the object, unquoted.
obj_name: The name of the object, unqualified and unquoted.
*/
BEGIN
RETURN format('%I.%I', sch_name, obj_name);
END;
$$ LANGUAGE plpgsql RETURNS NULL ON NULL INPUT;
CREATE OR REPLACE FUNCTION
__msar.get_qualified_relation_name(rel_id oid) RETURNS text AS $$/*
Return the name for a given relation (e.g., table), qualified or quoted as appropriate.
In cases where the relation is already included in the search path, the returned name will not be
fully-qualified.
The relation *must* be in the pg_class table to use this function.
Args:
rel_id: The OID of the relation.
*/
BEGIN
RETURN rel_id::regclass::text;
END;
$$ LANGUAGE plpgsql RETURNS NULL ON NULL INPUT;
CREATE OR REPLACE FUNCTION
__msar.get_qualified_relation_name_or_null(rel_id oid) RETURNS text AS $$/*
Return the name for a given relation (e.g., table), qualified or quoted as appropriate.
In cases where the relation is already included in the search path, the returned name will not be
fully-qualified.
The relation *must* be in the pg_class table to use this function. This function will return NULL if
no corresponding relation can be found.
Args:
rel_id: The OID of the relation.
*/
SELECT CASE
WHEN EXISTS (SELECT oid FROM pg_catalog.pg_class WHERE oid=rel_id) THEN rel_id::regclass::text
END
$$ LANGUAGE SQL RETURNS NULL ON NULL INPUT;
CREATE OR REPLACE FUNCTION msar.get_relation_name(rel_oid oid) RETURNS TEXT AS $$/*
Return the UNQUOTED name of a given relation (e.g., table).
If the relation does not exist, an exception will be raised.
Args:
rel_oid: The OID of the relation.
*/
DECLARE rel_name text;
BEGIN
SELECT relname INTO rel_name FROM pg_class WHERE oid=rel_oid;
IF rel_name IS NULL THEN
RAISE EXCEPTION 'Relation with OID % does not exist', rel_oid
USING ERRCODE = '42P01'; -- undefined_table
END IF;
RETURN rel_name;
END;
$$ LANGUAGE plpgsql RETURNS NULL ON NULL INPUT;
CREATE OR REPLACE FUNCTION msar.get_relation_schema_name(rel_oid oid) RETURNS TEXT AS $$/*
Return the UNQUOTED name of the schema which contains a given relation (e.g., table).
If the relation does not exist, an exception will be raised.
Args:
rel_oid: The OID of the relation.
*/
DECLARE sch_name text;
BEGIN
SELECT n.nspname INTO sch_name
FROM pg_catalog.pg_class c
JOIN pg_catalog.pg_namespace n ON n.oid = c.relnamespace
WHERE c.oid = rel_oid;
IF sch_name IS NULL THEN
RAISE EXCEPTION 'Relation with OID % does not exist', rel_oid
USING ERRCODE = '42P01'; -- undefined_table
END IF;
RETURN sch_name;
END;
$$ LANGUAGE plpgsql RETURNS NULL ON NULL INPUT;
CREATE OR REPLACE FUNCTION
msar.get_relation_oid(sch_name text, rel_name text) RETURNS oid AS $$/*
Return the OID for a given relation (e.g., table).
The relation *must* be in the pg_class table to use this function.
Args:
sch_name: The schema of the relation, unquoted.
rel_name: The name of the relation, unqualified and unquoted.
*/
BEGIN
RETURN __msar.build_qualified_name_sql(sch_name, rel_name)::regclass::oid;
END;
$$ LANGUAGE plpgsql RETURNS NULL ON NULL INPUT;
CREATE OR REPLACE FUNCTION msar.get_relation_namespace_oid(rel_id oid) RETURNS oid AS $$/*
Get the OID of the namespace containing the given relation.
Most useful for getting the OID of the schema of a given table.
Args:
rel_id: The OID of the relation whose namespace we want to find.
*/
SELECT relnamespace FROM pg_class WHERE oid=rel_id;
$$ LANGUAGE SQL RETURNS NULL ON NULL INPUT;
CREATE OR REPLACE FUNCTION
msar.get_column_name(rel_id oid, col_id integer) RETURNS text AS $$/*
Return the UNQUOTED name for a given column in a given relation (e.g., table).
More precisely, this function returns the name of attributes of any relation appearing in the
pg_class catalog table (so you could find attributes of indices with this function).
Args:
rel_id: The OID of the relation.
col_id: The attnum of the column in the relation.
*/
SELECT attname::text FROM pg_attribute WHERE attrelid=rel_id AND attnum=col_id;
$$ LANGUAGE sql RETURNS NULL ON NULL INPUT;
CREATE OR REPLACE FUNCTION
msar.get_column_name(rel_id oid, col_name text) RETURNS text AS $$/*
Return the UNQUOTED name for a given column in a given relation (e.g., table).
More precisely, this function returns the unquoted name of attributes of any relation appearing in the
pg_class catalog table (so you could find attributes of indices with this function). If the given
col_name is not in the relation, we return null.
This has the effect of both quoting and preparing the given col_name, and also validating that it
exists.
Args:
rel_id: The OID of the relation.
col_name: The unquoted name of the column in the relation.
*/
SELECT attname::text FROM pg_attribute WHERE attrelid=rel_id AND attname=col_name;
$$ LANGUAGE sql RETURNS NULL ON NULL INPUT;
CREATE OR REPLACE FUNCTION
__msar.get_column_names(rel_id oid, columns jsonb) RETURNS text[] AS $$/*
Return the QUOTED names for given columns in a given relation (e.g., table).
- If the rel_id is given as 0, the assumption is that this is a new table, so we just apply normal
quoting rules to a column without validating anything further.
- If the rel_id is given as nonzero, and a column is given as text, then we validate that
the column name exists in the table, and use that.
- If the rel_id is given as nonzero, and the column is given as a number, then we look the column up
by attnum and use that name.
The columns jsonb can have a mix of numerical IDs and column names. The reason for this is that we
may be adding a column algorithmically, and this saves having to modify the column adding logic
based on the IDs passed by the user for given columns.
Args:
rel_id: The OID of the relation.
columns: A JSONB array of the unquoted names or IDs (can be mixed) of the columns.
*/
SELECT array_agg(
CASE
WHEN rel_id=0 THEN quote_ident(col #>> '{}')
WHEN jsonb_typeof(col)='number' THEN quote_ident(msar.get_column_name(rel_id, col::integer))
WHEN jsonb_typeof(col)='string' THEN quote_ident(msar.get_column_name(rel_id, col #>> '{}'))
END
)
FROM jsonb_array_elements(columns) AS x(col);
$$ LANGUAGE sql RETURNS NULL ON NULL INPUT;
CREATE OR REPLACE FUNCTION msar.get_attnum(rel_id oid, att_name text) RETURNS smallint AS $$/*
Get the attnum for a given attribute in the relation. Returns null if no such attribute exists.
Usually, this will be used to get the attnum for a column of a table.
Args:
rel_id: The relation where we'll look for the attribute.
att_name: The name of the attribute, unquoted.
*/
SELECT attnum FROM pg_attribute WHERE attrelid=rel_id AND attname=att_name;
$$ LANGUAGE SQL RETURNS NULL ON NULL INPUT;
CREATE OR REPLACE FUNCTION
msar.is_pkey_col(rel_id oid, col_id integer) RETURNS boolean AS $$/*
Return whether the given column is in the primary key of the given relation (e.g., table).
Args:
rel_id: The OID of the relation.
col_id: The attnum of the column in the relation.
*/
SELECT EXISTS (
SELECT 1 FROM pg_constraint WHERE
ARRAY[col_id::smallint] <@ conkey AND conrelid=rel_id AND contype='p'
);
$$ LANGUAGE SQL STABLE RETURNS NULL ON NULL INPUT;
CREATE OR REPLACE FUNCTION
msar.get_selectable_pkey_attnum(rel_id regclass) RETURNS smallint AS $$/*
Get the attnum of the single-column primary key for a relation if it has one. If not, return null.
The attnum will only be returned if the current user has SELECT on that column.
TODO: resolve potential code duplication between this function and `get_pk_column`.
Args:
rel_id: The OID of the relation.
*/
SELECT conkey[1] FROM pg_constraint
WHERE
conrelid = rel_id
AND cardinality(conkey) = 1
AND contype='p'
AND has_column_privilege(rel_id, conkey[1], 'SELECT');
$$ LANGUAGE SQL STABLE RETURNS NULL ON NULL INPUT;
CREATE OR REPLACE FUNCTION
msar.is_default_possibly_dynamic(tab_id oid, col_id integer) RETURNS boolean AS $$/*
Determine whether the default value for the given column is an expression or constant.
If the column default is an expression, then we return 'True', since that could be dynamic. If the
column default is a simple constant, we return 'False'. The check is not very sophisticated, and
errs on the side of returning 'True'. We simply pull apart the pg_node_tree representation of the
expression, and check whether the root node is a known function call type. Note that we do *not*
search any deeper in the tree than the root node. This means we won't notice that some expressions
are actually constant (or at least static), if they have a function call or operator as their root
node.
For example, the following would return 'True', even though they're not dynamic:
3 + 5
msar.cast_to_integer('8')
Args:
tab_id: The OID of the table with the column.
col_id: The attnum of the column in the table.
*/
SELECT
-- This is a typical dynamic default like NOW() or CURRENT_DATE
(split_part(substring(adbin, 2), ' ', 1) IN (('SQLVALUEFUNCTION'), ('FUNCEXPR')))
OR
-- This is an identity column `GENERATED {ALWAYS | DEFAULT} AS IDENTITY`
(attidentity <> '')
OR
-- Other generated columns show up here.
(attgenerated <> '')
FROM pg_attribute LEFT JOIN pg_attrdef ON attrelid=adrelid AND attnum=adnum
WHERE attrelid=tab_id AND attnum=col_id;
$$ LANGUAGE SQL RETURNS NULL ON NULL INPUT;
CREATE OR REPLACE FUNCTION
msar.is_mathesar_id_column(tab_id oid, col_id integer) RETURNS boolean AS $$/*
Determine whether the given column is our default Mathesar ID column.
The column in question is always attnum 1, and is created with the string
id integer PRIMARY KEY GENERATED BY DEFAULT AS IDENTITY
Args:
tab_id: The OID of the table whose column we'll check
col_id: The attnum of the column in question
*/
SELECT col_id=1 AND attname='id' AND atttypid='integer'::regtype::oid AND attidentity <> ''
FROM pg_attribute WHERE attrelid=tab_id AND attnum=col_id;
$$ LANGUAGE SQL RETURNS NULL ON NULL INPUT;
CREATE OR REPLACE FUNCTION
msar.get_cast_function_name(target_type regtype) RETURNS text AS $$/*
Return a string giving the appropriate name of the casting function for the target_type.
Currently set up to duplicate the logic in our python casting function builder. This will be
changed. Given a qualified, potentially capitalized type name, we
- Remove the namespace (schema),
- Replace any white space in the type name with underscores,
- Replace double quotes in the type name (e.g., the "char" type) with '_double_quote_'
- Use the prepped type name in the name `msar.cast_to_%s`.
Args:
target_type: This should be a type that exists.
*/
DECLARE target_type_prepped text;
BEGIN
-- TODO: Come up with a way to build these names that is more robust against collisions.
WITH unqualifier AS (
SELECT x[array_upper(x, 1)] unqualified_type
FROM regexp_split_to_array(target_type::text, '\.') x
), unspacer AS(
SELECT replace(unqualified_type, ' ', '_') unspaced_type
FROM unqualifier
)
SELECT replace(unspaced_type, '"', '_double_quote_')
FROM unspacer
INTO target_type_prepped;
RETURN format('msar.cast_to_%s', target_type_prepped);
END;
$$ LANGUAGE plpgsql RETURNS NULL ON NULL INPUT;
CREATE OR REPLACE FUNCTION msar.get_database_name(dat_id oid) RETURNS TEXT AS $$/*
Return the UNQUOTED name of a given database.
If the database does not exist, an exception will be raised.
Args:
dat_id: The OID of the role.
*/
DECLARE dat_name text;
BEGIN
SELECT datname INTO dat_name FROM pg_catalog.pg_database WHERE oid=dat_id;
IF dat_name IS NULL THEN
RAISE EXCEPTION 'Database with OID % does not exist', dat_id
USING ERRCODE = '42704'; -- undefined_object
END IF;
RETURN dat_name;
END;
$$ LANGUAGE plpgsql STABLE RETURNS NULL ON NULL INPUT;
CREATE OR REPLACE FUNCTION msar.get_role_name(rol_oid oid) RETURNS TEXT AS $$/*
Return the UNQUOTED name of a given role.
If the role does not exist, an exception will be raised.
Args:
rol_oid: The OID of the role.
*/
DECLARE rol_name text;
BEGIN
SELECT rolname INTO rol_name FROM pg_catalog.pg_roles WHERE oid=rol_oid;
IF rol_name IS NULL THEN
RAISE EXCEPTION 'Role with OID % does not exist', rol_oid
USING ERRCODE = '42704'; -- undefined_object
END IF;
RETURN rol_name;
END;
$$ LANGUAGE plpgsql STABLE RETURNS NULL ON NULL INPUT;
CREATE OR REPLACE FUNCTION msar.get_constraint_type_api_code(contype char) RETURNS TEXT AS $$/*
This function returns a string that represents the constraint type code used to describe
constraints when listing them within the Mathesar API.
PostgreSQL constraint types are documented by the `contype` field here:
https://www.postgresql.org/docs/current/catalog-pg-constraint.html
Notably, we don't include 't' (trigger) because triggers a bit different structurally and we don't
support working with them (yet?) in Mathesar.
*/
SELECT CASE contype
WHEN 'c' THEN 'check'
WHEN 'f' THEN 'foreignkey'
WHEN 'p' THEN 'primary'
WHEN 'u' THEN 'unique'
WHEN 'x' THEN 'exclude'
END;
$$ LANGUAGE SQL;
CREATE OR REPLACE FUNCTION msar.get_constraints_for_table(tab_id oid) RETURNS TABLE
(
oid oid,
name text,
type text,
columns smallint[],
referent_table_oid oid,
referent_columns smallint[]
)
AS $$/*
Return data describing the constraints set on a given table.
Args:
tab_id: The OID of the table.
*/
WITH constraints AS (
SELECT
oid,
conname AS name,
msar.get_constraint_type_api_code(contype::char) AS type,
conkey AS columns,
confrelid AS referent_table_oid,
confkey AS referent_columns
FROM pg_catalog.pg_constraint
WHERE conrelid = tab_id
)
SELECT *
FROM constraints
-- Only return constraints with types that we're able to classify
WHERE type IS NOT NULL
$$ LANGUAGE SQL;
CREATE OR REPLACE FUNCTION
msar.get_constraint_name(con_id oid) RETURNS text AS $$/*
Return the UNQUOTED constraint name of the corresponding constraint oid.
Args:
con_id: The OID of the constraint.
*/
BEGIN
RETURN conname::text FROM pg_constraint WHERE pg_constraint.oid = con_id;
END;
$$ LANGUAGE plpgsql RETURNS NULL ON NULL INPUT;
CREATE OR REPLACE FUNCTION
msar.get_pk_column(rel_id oid) RETURNS smallint AS $$/*
Return the first column attnum in the primary key of a given relation (e.g., table).
TODO: resolve potential code duplication between this function and `get_selectable_pkey_attnum`.
Args:
rel_id: The OID of the relation.
*/
SELECT CASE WHEN array_length(conkey, 1) = 1 THEN conkey[1] END
FROM pg_constraint
WHERE contype='p'
AND conrelid=rel_id;
$$ LANGUAGE SQL RETURNS NULL ON NULL INPUT;
CREATE OR REPLACE FUNCTION
msar.get_pk_column(sch_name text, rel_name text) RETURNS smallint AS $$/*
Return the first column attnum in the primary key of a given relation (e.g., table).
Args:
sch_name: The schema of the relation, unquoted.
rel_name: The name of the relation, unqualified and unquoted.
*/
SELECT CASE WHEN array_length(conkey, 1) = 1 THEN conkey[1] END
FROM pg_constraint
WHERE contype='p'
AND conrelid=msar.get_relation_oid(sch_name, rel_name);
$$ LANGUAGE SQL RETURNS NULL ON NULL INPUT;
CREATE OR REPLACE FUNCTION
msar.get_column_type(rel_id oid, col_id smallint) RETURNS text AS $$/*
Return the type of a given column in a relation.
Args:
rel_id: The OID of the relation.
col_id: The attnum of the column in the relation.
*/
SELECT atttypid::regtype
FROM pg_attribute
WHERE attnum = col_id
AND attrelid = rel_id;
$$ LANGUAGE SQL RETURNS NULL ON NULL INPUT;
CREATE OR REPLACE FUNCTION
msar.get_column_type(sch_name text, rel_name text, col_name text) RETURNS text AS $$/*
Return the type of a given column in a relation.
Args:
sch_name: The schema of the relation, unquoted.
rel_name: The name of the relation, unqualified and unquoted.
col_name: The name of the column in the relation, unquoted.
*/
SELECT atttypid::regtype
FROM pg_attribute
WHERE attname = quote_ident(col_name)
AND attrelid = msar.get_relation_oid(sch_name, rel_name);
$$ LANGUAGE SQL RETURNS NULL ON NULL INPUT;
CREATE OR REPLACE FUNCTION
msar.get_interval_fields(typ_mod integer) RETURNS text AS $$/*
Return the string giving the fields for an interval typmod integer.
This logic is ported from the relevant PostgreSQL source code, reimplemented in SQL. See the
`intervaltypmodout` function at
https://doxygen.postgresql.org/backend_2utils_2adt_2timestamp_8c.html
Args:
typ_mod: The atttypmod from the pg_attribute table. Should be valid for the interval type.
*/
SELECT CASE (typ_mod >> 16 & 32767)
WHEN 1 << 2 THEN 'year'
WHEN 1 << 1 THEN 'month'
WHEN 1 << 3 THEN 'day'
WHEN 1 << 10 THEN 'hour'
WHEN 1 << 11 THEN 'minute'
WHEN 1 << 12 THEN 'second'
WHEN (1 << 2) | (1 << 1) THEN 'year to month'
WHEN (1 << 3) | (1 << 10) THEN 'day to hour'
WHEN (1 << 3) | (1 << 10) | (1 << 11) THEN 'day to minute'
WHEN (1 << 3) | (1 << 10) | (1 << 11) | (1 << 12) THEN 'day to second'
WHEN (1 << 10) | (1 << 11) THEN 'hour to minute'
WHEN (1 << 10) | (1 << 11) | (1 << 12) THEN 'hour to second'
WHEN (1 << 11) | (1 << 12) THEN 'minute to second'
END;
$$ LANGUAGE SQL RETURNS NULL ON NULL INPUT;
CREATE OR REPLACE FUNCTION
msar.get_type_options(typ_id regtype, typ_mod integer, typ_ndims integer) RETURNS jsonb AS $$/*
Return the type options calculated from a type, typmod pair.
This function uses a number of hard-coded constants. The form of the returned object is determined
by the input type, but the keys will be a subset of:
precision: the precision of a numeric or interval type. See PostgreSQL docs for details.
scale: the scale of a numeric type
fields: See PostgreSQL documentation of the `interval` type.
length: Applies to "text" types where the user can specify the length.
item_type: Gives the type of array members for array-types
Args:
typ_id: an OID or valid type representing string will work here.
typ_mod: The integer corresponding to the type options; see pg_attribute catalog table.
typ_ndims: Used to determine whether the type is actually an array without an extra join.
*/
SELECT nullif(
CASE
WHEN typ_id = ANY('{numeric, _numeric}'::regtype[]) THEN
jsonb_build_object(
-- This calculation is modified from the relevant PostgreSQL source code. See the function
-- numeric_typmod_precision(int32) at
-- https://doxygen.postgresql.org/backend_2utils_2adt_2numeric_8c.html
'precision', ((nullif(typ_mod, -1) - 4) >> 16) & 65535,
-- This calculation is from numeric_typmod_scale(int32) at the same location
'scale', (((nullif(typ_mod, -1) - 4) & 2047) # 1024) - 1024
)
WHEN typ_id = ANY('{interval, _interval}'::regtype[]) THEN
jsonb_build_object(
'precision', nullif(typ_mod & 65535, 65535),
'fields', msar.get_interval_fields(typ_mod)
)
WHEN typ_id = ANY('{bpchar, _bpchar, varchar, _varchar}'::regtype[]) THEN
-- For char and varchar types, the typemod is equal to 4 more than the set length.
jsonb_build_object('length', nullif(typ_mod, -1) - 4)
WHEN typ_id = ANY(
'{bit, varbit, time, timetz, timestamp, timestamptz}'::regtype[]
|| '{_bit, _varbit, _time, _timetz, _timestamp, _timestamptz}'::regtype[]
) THEN
-- For all these types, the typmod is equal to the precision.
jsonb_build_object(
'precision', nullif(typ_mod, -1)
)
ELSE jsonb_build_object()
END
|| CASE
WHEN typ_ndims>0 THEN
-- This string wrangling is debatably dubious, but avoids a slow join.
jsonb_build_object('item_type', rtrim(typ_id::regtype::text, '[]'))
ELSE '{}'
END,
'{}'
)
$$ LANGUAGE SQL RETURNS NULL ON NULL INPUT;
CREATE OR REPLACE FUNCTION msar.get_valid_target_type_strings(typ_id regtype) RETURNS jsonb AS $$/*
Given a source type, return the target types for which Mathesar provides a casting function.
Args:
typ_id: The type we're casting from.
*/
SELECT jsonb_agg(prorettype::regtype::text)
FROM pg_proc
WHERE
pronamespace=msar.get_schema_oid('msar')
AND proargtypes[0]=typ_id
AND left(proname, 5) = 'cast_';
$$ LANGUAGE SQL RETURNS NULL ON NULL INPUT;
CREATE OR REPLACE FUNCTION msar.has_dependents(rel_id oid, att_id smallint) RETURNS boolean AS $$/*
Return a boolean according to whether the column identified by the given oid, attnum pair is
referenced (i.e., would dropping that column require CASCADE?).
Args:
rel_id: The relation of the attribute.
att_id: The attnum of the attribute in the relation.
*/
SELECT EXISTS (
SELECT 1 FROM pg_depend WHERE refobjid=rel_id AND refobjsubid=att_id AND deptype='n'
);
$$ LANGUAGE SQL RETURNS NULL ON NULL INPUT;
CREATE OR REPLACE FUNCTION msar.get_fkey_map_table(tab_id oid)
RETURNS TABLE (target_oid oid, conkey smallint, confkey smallint)
AS $$/*
Generate a table mapping foreign key values from refererrer to referent tables.
Given an input table (identified by OID), we return a table with each row representing a foreign key
constraint on that table. We return only single-column foreign keys, and only one per foreign key
column.
Args:
tab_id: The OID of the table containing the foreign key columns to map.
*/
SELECT DISTINCT ON (conkey) pgc.confrelid AS target_oid, x.conkey AS conkey, y.confkey AS confkey
FROM pg_constraint pgc, LATERAL unnest(conkey) x(conkey), LATERAL unnest(confkey) y(confkey)
WHERE
pgc.conrelid = tab_id
AND pgc.contype='f'
AND cardinality(pgc.confkey) = 1
AND has_column_privilege(tab_id, x.conkey, 'SELECT')
AND has_column_privilege(pgc.confrelid, y.confkey, 'SELECT')
ORDER BY conkey, target_oid, confkey;
$$ LANGUAGE SQL STABLE RETURNS NULL ON NULL INPUT;
CREATE OR REPLACE FUNCTION
msar.list_column_privileges_for_current_role(tab_id regclass, attnum smallint) RETURNS jsonb AS $$/*
Return a JSONB array of all privileges current_user holds on the passed table.
*/
SELECT coalesce(jsonb_agg(privilege), '[]'::jsonb)
FROM
unnest(ARRAY['SELECT', 'INSERT', 'UPDATE', 'REFERENCES']) AS x(privilege),
pg_catalog.has_column_privilege(tab_id, attnum, privilege) as has_privilege
WHERE has_privilege;
$$ LANGUAGE SQL STABLE RETURNS NULL ON NULL INPUT;
CREATE OR REPLACE FUNCTION
msar.describe_column_default(tab_id regclass, col_id smallint) RETURNS jsonb AS $$/*
Return a JSONB object describing the default (if any) of the given column in the given table.
The returned JSON will have the form:
{
"value": <any>,
"is_dynamic": <bool>,
}
If the default is possibly dynamic, i.e., if "is_dynamic" is true, then "value" will be a text SQL
expression that generates the default value if evaluated. If it is not dynamic, then "value" is the
actual default value.
*/
DECLARE
def_expr text;
def_json jsonb;
BEGIN
def_expr = CASE
WHEN attidentity='' THEN pg_catalog.pg_get_expr(adbin, tab_id)
ELSE 'identity'
END
FROM pg_catalog.pg_attribute LEFT JOIN pg_catalog.pg_attrdef ON attrelid=adrelid AND attnum=adnum
WHERE attrelid=tab_id AND attnum=col_id;
IF def_expr IS NULL THEN
RETURN NULL;
ELSIF msar.is_default_possibly_dynamic(tab_id, col_id) THEN
EXECUTE format(
'SELECT jsonb_build_object(''value'', %L, ''is_dynamic'', true)', def_expr
) INTO def_json;
ELSE
EXECUTE format(
'SELECT jsonb_build_object(''value'', msar.format_data(%s), ''is_dynamic'', false)', def_expr
) INTO def_json;
END IF;
RETURN def_json;
END;
$$ LANGUAGE plpgsql RETURNS NULL ON NULL INPUT;
CREATE OR REPLACE FUNCTION msar.get_column_info(tab_id regclass) RETURNS jsonb AS $$/*
Given a table identifier, return an array of objects describing the columns of the table.
Each returned JSON object in the array will have the form:
{
"id": <int>,
"name": <str>,
"type": <str>,
"type_options": <obj>,
"nullable": <bool>,
"primary_key": <bool>,
"default": {"value": <str>, "is_dynamic": <bool>},
"has_dependents": <bool>,
"description": <str>,
"current_role_priv": [<str>, <str>, ...],
"valid_target_types": [<str>, <str>, ...]
}
The `type_options` object is described in the docstring of `msar.get_type_options`. The `default`
object has the keys:
value: A string giving the value (as an SQL expression) of the default.
is_dynamic: A boolean giving whether the default is (likely to be) dynamic.
*/
SELECT jsonb_agg(
jsonb_build_object(
'id', attnum,
'name', attname,
'type', CASE WHEN attndims>0 THEN '_array' ELSE atttypid::regtype::text END,
'type_options', msar.get_type_options(atttypid, atttypmod, attndims),
'nullable', NOT attnotnull,
'primary_key', COALESCE(pgi.indisprimary, false),
'default', msar.describe_column_default(tab_id, attnum),
'has_dependents', msar.has_dependents(tab_id, attnum),
'description', msar.col_description(tab_id, attnum),
'current_role_priv', msar.list_column_privileges_for_current_role(tab_id, attnum),
'valid_target_types', msar.get_valid_target_type_strings(atttypid)
)
)
FROM pg_attribute pga
LEFT JOIN pg_index pgi ON pga.attrelid=pgi.indrelid AND pga.attnum=ANY(pgi.indkey)
LEFT JOIN pg_attrdef pgd ON pga.attrelid=pgd.adrelid AND pga.attnum=pgd.adnum
WHERE pga.attrelid=tab_id AND pga.attnum > 0 and NOT attisdropped;
$$ LANGUAGE SQL RETURNS NULL ON NULL INPUT;
CREATE OR REPLACE FUNCTION msar.column_exists(tab_id oid, col_name text) RETURNS boolean AS $$/*