blib/lib/App/Netdisco/DB/SchemaCheck.pm untested

filter: Statementstmt 0.0% 0 / 136 Branchbran 0.0% 0 / 30 Conditioncond 0.0% 0 / 12 MC/DCmcdc 0.0% 0 / 7 Subroutinesub 0.0% 0 / 24 Podpod 0.0% 0 / 16 totaltotal 0.0% 0 / 225 CC 16 SCAR 24.7
CC
16
Cov
0%
run_check
42.0
_scratch_connect_info
20.0
_report_differences
12.0
CRAP 11.8
1 package App::Netdisco::DB::SchemaCheck;
2  
3 use strict;
4 use warnings;
5  
6 use Try::Tiny;
7 use Digest::MD5 'md5_hex';
8 use Encode 'encode_utf8';
9  
10 use App::Netdisco::DB;
11 use App::Netdisco::DB::Deploy 'run_deploy';
12  
13 use base 'Exporter';
14 our @EXPORT_OK = qw(
15 catalog_sql normalize_lines diff_lines check_privilege_message
16 version_mismatch_message run_check
17 );
18  
19 # One line per object in the bound schema; written for 9.6 and later, so no
20 # prokind (11+). Extensions are database-wide, so both sides list the same,
21 # and objects an extension put in the schema are left out for the same reason.
22 # PostgreSQL 18 names NOT NULL constraints after the column at creation, so a
23 # renamed column's name depends on history; the column line carries nullability.
24 my $CATALOG_SQL = <<'EOF';
25 WITH rel AS (
26 SELECT c.oid, c.relname, c.relkind FROM pg_class c
27 JOIN pg_namespace n ON n.oid = c.relnamespace WHERE n.nspname = ?
28 AND NOT EXISTS (SELECT 1 FROM pg_depend e WHERE e.classid = 'pg_class'::regclass
29 AND e.objid = c.oid AND e.deptype = 'e')
30 )
31 SELECT line FROM (
32 SELECT 'table ' || relname AS line FROM rel WHERE relkind IN ('r', 'p')
33 UNION ALL
34 SELECT 'column ' || r.relname || '.' || a.attname || ' ' || format_type(a.atttypid, a.atttypmod)
35 || CASE WHEN a.attnotnull THEN ' not null' ELSE ' null' END
36 || ' default ' || coalesce(pg_get_expr(d.adbin, d.adrelid), 'none')
37 FROM rel r JOIN pg_attribute a ON a.attrelid = r.oid
38 LEFT JOIN pg_attrdef d ON d.adrelid = a.attrelid AND d.adnum = a.attnum
39 WHERE r.relkind IN ('r', 'p') AND a.attnum > 0 AND NOT a.attisdropped
40 UNION ALL
41 SELECT 'index ' || ic.relname || ' ' || pg_get_indexdef(i.indexrelid)
42 FROM pg_index i JOIN pg_class ic ON ic.oid = i.indexrelid JOIN rel t ON t.oid = i.indrelid
43 UNION ALL
44 SELECT 'constraint ' || t.relname || '.' || con.conname || ' ' || pg_get_constraintdef(con.oid)
45 FROM pg_constraint con JOIN rel t ON t.oid = con.conrelid WHERE con.contype <> 'n'
46 UNION ALL
47 SELECT 'sequence ' || relname FROM rel WHERE relkind = 'S'
48 UNION ALL
49 SELECT 'view ' || relname || ' ' || pg_get_viewdef(oid) FROM rel WHERE relkind IN ('v', 'm')
50 UNION ALL
51 SELECT 'function ' || p.proname || '(' || pg_get_function_identity_arguments(p.oid) || ') '
52 || pg_get_functiondef(p.oid)
53 FROM pg_proc p JOIN pg_namespace n ON n.oid = p.pronamespace
54 WHERE n.nspname = ? AND NOT EXISTS (SELECT 1 FROM pg_aggregate g WHERE g.aggfnoid = p.oid)
55 AND NOT EXISTS (SELECT 1 FROM pg_depend e WHERE e.classid = 'pg_proc'::regclass
56 AND e.objid = p.oid AND e.deptype = 'e')
57 UNION ALL
58 SELECT 'extension ' || extname FROM pg_extension
59 ) lines ORDER BY line COLLATE "C"
60 EOF
61  
62 sub catalog_sql { return $CATALOG_SQL }
63  
64 sub _hash_definition {
65 my $line = shift;
66 return "$1 " . md5_hex(encode_utf8($2))
67 if $line =~ m/\A(function .+?\)) (CREATE\b.*)\z/s
68 or $line =~ m/\A(view \S+) (.*)\z/s;
69 return $line;
70 }
71  
72 # Before PostgreSQL 10 these defaults were stored expanded, and a dump restore
73 # keeps the expansion, so a database first built on 9.x reads differently.
74 my %VALUE_FUNCTION = (
75 q{('now'::text)::date} => 'CURRENT_DATE',
76 q{('now'::text)::time with time zone} => 'CURRENT_TIME',
77 q{('now'::text)::time without time zone} => 'LOCALTIME',
78 q{('now'::text)::timestamp without time zone} => 'LOCALTIMESTAMP',
79 q{now()} => 'CURRENT_TIMESTAMP',
80 );
81  
82 sub _value_function_default {
83 my $line = shift;
84 return $line unless $line =~ m/\A(column .+? default )(.+)\z/s;
85 return $1 . ($VALUE_FUNCTION{$2} // $2);
86 }
87  
88 sub normalize_lines {
89 my ($lines, $schema_name) = @_;
90 my $qualified = qr/(?<![\w"])(?:\Q$schema_name\E|"\Q$schema_name\E")\./;
91 return [ map { _hash_definition(_value_function_default(s/$qualified/public./gr)) } @$lines ];
92 }
93  
94 sub diff_lines {
95 my ($here, $fresh) = @_;
96 my %in_here = map { $_ => 1 } @$here;
97 my %in_fresh = map { $_ => 1 } @$fresh;
98 return {
99 only_here => [ grep { not $in_fresh{$_} } @$here ],
100 only_fresh => [ grep { not $in_here{$_} } @$fresh ],
101 };
102 }
103  
104 sub check_privilege_message {
105 my ($database, $role) = @_;
106 return "Cannot check the schema: --check builds a fresh install in a temporary"
107 . " schema to compare with, which needs the CREATE privilege on database"
108 . " $database, and role $role does not have it. Nothing was changed. As a"
109 . " PostgreSQL superuser, run one of these, then run the check again:\n"
110 . " ALTER DATABASE $database OWNER TO $role;\n"
111 . " GRANT CREATE ON DATABASE $database TO $role;\n"
112 . "The first matches a documented install, where Netdisco's role owns its database.";
113 }
114  
115 # A fresh install is built at the code's version, so against a database at
116 # another version every pending step would read as drift.
117 sub version_mismatch_message {
118 my ($db_version, $target_version) = @_;
119 my $action = $db_version > $target_version
120 ? "This database is newer than this Netdisco: run the check with the Netdisco version that upgraded it."
121 : "Run netdisco-db-deploy to upgrade it, then run the check again.";
122 return "Cannot check the schema: this database is at schema version "
123 . ($db_version || 'none') . " and this Netdisco expects $target_version."
124 . " A comparison would mix drift with steps not yet applied, so none was"
125 . " made and nothing was changed. $action";
126 }
127  
128 sub _read_catalog {
129 my ($dbh, $schema_name) = @_;
130 my $lines = $dbh->selectcol_arrayref(catalog_sql(), undef, $schema_name, $schema_name);
131 return normalize_lines($lines, $schema_name);
132 }
133  
134 sub _scratch_connect_info {
135 my ($schema, $quoted_scratch) = @_;
136 my @info = @{ $schema->storage->connect_info };
137 my %attributes = (ref $info[-1] eq 'HASH') ? %{ pop @info } : ();
138 my $existing = $attributes{on_connect_do};
139 $attributes{on_connect_do} = [
140 (ref $existing eq 'ARRAY' ? @$existing : defined $existing ? ($existing) : ()),
141 "SET search_path TO $quoted_scratch",
142 'SET client_min_messages TO warning',
143 ];
144 $attributes{ignore_version} = 1;
145 return (@info, \%attributes);
146 }
147  
148 # Deploy prints its failure advice for a real upgrade, so it is captured and
149 # shown only when the reference install fails.
150 sub _deploy_reference {
151 my $scratch_schema = shift;
152 my ($exit_code, $captured) = (2, '');
153 {
154 local *STDERR;
155 open STDERR, '>', \$captured or die "cannot capture the reference install's output: $!\n";
156 $exit_code = try { run_deploy($scratch_schema, { quiet => 1 }) }
157 catch { print STDERR $_; 2 };
158 }
159 return 1 if $exit_code == 0;
160 print STDERR "Cannot check the schema: the fresh reference install, built in a"
161 . " temporary schema, did not complete, so no comparison was made. This"
162 . " database was not changed; ignore any advice below about forcing a step,"
163 . " which concerns the temporary copy. Please report this as a Netdisco bug."
164 . " The reference install reported:\n", $captured;
165 return 0;
166 }
167  
168 sub _fresh_catalog {
169 my ($schema, $scratch_name, $quoted_scratch) = @_;
170 my $scratch_schema = App::Netdisco::DB->connect(
171 _scratch_connect_info($schema, $quoted_scratch));
172 return try {
173 _deploy_reference($scratch_schema)
174 ? _read_catalog($scratch_schema->storage->dbh, $scratch_name) : undef;
175 }
176 catch { print STDERR "Cannot check the schema: $_"; undef }
177 finally { $scratch_schema->storage->disconnect };
178 }
179  
180 sub _drop_scratch {
181 my ($schema, $quoted_scratch) = @_;
182 try {
183 $schema->txn_do(sub {
184 my $dbh = $schema->storage->dbh;
185 $dbh->do('SET LOCAL client_min_messages TO warning');
186 $dbh->do("DROP SCHEMA $quoted_scratch CASCADE");
187 });
188 }
189 catch {
190 print STDERR "Could not drop the temporary schema $quoted_scratch: $_"
191 . "Drop it by hand with: DROP SCHEMA $quoted_scratch CASCADE;\n";
192 };
193 }
194  
195 sub _report_differences {
196 my ($schema, $differences) = @_;
197 print "only in this database: $_\n" for @{ $differences->{only_here} };
198 print "only in a fresh install: $_\n" for @{ $differences->{only_fresh} };
199  
200 my $count = @{ $differences->{only_here} } + @{ $differences->{only_fresh} };
201 my $target_version = $schema->schema_version;
202 my $noun = $count == 1 ? 'difference' : 'differences';
203 print(($count || 'No') . " $noun from a fresh install of schema version $target_version.\n");
204 return $count ? 1 : 0;
205 }
206  
207 sub _session_facts {
208 my $dbh = shift;
209 return $dbh->selectrow_hashref(q{SELECT current_schema() AS schema_name,
210 current_database() AS database, current_user AS role,
211 has_database_privilege(current_user, current_database(), 'CREATE') AS can_create});
212 }
213  
214 sub _create_scratch {
215 my ($dbh, $quoted_scratch) = @_;
216 return try { $dbh->do("CREATE SCHEMA $quoted_scratch"); 1 }
217 catch {
218 print STDERR "Cannot check the schema: creating the temporary schema"
219 . " $quoted_scratch failed, so nothing was changed: $_";
220 0;
221 };
222 }
223  
224 sub run_check {
225 my $schema = shift;
226 my $dbh = $schema->storage->dbh;
227 my $facts = _session_facts($dbh);
228 if (not defined $facts->{schema_name}) {
229 print STDERR "Cannot check the schema: no schema on the search_path exists in database $facts->{database}.\n";
230 return 2;
231 }
232 if (not $facts->{can_create}) {
233 print STDERR check_privilege_message($facts->{database}, $facts->{role}), "\n";
234 return 2;
235 }
236 my ($db_version, $target_version) = ($schema->get_db_version, $schema->schema_version);
237 if ($db_version != $target_version) {
238 print STDERR version_mismatch_message($db_version, $target_version), "\n";
239 return 2;
240 }
241  
242 my $scratch_name = "ndcheck_$$";
243 my $quoted_scratch = $dbh->quote_identifier($scratch_name);
244 return 2 unless _create_scratch($dbh, $quoted_scratch);
245  
246 my $fresh_lines = try { _fresh_catalog($schema, $scratch_name, $quoted_scratch) }
247 catch { print STDERR "Cannot check the schema: $_"; undef }
248 finally { _drop_scratch($schema, $quoted_scratch) };
249 return 2 unless $fresh_lines;
250  
251 my $here_lines = _read_catalog($dbh, $facts->{schema_name});
252 return _report_differences($schema, diff_lines($here_lines, $fresh_lines));
253 }
254  
255 1;