-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdatalink.sql
2924 lines (2607 loc) · 104 KB
/
datalink.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
--
-- datalink
-- version 0.24 lacanoid@ljudmila.org
--
---------------------------------------------------
SET client_min_messages = warning;
COMMENT ON SCHEMA datalink IS 'SQL/MED DATALINK support';
GRANT USAGE ON SCHEMA datalink TO PUBLIC;
---------------------------------------------------
-- url type
---------------------------------------------------
ALTER extension uri SET schema pg_catalog;
-- CREATE DOMAIN url AS text;
CREATE DOMAIN url AS uri;
---------------------------------------------------
-- datalink type
---------------------------------------------------
CREATE DOMAIN dl_linktype AS text;
CREATE DOMAIN dl_token AS uuid;
CREATE DOMAIN file_path AS text;
COMMENT ON DOMAIN file_path IS 'Absolute file system path';
ALTER DOMAIN file_path ADD CONSTRAINT file_path_noparent CHECK(value not like all('{../%,%/../%,%/..}'));
ALTER DOMAIN file_path ADD CONSTRAINT file_path_chars CHECK(not value ~* '[%*]');
ALTER DOMAIN file_path ADD CONSTRAINT file_path_absolute CHECK(length(value)=0 or value like '/%');
ALTER DOMAIN file_path ADD CONSTRAINT file_path_noserver CHECK(not value like '%//%');
/* ADD ADDITIONAL CONSTRAINTS FOR FILENAMES HERE */
/*
CREATE DOMAIN pg_catalog.datalink AS jsonb;
COMMENT ON DOMAIN pg_catalog.datalink IS 'SQL/MED DATALINK like type for storing URLs';
*/
CREATE TYPE pg_catalog.datalink;
CREATE OR REPLACE FUNCTION dl_datalink_in(cstring)
RETURNS datalink LANGUAGE internal IMMUTABLE PARALLEL SAFE STRICT
AS $function$jsonb_in$function$;
CREATE OR REPLACE FUNCTION dl_datalink_out(datalink)
RETURNS cstring LANGUAGE internal IMMUTABLE PARALLEL SAFE STRICT
AS $function$jsonb_out$function$;
CREATE OR REPLACE FUNCTION dl_datalink_recv(internal)
RETURNS datalink LANGUAGE internal IMMUTABLE PARALLEL SAFE STRICT
AS $function$jsonb_recv$function$;
CREATE OR REPLACE FUNCTION dl_datalink_send(datalink)
RETURNS bytea LANGUAGE internal IMMUTABLE PARALLEL SAFE STRICT
AS $function$jsonb_send$function$;
CREATE TYPE pg_catalog.datalink (
INPUT = dl_datalink_in,
OUTPUT = dl_datalink_out,
SEND = dl_datalink_send,
RECEIVE = dl_datalink_recv,
TYPMOD_IN = varchartypmodin,
TYPMOD_OUT = varchartypmodout,
INTERNALLENGTH = VARIABLE,
ALIGNMENT = int4,
STORAGE = extended,
CATEGORY = 'U',
DELIMITER = ',',
COLLATABLE = false
);
COMMENT ON TYPE pg_catalog.datalink IS 'SQL/MED DATALINK type for external file references';
create cast (datalink as jsonb) without function;
-- create cast (datalink as jsonb) without function as implicit;
-- create cast (datalink as jsonb) with inout as implicit;
-- create cast (jsonb as datalink) with inout;
---------------------------------------------------
-- link control options
---------------------------------------------------
create type dl_link_control as enum ( 'NO','FILE' );
create type dl_integrity as enum ( 'NONE','SELECTIVE','ALL' );
create type dl_read_access as enum ( 'FS','DB' );
create type dl_write_access as enum ( 'FS','BLOCKED', 'TOKEN', 'ADMIN' );
create type dl_recovery as enum ( 'NO','YES' );
create type dl_on_unlink as enum ( 'NONE','RESTORE','DELETE' );
create cast (text as dl_link_control) with inout as implicit;
create cast (text as dl_integrity) with inout as implicit;
create cast (text as dl_read_access) with inout as implicit;
create cast (text as dl_write_access) with inout as implicit;
create cast (text as dl_recovery) with inout as implicit;
create cast (text as dl_on_unlink) with inout as implicit;
create domain dl_lco as integer;
comment on type dl_lco is 'Datalink Link Control Options as integer';
create domain whoami as name check ( value = current_user );
comment on type whoami is 'Domain which can be set only to current user';
---------------------------------------------------
-- view of all datalink types
create or replace view types as
with recursive r (regtype, typtype, typmod, depth)
as (
select oid::regtype, t.typtype,
case when t.typtypmod > 0 then t.typtypmod-4 end :: datalink.dl_lco,
0
from pg_catalog.pg_type as t
where oid = 'pg_catalog.datalink'::regtype
union all
select oid::regtype, t.typtype,
coalesce(
case when t.typtypmod > 0 then t.typtypmod-4 end :: datalink.dl_lco,
r.typmod
),
depth+1
from pg_catalog.pg_type as t
join r on t.typbasetype = r.regtype
)
select * from r;
grant select on types to public;
---------------------------------------------------
-- functions intended for constraints
-- does datalink reference a local file?
create or replace function is_local(datalink) returns boolean
language sql immutable strict as $$
select ($1::jsonb->>'a')::text ~* '^file:(//|//localhost)?/[^/]';$$;
comment on function is_local(datalink)
is 'The address of this datalink references a local file';
-- does datalink contain a valid URI?
create or replace function is_valid(datalink) returns boolean
language sql immutable strict as $$
select case when ($1::jsonb->>'a')::text ilike 'file://%'
then pg_catalog.dlurlpathonly($1)::datalink.file_path is not null
else ($1::jsonb->>'a')::uri is not null
end
$$;
comment on function is_valid(datalink)
is 'The address of this datalink is a valid URI';
-- does datalink contain a succesful HTTP response code (200..299)?
create or replace function is_http_success(datalink) returns boolean
language sql immutable strict as $$
select cast($1::jsonb->>'rc' as int) between 200 and 299 $$;
comment on function is_http_success(datalink)
is 'The HTTP return code of this datalink indicates success';
---------------------------------------------------
-- link control options
---------------------------------------------------
CREATE TABLE link_control_options (
lco dl_lco primary key,
link_control dl_link_control,
integrity dl_integrity,
read_access dl_read_access,
write_access dl_write_access,
recovery dl_recovery,
on_unlink dl_on_unlink
);
comment on table link_control_options is 'Valid combinations of Datalink Link Control Options';
grant select on link_control_options to public;
---------------------------------------------------
-- helper functions
---------------------------------------------------
CREATE FUNCTION dl_lco(
link_control dl_link_control DEFAULT 'NO'::dl_link_control,
integrity dl_integrity DEFAULT 'NONE'::dl_integrity,
read_access dl_read_access DEFAULT 'FS'::dl_read_access,
write_access dl_write_access DEFAULT 'FS'::dl_write_access,
recovery dl_recovery DEFAULT 'NO'::dl_recovery,
on_unlink dl_on_unlink DEFAULT 'NONE'::dl_on_unlink)
RETURNS dl_lco
LANGUAGE sql IMMUTABLE
AS $_$
select cast (trunc(
(case $2 when 'ALL' then 2 when 'SELECTIVE' then 1 when 'NONE' then 0 else 0 end)
+ 10 * (
(case $4
when 'ADMIN' then 3 when 'TOKEN' then 2 when 'BLOCKED' then 1 when 'FS' then 0
else 0 end)
+ 4 * (case $3 when 'DB' then 1 when 'FS' then 0 else 0 end)
+ 10 * (
(case $5 when 'YES' then 1 when 'NO' then 0 else 0 end)
+ (case $6 when 'DELETE' then 2 when 'RESTORE' then 0 when 'NONE' then 0 else 0 end)
))
) as datalink.dl_lco)
$_$;
COMMENT ON FUNCTION dl_lco(
dl_link_control,dl_integrity,dl_read_access,dl_write_access,dl_recovery,dl_on_unlink)
IS 'Calculate dl_lco from enumerated options';
---------------------------------------------------
-- find dl_lco for a column
create or replace function dl_lco(regclass regclass,column_name name) returns dl_lco
as $$
select coalesce(
dt.typmod,
case when atttypmod > 0 then atttypmod-4 else 0 end :: datalink.dl_lco
) as lco
from pg_attribute a
join pg_type t on (t.oid=a.atttypid)
join datalink.types dt ON (dt.regtype = t.oid)
where attrelid = $1 and attname = $2
and attnum > 0 and not attisdropped
$$ language sql;
COMMENT ON FUNCTION dl_lco(regclass, name)
IS 'Find dl_lco for a table column';
---------------------------------------------------
-- find dl_lco for a datalink
CREATE OR REPLACE FUNCTION dl_lco(datalink)
RETURNS dl_lco LANGUAGE sql
SECURITY DEFINER
AS $function$
select coalesce((select lco
from datalink.dl_linked_files f where f.token = ($1::jsonb->>'b')::datalink.dl_token)
,0)::datalink.dl_lco
$function$;
COMMENT ON FUNCTION dl_lco(datalink)
IS 'Find dl_lco for a linked datalink';
---------------------------------------------------
-- expand lco into individual options
CREATE FUNCTION link_control_options(dl_lco)
RETURNS link_control_options
LANGUAGE sql IMMUTABLE AS $_$
select * from datalink.link_control_options where lco = $1
$_$;
COMMENT ON FUNCTION link_control_options(dl_lco)
IS 'Calculate link_control_options from dl_lco';
---------------------------------------------------
-- get link_control_options for a linked datalink
CREATE OR REPLACE FUNCTION link_control_options(datalink)
RETURNS link_control_options
LANGUAGE sql IMMUTABLE
AS $function$
select lco.*
from datalink.link_control_options lco
where lco.lco = datalink.dl_lco($1)
$function$
;
COMMENT ON FUNCTION link_control_options(datalink)
IS 'Get link_control_options for a linked datalink';
---------------------------------------------------
-- init options table
---------------------------------------------------
-- initialize valid link control options
insert into link_control_options
with l as (
select datalink.dl_lco(link_control=>lc,integrity=>itg,
read_access=>ra,write_access=>wa,
recovery=>rec,on_unlink=>unl
),*
from
unnest(array['NO','FILE']) as lc,
unnest(array['NONE','SELECTIVE','ALL']) as itg,
unnest(array['FS','DB']) as ra,
unnest(array['FS','BLOCKED','TOKEN','ADMIN']) as wa,
unnest(array['NO','YES']) as rec,
unnest(array['NONE','RESTORE','DELETE']) as unl
)
-- valid option combinations per SQL/MED 2011
select distinct * from l
where lc='NO' and itg='NONE' and ra='FS' and wa='FS' and unl='NONE' and rec='NO'
or lc='FILE' and itg='SELECTIVE' and ra='FS' and wa='FS' and unl='NONE' and rec='NO'
or lc='FILE' and itg='ALL' and (
ra='FS' and wa='FS' and unl='NONE' and rec='NO'
or ra='FS' and wa='BLOCKED' and unl='RESTORE'
or ra='DB' and wa<>'FS' and unl<>'NONE'
)
-- and not (rec='NO' and unl='DELETE')
order by dl_lco
;
-- is class adminable (owned or we are superuser)
CREATE FUNCTION has_class_privilege(my_class regclass) RETURNS boolean
LANGUAGE sql
AS $_$
select case
when current_setting('is_superuser')::boolean then true
when (select rolsuper
from pg_roles where oid = current_role::regrole) then true
else (select relowner = current_role::regrole
from pg_class where oid = $1)
end
$_$;
---------------------------------------------------
-- views
---------------------------------------------------
-- internal datalink columns view
CREATE VIEW dl_columns AS
SELECT c.relowner::regrole AS table_owner,
s.nspname AS schema_name,
c.relname AS table_name,
a.attname AS column_name,
dl_lco(c.oid::regclass,a.attname::name) AS lco,
a.attnum,
-- a.atttypmod,
a.attoptions,
a.attfdwoptions,
c.oid::regclass AS regclass,
a.atttypid::regtype as regtype,
col_description(c.oid, (a.attnum)::integer) AS comment
FROM pg_class c
JOIN pg_namespace s ON (s.oid = c.relnamespace)
JOIN pg_attribute a ON (c.oid = a.attrelid)
JOIN pg_type t ON (t.oid = a.atttypid)
JOIN datalink.types dt ON (dt.regtype = t.oid)
LEFT JOIN pg_attrdef def ON (c.oid = def.adrelid AND a.attnum = def.adnum)
WHERE (c.relkind = 'r'::"char" AND a.attnum > 0 AND NOT a.attisdropped)
ORDER BY s.nspname, c.relname, a.attnum;
---------------------------------------------------
-- user datalink columns view
CREATE VIEW columns AS
SELECT
cast(regclass as text) as table_name,
column_name,
lco.link_control,
lco.integrity,
lco.read_access,
lco.write_access,
lco.recovery,
lco.on_unlink
FROM datalink.dl_columns c
LEFT JOIN link_control_options lco ON lco.lco=coalesce(c.lco,0)
WHERE datalink.has_class_privilege(regclass);
COMMENT ON VIEW columns
IS 'Link Control Options for datalink columns, updatable';
grant select on columns to public;
grant update on columns to public;
---------------------------------------------------
-- triggers we might need to setup
CREATE FUNCTION dl_trigger_advice(
OUT owner name, OUT regclass regclass,
OUT valid boolean, OUT needed boolean,
OUT identifier name, OUT links bigint, OUT mco int, OUT sql_advice text)
RETURNS SETOF record
LANGUAGE sql
AS $$
WITH
triggers AS (
SELECT c0_1.oid,
t0.tgname
FROM pg_trigger t0
JOIN pg_class c0_1 ON t0.tgrelid = c0_1.oid
WHERE t0.tgname = '~RI_DatalinkTrigger'::name
AND datalink.has_class_privilege(c0_1.oid)
),
classes AS (
SELECT dl_columns.regclass,
count(*) AS count,
max(dl_columns.lco) AS mco
FROM datalink.dl_columns dl_columns
WHERE datalink.has_class_privilege(dl_columns.regclass)
GROUP BY dl_columns.regclass
),
dl_triggers AS (
SELECT c0.relowner::regrole::name AS owner,
(COALESCE(c.regclass, t.oid))::regclass AS regclass,
COALESCE(c.count, (0)::bigint) AS links,
c.mco,
t.tgname
FROM triggers t
FULL JOIN classes c ON (t.oid = c.regclass)
JOIN pg_class c0 ON (c0.oid = COALESCE(c.regclass, t.oid))
ORDER BY COALESCE(c.regclass, t.oid)::regclass::text
)
SELECT
owner,
regclass AS regclass,
-- not (tgname is null or links = 0) as valid,
(tgname is null and mco=0) or (tgname is not null and mco>0) as valid,
links>0 and mco>0 as needed,
tgname AS identifier,
links,
mco,
case when tgname is not null then
format(e'DROP TRIGGER IF EXISTS %I ON %s; ', tgname, regclass::text) ||
format(e'DROP TRIGGER IF EXISTS %I ON %s;\n', tgname||'2', regclass::text)
else '' end ||
case when links>0 and mco > 0 then
format(e'CREATE TRIGGER %I BEFORE INSERT OR UPDATE OR DELETE ON %s' ||
e' FOR EACH ROW EXECUTE PROCEDURE datalink.dl_trigger_table();\n',
'~RI_DatalinkTrigger', regclass::text) ||
format(e'CREATE TRIGGER %I BEFORE TRUNCATE ON %s' ||
e' FOR EACH STATEMENT EXECUTE PROCEDURE datalink.dl_trigger_table();',
'~RI_DatalinkTrigger2', regclass::text)
else '' end
AS sql_advice
FROM dl_triggers
$$;
---------------------------------------------------
-- linked files
---------------------------------------------------
CREATE TYPE file_link_state AS ENUM (
'LINK','LINKED','ERROR','UNLINK'
);
create table dl_linked_files (
path file_path primary key,
state file_link_state not null default 'LINK',
cons "char",
size bigint,
mtime timestamptz,
txid xid8 not null default pg_current_xact_id(),
token dl_token not null unique,
lco dl_lco not null references datalink.link_control_options,
attrelid regclass not null,
attnum smallint not null,
online boolean not null default TRUE,
address text[] unique,
fstat jsonb,
info jsonb,
err jsonb
);
-- index for datalinker
create index dl_linked_files_txid on dl_linked_files (txid)
where state = ANY ('{LINK,UNLINK}'::file_link_state[]);
create view linked_files as
select path,state,
lco.read_access as read_access,
lco.write_access as write_access,
lco.recovery,
lco.on_unlink,
a.attrelid::regclass as regclass,
a.attname,
c.relowner::regrole as owner,
jsonb_pretty(lf.err)::json as err
from datalink.dl_linked_files lf
join datalink.link_control_options lco on lco.lco=coalesce(lf.lco,0)
join pg_class c on c.oid = lf.attrelid
join pg_attribute a using (attrelid,attnum)
where datalink.has_class_privilege(attrelid);
comment on view linked_files
is 'Currently linked files';
grant select on linked_files to public;
---------------------------------------------------
-- for backup and restore and upgrades
CREATE OR REPLACE FUNCTION set_online(boolean) returns boolean language plpgsql as $$
begin
execute
'alter table datalink.dl_linked_files alter column online set default '||$1;
update datalink.dl_linked_files set online = $1
where online is distinct from $1;
return $1;
end
$$ strict;
COMMENT ON FUNCTION set_online(boolean) IS 'Set datalink online status for dump/restore';
---------------------------------------------------
CREATE OR REPLACE FUNCTION stat(file_path file_path,
OUT dev bigint, OUT inode bigint, OUT mode integer, OUT typ "char", OUT nlink integer,
OUT uid integer, OUT gid integer,
OUT rdev integer, OUT size numeric,
OUT atime numeric, OUT mtime numeric, OUT ctime numeric,
OUT blksize integer, OUT blocks bigint)
RETURNS record
LANGUAGE plperlu
STRICT
AS $function$
## use Date::Format;
my ($filename) = @_;
unless(-e $filename) { return undef; }
my (@s) = lstat($filename);
my $typs="?pc?d?b?-?l?s???"; # file types as shown by ls(1)
return {
'dev'=>$s[0],'inode'=>$s[1],
'mode'=>($s[2] & 07777),
'typ'=>substr($typs,(($s[2] & 0170000)>>12),1),
'nlink'=>$s[3],
'uid'=>$s[4],'gid'=>$s[5],
'rdev'=>$s[6],'size'=>$s[7],
## 'atime'=>time2str("%C",$s[8]),'mtime'=>time2str("%C",$s[9]),'ctime'=>time2str("%C",$s[10]),
'atime'=>$s[8],'mtime'=>$s[9],'ctime'=>$s[10],
'blksize'=>$s[11],'blocks'=>$s[12]
};
$function$;
COMMENT ON FUNCTION stat(file_path) IS 'Return info record from stat(2)';
CREATE OR REPLACE FUNCTION stat(link datalink,
OUT dev bigint, OUT inode bigint, OUT mode integer, OUT typ "char", OUT nlink integer,
OUT uid integer, OUT gid integer,
OUT rdev integer, OUT size numeric,
OUT atime numeric, OUT mtime numeric, OUT ctime numeric,
OUT blksize integer, OUT blocks bigint)
RETURNS record
LANGUAGE sql
STRICT
AS $$
select * from datalink.stat(dlurlpathonly($1))
$$;
COMMENT ON FUNCTION stat(datalink) IS 'Return info record from stat(2)';
-- return most appropriate path to a file
-- return NULL if file does not exist
create or replace function filepath(datalink) returns text as $$
declare p text;
begin
if datalink.is_local($1) then
p := datalink.filepathwrite($1);
if (datalink.stat(p)).size is not null then return p; end if;
p := pg_catalog.dlurlpathonly($1);
if (datalink.stat(p)).size is not null then return p; end if;
end if;
return null;
end
$$ language plpgsql strict;
comment on function filepath(datalink) is 'Returns the read file path from DATALINK value';
---------------------------------------------------
-- link a file to SQL
create function dl_file_link(file_path file_path,
my_token dl_token,
my_cons "char",
my_lco dl_lco,
my_regclass regclass,my_attname name)
returns boolean
language plpgsql as
$$
declare
r record;
fstat jsonb;
my_address text[];
my_attnum smallint;
my_mtime timestamptz;
my_size bigint;
begin
-- raise notice 'DATALINK LINK:%:%',format('%s.%I',regclass::text,attname),file_path;
raise notice 'DATALINK LINK:%',file_path;
-- if (datalink.link_control_options(my_lco)).write_access >= 'BLOCKED' then
if not datalink.has_valid_prefix(file_path) THEN
raise exception 'DATALINK EXCEPTION - referenced file not valid'
using errcode = 'HW007',
detail = format('unknown path prefix for "%s"',file_path),
hint = 'run "dlfm add" to add prefixes'
;
end if;
-- end if;
fstat := row_to_json(datalink.stat(file_path||'#'||my_token))::jsonb;
if fstat is null then
fstat := row_to_json(datalink.stat(file_path))::jsonb;
end if;
if fstat is null then
raise exception 'DATALINK EXCEPTION - referenced file not valid'
using errcode = 'HW007',
detail = format('stat failed for "%s"',file_path);
end if;
if fstat->>'typ' not in ('-','d') then
raise exception 'DATALINK EXCEPTION - referenced file not valid'
using errcode = 'HW007',
detail = format('file "%s" is neither file nor directory, but "%s"',file_path,fstat->>'typ');
end if;
my_address := array[fstat->>'dev',fstat->>'inode'];
my_size := fstat->>'size';
my_mtime := to_timestamp(cast(fstat->>'mtime' as double precision));
select attnum
from pg_attribute where attname=my_attname and attrelid=my_regclass
into my_attnum;
select * into r
from datalink.dl_linked_files
join pg_attribute a using (attrelid,attnum)
where path = file_path or address = my_address
for update;
if not found then
insert into datalink.dl_linked_files (token,path,lco,attrelid,attnum,address,size,mtime,cons)
values (my_token,file_path,my_lco,my_regclass,my_attnum,my_address,my_size,my_mtime,my_cons);
notify "datalink.linker_jobs";
return true;
else -- found in dl_linked_files
-- this is needed to eliminate problems during pg_restore
if r.token = my_token and r.path = file_path and r.lco = my_lco and
r.attrelid = my_regclass and r.attnum = my_attnum then
raise warning 'DATALINK WARNING - external file possibly already linked'
using detail = format('from %s.%I as ''%s''',r.attrelid::text,r.attname,r.path);
end if;
-- already linked ?
if r.state in ('LINK','LINKED') then
raise exception 'DATALINK EXCEPTION - external file already linked'
using errcode = 'HW002',
detail = format('from %s.%I as ''%s''',r.attrelid::text,r.attname,r.path);
-- scheduled for unlinking by datalinker but not processed yet
elsif r.state in ('UNLINK') then
if r.lco is distinct from my_lco
then
raise exception 'DATALINK EXCEPTION - external file already linked'
using errcode = 'HW002',
detail = format('Cannot change link control options in update');
end if;
if r.token is not distinct from my_token
then -- same file and protection
update datalink.dl_linked_files
set state='LINKED',
attrelid=my_regclass,
attnum=my_attnum,
address=my_address,
size=my_size,
mtime=my_mtime,
cons=my_cons
where path = file_path and state='UNLINK';
notify "datalink.linker_jobs";
return true;
else -- relink
update datalink.dl_linked_files
set state='LINK',
token=my_token,
attrelid=my_regclass,
attnum=my_attnum,
address=my_address,
size=my_size,
mtime=my_mtime,
cons=my_cons
where path = file_path and state='UNLINK';
notify "datalink.linker_jobs";
return true;
-- raise exception 'DATALINK EXCEPTION - external file already linked'
-- using errcode = 'HW002',
-- detail = format('file is waiting for unlink ''%s'' by datalinker process',r.path);
end if; -- token changed
else -- other link state
raise exception 'DATALINK EXCEPTION'
using errcode = 'HW000',
detail = format('unknown link state %s',r.state);
end if;
end if; -- if found
end
$$;
revoke execute on function dl_file_link from public;
---------------------------------------------------
-- unlink a file from SQL
create function dl_file_unlink(file_path file_path)
returns boolean as
$$
declare
r record;
begin
raise notice 'DATALINK UNLINK:%',file_path;
select * into r
from datalink.dl_linked_files
join datalink.link_control_options using (lco)
where path = file_path
for update of dl_linked_files;
if not found then
raise exception 'DATALINK EXCEPTION - external file not linked'
using errcode = 'HW001',
detail = file_path;
else
if r.state = 'LINK' then
update datalink.dl_linked_files
set state = 'UNLINK',
token = cast(info->>'b' as datalink.dl_token),
lco = cast(info->>'lco' as datalink.dl_lco)
where path = file_path and info is not null
and state = 'LINK';
delete from datalink.dl_linked_files
where path = file_path and info is null
and state = 'LINK';
elsif r.state = 'LINKED' then
if r.on_unlink = 'DELETE' then
if not datalink.has_file_privilege(file_path,'delete',false) then
raise exception e'DATALINK EXCEPTION - DELETE permission denied on directory\nPATH: %',file_path
using errcode = 'HW005',
detail = 'delete permission is required on directory',
hint = 'add appropriate entry in table datalink.access';
end if;
end if;
update datalink.dl_linked_files
set state = 'UNLINK'
where path = file_path and state = 'LINKED';
elsif r.state = 'ERROR' then
delete from datalink.dl_linked_files
where path = file_path and state = 'ERROR';
elsif r.state = 'UNLINK' then
raise exception 'DATALINK EXCEPTION - waiting for datalinker'
using errcode = 'HW000',
detail = format('file is ''%s'' waiting for unlink by the datalinker process',r.path),
hint = 'start datalinker with "dlfm start"';
else
raise exception 'DATALINK EXCEPTION'
using errcode = 'HW000',
detail = format('unknown link state %s',r.state);
end if;
end if;
notify "datalink.linker_jobs";
return true;
end
$$ language plpgsql strict;
revoke execute on function dl_file_unlink from public;
---------------------------------------------------
-- uri functions
---------------------------------------------------
/*
CREATE OR REPLACE FUNCTION uri_get(url text, part text)
RETURNS text
LANGUAGE plperlu
AS $function$
use URI;
use File::Basename;
my $u=URI->new($_[0]);
my $part=$_[1]; lc($part);
# common
if($part eq 'path') { return $u->path; }
if($part eq 'fragment') { return $u->fragment; }
my $scheme=$u->scheme;
if($part eq 'scheme') { return $u->has_recognized_scheme?$scheme:undef; }
my $v = eval {
if($part eq 'authority') { return $u->authority; }
if($part eq 'user') { return $u->user(); }
if($part eq 'userinfo') {
if($scheme eq 'file') { my $r=$u->host; $r=~s/@.*$//; return $r?$r:undef; }
return $u->userinfo();
}
if($part eq 'host') { my $r=$u->host; $r=~s/^.*@//; return $r; }
if($part eq 'server') { return $u->host; }
if($part eq 'domain') { my $d = $u->host; $d=~s|^[^\.]*\.||; return $d; }
if($part eq 'port') { return $u->port; }
if($part eq 'host_port') { return $u->host_port(); }
if($part eq 'dirname') { return dirname($u->path); }
if(!($scheme eq 'data')) {
if($part eq 'basename') { return basename($u->path()); }
if($part eq 'filename') { return (fileparse($u->path()))[0]; }
if($part eq 'media_type') { return undef; }
if($part eq 'dirname') { return dirname($u->path); }
} else { # data:
if($part eq 'basename') { return undef; }
if($part eq 'filename') { return undef; }
if($part eq 'media_type') { return $u->media_type; }
if($part eq 'dirname') { return $u->media_type; }
}
if($part eq 'dir') { return $u->dir; }
if($part eq 'file') { return $u->file; }
if($part eq 'suffix') { return (fileparse($u->path()))[2]; }
if($part eq 'path_query') { return $u->path_query(); }
if($part eq 'query') { return $u->query(); }
if($part eq 'query_form') { return $u->query_form(); }
if($part eq 'query_keywords') { return $u->query_keywords(); }
if($part eq 'token') { return $u->fragment(); }
if($part eq 'canonical') {
if($u->query() eq '') { $u->query(undef); }
if($u->fragment() eq '') { $u->fragment(undef); }
my $c = $u->canonical; return "$c";
}
else { elog(ERROR,"Unknown part '$part'."); }
};
if($part eq 'canonical') { return $u->canonical->as_string; }
return $v;
elog(ERROR,"Unknown part '$_[1]'.");
return undef;
$function$
;
*/
CREATE OR REPLACE FUNCTION uri_get(url text, part text)
RETURNS text LANGUAGE SQL immutable strict AS $$
select datalink.uri_get($1::uri,$2)
$$;
COMMENT ON FUNCTION uri_get(text,text) IS 'Get (extract) parts of URI';
---------------------------------------------------
CREATE OR REPLACE FUNCTION uri_get(url uri, part text)
RETURNS text LANGUAGE sql IMMUTABLE STRICT AS $$
select case part
when 'scheme' then uri_scheme($1)
when 'server' then uri_host($1)
when 'userinfo' then uri_userinfo($1)
when 'host' then uri_host($1)
when 'path' then uri_unescape(uri_path($1))
when 'basename' then nullif(to_json(uri_path_array($1))->>-1,'')
when 'dirname' then nullif(to_json(uri_path_array($1))->>-1,'')
when 'query' then uri_query($1)
when 'fragment' then uri_fragment($1)
when 'token' then uri_unescape(uri_fragment($1))
when 'canonical' then uri_normalize($1)::text
-- without fragment
when 'only' then regexp_replace(uri_normalize($1)::text,'#.*','')
end $$;
COMMENT ON FUNCTION uri_get(uri,text) IS 'Get (extract) parts of URI';
CREATE OR REPLACE FUNCTION uri_get(link datalink, part text)
RETURNS text LANGUAGE sql IMMUTABLE STRICT AS $$
select datalink.uri_get($1::jsonb->>'a',$2) $$;
COMMENT ON FUNCTION uri_get(datalink,text) IS 'Get (extract) parts of datalink URI';
---------------------------------------------------
CREATE OR REPLACE FUNCTION uri_set(url uri, part text, val text)
RETURNS text
LANGUAGE plperlu
AS $function$
use URI;
my $u=$_[0];
my $part=$_[1]; lc($part);
my $v=$_[2];
if($part eq 'src') { $u = URI->new_abs($v,$u); return $u->as_string; }
$u = URI->new($u);
if($part eq 'scheme') { $u->scheme($v); }
elsif($part eq 'server') { $u->host($v); }
elsif($part eq 'authority') { $u->authority($v); }
elsif($part eq 'path_query') { $u->path_query($v); }
elsif($part eq 'userinfo') { $u->userinfo($v); }
elsif($part eq 'host') { $u->host($v); }
elsif($part eq 'port') { $u->port($v); }
elsif($part eq 'host_port') { $u->host_port($v); }
elsif($part eq 'path') { $u->path($v); }
elsif($part eq 'basename') {
my $p=$u->path(); $p=~s|/[^/]*$||; $p.='/'.$v; $u->path($p);
}
elsif($part eq 'query') { $u->query($v); }
elsif($part eq 'query_form') { $u->query_form($v); }
elsif($part eq 'query_keywords') { $u->query_keywords($v); }
elsif($part eq 'fragment') { $u->fragment($v); }
elsif($part eq 'token') { $u->fragment($v); }
else { elog(ERROR,"Unknown part '$part'."); }
return $u->as_string;
$function$
;
COMMENT ON FUNCTION uri_set(uri,text,text) IS 'Set (replace) parts of URI';
---------------------------------------------------
CREATE OR REPLACE FUNCTION iri(iri text) RETURNS text language sql strict as $$
SELECT datalink.uri_set('/','src',$1) $$;
COMMENT ON FUNCTION iri(text)
IS 'Convert IRI (unicode characters) to URI (escaped)';
---------------------------------------------------
-- event triggers
---------------------------------------------------
CREATE FUNCTION dl_trigger_event()
RETURNS event_trigger LANGUAGE plpgsql
SECURITY DEFINER
AS $$
declare
obj record;
js json;
begin
-- RAISE NOTICE 'DATALINK EVENT [%] TAG [%] ROLE % %', tg_event, tg_tag, current_role, current_setting('is_superuser');
if tg_event = 'ddl_command_end' then
if tg_tag in ('CREATE TABLE','CREATE TABLE AS','SELECT INTO','ALTER TABLE')
then
-- update triggers on tables with datalinks
for obj in select * from datalink.dl_trigger_advice()
where not valid
loop
RAISE NOTICE 'DATALINK DDL:% on %','TRIGGER',obj.regclass;
execute obj.sql_advice;
end loop;
-- mark datalink triggers as internal
update pg_trigger
set tgisinternal = true
where tgisinternal is distinct from true
and tgname like '%RI_DatalinkTrigger%';
if tg_tag = 'ALTER TABLE' then
with info as (
select classid::regclass,objid,objsubid,
command_tag,object_type,schema_name,object_identity,
in_extension
from pg_event_trigger_ddl_commands()
)
select json_agg(row_to_json(info))
from info
into js;
-- RAISE NOTICE 'ALTER TABLE %',js;
end if; -- alter table
-- check if there are invallid link control options
if exists(
select regclass from datalink.dl_columns
where lco not in (select lco from datalink.link_control_options)
) then
raise exception 'DATALINK EXCEPTION'
using errcode = 'HW000',
detail = format('Invalid link control options'),
hint = 'see table datalink.link_control_options for valid link control options';
end if;
end if; -- tg_tag in (...)
elsif tg_event = 'sql_drop' then
-- unlink files referenced by dropped tables
for obj in
select *
from datalink.dl_linked_files f
where attrelid in
(select tdo.objid
from pg_event_trigger_dropped_objects() tdo
where object_type = 'table'
)
order by txid
loop
perform datalink.dl_file_unlink(obj.path);
end loop;
-- unlink files referenced by dropped dl_columns
for obj in
select *
from
(select objid::regclass as regclass, objsubid as attnum,
address_names[3] as attname
from pg_event_trigger_dropped_objects()
where object_type = 'table column'
) as tdo
join datalink.dl_linked_files f on f.attrelid=tdo.regclass and f.attnum=tdo.attnum
order by txid
loop
perform datalink.dl_file_unlink(obj.path);
end loop;
end if;
end
$$;
alter function dl_trigger_event() owner to postgres;
---------------------------------------------------
create event trigger datalink_event_trigger_end on ddl_command_end
when tag in ('CREATE TABLE','CREATE TABLE AS','SELECT INTO','ALTER TABLE')
execute procedure dl_trigger_event();
create event trigger datalink_event_trigger_drop
on sql_drop execute procedure dl_trigger_event();
---------------------------------------------------
-- token generator
---------------------------------------------------
CREATE OR REPLACE FUNCTION uuid_generate_v4() RETURNS uuid
LANGUAGE c PARALLEL SAFE STRICT
AS '$libdir/uuid-ossp', $function$uuid_generate_v4$function$;
CREATE FUNCTION dl_newtoken() RETURNS dl_token LANGUAGE sql
AS $$select cast(datalink.uuid_generate_v4() as datalink.dl_token);$$;
---------------------------------------------------
-- SQL/MED datalink functions
---------------------------------------------------
CREATE FUNCTION pg_catalog.dlvalue(url text, linktype dl_linktype DEFAULT NULL, comment text DEFAULT NULL)
RETURNS datalink
LANGUAGE plpgsql IMMUTABLE
AS $$
declare
my_dl datalink;
my_uri text;
my_type text;
begin