-
Notifications
You must be signed in to change notification settings - Fork 2
/
dbi_link.sql
1915 lines (1716 loc) · 49.3 KB
/
dbi_link.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
SET client_min_messages=ERROR;
CREATE SCHEMA dbi_link;
COMMENT ON SCHEMA dbi_link IS $$
This schema holds all the functionality needed for using dbi-link.
$$;
CREATE OR REPLACE FUNCTION dbi_link.ensure_in_search_path(TEXT)
RETURNS TEXT
LANGUAGE SQL
AS $$
UPDATE
pg_catalog.pg_settings
SET
setting = CASE
WHEN
$1 = ANY(string_to_array(setting,','))
THEN
setting
ELSE $1 || ',' || setting
END
WHERE
name = 'search_path';
SELECT setting FROM pg_catalog.pg_settings WHERE name = 'search_path';
$$;
SELECT dbi_link.ensure_in_search_path('dbi_link');
CREATE VIEW dbi_link.min_pg_version (
min_pg_version
) AS
VALUES (90300::int);
COMMENT ON VIEW dbi_link.min_pg_version IS
$$This view contains exactly one row: the minimum version of
PostgreSQL required to use this version of DBI-Link.$$;
CREATE OR REPLACE FUNCTION dbi_link.is_data_source(TEXT)
RETURNS boolean
STRICT
LANGUAGE plperlu
AS $$
use DBI 1.609;
my @args = DBI->parse_dsn($_[0]);
if (defined @args) {
return 1;
}
return 0;
$$;
COMMENT ON FUNCTION dbi_link.is_data_source(TEXT) IS $$
Pretty self-explanatory ;)
$$;
CREATE DOMAIN dbi_link.data_source AS TEXT
CHECK (
dbi_link.is_data_source(VALUE)
);
COMMENT ON DOMAIN dbi_link.data_source IS $$
Pretty self-explanatory ;)
$$;
CREATE TABLE dbi_link.dbi_connection (
data_source_id SERIAL PRIMARY KEY,
data_source DATA_SOURCE NOT NULL,
user_name TEXT,
auth TEXT,
dbh_attributes JSON,
remote_schema TEXT,
remote_catalog TEXT,
local_schema TEXT,
UNIQUE(data_source, user_name)
);
COMMENT ON TABLE dbi_link.dbi_connection IS
$$This table contains the necessary connection information for a DBI
connection. The dbh_attributes is a JSON <http://www.json.org>
representation of the DBI database handle attributes which allows
maximum flexibility while ensuring some modicum of safety.$$;
CREATE TABLE dbi_link.dbi_connection_environment (
data_source_id INTEGER NOT NULL
REFERENCES dbi_link.dbi_connection(data_source_id)
ON DELETE CASCADE
ON UPDATE CASCADE,
env_name TEXT NOT NULL,
env_value TEXT NOT NULL,
env_action TEXT NOT NULL CHECK(
env_action IN (
'overwrite', -- Set the envonment variable to this.
'prepend', -- Prepend this to the environment variable with a ':' separator if it is not already there.
'append' -- Append this to the environment variable with a ':' separator if it is not already there.
)
)
);
COMMENT ON TABLE dbi_link.dbi_connection_environment
IS $$Environment settings for a $dbh$$;
CREATE OR REPLACE FUNCTION dbi_link.add_dbi_connection_environment(
in_data_source_id BIGINT,
in_settings JSON
)
RETURNS VOID
LANGUAGE plperlU
AS $$
my ($data_source_id, $settings_json) = @_;
return unless (defined $settings_json);
my $settings = decode_json($settings_json);
warn encode_json($settings) if $_SHARED{debug};
die "In dbi_link.add_dbi_connection_environment, settings is a >@{[
ref($settings)
]}<, not an array reference"
unless (ref($settings) eq 'ARRAY');
my $count = 0;
foreach my $setting (@$settings) {
die "In dbi_link.add_dbi_connection_environment, setting $count is not even a hash reference"
unless (ref($setting) eq 'HASH');
die "In dbi_link.add_dbi_connection_environment, setting $count does have the proper components"
unless (
exists $setting->{env_name} &&
exists $setting->{env_value} &&
exists $setting->{env_action}
);
die "In dbi_link.add_dbi_connection_environment, setting $count does have the proper right-hand sides"
if (
ref($setting->{env_name}) ||
ref($setting->{env_value}) ||
ref($setting->{env_action})
);
foreach my $sub_setting (qw(env_name env_value env_action)) {
if (defined $setting->{$sub_setting}) {
$setting->{$sub_setting} = $_SHARED{quote_literal}->(
$setting->{$sub_setting}
);
}
else {
$setting->{$sub_setting} = 'NULL';
}
}
my $sql = <<SQL;
INSERT INTO dbi_link.dbi_connection_environment (
data_source_id,
env_name,
env_value,
env_action
)
VALUES (
$data_source_id,
$setting->{env_name},
$setting->{env_value},
$setting->{env_action}
)
SQL
warn "In dbi_link.add_dbi_connection_environment, executing:\n$sql" if $_SHARED{debug};
my $rv = spi_exec_query($sql);
if ($rv->{status} ne 'SPI_OK_INSERT') {
die "In dbi_link.add_dbi_connection_environment, could not insert into dbi_link.dbi_connection_environment: $rv->{status}";
}
}
return;
$$;
CREATE OR REPLACE FUNCTION dbi_link.json_result_set(in_query TEXT)
RETURNS JSON
LANGUAGE plperlU
AS $$
use JSON;
my $rv = spi_exec_query($_[0]);
if ($rv->{processed} > 0) {
return encode_json($rv->{rows});
}
else {
return undef;
}
$$;
COMMENT ON FUNCTION dbi_link.json_result_set(in_query TEXT)
IS $$
This takes a query as input and returns json that rolls up all the
records.
$$;
CREATE VIEW dbi_link.dbi_all_connection_info AS
SELECT
c.data_source_id,
c.data_source,
c.user_name,
c.auth,
c.dbh_attributes,
c.remote_schema,
c.remote_catalog,
c.local_schema,
dbi_link.json_result_set(
'SELECT
env_name, env_value, env_action
FROM
dbi_link.dbi_connection_environment
WHERE
data_source_id = ' || c.data_source_id
) AS dbi_connection_environment
FROM
dbi_link.dbi_connection c
;
COMMENT ON VIEW dbi_link.dbi_all_connection_info IS
$$Rollup of the whole connection_info object.$$;
CREATE RULE dbi_all_connection_info_insert AS
ON INSERT TO dbi_link.dbi_all_connection_info
DO INSTEAD (
INSERT INTO dbi_link.dbi_connection (
data_source,
user_name,
auth,
dbh_attributes,
remote_schema,
remote_catalog,
local_schema
)
VALUES (
NEW.data_source,
NEW.user_name,
NEW.auth,
NEW.dbh_attributes,
NEW.remote_schema,
NEW.remote_catalog,
NEW.local_schema
);
SELECT dbi_link.add_dbi_connection_environment(
pg_catalog.currval(
pg_catalog.pg_get_serial_sequence(
'dbi_link.dbi_connection',
'data_source_id'
)
),
NEW.dbi_connection_environment
)
);
--------------------------------------
-- --
-- PL/PerlU Interface to DBI. :) --
-- --
--------------------------------------
CREATE OR REPLACE FUNCTION dbi_link.available_drivers()
RETURNS SETOF TEXT
LANGUAGE plperlu
AS $$
require 5.8.3;
use DBI;
return \@{[ DBI->available_drivers ]};
$$;
COMMENT ON FUNCTION dbi_link.available_drivers() IS $$
This is a wrapper around the DBI function of the same name which
returns a list (SETOF TEXT) of DBD:: drivers available through DBI on
your machine. This is used internally and is unlikely to be called
directly.
$$;
CREATE OR REPLACE FUNCTION dbi_link.data_sources(TEXT)
RETURNS SETOF TEXT
LANGUAGE plperlu
AS $$
require 5.8.3;
use DBI;
return \@{[ DBI->data_sources($_[0]) ]};
$$;
COMMENT ON FUNCTION dbi_link.data_sources(TEXT) IS $$
This is a wrapper around the DBI function of the same name. It takes
as input one of the rows from available_drivers() and returns known
data sources for that driver. You will probably not call this
function, but it is there just in case.
$$;
CREATE OR REPLACE FUNCTION dbi_link.dbi_link_init()
RETURNS VOID
LANGUAGE plperlu
AS $$
$_SHARED{debug} = 1;
my $res = spi_exec_query(<<'SQL')->{rows}[0];
SELECT
s.setting AS "server_version_num",
v.min_pg_version
FROM
dbi_link.min_pg_version v
CROSS JOIN
pg_catalog.pg_settings s
WHERE s."name"='server_version_num'
SQL
if ($res->{server_version_num} < $res->{min_pg_version}) {
die "Server version is $res->{server_version_num}. You need at least $res->{min_pg_version} to run DBI-Link.";
}
my $shared = populate_hashref();
foreach my $sub (keys %$shared) {
my $ref = ref($_SHARED{$sub});
# warn $ref if $_SHARED{debug};
if ($ref eq 'CODE') {
# Do nothing.
# warn "$sub already set." if $_SHARED{debug};
}
else {
warn "Setting $sub in \%_SHARED hash." if $_SHARED{debug};
$_SHARED{$sub} = $shared->{$sub};
}
}
undef $shared;
sub populate_hashref {
return {
bail => sub {
my ($params) = @_;
die join("\n",
map{$params->{$_}} grep {
$params->{$_} =~ /\S/
} qw(header message error));
},
get_connection_info => sub {
my ($args) = @_;
warn "Entering get_connection_info" if $_SHARED{debug};
warn 'ref($args) is '.ref($args)."\n".encode_json($args) if $_SHARED{debug};
unless (defined $args->{data_source_id}) {
die "In get_connection_info, must provide a data_source_id";
}
unless ($args->{data_source_id} =~ /^\d+$/) {
die "In get_connection_info, must provide an integer data_source_id";
}
my $sql = <<SQL;
SELECT
data_source,
user_name,
auth,
dbh_attributes,
remote_schema,
remote_catalog,
local_schema,
dbi_connection_environment
FROM
dbi_link.dbi_all_connection_info
WHERE
data_source_id = $args->{data_source_id}
SQL
my $rv = spi_exec_query($sql);
if ($rv->{processed} != 1) {
die "Should have gotten 1 row back. Got $rv->{processed} instead.";
}
else {
# Do nothing
# warn "Got 1 row back" if $_SHARED{debug};
}
# warn encode_json($rv->{rows}[0]) if $_SHARED{debug};
warn "Leaving get_connection_info" if $_SHARED{debug};
return $rv->{rows}[0];
},
set_environment => sub {
use JSON;
my $dbi_connection_environment = $_[0];
if (defined $dbi_connection_environment) {
my $parsed_env = decode_json($dbi_connection_environment);
die "In set_environment, argument must be an array reference."
unless (ref($parsed_env) eq 'ARRAY');
foreach my $setting (@$parsed_env) {
foreach my $key (qw(env_name env_value env_action)) {
die "In set_environment, missing key $key"
unless (defined $setting->{$key});
}
if ($setting->{env_action} eq 'overwrite') {
$ENV{ $setting->{env_name} } = $setting->{env_value};
}
elsif (
$setting->{env_action} eq 'prepend'
) {
if ($ENV{ $setting->{env_name} } !~ /$setting->{env_value}/) {
$ENV{ $setting->{env_name} } =
$setting->{env_value} .
$ENV{ $setting->{env_name} }
;
}
}
elsif (
$setting->{env_action} eq 'append'
) {
if ($ENV{ $setting->{env_name} } !~ /$setting->{env_value}/) {
$ENV{ $setting->{env_name} } .= $setting->{env_value};
}
}
else {
die "In set_environment, env_action may only be one of {overwrite, prepend, append}.";
}
}
}
},
get_dbh => sub {
use JSON;
use DBI;
local %ENV;
my ($connection_info) = @_;
my $attribute_hashref;
warn "In get_dbh, input connection info is\n".encode_json($connection_info) if $_SHARED{debug};
##################################################
# #
# Here, we get the raw connection info as input. #
# #
##################################################
unless (
defined $connection_info->{data_source} && # NOT NULL
exists $connection_info->{user_name} &&
exists $connection_info->{auth} &&
exists $connection_info->{dbh_attributes}
) {
die "You must provide all of data_source, user_name, auth and dbh_attributes to get a database handle.";
}
# set environment variables for connection
$_SHARED{set_environment}->(
$connection_info->{dbi_connection_environment}
);
$attribute_hashref = decode_json(
$connection_info->{dbh_attributes}
);
my $dbh = DBI->connect(
$connection_info->{data_source},
$connection_info->{user_name},
$connection_info->{auth},
$attribute_hashref,
);
if ($DBI::errstr) {
die <<ERROR;
$DBI::errstr
Could not connect with parameters
data_source: $connection_info->{data_source}
user_name: $connection_info->{user_name}
auth: $connection_info->{auth}
dbh_attributes: $connection_info->{dbh_attributes}
ERROR
}
return $dbh;
},
remote_exec_dbh => sub {
use DBI;
my @errors;
my ($params) = @_;
push @errors, 'You must supply a database handle.'
unless defined $params->{dbh};
push @errors, 'You must supply a query.'
unless defined $params->{query};
push @errors, 'You must tell whether your query returns rows.'
unless (
lc($params->{returns_rows}) eq 't' ||
lc($params->{returns_rows}) eq 'f'
);
if (scalar @errors > 0) {
$_SHARED{bail}->({
header => 'In $_SHARED{remote_exec_dbh}',
error => join("\n", @errors),
});
}
my $sth = $params->{dbh}->prepare(
$params->{query}
);
if ($DBI::errstr) {
$_SHARED{bail}->({
header => 'Cannot prepare',
message => $params->{query},
error => $DBI::errstr,
});
}
$sth->execute();
if ($DBI::errstr) {
$_SHARED{bail}-> ({
header => 'Cannot execute',
message => $params->{query},
error => $DBI::errstr,
});
}
if (lc($params->{returns_rows}) eq 't') {
while(my $row = $sth->fetchrow_hashref) {
return_next($row);
}
$sth->finish;
}
return;
},
quote_ident => sub {
my $plan = spi_prepare(
'SELECT pg_catalog.quote_ident($1) AS foo',
'TEXT'
);
my $quoted = spi_exec_prepared(
$plan,
$_[0]
)->{rows}[0]{foo};
spi_freeplan($plan);
return $quoted;
},
quote_literal => sub {
my $plan = spi_prepare(
'SELECT pg_catalog.quote_literal($1) AS foo',
'TEXT'
);
my $quoted = spi_exec_prepared(
$plan,
$_[0]
)->{rows}[0]{foo};
spi_freeplan($plan);
return $quoted;
},
};
}
$$;
COMMENT ON FUNCTION dbi_link.dbi_link_init() IS $$
This function sets up all the common perl-callable functions in
$_SHARED.
bail:
This takes a hashref with (all optional) keys header, message and
error, and raises an ERROR with an informative message of all
that appear.
get_connection_info:
Input:
data_source_id INTEGER NOT NULL
Output:
data_source TEXT
user_name TEXT
auth TEXT
dbh_attributes JSON
remote_schema TEXT
remote_catalog TEXT
local_schema TEXT
get_dbh:
This takes the output of get_connection_info or equivalent data
structure, returns a database handle. Used to populate
$_SHARED->{dbh}. Also used in remote_select in the case where you
set the connection at run time.
Input:
data_source TEXT
user_name TEXT
auth TEXT
dbh_attributes JSON
Output:
a dbh (perl structure)
remote_exec_dbh:
This takes a database handle, a query and a bool telling whether
the query returns rows, then does as told. Beware telling it
something untrue.
Input:
dbh database handle NOT NULL
query TEXT NOT NULL
returns_rows BOOLEAN NOT NULL
Output:
undef
quote_ident:
Perl function which wraps SQL function of the same name.
Input:
raw_identifier TEXT
Output:
quoted_identifier TEXT
quote_literal:
Perl function which wraps SQL function of the same name.
Input:
raw_literal TEXT
Output:
quoted_literal TEXT
$$;
CREATE OR REPLACE FUNCTION dbi_link.cache_connection(
in_data_source_id INTEGER
)
RETURNS VOID
LANGUAGE plperlU
AS $$
use JSON;
spi_exec_query('SELECT dbi_link.dbi_link_init()');
return if (defined $_SHARED{dbh}{ $_[0] } );
warn "In cache_connection, there's no shared dbh $_[0]" if $_SHARED{debug};
my $info = $_SHARED{get_connection_info}->({
data_source_id => $_[0]
});
warn encode_json($info) if $_SHARED{debug};
$_SHARED{dbh}{ $_[0] } = $_SHARED{get_dbh}->(
$info
);
return;
$$;
CREATE OR REPLACE FUNCTION dbi_link.remote_select (
data_source_id INTEGER,
query TEXT
)
RETURNS SETOF RECORD
STRICT
LANGUAGE plperlu AS $$
# use warnings;
spi_exec_query('SELECT dbi_link.dbi_link_init()');
##########################################################
# #
# This is safe because we already know it is an integer. #
# #
##########################################################
my $query = "SELECT dbi_link.cache_connection( $_[0] )";
warn $query if $_SHARED{debug};
my $rv = spi_exec_query($query);
$_SHARED{remote_exec_dbh}->({
dbh => $_SHARED{dbh}{ $_[0] },
query => $_[1],
returns_rows => 't',
});
return;
$$;
COMMENT ON FUNCTION dbi_link.remote_select (
data_source_id INTEGER,
query TEXT
) IS $$
This function does SELECTs on a remote data source stored in
dbi_link.data_sources.
$$;
CREATE OR REPLACE FUNCTION dbi_link.remote_select (
data_source TEXT,
user_name TEXT,
auth TEXT,
dbh_attributes JSON,
query TEXT
)
RETURNS SETOF RECORD
LANGUAGE plperlu AS $$
#################################
# #
# Get common code into %_SHARED #
# #
#################################
spi_exec_query('SELECT dbi_link.dbi_link_init()');
my ($params) = @_;
#########################################################################
# #
# Sanity checks: must have a query, and it must be row-returning query. #
# TODO: check for multiple queries. #
# #
#########################################################################
if (length($params->{query}) == 0) {
die 'Must issue a query!';
}
my $dbh = $_SHARED{get_dbh}->({
data_source => $_[0],
user_name => $_[1],
auth => $_[2],
dbh_attributes => $_[3],
});
my $sth = $dbh->prepare($params->{query});
$sth->execute();
while(my $row = $sth->fetchrow_hashref) {
return_next($row);
}
$sth->finish;
$dbh->disconnect;
return;
$$;
COMMENT ON FUNCTION dbi_link.remote_select (
data_source TEXT,
user_name TEXT,
auth TEXT,
dbh_attributes JSON,
query TEXT
) IS $$
This function does SELECTs on a remote data source de novo.
$$;
CREATE OR REPLACE FUNCTION dbi_link.remote_execute (
data_source_id INTEGER,
query TEXT
)
RETURNS VOID
STRICT
LANGUAGE plperlu AS $$
#################################
# #
# Get common code into %_SHARED #
# #
#################################
spi_exec_query('SELECT dbi_link.dbi_link_init()');
spi_exec_query("SELECT dbi_link.cache_connection($_[0])");
$_SHARED{remote_exec_dbh}->({
dbh => $_SHARED{dbh}{ $_[0] },
query => $_[1],
returns_rows => 'f',
});
return;
$$;
COMMENT ON FUNCTION dbi_link.remote_execute (
data_source_id INTEGER,
query TEXT
) IS $$
This function executes non-row-returning queries on a remote data
source stored in dbi_link.data_sources.
$$;
CREATE OR REPLACE FUNCTION dbi_link.shadow_trigger_func()
RETURNS TRIGGER
LANGUAGE plperlu
AS $$
require 5.8.3;
######################################################
# #
# Immediately reject anything that is not an INSERT. #
# #
######################################################
if ($_TD->{event} ne 'INSERT') {
return "SKIP";
}
spi_exec_query('SELECT dbi_link.dbi_link_init()');
my $data_source_id = shift;
die "In shadow_trigger_function, data_source_id must be an integer"
unless ($data_source_id =~ /^\d+$/);
my $query = "SELECT dbi_link.cache_connection( $data_source_id )";
warn "In shadow_trigger_function, calling\n $query" if $_SHARED{debug};
warn "In shadow_trigger_function, the trigger payload is\n". encode_json(\$_TD) if $_SHARED{debug};
my $rv = spi_exec_query($query);
my $remote_schema = $_SHARED{get_connection_info}->({
data_source_id => $data_source_id
})->{remote_schema};
my $table = $_TD->{relname};
warn "Raw table name is $table" if $_SHARED{debug};
warn "In trigger on $table, action is $_TD->{new}{iud_action}" if $_SHARED{debug};
$table =~ s{
\A # Beginning of string.
(.*) # Actual table name.
_shadow # Strip off shadow.
\z # End of string.
}
{$1}sx;
$table = $remote_schema . "." . $table if defined $remote_schema;
warn "Cooked table name is $table" if $_SHARED{debug};
my $iud = {
I => \&do_insert,
U => \&do_update,
D => \&do_delete,
};
if ($iud->{ $_TD->{new}{iud_action} }) {
$iud->{ $_TD->{new}{iud_action} }->({
payload => $_TD->{new}
});
}
else {
die "Trigger event was $_TD->{new}{iud_action}<, but should have been one of I, U or D!"
}
return 'SKIP';
sub do_insert {
my ($params) = @_;
die "In do_insert, must pass a payload!"
unless (defined $params->{payload});
die "In do_insert, payload must be a hash reference!"
unless (ref $params->{payload} eq 'HASH');
my (@keys, @values);
foreach my $key (sort keys %{ $params->{payload} } ) {
next unless $key =~ /^.?new_(.*)/;
my $real_key = $1;
push @keys, $real_key;
push @values, $_SHARED{dbh}{ $data_source_id }->quote(
$params->{payload}{$key}
);
}
my $sql = <<SQL;
INSERT INTO $table (
@{[
join(
",\n ",
@keys
)
]}
)
VALUES (
@{[
join(
",\n ",
@values
)
]}
)
SQL
warn "SQL is\n$sql" if $_SHARED{debug};
$_SHARED{dbh}{ $data_source_id }->do($sql);
}
sub do_update {
my ($params) = @_;
die "In do_update, must pass a payload!"
unless (defined $params->{payload});
die "In do_update, payload must be a hash reference!"
unless (ref $params->{payload} eq 'HASH');
my $sql = <<SQL;
UPDATE $table
SET
@{[ make_pairs({
payload => $params->{payload},
which => 'new',
joiner => ",\n ",
}) ]}
WHERE
@{[ make_pairs({
payload => $params->{payload},
which => 'old',
joiner => "\nAND ",
transform_null => 'true'
}) ]}
SQL
warn "SQL is\n$sql" if $_SHARED{debug};
$_SHARED{dbh}{ $data_source_id }->do($sql);
}
sub do_delete {
my ($params) = @_;
die "In do_delete, must pass a payload!"
unless (defined $params->{payload});
die "In do_delete, payload must be a hash reference!"
unless (ref $params->{payload} eq 'HASH');
my $sql = <<SQL;
DELETE FROM $table
WHERE
@{[ make_pairs({
payload => $params->{payload},
which => 'old',
joiner => "\nAND ",
transform_null => 'true'
}) ]}
SQL
warn "SQL is\n$sql" if $_SHARED{debug};
$_SHARED{dbh}{ $data_source_id }->do($sql);
}
sub make_pairs {
my ($params) = @_;
die "In make_pairs, must pass a payload!"
unless (defined $params->{payload});
die "In make_pairs, payload must be a hash reference!"
unless (ref $params->{payload} eq 'HASH');
warn "In make_pairs, parameters are:\n". encode_json($params) if $_SHARED{debug};
my @pairs;
foreach my $key (
keys %{ $params->{payload} }
) {
next unless $key =~ m/^(.?)$params->{which}_(.*)/;
my $left = "$1$2";
warn "In make_pairs, raw key is $key, cooked key is $left" if $_SHARED{debug};
if (
defined $params->{transform_null} && # In a WHERE clause,
!defined $params->{payload}{$key} # turn undef into IS NULL
) {
push @pairs, "$left IS NULL";
}
else {
push @pairs, "$left = " . $_SHARED{dbh}{ $data_source_id }->quote(
$params->{payload}{$key}
);
}
}
my $ret =
join (
$params->{joiner},
@pairs,
);
warn "In make_pairs, the pairs are:\n". encode_json(\@pairs) if $_SHARED{debug};
return $ret;
}
$$;
CREATE OR REPLACE FUNCTION set_up_connection (
data_source DATA_SOURCE,
user_name TEXT,
auth TEXT,
dbh_attributes JSON,
dbi_connection_environment JSON,
remote_schema TEXT,
remote_catalog TEXT,
local_schema TEXT
)
RETURNS INTEGER
LANGUAGE plperlu
AS $$
spi_exec_query('SELECT dbi_link.dbi_link_init()');
my ($params, $quoted);
foreach my $param (qw(data_source user_name auth dbh_attributes
dbi_connection_environment remote_schema remote_catalog
local_schema)) {
$params->{ $param } = shift;
if ( defined $params->{ $param } ) {
$quoted->{ $param } = $_SHARED{quote_literal}->(
$params->{ $param }
);
}
else {
$quoted->{ $param } = 'NULL';
}
}
my $driver = $_SHARED{quote_literal}->(
$params->{data_source}
);
my $sql = <<SQL;
SELECT count(*) AS "driver_there"
FROM dbi_link.available_drivers()
WHERE available_drivers = $driver
SQL
warn $sql if $_SHARED{debug};
my $driver_there = spi_exec_query($sql);
if ($driver_there->{processed} == 0) {
die "Driver $driver is not available. Can't look at database."
}
# set environment variables for initial connection
local %ENV;
$_SHARED{set_environment}->(
$params->{dbi_connection_environment}
);
my $attr_href = decode_json($params->{dbh_attributes});
my $dbh = DBI->connect(
$params->{data_source},
$params->{user_name},
$params->{auth},
$attr_href,
);
if ($DBI::errstr) {
die <<ERR;
Could not connect to database
data source: $params->{data_source}
user: $params->{user_name}
password: $params->{auth}
dbh attributes:
$params->{dbh_attributes}
$DBI::errstr
ERR
}
my @methods = qw(table_info column_info quote);
foreach my $method (@methods) {
warn "Checking whether $driver has $method..." if $_SHARED{debug};
if ($dbh->can($method)) {
warn "$driver has $method :)" if $_SHARED{debug};