forked from bucardo/bucardo
-
Notifications
You must be signed in to change notification settings - Fork 0
/
bucardo.schema
2160 lines (1904 loc) · 77.6 KB
/
bucardo.schema
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
-- Schema for the main Bucardo database
-- Dependencies:
-- Superuser bucardo owns a database named bucardo
-- plpgsql and plperlu are loaded, but just in case:
SET client_min_messages = 'FATAL';
CREATE LANGUAGE plpgsql;
CREATE LANGUAGE plperlu;
SET client_min_messages = 'ERROR';
COMMIT;
\set ON_ERROR_STOP
CREATE SCHEMA bucardo;
CREATE SCHEMA freezer;
SET search_path TO bucardo;
SET client_min_messages = 'WARNING';
SET escape_string_warning = 'OFF';
--
-- Main bucardo configuration information
--
CREATE TABLE bucardo_config (
setting TEXT NOT NULL, -- short unique name, maps to %config inside Bucardo
value TEXT NOT NULL,
about TEXT NULL, -- long description
type TEXT NULL, -- sync or goat
name TEXT NULL, -- which specific sync or goat
cdate TIMESTAMPTZ NOT NULL DEFAULT now()
);
CREATE UNIQUE INDEX bucardo_config_unique ON bucardo_config(setting) WHERE name IS NULL;
CREATE UNIQUE INDEX bucardo_config_unique_name ON bucardo_config(setting,name,type) WHERE name IS NOT NULL;
ALTER TABLE bucardo_config ADD CONSTRAINT valid_config_type
CHECK (type IN ('sync','goat'));
CREATE FUNCTION check_bucardo_config()
RETURNS TRIGGER
LANGUAGE plpgsql
AS $bc$
BEGIN
NEW.setting = LOWER(NEW.setting);
IF (NEW.type IS NOT NULL and NEW.name IS NULL) THEN
RAISE EXCEPTION 'Must provide a specific %', NEW.type;
END IF;
IF (NEW.name IS NOT NULL and NEW.type IS NULL) THEN
RAISE EXCEPTION 'Must provide a type if giving a name';
END IF;
IF (NEW.setting = 'sync' OR NEW.setting = 'goat') THEN
RAISE EXCEPTION 'Invalid setting name';
END IF;
RETURN NEW;
END;
$bc$;
CREATE TRIGGER check_bucardo_config
BEFORE INSERT OR UPDATE ON bucardo_config
FOR EACH ROW EXECUTE PROCEDURE check_bucardo_config();
-- Sleep times (all in seconds)
COPY bucardo_config(setting,value,about)
FROM STDIN
WITH DELIMITER '|';
kick_sleep|0.2|How long do we sleep while waiting for a kick response?
mcp_loop_sleep|0.1|How long does the main MCP daemon sleep between loops?
mcp_dbproblem_sleep|15|How many seconds to sleep before trying to respawn
ctl_nothingfound_sleep|0.2|How long does the controller loop sleep if nothing is found?
kid_nothingfound_sleep|0.3|How long does a kid sleep if nothing is found?
kid_nodeltarows_sleep|0.8|How long do kids sleep if no delta rows are found?
kid_serial_sleep|10|How long to sleep in seconds if we hit a serialization error
endsync_sleep|1.0|How long do we sleep when custom code requests an endsync?
\.
-- Various timeouts (times are in seconds)
COPY bucardo_config(setting,value,about)
FROM STDIN
WITH DELIMITER '|';
mcp_pingtime|60|How often do we ping check the MCP?
ctl_pingtime|600|How often do we ping check the CTL?
kid_pingtime|60|How often do we ping check the KID?
ctl_checkonkids_time|10|How often does the controller check on the kids health?
ctl_checkabortedkids_time|30|How often does the controller check the q table for aborted children?
ctl_createkid_time|0.5|How long do we sleep to allow kids-on-demand to get on their feet?
tcp_keepalives_idle|10|How long to wait between each keepalive probe.
tcp_keepalives_interval|5|How long to wait for a response to a keepalive probe.
tcp_keepalives_count|2|How many probes to send. 0 indicates sticking with system defaults.
\.
-- Debug output
COPY bucardo_config(setting,value,about)
FROM STDIN
WITH DELIMITER '|';
audit_pid|1|Do we populate the audit_pid table or not?
log_showpid|0|Show PID in the log output?
log_showtime|1|Show timestamp in the log output? 0=off 1=seconds since epoch 2=scalar gmtime 3=scalar localtime
log_showline|0|Show line number in the log output?
log_conflict_details|0|Log detailed conflict data?
log_conflict_file|bucardo_conflict.log|Name of the conflict detail log file
\.
-- Versioning
COPY bucardo_config(setting,value,about)
FROM STDIN
WITH DELIMITER '|';
bucardo_version|3.2.7|Bucardo version this schema was created with
bucardo_current_version|3.2.7|Current version of Bucardo
\.
-- Other settings:
COPY bucardo_config(setting,value,about)
FROM STDIN
WITH DELIMITER '|';
default_email_from|[email protected]|Who the alert emails are sent as
default_email_to|[email protected]|Who to send alert emails to
kid_abort_limit|3|How many times we will restore an aborted kid before giving up?
max_delete_clause|200|Maximum number of items to delete inside of IN() clauses
max_select_clause|500|Maximum number of items to select inside of IN() clauses
piddir|/var/run/bucardo|Directory holding Bucardo PID files
pidfile|bucardo.pid|Name of the main Bucardo pid file
reason_file|/home/bucardo/restart.reason|File to hold reasons for stopping and starting
stats_script_url|http://www.bucardo.org/|Location of the stats script
stopfile|fullstopbucardo|Name of the semaphore file used to stop Bucardo processes
syslog_facility|LOG_LOCAL1|Which syslog facility level to use
upsert_attempts|3|How many times do we try out the upsert loop?
\.
--
-- Keep track of every database we need to connect to
--
CREATE TABLE db (
name TEXT NOT NULL, -- local name for convenience, not necessarily database name
CONSTRAINT db_name_pk PRIMARY KEY (name),
dbhost TEXT NOT NULL DEFAULT '',
dbport TEXT NOT NULL DEFAULT 5432,
dbname TEXT NOT NULL,
dbuser TEXT NOT NULL,
dbpass TEXT NULL,
dbconn TEXT NOT NULL DEFAULT '', -- string to add to the generated dsn
dbservice TEXT NULL,
pgpass TEXT NULL, -- local file with connection info same as pgpass
status TEXT NOT NULL DEFAULT 'active',
sourcelimit SMALLINT NOT NULL DEFAULT 0, -- maximum concurrent read connections to this database
targetlimit SMALLINT NOT NULL DEFAULT 0, -- maximum concurrent write connections to this database
cdate TIMESTAMPTZ NOT NULL DEFAULT now()
);
CREATE UNIQUE INDEX "db_dsn_unique" ON db(dbhost,dbport,dbname,dbuser) WHERE NOT name ~ '^bctest';
ALTER TABLE db ADD CONSTRAINT db_status CHECK (status IN ('active','inactive'));
--
-- Databases can belong to zero or more named groups
--
CREATE TABLE dbgroup (
name TEXT NOT NULL,
CONSTRAINT dbgroup_name_pk PRIMARY KEY (name),
cdate TIMESTAMPTZ NOT NULL DEFAULT now()
);
CREATE TABLE dbmap (
db TEXT NOT NULL,
CONSTRAINT dbmap_db_fk FOREIGN KEY (db) REFERENCES db(name) ON DELETE CASCADE,
dbgroup TEXT NOT NULL,
CONSTRAINT dbmap_dbgroup_fk FOREIGN KEY (dbgroup) REFERENCES dbgroup(name) ON DELETE CASCADE,
priority SMALLINT NOT NULL DEFAULT 0,
cdate TIMESTAMPTZ NOT NULL DEFAULT now()
);
CREATE UNIQUE INDEX dbmap_unique ON dbmap(db,dbgroup);
--
-- Track status information about each database
--
CREATE TABLE db_connlog (
db TEXT NOT NULL,
CONSTRAINT db_connlog_dbid_fk FOREIGN KEY (db) REFERENCES db(name) ON DELETE CASCADE,
conndate TIMESTAMPTZ NOT NULL DEFAULT now(), -- when we first connected to it
connstring TEXT NOT NULL,
status TEXT NOT NULL DEFAULT 'unknown',
CONSTRAINT db_connlog_status CHECK (status IN ('unknown', 'good', 'down', 'unreachable')),
version TEXT NULL
);
--
-- We need to track each item we want to replicate from or replicate to
--
CREATE SEQUENCE goat_id_seq;
CREATE TABLE goat (
id INTEGER NOT NULL DEFAULT nextval('goat_id_seq'),
CONSTRAINT goat_id_pk PRIMARY KEY (id),
db TEXT NOT NULL,
CONSTRAINT goat_db_fk FOREIGN KEY (db) REFERENCES db(name) ON DELETE RESTRICT,
schemaname TEXT NOT NULL,
tablename TEXT NOT NULL,
reltype TEXT NOT NULL DEFAULT 'table',
pkey TEXT NULL,
qpkey TEXT NULL,
pkeytype TEXT NULL,
has_delta BOOLEAN NOT NULL DEFAULT 'false',
ping BOOLEAN NULL, -- overrides sync-level ping
customselect TEXT NULL,
makedelta BOOLEAN NULL,
rebuild_index BOOLEAN NULL, -- overrides sync-level rebuild_index
ghost BOOLEAN NOT NULL DEFAULT 'false', -- only drop triggers, do not replicate
standard_conflict TEXT NULL,
analyze_after_copy BOOLEAN NOT NULL DEFAULT 'true',
strict_checking BOOLEAN NOT NULL DEFAULT 'true',
cdate TIMESTAMPTZ NOT NULL DEFAULT now()
);
ALTER TABLE goat ADD CONSTRAINT has_schemaname CHECK (length(schemaname) > 1);
ALTER TABLE goat ADD CONSTRAINT custom_needs_pkey CHECK (customselect IS NULL OR length(pkey) > 1);
ALTER TABLE goat ADD CONSTRAINT pkey_needs_type CHECK (pkey = '' OR pkeytype IS NOT NULL);
ALTER TABLE goat ADD CONSTRAINT standard_conflict CHECK (standard_conflict IS NULL
OR standard_conflict IN ('source','target','skip','random','latest','abort'));
-- CREATE UNIQUE INDEX goats_r_unique ON goat(db,schemaname,tablename,reltype);
--
-- A group of goats. Ideally arranged in some sort of tree.
--
CREATE TABLE herd (
name TEXT NOT NULL,
CONSTRAINT herd_name_pk PRIMARY KEY (name),
cdate TIMESTAMPTZ NOT NULL DEFAULT now()
);
--
-- Goats belong to zero or more herds. In most cases, they will
-- belong to a single her if they are being replicated.
--
CREATE TABLE herdmap (
herd TEXT NOT NULL,
CONSTRAINT herdmap_herd_fk FOREIGN KEY (herd) REFERENCES herd(name) ON DELETE CASCADE,
goat INTEGER NOT NULL,
CONSTRAINT herdmap_goat_fk FOREIGN KEY (goat) REFERENCES goat(id) ON DELETE CASCADE,
priority SMALLINT NOT NULL DEFAULT 0,
cdate TIMESTAMPTZ NOT NULL DEFAULT now()
);
CREATE VIEW goats_in_herd AS
SELECT hm.herd, g.*
FROM goat g
JOIN herdmap hm ON hm.goat = g.id;
CREATE FUNCTION herdcheck()
RETURNS TRIGGER
LANGUAGE plperlu
AS
$bc$
use strict; use warnings;
## Make sure that all goats in a herd are from the same database
my $new = $_TD->{new};
my $herdname = $new->{herd};
$herdname =~ s/'/''/go;
my $SQL = qq{
SELECT 1
FROM bucardo.herdmap h, bucardo.goat g
WHERE h.goat = g.id
AND h.herd='$herdname'
AND g.db != (SELECT db FROM bucardo.goat WHERE id = $new->{goat})
};
elog(DEBUG, "Running $SQL");
my $count = spi_exec_query($SQL)->{processed};
if ($count >= 1) {
elog(ERROR, "Cannot have goats from different databases in the same herd ($count)");
}
## Make sure that a herd contains at most one schemaname/tablename combination
$SQL = qq{
SELECT count(*) AS goats
FROM bucardo.herdmap h, bucardo.goat g
WHERE h.goat = g.id
AND g.id != $new->{goat}
AND h.herd = '$herdname'
AND g.tablename = (SELECT tablename FROM bucardo.goat WHERE id = $new->{goat})
AND g.schemaname = (SELECT schemaname FROM bucardo.goat WHERE id = $new->{goat})
};
elog(DEBUG, "Running $SQL");
$count = spi_exec_query($SQL)->{rows}[0]{goats};
if ($count >= 1) {
elog(ERROR, "Cannot have two goats with the same schema and table inside a herd (herd=$herdname) (goat=$new->{goat}) (count=$count)");
}
return;
$bc$;
CREATE TRIGGER herdcheck
AFTER INSERT OR UPDATE ON herdmap
FOR EACH ROW EXECUTE PROCEDURE herdcheck();
--
-- We need to know who is replicating to who, and how
--
CREATE TABLE sync (
name TEXT NOT NULL UNIQUE,
CONSTRAINT sync_name_pk PRIMARY KEY (name),
source TEXT NOT NULL,
CONSTRAINT sync_source_herd_fk FOREIGN KEY (source) REFERENCES herd(name) ON DELETE RESTRICT,
targetdb TEXT NULL,
CONSTRAINT sync_targetdb_fk FOREIGN KEY (targetdb) REFERENCES db(name) ON DELETE RESTRICT,
targetgroup TEXT NULL,
CONSTRAINT sync_targetgroup_fk FOREIGN KEY (targetgroup) REFERENCES dbgroup(name) ON DELETE RESTRICT,
synctype TEXT NOT NULL,
stayalive BOOLEAN NOT NULL DEFAULT 'true', -- Does the sync controller stay connected?
kidsalive BOOLEAN NOT NULL DEFAULT 'true', -- Do the children stay connected?
usecustomselect BOOLEAN NOT NULL DEFAULT 'false',
copytype TEXT NOT NULL DEFAULT 'copy',
copyextra TEXT NOT NULL DEFAULT '', -- e.g. WITH OIDS
deletemethod TEXT NOT NULL DEFAULT 'delete',
limitdbs SMALLINT NOT NULL DEFAULT 0, -- How many databases can sync at once? 0=all
ping BOOLEAN NOT NULL DEFAULT true, -- Are we issuing NOTICES via triggers?
do_listen BOOLEAN NOT NULL DEFAULT false, -- LISTEN for kicks on source/target database if ! ping
checktime INTERVAL NULL, -- How often to check if we've not heard anything?
status TEXT NOT NULL DEFAULT 'active', -- Possibly CHECK / FK ('stopped','paused','b0rken')
makedelta BOOLEAN NOT NULL DEFAULT 'false',
rebuild_index BOOLEAN NOT NULL DEFAULT 'false', -- Load without indexes and then REINDEX table
priority SMALLINT NOT NULL DEFAULT 0, -- Higher is better
txnmode TEXT NOT NULL DEFAULT 'SERIALIZABLE',
analyze_after_copy BOOLEAN NOT NULL DEFAULT 'true',
strict_checking BOOLEAN NOT NULL DEFAULT 'true',
overdue INTERVAL NOT NULL DEFAULT '0 seconds'::interval,
expired INTERVAL NOT NULL DEFAULT '0 seconds'::interval,
track_rates BOOLEAN NOT NULL DEFAULT 'false',
cdate TIMESTAMPTZ NOT NULL DEFAULT now()
);
ALTER TABLE sync ADD CONSTRAINT sync_type CHECK (synctype IN ('pushdelta','fullcopy','swap'));
ALTER TABLE sync ADD CONSTRAINT sync_copytype CHECK (copytype IN ('insert','copy'));
ALTER TABLE sync ADD CONSTRAINT sync_deletemethod CHECK (deletemethod IN ('truncate', 'delete'));
CREATE UNIQUE INDEX sync_source_targetdb_type ON sync(source, targetdb, synctype);
CREATE UNIQUE INDEX sync_source_targetgroup_type ON sync(source, targetgroup, synctype);
ALTER TABLE sync ADD CONSTRAINT sync_validtarget CHECK
((targetdb IS NULL AND targetgroup IS NOT NULL)
OR
(targetdb IS NOT NULL AND targetgroup IS NULL));
ALTER TABLE sync ADD CONSTRAINT sync_swap_nogroup CHECK
(synctype <> 'swap' or targetdb IS NOT NULL);
-- Because NOTIFY is broke, make sure our names are simple:
ALTER TABLE db ADD CONSTRAINT db_name_sane CHECK (name ~ E'^[a-zA-Z]\\w*$');
ALTER TABLE dbgroup ADD CONSTRAINT dbgroup_name_sane CHECK (name ~ E'^[a-zA-Z]\\w*$');
ALTER TABLE sync ADD CONSTRAINT sync_name_sane CHECK (name ~ E'^[a-zA-Z]\\w*$');
--
-- Track our children
--
CREATE SEQUENCE audit_pid_id_seq;
CREATE TABLE audit_pid (
id INTEGER NOT NULL DEFAULT nextval('audit_pid_id_seq'),
parentid INTEGER NULL, -- CTL or MCP id
familyid INTEGER NULL, -- the MCP id
type TEXT NOT NULL,
sync TEXT NOT NULL,
source TEXT NULL,
target TEXT NULL,
master_backend INT NOT NULL DEFAULT pg_backend_pid(),
source_backend INT NULL,
target_backend INT NULL,
ppid INTEGER NOT NULL,
pid INTEGER NOT NULL,
birthdate TIMESTAMPTZ NOT NULL DEFAULT now(),
killdate TIMESTAMPTZ NULL,
birth TEXT NULL,
death TEXT NULL
);
CREATE TABLE freezer.old_audit_pid AS SELECT * FROM audit_pid LIMIT 0;
--
-- Traffic control for children
--
CREATE TABLE q (
sync TEXT NULL,
CONSTRAINT q_sync_fk FOREIGN KEY (sync) REFERENCES sync(name) ON DELETE SET NULL,
sourcedb TEXT NULL,
CONSTRAINT q_sdb_fk FOREIGN KEY (sourcedb) REFERENCES db(name) ON DELETE SET NULL,
targetdb TEXT NULL,
CONSTRAINT q_tdb_fk FOREIGN KEY (targetdb) REFERENCES db(name) ON DELETE SET NULL,
ppid INTEGER NOT NULL,
pid INTEGER NULL,
synctype TEXT NULL,
updates BIGINT NULL,
inserts BIGINT NULL,
deletes BIGINT NULL,
started TIMESTAMPTZ NULL,
aborted TIMESTAMPTZ NULL,
whydie TEXT NULL,
ended TIMESTAMPTZ NULL,
cdate TIMESTAMPTZ NOT NULL DEFAULT now()
);
-- insert constraint - db and sync not null
-- Can only be one unstarted source->target per sync
CREATE UNIQUE INDEX "q_unique" ON q (sync,sourcedb,targetdb) WHERE started IS NULL;
CREATE INDEX q_ppid ON q (ppid,pid) WHERE ended IS NULL AND aborted IS NULL;
CREATE INDEX q_aborted ON q(sync) WHERE started IS NOT NULL AND aborted IS NOT NULL AND ended IS NULL;
CREATE INDEX q_cleanup ON q(cdate) WHERE ended IS NOT NULL;
CREATE INDEX q_stathelper ON q(cdate, sync) WHERE ended IS NOT NULL;
CREATE FUNCTION bucardo.bucardo_q()
RETURNS TRIGGER
LANGUAGE plpgsql
AS $bc$
BEGIN
EXECUTE 'NOTIFY "bucardo_q_'||NEW.sync||'_'||NEW.targetdb||'"';
RETURN NEW;
END;
$bc$;
CREATE TRIGGER bucardo_q
AFTER INSERT ON bucardo.q
FOR EACH ROW EXECUTE PROCEDURE bucardo.bucardo_q();
CREATE TABLE freezer.master_q AS SELECT * FROM q LIMIT 0;
GRANT SELECT ON freezer.master_q TO PUBLIC;
CREATE FUNCTION bucardo_purge_q_table(interval)
RETURNS BIGINT
SECURITY DEFINER
LANGUAGE plpgsql
AS $bc$
DECLARE
numrows BIGINT;
qcount BIGINT;
BEGIN
RAISE DEBUG 'Purging q table of finished items older than %', $1;
INSERT INTO freezer.master_q SELECT * FROM bucardo.q
WHERE (ended IS NOT NULL OR aborted IS NOT NULL) AND cdate <= now() - $1;
DELETE FROM bucardo.q WHERE (ended IS NOT NULL OR aborted IS NOT NULL) AND cdate <= now() - $1;
GET DIAGNOSTICS numrows := row_count;
SELECT count(*) FROM q INTO qcount;
RAISE NOTICE 'Rows left in q table: %', qcount;
RETURN numrows;
END;
$bc$;
CREATE FUNCTION bucardo_purge_q_table(text)
RETURNS BIGINT
LANGUAGE SQL
AS $bc$
SELECT bucardo_purge_q_table($1::interval);
$bc$;
CREATE FUNCTION bucardo_purge_q_table()
RETURNS BIGINT
LANGUAGE SQL
AS $bc$
SELECT bucardo_purge_q_table('2 hours'::interval);
$bc$;
CREATE FUNCTION bucardo_purge_q_table(integer)
RETURNS BIGINT
LANGUAGE plpgsql
IMMUTABLE
AS $bc$
BEGIN
RAISE EXCEPTION 'Please use an time interval such as ''2 hours''';
END;
$bc$;
CREATE FUNCTION table_exists(text,text)
RETURNS BOOLEAN
LANGUAGE plpgsql
AS $bc$
BEGIN
PERFORM 1
FROM pg_catalog.pg_class c, pg_namespace n
WHERE c.relnamespace = n.oid
AND n.nspname = $1
AND c.relname = $2;
IF FOUND THEN RETURN true; END IF;
RETURN false;
END;
$bc$;
-- Called on update to master_q. Creates and populates child tables, empties master_q.
CREATE OR REPLACE FUNCTION populate_child_q_table()
RETURNS TRIGGER
LANGUAGE plpgsql
VOLATILE
SECURITY DEFINER
AS
$bc$
DECLARE
myrec RECORD;
myst TEXT;
needindex BOOL = false;
tablename TEXT;
BEGIN
-- Make sure we have all child tables
FOR myrec IN SELECT DISTINCT TO_CHAR(cdate, 'YYYYMMDD') AS t FROM freezer.master_q LOOP
tablename = 'child_q_' || myrec.t;
RAISE DEBUG 'Found %', tablename;
PERFORM 1 FROM pg_class c JOIN pg_namespace n ON (n.oid = c.relnamespace)
WHERE n.nspname = 'freezer' AND c.relname = tablename;
IF NOT FOUND THEN
myst = 'CREATE TABLE freezer.' || tablename ||'() INHERITS (freezer.master_q)';
EXECUTE myst;
myst = 'GRANT SELECT ON freezer.' || tablename ||' TO public';
EXECUTE myst;
needindex = TRUE;
END IF;
IF needindex IS FALSE THEN
PERFORM 1 FROM pg_class c JOIN pg_namespace n ON (n.oid = c.relnamespace)
WHERE n.nspname = 'freezer' AND c.relname = tablename||'_daterange';
IF NOT FOUND THEN
needindex = TRUE;
END IF;
END IF;
IF needindex IS TRUE THEN
myst = 'CREATE INDEX '
|| tablename
|| '_daterange ON freezer.'
|| tablename
|| '(cdate)';
EXECUTE myst;
END IF;
-- Move all the rows over!
myst = 'INSERT INTO freezer.'
|| tablename
|| $$ SELECT * FROM ONLY freezer.master_q WHERE TO_CHAR(cdate,'YYYYMMDD') = $$
|| quote_literal(myrec.t);
EXECUTE myst;
myst = $$DELETE FROM ONLY freezer.master_q WHERE TO_CHAR(cdate, 'YYYYMMDD') = $$
|| quote_literal(myrec.t);
EXECUTE myst;
END LOOP;
RETURN NULL;
END;
$bc$;
CREATE TRIGGER populate_child_q_table
AFTER INSERT OR UPDATE ON freezer.master_q
FOR EACH STATEMENT EXECUTE PROCEDURE bucardo.populate_child_q_table();
--
-- Return a created connection string from the db table
--
CREATE OR REPLACE FUNCTION bucardo.db_getconn(text)
RETURNS TEXT
LANGUAGE plperlu
SECURITY DEFINER
AS $bc$
## Given the name of a db, return a connection string, username, and password
use strict; use warnings; use DBI;
my ($name, $SQL, $rv, $row, %db);
$name = shift;
$name =~ s/'/''/go;
$SQL = "SELECT * FROM db WHERE name = '$name'";
$rv = spi_exec_query($SQL);
if (!$rv->{processed}) {
elog(ERROR, qq{Error: Could not find a database with a name of $name\n});
}
$row = $rv->{rows}[0];
## If there is a dbfile and it exists, it overrides the rest
## Format = hostname:port:database:username:password
## http://www.postgresql.org/docs/current/static/libpq-pgpass.html
## We also check for one if no password is given
if (!defined $row->{dbpass}) {
my $passfile = $row->{pgpass} || '';
if (open my $pass, "<", $passfile) {
## We only do complete matches
my $match = "$row->{dbhost}:$row->{dbport}:$row->{dbname}:$row->{dbuser}";
while (<$pass>) {
if (/^$match:(.+)/) {
$row->{dbpass} = $1;
elog(DEBUG, "Found password in pgpass file $passfile for $match");
last;
}
}
}
}
if (defined $row->{pgpass} and length $row->{pgpass}) {
my $pfile = $row->{pgpass};
if (! -e $pfile) {
elog(WARNING, qq{Password file "$pfile" does not exist, falling back to default method.});
}
else {
open my $pw, "<", $pfile or elog(ERROR, qq{Could not open password file "$pfile": $!\n});
while(<$pw>) {
next unless /^([^:]*):([^:]*):([^:]+):([^:]+):([^:]*)$/o;
($db{host},$db{port},$db{name},$db{user},$db{pw}) = ($1,$2,$3,$4,$5);
last;
}
close $pw;
exists $db{name} or elog(ERROR, qq{The password file "$pfile" did not contain any valid information\n});
}
}
if (! exists $db{name}) {
for (qw(host port name user pass conn)) {
$db{$_} = exists $row->{"db$_"} ? $row->{"db$_"} : '';
}
}
## Check that the port is numeric
if (defined $db{port} and length $db{port} and $db{port} !~ /^\d+$/) {
elog(ERROR, qq{Database port must be numeric, but got "$db{port}"\n});
}
length $db{name} or elog(ERROR, qq{Database name is mandatory\n});
length $db{user} or elog(ERROR, qq{Database username is mandatory\n});
my $connstring = "dbi:Pg:dbname=$db{name}";
$db{host} ||= ''; $db{port} ||= ''; $db{pass} ||= '';
length $db{host} and $connstring .= ";host=$db{host}";
length $db{port} and $connstring .= ";port=$db{port}";
length $db{conn} and $connstring .= ";$db{conn}";
return "$connstring\n$db{user}\n$db{pass}";
$bc$;
--
-- Test a database connection, and log to the db_connlog table
--
CREATE FUNCTION bucardo.db_testconn(text)
RETURNS TEXT
LANGUAGE plperlu
SECURITY DEFINER
AS
$bc$
## Given the name of a db connection, construct the connection
## string for it and then connect to it and log the attempt
use strict; use warnings; use DBI;
my ($name, $SQL, $rv, $row, $dbh, %db, $version, $found);
$name = shift;
$name =~ s/'/''/g;
$SQL = "SELECT bucardo.db_getconn('$name') AS bob";
$rv = spi_exec_query($SQL);
if (!$rv->{processed}) {
elog(ERROR, qq{Error: Could not find a database with an name of $name\n});
}
$row = $rv->{rows}[0]{bob};
($db{dsn},$db{user},$db{pass}) = split /\n/ => $row;
elog(DEBUG, "Connecting as $db{dsn} user=$db{user} $$");
$dbh = DBI->connect($db{dsn}, $db{user}, $db{pass},
{AutoCommit=>1, RaiseError=>1, PrintError=>0});
if (!$dbh) {
elog(ERROR, qq{Database connection "$db{dsn}" failed: $DBI::errstr\n});
}
$version = $dbh->{pg_server_version};
# Install plpgsql if not there already
$SQL = q{SELECT 1 FROM pg_language WHERE lanname = 'plpgsql'};
my $sth = $dbh->prepare($SQL);
my $count = $sth->execute();
$sth->finish();
if ($count < 1) {
$dbh->do("CREATE LANGUAGE plpgsql");
$dbh->commit();
}
$dbh->disconnect();
my $safeconn = "$db{dsn} user=$db{user}"; ## No password for now
$safeconn =~ s/'/''/go;
$name =~ s/'/''/go;
$SQL = "INSERT INTO db_connlog (db,connstring,status,version) VALUES ('$name','$safeconn','good',$version)";
spi_exec_query($SQL);
return "Database connection successful";
$bc$;
--
-- Check the database connection if anything changes in the db table
--
CREATE FUNCTION db_change()
RETURNS TRIGGER
LANGUAGE plperlu
SECURITY DEFINER
AS
$bc$
return if $_TD->{new}{status} eq 'inactive';
## Test connection to the database specified
my $name = $_TD->{new}{name};
$name =~ s/'/''/g;
spi_exec_query("SELECT bucardo.db_testconn('$name')");
return;
$bc$;
CREATE TRIGGER db_change AFTER INSERT OR UPDATE ON db
FOR EACH ROW EXECUTE PROCEDURE db_change();
--
-- Setup the goat table after any change
--
CREATE OR REPLACE FUNCTION validate_goat()
RETURNS TRIGGER
LANGUAGE plperlu
SECURITY DEFINER
AS
$bc$
## If a row in goat has changed, re-validate and set things up for that table
elog(DEBUG, "Running validate_goat");
use strict; use warnings; use DBI;
my ($SQL, $rv, $row, %db, $dbh, $sth, $count, $oid);
my $old = $_TD->{event} eq 'UPDATE' ? $_TD->{old} : 0;
my $new = $_TD->{new};
if (!defined $new->{db}) {
die qq{Must provide a db\n};
}
if (!defined $new->{tablename}) {
die qq{Must provide a tablename\n};
}
if (!defined $new->{schemaname}) {
die qq{Must provide a schemaname\n};
}
my ($dbname,$schema,$table,$pkey) =
($new->{db}, $new->{schemaname}, $new->{tablename}, $new->{pkey});
## Do not allow pkeytype or qpkey to be set manually.
if (defined $new->{pkeytype} and (!$old or $new->{pkeytype} ne $old->{pkeytype})) {
die qq{Cannot set pkeytype manually\n};
}
if (defined $new->{qpkey} and (!$old or $new->{qpkey} ne $old->{qpkey})) {
die qq{Cannot set qpkey manually\n};
}
## If this is an update, we only continue if certain fields have changed
if ($old
and $old->{db} eq $new->{db}
and $old->{schemaname} eq $new->{schemaname}
and $old->{tablename} eq $new->{tablename}
and (defined $new->{pkey} and $new->{pkey} eq $old->{pkey})
) {
#return;
}
(my $safedbname = $dbname) =~ s/'/''/go;
$SQL = "SELECT bucardo.db_getconn('$safedbname') AS apple";
$rv = spi_exec_query($SQL);
if (!$rv->{processed}) {
elog(ERROR, qq{Error: Could not find a database with an name of $dbname\n});
}
$row = $rv->{rows}[0]{apple};
($db{dsn},$db{user},$db{pass}) = split /\n/ => $row;
elog(DEBUG, "Connecting in validate_goat as $db{dsn} user=$db{user} pid=$$ for table $schema.$table");
$dbh = DBI->connect($db{dsn}, $db{user}, $db{pass},
{AutoCommit=>0, RaiseError=>1, PrintError=>0});
$dbh or elog(ERROR, qq{Database connection "$db{dsn}" as user $db{user} failed: $DBI::errstr\n});
## Get column information for this table (and verify it exists)
$SQL = q{
SELECT c.oid, attnum, attname, quote_ident(attname) AS qattname, typname, atttypid
FROM pg_attribute a, pg_type t, pg_class c, pg_namespace n
WHERE c.relnamespace = n.oid
AND nspname = ? AND relname = ?
AND a.attrelid = c.oid
AND a.atttypid = t.oid
AND attnum > 0
};
$sth = $dbh->prepare($SQL);
$count = $sth->execute($schema,$table);
if ($count < 1) {
$sth->finish();
$dbh->disconnect();
die qq{Table not found at $db{dsn}: $schema.$table\n};
}
my $col = $sth->fetchall_hashref('attnum');
$oid = $col->{each %$col}{oid};
## Find all usable unique constraints for this table
$SQL = q{
SELECT indisprimary, indkey
FROM pg_index i
WHERE indisunique AND indpred IS NULL AND indexprs IS NULL AND indrelid = ?
ORDER BY indexrelid DESC
};
## DESC because we choose the "newest" index in case of a tie below
$sth = $dbh->prepare($SQL);
$count = 0+$sth->execute($oid);
my $cons = $sth->fetchall_arrayref({});
$dbh->rollback();
$dbh->disconnect();
elog(DEBUG, "Valid unique constraints found: $count\n");
if ($count < 1) {
## We have no usable constraints. The entries must be blank.
my $orignew = $new->{pkey};
$new->{pkey} = $new->{qpkey} = $new->{pkeytype} = '';
if (!$old) { ## This was an insert: just go
elog(DEBUG, "No usable constraints, setting pkey et. al. to blank");
return 'MODIFY';
}
## If pkey has been set to NULL, this was a specific reset request, so return
## If pkey ended up blank (no change, or changed to blank), just return
if (!defined $orignew or $orignew eq '') {
return 'MODIFY';
}
## The user has tried to change it something not blank, but this is not possible.
die qq{Cannot set pkey for table $schema.$table: no unique constraint found\n};
}
## Pick the best possible one. Primary keys are always the best choice.
my ($primary) = grep { $_->{indisprimary} } @$cons;
my $uniq;
if (defined $primary) {# and !$old and defined $new->{pkey}) {
$uniq = $primary;
}
else {
my (@foo) = grep { ! $_->{indisprimary} } @$cons;
$count = @foo;
## Pick the one with the smallest number of columns.
## In case of a tie, choose the one with the smallest column footprint
if ($count < 2) {
$uniq = $foo[0];
}
else {
my $lowest = 10_000;
for (@foo) {
my $cc = $_->{indkey} =~ y/ / /;
if ($cc < $lowest) {
$lowest = $cc;
$uniq = $_;
}
}
}
}
## This should not happen:
if (!defined $uniq) {
die "Could not find a suitable unique index for table $schema.$table\n";
}
## If the user is not trying a manual override, set the best one and leave
if ((!defined $new->{pkey} or !length $new->{pkey}) or ($old and $new->{pkey} eq $old->{pkey})) {
($new->{pkey} = $uniq->{indkey}) =~ s/(\d+)(\s+)?/$col->{$1}{attname} . ($2 ? '|' : '')/ge;
($new->{qpkey} = $uniq->{indkey}) =~ s/(\d+)(\s+)?/$col->{$1}{qattname} . ($2 ? '|' : '')/ge;
($new->{pkeytype} = $uniq->{indkey}) =~ s/(\d+)(\s+)?/$col->{$1}{typname} . ($2 ? '|' : '')/ge;
return 'MODIFY';
}
## They've attempted a manual override of pkey. Make sure it is valid.
for (@$cons) {
(my $name = $_->{indkey}) =~ s/(\d+)(\s+)?/$col->{$1}{attname} . ($2 ? '|' : '')/ge;
next unless $name eq $new->{pkey};
($new->{qpkey} = $uniq->{indkey}) =~ s/(\d+)(\s+)?/$col->{$1}{qattname} . ($2 ? '|' : '')/ge;
($new->{pkeytype} = $uniq->{indkey}) =~ s/(\d+)(\s+)?/$col->{$1}{typname} . ($2 ? '|' : '')/ge;
return 'MODIFY';
}
die qq{Could not find a matching unique constraint that provides those columns\n};
$bc$; -- End of validate_goat()
CREATE TRIGGER validate_goat
BEFORE INSERT OR UPDATE ON goat
FOR EACH ROW EXECUTE PROCEDURE validate_goat();
--
-- Check that the goat tables are ready and compatible
--
CREATE OR REPLACE FUNCTION validate_sync(text,integer)
RETURNS TEXT
LANGUAGE plperlu
SECURITY DEFINER
AS
$bc$
use strict; use warnings; use DBI;
my $syncname = shift;
my $force = shift || 0;
my ($rv,$SQL,%cache);
elog(NOTICE, "Starting validate_sync for $syncname");
## Connect to source and target(s) and verify that tables exist,
## and are identical. Setup the delta stuff as needed.
## Grab information about this sync from the database
my $safename = $syncname;
$safename =~ s/'/''/go;
$SQL = "SELECT * FROM sync WHERE name = '$safename'";
$rv = spi_exec_query($SQL);
if (!$rv->{processed}) {
elog(ERROR, "No such sync: $syncname");
}
my $info = $rv->{rows}[0];
my $source = $info->{source};
$source =~ s/'/''/go;
## Source is always a herd
## Prepare a list of all databases and tables involved in this sync
## We need to verify that the databases are reachable, that the tables exists,
## that the columns match up, and that the delta stuff is set up as needed.
my %database;
## Does this herd exist?
$SQL = qq{SELECT 1 FROM herd WHERE name = '$source'};
$rv = spi_exec_query($SQL);
if (!$rv->{processed}) {
elog(ERROR, "No such herd: $source");
}
## Process the source herd
$SQL = qq{
SELECT id, db, schemaname, tablename, pkey, pkeytype,
standard_conflict, ping AS goatping,
pg_catalog.quote_ident(db) AS safedb,
pg_catalog.quote_ident(schemaname) AS safeschema,
pg_catalog.quote_ident(tablename) AS safetable,
pg_catalog.quote_ident(pkey) AS safepkey
FROM goat g, herdmap h
WHERE g.id = h.goat
AND h.herd = '$source'
};
$rv = spi_exec_query($SQL);
if (!$rv->{processed}) {
elog(WARNING, "Herd has no members: $source");
return qq{Herd "$source" for sync "$syncname" has no members: cannot validate};
}
## All the same database, so we can extract it outside of the loop
my $sourcedb = $rv->{rows}[0]{db};
elog(DEBUG, "Got a sourcedb of $sourcedb for herd of $source");
my %sourcetable;
my %goat;
for my $x (@{$rv->{rows}}) {
$sourcetable{$x->{schemaname}}{$x->{tablename}} = $x;
}
## Now to get all the target databases (will use schemas/tables from above)
my $targetdb;
if ($info->{targetdb}) {
$targetdb->{$info->{targetdb}} = 'target';
}
elsif ($info->{targetgroup}) {
my $group = $info->{targetgroup};
$group =~ s/'/''/go;
$SQL = qq{
SELECT db, pg_catalog.quote_ident(db) AS safedb
FROM dbmap
WHERE dbgroup = '$group'
};