Support database schema updates
v2 cover Support database schema updates
Thanks for the quick review. There is little change here, other than significant changes to the README in
5/8 Schema: Support database schema updates
as prompted by review comments.
All the patches apart from that and
4/8 Schema: Introduce mg-schema-create
have been acked.
Thanks,
Ian.
PATCH v2 1/8 mg-schema-test-database: Fix argument parsing for _SUFFIX
--- mg-schema-test-database | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-)
mg-schema-test-database +1 -1
@@ -244,7 +244,7 @@ create) -v type="${rhs%% *}" \ -v refkey="${rhs#* }" ;; - _) suffix="$arg" + _*) suffix="$arg" ;; -f*) minflight="${arg#-f}" ;;
Signature · 1 line
1.7.10.4
PATCH v2 2/8 Schema: Rename schema file
In reply to Ian JacksonWe are going to have multiple schema snippets and this is going be just the initial baseline.
Rename the file and change references to it.
--- INSTALL.production | 4 ++-- mg-schema-test-database | 2 +- executive-postgresql-schema => schema/initial.sql | 0 3 files changed, 3 insertions(+), 3 deletions(-) rename executive-postgresql-schema => schema/initial.sql (100%)
INSTALL.production +2 -2
@@ -29,8 +29,8 @@ DATABASE SERVER --------------- osstest requires a Postgres database server and a database configured -with the schema described in executive-postgresql-schema which should -be accessible to an osstest role account. +with the schema described in schema/initial.sql should be accessible +to an osstest role account. The hostname and dbname are configured via the "ExecutiveDbnamePat" config option.
mg-schema-test-database +1 -1
@@ -387,7 +387,7 @@ END tables=$(tsort <$t.tablesortlist) # We don't want to set the permissions - perl <executive-postgresql-schema >$t.new-schema -pe ' + perl <schema/initial.sql >$t.new-schema -pe ' s/^/--/ if m/^ALTER TABLE .* OWNER TO / || m/^GRANT |^REVOKE /
schema/initial.sql renamed from executive-postgresql-schema +0 -0
Signature · 1 line
1.7.10.4
PATCH v2 3/8 Schema: Remove SET OWNER and GRANT/REVOKE from schema/initial.sql
In reply to Ian JacksonReally, we don't want the initial schema setup to mess about with permissions. Instead, we simply expect to run the creation as the correct role user.
So:
- Remove the code in mg-schema-test-database to remove the permission settings from initial.sql;
- Instead, run exactly that code on initial.sql and commit the result.
--- mg-schema-test-database | 9 +--- schema/initial.sql | 132 +++++++++++++++++++++++------------------------ 2 files changed, 67 insertions(+), 74 deletions(-)
mg-schema-test-database +1 -8
@@ -386,19 +386,12 @@ END tables=$(tsort <$t.tablesortlist) - # We don't want to set the permissions - perl <schema/initial.sql >$t.new-schema -pe ' - s/^/--/ if - m/^ALTER TABLE .* OWNER TO / || - m/^GRANT |^REVOKE / - ' - #---------- create test db ---------- psql_do <<END CREATE DATABASE $dbname; END - $(withtest get_psql_cmd) -q -f $t.new-schema + $(withtest get_psql_cmd) -q -f schema/initial.sql printf ".\n"
schema/initial.sql +66 -66
294 lines not on this page · raw message
Signature · 1 line
1.7.10.4
PATCH v2 4/8 Schema: Introduce mg-schema-create
In reply to Ian JacksonThere is a fair amount of option parsing clobber here that will be relevant shortly.
--- mg-schema-create | 61 +++++++++++++++++++++++++++++++++++++++++++++++ mg-schema-test-database | 2 +- 2 files changed, 62 insertions(+), 1 deletion(-) create mode 100755 mg-schema-create
mg-schema-create new file +61 -0
@@ -0,0 +1,61 @@ +#!/bin/bash + +# This is part of "osstest", an automated testing framework for Xen. +# Copyright (C) 2009-2015 Citrix Inc. +# +# This program is free software: you can redistribute it and/or modify +# it under the terms of the GNU Affero General Public License as published by +# the Free Software Foundation, either version 3 of the License, or +# (at your option) any later version. +# +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU Affero General Public License for more details. +# +# You should have received a copy of the GNU Affero General Public License +# along with this program. If not, see <http://www.gnu.org/licenses/>. + + +# Usages: +# +# ./mg-schema-create [<options>] +# +# Database must already exist. (Ie, mg-schema-create does not +# do CREATE DATABASE.) +# +# When setting up a production database, mg-schema-create should +# be run *AS THE ROLE USER* who is to own all the resources. +# +# Options: +# +# -q don't print progress messages + +set -e +set -o posix +set -o pipefail + +progress () { printf "%s\n" "$*"; } +progress=progress +quietopt='' + +while [ $# != 0 ]; do + arg=$1; shift + case "$arg" in + -q) + progress=: + quietopt=-q + ;; + *) + echo >&2 "bad usage ($arg)"; exit 127 + ;; + esac +done + +. ./cri-getconfig + +$progress "Populating database..." + +$(get_psql_cmd) $quietopt -f schema/initial.sql + +$progress "Database set up."
mg-schema-test-database +1 -1
@@ -391,7 +391,7 @@ END psql_do <<END CREATE DATABASE $dbname; END - $(withtest get_psql_cmd) -q -f schema/initial.sql + withtest ./mg-schema-create -q printf ".\n"
Signature · 1 line
1.7.10.4
Re: [OSSTEST PATCH 4/8] Schema: Introduce mg-schema-create
Quoted 4 lines · Ian Jackson
There is a fair amount of option parsing clobber here that will be relevant shortly.
Signed-off-by Ian Jackson <[email protected]>
(perhaps assuming #8 goes in in the same batch)
Re: [OSSTEST PATCH 4/8] Schema: Introduce mg-schema-create
Ian Campbell writes ("Re: [OSSTEST PATCH 4/8] Schema: Introduce mg-schema-create"):
Quoted 9 lines · Ian Jackson
Quoted 4 lines
There is a fair amount of option parsing clobber here that will be relevant shortly.
Signed-off-by Ian Jackson <[email protected]>Acked-by Ian Campbell <[email protected]>(perhaps assuming #8 goes in in the same batch)
It should do.
Ian.
PATCH v2 5/8 Schema: Support database schema updates
In reply to Ian JacksonSee schema/README.schema, introduced in this patch, for the design.
---
v2: Slight increase schema update name length format.
Docs fixes:
Change erroneous three' to four'.
Change state' to status' throghout.
Explain scope of <status>.
Sort out (and renumber) `Update order for Populate-then-rely'. Sort out "Statuses" explanations.
Encourage use of DML update, rather than ad-hoc scripts,
for populating new columns.
--- Osstest/Executive.pm | 82 +++++++++++++++ mg-schema-create | 20 ++++ mg-schema-test-database | 6 +- mg-schema-update | 255 +++++++++++++++++++++++++++++++++++++++++++++ schema/README.updates | 179 +++++++++++++++++++++++++++++++ schema/schema-updates.sql | 6 ++ 6 files changed, 547 insertions(+), 1 deletion(-) create mode 100755 mg-schema-update create mode 100644 schema/README.updates create mode 100644 schema/schema-updates.sql
Osstest/Executive.pm +82 -0
@@ -56,6 +56,7 @@ BEGIN { resource_check_allocated resource_shared_mark_ready duration_estimator db_pg_dsn opendb opendb_state + db_schema_updates_applied db_schema_updates_intree ); %EXPORT_TAGS = ( colours => [qw($green $red $yellow $purple $blue)] );
@@ -128,6 +129,87 @@ sub grabrepolock_reexec { } } +sub db_schema_updates_applied (;$) { + my ($cond) = @_; + my $r; + $cond //= '1=1'; + eval { + local $dbh_tests->{PrintError} = 0; + $r = $dbh_tests->selectall_arrayref(<<END); + SELECT updatename, applytime + FROM schema_updates WHERE $cond +END + }; + if ($@) { + die unless + $dbh_tests->err()==7 && # DBD::Pg(3pm) + $dbh_tests->state() eq '42P01'; + # http://www.postgresql.org/docs/current/static/errcodes-appendix.html + $r = [ ]; + } + my @r; + foreach (@$r) { + push @r, { Name => $_->[0], Applied => $_->[1] }; + } + return \@r; +} + +sub db_schema_updates_intree (;$) { + my ($incommit) = @_; + # ->[]{Name} + # ->[]{Seq} + # ->[]{State} + + my @results; + + my @files; + if (!$incommit) { + @files = <schema/*.sql>; + } else { + local $/ = "\0"; + open GLF, "-|", qw(git ls-tree -z), $incommit, "schema/" or die $!; + while (<GLF>) { + chomp; + next unless s/^\d+ blob \w+\t//; + push @files, $_; + } + $!=0; $?=0; close GLF or die "$! $? ($incommit)"; + } + + FILE: foreach my $f (@files) { + $f =~ m/\.sql$/ or next; + $f =~ m#/([a-z][0-9a-z-]+)\.sql$# or die "badly named .sql file $f\n"; + my $name = $1; + next if $name eq 'initial'; + if ($incommit) { + open SQLF, "-|", qw(git cat-file blob), "$incommit:$f" or die $!; + } else { + open SQLF, "<", $f or die "$f $!"; + } + while (<SQLF>) { + chomp; + my $origl = $_; + next unless s/^\s*--\s*##OSSTEST##\s+//; + m/^0*([1-9]\d*)\s+(Harmless|Preparatory|Unfinished|Ready|Needed)\b/ + or die "$origl ?"; + push @results, { + Name => $name, + Seq => $1+0, + State => $2, + }; + next FILE; + } + $!=0; $?=0; close SQLF; die "$f \`$name' no token ($! $?)"; + } + + @results = sort { + $a->{Seq} <=> $b->{Seq} || + die "$a->{Name} $a->{Seq} == $b->{Name} $b->{Seq}" + } @results; + + return \@results; +} + #---------- database access ----------# sub opendb_state () {
mg-schema-create +20 -0
@@ -30,6 +30,9 @@ # Options: # # -q don't print progress messages +# --no-updates apply no schema updates +# --stop-before --stop-after only apply some schema updates - +# see mg-schema-update set -e set -o posix
@@ -38,6 +41,8 @@ set -o pipefail progress () { printf "%s\n" "$*"; } progress=progress quietopt='' +do_updates=true +updates=() while [ $# != 0 ]; do arg=$1; shift
@@ -46,16 +51,31 @@ while [ $# != 0 ]; do progress=: quietopt=-q ;; + --stop-before|--stop-after) + updates+=("$arg" "$1"); shift + ;; + --stop-before=*|--stop-after=*) + updates+=("$arg"); shift + ;; + --no-updates) + do_updates=false + ;; *) echo >&2 "bad usage ($arg)"; exit 127 ;; esac done +export OSSTEST_DB_USEREAL_IGNORETEST='.*' + . ./cri-getconfig $progress "Populating database..." $(get_psql_cmd) $quietopt -f schema/initial.sql +if $do_updates; then + ./mg-schema-update $quietopt apply-all "${updates[@]}" +fi + $progress "Database set up."
mg-schema-test-database +5 -1
@@ -344,6 +344,8 @@ END # Keep a copy as it came from dump, for comparison cp $t.schema $t.schema.orig + wantupdates=$(./mg-schema-update list-applied) + # http://www.postgresql.org/message-id/[email protected] perl -i~ -pe ' s/^/--/ if
@@ -391,7 +393,9 @@ END psql_do <<END CREATE DATABASE $dbname; END - withtest ./mg-schema-create -q + withtest ./mg-schema-create -q --no-updates + + withtest ./mg-schema-update -q apply $wantupdates printf ".\n"
mg-schema-update new file +255 -0
255 lines not on this page · raw message
schema/README.updates new file +179 -0
179 lines not on this page · raw message
schema/schema-updates.sql new file +6 -0
@@ -0,0 +1,6 @@ +-- ##OSSTEST## 001 Harmless + +CREATE TABLE schema_updates ( + updatename TEXT PRIMARY KEY, + applytime integer NOT NULL +);
Signature · 1 line
1.7.10.4
Re: [OSSTEST PATCH 5/8] Schema: Support database schema updates
Quoted 26 lines · Ian Jackson
schema/README.updates new file +20
-0@@ -0,0 +1,179 @@ +SCHEMA DEFINITION AND SCHEMA UPDATES (PRODUCTION `EXECUTIVE' MODE) +================================================================== + +To generate a new DB, we apply the original schema (in initial.sql) +and then apply all the updates, in order. + +We maintain a table in the DB which records which updates are applied. + + +Schema update snippet format +---------------------------- + +Schema update snippets should be called + schema/<updatename>.sql + +They should contain DDL commands (ALTER TABLE etc.) to make whatever +changes are needed. + +They MUST NOT contain BEGIN or COMMIT. +
schema/README.updates line 30
Quoted 10 lines
schema/README.updates new file +10
-0+They must contain a special comment near the top: + + -- ##OSSTEST## <sequence> <status> + +<updatename> is a string (/^[a-z][0-9a-z-]+$/) which uniquely identifies +the update. It must not be changed because existing installations +rely on updates having stable names. + +<sequence> is a positive integer, which should be unique. Updates are +applied in order.
Don't these also need to be monotonically increasing over time/commits?
i.e. committing (and applying through all the states) sequence #42 and then later committing #12 would be at best confusing and at worse perhaps produce different results when recreating the db (which, I think, would run #12 first).
So maybe the rule needs to be something about being larger than the largest currently applied patch?
schema/README.updates line 40
Quoted 10 lines
schema/README.updates new file +10
-0+ +<status> reflects the compatibility of various schema versions. It is +a literal string naming one of the statuses shown in `Update orders', +below. + +<status> depends on the nature of the specific database change, and +the behaviour and capabilities of the other code in the same revision +of osstest.git. But, so <status> does not depend on the state of the +database. Applying a schema update to a database does not change its +`status'.
"But, so ..." ? I think maybe s/But, s/S/ is what you meant? Or maybe there was a missing thought?
It's not stated outright, but AIUI the <status> of an update changes in a commit which either adds/edits a schema update, or which adds code which adds compatibility/requirements for a particular schema update. Is that right?
Quoted 9 lines
schema/README.updates new file +9
-0+In principle, each update can separately be in applied or not applied +in any one moment in time (in various databases), and simultaneously +have different statuses in different relevant versions of osstest.git. +So overall the possible states of an update in the whole world are the +cross product of (i) status in each relevant osstest revision, and +(ii) appliedness (boolean) in each relevant database instance. + + +Update orders
schema/README.updates line 60
Quoted 10 lines
schema/README.updates new file +10
-0+------------- + +There are four reasonable plans for schema changes: + + * Fully intercompatible: both old code and new code are each + compatible with both old schema and new schema. The code and + schema updates may be done in any order. + + Such a schema change always has status: + Harmless
What happens if some subsequent change (perhaps a long time later) causes the code to require the changes made by a "Harmless" schema update?
Would that be a bug in that later code for not coping with the old schema, or a bug in the commit adding it for not updating the header of the schema update (to "Needed", presumably) or is it not an issue because there is some point at which a schema update becomes part of the assumed baseline?
schema/README.updates line 69
Quoted 9 lines
schema/README.updates new file +9
-0+ + * Explicit conditional: first update the code to understand both + versions of the schema; then update the schema; then drop the + compatibility code. + + Such a schema change always has status: + Unfinished (or absent) in old code + Ready in intermediate code + Needed in the final code
So, a plausible sequence of commits to osstest.git might be:
1: Add schema/foo.update with initial status "Unfinished". 2a: Add code to partially implement compat with the new schema:
no status change
[2b,2c...] more compat or unrelated changes
3: Add final code to completely implement compat with the new schema:
status changed to "Ready" in that same commit
4a,b,c: Maybe other unrelated changes
5: Remove any piece code which provides support for the old schema:
status changes to "Needed"
6: Eventually remove remove other compat code.
I've broken down the addition/removal of compat code into stages to illustrate, that code might really all come/go in a single commit.
(I see now that there is a more comprehensive example further down the doc)
Quoted 22 lines
schema/README.updates new file +22
-0+ + * Code first: the new code works with either old or new schema, + but the old code cannot cope with the new schema. + + Such a schema change has status: + Unfinished (or absent) in old code + Ready in new code + + * Schema first: the new schema works with any code; but the old + schema does not work with new code. + + Such a schema change has status: + Preparatory in old code + Needed in the new code + + +Update order for Populate-then-rely +----------------------------------- + +This is for when we want to record new information and then later rely +on it. There are typically two schema changes: +
schema/README.updates line 101
Quoted 10 lines
schema/README.updates new file +10
-0+* To add the column(s). I will call this `add'. It is a `Schema + first' change, in the taxonomy above. + +* To add appropriate constraints, to prevent the new information being + left blank. I will call this `constraint'. This is a `Code first' + or `Explicit conditional' change in the taxonomy above. + +1. Commit: new schema update `add', status Preparatory. + +2. Commit: new schema update `constraint', status Unfinished.
At this point we want to wait for those commits to pass the push gate, before we can apply add', since applying add' should be done from a "properly acked version of osstest.git".
This is made pretty clear by the following commentary, for `Apply' but I wanted to check I'd got the placement of the wait correct.
Quoted 47 lines
schema/README.updates new file +47
-0+3. Apply: `add'. + +4. Optionally commit: code to read new column, but which tolerates + both complete absence of the column, and/or it containing NULL + (or whatever the DEFAULT value is). + +5. Commit: code to populate new column; changing `add' to status + Needed and `constraint' to status Ready. + +6. Optionally commit: code which read new column, but which tolerates + it containing NULL/DEFAULT. (`add' is already Needed.) + +7. If necessary commit: idempotent utility script to populate missing + data. (Alternatively, this can be done with DML statements in the + `constraint' schema update .sql file. This is better if it is + possible.) + +8. Wait for all executions of old code to finish. (This obviously + implies first getting a push of all the commits mentioned above.) + +8. If necessary, execute utility script to populate missing data. + +9. Apply: `constraint'. + +10. Optionally commit: code which relies on new column, and does not + necessarily tolerate NULL/DEFAULT; changing `constraint' to Needed. + + +`Commit' means committing somewhere public and probably pushing to +osstest.git#pretest, but not necessarily getting a push. (It +necessarily precedes any formal testing of the relevant changes on a +production instance.) + +`Apply' (and `execute utility script') should only be done using a +properly acked version of osstest.git. If verifying the sanity of the +schema change is nontrivial then ad-hoc tests may need to have been +run with a testing instance of the database. Using only a pushed +production version is a good idea to avoid the possibility that the +production database might contain changes which are not evident in +published code (or worse, which are different in future versions). + +Subject to those conditions, `Apply' means an administrator running +./mg-schema-update as osstest; if `wait for executions of old code to +finish is needed', this will usually involve passing an appropriate +`-o' option. + +
schema/README.updates line 159
Quoted 10 lines
schema/README.updates new file +10
-0+Statuses and rules for push and db update +----------------------------------------- + + Harmless + Preparatory + No restrictions + + Unfinished + (sql fragment entirely missing is equivalent to Unfinished) + Schema update: prevented
In the case of "entirely missing" "prevented" must really mean "there can't possibly be anything to do/prevent"?
Quoted 10 lines
schema/README.updates new file +10
-0+ Code push: unrestricted + + Ready + Schema update: need all live code to be Preparatory/Ready/Needed + Code push: unrestricted + + Needed + Schema update: need all live code to be Preparatory/Ready/Needed + Code push: depends on schema update +
schema/README.updates line 179
Quoted 10 lines
schema/README.updates new file +10
-0+ +"Code push: depends on schema update" is not currently implemented. +However, many (most?) such changes would cause the push gate itself to +fail. + +"Need all live code to be ..." means to look for the status of this +schema update in other running versions of osstest. An attempt at +this is provided in the form of the `-o' option to mg-schema-update. +It is the administrator's responsibility to select an appropriate +argument to `-o'.
Ian.
_______________________________________________
Xen-devel mailing list
[email protected]
http://lists.xen.org/xen-devel
Re: [OSSTEST PATCH 5/8] Schema: Support database schema updates
Ian Campbell writes ("Re: [OSSTEST PATCH 5/8] Schema: Support database schema updates"):
Quoted 6 lines · Ian Jackson
Quoted 2 lines
+<sequence> is a positive integer, which should be unique. Updates are +applied in order.
Don't these also need to be monotonically increasing over time/commits?
Quoted 7 lines
i.e. committing (and applying through all the states) sequence #42 and then later committing #12 would be at best confusing and at worse perhaps produce different results when recreating the db (which, I think, would run #12 first).
So maybe the rule needs to be something about being larger than the largest currently applied patch?
It does say that updates are applied in order. I will add and monotonically increasing' after unique'.
Quoted 4 lines
Quoted 4 lines
+<status> reflects the compatibility of various schema versions. It is
schema/README.updates new file +3
-0+a literal string naming one of the statuses shown in `Update orders', +below. +
Quoted 8 lines
schema/README.updates line 40
Quoted 5 lines
+<status> depends on the nature of the specific database change, and
schema/README.updates new file +4
-0+the behaviour and capabilities of the other code in the same revision +of osstest.git. But, so <status> does not depend on the state of the +database. Applying a schema update to a database does not change its +`status'."But, so ..." ? I think maybe s/But, s/S/ is what you meant? Or maybe there was a missing thought?
I reordered this, and the so' is spurious. It should just say But, <status> does not depend...'.
Quoted 4 lines
It's not stated outright, but AIUI the <status> of an update changes in a commit which either adds/edits a schema update, or which adds code which adds compatibility/requirements for a particular schema update. Is that right?
Yes. I think it should be clear from the rest of the discussion and I'm not sure that adding some more text here would help clarify things overall.
Quoted 10 lines
Quoted 2 lines
+ Such a schema change always has status:
+ HarmlessWhat happens if some subsequent change (perhaps a long time later) causes the code to require the changes made by a "Harmless" schema update?
Would that be a bug in that later code for not coping with the old schema, or a bug in the commit adding it for not updating the header of the schema update (to "Needed", presumably) or is it not an issue because there is some point at which a schema update becomes part of the assumed baseline?
If code starts to depend on the schema change, it should be changed to Needed when the code is changed. In practice this is not likely to be a problem because the update will have been applied a long time ago.
Quoted 22 lines
Quoted 8 lines
+ * Explicit conditional: first update the code to understand both + versions of the schema; then update the schema; then drop the + compatibility code.
+
+ Such a schema change always has status:
+ Unfinished (or absent) in old code
+ Ready in intermediate code
+ Needed in the final codeSo, a plausible sequence of commits to osstest.git might be:
1: Add schema/foo.update with initial status "Unfinished". 2a: Add code to partially implement compat with the new schema:
no status change
[2b,2c...] more compat or unrelated changes
3: Add final code to completely implement compat with the new schema:
status changed to "Ready" in that same commit
4a,b,c: Maybe other unrelated changes
5: Remove any piece code which provides support for the old schema:
status changes to "Needed"
6: Eventually remove remove other compat code.
Quoted 2 lines
I've broken down the addition/removal of compat code into stages to illustrate, that code might really all come/go in a single commit.
Yes.
Quoted 21 lines
Quoted 6 lines
schema/README.updates new file +6
-0+Update order for Populate-then-rely +----------------------------------- + +This is for when we want to record new information and then later rely +on it. There are typically two schema changes: +schema/README.updates line 101
Quoted 10 lines
schema/README.updates new file +10
-0+* To add the column(s). I will call this `add'. It is a `Schema + first' change, in the taxonomy above. + +* To add appropriate constraints, to prevent the new information being + left blank. I will call this `constraint'. This is a `Code first' + or `Explicit conditional' change in the taxonomy above. + +1. Commit: new schema update `add', status Preparatory. + +2. Commit: new schema update `constraint', status Unfinished.At this point we want to wait for those commits to pass the push gate, before we can apply
add', since applyingadd' should be done from a "properly acked version of osstest.git".
Quoted 2 lines
This is made pretty clear by the following commentary, for `Apply' but I wanted to check I'd got the placement of the wait correct.
Yes.
Quoted 5 lines
Quoted 5 lines
schema/README.updates new file +5
-0+Statuses and rules for push and db update +----------------------------------------- + + Harmless + Preparatory
Quoted 8 lines
Quoted 5 lines
+ No restrictions
+
+ Unfinished
+ (sql fragment entirely missing is equivalent to Unfinished) + Schema update: preventedIn the case of "entirely missing" "prevented" must really mean "there can't possibly be anything to do/prevent"?
Well, if you say
./mg-schema-update apply this-update-does-not-exist
it will bomb out.
And
./mg-schema-update apply-all
will not invent imaginary schema changes out of thin air so that it can apply them.
So, application of nonexistent schema changes is indeed prevented by their nonexistence.
Ian.
Re: [OSSTEST PATCH 5/8] Schema: Support database schema updates
Ian Jackson writes ("Re: [OSSTEST PATCH 5/8] Schema: Support database schema updates"):
Quoted 2 lines
It does say that updates are applied in order. I will add
and monotonically increasing' afterunique'. [etc etc]
Here is v3 of this patch. I'll refrain from reposting the whole series.
Ian.
Quoted 1 line
From
a7fe7187f6237043f8d6aedeb714409b606af8e0Mon Sep 17 00:00:00 2001
From: Ian Jackson <[email protected]>
Date: Thu, 10 Dec 2015 13:26:00 +0000
Subject: [OSSTEST PATCH 5/8] Schema: Support database schema updates
See schema/README.schema, introduced in this patch, for the design.
---
v3: Fix spurious message from ./mg-schema-updates apply.
Fix grammar error in README.updates.
v2: Slight increase schema update name length format.
Docs fixes:
Change erroneous three' to four'.
Change state' to status' throghout.
Explain scope of <status>.
Sort out (and renumber) `Update order for Populate-then-rely'. Sort out "Statuses" explanations.
Encourage use of DML update, rather than ad-hoc scripts,
for populating new columns.
--- Osstest/Executive.pm | 82 +++++++++++++++ mg-schema-create | 20 ++++ mg-schema-test-database | 6 +- mg-schema-update | 255 +++++++++++++++++++++++++++++++++++++++++++++ schema/README.updates | 179 +++++++++++++++++++++++++++++++ schema/schema-updates.sql | 6 ++ 6 files changed, 547 insertions(+), 1 deletion(-) create mode 100755 mg-schema-update create mode 100644 schema/README.updates create mode 100644 schema/schema-updates.sql
Osstest/Executive.pm +82 -0
@@ -56,6 +56,7 @@ BEGIN { resource_check_allocated resource_shared_mark_ready duration_estimator db_pg_dsn opendb opendb_state + db_schema_updates_applied db_schema_updates_intree ); %EXPORT_TAGS = ( colours => [qw($green $red $yellow $purple $blue)] );
@@ -128,6 +129,87 @@ sub grabrepolock_reexec { } } +sub db_schema_updates_applied (;$) { + my ($cond) = @_; + my $r; + $cond //= '1=1'; + eval { + local $dbh_tests->{PrintError} = 0; + $r = $dbh_tests->selectall_arrayref(<<END); + SELECT updatename, applytime + FROM schema_updates WHERE $cond +END + }; + if ($@) { + die unless + $dbh_tests->err()==7 && # DBD::Pg(3pm) + $dbh_tests->state() eq '42P01'; + # http://www.postgresql.org/docs/current/static/errcodes-appendix.html + $r = [ ]; + } + my @r; + foreach (@$r) { + push @r, { Name => $_->[0], Applied => $_->[1] }; + } + return \@r; +} + +sub db_schema_updates_intree (;$) { + my ($incommit) = @_; + # ->[]{Name} + # ->[]{Seq} + # ->[]{State} + + my @results; + + my @files; + if (!$incommit) { + @files = <schema/*.sql>; + } else { + local $/ = "\0"; + open GLF, "-|", qw(git ls-tree -z), $incommit, "schema/" or die $!; + while (<GLF>) { + chomp; + next unless s/^\d+ blob \w+\t//; + push @files, $_; + } + $!=0; $?=0; close GLF or die "$! $? ($incommit)"; + } + + FILE: foreach my $f (@files) { + $f =~ m/\.sql$/ or next; + $f =~ m#/([a-z][0-9a-z-]+)\.sql$# or die "badly named .sql file $f\n"; + my $name = $1; + next if $name eq 'initial'; + if ($incommit) { + open SQLF, "-|", qw(git cat-file blob), "$incommit:$f" or die $!; + } else { + open SQLF, "<", $f or die "$f $!"; + } + while (<SQLF>) { + chomp; + my $origl = $_; + next unless s/^\s*--\s*##OSSTEST##\s+//; + m/^0*([1-9]\d*)\s+(Harmless|Preparatory|Unfinished|Ready|Needed)\b/ + or die "$origl ?"; + push @results, { + Name => $name, + Seq => $1+0, + State => $2, + }; + next FILE; + } + $!=0; $?=0; close SQLF; die "$f \`$name' no token ($! $?)"; + } + + @results = sort { + $a->{Seq} <=> $b->{Seq} || + die "$a->{Name} $a->{Seq} == $b->{Name} $b->{Seq}" + } @results; + + return \@results; +} + #---------- database access ----------# sub opendb_state () {
mg-schema-create +20 -0
@@ -30,6 +30,9 @@ # Options: # # -q don't print progress messages +# --no-updates apply no schema updates +# --stop-before --stop-after only apply some schema updates - +# see mg-schema-update set -e set -o posix
@@ -38,6 +41,8 @@ set -o pipefail progress () { printf "%s\n" "$*"; } progress=progress quietopt='' +do_updates=true +updates=() while [ $# != 0 ]; do arg=$1; shift
@@ -46,16 +51,31 @@ while [ $# != 0 ]; do progress=: quietopt=-q ;; + --stop-before|--stop-after) + updates+=("$arg" "$1"); shift + ;; + --stop-before=*|--stop-after=*) + updates+=("$arg"); shift + ;; + --no-updates) + do_updates=false + ;; *) echo >&2 "bad usage ($arg)"; exit 127 ;; esac done +export OSSTEST_DB_USEREAL_IGNORETEST='.*' + . ./cri-getconfig $progress "Populating database..." $(get_psql_cmd) $quietopt -f schema/initial.sql +if $do_updates; then + ./mg-schema-update $quietopt apply-all "${updates[@]}" +fi + $progress "Database set up."
mg-schema-test-database +5 -1
@@ -344,6 +344,8 @@ END # Keep a copy as it came from dump, for comparison cp $t.schema $t.schema.orig + wantupdates=$(./mg-schema-update list-applied) + # http://www.postgresql.org/message-id/[email protected] perl -i~ -pe ' s/^/--/ if
@@ -391,7 +393,9 @@ END psql_do <<END CREATE DATABASE $dbname; END - withtest ./mg-schema-create -q + withtest ./mg-schema-create -q --no-updates + + withtest ./mg-schema-update -q apply $wantupdates printf ".\n"
mg-schema-update new file +255 -0
255 lines not on this page · raw message
schema/README.updates new file +179 -0
179 lines not on this page · raw message
schema/schema-updates.sql new file +6 -0
@@ -0,0 +1,6 @@ +-- ##OSSTEST## 001 Harmless + +CREATE TABLE schema_updates ( + updatename TEXT PRIMARY KEY, + applytime integer NOT NULL +);
Signature · 1 line
1.7.10.4
Re: [OSSTEST PATCH 5/8] Schema: Support database schema updates
Quoted 8 lines · Ian Jackson
Ian Jackson writes ("Re: [OSSTEST PATCH 5/8] Schema: Support database schema updates"):
Quoted 2 lines
It does say that updates are applied in order. I will add
and monotonically increasing' afterunique'. [etc etc]Here is v3 of this patch. I'll refrain from reposting the whole series.
Quoted 8 lines
Ian.
From
a7fe7187f6237043f8d6aedeb714409b606af8e0Mon Sep 17 00:00:00 2001
From: Ian Jackson <[email protected]>
Date: Thu, 10 Dec 2015 13:26:00 +0000
Subject: [OSSTEST PATCH 5/8] Schema: Support database schema updatesSee schema/README.schema, introduced in this patch, for the design.
The README looks good now, thanks.
Code comments....
[...]
Quoted 18 lines
mg-schema-create +0
-0@@ -46,16 +51,31 @@ while [ $# != 0 ]; doprogress=:
quietopt=-q
;;
+ --stop-before|--stop-after)
+ updates+=("$arg" "$1"); shiftmg-schema-create +7
-0+ ;; + --stop-before=*|--stop-after=*) + updates+=("$arg"); shift + ;; + --no-updates) + do_updates=false + ;;
Quoted 7 lines
*)
echo >&2 "bad usage ($arg)"; exit 127
;;
esac
done
+export OSSTEST_DB_USEREAL_IGNORETEST='.*'
Why remove the safety catch in this context?
... and that seems to be my only comment.
Ian.
_______________________________________________
Xen-devel mailing list
[email protected]
http://lists.xen.org/xen-devel
Re: [OSSTEST PATCH 5/8] Schema: Support database schema updates
Ian Campbell writes ("Re: [OSSTEST PATCH 5/8] Schema: Support database schema updates"):
Quoted 4 lines · Ian Jackson
Quoted 1 line
See schema/README.schema, introduced in this patch, for the design.
The README looks good now, thanks.
Thanks.
Quoted 3 lines
Code comments....
Quoted 1 line
mg-schema-create +0
-0
...
Quoted 3 lines
Quoted 1 line
+export OSSTEST_DB_USEREAL_IGNORETEST='.*'
Why remove the safety catch in this context?
The safety catch breaks when run on an empty schema, because there is no tasks' table. Setting this pattern to .*' triggers a special case which avoids even trying to see what test DBs exist.
And furthermore the safety catch is not needed because if we are mistakenly operating on an existing database (test or real) we bomb out as previously discussed.
I can put this in a comment if you like.
Ian.
Re: [OSSTEST PATCH 5/8] Schema: Support database schema updates
Quoted 17 lines · Ian Jackson
Ian Campbell writes ("Re: [OSSTEST PATCH 5/8] Schema: Support database schema updates"):
Quoted 4 lines · Ian Jackson
Quoted 1 line
See schema/README.schema, introduced in this patch, for the design.
The README looks good now, thanks.
Thanks.
Quoted 3 lines
Code comments....
Quoted 1 line
mg-schema-create +0
-0...
Quoted 3 lines
Quoted 1 line
+export OSSTEST_DB_USEREAL_IGNORETEST='.*'
Why remove the safety catch in this context?
Quoted 7 lines
The safety catch breaks when run on an empty schema, because there is no
tasks' table. Setting this pattern to.*' triggers a special case which avoids even trying to see what test DBs exist.And furthermore the safety catch is not needed because if we are mistakenly operating on an existing database (test or real) we bomb out as previously discussed.
Thanks for the explanation.
Quoted 1 line
I can put this in a comment if you like.
I suppose a comment next to any such override is a pretty good policy to have.
With that: Acked-by: Ian Campbell <[email protected]>
Ian.
_______________________________________________
Xen-devel mailing list
[email protected]
http://lists.xen.org/xen-devel
Re: [OSSTEST PATCH 5/8] Schema: Support database schema updates
Ian Campbell writes ("Re: [OSSTEST PATCH 5/8] Schema: Support database schema updates"):
Quoted 5 lines · Ian Jackson
Quoted 1 line
I can put this in a comment if you like.
I suppose a comment next to any such override is a pretty good policy to have.
OK. See below; I have folded each hunk into the appropriate patch.
Quoted 1 line
With that: Acked-by: Ian Campbell <[email protected]>
Thanks,
Ian.
mg-schema-create +8 -0
@@ -67,9 +67,17 @@ while [ $# != 0 ]; do done export OSSTEST_DB_USEREAL_IGNORETEST='.*' +# Completely disable this safety catch, because it otherwise breaks +# when run on an empty schema (since there is no `tasks' table). +# +# It is not needed because if we are mistakenly operating on an +# existing database (test or real) we will bomb out because the first +# thing in `initial.sql' is to create the already-existing `flights' +# table ... . ./cri-getconfig +# ... Unless some update has been applied which removed `flights': updates_applied=$(./mg-schema-update list-applied) if [ "x$updates_applied" != x ]; then ./mg-schema-update show
Re: [OSSTEST PATCH 5/8] Schema: Support database schema updates
Quoted 10 lines · Ian Jackson
Ian Campbell writes ("Re: [OSSTEST PATCH 5/8] Schema: Support database schema updates"):
Quoted 6 lines · Ian Jackson
Quoted 1 line
I can put this in a comment if you like.
I suppose a comment next to any such override is a pretty good policy to
have.OK. See below; I have folded each hunk into the appropriate patch.
Looks good, thanks.
Quoted 21 lines
Quoted 2 lines
With that: Acked-by: Ian Campbell <[email protected]>
Thanks,
Ian.mg-schema-create +0
-0@@ -67,9 +67,17 @@ while [ $# != 0 ]; dodone
export OSSTEST_DB_USEREAL_IGNORETEST='.*'mg-schema-create +7
-0+# Completely disable this safety catch, because it otherwise breaks +# when run on an empty schema (since there is no `tasks' table). +# +# It is not needed because if we are mistakenly operating on an +# existing database (test or real) we will bomb out because the first +# thing in `initial.sql' is to create the already-existing `flights' +# table ...
Quoted 7 lines
. ./cri-getconfig
+# ... Unless some update has been applied which removed `flights':
updates_applied=$(./mg-schema-update list-applied)
if [ "x$updates_applied" != x ]; then ./mg-schema-update show
_______________________________________________
Xen-devel mailing list
[email protected]
http://lists.xen.org/xen-devel
Re: [OSSTEST PATCH 5/8] Schema: Support database schema updates
In reply to Ian JacksonQuoted 16 lines · Ian Jackson
Ian Campbell writes ("Re: [OSSTEST PATCH 5/8] Schema: Support database schema updates"):
Quoted 14 lines · Ian Jackson
Quoted 3 lines
+<sequence> is a positive integer, which should be unique. Updates are
+applied in order.Don't these also need to be monotonically increasing over time/commits?
i.e. committing (and applying through all the states) sequence #42 and then
later committing #12 would be at best confusing and at worse perhaps produce different results when recreating the db (which, I think, would run
#12 first).
Quoted 5 lines
Quoted 3 lines
So maybe the rule needs to be something about being larger than the largest
currently applied patch?It does say that updates are applied in order.
Right I was considering an osstest repo with 01 and 03 in it, which is applied and all up to date, but then someone adds 02 and applies it (therefore after 03).
Quoted 10 lines
Quoted 6 lines
It's not stated outright, but AIUI the <status> of an update changes in a
commit which either adds/edits a schema update, or which adds code which
adds compatibility/requirements for a particular schema update. Is that right?Yes. I think it should be clear from the rest of the discussion and I'm not sure that adding some more text here would help clarify things overall.
I was just checking that I had groked it correctly, no need to change anything.
Quoted 19 lines
Quoted 6 lines
Quoted 6 lines
schema/README.updates new file +6
-0+Statuses and rules for push and db update +----------------------------------------- + + Harmless + Preparatory + No restrictionsQuoted 8 lines
Quoted 4 lines
+
+ Unfinished
+ (sql fragment entirely missing is equivalent to Unfinished) + Schema update: preventedIn the case of "entirely missing" "prevented" must really mean "there can't
possibly be anything to do/prevent"?Well, if you say
./mg-schema-update apply this-update-does-not-exist it will bomb out.
Quoted 7 lines
And
./mg-schema-update apply-all
will not invent imaginary schema changes out of thin air so that it can apply them.So, application of nonexistent schema changes is indeed prevented by their nonexistence.
Right, I was just wanting to check that you didn't have some mad scheme in mind for knowing about things which don't exist.
It occurs to me now that while "update-foo" might not exist in the osstest.git where ./mg-schema-update is being run, it might exist in another one and therefore have been applied and be present in the database.
Ian.
_______________________________________________
Xen-devel mailing list
[email protected]
http://lists.xen.org/xen-devel
Re: [OSSTEST PATCH 5/8] Schema: Support database schema updates
Ian Campbell writes ("Re: [OSSTEST PATCH 5/8] Schema: Support database schema updates"):
Quoted 6 lines · Ian Jackson
Quoted 1 line
It does say that updates are applied in order.
Right I was considering an osstest repo with 01 and 03 in it, which is applied and all up to date, but then someone adds 02 and applies it (therefore after 03).
In think in principle this is OK if it is OK, IYSWIM.
If not then perhaps we need a dependency system but let's not go there :-).
Quoted 5 lines
Quoted 2 lines
So, application of nonexistent schema changes is indeed prevented by their nonexistence.
Right, I was just wanting to check that you didn't have some mad scheme in mind for knowing about things which don't exist.
:-).
Quoted 3 lines
It occurs to me now that while "update-foo" might not exist in the osstest.git where ./mg-schema-update is being run, it might exist in another one and therefore have been applied and be present in the database.
Indeed. ./mg-schema-update should display such things correctly. Let me try it and see...
(osstest)mariner:testing.git> rm schema/schema-updates.sql
(osstest)mariner:testing.git> OSSTEST_CONFIG=/u/iwj/.xen-osstest/config:local-config.test-database_iwj ./mg-schema-update -oHEAD show
Name Worktree HEAD DB update schema-updates - 1 Harml 2015-12-11 15:06:45 Z drop-old-resource-log 2 Harml 2 Harml 2015-12-11 15:06:45 Z (osstest)mariner:testing.git> OSSTEST_CONFIG=/u/iwj/.xen-osstest/config:local-config.test-database_iwj ./mg-schema-update show Name Worktree DB update schema-updates - 2015-12-11 15:06:45 Z drop-old-resource-log 2 Harml 2015-12-11 15:06:45 Z
(osstest)mariner:testing.git>
... which is as I would hope.
Ian.
PATCH v2 6/8 Schema: Check that schema creation and update runs as the right user
In reply to Ian Jackson--- Osstest/Executive.pm | 1 + README | 5 +++++ mg-schema-create | 4 +++- mg-schema-test-database | 1 + mg-schema-update | 16 ++++++++++++++++ 5 files changed, 26 insertions(+), 1 deletion(-)
Osstest/Executive.pm +1 -0
@@ -105,6 +105,7 @@ augmentconfigdefaults( QueuePlanUpdateInterval => 300, # seconds Repos => "$ENV{'HOME'}/repos", BisectionRevisonGraphSize => '600x300', + ExecutiveDbOwningRoleRegexp => 'osstest', ); augmentconfigdefaults(
README +5 -0
@@ -571,6 +571,11 @@ ExecutiveDbname_<DB> PostgreSQL dbname string for the database <DB>. Default is to use ExecutiveDbnamePat. +ExecutiveDbOwningRoleRegexp + Regexp which is supposed to match the database user used for schema + changes - because, that role will end up owning the database objects. + Defaults to `osstest'. + Adhoc/Custom Flights ====================
mg-schema-create +3 -1
@@ -25,7 +25,7 @@ # do CREATE DATABASE.) # # When setting up a production database, mg-schema-create should -# be run *AS THE ROLE USER* who is to own all the resources. +# be run as the role user who is to own all the resources. # # Options: #
@@ -70,6 +70,8 @@ export OSSTEST_DB_USEREAL_IGNORETEST='.*' . ./cri-getconfig +./mg-schema-update $quietopt check-user + $progress "Populating database..." $(get_psql_cmd) $quietopt -f schema/initial.sql
mg-schema-test-database +1 -0
@@ -335,6 +335,7 @@ OwnerDaemonHost $ctrlhost QueueDaemonHost $ctrlhost OwnerDaemonPort ${ctrlports%,*} QueueDaemonPort ${ctrlports#*,} +ExecutiveDbOwningRoleRegexp .* END mv -f $tcfg.tmp $tcfg
mg-schema-update +16 -0
@@ -22,6 +22,7 @@ # ./mg-schema-update [<options>] apply [<updatename>...] # ./mg-schema-update [<options>] show # ./mg-schema-update [<options>] apply-all +# ./mg-schema-update [<options>] check-user # # Usual rune for applying updates: #
@@ -119,6 +120,13 @@ sub getstate () { @state = sort { $a->{Sortkey} <=> $b->{Sortkey} } values %state; } +sub check_user () { + my $user = $dbh_tests->{pg_user}; + my $re = $c{ExecutiveDbOwningRoleRegexp}; + return if $user =~ m/^$re$/o; + die "running as wrong user \`$user', expected to match \`$re'\n"; +} + sub cmd_list_applied () { die if @ARGV; getstate();
@@ -170,6 +178,8 @@ sub applyone ($) { die "Will not apply $v->{Name}.sql: $v->{Msg}\n" unless want_apply($v); + check_user(); + my $fn = $v->{File}; db_retry($dbh_tests, \@all_lock_tables, sub {
@@ -242,6 +252,12 @@ sub cmd_apply_all () { print "Appropriate updates applied.\n" unless $quiet; } +sub cmd_check_user () { + die "too many arguments\n" if @ARGV>1; + $c{ExecutiveDbOwningRoleRegexp} = shift @ARGV if @ARGV; + check_user(); +} + GetOptions('f|force+' => \$force, 'q+' => \$quiet, 'o|oldest=s' => \$there);
Signature · 1 line
1.7.10.4
PATCH v2 7/8 Schema: drop old resource_log table
In reply to Ian Jackson--- schema/drop-old-resource-log.sql | 8 ++++++++ 1 file changed, 8 insertions(+) create mode 100644 schema/drop-old-resource-log.sql
schema/drop-old-resource-log.sql new file +8 -0
@@ -0,0 +1,8 @@ +-- ##OSSTEST## 002 Harmless +-- +-- This table and associated constraints and indices is from a previous +-- aborted attempt at resource logging. Nothing actually reads or +-- writes it. + +DROP TABLE resource_log; +DROP SEQUENCE resource_log_evid_seq;
Signature · 1 line
1.7.10.4
PATCH v2 8/8 Schema: When creating, check that no updates are applied
In reply to Ian JacksonIf you try to run mg-schema-create on an existing instance it bombs out right at the beginning because it tries to create the `flights' table, which already exists.
But in the future the `flights' table might be removed in an update, which would remove this safety catch. Then running the create might partially succeed, leaving debris a production instance.
Detect this situation by looking for applied schema updates, and bombing out if there are any.
--- mg-schema-create | 7 +++++++ 1 file changed, 7 insertions(+)
mg-schema-create +7 -0
@@ -70,6 +70,13 @@ export OSSTEST_DB_USEREAL_IGNORETEST='.*' . ./cri-getconfig +updates_applied=$(./mg-schema-update list-applied) +if [ "x$updates_applied" != x ]; then + ./mg-schema-update show + echo >&2 'Database already exists with applied updates!' + exit 127 +fi + ./mg-schema-update $quietopt check-user $progress "Populating database..."
Signature · 1 line
1.7.10.4