-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtest.sql
74 lines (57 loc) · 2.11 KB
/
test.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
BEGIN;
CREATE SCHEMA test_pg_array_fk;
SET search_path TO test_pg_array_fk;
SET client_min_messages TO WARNING;
\set ON_ERROR_STOP on
-- Load the library.
\ir ./pg-array-fk-up.sql
-- Initial fixture.
CREATE TABLE test (
id text,
parents text[],
ancestors text[]
);
-- Add triggers.
SELECT array_fk_create('test', 'parents', 'test', 'text');
SELECT array_fk_create('test', 'ancestors', 'test', 'text');
-- Add stuff
INSERT INTO test VALUES ('root', '{null}', '{null}');
INSERT INTO test VALUES ('root.foo', '{root}', '{}');
INSERT INTO test VALUES ('root.bar', '{root}', '{}');
INSERT INTO test VALUES ('root.foo.child', '{root,root.foo}', '{}');
INSERT INTO test VALUES ('orphan', '{}', '{}');
UPDATE test SET ancestors = '{root.foo,root.bar,root.foo.child}' WHERE id = 'root';
UPDATE test SET ancestors = '{root.foo.child}' WHERE id = 'root.foo';
UPDATE test SET ancestors = '{root.foo.child}' WHERE id = 'orphan';
UPDATE test SET parents = '{root.foo,root}' WHERE id = 'orphan';
UPDATE test SET ancestors = ancestors || '{orphan}' WHERE id IN ('root', 'root.foo');
DO $$
BEGIN
DELETE FROM test WHERE id = 'root';
ASSERT NOT EXISTS (
SELECT id FROM test WHERE 'root' = ANY(ancestors) OR 'root' = ANY(parents)
), 'root still present';
DELETE FROM test WHERE id = 'orphan';
ASSERT NOT EXISTS (
SELECT id FROM test WHERE 'orphan' = ANY(ancestors) OR 'orphan' = ANY(parents)
), 'orphan still present';
BEGIN
UPDATE test SET parents = '{not-found}' WHERE id = 'root.foo';
SELECT 1/0;
EXCEPTION
WHEN division_by_zero THEN RAISE EXCEPTION 'Should not reach here';
WHEN OTHERS THEN RAISE NOTICE 'ok!';
END;
DELETE FROM test WHERE id = 'root.foo.child';
PERFORM test FROM test
WHERE parents IS DISTINCT FROM '{}' OR ancestors IS DISTINCT FROM '{}';
IF FOUND THEN
RAISE 'All rows must have empty parents/ancestors after DELETE.';
END IF;
END;
$$ LANGUAGE plpgsql;
-- Test that cleanup works.
SELECT array_fk_drop('test', 'parents', 'test');
SELECT array_fk_create('test', 'ancestors', 'test', 'text');
\ir ./pg-array-fk-down.sql
ROLLBACK;