| 1 | package App::Netdisco::DB::Upsert; | ||
| 2 | |||
| 3 | use strict; | ||
| 4 | use warnings; | ||
| 5 | |||
| 6 | my $max_bind_parameters = 65535; | ||
| 7 | |||
| 8 | # The three timestamp expressions netdisco workers build themselves, see | ||
| 9 | # App::Netdisco::Worker::Plugin::Discover. Nothing else is ever inlined. | ||
| 10 | my @allowed_timestamp_literals = ( | ||
| 11 | qr/\ALOCALTIMESTAMP\z/, | ||
| 12 | qr/\Ato_timestamp\([0-9]+(?:\.[0-9]+)?\)::timestamp\z/, | ||
| 13 | qr/\A'[0-9][0-9 :.+\-T]*'::timestamp\z/, | ||
| 14 | ); | ||
| 15 | |||
| 16 | =head1 NAME | ||
| 17 | |||
| 18 | App::Netdisco::DB::Upsert - bulk INSERT ... ON CONFLICT for every result set | ||
| 19 | |||
| 20 | =head1 DESCRIPTION | ||
| 21 | |||
| 22 | Internal. This interface may change between releases and is not for site-local | ||
| 23 | plugins. | ||
| 24 | |||
| 25 | Table and column names come only from the result source, never from the | ||
| 26 | caller, and every identifier is quoted. Every value is a bind parameter, with | ||
| 27 | one exception: a scalar reference is inlined only when it matches one of the | ||
| 28 | timestamp expressions netdisco itself builds. Any other reference to SQL dies. | ||
| 29 | |||
| 30 | =head1 METHODS | ||
| 31 | |||
| 32 | =head2 upsert( \@rows, \%options ) | ||
| 33 | |||
| 34 | Writes each row with one C<INSERT ... ON CONFLICT (primary key) DO UPDATE>, | ||
| 35 | in batches that stay under the PostgreSQL bind parameter limit. Returns the | ||
| 36 | number of rows inserted or updated, so a row already holding the same values | ||
| 37 | counts as zero. Returns 0 and sends nothing for an empty list. | ||
| 38 | |||
| 39 | Each row is a hash reference of column to value. Every row must have the same | ||
| 40 | keys, including every primary key column, and each key must appear once. | ||
| 41 | Values are undef, a plain scalar, an array reference of plain scalars (for | ||
| 42 | array columns), or an allowed timestamp literal. | ||
| 43 | |||
| 44 | Options: | ||
| 45 | |||
| 46 | =over 4 | ||
| 47 | |||
| 48 | =item C<insert_only> | ||
| 49 | |||
| 50 | Columns written on insert and never changed by the update. | ||
| 51 | |||
| 52 | =item C<touch> | ||
| 53 | |||
| 54 | Columns updated, but left out of the change test, so they change only when | ||
| 55 | some other column does. | ||
| 56 | |||
| 57 | =back | ||
| 58 | |||
| 59 | =cut | ||
| 60 | |||
| 61 | sub upsert { | ||
| 62 | my ($rs, $rows, $options) = @_; | ||
| 63 | $rs->throw_exception("upsert: rows must be an array reference of hash references of column to value") | ||
| 64 | unless ref $rows eq 'ARRAY'; | ||
| 65 | $options = _upsert_options($rs, $options); | ||
| 66 | return 0 unless scalar @$rows; | ||
| 67 | |||
| 68 | my $source = $rs->result_source; | ||
| 69 | my ($table, @key_columns) = _upsert_target($rs, 'upsert'); | ||
| 70 | |||
| 71 | my @columns = _upsert_columns($rs, $table, $rows->[0], $options); | ||
| 72 | my @sorted = _upsert_sorted_rows($rs, $table, $rows, \@columns, \@key_columns); | ||
| 73 | |||
| 74 | my $per_batch = int($max_bind_parameters / scalar @columns) || 1; | ||
| 75 | my $changed = 0; | ||
| 76 | while (my @batch = splice @sorted, 0, $per_batch) { | ||
| 77 | $changed += $source->storage->dbh_do(sub { | ||
| 78 | my ($sql, @binds) = _upsert_statement($_[1], $table, \@columns, | ||
| 79 | \@key_columns, \@batch, $options); | ||
| 80 | return 0 + $_[1]->do($sql, undef, @binds); | ||
| 81 | }); | ||
| 82 | } | ||
| 83 | return $changed; | ||
| 84 | } | ||
| 85 | |||
| 86 | =head2 remove_unseen( \%scope, \@seen ) | ||
| 87 | |||
| 88 | Deletes the rows in C<%scope> whose primary key is not in C<@seen>, with one | ||
| 89 | plain C<DELETE> and returns the number of rows deleted. It does no cascade, and | ||
| 90 | it refuses the C<Node> and C<DevicePortLog> sources, whose rows are never | ||
| 91 | deleted by this method. | ||
| 92 | |||
| 93 | Call it on a plain C<< resultset('Source') >>. A result set carrying search | ||
| 94 | conditions, such as C<< $device-E<gt>port_vlans >>, is refused, because only | ||
| 95 | C<%scope> restricts the C<DELETE>. | ||
| 96 | |||
| 97 | C<%scope> maps primary key columns to plain scalars and must be non-empty. When | ||
| 98 | C<ip> is one of the source's key columns, C<%scope> must include it (for | ||
| 99 | discover, C<< { ip =E<gt> $device-E<gt>ip } >>). It must leave at least one key | ||
| 100 | column out, or it would name a single row. C<@seen> holds hash references with | ||
| 101 | exactly the key columns not in C<%scope>. An empty C<@seen> deletes every row in | ||
| 102 | the scope, which is right for a complete walk that found nothing. | ||
| 103 | |||
| 104 | =cut | ||
| 105 | |||
| 106 | sub remove_unseen { | ||
| 107 | my ($rs, $scope, $seen) = @_; | ||
| 108 | my ($table, @key_columns) = _upsert_target($rs, 'remove_unseen'); | ||
| 109 | _remove_unseen_refuse_unsafe_target($rs); | ||
| 110 | $rs->throw_exception("remove_unseen: scope must be a hash reference of primary key column to value") | ||
| 111 | unless ref $scope eq 'HASH'; | ||
| 112 | $rs->throw_exception("remove_unseen: scope must name at least one key column of '$table' (" | ||
| 113 | . join(', ', @key_columns) . "); an empty scope would delete rows beyond the one device or group being refreshed") | ||
| 114 | unless scalar keys %$scope; | ||
| 115 | $rs->throw_exception("remove_unseen: seen must be an array reference of hash references of the key columns not in scope") | ||
| 116 | unless ref $seen eq 'ARRAY'; | ||
| 117 | |||
| 118 | my %is_key = map { $_ => 1 } @key_columns; | ||
| 119 | foreach my $name (sort keys %$scope) { | ||
| 120 | $rs->throw_exception("remove_unseen: scope column '$name' is not a primary key column of '$table'; use only " | ||
| 121 | . join(', ', @key_columns)) | ||
| 122 | unless $is_key{$name}; | ||
| 123 | $rs->throw_exception("remove_unseen: scope value for '$name' must be a plain scalar, not undef or a reference") | ||
| 124 | unless defined $scope->{$name} and not ref $scope->{$name}; | ||
| 125 | } | ||
| 126 | $rs->throw_exception("remove_unseen: scope for '$table' must include 'ip' or the DELETE would remove other devices' rows;" | ||
| 127 | . " discover callers must scope by device, for example { ip => \$device->ip }") | ||
| 128 | if $is_key{ip} and not exists $scope->{ip}; | ||
| 129 | my @scoped = grep { exists $scope->{$_} } @key_columns; | ||
| 130 | my @rest = grep { not exists $scope->{$_} } @key_columns; | ||
| 131 | $rs->throw_exception("remove_unseen: scope covers the whole key of '$table'; leave at least one of " | ||
| 132 | . join(', ', @key_columns) . " out of the scope and pass its values in seen") | ||
| 133 | unless @rest; | ||
| 134 | |||
| 135 | my @casts = _remove_unseen_casts($rs, $table, \@rest); | ||
| 136 | my @arrays = _remove_unseen_arrays($rs, $seen, \@rest); | ||
| 137 | return $rs->result_source->storage->dbh_do(sub { | ||
| 138 | my $dbh = $_[1]; | ||
| 139 | my $quote = sub { $dbh->quote_identifier($_[0]) }; | ||
| 140 | my $sql = 'DELETE FROM ' . $quote->($table) . ' WHERE ' | ||
| 141 | . join(' AND ', map { $quote->($_) . ' = ?' } @scoped) | ||
| 142 | . ' AND (' . join(', ', map { $quote->($_) } @rest) . ') NOT IN (SELECT * FROM unnest(' | ||
| 143 | . join(', ', map { "?::$_\[]" } @casts) . '))'; | ||
| 144 | return 0 + $dbh->do($sql, undef, (map { $scope->{$_} } @scoped), @arrays); | ||
| 145 | }); | ||
| 146 | } | ||
| 147 | |||
| 148 | sub _remove_unseen_refuse_unsafe_target { | ||
| 149 | my $rs = shift; | ||
| 150 | my $source_name = $rs->result_source->source_name; | ||
| 151 | $rs->throw_exception("remove_unseen: '$source_name' rows are never deleted by this method; remove them with their own delete code") | ||
| 152 | if $source_name eq 'Node' or $source_name eq 'DevicePortLog'; | ||
| 153 | |||
| 154 | my $where = $rs->{attrs}{where}; | ||
| 155 | my $has_conditions = ref $where eq 'HASH' ? scalar keys %$where | ||
| 156 | : ref $where eq 'ARRAY' ? scalar @$where : defined $where; | ||
| 157 | $rs->throw_exception("remove_unseen: this result set carries search conditions, which the DELETE would ignore;" | ||
| 158 | . " call remove_unseen on resultset('$source_name') and pass the restriction in the scope, for example { ip => \$device->ip }") | ||
| 159 | if $has_conditions; | ||
| 160 | return; | ||
| 161 | } | ||
| 162 | |||
| 163 | sub _remove_unseen_casts { | ||
| 164 | my ($rs, $table, $columns) = @_; | ||
| 165 | my $source = $rs->result_source; | ||
| 166 | return map { | ||
| 167 | my $type = $source->column_info($_)->{data_type}; | ||
| 168 | $rs->throw_exception("remove_unseen: column '$_' of '$table' has data type " | ||
| 169 | . (defined $type ? "'$type'" : 'undef') . " that cannot be used as a cast; give it a plain data_type in its result class") | ||
| 170 | unless defined $type and $type =~ m/\A[a-z][a-z ]*\z/; | ||
| 171 | $type; | ||
| 172 | } @$columns; | ||
| 173 | } | ||
| 174 | |||
| 175 | sub _remove_unseen_arrays { | ||
| 176 | my ($rs, $seen, $columns) = @_; | ||
| 177 | my $expected = join ', ', sort @$columns; | ||
| 178 | my @arrays = map { [] } @$columns; | ||
| 179 | |||
| 180 | foreach my $index (0 .. $#$seen) { | ||
| 181 | my $row = $seen->[$index]; | ||
| 182 | $rs->throw_exception("remove_unseen: seen row $index is not a hash reference; pass hash references of key column to value") | ||
| 183 | unless ref $row eq 'HASH'; | ||
| 184 | my $actual = join ', ', sort keys %$row; | ||
| 185 | $rs->throw_exception("remove_unseen: seen row $index has columns ($actual) but must have exactly ($expected)") | ||
| 186 | unless scalar(keys %$row) == scalar(@$columns) and not grep { not exists $row->{$_} } @$columns; | ||
| 187 | |||
| 188 | foreach my $position (0 .. $#$columns) { | ||
| 189 | my $name = $columns->[$position]; | ||
| 190 | $rs->throw_exception("remove_unseen: seen row $index value for '$name' must be a plain scalar, not undef or a reference") | ||
| 191 | unless defined $row->{$name} and not ref $row->{$name}; | ||
| 192 | push @{ $arrays[$position] }, $row->{$name}; | ||
| 193 | } | ||
| 194 | } | ||
| 195 | return @arrays; | ||
| 196 | } | ||
| 197 | |||
| 198 | sub _upsert_target { | ||
| 199 | my ($rs, $method) = @_; | ||
| 200 | my $source = $rs->result_source; | ||
| 201 | my $table = $source->name; | ||
| 202 | $rs->throw_exception("$method: result source '" . $source->source_name | ||
| 203 | . "' has no plain table name, so $method cannot use it; call $method on a table result set") | ||
| 204 | if ref $table or not defined $table or $table !~ m/\A\w+\z/; | ||
| 205 | |||
| 206 | my @key_columns = $source->primary_columns; | ||
| 207 | $rs->throw_exception("$method: table '$table' has no primary key to identify rows by") | ||
| 208 | unless @key_columns; | ||
| 209 | return ($table, @key_columns); | ||
| 210 | } | ||
| 211 | |||
| 212 | sub _upsert_options { | ||
| 213 | my ($rs, $options) = @_; | ||
| 214 | return { insert_only => [], touch => [] } unless defined $options; | ||
| 215 | $rs->throw_exception("upsert: options must be a hash reference; allowed keys are insert_only, touch") | ||
| 216 | unless ref $options eq 'HASH'; | ||
| 217 | |||
| 218 | foreach my $name (sort keys %$options) { | ||
| 219 | $rs->throw_exception("upsert: unknown option '$name'; allowed options are insert_only, touch") | ||
| 220 | unless $name eq 'insert_only' or $name eq 'touch'; | ||
| 221 | } | ||
| 222 | my %clean; | ||
| 223 | foreach my $name (qw/insert_only touch/) { | ||
| 224 | my $list = $options->{$name}; | ||
| 225 | $list = [] unless defined $list; | ||
| 226 | $rs->throw_exception("upsert: option '$name' must be an array reference of column names") | ||
| 227 | if ref $list ne 'ARRAY' or grep { not defined $_ or ref $_ } @$list; | ||
| 228 | $clean{$name} = $list; | ||
| 229 | } | ||
| 230 | return \%clean; | ||
| 231 | } | ||
| 232 | |||
| 233 | sub _upsert_columns { | ||
| 234 | my ($rs, $table, $first_row, $options) = @_; | ||
| 235 | my $source = $rs->result_source; | ||
| 236 | $rs->throw_exception("upsert: rows must be hash references of column to value") | ||
| 237 | unless ref $first_row eq 'HASH'; | ||
| 238 | |||
| 239 | my @columns = sort keys %$first_row; | ||
| 240 | foreach my $name (@columns, @{ $options->{insert_only} || [] }, @{ $options->{touch} || [] }) { | ||
| 241 | $rs->throw_exception("upsert: no column '$name' in table '$table'; remove it from the rows or options") | ||
| 242 | unless defined $name and $source->has_column($name); | ||
| 243 | } | ||
| 244 | my %in_rows = map { $_ => 1 } @columns; | ||
| 245 | foreach my $name (@{ $options->{insert_only} || [] }, @{ $options->{touch} || [] }) { | ||
| 246 | $rs->throw_exception("upsert: option column '$name' is not a key of the rows; add it to every row or remove it from the options") | ||
| 247 | unless $in_rows{$name}; | ||
| 248 | } | ||
| 249 | return @columns; | ||
| 250 | } | ||
| 251 | |||
| 252 | sub _upsert_sorted_rows { | ||
| 253 | my ($rs, $table, $rows, $columns, $key_columns) = @_; | ||
| 254 | my $expected = join ', ', @$columns; | ||
| 255 | my (%seen, @keyed); | ||
| 256 | |||
| 257 | foreach my $index (0 .. $#$rows) { | ||
| 258 | my $row = $rows->[$index]; | ||
| 259 | $rs->throw_exception("upsert: row $index is not a hash reference; pass hash references of column to value") | ||
| 260 | unless ref $row eq 'HASH'; | ||
| 261 | |||
| 262 | my $actual = join ', ', sort keys %$row; | ||
| 263 | $rs->throw_exception("upsert: row $index has columns ($actual) but row 0 has ($expected); pass rows that all have the same columns") | ||
| 264 | unless scalar(keys %$row) == scalar(@$columns) and not grep { not exists $row->{$_} } @$columns; | ||
| 265 | |||
| 266 | foreach my $name (@$key_columns) { | ||
| 267 | $rs->throw_exception("upsert: row $index has no value for primary key column '$name' of '$table'; every row must set " | ||
| 268 | . join(', ', @$key_columns)) | ||
| 269 | unless defined $row->{$name} and not ref $row->{$name}; | ||
| 270 | } | ||
| 271 | _upsert_check_value($rs, $_, $row->{$_}) for @$columns; | ||
| 272 | |||
| 273 | my @key_values = map { $row->{$_} } @$key_columns; | ||
| 274 | my $joined = join "\0", @key_values; | ||
| 275 | $rs->throw_exception("upsert: duplicate key (" . join(', ', @key_values) | ||
| 276 | . ") in rows for '$table'; the caller must pass each key once") | ||
| 277 | if $seen{$joined}++; | ||
| 278 | push @keyed, [$joined, $row]; | ||
| 279 | } | ||
| 280 | return map { $_->[1] } sort { $a->[0] cmp $b->[0] } @keyed; | ||
| 281 | } | ||
| 282 | |||
| 283 | sub _upsert_check_value { | ||
| 284 | my ($rs, $name, $value) = @_; | ||
| 285 | my $kind = ref $value; | ||
| 286 | return if not $kind; | ||
| 287 | |||
| 288 | if ($kind eq 'ARRAY') { | ||
| 289 | return unless grep { ref $_ } @$value; | ||
| 290 | $rs->throw_exception("upsert: value for '$name' is an array reference with an element that is itself a reference; " | ||
| 291 | . "it must be undef, a plain scalar, an array reference of plain scalars, or an allowed timestamp literal"); | ||
| 292 | } | ||
| 293 | elsif ($kind eq 'SCALAR' or $kind eq 'REF') { | ||
| 294 | return if $kind eq 'SCALAR' and _upsert_is_timestamp_literal($value); | ||
| 295 | my $shown = (($kind eq 'SCALAR') and defined $$value and not ref $$value) | ||
| 296 | ? "'$$value'" : '(a reference)'; | ||
| 297 | $rs->throw_exception("upsert: literal SQL $shown for '$name' is not an allowed timestamp form; " | ||
| 298 | . "pass a plain value so it is bound, or LOCALTIMESTAMP, to_timestamp(N)::timestamp or 'YYYY-MM-DD HH:MM:SS'::timestamp"); | ||
| 299 | } | ||
| 300 | $rs->throw_exception("upsert: value for '$name' is a $kind reference, which must be undef, a plain scalar, " | ||
| 301 | . "an array reference of plain scalars, or an allowed timestamp literal"); | ||
| 302 | } | ||
| 303 | |||
| 304 | sub _upsert_is_timestamp_literal { | ||
| 305 | my $text = ${ $_[0] }; | ||
| 306 | return 0 if not defined $text or ref $text; | ||
| 307 | return scalar grep { $text =~ $_ } @allowed_timestamp_literals; | ||
| 308 | } | ||
| 309 | |||
| 310 | sub _upsert_statement { | ||
| 311 | my ($dbh, $table, $columns, $key_columns, $batch, $options) = @_; | ||
| 312 | my $quote = sub { $dbh->quote_identifier($_[0]) }; | ||
| 313 | my %skip = map { $_ => 1 } @$key_columns, @{ $options->{insert_only} || [] }; | ||
| 314 | my %touch = map { $_ => 1 } @{ $options->{touch} || [] }; | ||
| 315 | |||
| 316 | my @update = grep { not $skip{$_} } @$columns; | ||
| 317 | my @compare = grep { not $touch{$_} } @update; | ||
| 318 | |||
| 319 | my @binds; | ||
| 320 | my @tuples = map { | ||
| 321 | my $row = $_; | ||
| 322 | '(' . join(', ', map { | ||
| 323 | my $value = $row->{$_}; | ||
| 324 | if (ref $value eq 'SCALAR') { $$value } | ||
| 325 | else { push @binds, $value; '?' } | ||
| 326 | } @$columns) . ')'; | ||
| 327 | } @$batch; | ||
| 328 | |||
| 329 | my $quoted_table = $quote->($table); | ||
| 330 | my $sql = "INSERT INTO $quoted_table (" . join(', ', map { $quote->($_) } @$columns) | ||
| 331 | . ') VALUES ' . join(', ', @tuples) | ||
| 332 | . ' ON CONFLICT (' . join(', ', map { $quote->($_) } @$key_columns) . ')'; | ||
| 333 | |||
| 334 | if (not @compare) { | ||
| 335 | return ("$sql DO NOTHING", @binds); | ||
| 336 | } | ||
| 337 | $sql .= ' DO UPDATE SET ' | ||
| 338 | . join(', ', map { $quote->($_) . ' = EXCLUDED.' . $quote->($_) } @update) | ||
| 339 | . ' WHERE (' . join(', ', map { "$quoted_table." . $quote->($_) } @compare) | ||
| 340 | . ') IS DISTINCT FROM (' . join(', ', map { 'EXCLUDED.' . $quote->($_) } @compare) . ')'; | ||
| 341 | return ($sql, @binds); | ||
| 342 | } | ||
| 343 | |||
| 344 | 1; |