on 570cf4a help sign in
.github/workflows/lint.yaml+3−6
since splitsnapshots
unifiedsplit
@@ -3,9 +3,6 @@ name: Lint
3on:
3on:
4 push:
4 push:
5 branches: [ main ]
5 branches: [ main ]
6− pull_request:
7− branches:
8− - main
9
6
10env:
7env:
11 CARGO_TERM_COLOR: always
8 CARGO_TERM_COLOR: always
@@ -15,7 +12,7 @@ jobs:
15 runs-on: ubuntu-latest
12 runs-on: ubuntu-latest
16 steps:
13 steps:
17 - name: Checkout
14 - name: Checkout
18− uses: actions/checkout@v4
15+ uses: actions/checkout@v2
19 - name: Select Rust toolchain with Clippy
16 - name: Select Rust toolchain with Clippy
20 uses: actions-rs/toolchain@v1
17 uses: actions-rs/toolchain@v1
21 with:
18 with:
@@ -23,6 +20,6 @@ jobs:
23 components: clippy
20 components: clippy
24 override: true
21 override: true
25 - name: Use cache for Rust dependencies
22 - name: Use cache for Rust dependencies
26− uses: Swatinem/rust-cache@v2
23+ uses: Swatinem/rust-cache@v1
27 - name: Lint using Clippy
24 - name: Lint using Clippy
28− run: cargo clippy
25+ run: cargo clippy
.github/workflows/publish-crate.yamldeleted−20
@@ -1,20 +0,0 @@
1−name: Publish crate
2−
3−on: workflow_dispatch
4−
5−jobs:
6− publish-crate:
7− runs-on: ubuntu-latest
8− steps:
9− - name: Checkout
10− uses: actions/checkout@v2
11− - name: Select Rust toolchain
12− uses: actions-rs/toolchain@v1
13− with:
14− toolchain: stable
15− - name: Publish to crates.io
16− uses: actions-rs/cargo@v1
17− with:
18− command: publish
19− env:
20− CARGO_REGISTRY_TOKEN: ${{ secrets.CRATES_IO_TOKEN }}
.github/workflows/publish-docker.yamldeleted−25
@@ -1,25 +0,0 @@
1−name: Publish Docker image
2−
3−on:
4− workflow_dispatch:
5− inputs:
6− version:
7− description: "Version (without 'v' prefix)"
8− required: true
9− type: string
10−
11−jobs:
12− publish-docker:
13− runs-on: ubuntu-latest
14− steps:
15− - name: Checkout
16− uses: actions/checkout@v2
17− - name: Log in to Docker
18− env:
19− DOCKER_PASSWORD: ${{ secrets.DOCKER_ACCESS_TOKEN }}
20− run: |
21− docker login -u ${{ secrets.DOCKER_USER }} -p $DOCKER_PASSWORD
22− - name: Build Docker image
23− run: docker build . --tag ${{ secrets.DOCKER_USER }}/reshape:${{ inputs.version }} --tag ${{ secrets.DOCKER_USER }}/reshape:latest
24− - name: Push Docker image
25− run: docker push --all-tags ${{ secrets.DOCKER_USER }}/reshape
.github/workflows/release.yaml+3−21
@@ -47,7 +47,6 @@ jobs:
47 uses: actions-rs/toolchain@v1
47 uses: actions-rs/toolchain@v1
48 with:
48 with:
49 toolchain: stable
49 toolchain: stable
50− override: true
51 target: ${{ matrix.target }}
50 target: ${{ matrix.target }}
52 - name: Use cache for Rust dependencies
51 - name: Use cache for Rust dependencies
53 uses: Swatinem/rust-cache@v1
52 uses: Swatinem/rust-cache@v1
@@ -55,10 +54,10 @@ jobs:
55 uses: actions-rs/cargo@v1
54 uses: actions-rs/cargo@v1
56 with:
55 with:
57 command: build
56 command: build
58− args: --release --target ${{ matrix.target }}
57+ args: --release
59 use-cross: ${{ matrix.use-cross }}
58 use-cross: ${{ matrix.use-cross }}
60 - name: Rename binary
59 - name: Rename binary
61− run: mv target/${{ matrix.target }}/release/reshape ./reshape-${{ matrix.file-name }}
60+ run: mv target/release/reshape ./reshape-${{ matrix.file-name }}
62 - name: Upload binary to release
61 - name: Upload binary to release
63 env:
62 env:
64 GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
63 GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
@@ -79,21 +78,4 @@ jobs:
79 # The shell expansion used below will remove everything up to the version number, leaving 0.0.1
78 # The shell expansion used below will remove everything up to the version number, leaving 0.0.1
80 run: docker build . --tag ${{ secrets.DOCKER_USER }}/reshape:${GITHUB_REF##*/v} --tag ${{ secrets.DOCKER_USER }}/reshape:latest
79 run: docker build . --tag ${{ secrets.DOCKER_USER }}/reshape:${GITHUB_REF##*/v} --tag ${{ secrets.DOCKER_USER }}/reshape:latest
81 - name: Push Docker image
80 - name: Push Docker image
82− run: docker push --all-tags ${{ secrets.DOCKER_USER }}/reshape
81+ run: docker push --all-tags ${{ secrets.DOCKER_USER }}/reshape
83−
84− publish-crate:
85− runs-on: ubuntu-latest
86− needs: ["build-binary", "publish-docker"]
87− steps:
88− - name: Checkout
89− uses: actions/checkout@v2
90− - name: Select Rust toolchain
91− uses: actions-rs/toolchain@v1
92− with:
93− toolchain: stable
94− - name: Publish to crates.io
95− uses: actions-rs/cargo@v1
96− with:
97− command: publish
98− env:
99− CARGO_REGISTRY_TOKEN: ${{ secrets.CRATES_IO_TOKEN }}
.github/workflows/test.yaml−3
@@ -3,9 +3,6 @@ name: Tests
3on:
3on:
4 push:
4 push:
5 branches: [ main ]
5 branches: [ main ]
6− pull_request:
7− branches:
8− - main
9
6
10env:
7env:
11 CARGO_TERM_COLOR: always
8 CARGO_TERM_COLOR: always
Cargo.toml+4−14
@@ -1,26 +1,16 @@
1[package]
1[package]
2name = "reshape"
2name = "reshape"
3−version = "0.7.0"
3+version = "0.1.0"
4−description = "An easy-to-use, zero-downtime schema migration tool for Postgres"
5−homepage = "https://github.com/fabianlindfors/reshape"
6−documentation = "https://github.com/fabianlindfors/reshape"
7−repository = "https://github.com/fabianlindfors/reshape"
8−license = "MIT"
9−keywords = ["postgres", "migrations"]
10edition = "2021"
4edition = "2021"
11−authors = ["Fabian Lindfors"]
12−rust-version = "1.70"
13
5
14[dependencies]
6[dependencies]
15postgres = { version = "0.19.2", features = ["with-serde_json-1"] }
7postgres = { version = "0.19.2", features = ["with-serde_json-1"] }
16serde = { version = "1.0", features = ["derive"] }
8serde = { version = "1.0", features = ["derive"] }
17serde_json = "1.0"
9serde_json = "1.0"
18typetag = "0.1.7"
10typetag = "0.1.7"
19−anyhow = { version = "1.0.44", features = ["backtrace"] }
11+anyhow = "1.0.44"
20−clap = { version = "3.1.9", features = ["derive"] }
12+clap = { version = "3.0.0-rc.8", features = ["derive"] }
21toml = "0.5"
13toml = "0.5"
22version = "3.0.0"
14version = "3.0.0"
23colored = "2"
15colored = "2"
24−rand = "0.8"
16+bimap = "0.6.1"
25−dotenv = "0.15.0"
26−lexical-sort = "0.3.1"
Dockerfile+1−1
@@ -1,4 +1,4 @@
1−FROM rust:1.70.0 AS builder
1+FROM rust:1.57.0 AS builder
2WORKDIR /usr/src/reshape
2WORKDIR /usr/src/reshape
3COPY . .
3COPY . .
4RUN cargo build --release
4RUN cargo build --release
LICENSE.mddeleted−21
@@ -1,21 +0,0 @@
1−MIT License
2−
3−Copyright (c) 2022 Fabian Lindfors
4−
5−Permission is hereby granted, free of charge, to any person obtaining a copy
6−of this software and associated documentation files (the "Software"), to deal
7−in the Software without restriction, including without limitation the rights
8−to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9−copies of the Software, and to permit persons to whom the Software is
10−furnished to do so, subject to the following conditions:
11−
12−The above copyright notice and this permission notice shall be included in all
13−copies or substantial portions of the Software.
14−
15−THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16−IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17−FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18−AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19−LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20−OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21−SOFTWARE.
README.md+89−436
@@ -1,57 +1,35 @@
1# Reshape
1# Reshape
2
2
3−[![Test status badge](https://github.com/fabianlindfors/Reshape/actions/workflows/test.yaml/badge.svg)](https://github.com/fabianlindfors/reshape/actions/workflows/test.yaml) [![Latest release](https://shields.io/github/v/release/fabianlindfors/reshape?display_name=tag&sort=semver&color=blue)](https://github.com/fabianlindfors/reshape/releases)
3+[![Test status badge](https://github.com/fabianlindfors/Reshape/actions/workflows/test.yaml/badge.svg)](https://github.com/fabianlindfors/Reshape/actions/workflows/test.yaml)
4
4
5−> Also check out [ReshapeDB](https://reshapedb.com), a new database built from the ground up to make zero-downtime schema and data migrations as simple and safe as possible. If you'd like to chat about it, please [reach out](contact@reshapedb.com)!
5+Reshape is an easy-to-use, zero-downtime schema migration tool for Postgres. It automatically handles complex migrations that would normally require downtime or manual multi-step changes. During a migration, Reshape ensures both the old and new schema are available at the same time, allowing you to gradually roll out your application.
6
6
7−Reshape is an easy-to-use, zero-downtime schema migration tool for Postgres. It automatically handles complex migrations that would normally require downtime or manual multi-step changes. During a migration, Reshape ensures both the old and new schema are available at the same time, allowing you to gradually roll out your application. It will also perform all changes without excessive locking, avoiding downtime caused by blocking other queries. For a more thorough introduction to Reshape, check out the [introductory blog post](https://fabianlindfors.se/blog/schema-migrations-in-postgres-using-reshape/).
7+*Note: Reshape is **experimental** and should not be used in production. It can (and probably will) destroy your data and break your application.*
8
8
9−Designed for Postgres 12 and later.
10−
11−- [How it works](#how-it-works)
12- [Getting started](#getting-started)
9- [Getting started](#getting-started)
13− - [Installation](#installation)
10+ - [Installation](#installation)
14− - [Creating your first migration](#creating-your-first-migration)
11+ - [Creating your first migration](#creating-your-first-migration)
15− - [Preparing your application](#preparing-your-application)
12+ - [Preparing your application](#preparing-your-application)
16− - [Running your migration](#running-your-migration)
13+ - [Running your migration](#running-your-migration)
17− - [Using during development](#using-during-development)
18- [Writing migrations](#writing-migrations)
14- [Writing migrations](#writing-migrations)
19− - [Basics](#basics)
15+ - [Basics](#basics)
20− - [Tables](#tables)
16+ - [Tables](#tables)
21− - [Create table](#create-table)
17+ - [Create table](#create-table)
22− - [Rename table](#rename-table)
18+ - [Rename table](#rename-table)
23− - [Remove table](#remove-table)
19+ - [Remove table](#remove-table)
24− - [Add foreign key](#add-foreign-key)
25− - [Remove foreign key](#remove-foreign-key)
26− - [Columns](#columns)
20+ - [Columns](#columns)
27− - [Add column](#add-column)
21+ - [Add column](#add-column)
28− - [Alter column](#alter-column)
22+ - [Alter column](#alter-column)
29− - [Remove column](#remove-column)
23+ - [Remove column](#remove-column)
30− - [Indices](#indices)
24+ - [Indices](#indices)
31− - [Add index](#add-index)
25+ - [Add index](#add-index)
32− - [Remove index](#remove-index)
33− - [Enums](#enums)
34− - [Create enum](#create-enum)
35− - [Remove enum](#remove-enum)
36− - [Custom](#custom)
37− - [Complex changes across tables](#complex-changes-across-tables)
38- [Commands and options](#commands-and-options)
26- [Commands and options](#commands-and-options)
39− - [`reshape migration start`](#reshape-migration-start)
27+ - [`reshape migrate`](#reshape-migrate)
40− - [`reshape migration complete`](#reshape-migration-complete)
28+ - [`reshape complete`](#reshape-complete)
41− - [`reshape migration abort`](#reshape-migration-abort)
29+ - [`reshape abort`](#reshape-abort)
42− - [`reshape schema-query`](#reshape-schema-query)
30+ - [`reshape generate-schema-query`](#reshape-generate-schema-query)
43− - [Connection options](#connection-options)
31+ - [Connection options](#connection-options)
44−- [License](#license)
45−
46−## How it works
32+- [How it works](#how-it-works)
47−
48−Reshape works by creating views that encapsulate the underlying tables, which your application will interact with. During a migration, Reshape will automatically create a new set of views and set up triggers to translate inserts and updates between the old and new schema. This means that every deployment is a three-phase process:
49−
50−1. **Start migration** (`reshape migration start`): Sets up views and triggers to ensure both the new and old schema are usable at the same time.
51−2. **Roll out application**: Your application can be gradually rolled out without downtime. The existing deployment will continue using the old schema whilst the new deployment uses the new schema.
52−3. **Complete migration** (`reshape migration complete`): Removes the old schema and any intermediate data and triggers.
53−
54−If the application deployment fails, you should run `reshape migration abort` which will roll back any changes made by `reshape migration start` without losing data.
55
33
56## Getting started
34## Getting started
57
35
@@ -61,33 +39,24 @@ If the application deployment fails, you should run `reshape migration abort` wh
61
39
62Binaries are available for macOS and Linux under [Releases](https://github.com/fabianlindfors/reshape/releases).
40Binaries are available for macOS and Linux under [Releases](https://github.com/fabianlindfors/reshape/releases).
63
41
64−#### Cargo
65−
66−Reshape can be installed using [Cargo](https://doc.rust-lang.org/cargo/) (requires Rust 1.58 or later):
67−
68−```shell
69−cargo install reshape
70−```
71−
72#### Docker
42#### Docker
73
43
74−Reshape is available as a Docker image on [Docker Hub](https://hub.docker.com/repository/docker/fabianlindfors/reshape).
44+Reshape is available as a Docker image on [Docker Hub](https://hub.docker.com/repository/docker/fabianlindfors/reshape).
75
45
76```shell
46```shell
77−docker run -v $(pwd):/usr/share/app fabianlindfors/reshape reshape migration start
47+docker run -v $(pwd):/usr/share/app fabianlindfors/reshape reshape migrate
78```
48```
79
49
80### Creating your first migration
50### Creating your first migration
81
51
82−Each migration should be stored as a separate file in a `migrations/` directory. The files can be in either JSON or TOML format and the name of the file will become the name of your migration. We recommend prefixing every migration with an incrementing number as migrations are sorted by file name.
52+Each migration should be stored as a separate file under `migrations/`. The files can be in either JSON or TOML format. The name of the file will become the name of your migration and they will be sorted by file name. We recommend prefixing every migration with an incrementing number.
83
53
84−Let's create a simple migration to set up a new table `users` with two fields, `id` and `name`. We'll create a file called `migrations/1_create_users_table.toml`:
54+Let's create a simple migration to set up a new table `users` with two fields, `id` and `name`. We'll create a file called `migration/1_create_users_table.toml`:
85
55
86```toml
56```toml
87[[actions]]
57[[actions]]
88type = "create_table"
58type = "create_table"
89−name = "users"
59+table = "users"
90−primary_key = ["id"]
91
60
92 [[actions.columns]]
61 [[actions.columns]]
93 name = "id"
62 name = "id"
@@ -103,14 +72,9 @@ This is the equivalent of running `CREATE TABLE users (id INTEGER GENERATED ALWA
103
72
104### Preparing your application
73### Preparing your application
105
74
106−Reshape relies on your application using a specific schema. When establishing the connection to Postgres in your application, you need to run a query to select the most recent schema. The simplest way to do this is to use one of the helper libraries:
75+Reshape relies on your application using a specific schema. When establishing the connection to Postgres in your application, you need to run a query to select the most recent schema. This query can be generated using: `reshape generate-schema-query`.
107−
108−- [Rust](https://github.com/fabianlindfors/reshape-helper)
109−- [Ruby (and Rails)](https://github.com/fabianlindfors/reshape-ruby)
110−- [Python (and Django)](https://github.com/fabianlindfors/reshape-python)
111−- [Go](https://github.com/leourbina/reshape-helper)
112
76
113−If your application is not using one of the languages with an available helper library, you can instead generate the query with the command: `reshape schema-query`. To pass it along to your application, you can for example use an environment variable in your run script: `RESHAPE_SCHEMA_QUERY=$(reshape schema-query)`. Then in your application:
77+To pass it along to your application, you can for example use an environment variable in your run script: `RESHAPE_SCHEMA_QUERY=$(reshape generate-schema-query)`. Then in your application:
114
78
115```python
79```python
116# Example for Python
80# Example for Python
@@ -123,17 +87,13 @@ db.execute(reshape_schema_query)
123To create your new `users` table, run:
87To create your new `users` table, run:
124
88
125```bash
89```bash
126−reshape migration start --complete
90+reshape migrate
127```
91```
128
92
129−We use the `--complete` flag to automatically complete the migration. During a production deployment, you should first run `reshape migration start` followed by `reshape migration complete` once your application has been fully rolled out.
93+As this is the first migration, Reshape will automatically complete it. For subsequent migrations, you will need to first run `reshape migrate`, roll out your application and then complete the migration using `reshape complete`.
130
94
131If nothing else is specified, Reshape will try to connect to a Postgres database running on `localhost` using `postgres` as both username and password. See [Connection options](#connection-options) for details on how to change the connection settings.
95If nothing else is specified, Reshape will try to connect to a Postgres database running on `localhost` using `postgres` as both username and password. See [Connection options](#connection-options) for details on how to change the connection settings.
132
96
133−### Using during development
134−
135−When adding new migrations during development, we recommend running `reshape migration start` but skipping `reshape migration complete`. This way, the new migrations can be iterated on by updating the migration file and running `reshape migration abort` followed by `reshape migration start`.
136−
137## Writing migrations
97## Writing migrations
138
98
139### Basics
99### Basics
@@ -143,8 +103,7 @@ Every migration consists of one or more actions. The actions will be run sequent
143```toml
103```toml
144[[actions]]
104[[actions]]
145type = "create_table"
105type = "create_table"
146−name = "customers"
106+table = "customers"
147−primary_key = ["id"]
148
107
149 [[actions.columns]]
108 [[actions.columns]]
150 name = "id"
109 name = "id"
@@ -153,8 +112,7 @@ primary_key = ["id"]
153
112
154[[actions]]
113[[actions]]
155type = "create_table"
114type = "create_table"
156−name = "products"
115+table = "products"
157−primary_key = ["sku"]
158
116
159 [[actions.columns]]
117 [[actions.columns]]
160 name = "sku"
118 name = "sku"
@@ -167,15 +125,15 @@ Every action has a `type`. The supported types are detailed below.
167
125
168#### Create table
126#### Create table
169
127
170−The `create_table` action will create a new table with the specified columns, indices and constraints. You can optionally provide an `up` option to backfill values from an existing table.
128+The `create_table` action will create a new table with the specified columns, indices and constraints.
171
129
172−_Example: create a `customers` table with a few columns and a primary key_
130+*Example: create a `customers` table with a few columns and a primary key*
173
131
174```toml
132```toml
175[[actions]]
133[[actions]]
176type = "create_table"
134type = "create_table"
177−name = "customers"
135+table = "customers"
178−primary_key = ["id"]
136+primary_key = "id"
179
137
180 [[actions.columns]]
138 [[actions.columns]]
181 name = "id"
139 name = "id"
@@ -187,19 +145,19 @@ primary_key = ["id"]
187 type = "TEXT"
145 type = "TEXT"
188
146
189 # Columns default to nullable
147 # Columns default to nullable
190− nullable = false
148+ nullable = false
191
149
192 # default can be any valid SQL value, in this case a string literal
150 # default can be any valid SQL value, in this case a string literal
193− default = "'PLACEHOLDER'"
151+ default = "'PLACEHOLDER'"
194```
152```
195
153
196−_Example: create `users` and `items` tables with a foreign key between them_
154+*Example: create `users` and `items` tables with a foreign key between them*
197
155
198```toml
156```toml
199[[actions]]
157[[actions]]
200type = "create_table"
158type = "create_table"
201−name = "users"
159+table = "users"
202−primary_key = ["id"]
160+primary_key = "id"
203
161
204 [[actions.columns]]
162 [[actions.columns]]
205 name = "id"
163 name = "id"
@@ -208,8 +166,8 @@ primary_key = ["id"]
208
166
209[[actions]]
167[[actions]]
210type = "create_table"
168type = "create_table"
211−name = "items"
169+table = "items"
212−primary_key = ["id"]
170+primary_key = "id"
213
171
214 [[actions.columns]]
172 [[actions.columns]]
215 name = "id"
173 name = "id"
@@ -226,34 +184,11 @@ primary_key = ["id"]
226 referenced_columns = ["id"]
184 referenced_columns = ["id"]
227```
185```
228
186
229−_Example: create `profiles` table based on existing `users` table_
230−
231−```toml
232−[[actions]]
233−type = "create_table"
234−name = "profiles"
235−primary_key = ["user_id"]
236−
237− [[actions.columns]]
238− name = "user_id"
239− type = "INTEGER"
240−
241− [[actions.columns]]
242− name = "user_email"
243− type = "TEXT"
244−
245− # Backfill from `users` table and copy `users.email` to `user_email` column
246− # This will perform an upsert based on the primary key to avoid duplicate rows
247− [actions.up]
248− table = "users"
249− values = { user_id = "id", user_email = "email" }
250−```
251−
252#### Rename table
187#### Rename table
253
188
254The `rename_table` action will change the name of an existing table.
189The `rename_table` action will change the name of an existing table.
255
190
256−_Example: change name of `users` table to `customers`_
191+*Example: change name of `users` table to `customers`*
257
192
258```toml
193```toml
259[[actions]]
194[[actions]]
@@ -266,7 +201,7 @@ new_name = "customers"
266
201
267The `remove_table` action will remove an existing table.
202The `remove_table` action will remove an existing table.
268
203
269−_Example: remove `users` table_
204+*Example: remove `users` table*
270
205
271```toml
206```toml
272[[actions]]
207[[actions]]
@@ -274,43 +209,13 @@ type = "remove_table"
274table = "users"
209table = "users"
275```
210```
276
211
277−#### Add foreign key
278−
279−The `add_foreign_key` action will add a foreign key between two existing tables. The migration will fail if the existing column values aren't valid references.
280−
281−_Example: create foreign key from `items` to `users` table_
282−
283−```toml
284−[[actions]]
285−type = "add_foreign_key"
286−table = "items"
287−
288− [actions.foreign_key]
289− columns = ["user_id"]
290− referenced_table = "users"
291− referenced_columns = ["id"]
292−```
293−
294−#### Remove foreign key
295−
296−The `remove_foreign_key` action will remove an existing foreign key. The foreign key will only be removed once the migration is completed, which means that your new application must continue to adhere to the foreign key constraint.
297−
298−_Example: remove foreign key `items_user_id_fkey` from `users` table_
299−
300−```toml
301−[[actions]]
302−type = "remove_foreign_key"
303−table = "items"
304−foreign_key = "items_user_id_fkey"
305−```
306−
307### Columns
212### Columns
308
213
309#### Add column
214#### Add column
310
215
311−The `add_column` action will add a new column to an existing table. You can optionally provide an `up` setting. This should be an SQL expression which will be run for all existing rows to backfill the new column. `up` may also reference another table to perform cross-table migrations (see ["Complex changes across tables"](#complex-changes-across-tables)).
216+The `add_column` action will add a new column to an existing table. You can optionally provide an `up` setting. This should be an SQL expression which will be run for all existing rows to backfill the new column.
312
217
313−_Example: add a new column `reference` to table `products`_
218+*Example: add a new column `reference` to table `products`*
314
219
315```toml
220```toml
316[[actions]]
221[[actions]]
@@ -324,7 +229,7 @@ table = "products"
324 default = "10"
229 default = "10"
325```
230```
326
231
327−_Example: replace an existing `name` column with two new columns, `first_name` and `last_name`_
232+*Example: replace an existing `name` column with two new columns, `first_name` and `last_name`*
328
233
329```toml
234```toml
330[[actions]]
235[[actions]]
@@ -360,48 +265,14 @@ column = "name"
360down = "first_name || ' ' || last_name"
265down = "first_name || ' ' || last_name"
361```
266```
362
267
363−_Example: extract nested value from unstructured JSON `data` column to new `name` column_
364−
365−```toml
366−[[actions]]
367−type = "add_column"
368−table = "users"
369−
370−# #>> '{}' converts the JSON string value to TEXT
371−up = "data['path']['to']['value'] #>> '{}'"
372−
373− [actions.column]
374− name = "name"
375− type = "TEXT"
376−```
377−
378−_Example: duplicate `email` column from `users` to `profiles` table_
379−
380−```toml
381−# `profiles` has `user_id` column which maps to `users.id`
382−[[actions]]
383−type = "add_column"
384−table = "profiles"
385−
386− [actions.column]
387− name = "email"
388− type = "TEXT"
389− nullable = false
390−
391− # When `users` is updated in the old schema, we write the email value to `profiles`
392− [actions.up]
393− table = "users"
394− value = "email"
395− where = "user_id = id"
396−```
397
268
398#### Alter column
269#### Alter column
399
270
400The `alter_column` action enables many different changes to an existing column, for example renaming, changing type and changing existing values.
271The `alter_column` action enables many different changes to an existing column, for example renaming, changing type and changing existing values.
401
272
402−When performing more complex changes than a rename, `up` and `down` should be provided. These should be SQL expressions which determine how to transform between the new and old version of the column. Inside those expressions, you can reference the current column value by the column name.
273+When performing more complex changes than a rename, `up` and `down` must be provided. These should be SQL expressions which determine how to transform between the new and old version of the column. Inside those expressions, you can reference the current column value by the column name.
403
274
404−_Example: rename `last_name` column on `users` table to `family_name`_
275+*Example: rename `last_name` column on `users` table to `family_name`*
405
276
406```toml
277```toml
407[[actions]]
278[[actions]]
@@ -413,7 +284,7 @@ column = "last_name"
413 name = "family_name"
284 name = "family_name"
414```
285```
415
286
416−_Example: change the type of `reference` column from `INTEGER` to `TEXT`_
287+*Example: change the type of `reference` column from `INTEGER` to `TEXT`*
417
288
418```toml
289```toml
419[[actions]]
290[[actions]]
@@ -428,13 +299,12 @@ down = "CAST(reference AS INTEGER)" # Converts from text value to integer
428 type = "TEXT" # Previous type was 'INTEGER'
299 type = "TEXT" # Previous type was 'INTEGER'
429```
300```
430
301
431−_Example: increment all values of an `index` column by one_
302+*Example: increment all values of an `index` column by one*
432
303
433```toml
304```toml
434[[actions]]
305[[actions]]
435type = "alter_column"
306type = "alter_column"
436table = "users"
307table = "users"
437−column = "index"
438
308
439up = "index + 1" # Increment for new schema
309up = "index + 1" # Increment for new schema
440down = "index - 1" # Decrement to revert for old schema
310down = "index - 1" # Decrement to revert for old schema
@@ -443,40 +313,11 @@ down = "index - 1" # Decrement to revert for old schema
443 name = "index"
313 name = "index"
444```
314```
445
315
446−_Example: make `name` column not nullable_
447−
448−```toml
449−[[actions]]
450−type = "alter_column"
451−table = "users"
452−column = "name"
453−
454−# Use "N/A" for any rows that currently have a NULL name
455−up = "COALESCE(name, 'N/A')"
456−
457− [actions.changes]
458− nullable = false
459−```
460−
461−_Example: change default value of `created_at` column to current time_
462−
463−```toml
464−[[actions]]
465−type = "alter_column"
466−table = "users"
467−column = "created_at"
468−
469− [actions.changes]
470− default = "NOW()"
471−```
472−
473#### Remove column
316#### Remove column
474
317
475−The `remove_column` action will remove an existing column from a table. You can optionally provide a `down` setting. This should be an SQL expression which will be used to determine values for the old schema when inserting or updating rows using the new schema. `down` may also reference another table to perform cross-table migrations (see ["Complex changes across tables"](#complex-changes-across-tables)) . The `down` setting must be provided when the removed column is `NOT NULL` or doesn't have a default value.
318+The `remove_column` action will remove an existing column from a table. You can optionally provide a `down` setting. This should be an SQL expression which will be used to determine values for the old schema when inserting or updating rows using the new schema. The `down` setting must be provided when the removed column is `NOT NULL` or doesn't have a default value.
476−
477−Any indices that cover the column will be removed.
478
319
479−_Example: remove column `name` from table `users`_
320+*Example: remove column `name` from table `users`*
480
321
481```toml
322```toml
482[[actions]]
323[[actions]]
@@ -488,34 +329,18 @@ column = "name"
488down = "'N/A'"
329down = "'N/A'"
489```
330```
490
331
491−_Example: remove `email` column from `users` table and use column from `profiles` table instead_
492−
493−```toml
494−[[actions]]
495−type = "remove_column"
496−table = "users"
497−column = "email"
498−
499− # Our application will use the `profiles.email` column instead
500− # For backwards compatibility, we will write back to the removed `email` column whenever `profiles` is changed
501− [actions.down]
502− table = "profiles"
503− value = "profiles.email"
504− where = "users.id = profiles.user_id"
505−```
506−
507### Indices
332### Indices
508
333
509#### Add index
334#### Add index
510
335
511The `add_index` action will add a new index to an existing table.
336The `add_index` action will add a new index to an existing table.
512
337
513−_Example: create a `users` table with a unique index on the `name` column_
338+*Example: create a `users` table with an index on the `name` column*
514
339
515```toml
340```toml
516[[actions]]
341[[actions]]
517type = "create_table"
342type = "create_table"
518−name = "users"
343+table = "users"
519primary_key = "id"
344primary_key = "id"
520
345
521 [[actions.columns]]
346 [[actions.columns]]
@@ -530,242 +355,70 @@ primary_key = "id"
530[[actions]]
355[[actions]]
531type = "add_index"
356type = "add_index"
532table = "users"
357table = "users"
533−
534− [actions.index]
535− name = "name_idx"
358+name = "name_idx"
536− columns = ["name"]
359+columns = ["name"]
537−
538− # Defaults to false
539− unique = true
540−```
541−
542−_Example: add GIN index to `data` column on `products` table_
543−
544−```toml
545−[[actions]]
546−type = "add_index"
547−table = "products"
548−
549− [actions.index]
550− name = "data_idx"
551− columns = ["data"]
552−
553− # One of: btree (default), hash, gist, spgist, gin, brin
554− type = "gin"
555−```
556−
557−#### Remove index
558−
559−The `remove_index` action will remove an existing index. The index won't actually be removed until the migration is completed.
560−
561−_Example: remove the `name_idx` index_
562−
563−```toml
564−[[actions]]
565−type = "remove_index"
566−index = "name_idx"
567−```
568−
569−### Enums
570−
571−#### Create enum
572−
573−The `create_enum` action will create a new [enum type](https://www.postgresql.org/docs/current/datatype-enum.html) with the specified values.
574−
575−_Example: add a new `mood` enum type with three possible values_
576−
577−```toml
578−[[actions]]
579−type = "create_enum"
580−name = "mood"
581−values = ["happy", "ok", "sad"]
582−```
583−
584−#### Remove enum
585−
586−The `remove_enum` action will remove an existing [enum type](https://www.postgresql.org/docs/current/datatype-enum.html). Make sure all usages of the enum has been removed before running the migration. The enum will only be removed once the migration is completed.
587−
588−_Example: remove the `mood` enum type_
589−
590−```toml
591−[[actions]]
592−type = "remove_enum"
593−enum = "mood"
594−```
595−
596−### Custom
597−
598−The `custom` action lets you create a migration which runs custom SQL. It should be used with great care as it provides no guarantees of zero-downtime and will simply run whatever SQL is provided. Use other actions whenever possible as they are explicitly designed for zero downtime.
599−
600−There are three optional settings available which all accept SQL queries. All queries need to be idempotent, for example by using `IF NOT EXISTS` wherever available.
601−
602−- `start`: run when a migration is started using `reshape migration start`
603−- `complete`: run when a migration is completed using `reshape migration complete`
604−- `abort`: run when a migration is aborted using `reshape migration abort`
605−
606−_Example: enable PostGIS and pg_stat_statements extensions_
607−
608−```toml
609−[[actions]]
610−type = "custom"
611−
612−start = """
613− CREATE EXTENSION IF NOT EXISTS postgis;
614− CREATE EXTENSION IF NOT EXISTS pg_stat_statements;
615−"""
616−
617−abort = """
618− DROP EXTENSION IF EXISTS postgis;
619− DROP EXTENSION IF EXISTS pg_stat_statements;
620−"""
621−```
622−
623−### Complex changes across tables
624−
625−The `up` and `down` options available when creating tables, adding columns and removing columns can also perform more complex changes that span tables.
626−
627−_Example: move `email` column from `users` to `profiles` table_
628−
629−```toml
630−[[actions]]
631−type = "add_column"
632−table = "profiles"
633−
634− [actions.column]
635− name = "email"
636− type = "TEXT"
637− nullable = false
638−
639− # When `users` is updated in the old schema, we write the email value to `profiles`
640− [actions.up]
641− table = "users"
642− value = "users.email"
643− where = "profiles.user_id = users.id"
644−
645−[[actions]]
646−type = "remove_column"
647−table = "users"
648−column = "email"
649−
650− # When `profiles` is changed in the new schema, we write the email address back to the removed column
651− [actions.down]
652− table = "profiles"
653− value = "profiles.email"
654− where = "users.id = profiles.user_id"
655−```
656−
657−_Example: turn a 1:N relationship between `users` and `accounts` into N:M and change the format of the associated `role`_
658−
659−```toml
660−# Add `user_account_connections` as a junction table
661−[[actions]]
662−type = "create_table"
663−name = "user_account_connections"
664−primary_key = ["account_id", "user_id"]
665−
666− [[actions.columns]]
667− name = "account_id"
668− type = "INTEGER"
669−
670− [[actions.columns]]
671− name = "user_id"
672− type = "INTEGER"
673−
674− # `role` is currently stored directly on the `users` table but is part of the relationship
675− [[actions.columns]]
676− name = "role"
677− type = "TEXT"
678− nullable = false
679−
680− # Backfill the new table from `users` and uppercase the `role`
681− [actions.up]
682− table = "users"
683− values = { user_id = "id", account_id = "account_id", role = "UPPER(account_role)" }
684− where = "user_account_connections.user_id = users.id"
685−
686−[[actions]]
687−type = "remove_column"
688−table = "users"
689−column = "account_id"
690−
691− # When `user_account_connections` is updated, we write the `account_id` back to `users`
692− [actions.down]
693− table = "user_account_connections"
694− value = "user_account_connections.account_id"
695− where = "users.id = user_account_connections.user_id"
696−
697−[[actions]]
698−type = "remove_column"
699−table = "users"
700−column = "account_role"
701−
702− # When `user_account_connections` is updated, we write the lowercase role back to `users`
703− [actions.down]
704− table = "user_account_connections"
705− value = "LOWER(user_account_connections.role)"
706− where = "users.id = user_account_connections.user_id"
707```
360```
708
361
709## Commands and options
362## Commands and options
710
363
711−### `reshape migration start`
364+### `reshape migrate`
712
365
713−Starts a new migration, applying all migrations under `migrations/` that haven't yet been applied. After the command has completed, both the old and new schema will be usable at the same time. When you have rolled out the new version of your application which uses the new schema, you should run `reshape migration complete`.
366+Starts a new migration, applying all migrations under `migrations/` that haven't yet been applied. After the command has completed, both the old and new schema will be usable at the same time. When you have rolled out the new version of your application which uses the new schema, you should run `reshape complete`.
714
367
715#### Options
368#### Options
716
369
717−_See also [Connection options](#connection-options)_
370+*See also [Connection options](#connection-options)*
718
371
719−| Option | Default | Description |
372+| Option | Default | Description |
720−| ------------------ | ------------- | --------------------------------------------------------------------------------------------------------------- |
373+| ------ | ------- | ----------- |
721−| `--complete`, `-c` | `false` | Automatically complete migration after applying it. |
374+| `--complete`, `-c` | `false` | Automatically complete migration after applying it. Useful during development. |
722−| `--dirs` | `migrations/` | Directories to search for migration files. Multiple directories can be specified using `--dirs dir1 dir2 dir3`. |
375+| `--dirs` | `migrations/` | Directories to search for migration files. Multiple directories can be specified using `--dirs dir1 dir2 dir3`. |
723
376
724−### `reshape migration complete`
377+### `reshape complete`
725
378
726−Completes migrations previously started with `reshape migration complete`.
379+Completes migrations previously started with `reshape complete`.
727
380
728#### Options
381#### Options
729
382
730See [Connection options](#connection-options)
383See [Connection options](#connection-options)
731
384
732−### `reshape migration abort`
385+### `reshape abort`
733
386
734−Aborts any migrations which haven't yet been completed.
387+Aborts any migrations which haven't yet been completed.
735
388
736#### Options
389#### Options
737
390
738See [Connection options](#connection-options)
391See [Connection options](#connection-options)
739
392
740−### `reshape schema-query`
393+### `reshape generate-schema-query`
741
394
742Generates the SQL query you need to run in your application before using the database. This command does not require a database connection. Instead it will generate the query based on the latest migration in the `migrations/` directory (or the directories specified by `--dirs`).
395Generates the SQL query you need to run in your application before using the database. This command does not require a database connection. Instead it will generate the query based on the latest migration in the `migrations/` directory (or the directories specified by `--dirs`).
743
396
744−If your application is written in Rust, we recommend using the [Rust helper library](https://github.com/fabianlindfors/reshape-helper/) instead.
745−
746The query should look something like `SET search_path TO migration_1_initial_migration`.
397The query should look something like `SET search_path TO migration_1_initial_migration`.
747
398
748#### Options
399#### Options
749
400
750−| Option | Default | Description |
401+| Option | Default | Description |
751−| -------- | ------------- | --------------------------------------------------------------------------------------------------------------- |
402+| ------ | ------- | ----------- |
752| `--dirs` | `migrations/` | Directories to search for migration files. Multiple directories can be specified using `--dirs dir1 dir2 dir3`. |
403| `--dirs` | `migrations/` | Directories to search for migration files. Multiple directories can be specified using `--dirs dir1 dir2 dir3`. |
753
404
754### Connection options
405### Connection options
755
406
756−The options below can be used with all commands that communicate with Postgres. Use either a [connection URL](https://www.postgresql.org/docs/current/libpq-connect.html#LIBPQ-CONNSTRING) or specify each connection option individually.
407+The options below can be used with all commands that communicate with Postgres. Use either a connection URL or specify each connection option individually.
757
408
758−All options can also be set using environment variables instead of flags. If a `.env` file exists, then variables will be automatically loaded from there.
409+| Option | Default | Description |
410+| ------ | ------- | ----------- |
411+| `--url` | | URI to connect to your Postgres database.<br>Can also be provided with the environment variable `DATABASE_URL`. |
412+| `--host` | `localhost` | Hostname to use when connecting to Postgres |
413+| `--port` | `5432` | Port which Postgres is listening on |
414+| `--database` | `postgres` | Database name |
415+| `--username` | `postgres` | Postgres username |
416+| `--password` | `postgres` | Postgres password |
759
417
760−| Option | Default | Environment variable | Description |
418+## How it works
761−| ------------ | ----------- | -------------------- | ------------------------------------------- |
762−| `--url` | | `DB_URL` | URL to your Postgres database |
763−| `--host` | `localhost` | `DB_HOST` | Hostname to use when connecting to Postgres |
764−| `--port` | `5432` | `DB_PORT` | Port which Postgres is listening on |
765−| `--database` | `postgres` | `DB_NAME` | Database name |
766−| `--username` | `postgres` | `DB_USERNAME` | Postgres username |
767−| `--password` | `postgres` | `DB_PASSWORD` | Postgres password |
768
419
769−## License
420+Reshape works by creating views that encapsulate the underlying tables, which your application will interact with. During a migration, Reshape will automatically create a new set of views and set up triggers to translate inserts and updates between the old and new schema. This means that every migration is a two phase process:
770
421
771−Reshape is released under the [MIT license](https://choosealicense.com/licenses/mit/).
422+1. **Start migration** (`reshape migrate`): Create new views to ensure both the new and old schema are usable at the same time.
423+ - After phase one is complete, you can start the roll out of your application. Once the roll out is complete, the second phase can be run.
424+2. **Complete migration** (`reshape complete`): Removes the old schema and any intermediate data.
src/db.rs+11−155
@@ -1,87 +1,4 @@
1−use std::{cmp::min, time::Duration};
2−
3−use anyhow::{anyhow, Context};
4use postgres::{types::ToSql, NoTls, Row};
1use postgres::{types::ToSql, NoTls, Row};
5−use rand::prelude::*;
6−
7−// DbLocker wraps a regular DbConn, only allowing access using the
8−// `lock` method. This method will acquire the advisory lock before
9−// allowing access to the database, and then release it afterwards.
10−//
11−// We use advisory locks to avoid multiple Reshape instances working
12−// on the same database as the same time. DbLocker is the only way to
13−// get a DbConn which ensures that all database access is protected by
14−// a lock.
15−//
16−// Postgres docs on advisory locks:
17−// https://www.postgresql.org/docs/current/explicit-locking.html#ADVISORY-LOCKS
18−pub struct DbLocker {
19− client: DbConn,
20−}
21−
22−impl DbLocker {
23− // Advisory lock keys in Postgres are 64-bit integers.
24− // The key we use was chosen randomly.
25− const LOCK_KEY: i64 = 4036779288569897133;
26−
27− pub fn connect(config: &postgres::Config) -> anyhow::Result<Self> {
28− let mut pg = config.connect(NoTls)?;
29−
30− // When running DDL queries that acquire locks, we risk causing a "lock queue".
31− // When attempting to acquire a lock, Postgres will wait for any long running queries to complete.
32− // At the same time, it will block other queries until the lock has been acquired and released.
33− // This has the bad effect of the long-running query blocking other queries because of us, forming
34− // a queue of other queries until we release our lock.
35− //
36− // We set the lock_timeout setting to avoid this. This puts an upper bound for how long Postgres will
37− // wait to acquire locks and also the maximum amount of time a long-running query can block other queries.
38− // We should also add automatic retries to handle these timeouts gracefully.
39− //
40− // Reference: https://medium.com/paypal-tech/postgresql-at-scale-database-schema-changes-without-downtime-20d3749ed680
41− //
42− // TODO: Make lock_timeout configurable
43− pg.simple_query("SET lock_timeout = '1s'")
44− .context("failed to set lock_timeout")?;
45−
46− Ok(Self {
47− client: DbConn::new(pg),
48− })
49− }
50−
51− pub fn lock(
52− &mut self,
53− f: impl FnOnce(&mut DbConn) -> anyhow::Result<()>,
54− ) -> anyhow::Result<()> {
55− self.acquire_lock()?;
56− let result = f(&mut self.client);
57− self.release_lock()?;
58−
59− result
60− }
61−
62− fn acquire_lock(&mut self) -> anyhow::Result<()> {
63− let success = self
64− .client
65− .query(&format!("SELECT pg_try_advisory_lock({})", Self::LOCK_KEY))?
66− .first()
67− .ok_or_else(|| anyhow!("unexpectedly failed when acquiring advisory lock"))
68− .map(|row| row.get::<'_, _, bool>(0))?;
69−
70− if success {
71− Ok(())
72− } else {
73− Err(anyhow!("another instance of Reshape is already running"))
74− }
75− }
76−
77− fn release_lock(&mut self) -> anyhow::Result<()> {
78− self.client
79− .query(&format!("SELECT pg_advisory_unlock({})", Self::LOCK_KEY))?
80− .first()
81− .ok_or_else(|| anyhow!("unexpectedly failed when releasing advisory lock"))?;
82− Ok(())
83− }
84−}
85
2
86pub trait Conn {
3pub trait Conn {
87 fn run(&mut self, query: &str) -> anyhow::Result<()>;
4 fn run(&mut self, query: &str) -> anyhow::Result<()>;
@@ -91,7 +8,6 @@ pub trait Conn {
91 query: &str,
8 query: &str,
92 params: &[&(dyn ToSql + Sync)],
9 params: &[&(dyn ToSql + Sync)],
93 ) -> anyhow::Result<Vec<Row>>;
10 ) -> anyhow::Result<Vec<Row>>;
94− fn transaction(&mut self) -> anyhow::Result<Transaction>;
95}
11}
96
12
97pub struct DbConn {
13pub struct DbConn {
@@ -99,19 +15,25 @@ pub struct DbConn {
99}
15}
100
16
101impl DbConn {
17impl DbConn {
102− fn new(client: postgres::Client) -> Self {
18+ pub fn connect(config: &postgres::Config) -> anyhow::Result<DbConn> {
19+ let client = config.connect(NoTls)?;
103− DbConn { client }
20+ Ok(DbConn { client })
21+ }
22+
23+ pub fn transaction(&mut self) -> anyhow::Result<Transaction> {
24+ let transaction = self.client.transaction()?;
25+ Ok(Transaction { transaction })
104 }
26 }
105}
27}
106
28
107impl Conn for DbConn {
29impl Conn for DbConn {
108 fn run(&mut self, query: &str) -> anyhow::Result<()> {
30 fn run(&mut self, query: &str) -> anyhow::Result<()> {
109− retry_automatically(|| self.client.batch_execute(query))?;
31+ self.client.batch_execute(query)?;
110 Ok(())
32 Ok(())
111 }
33 }
112
34
113 fn query(&mut self, query: &str) -> anyhow::Result<Vec<Row>> {
35 fn query(&mut self, query: &str) -> anyhow::Result<Vec<Row>> {
114− let rows = retry_automatically(|| self.client.query(query, &[]))?;
36+ let rows = self.client.query(query, &[])?;
115 Ok(rows)
37 Ok(rows)
116 }
38 }
117
39
@@ -120,14 +42,9 @@ impl Conn for DbConn {
120 query: &str,
42 query: &str,
121 params: &[&(dyn ToSql + Sync)],
43 params: &[&(dyn ToSql + Sync)],
122 ) -> anyhow::Result<Vec<Row>> {
44 ) -> anyhow::Result<Vec<Row>> {
123− let rows = retry_automatically(|| self.client.query(query, params))?;
45+ let rows = self.client.query(query, params)?;
124 Ok(rows)
46 Ok(rows)
125 }
47 }
126−
127− fn transaction(&mut self) -> anyhow::Result<Transaction> {
128− let transaction = self.client.transaction()?;
129− Ok(Transaction { transaction })
130− }
131}
48}
132
49
133pub struct Transaction<'a> {
50pub struct Transaction<'a> {
@@ -139,11 +56,6 @@ impl Transaction<'_> {
139 self.transaction.commit()?;
56 self.transaction.commit()?;
140 Ok(())
57 Ok(())
141 }
58 }
142−
143− pub fn rollback(self) -> anyhow::Result<()> {
144− self.transaction.rollback()?;
145− Ok(())
146− }
147}
59}
148
60
149impl Conn for Transaction<'_> {
61impl Conn for Transaction<'_> {
@@ -165,60 +77,4 @@ impl Conn for Transaction<'_> {
165 let rows = self.transaction.query(query, params)?;
77 let rows = self.transaction.query(query, params)?;
166 Ok(rows)
78 Ok(rows)
167 }
79 }
168−
169− fn transaction(&mut self) -> anyhow::Result<Transaction> {
170− let transaction = self.transaction.transaction()?;
171− Ok(Transaction { transaction })
172− }
173−}
174−
175−// Retry a database operation with exponential backoff and jitter
176−fn retry_automatically<T>(
177− mut f: impl FnMut() -> Result<T, postgres::Error>,
178−) -> Result<T, postgres::Error> {
179− const STARTING_WAIT_TIME: u64 = 100;
180− const MAX_WAIT_TIME: u64 = 3_200;
181− const MAX_ATTEMPTS: u32 = 10;
182−
183− let mut rng = rand::thread_rng();
184− let mut attempts = 0;
185− loop {
186− let result = f();
187−
188− let error = match result {
189− Ok(_) => return result,
190− Err(err) => err,
191− };
192−
193− // If we got a database error, we check if it's retryable.
194− // If we didn't get a database error, then it's most likely some kind of connection
195− // error which should also be retried.
196− if let Some(db_error) = error.as_db_error() {
197− if !error_retryable(db_error) {
198− return Err(error);
199− }
200− }
201−
202− attempts += 1;
203− if attempts >= MAX_ATTEMPTS {
204− return Err(error);
205− }
206−
207− // The wait time increases exponentially, starting at 100ms and doubling up to a max of 3.2s.
208− let wait_time = min(
209− MAX_WAIT_TIME,
210− STARTING_WAIT_TIME * u64::pow(2, attempts - 1),
211− );
212−
213− // The jitter is up to half the wait time
214− let jitter: u64 = rng.gen_range(0..wait_time / 2);
215−
216− std::thread::sleep(Duration::from_millis(wait_time + jitter));
217− }
218−}
219−
220−// Check if a database error can be retried
221−fn error_retryable(error: &postgres::error::DbError) -> bool {
222− // LOCK_NOT_AVAILABLE is caused by lock_timeout being exceeded
223− matches!(error.code(), &postgres::error::SqlState::LOCK_NOT_AVAILABLE)
224}
80}
src/helpers.rs+17−8
@@ -2,28 +2,37 @@ use anyhow::Context;
2
2
3use crate::db::Conn;
3use crate::db::Conn;
4
4
5−pub fn set_up_helpers(db: &mut dyn Conn, target_migration: &str) -> anyhow::Result<()> {
5+pub fn setup_helpers(db: &mut dyn Conn, current_migration: &Option<String>) -> anyhow::Result<()> {
6+ let predicate = if let Some(current_migration) = current_migration {
7+ format!(
8+ "current_setting('search_path') = 'migration_{}' OR setting_bool",
9+ current_migration
10+ )
11+ } else {
12+ format!("setting_bool")
13+ };
14+
6 let query = format!(
15 let query = format!(
7 "
16 "
8− CREATE OR REPLACE FUNCTION reshape.is_new_schema()
17+ CREATE OR REPLACE FUNCTION reshape.is_old_schema()
9 RETURNS BOOLEAN AS $$
18 RETURNS BOOLEAN AS $$
10 DECLARE
19 DECLARE
11− setting TEXT := current_setting('reshape.is_new_schema', TRUE);
20+ setting TEXT := current_setting('reshape.is_old_schema', TRUE);
12 setting_bool BOOLEAN := setting IS NOT NULL AND setting = 'YES';
21 setting_bool BOOLEAN := setting IS NOT NULL AND setting = 'YES';
13 BEGIN
22 BEGIN
14− RETURN current_setting('search_path') = 'migration_{}' OR setting_bool;
23+ RETURN {};
15 END
24 END
16 $$ language 'plpgsql';
25 $$ language 'plpgsql';
17 ",
26 ",
18− target_migration,
27+ predicate
19 );
28 );
20 db.query(&query)
29 db.query(&query)
21− .context("failed creating helper function reshape.is_new_schema()")?;
30+ .context("failed creating helper function reshape.is_old_schema()")?;
22
31
23 Ok(())
32 Ok(())
24}
33}
25
34
26−pub fn tear_down_helpers(db: &mut dyn Conn) -> anyhow::Result<()> {
35+pub fn teardown_helpers(db: &mut dyn Conn) -> anyhow::Result<()> {
27− db.query("DROP FUNCTION IF EXISTS reshape.is_new_schema;")?;
36+ db.query("DROP FUNCTION reshape.is_old_schema;")?;
28 Ok(())
37 Ok(())
29}
38}
src/lib.rs+198−419
@@ -1,11 +1,10 @@
1use crate::{
1use crate::{
2− migrations::{Migration, MigrationContext},
2+ migrations::{Context, Migration},
3 schema::Schema,
3 schema::Schema,
4};
4};
5
5
6−use anyhow::{anyhow, Context};
7use colored::*;
6use colored::*;
8−use db::{Conn, DbConn, DbLocker};
7+use db::{Conn, DbConn};
9use postgres::Config;
8use postgres::Config;
10use schema::Table;
9use schema::Table;
11
10
@@ -15,10 +14,11 @@ pub mod migrations;
15mod schema;
14mod schema;
16mod state;
15mod state;
17
16
18−pub use crate::state::State;
17+pub use crate::state::{State, Status};
19
18
20pub struct Reshape {
19pub struct Reshape {
21− db: DbLocker,
20+ pub state: State,
21+ db: DbConn,
22}
22}
23
23
24impl Reshape {
24impl Reshape {
@@ -30,7 +30,6 @@ impl Reshape {
30 pub fn new_with_options(
30 pub fn new_with_options(
31 host: &str,
31 host: &str,
32 port: u16,
32 port: u16,
33− database: &str,
34 username: &str,
33 username: &str,
35 password: &str,
34 password: &str,
36 ) -> anyhow::Result<Reshape> {
35 ) -> anyhow::Result<Reshape> {
@@ -39,488 +38,268 @@ impl Reshape {
39 .host(host)
38 .host(host)
40 .port(port)
39 .port(port)
41 .user(username)
40 .user(username)
42− .dbname(database)
43 .password(password);
41 .password(password);
44
42
45 Self::new_with_config(&config)
43 Self::new_with_config(&config)
46 }
44 }
47
45
48 fn new_with_config(config: &Config) -> anyhow::Result<Reshape> {
46 fn new_with_config(config: &Config) -> anyhow::Result<Reshape> {
49− let db = DbLocker::connect(config)?;
47+ let mut db = DbConn::connect(config)?;
50− Ok(Reshape { db })
48+ let state = State::load(&mut db);
51− }
52
49
53− pub fn migrate(
50+ Ok(Reshape { db, state })
54− &mut self,
55− migrations: impl IntoIterator<Item = Migration>,
56− ) -> anyhow::Result<()> {
57− self.db.lock(|db| {
58− let mut state = State::load(db)?;
59− migrate(db, &mut state, migrations)
60− })
61 }
51 }
62
52
63− pub fn complete(&mut self) -> anyhow::Result<()> {
53+ pub fn migrate<T>(&mut self, migrations: T) -> anyhow::Result<()>
64− self.db.lock(|db| {
54+ where
55+ T: IntoIterator<Item = Migration>,
56+ {
65− let mut state = State::load(db)?;
57+ self.state = State::load(&mut self.db);
66− complete(db, &mut state)
67− })
68− }
69
58
70− pub fn abort(&mut self) -> anyhow::Result<()> {
59+ // Make sure no migration is in progress
71− self.db.lock(|db| {
60+ if let state::Status::InProgress { migrations: _ } = &self.state.status {
72− let mut state = State::load(db)?;
61+ println!("Migration already in progress, please complete using 'reshape complete'");
73− abort(db, &mut state)
62+ return Ok(());
74− })
75− }
63+ }
76
64
77− pub fn remove(&mut self) -> anyhow::Result<()> {
65+ let current_migration = &self.state.current_migration.clone();
78− self.db.lock(|db| {
66+ let remaining_migrations = self.state.get_remaining_migrations(migrations)?;
79− let mut state = State::load(db)?;
67+ if remaining_migrations.is_empty() {
80−
68+ println!("No migrations left to apply");
81− // Remove migration schemas and views
69+ return Ok(());
82− if let Some(current_migration) = &state::current_migration(db)? {
83− db.run(&format!(
84− "DROP SCHEMA IF EXISTS {} CASCADE",
85− schema_name_for_migration(current_migration)
86− ))?;
87− }
70+ }
88
71
89− if let State::InProgress { migrations } = &state {
72+ println!(" Applying {} migrations\n", remaining_migrations.len());
90− let target_migration = migrations.last().unwrap().name.to_string();
91− db.run(&format!(
92− "DROP SCHEMA IF EXISTS {} CASCADE",
93− schema_name_for_migration(&target_migration)
94− ))?;
95− }
96
73
97− // Remove all tables
74+ let target_migration = remaining_migrations.last().unwrap().name.to_string();
98− let schema = Schema::new();
99− for table in schema.get_tables(db)? {
100− db.run(&format!(
101− r#"
102− DROP TABLE IF EXISTS "{}" CASCADE
103− "#,
104− table.real_name
105− ))?;
106− }
107
75
108− // Remove all enums
76+ let mut new_schema = Schema::new();
109− let enums: Vec<String> = db
110− .query("SELECT typname FROM pg_type WHERE typcategory = 'E'")?
111− .iter()
112− .map(|row| row.get("typname"))
113− .collect();
114− for enum_type in enums {
115− db.run(&format!("DROP TYPE {}", enum_type))?;
116− }
117
77
118− // Reset state
78+ helpers::setup_helpers(&mut self.db, current_migration)?;
119− state.clear(db)?;
120
79
121− println!("Reshape and all data has been removed");
80+ for (migration_index, migration) in remaining_migrations.iter().enumerate() {
81+ println!("Migrating '{}':", migration.name);
122
82
123− Ok(())
83+ for (action_index, action) in migration.actions.iter().enumerate() {
124− })
84+ print!(" + {} ", action.describe());
125− }
126−}
127
85
128−pub fn latest_schema_from_migrations(migrations: &[Migration]) -> Option<String> {
86+ let ctx = Context::new(migration_index, action_index);
129− migrations
87+ action.run(&ctx, &mut self.db, &new_schema)?;
130− .last()
88+ action.update_schema(&ctx, &mut new_schema)?;
131− .map(|migration| schema_name_for_migration(&migration.name))
132−}
133
89
134−pub fn schema_query_for_migration(migration_name: &str) -> String {
90+ println!("{}", "done".green());
135− let schema_name = schema_name_for_migration(migration_name);
136− format!("SET search_path TO {}", schema_name)
137−}
91+ }
138
92
139−fn schema_name_for_migration(migration_name: &str) -> String {
93+ println!("");
140− format!("migration_{}", migration_name)
141−}
94+ }
142
95
143−fn migrate(
96+ // Create schema and views for migration
144− db: &mut DbConn,
97+ self.create_schema_for_migration(&target_migration, &new_schema)?;
145− state: &mut State,
146− migrations: impl IntoIterator<Item = Migration>,
147−) -> anyhow::Result<()> {
148− // Make sure no migration is in progress
149− if let State::InProgress { .. } = &state {
150− println!(
151− "Migration already in progress, please complete using 'reshape migration complete'"
152− );
153− return Ok(());
154− }
155
98
156− if let State::Completing { .. } = &state {
99+ // Update state once migrations have been performed
157− println!(
100+ self.state.in_progress(remaining_migrations);
158− "Migration already in progress and has started completion, please finish using 'reshape migration complete'"
101+ self.state.save(&mut self.db)?;
159− );
160− return Ok(());
161− }
162
102
163− // Determine which migrations need to be applied by comparing the provided migrations
103+ // If we started from a blank slate, we can finish the migration immediately
164− // with the already applied ones stored in the state. This will throw an error if the
104+ if current_migration.is_none() {
165− // two sets of migrations don't agree, for example if a new migration has been added
105+ println!("Automatically completing migrations\n");
166− // in between two existing ones.
106+ self.complete_migration()?;
167− let remaining_migrations = state::remaining_migrations(db, migrations)?;
168− if remaining_migrations.is_empty() {
169− println!("No migrations left to apply");
170− return Ok(());
171− }
172
107
173− // If we have already started applying some migrations we need to ensure that
108+ println!("Migrations complete:");
174− // they are the same ones we want to apply now
109+ println!(
175− if let State::Applying {
110+ " - Run '{}' from your application to use the latest schema",
176− migrations: existing_migrations,
111+ schema_query_for_migration(&target_migration)
177− } = &state
112+ );
178− {
113+ } else {
179− if existing_migrations != &remaining_migrations {
114+ println!("Migrations have been applied and the new schema is ready for use:");
180− return Err(anyhow!(
115+ println!(
181− "a previous migration seems to have failed without cleaning up. Please run `reshape migration abort` and then run migrate again."
116+ " - Run '{}' from your application to use the latest schema",
117+ schema_query_for_migration(&target_migration)
118+ );
119+ println!(
120+ " - Run 'reshape complete' once your application has been updated and the previous schema is no longer in use"
182− ));
121+ );
183 }
122 }
123+
124+ Ok(())
184 }
125 }
185
126
186− // Move to the "Applying" state which is necessary as we can't run the migrations
127+ pub fn complete_migration(&mut self) -> anyhow::Result<()> {
187− // and state update as a single transaction. If a migration unexpectedly fails without
128+ // Make sure a migration is in progress
188− // automatically aborting, this state saves us from dangling migrations. It forces the user
129+ let remaining_migrations = match &self.state.status {
189− // to either run migrate again (which works as all migrations are idempotent) or abort.
130+ state::Status::InProgress { migrations } => migrations,
190− state.applying(remaining_migrations.clone());
131+ _ => {
191− state.save(db)?;
132+ println!("No migration in progress");
133+ return Ok(());
134+ }
135+ };
192
136
193− println!("Applying {} migrations\n", remaining_migrations.len());
137+ helpers::teardown_helpers(&mut self.db)?;
194
138
195− let target_migration = remaining_migrations.last().unwrap().name.to_string();
139+ let mut temp_schema = Schema::new();
196− helpers::set_up_helpers(db, &target_migration).context("failed to set up helpers")?;
197
140
198− let mut new_schema = Schema::new();
141+ // Run all the completion changes as a transaction to avoid incomplete updates
199− let mut last_migration_index = usize::MAX;
142+ let mut transaction = self.db.transaction()?;
200− let mut last_action_index = usize::MAX;
201− let mut result: anyhow::Result<()> = Ok(());
202
143
203− 'outer: for (migration_index, migration) in remaining_migrations.iter().enumerate() {
144+ // Remove previous migration's schema
204− println!("Migrating '{}':", migration.name);
145+ if let Some(current_migration) = &self.state.current_migration {
205− last_migration_index = migration_index;
146+ transaction.run(&format!(
147+ "DROP SCHEMA IF EXISTS {} CASCADE",
148+ schema_name_for_migration(current_migration)
149+ ))?;
150+ }
206
151
207− for (action_index, action) in migration.actions.iter().enumerate() {
152+ for (migration_index, migration) in remaining_migrations.iter().enumerate() {
208− last_action_index = action_index;
153+ println!("Completing '{}':", migration.name);
209
154
210− let description = action.describe();
155+ for (action_index, action) in migration.actions.iter().enumerate() {
211− print!(" + {} ", description);
156+ print!(" + {} ", action.describe());
212
157
213− let ctx =
214− MigrationContext::new(migration_index, action_index, state::current_migration(db)?);
158+ let ctx = Context::new(migration_index, action_index);
215− result = action
159+ action.complete(&ctx, &mut transaction, &temp_schema)?;
216− .run(&ctx, db, &new_schema)
160+ action.update_schema(&ctx, &mut temp_schema)?;
217− .with_context(|| format!("failed to {}", description));
218
161
219− if result.is_ok() {
220− action.update_schema(&ctx, &mut new_schema);
221 println!("{}", "done".green());
162 println!("{}", "done".green());
222− } else {
223− println!("{}", "failed".red());
224− break 'outer;
225 }
163 }
164+
165+ println!("");
226 }
166 }
227
167
228− println!();
168+ self.state.complete()?;
229− }
169+ self.state.save(&mut transaction)?;
230
170
231− // If a migration failed, we abort all the migrations that were applied
171+ transaction.commit()?;
232− if let Err(err) = result {
233− println!("A migration failed, aborting migrations that have already been applied");
234
172
235− // Set to the Aborting state. This is to ensure that the failed
173+ Ok(())
236− // migration is fully aborted and nothing is left dangling.
174+ }
237− // If the abort is interrupted for any reason, the user can try again
238− // by running `reshape migration abort`.
239− state.aborting(
240− remaining_migrations.clone(),
241− last_migration_index + 1,
242− last_action_index + 1,
243− );
244
175
245− // Abort will only
176+ fn create_schema_for_migration(
246− abort(db, state)?;
177+ &mut self,
178+ migration_name: &str,
179+ schema: &Schema,
180+ ) -> anyhow::Result<()> {
181+ // Create schema for migration
182+ let schema_name = schema_name_for_migration(migration_name);
183+ self.db
184+ .run(&format!("CREATE SCHEMA IF NOT EXISTS {}", schema_name))?;
185+
186+ // Create views inside schema
187+ for table in schema.get_tables(&mut self.db)? {
188+ Self::create_view_for_table(&mut self.db, &table, &schema_name)?;
189+ }
247
190
248− return Err(err);
191+ Ok(())
249 }
192 }
250
193
251− // Create schema and views for migration
194+ fn create_view_for_table(
252− create_schema_for_migration(db, &target_migration, &new_schema)
195+ db: &mut impl Conn,
253− .with_context(|| format!("failed to create schema for migration {}", target_migration))?;
196+ table: &Table,
254−
197+ schema: &str,
255− // Update state once migrations have been performed
198+ ) -> anyhow::Result<()> {
256− state.in_progress(remaining_migrations);
199+ let select_columns: Vec<String> = table
257− state.save(db).context("failed to save in-progress state")?;
200+ .columns
258−
201+ .iter()
259− println!("Migrations have been applied and the new schema is ready for use:");
202+ .map(|column| format!("{} AS {}", column.real_name, column.name))
260− println!(
203+ .collect();
261− " - Run '{}' from your application to use the latest schema",
262− schema_query_for_migration(&target_migration)
263− );
264− println!(
265− " - Run 'reshape migration complete' once your application has been updated and the previous schema is no longer in use"
266− );
267− Ok(())
268−}
269
204
270−fn complete(db: &mut DbConn, state: &mut State) -> anyhow::Result<()> {
271− // Make sure a migration is in progress
272− let (remaining_migrations, starting_migration_index, starting_action_index) = match state.clone() {
273− State::InProgress { migrations } => {
274− // Move into the Completing state. Once in this state,
275− // the migration can't be aborted and must be completed.
276− state.completing(migrations.clone(), 0, 0);
277− state.save(db).context("failed to save state")?;
278−
279− (migrations, 0, 0)
280− },
281− State::Completing {
282− migrations,
283− current_migration_index,
284− current_action_index
285− } => (migrations, current_migration_index, current_action_index),
286− State::Aborting { .. } => {
287− return Err(anyhow!("migration been aborted and can't be completed. Please finish using `reshape migration abort`."))
288− }
289− State::Applying { .. } => {
290− return Err(anyhow!("a previous migration unexpectedly failed. Please run `reshape migrate` to try applying the migration again."))
291− }
292− State::Idle => {
293− println!("No migration in progress");
294− return Ok(());
295− }
296− };
297−
298− // Remove previous migration's schema
299− if let Some(current_migration) = &state::current_migration(db)? {
300 db.run(&format!(
205 db.run(&format!(
301− "DROP SCHEMA IF EXISTS {} CASCADE",
206+ "CREATE OR REPLACE VIEW {schema}.{view_name} AS
302− schema_name_for_migration(current_migration)
207+ SELECT {columns}
303− ))
208+ FROM {table_name}",
304− .context("failed to remove previous migration's schema")?;
209+ schema = schema,
210+ table_name = table.real_name,
211+ view_name = table.name,
212+ columns = select_columns.join(","),
213+ ))?;
214+
215+ Ok(())
305 }
216 }
306
217
307− for (migration_index, migration) in remaining_migrations.iter().enumerate() {
218+ pub fn remove(&mut self) -> anyhow::Result<()> {
308− // Skip all the migrations which have already been completed
219+ // Remove migration schemas and views
309− if migration_index < starting_migration_index {
220+ if let Some(current_migration) = &self.state.current_migration {
310− continue;
221+ self.db.run(&format!(
222+ "DROP SCHEMA IF EXISTS {} CASCADE",
223+ schema_name_for_migration(current_migration)
224+ ))?;
311 }
225 }
312
226
313− println!("Completing '{}':", migration.name);
227+ if let Status::InProgress { migrations } = &self.state.status {
314−
228+ let target_migration = migrations.last().unwrap().name.to_string();
315− for (action_index, action) in migration.actions.iter().enumerate() {
229+ self.db.run(&format!(
316− // Skip all actions which have already been completed
230+ "DROP SCHEMA IF EXISTS {} CASCADE",
317− if migration_index == starting_migration_index && action_index < starting_action_index {
231+ schema_name_for_migration(&target_migration)
318− continue;
232+ ))?;
319− }
320−
321− let description = action.describe();
322− print!(" + {} ", description);
323−
324− let ctx =
325− MigrationContext::new(migration_index, action_index, state::current_migration(db)?);
326−
327− // Update state to indicate that this action has been completed.
328− // We won't save this new state until after the action has completed.
329− state.completing(
330− remaining_migrations.clone(),
331− migration_index + 1,
332− action_index + 1,
333− );
334−
335− // This did_save check is necessary because of the borrow checker.
336− // The Transaction which might be returned from action.complete
337− // contains a mutable reference to self.db. We need the Transaction
338− // to be dropped before we can save the state using self.db instead,
339− // which we achieve here by limiting the lifetime of the Transaction
340− // with a new block.
341− let did_save = {
342− let result = action
343− .complete(&ctx, db)
344− .with_context(|| format!("failed to complete migration {}", migration.name))
345− .with_context(|| format!("failed to complete action: {}", description));
346−
347− let maybe_transaction = match result {
348− Ok(maybe_transaction) => {
349− println!("{}", "done".green());
350− maybe_transaction
351− }
352− Err(e) => {
353− println!("{}", "failed".red());
354− return Err(e);
355− }
356− };
357−
358− // Update state with which migrations and actions have been completed.
359− // Each action can create and return a transaction if they need atomicity.
360− // We use this transaction to update the state to ensure the action only completes.
361− // once.
362− // We want to use a single transaction for each action to keep the length of
363− // the transaction as short as possible. Wherever possible, we don't want to
364− // use a transaction at all.
365− if let Some(mut transaction) = maybe_transaction {
366− state
367− .save(&mut transaction)
368− .context("failed to save state after completing action")?;
369− transaction
370− .commit()
371− .context("failed to commit transaction")?;
372−
373− true
374− } else {
375− false
376− }
377− };
378−
379− // If the action didn't return a transaction we save the state normally instead
380− if !did_save {
381− state
382− .save(db)
383− .context("failed to save state after completing action")?;
384− }
385 }
233 }
386
234
387− println!();
235+ // Remove all tables
236+ let schema = Schema::new();
237+ for table in schema.get_tables(&mut self.db)? {
238+ self.db
239+ .run(&format!("DROP TABLE IF EXISTS {} CASCADE", table.real_name))?;
388− }
240+ }
389
241
390− // Remove helpers which are no longer in use
242+ // Reset state
391− helpers::tear_down_helpers(db).context("failed to tear down helpers")?;
243+ self.state.clear(&mut self.db)?;
392
244
393− state
245+ println!("Reshape and all data has been removed");
394− .complete(db)
395− .context("failed to update state as completed")?;
396
246
397− Ok(())
247+ Ok(())
398−}
248+ }
399
249
400−fn abort(db: &mut DbConn, state: &mut State) -> anyhow::Result<()> {
250+ pub fn abort(&mut self) -> anyhow::Result<()> {
401− let (remaining_migrations, last_migration_index, last_action_index) = match state.clone() {
251+ let remaining_migrations = match &self.state.status {
402− State::InProgress { migrations } | State::Applying { migrations } => {
252+ Status::InProgress { migrations } => migrations,
403− // Set to the Aborting state. Once this is done, the migration has to
253+ _ => {
404− // be fully aborted and can't be completed.
254+ println!("No migration is in progress");
405− state.aborting(migrations.clone(), 0, 0);
255+ return Ok(());
406− state.save(db)?;
256+ }
257+ };
258+ let target_migration = remaining_migrations.last().unwrap().name.to_string();
407
259
408− (migrations, usize::MAX, usize::MAX)
260+ helpers::teardown_helpers(&mut self.db)?;
409− }
410− State::Aborting {
411− migrations,
412− last_migration_index,
413− last_action_index,
414− } => (migrations, last_migration_index, last_action_index),
415− State::Completing { .. } => {
416− return Err(anyhow!("migration completion has already been started. Please run `reshape migration complete` again to finish it."));
417− }
418− State::Idle => {
419− println!("No migration is in progress");
420− return Ok(());
421− }
422− };
423−
424− // Remove new migration's schema
425− let target_migration = remaining_migrations.last().unwrap().name.to_string();
426− let schema_name = schema_name_for_migration(&target_migration);
427− db.run(&format!("DROP SCHEMA IF EXISTS {} CASCADE", schema_name,))
428− .with_context(|| format!("failed to drop schema {}", schema_name))?;
429−
430− // Abort all pending migrations
431− // Abort all migrations in reverse order
432− for (migration_index, migration) in remaining_migrations.iter().enumerate().rev() {
433− // Skip migrations which shouldn't be aborted
434− // The reason can be that they have already been aborted or that
435− // the migration was never applied in the first place.
436− if migration_index >= last_migration_index {
437− continue;
438− }
439
261
440− print!("Aborting '{}' ", migration.name);
262+ // Run all the abort changes as a transaction to avoid incomplete changes
263+ let mut transaction = self.db.transaction()?;
441
264
442− for (action_index, action) in migration.actions.iter().enumerate().rev() {
265+ // Remove new migration's schema
443− // Skip actions which shouldn't be aborted
266+ transaction.run(&format!(
444− // The reason can be that they have already been aborted or that
267+ "DROP SCHEMA IF EXISTS {} CASCADE",
445− // the action was never applied in the first place.
268+ schema_name_for_migration(&target_migration)
446− if migration_index == last_migration_index - 1 && action_index >= last_action_index {
269+ ))?;
447− continue;
270+
271+ // Abort all pending migrations in reverse order
272+ for (migration_index, migration) in remaining_migrations.iter().rev().enumerate() {
273+ print!("Aborting'{}' ", migration.name);
274+ for (action_index, action) in migration.actions.iter().rev().enumerate() {
275+ let ctx = Context::new(migration_index, action_index);
276+ action.abort(&ctx, &mut transaction)?;
448 }
277 }
449−
278+ println!("{}", "done".green());
450− let ctx =
451− MigrationContext::new(migration_index, action_index, state::current_migration(db)?);
452− action
453− .abort(&ctx, db)
454− .with_context(|| format!("failed to abort migration {}", migration.name))
455− .with_context(|| format!("failed to abort action: {}", action.describe()))?;
456−
457− // Update state with which migrations and actions have been aborted.
458− // We don't need to run this in a transaction as aborts are idempotent.
459− state.aborting(remaining_migrations.to_vec(), migration_index, action_index);
460− state.save(db).context("failed to save state")?;
461 }
279 }
462
280
463− println!("{}", "done".green());
281+ let keep_count = self.state.migrations.len() - remaining_migrations.len();
464− }
282+ self.state.migrations.truncate(keep_count);
283+ self.state.status = state::Status::Idle;
284+ self.state.save(&mut transaction)?;
465
285
466− helpers::tear_down_helpers(db).context("failed to tear down helpers")?;
286+ transaction.commit()?;
467
287
468− *state = State::Idle;
288+ Ok(())
469− state.save(db).context("failed to save state")?;
289+ }
290+}
470
291
471− Ok(())
292+pub fn latest_schema_from_migrations(migrations: &[Migration]) -> Option<String> {
293+ migrations
294+ .last()
295+ .map(|migration| schema_name_for_migration(&migration.name))
472}
296}
473
297
474−fn create_schema_for_migration(
475− db: &mut DbConn,
476− migration_name: &str,
298+pub fn schema_query_for_migration(migration_name: &str) -> String {
477− schema: &Schema,
478−) -> anyhow::Result<()> {
479− // Create schema for migration
480 let schema_name = schema_name_for_migration(migration_name);
299 let schema_name = schema_name_for_migration(migration_name);
481− db.run(&format!("CREATE SCHEMA IF NOT EXISTS {}", schema_name))
300+ format!("SET search_path TO {}", schema_name)
482− .with_context(|| {
483− format!(
484− "failed to create schema {} for migration {}",
485− schema_name, migration_name
486− )
487− })?;
488−
489− // Create views inside schema
490− for table in schema.get_tables(db)? {
491− create_view_for_table(db, &table, &schema_name)?;
492− }
493−
494− Ok(())
495}
301}
496
302
497−fn create_view_for_table(db: &mut impl Conn, table: &Table, schema: &str) -> anyhow::Result<()> {
303+fn schema_name_for_migration(migration_name: &str) -> String {
498− let select_columns: Vec<String> = table
304+ format!("migration_{}", migration_name)
499− .columns
500− .iter()
501− .map(|column| {
502− format!(
503− r#"
504− "{real_name}" AS "{alias}"
505− "#,
506− real_name = column.real_name,
507− alias = column.name,
508− )
509− })
510− .collect();
511−
512− db.run(&format!(
513− r#"
514− CREATE OR REPLACE VIEW {schema}."{view_name}" AS
515− SELECT {columns}
516− FROM "{table_name}"
517− "#,
518− schema = schema,
519− table_name = table.real_name,
520− view_name = table.name,
521− columns = select_columns.join(","),
522− ))
523− .with_context(|| format!("failed to create view for table {}", table.name))?;
524−
525− Ok(())
526}
305}
src/main.rs+27−98
@@ -4,7 +4,6 @@ use std::{
4 path::Path,
4 path::Path,
5};
5};
6
6
7−use anyhow::Context;
8use clap::{Args, Parser};
7use clap::{Args, Parser};
9use reshape::{
8use reshape::{
10 migrations::{Action, Migration},
9 migrations::{Action, Migration},
@@ -13,69 +12,22 @@ use reshape::{
13use serde::{Deserialize, Serialize};
12use serde::{Deserialize, Serialize};
14
13
15#[derive(Parser)]
14#[derive(Parser)]
16−#[clap(name = "Reshape", version, about)]
17struct Opts {
15struct Opts {
18 #[clap(subcommand)]
16 #[clap(subcommand)]
19 cmd: Command,
17 cmd: Command,
20}
18}
21
19
22#[derive(Parser)]
20#[derive(Parser)]
23−#[clap(about)]
24enum Command {
21enum Command {
25− #[clap(subcommand)]
26− Migration(MigrationCommand),
27−
28− #[clap(
29− about = "Output the query your application should use to select the right schema",
30− display_order = 2
31− )]
32− SchemaQuery(FindMigrationsOptions),
33−
34− #[clap(
35− about = "Deprecated. Use `reshape schema-query` instead",
36− display_order = 3
37− )]
38− GenerateSchemaQuery(FindMigrationsOptions),
39−
40− #[clap(
41− about = "Deprecated. Use `reshape migration start` instead",
42− display_order = 4
43− )]
44 Migrate(MigrateOptions),
22 Migrate(MigrateOptions),
45− #[clap(
46− about = "Deprecated. Use `reshape migration complete` instead",
47− display_order = 5
48− )]
49 Complete(ConnectionOptions),
23 Complete(ConnectionOptions),
50− #[clap(
51− about = "Deprecated. Use `reshape migration abort` instead",
52− display_order = 6
53− )]
54− Abort(ConnectionOptions),
55−}
56−
57−#[derive(Parser)]
58−#[clap(about = "Commands for managing migrations", display_order = 1)]
59−enum MigrationCommand {
60− #[clap(
61− about = "Starts a new migration, applying any migrations which haven't yet been applied",
62− display_order = 1
63− )]
64− Start(MigrateOptions),
65−
66− #[clap(about = "Completes an in-progress migration", display_order = 2)]
67− Complete(ConnectionOptions),
24+ Remove(ConnectionOptions),
68−
69− #[clap(
70− about = "Aborts an in-progress migration without losing any data",
71− display_order = 3
72− )]
73 Abort(ConnectionOptions),
25 Abort(ConnectionOptions),
26+ GenerateSchemaQuery(FindMigrationsOptions),
74}
27}
75
28
76#[derive(Args)]
29#[derive(Args)]
77struct MigrateOptions {
30struct MigrateOptions {
78− // Some comment
79 #[clap(long, short)]
31 #[clap(long, short)]
80 complete: bool,
32 complete: bool,
81 #[clap(flatten)]
33 #[clap(flatten)]
@@ -106,35 +58,43 @@ struct FindMigrationsOptions {
106 dirs: Vec<String>,
58 dirs: Vec<String>,
107}
59}
108
60
109−fn main() -> anyhow::Result<()> {
61+fn main() {
110 let opts: Opts = Opts::parse();
62 let opts: Opts = Opts::parse();
63+
111− run(opts)
64+ let result = run(opts);
65+ if let Err(e) = result {
66+ println!("Error: {}", e);
67+ }
112}
68}
113
69
114fn run(opts: Opts) -> anyhow::Result<()> {
70fn run(opts: Opts) -> anyhow::Result<()> {
115 match opts.cmd {
71 match opts.cmd {
116− Command::Migration(MigrationCommand::Start(opts)) | Command::Migrate(opts) => {
72+ Command::Migrate(opts) => {
117 let mut reshape = reshape_from_connection_options(&opts.connection_options)?;
73 let mut reshape = reshape_from_connection_options(&opts.connection_options)?;
118 let migrations = find_migrations(&opts.find_migrations_options)?;
74 let migrations = find_migrations(&opts.find_migrations_options)?;
119 reshape.migrate(migrations)?;
75 reshape.migrate(migrations)?;
120
76
121 // Automatically complete migration if --complete flag is set
77 // Automatically complete migration if --complete flag is set
122 if opts.complete {
78 if opts.complete {
123− reshape.complete()?;
79+ reshape.complete_migration()?;
124 }
80 }
125
81
126 Ok(())
82 Ok(())
127 }
83 }
128− Command::Migration(MigrationCommand::Complete(opts)) | Command::Complete(opts) => {
84+ Command::Complete(opts) => {
85+ let mut reshape = reshape_from_connection_options(&opts)?;
86+ reshape.complete_migration()
87+ }
88+ Command::Remove(opts) => {
129 let mut reshape = reshape_from_connection_options(&opts)?;
89 let mut reshape = reshape_from_connection_options(&opts)?;
130− reshape.complete()
90+ reshape.remove()
131 }
91 }
132− Command::Migration(MigrationCommand::Abort(opts)) | Command::Abort(opts) => {
92+ Command::Abort(opts) => {
133 let mut reshape = reshape_from_connection_options(&opts)?;
93 let mut reshape = reshape_from_connection_options(&opts)?;
134 reshape.abort()
94 reshape.abort()
135 }
95 }
136− Command::SchemaQuery(opts) | Command::GenerateSchemaQuery(opts) => {
96+ Command::GenerateSchemaQuery(find_migrations_options) => {
137− let migrations = find_migrations(&opts)?;
97+ let migrations = find_migrations(&find_migrations_options)?;
138 let query = migrations
98 let query = migrations
139 .last()
99 .last()
140 .map(|migration| reshape::schema_query_for_migration(&migration.name));
100 .map(|migration| reshape::schema_query_for_migration(&migration.name));
@@ -146,42 +106,20 @@ fn run(opts: Opts) -> anyhow::Result<()> {
146}
106}
147
107
148fn reshape_from_connection_options(opts: &ConnectionOptions) -> anyhow::Result<Reshape> {
108fn reshape_from_connection_options(opts: &ConnectionOptions) -> anyhow::Result<Reshape> {
149− // Load environment variables from .env file if it exists
150− dotenv::dotenv().ok();
151−
152− let url_env = std::env::var("DB_URL").ok();
109+ let env_url = std::env::var("POSTGRES_URL").ok();
153− let url = url_env.as_ref().or_else(|| opts.url.as_ref());
110+ let url = env_url.as_ref().or(opts.url.as_ref());
154
111
155− // Use the connection URL if it has been set
112+ match url {
156− if let Some(url) = url {
157− return Reshape::new(url);
113+ Some(url) => Reshape::new(&url),
114+ None => Reshape::new_with_options(&opts.host, opts.port, &opts.username, &opts.password),
158 }
115 }
159−
160− let host_env = std::env::var("DB_HOST").ok();
161− let host = host_env.as_ref().unwrap_or_else(|| &opts.host);
162−
163− let port = std::env::var("DB_PORT")
164− .ok()
165− .and_then(|port| port.parse::<u16>().ok())
166− .unwrap_or(opts.port);
167−
168− let username_env = std::env::var("DB_USERNAME").ok();
169− let username = username_env.as_ref().unwrap_or_else(|| &opts.username);
170−
171− let password_env = std::env::var("DB_PASSWORD").ok();
172− let password = password_env.as_ref().unwrap_or_else(|| &opts.password);
173−
174− let database_env = std::env::var("DB_NAME").ok();
175− let database = database_env.as_ref().unwrap_or_else(|| &opts.database);
176−
177− Reshape::new_with_options(host, port, database, username, password)
178}
116}
179
117
180fn find_migrations(opts: &FindMigrationsOptions) -> anyhow::Result<Vec<Migration>> {
118fn find_migrations(opts: &FindMigrationsOptions) -> anyhow::Result<Vec<Migration>> {
181 let search_paths = opts
119 let search_paths = opts
182 .dirs
120 .dirs
183 .iter()
121 .iter()
184− .map(Path::new)
122+ .map(|path| Path::new(path))
185 // Filter out all directories that don't exist
123 // Filter out all directories that don't exist
186 .filter(|path| path.exists());
124 .filter(|path| path.exists());
187
125
@@ -196,13 +134,7 @@ fn find_migrations(opts: &FindMigrationsOptions) -> anyhow::Result<Vec<Migration
196 }
134 }
197
135
198 // Sort all files by their file names (without extension)
136 // Sort all files by their file names (without extension)
199− // The files are sorted naturally, e.g. "1_test_migration" < "10_test_migration"
137+ file_paths.sort_unstable_by_key(|path| path.as_path().file_stem().unwrap().to_os_string());
200− file_paths.sort_unstable_by(|path1, path2| {
201− let file1 = path1.as_path().file_stem().unwrap().to_str().unwrap();
202− let file2 = path2.as_path().file_stem().unwrap().to_str().unwrap();
203−
204− lexical_sort::natural_cmp(file1, file2)
205− });
206
138
207 file_paths
139 file_paths
208 .iter()
140 .iter()
@@ -218,10 +150,7 @@ fn find_migrations(opts: &FindMigrationsOptions) -> anyhow::Result<Vec<Migration
218 .map(|result| {
150 .map(|result| {
219 result.and_then(|(path, data)| {
151 result.and_then(|(path, data)| {
220 let extension = path.extension().and_then(|ext| ext.to_str()).unwrap();
152 let extension = path.extension().and_then(|ext| ext.to_str()).unwrap();
221− let file_migration =
222− decode_migration_file(&data, extension).with_context(|| {
153+ let file_migration = decode_migration_file(&data, extension)?;
223− format!("failed to parse migration file {}", path.display())
224− })?;
225
154
226 let file_name = path.file_stem().and_then(|name| name.to_str()).unwrap();
155 let file_name = path.file_stem().and_then(|name| name.to_str()).unwrap();
227 Ok(Migration {
156 Ok(Migration {
src/migrations/add_column.rs+107−313
@@ -1,40 +1,16 @@
1−use super::{common, Action, Column, MigrationContext};
1+use super::{common, Action, Column, Context};
2−use crate::{
3− db::{Conn, Transaction},
4− schema::Schema,
2+use crate::{db::Conn, schema::Schema};
5−};
6−use anyhow::{bail, Context};
7use serde::{Deserialize, Serialize};
3use serde::{Deserialize, Serialize};
8
4
9#[derive(Serialize, Deserialize, Debug)]
5#[derive(Serialize, Deserialize, Debug)]
10pub struct AddColumn {
6pub struct AddColumn {
11 pub table: String,
7 pub table: String,
8+ pub up: Option<String>,
12 pub column: Column,
9 pub column: Column,
13− pub up: Option<Transformation>,
14−}
15−
16−#[derive(Serialize, Deserialize, Debug)]
17−#[serde(untagged)]
18−pub enum Transformation {
19− Simple(String),
20− Update {
21− table: String,
22− value: String,
23− r#where: String,
24− },
25}
10}
26
11
27impl AddColumn {
12impl AddColumn {
28− fn temp_column_name(&self, ctx: &MigrationContext) -> String {
29− format!(
30− "{}_temp_column_{}_{}",
31− ctx.prefix(),
32− self.table,
33− self.column.name,
34− )
35− }
36−
37− fn trigger_name(&self, ctx: &MigrationContext) -> String {
13+ fn trigger_name(&self, ctx: &Context) -> String {
38 format!(
14 format!(
39 "{}_add_column_{}_{}",
15 "{}_add_column_{}_{}",
40 ctx.prefix(),
16 ctx.prefix(),
@@ -43,16 +19,7 @@ impl AddColumn {
43 )
19 )
44 }
20 }
45
21
46− fn reverse_trigger_name(&self, ctx: &MigrationContext) -> String {
47− format!(
48− "{}_add_column_{}_{}_rev",
49− ctx.prefix(),
50− self.table,
51− self.column.name
52− )
53− }
54−
55− fn not_null_constraint_name(&self, ctx: &MigrationContext) -> String {
22+ fn not_null_constraint_name(&self, ctx: &Context) -> String {
56 format!(
23 format!(
57 "{}_add_column_not_null_{}_{}",
24 "{}_add_column_not_null_{}_{}",
58 ctx.prefix(),
25 ctx.prefix(),
@@ -71,17 +38,11 @@ impl Action for AddColumn {
71 )
38 )
72 }
39 }
73
40
74− fn run(
41+ fn run(&self, ctx: &Context, db: &mut dyn Conn, schema: &Schema) -> anyhow::Result<()> {
75− &self,
76− ctx: &MigrationContext,
77− db: &mut dyn Conn,
78− schema: &Schema,
79− ) -> anyhow::Result<()> {
80 let table = schema.get_table(db, &self.table)?;
42 let table = schema.get_table(db, &self.table)?;
81− let temp_column_name = self.temp_column_name(ctx);
82
43
83 let mut definition_parts = vec![
44 let mut definition_parts = vec![
84− format!("\"{}\"", temp_column_name.to_string()),
45+ self.column.name.to_string(),
85 self.column.data_type.to_string(),
46 self.column.data_type.to_string(),
86 ];
47 ];
87
48
@@ -97,198 +58,63 @@ impl Action for AddColumn {
97
58
98 // Add column as NOT NULL
59 // Add column as NOT NULL
99 let query = format!(
60 let query = format!(
100− r#"
61+ "
101− ALTER TABLE "{table}"
62+ ALTER TABLE {table}
102 ADD COLUMN IF NOT EXISTS {definition};
63 ADD COLUMN IF NOT EXISTS {definition};
103− "#,
64+ ",
104 table = self.table,
65 table = self.table,
105 definition = definition_parts.join(" "),
66 definition = definition_parts.join(" "),
106 );
67 );
107− db.run(&query).context("failed to add column")?;
68+ db.run(&query)?;
108−
109− let declarations: Vec<String> = table
110− .columns
111− .iter()
112− .map(|column| {
113− format!(
114− "\"{alias}\" public.{table}.{real_name}%TYPE := NEW.{real_name};",
115− table = table.real_name,
116− alias = column.name,
117− real_name = column.real_name,
118− )
119− })
120− .collect();
121
69
122 if let Some(up) = &self.up {
70 if let Some(up) = &self.up {
123− if let Transformation::Simple(up) = up {
124− // Add triggers to fill in values as they are inserted/updated
125− let query = format!(
126− r#"
127− CREATE OR REPLACE FUNCTION {trigger_name}()
128− RETURNS TRIGGER AS $$
129− BEGIN
130− IF NOT reshape.is_new_schema() THEN
131− DECLARE
132− {declarations}
133− BEGIN
134− NEW."{temp_column_name}" = {up};
135− END;
136− END IF;
137− RETURN NEW;
138− END
139− $$ language 'plpgsql';
140−
141− DROP TRIGGER IF EXISTS "{trigger_name}" ON "{table}";
142− CREATE TRIGGER "{trigger_name}" BEFORE UPDATE OR INSERT ON "{table}" FOR EACH ROW EXECUTE PROCEDURE {trigger_name}();
143− "#,
144− temp_column_name = temp_column_name,
145− trigger_name = self.trigger_name(ctx),
146− up = up,
147− table = self.table,
148− declarations = declarations.join("\n"),
149− );
150− db.run(&query).context("failed to create up trigger")?;
151−
152− // Backfill values in batches
153− common::batch_touch_rows(db, &table.real_name, Some(&temp_column_name))
154− .context("failed to batch update existing rows")?;
155− }
156−
157− if let Transformation::Update {
158− table: from_table,
159− value,
160− r#where,
161− } = up
162− {
163− let existing_schema_name = match &ctx.existing_schema_name {
164− Some(name) => name,
165− None => bail!("can't use update without previous migration"),
166− };
167−
168− let from_table = schema.get_table(db, &from_table)?;
71+ let table = schema.get_table(db, &self.table)?;
169−
72+
170− let from_table_assignments: Vec<String> = from_table
73+ let declarations: Vec<String> = table
171− .columns
74+ .columns
172− .iter()
75+ .iter()
173− .map(|column| {
76+ .map(|column| {
174− format!(
175− "{table}.{alias} = NEW.{real_name};",
176− table = from_table.name,
177− alias = column.name,
178− real_name = column.real_name,
179− )
180− })
181− .collect();
182−
183− // Add triggers to fill in values as they are inserted/updated
184− let query = format!(
77+ format!(
185− r#"
78+ "{alias} public.{table}.{real_name}%TYPE := NEW.{real_name};",
186− CREATE OR REPLACE FUNCTION {trigger_name}()
187− RETURNS TRIGGER AS $$
188− #variable_conflict use_variable
189− BEGIN
190− IF NOT reshape.is_new_schema() THEN
191− DECLARE
192− {from_table} migration_{existing_schema_name}.{from_table}%ROWTYPE;
193− BEGIN
194− {assignments}
195−
196− -- Don't trigger reverse trigger when making this update
197− perform set_config('reshape.disable_triggers', 'TRUE', TRUE);
198−
199− UPDATE public."{changed_table_real}"
200− SET "{temp_column_name}" = {value}
201− WHERE {where};
202−
203− perform set_config('reshape.disable_triggers', '', TRUE);
204− END;
205− END IF;
206− RETURN NEW;
207− END
208− $$ language 'plpgsql';
209−
210− DROP TRIGGER IF EXISTS "{trigger_name}" ON "{from_table_real}";
211− CREATE TRIGGER "{trigger_name}" BEFORE UPDATE OR INSERT ON "{from_table_real}" FOR EACH ROW EXECUTE PROCEDURE {trigger_name}();
212− "#,
213− assignments = from_table_assignments.join("\n"),
214− changed_table_real = table.real_name,
215− from_table = from_table.name,
216− from_table_real = from_table.real_name,
217− trigger_name = self.trigger_name(ctx),
218− // declarations = from_table_declarations.join("\n"),
219− temp_column_name = temp_column_name,
220− );
221− db.run(&query).context("failed to create up trigger")?;
222−
223− let from_table_columns = from_table
224− .columns
225− .iter()
226− .map(|column| format!("{} as {}", column.real_name, column.name))
227− .collect::<Vec<String>>()
228− .join(", ");
229−
230− let changed_table_assignments: Vec<String> = table
231− .columns
232− .iter()
233− .map(|column| {
234− format!(
235− "{table}.{alias} := NEW.{real_name};",
236− table = table.name,
79+ table = table.real_name,
237− alias = column.name,
80+ alias = column.name,
238− real_name = column.real_name,
81+ real_name = column.real_name,
239− )
82+ )
240− })
83+ })
241− .collect();
84+ .collect();
242−
85+
243− // Add triggers to fill in values as they are inserted/updated
86+ // Add triggers to fill in values as they are inserted/updated
244− let query = format!(
87+ let query = format!(
245− r#"
88+ "
246− CREATE OR REPLACE FUNCTION {trigger_name}()
89+ CREATE OR REPLACE FUNCTION {trigger_name}()
247− RETURNS TRIGGER AS $$
90+ RETURNS TRIGGER AS $$
248− #variable_conflict use_variable
249− BEGIN
91+ BEGIN
250− IF NOT reshape.is_new_schema() AND NOT current_setting('reshape.disable_triggers', TRUE) = 'TRUE' THEN
92+ IF reshape.is_old_schema() THEN
251− DECLARE
93+ DECLARE
252− {changed_table} migration_{existing_schema_name}.{changed_table}%ROWTYPE;
94+ {declarations}
253− __temp_row migration_{existing_schema_name}.{from_table}%ROWTYPE;
254− BEGIN
255− {changed_table_assignments}
256−
257− SELECT {from_table_columns}
258− INTO __temp_row
259− FROM migration_{existing_schema_name}.{from_table} {from_table}
260− WHERE {where};
261−
262− DECLARE
263− {from_table} migration_{existing_schema_name}.{from_table}%ROWTYPE;
264− BEGIN
95+ BEGIN
265− {from_table} = __temp_row;
96+ NEW.{column_name} = {up};
266− NEW.{temp_column_name} = {value};
267− END;
268− END;
97+ END;
269− END IF;
98+ END IF;
270− RETURN NEW;
99+ RETURN NEW;
271− END
100+ END
272− $$ language 'plpgsql';
101+ $$ language 'plpgsql';
273−
102+
274− DROP TRIGGER IF EXISTS "{trigger_name}" ON "{changed_table_real}";
103+ DROP TRIGGER IF EXISTS {trigger_name} ON {table};
275− CREATE TRIGGER "{trigger_name}" BEFORE UPDATE OR INSERT ON "{changed_table_real}" FOR EACH ROW EXECUTE PROCEDURE {trigger_name}();
104+ CREATE TRIGGER {trigger_name} BEFORE UPDATE OR INSERT ON {table} FOR EACH ROW EXECUTE PROCEDURE {trigger_name}();
276− "#,
105+ ",
277− changed_table_assignments = changed_table_assignments.join("\n"),
106+ column_name = self.column.name,
278− changed_table_real = table.real_name,
279− changed_table = table.name,
280− from_table = from_table.name,
281− trigger_name = self.reverse_trigger_name(ctx),
107+ trigger_name = self.trigger_name(ctx),
282− temp_column_name = temp_column_name,
108+ up = up,
109+ table = self.table,
283− // declarations = declarations.join("\n"),
110+ declarations = declarations.join("\n"),
284− );
111+ );
285− db.run(&query)
112+ db.run(&query)?;
286− .context("failed to create reverse up trigger")?;
113+ }
287
114
288− // Backfill values in batches by touching the from table
115+ // Backfill values in batches
116+ if self.up.is_some() {
289− common::batch_touch_rows(db, &from_table.real_name, None)
117+ common::batch_touch_rows(db, &table.real_name, &self.column.name)?;
290− .context("failed to batch update existing rows")?;
291− }
292 }
118 }
293
119
294 // Add a temporary NOT NULL constraint if the column shouldn't be nullable.
120 // Add a temporary NOT NULL constraint if the column shouldn't be nullable.
@@ -297,134 +123,102 @@ impl Action for AddColumn {
297 // Thanks to this, we can set the full column as NOT NULL later with minimal locking.
123 // Thanks to this, we can set the full column as NOT NULL later with minimal locking.
298 if !self.column.nullable {
124 if !self.column.nullable {
299 let query = format!(
125 let query = format!(
300− r#"
126+ "
301− ALTER TABLE "{table}"
127+ ALTER TABLE {table}
302− ADD CONSTRAINT "{constraint_name}"
128+ ADD CONSTRAINT {constraint_name}
303− CHECK ("{column}" IS NOT NULL) NOT VALID
129+ CHECK ({column} IS NOT NULL) NOT VALID
304− "#,
130+ ",
305 table = self.table,
131 table = self.table,
306− constraint_name = self.not_null_constraint_name(ctx),
132+ constraint_name = self.not_null_constraint_name(&ctx),
307− column = temp_column_name,
133+ column = self.column.name,
308 );
134 );
309− db.run(&query)
135+ db.run(&query)?;
310− .context("failed to add NOT NULL constraint")?;
311 }
136 }
312
137
313 Ok(())
138 Ok(())
314 }
139 }
315
140
316− fn complete<'a>(
141+ fn complete(&self, ctx: &Context, db: &mut dyn Conn, _schema: &Schema) -> anyhow::Result<()> {
317− &self,
318− ctx: &MigrationContext,
319− db: &'a mut dyn Conn,
320− ) -> anyhow::Result<Option<Transaction<'a>>> {
321− let mut transaction = db.transaction().context("failed to create transaction")?;
322−
323 // Remove triggers and procedures
142 // Remove triggers and procedures
324 let query = format!(
143 let query = format!(
325− r#"
144+ "
326− DROP FUNCTION IF EXISTS "{trigger_name}" CASCADE;
145+ DROP TRIGGER IF EXISTS {trigger_name} ON {table};
327− DROP FUNCTION IF EXISTS "{reverse_trigger_name}" CASCADE;
146+ DROP FUNCTION IF EXISTS {trigger_name};
328− "#,
147+ ",
148+ table = self.table,
329 trigger_name = self.trigger_name(ctx),
149 trigger_name = self.trigger_name(ctx),
330− reverse_trigger_name = self.reverse_trigger_name(ctx),
331 );
150 );
332− transaction
333− .run(&query)
151+ db.run(&query)?;
334− .context("failed to drop up trigger")?;
335
152
336 // Update column to be NOT NULL if necessary
153 // Update column to be NOT NULL if necessary
337 if !self.column.nullable {
154 if !self.column.nullable {
338 // Validate the temporary constraint (should always be valid).
155 // Validate the temporary constraint (should always be valid).
339 // This performs a sequential scan but does not take an exclusive lock.
156 // This performs a sequential scan but does not take an exclusive lock.
340 let query = format!(
157 let query = format!(
341− r#"
158+ "
342− ALTER TABLE "{table}"
159+ ALTER TABLE {table}
343− VALIDATE CONSTRAINT "{constraint_name}"
160+ VALIDATE CONSTRAINT {constraint_name}
344− "#,
161+ ",
345 table = self.table,
162 table = self.table,
346 constraint_name = self.not_null_constraint_name(ctx),
163 constraint_name = self.not_null_constraint_name(ctx),
347 );
164 );
348− transaction
349− .run(&query)
165+ db.run(&query)?;
350− .context("failed to validate NOT NULL constraint")?;
351
166
352 // Update the column to be NOT NULL.
167 // Update the column to be NOT NULL.
353 // This requires an exclusive lock but since PG 12 it can check
168 // This requires an exclusive lock but since PG 12 it can check
354 // the existing constraint for correctness which makes the lock short-lived.
169 // the existing constraint for correctness which makes the lock short-lived.
355 // Source: https://dba.stackexchange.com/a/268128
170 // Source: https://dba.stackexchange.com/a/268128
356 let query = format!(
171 let query = format!(
357− r#"
172+ "
358− ALTER TABLE "{table}"
173+ ALTER TABLE {table}
359− ALTER COLUMN "{column}" SET NOT NULL
174+ ALTER COLUMN {column} SET NOT NULL
360− "#,
175+ ",
361 table = self.table,
176 table = self.table,
362− column = self.temp_column_name(ctx),
177+ column = self.column.name,
363 );
178 );
364− transaction
365− .run(&query)
179+ db.run(&query)?;
366− .context("failed to set column as NOT NULL")?;
367
180
368 // Drop the temporary constraint
181 // Drop the temporary constraint
369 let query = format!(
182 let query = format!(
370− r#"
183+ "
371− ALTER TABLE "{table}"
184+ ALTER TABLE {table}
372− DROP CONSTRAINT "{constraint_name}"
185+ DROP CONSTRAINT {constraint_name}
373− "#,
186+ ",
374 table = self.table,
187 table = self.table,
375 constraint_name = self.not_null_constraint_name(ctx),
188 constraint_name = self.not_null_constraint_name(ctx),
376 );
189 );
377− transaction
378− .run(&query)
190+ db.run(&query)?;
379− .context("failed to drop NOT NULL constraint")?;
380 }
191 }
381
192
382− // Rename the temporary column to its real name
193+ Ok(())
383− transaction
384− .run(&format!(
385− r#"
386− ALTER TABLE "{table}"
387− RENAME COLUMN "{temp_column_name}" TO "{column_name}"
388− "#,
389− table = self.table,
390− temp_column_name = self.temp_column_name(ctx),
391− column_name = self.column.name,
392− ))
393− .context("failed to rename column to final name")?;
394−
395− Ok(Some(transaction))
396 }
194 }
397
195
398− fn update_schema(&self, ctx: &MigrationContext, schema: &mut Schema) {
196+ fn update_schema(&self, _ctx: &Context, _schema: &mut Schema) -> anyhow::Result<()> {
399− schema.change_table(&self.table, |table_changes| {
197+ Ok(())
400− table_changes.change_column(&self.column.name, |column_changes| {
401− column_changes.set_column(&self.temp_column_name(ctx));
402− })
403− });
404 }
198 }
405
199
406− fn abort(&self, ctx: &MigrationContext, db: &mut dyn Conn) -> anyhow::Result<()> {
200+ fn abort(&self, ctx: &Context, db: &mut dyn Conn) -> anyhow::Result<()> {
407− // Remove column
201+ // Remove triggers and procedures
408 let query = format!(
202 let query = format!(
409− r#"
203+ "
410− ALTER TABLE "{table}"
204+ DROP TRIGGER IF EXISTS {trigger_name} ON {table};
411− DROP COLUMN IF EXISTS "{column}"
205+ DROP FUNCTION IF EXISTS {trigger_name};
412− "#,
206+ ",
413 table = self.table,
207 table = self.table,
414− column = self.temp_column_name(ctx),
208+ trigger_name = self.trigger_name(ctx),
415 );
209 );
416− db.run(&query).context("failed to drop column")?;
210+ db.run(&query)?;
417
211
418− // Remove triggers and procedures
212+ // Remove column
419 let query = format!(
213 let query = format!(
420− r#"
214+ "
421− DROP FUNCTION IF EXISTS "{trigger_name}" CASCADE;
215+ ALTER TABLE {table}
422− DROP FUNCTION IF EXISTS "{reverse_trigger_name}" CASCADE;
216+ DROP COLUMN IF EXISTS {column}
423− "#,
217+ ",
424− trigger_name = self.trigger_name(ctx),
218+ table = self.table,
425− reverse_trigger_name = self.reverse_trigger_name(ctx),
219+ column = self.column.name,
426 );
220 );
427− db.run(&query).context("failed to drop up trigger")?;
221+ db.run(&query)?;
428
222
429 Ok(())
223 Ok(())
430 }
224 }
src/migrations/add_foreign_key.rsdeleted−122
@@ -1,122 +0,0 @@
1−use super::{common::ForeignKey, Action, MigrationContext};
2−use crate::{
3− db::{Conn, Transaction},
4− schema::Schema,
5−};
6−use anyhow::Context;
7−use serde::{Deserialize, Serialize};
8−
9−#[derive(Serialize, Deserialize, Debug)]
10−pub struct AddForeignKey {
11− pub table: String,
12− foreign_key: ForeignKey,
13−}
14−
15−#[typetag::serde(name = "add_foreign_key")]
16−impl Action for AddForeignKey {
17− fn describe(&self) -> String {
18− format!(
19− "Adding foreign key from table \"{}\" to \"{}\"",
20− self.table, self.foreign_key.referenced_table
21− )
22− }
23−
24− fn run(
25− &self,
26− ctx: &MigrationContext,
27− db: &mut dyn Conn,
28− schema: &Schema,
29− ) -> anyhow::Result<()> {
30− let table = schema.get_table(db, &self.table)?;
31− let referenced_table = schema.get_table(db, &self.foreign_key.referenced_table)?;
32−
33− // Add quotes around all column names
34− let columns: Vec<String> = table
35− .real_column_names(&self.foreign_key.columns)
36− .map(|col| format!("\"{}\"", col))
37− .collect();
38− let referenced_columns: Vec<String> = referenced_table
39− .real_column_names(&self.foreign_key.referenced_columns)
40− .map(|col| format!("\"{}\"", col))
41− .collect();
42−
43− // Create foreign key but set is as NOT VALID.
44− // This means the foreign key will be enforced for inserts and updates
45− // but the existing data won't be checked, that would cause a long-lived lock.
46− db.run(&format!(
47− r#"
48− ALTER TABLE "{table}"
49− ADD CONSTRAINT {constraint_name}
50− FOREIGN KEY ({columns})
51− REFERENCES "{referenced_table}" ({referenced_columns})
52− NOT VALID
53− "#,
54− table = table.real_name,
55− constraint_name = self.temp_constraint_name(ctx),
56− columns = columns.join(", "),
57− referenced_table = referenced_table.real_name,
58− referenced_columns = referenced_columns.join(", "),
59− ))
60− .context("failed to create foreign key")?;
61−
62− db.run(&format!(
63− r#"
64− ALTER TABLE "{table}"
65− VALIDATE CONSTRAINT "{constraint_name}"
66− "#,
67− table = table.real_name,
68− constraint_name = self.temp_constraint_name(ctx),
69− ))
70− .context("failed to validate foreign key")?;
71−
72− Ok(())
73− }
74−
75− fn complete<'a>(
76− &self,
77− ctx: &MigrationContext,
78− db: &'a mut dyn Conn,
79− ) -> anyhow::Result<Option<Transaction<'a>>> {
80− db.run(&format!(
81− r#"
82− ALTER TABLE {table}
83− RENAME CONSTRAINT {temp_constraint_name} TO {constraint_name}
84− "#,
85− table = self.table,
86− temp_constraint_name = self.temp_constraint_name(ctx),
87− constraint_name = self.final_constraint_name(),
88− ))
89− .context("failed to rename temporary constraint")?;
90− Ok(None)
91− }
92−
93− fn update_schema(&self, _ctx: &MigrationContext, _schema: &mut Schema) {}
94−
95− fn abort(&self, ctx: &MigrationContext, db: &mut dyn Conn) -> anyhow::Result<()> {
96− db.run(&format!(
97− r#"
98− ALTER TABLE "{table}"
99− DROP CONSTRAINT IF EXISTS "{constraint_name}"
100− "#,
101− table = self.table,
102− constraint_name = self.temp_constraint_name(ctx),
103− ))
104− .context("failed to validate foreign key")?;
105−
106− Ok(())
107− }
108−}
109−
110−impl AddForeignKey {
111− fn temp_constraint_name(&self, ctx: &MigrationContext) -> String {
112− format!("{}_temp_fkey", ctx.prefix())
113− }
114−
115− fn final_constraint_name(&self) -> String {
116− format!(
117− "{table}_{columns}_fkey",
118− table = self.table,
119− columns = self.foreign_key.columns.join("_")
120− )
121− }
122−}
src/migrations/add_index.rs+23−54
@@ -1,88 +1,57 @@
1−use super::{Action, MigrationContext};
1+use super::{Action, Context};
2−use crate::{
3− db::{Conn, Transaction},
4− schema::Schema,
2+use crate::{db::Conn, schema::Schema};
5−};
6−use anyhow::Context;
7use serde::{Deserialize, Serialize};
3use serde::{Deserialize, Serialize};
8
4
9#[derive(Serialize, Deserialize, Debug)]
5#[derive(Serialize, Deserialize, Debug)]
10pub struct AddIndex {
6pub struct AddIndex {
11 pub table: String,
7 pub table: String,
12− pub index: Index,
13−}
14−
15−#[derive(Serialize, Deserialize, Clone, Debug)]
16−pub struct Index {
17 pub name: String,
8 pub name: String,
18 pub columns: Vec<String>,
9 pub columns: Vec<String>,
19− #[serde(default)]
20− pub unique: bool,
21− #[serde(rename = "type")]
22− pub index_type: Option<String>,
23}
10}
24
11
25#[typetag::serde(name = "add_index")]
12#[typetag::serde(name = "add_index")]
26impl Action for AddIndex {
13impl Action for AddIndex {
27 fn describe(&self) -> String {
14 fn describe(&self) -> String {
28− format!(
29− "Adding index \"{}\" to table \"{}\"",
15+ format!("Adding index \"{}\" to table \"{}\"", self.name, self.table)
30− self.index.name, self.table
31− )
32 }
16 }
33
17
34− fn run(
18+ fn run(&self, _ctx: &Context, db: &mut dyn Conn, schema: &Schema) -> anyhow::Result<()> {
35− &self,
36− _ctx: &MigrationContext,
37− db: &mut dyn Conn,
38− schema: &Schema,
39− ) -> anyhow::Result<()> {
40 let table = schema.get_table(db, &self.table)?;
19 let table = schema.get_table(db, &self.table)?;
41
20
42 let column_real_names: Vec<String> = table
21 let column_real_names: Vec<String> = table
43 .columns
22 .columns
44 .iter()
23 .iter()
45− .filter(|column| self.index.columns.contains(&column.name))
24+ .filter(|column| self.columns.contains(&column.name))
46− .map(|column| format!("\"{}\"", column.real_name))
25+ .map(|column| column.real_name.to_string())
47 .collect();
26 .collect();
48
27
49− let unique = if self.index.unique { "UNIQUE" } else { "" };
50− let index_type_def = if let Some(index_type) = &self.index.index_type {
51− format!("USING {index_type}")
52− } else {
53− "".to_string()
54− };
55−
56 db.run(&format!(
28 db.run(&format!(
57− r#"
29+ "
58− CREATE {unique} INDEX CONCURRENTLY "{name}" ON "{table}" {index_type_def} ({columns})
30+ CREATE INDEX CONCURRENTLY {name} ON {table} ({columns})
59− "#,
31+ ",
60− name = self.index.name,
32+ name = self.name,
61 table = self.table,
33 table = self.table,
62 columns = column_real_names.join(", "),
34 columns = column_real_names.join(", "),
63− ))
35+ ))?;
64− .context("failed to create index")?;
65 Ok(())
36 Ok(())
66 }
37 }
67
38
68− fn complete<'a>(
39+ fn complete(&self, _ctx: &Context, _db: &mut dyn Conn, _schema: &Schema) -> anyhow::Result<()> {
69− &self,
70− _ctx: &MigrationContext,
71− _db: &'a mut dyn Conn,
72− ) -> anyhow::Result<Option<Transaction<'a>>> {
73− Ok(None)
40+ Ok(())
74 }
41 }
75
42
76− fn update_schema(&self, _ctx: &MigrationContext, _schema: &mut Schema) {}
43+ fn update_schema(&self, _ctx: &Context, _schema: &mut Schema) -> anyhow::Result<()> {
44+ Ok(())
45+ }
77
46
78− fn abort(&self, _ctx: &MigrationContext, db: &mut dyn Conn) -> anyhow::Result<()> {
47+ fn abort(&self, _ctx: &Context, db: &mut dyn Conn) -> anyhow::Result<()> {
79 db.run(&format!(
48 db.run(&format!(
80− r#"
49+ "
81− DROP INDEX CONCURRENTLY IF EXISTS "{name}"
50+ DROP INDEX {name} ON {table}
82− "#,
51+ ",
83− name = self.index.name,
52+ name = self.name,
84− ))
53+ table = self.table,
85− .context("failed to drop index")?;
54+ ))?;
86 Ok(())
55 Ok(())
87 }
56 }
88}
57}
src/migrations/alter_column.rs+208−321
@@ -1,10 +1,6 @@
1−use super::{Action, MigrationContext};
1+use super::{Action, Context};
2−use crate::{
3− db::{Conn, Transaction},
4− migrations::common,
2+use crate::{db::Conn, migrations::common, schema::Schema};
5− schema::Schema,
6−};
7−use anyhow::{anyhow, Context};
3+use anyhow::anyhow;
8use serde::{Deserialize, Serialize};
4use serde::{Deserialize, Serialize};
9
5
10#[derive(Serialize, Deserialize, Debug)]
6#[derive(Serialize, Deserialize, Debug)]
@@ -13,31 +9,63 @@ pub struct AlterColumn {
13 pub column: String,
9 pub column: String,
14 pub up: Option<String>,
10 pub up: Option<String>,
15 pub down: Option<String>,
11 pub down: Option<String>,
16− #[serde(default)]
17 pub changes: ColumnChanges,
12 pub changes: ColumnChanges,
18}
13}
19
14
20−#[derive(Serialize, Deserialize, Default, Debug)]
15+#[derive(Serialize, Deserialize, Debug)]
21pub struct ColumnChanges {
16pub struct ColumnChanges {
22 pub name: Option<String>,
17 pub name: Option<String>,
23 #[serde(rename = "type")]
18 #[serde(rename = "type")]
24 pub data_type: Option<String>,
19 pub data_type: Option<String>,
25 pub nullable: Option<bool>,
20 pub nullable: Option<bool>,
26− pub default: Option<String>,
27}
21}
28
22
23+impl AlterColumn {
24+ fn temporary_column_name(&self, ctx: &Context) -> String {
25+ format!("{}_new_{}", ctx.prefix(), self.column)
26+ }
27+
28+ fn up_trigger_name(&self, ctx: &Context) -> String {
29+ format!(
30+ "{}_alter_column_up_trigger_{}_{}",
31+ ctx.prefix(),
32+ self.table,
33+ self.column
34+ )
35+ }
36+
37+ fn down_trigger_name(&self, ctx: &Context) -> String {
38+ format!(
39+ "{}_alter_column_down_trigger_{}_{}",
40+ ctx.prefix_inverse(),
41+ self.table,
42+ self.column
43+ )
44+ }
45+
46+ fn not_null_constraint_name(&self, ctx: &Context) -> String {
47+ format!(
48+ "{}_alter_column_temporary_not_null_{}_{}",
49+ ctx.prefix(),
50+ self.table,
51+ self.column
52+ )
53+ }
54+
55+ fn can_short_circuit(&self) -> bool {
56+ self.changes.name.is_some()
57+ && self.changes.data_type.is_none()
58+ && self.changes.nullable.is_none()
59+ }
60+}
61+
29−#[typetag::serde(name = "alter_column")]
62+#[typetag::serde(name = "uppercase_column")]
30impl Action for AlterColumn {
63impl Action for AlterColumn {
31 fn describe(&self) -> String {
64 fn describe(&self) -> String {
32 format!("Altering column \"{}\" on \"{}\"", self.column, self.table)
65 format!("Altering column \"{}\" on \"{}\"", self.column, self.table)
33 }
66 }
34
67
35− fn run(
68+ fn run(&self, ctx: &Context, db: &mut dyn Conn, schema: &Schema) -> anyhow::Result<()> {
36− &self,
37− ctx: &MigrationContext,
38− db: &mut dyn Conn,
39− schema: &Schema,
40− ) -> anyhow::Result<()> {
41 // If we are only changing the name of a column, we don't have to do anything at this stage
69 // If we are only changing the name of a column, we don't have to do anything at this stage
42 // We'll set the new schema to point to the old column. When the migration is completed,
70 // We'll set the new schema to point to the old column. When the migration is completed,
43 // we rename the actual column.
71 // we rename the actual column.
@@ -45,44 +73,37 @@ impl Action for AlterColumn {
45 return Ok(());
73 return Ok(());
46 }
74 }
47
75
76+ // If we couldn't short circuit, then we need up and down functions
77+ let (up, down) = match (&self.up, &self.down) {
78+ (Some(up), Some(down)) => (up, down),
79+ _ => return Err(anyhow!("missing up or down values")),
80+ };
81+
48 let table = schema.get_table(db, &self.table)?;
82 let table = schema.get_table(db, &self.table)?;
49
83
50 let column = table
84 let column = table
85+ .columns
86+ .iter()
51− .get_column(&self.column)
87+ .find(|column| column.name == self.column)
52− .ok_or_else(|| anyhow!("no such column {} exists", self.column))?;
88+ .ok_or_else(|| anyhow!("no such column exists"))?;
53−
54− let temporary_column_name = self.temporary_column_name(ctx);
55− let temporary_column_type = self.changes.data_type.as_ref().unwrap_or(&column.data_type);
56−
57− // Add temporary, nullable column
58− let mut temp_column_definition_parts: Vec<&str> =
59− vec![&temporary_column_name, temporary_column_type];
60
89
61− // Use either new default value or existing one if one exists
90+ let temporary_column_type = self
62− let default_value = self
63 .changes
91 .changes
64− .default
92+ .data_type
65 .as_ref()
93 .as_ref()
66− .or_else(|| column.default.as_ref());
94+ .unwrap_or_else(|| &column.data_type);
67− if let Some(default) = default_value {
68− temp_column_definition_parts.push("DEFAULT");
69− temp_column_definition_parts.push(default);
70− }
71
95
96+ // Add temporary, nullable column
72 let query = format!(
97 let query = format!(
73− r#"
98+ "
74− ALTER TABLE "{table}"
99+ ALTER TABLE {table}
75− ADD COLUMN IF NOT EXISTS {temp_column_definition}
100+ ADD COLUMN IF NOT EXISTS {temp_column} {temp_column_type};
76− "#,
101+ ",
77 table = self.table,
102 table = self.table,
78− temp_column_definition = temp_column_definition_parts.join(" "),
103+ temp_column = self.temporary_column_name(ctx),
104+ temp_column_type = temporary_column_type,
79 );
105 );
80− db.run(&query).context("failed to add temporary column")?;
106+ db.run(&query)?;
81−
82− // If up or down wasn't provided, we default to simply moving the value over.
83− // This is the correct behaviour for example when only changing the default value.
84− let up = self.up.as_ref().unwrap_or(&self.column);
85− let down = self.down.as_ref().unwrap_or(&self.column);
86
107
87 let declarations: Vec<String> = table
108 let declarations: Vec<String> = table
88 .columns
109 .columns
@@ -98,44 +119,45 @@ impl Action for AlterColumn {
98 })
119 })
99 .collect();
120 .collect();
100
121
122+ // Add triggers to fill in values as they are inserted/updated
101 let query = format!(
123 let query = format!(
102− r#"
124+ "
103− CREATE OR REPLACE FUNCTION {up_trigger}()
125+ CREATE OR REPLACE FUNCTION {up_trigger}()
104− RETURNS TRIGGER AS $$
126+ RETURNS TRIGGER AS $$
127+ BEGIN
128+ IF reshape.is_old_schema() THEN
129+ DECLARE
130+ {declarations}
131+ {existing_column} public.{table}.{existing_column_real}%TYPE := NEW.{existing_column_real};
105− BEGIN
132+ BEGIN
133+ NEW.{temp_column} = {up};
134+ END;
135+ END IF;
136+ RETURN NEW;
137+ END
138+ $$ language 'plpgsql';
139+
140+ DROP TRIGGER IF EXISTS {up_trigger} ON {table};
141+ CREATE TRIGGER {up_trigger} BEFORE INSERT OR UPDATE ON {table} FOR EACH ROW EXECUTE PROCEDURE {up_trigger}();
142+
143+ CREATE OR REPLACE FUNCTION {down_trigger}()
144+ RETURNS TRIGGER AS $$
145+ BEGIN
106− IF NOT reshape.is_new_schema() THEN
146+ IF NOT reshape.is_old_schema() THEN
107− DECLARE
147+ DECLARE
108− {declarations}
148+ {declarations}
109− {existing_column} public.{table}.{existing_column_real}%TYPE := NEW.{existing_column_real};
149+ {existing_column} public.{table}.{temp_column}%TYPE := NEW.{temp_column};
110− BEGIN
111− NEW.{temp_column} = {up};
112− END;
113− END IF;
114− RETURN NEW;
115− END
116− $$ language 'plpgsql';
117−
118− DROP TRIGGER IF EXISTS "{up_trigger}" ON "{table}";
119− CREATE TRIGGER "{up_trigger}" BEFORE INSERT OR UPDATE ON "{table}" FOR EACH ROW EXECUTE PROCEDURE {up_trigger}();
120−
121− CREATE OR REPLACE FUNCTION {down_trigger}()
122− RETURNS TRIGGER AS $$
123− BEGIN
150+ BEGIN
124− IF reshape.is_new_schema() THEN
125− DECLARE
126− {declarations}
127− {existing_column} public.{table}.{temp_column}%TYPE := NEW.{temp_column};
128− BEGIN
129− NEW.{existing_column_real} = {down};
151+ NEW.{existing_column_real} = {down};
130− END;
152+ END;
131− END IF;
153+ END IF;
132− RETURN NEW;
154+ RETURN NEW;
133− END
155+ END
134− $$ language 'plpgsql';
156+ $$ language 'plpgsql';
135−
157+
136− DROP TRIGGER IF EXISTS "{down_trigger}" ON "{table}";
158+ DROP TRIGGER IF EXISTS {down_trigger} ON {table};
137− CREATE TRIGGER "{down_trigger}" BEFORE INSERT OR UPDATE ON "{table}" FOR EACH ROW EXECUTE PROCEDURE {down_trigger}();
159+ CREATE TRIGGER {down_trigger} BEFORE INSERT OR UPDATE ON {table} FOR EACH ROW EXECUTE PROCEDURE {down_trigger}();
138− "#,
160+ ",
139 existing_column = &self.column,
161 existing_column = &self.column,
140 existing_column_real = column.real_name,
162 existing_column_real = column.real_name,
141 temp_column = self.temporary_column_name(ctx),
163 temp_column = self.temporary_column_name(ctx),
@@ -146,315 +168,180 @@ impl Action for AlterColumn {
146 down_trigger = self.down_trigger_name(ctx),
168 down_trigger = self.down_trigger_name(ctx),
147 declarations = declarations.join("\n"),
169 declarations = declarations.join("\n"),
148 );
170 );
149− db.run(&query)
171+ db.run(&query)?;
150− .context("failed to create up and down triggers")?;
151
172
152 // Backfill values in batches by touching the previous column
173 // Backfill values in batches by touching the previous column
153− common::batch_touch_rows(db, &table.real_name, Some(&column.real_name))
174+ common::batch_touch_rows(db, &table.real_name, &column.real_name)?;
154− .context("failed to batch update existing rows")?;
155−
156− // Duplicate any indices to the temporary column
157− let indices = common::get_indices_for_column(db, &table.real_name, &column.real_name)?;
158− for index in indices {
159− let index_columns: Vec<String> = common::get_index_columns(db, &index.name)?
160− .into_iter()
161− .map(|idx_column| {
162− // Replace column with temporary column for new index
163− if idx_column == column.real_name {
164− temporary_column_name.to_string()
165− } else {
166− idx_column
167− }
168− })
169− .collect();
170− let temp_index_name = self.temp_index_name(ctx, index.oid);
171−
172− let unique_def = if index.unique { "UNIQUE" } else { "" };
173−
174− db.query(&format!(
175− r#"
176− CREATE {unique_def} INDEX CONCURRENTLY IF NOT EXISTS "{new_index_name}" ON "{table}" USING {index_type} ({columns})
177− "#,
178− new_index_name = temp_index_name,
179− table = table.real_name,
180− columns = index_columns.join(", "),
181− index_type = index.index_type,
182− ))
183− .context("failed to create temporary index")?;
184− }
185
175
186 // Add a temporary NOT NULL constraint if the column shouldn't be nullable.
176 // Add a temporary NOT NULL constraint if the column shouldn't be nullable.
187 // This constraint is set as NOT VALID so it doesn't apply to existing rows and
177 // This constraint is set as NOT VALID so it doesn't apply to existing rows and
188 // the existing rows don't need to be scanned under an exclusive lock.
178 // the existing rows don't need to be scanned under an exclusive lock.
189 // Thanks to this, we can set the full column as NOT NULL later with minimal locking.
179 // Thanks to this, we can set the full column as NOT NULL later with minimal locking.
190− if !self.changes.nullable.unwrap_or(column.nullable) {
180+ if !column.nullable {
191 let query = format!(
181 let query = format!(
192− r#"
182+ "
193− ALTER TABLE "{table}"
183+ ALTER TABLE {table}
194− ADD CONSTRAINT "{constraint_name}"
184+ ADD CONSTRAINT {constraint_name}
195− CHECK ("{column}" IS NOT NULL) NOT VALID
185+ CHECK ({column} IS NOT NULL) NOT VALID
196− "#,
186+ ",
197 table = self.table,
187 table = self.table,
198 constraint_name = self.not_null_constraint_name(ctx),
188 constraint_name = self.not_null_constraint_name(ctx),
199 column = self.temporary_column_name(ctx),
189 column = self.temporary_column_name(ctx),
200 );
190 );
201− db.run(&query)
191+ db.run(&query)?;
202− .context("failed to add NOT NULL constraint")?;
203 }
192 }
204
193
205 Ok(())
194 Ok(())
206 }
195 }
207
196
208− fn complete<'a>(
197+ fn complete(&self, ctx: &Context, db: &mut dyn Conn, schema: &Schema) -> anyhow::Result<()> {
209− &self,
210− ctx: &MigrationContext,
211− db: &'a mut dyn Conn,
212− ) -> anyhow::Result<Option<Transaction<'a>>> {
213 if self.can_short_circuit() {
198 if self.can_short_circuit() {
214 if let Some(new_name) = &self.changes.name {
199 if let Some(new_name) = &self.changes.name {
215 let query = format!(
200 let query = format!(
216− r#"
201+ "
217− ALTER TABLE "{table}"
202+ ALTER TABLE {table}
218− RENAME COLUMN "{existing_name}" TO "{new_name}"
203+ RENAME COLUMN {existing_name} TO {new_name}
219− "#,
204+ ",
220 table = self.table,
205 table = self.table,
221 existing_name = self.column,
206 existing_name = self.column,
222 new_name = new_name,
207 new_name = new_name,
223 );
208 );
224− db.run(&query).context("failed to rename column")?;
209+ db.run(&query)?;
225 }
210 }
226− return Ok(None);
211+ return Ok(());
227 }
212 }
228
213
214+ let table = schema.get_table(db, &self.table)?;
215+
216+ let column = table
217+ .columns
218+ .iter()
219+ .find(|column| column.name == self.column)
220+ .ok_or_else(|| anyhow!("no such column exists"))?;
221+ let column_name = self.changes.name.as_deref().unwrap_or(&column.real_name);
222+
223+ // Remove old column
224+ let query = format!(
225+ "
226+ ALTER TABLE {} DROP COLUMN {} CASCADE
227+ ",
228+ self.table, column.real_name
229+ );
230+ db.run(&query)?;
231+
232+ // Rename temporary column
233+ let query = format!(
234+ "
235+ ALTER TABLE {table} RENAME COLUMN {temp_column} TO {name}
236+ ",
237+ table = self.table,
238+ temp_column = self.temporary_column_name(ctx),
239+ name = column_name,
240+ );
241+ db.run(&query)?;
242+
243+ // Remove triggers and procedures
244+ let query = format!(
245+ "
246+ DROP TRIGGER IF EXISTS {up_trigger} ON {table};
247+ DROP FUNCTION IF EXISTS {up_trigger};
248+
249+ DROP TRIGGER IF EXISTS {down_trigger} ON {table};
250+ DROP FUNCTION IF EXISTS {down_trigger};
251+ ",
252+ table = self.table,
253+ up_trigger = self.up_trigger_name(ctx),
254+ down_trigger = self.down_trigger_name(ctx),
255+ );
256+ db.run(&query)?;
257+
229 // Update column to be NOT NULL if necessary
258 // Update column to be NOT NULL if necessary
230− let has_not_null_constraint = !db
259+ if !column.nullable {
231− .query_with_params(
232− "
233− SELECT constraint_name
234− FROM information_schema.constraint_column_usage
235− WHERE constraint_name = $1
236− ",
237− &[&self.not_null_constraint_name(ctx)],
238− )
239− .context("failed to get any NOT NULL constraint")?
240− .is_empty();
241− if has_not_null_constraint {
242 // Validate the temporary constraint (should always be valid).
260 // Validate the temporary constraint (should always be valid).
243 // This performs a sequential scan but does not take an exclusive lock.
261 // This performs a sequential scan but does not take an exclusive lock.
244 let query = format!(
262 let query = format!(
245− r#"
263+ "
246− ALTER TABLE "{table}"
264+ ALTER TABLE {table}
247− VALIDATE CONSTRAINT "{constraint_name}"
265+ VALIDATE CONSTRAINT {constraint_name}
248− "#,
266+ ",
249 table = self.table,
267 table = self.table,
250 constraint_name = self.not_null_constraint_name(ctx),
268 constraint_name = self.not_null_constraint_name(ctx),
251 );
269 );
252− db.run(&query)
270+ db.run(&query)?;
253− .context("failed to validate NOT NULL constraint")?;
254
271
255 // Update the column to be NOT NULL.
272 // Update the column to be NOT NULL.
256 // This requires an exclusive lock but since PG 12 it can check
273 // This requires an exclusive lock but since PG 12 it can check
257 // the existing constraint for correctness which makes the lock short-lived.
274 // the existing constraint for correctness which makes the lock short-lived.
258 // Source: https://dba.stackexchange.com/a/268128
275 // Source: https://dba.stackexchange.com/a/268128
259 let query = format!(
276 let query = format!(
260− r#"
277+ "
261− ALTER TABLE "{table}"
278+ ALTER TABLE {table}
262− ALTER COLUMN "{column}" SET NOT NULL
279+ ALTER COLUMN {column} SET NOT NULL
263− "#,
280+ ",
264 table = self.table,
281 table = self.table,
265− column = self.temporary_column_name(ctx),
282+ column = column_name,
266 );
283 );
267− db.run(&query).context("failed to set column as NOT NULL")?;
284+ db.run(&query)?;
268
285
269 // Drop the temporary constraint
286 // Drop the temporary constraint
270 let query = format!(
287 let query = format!(
271− r#"
288+ "
272− ALTER TABLE "{table}"
289+ ALTER TABLE {table}
273− DROP CONSTRAINT "{constraint_name}"
290+ DROP CONSTRAINT {constraint_name}
274− "#,
291+ ",
275 table = self.table,
292 table = self.table,
276 constraint_name = self.not_null_constraint_name(ctx),
293 constraint_name = self.not_null_constraint_name(ctx),
277 );
294 );
278− db.run(&query)
295+ db.run(&query)?;
279− .context("failed to drop NOT NULL constraint")?;
280− }
281−
282− // Replace old indices with the new temporary ones created for the temporary column
283− let indices = common::get_indices_for_column(db, &self.table, &self.column)?;
284− for current_index in indices {
285− // To keep the index handling idempotent, we need to do the following:
286− // 1. Add a prefix to the existing index
287− // 2. Rename temporary index to its final name
288− // 3. Drop existing index concurrently
289−
290− // Add prefix (if not already added) to existing index
291− let prefix = "__reshape_old";
292− let target_index_name = current_index.name.trim_start_matches(prefix);
293− let old_index_name = format!("{}_{}", prefix, target_index_name);
294− db.query(&format!(
295− r#"
296− ALTER INDEX IF EXISTS "{current_name}" RENAME TO "{new_name}"
297− "#,
298− current_name = target_index_name,
299− new_name = old_index_name,
300− ))
301− .context("failed to rename old index")?;
302−
303− // Rename temporary index to real name
304− let temp_index_name = self.temp_index_name(ctx, current_index.oid);
305− db.query(&format!(
306− r#"
307− ALTER INDEX IF EXISTS "{temp_index_name}" RENAME TO "{target_index_name}"
308− "#,
309− temp_index_name = temp_index_name,
310− target_index_name = target_index_name,
311− ))
312− .context("failed to rename temporary index")?;
313−
314− // Drop old index concurrently
315− db.query(&format!(
316− r#"
317− DROP INDEX CONCURRENTLY IF EXISTS "{old_index_name}"
318− "#,
319− old_index_name = old_index_name,
320− ))
321− .context("failed to drop old index")?;
322 }
296 }
323
297
324− // Remove old column
325− let query = format!(
326− r#"
327− ALTER TABLE "{table}" DROP COLUMN IF EXISTS "{column}" CASCADE
328− "#,
329− table = self.table,
330− column = self.column,
331− );
332− db.run(&query).context("failed to drop old column")?;
333−
334− // Rename temporary column
335− let column_name = self.changes.name.as_deref().unwrap_or(&self.column);
336− let query = format!(
337− r#"
338− ALTER TABLE "{table}" RENAME COLUMN "{temp_column}" TO "{name}"
339− "#,
340− table = self.table,
341− temp_column = self.temporary_column_name(ctx),
342− name = column_name,
343− );
344− db.run(&query)
345− .context("failed to rename temporary column")?;
346−
347− // Remove triggers and procedures
348− let query = format!(
349− r#"
350− DROP TRIGGER IF EXISTS "{up_trigger}" ON "{table}";
351− DROP FUNCTION IF EXISTS "{up_trigger}";
352−
353− DROP TRIGGER IF EXISTS "{down_trigger}" ON "{table}";
354− DROP FUNCTION IF EXISTS "{down_trigger}";
355− "#,
356− table = self.table,
357− up_trigger = self.up_trigger_name(ctx),
358− down_trigger = self.down_trigger_name(ctx),
359− );
360− db.run(&query)
361− .context("failed to drop up and down triggers")?;
362−
363− Ok(None)
298+ Ok(())
364 }
299 }
365
300
366− fn update_schema(&self, ctx: &MigrationContext, schema: &mut Schema) {
301+ fn update_schema(&self, ctx: &Context, schema: &mut Schema) -> anyhow::Result<()> {
367 // If we are only changing the name of a column, we haven't created a temporary column
302 // If we are only changing the name of a column, we haven't created a temporary column
368 // Instead, we rename the schema column but point it to the old column
303 // Instead, we rename the schema column but point it to the old column
369 if self.can_short_circuit() {
304 if self.can_short_circuit() {
370 if let Some(new_name) = &self.changes.name {
305 if let Some(new_name) = &self.changes.name {
371− schema.change_table(&self.table, |table_changes| {
306+ schema.set_column_alias(&self.table, &self.column, new_name);
372− table_changes.change_column(&self.column, |column_changes| {
307+ println!("Schema is now: {:?}", schema);
373− column_changes.set_name(new_name);
374− });
375− });
376 }
308 }
377
309
378− return;
310+ return Ok(());
379 }
311 }
380
312
381− schema.change_table(&self.table, |table_changes| {
382− table_changes.change_column(&self.column, |column_changes| {
383− column_changes.set_column(&self.temporary_column_name(ctx));
313+ schema.set_column_alias(&self.table, &self.temporary_column_name(ctx), &self.column);
384− });
385− });
386− }
387
314
388− fn abort(&self, ctx: &MigrationContext, db: &mut dyn Conn) -> anyhow::Result<()> {
315+ Ok(())
389− // Safely remove any indices created for the temporary column
316+ }
390− let temp_column_name = self.temporary_column_name(ctx);
391− let indices = common::get_indices_for_column(db, &self.table, &temp_column_name)?;
392− for index in indices {
393− let temp_index_name = self.temp_index_name(ctx, index.oid);
394− db.query(&format!(
395− r#"
396− DROP INDEX CONCURRENTLY IF EXISTS "{index_name}"
397− "#,
398− index_name = temp_index_name,
399− ))?;
400− }
401−
402− // Drop temporary column
403− let query = format!(
404− r#"
405− ALTER TABLE "{table}"
406− DROP COLUMN IF EXISTS "{temp_column}";
407− "#,
408− table = self.table,
409− temp_column = self.temporary_column_name(ctx),
410− );
411− db.run(&query).context("failed to drop temporary column")?;
412
317
318+ fn abort(&self, ctx: &Context, db: &mut dyn Conn) -> anyhow::Result<()> {
413 // Remove triggers and procedures
319 // Remove triggers and procedures
414 let query = format!(
320 let query = format!(
415− r#"
321+ "
416− DROP TRIGGER IF EXISTS "{up_trigger}" ON "{table}";
322+ DROP TRIGGER IF EXISTS {up_trigger} ON {table};
417− DROP FUNCTION IF EXISTS "{up_trigger}";
323+ DROP FUNCTION IF EXISTS {up_trigger};
418
324
419− DROP TRIGGER IF EXISTS "{down_trigger}" ON "{table}";
325+ DROP TRIGGER IF EXISTS {down_trigger} ON {table};
420− DROP FUNCTION IF EXISTS "{down_trigger}";
326+ DROP FUNCTION IF EXISTS {down_trigger};
421− "#,
327+ ",
422 table = self.table,
328 table = self.table,
423 up_trigger = self.up_trigger_name(ctx),
329 up_trigger = self.up_trigger_name(ctx),
424 down_trigger = self.down_trigger_name(ctx),
330 down_trigger = self.down_trigger_name(ctx),
425 );
331 );
426− db.run(&query)
332+ db.run(&query)?;
427− .context("failed to drop up and down triggers")?;
428−
429− Ok(())
430− }
431−}
432−
433−impl AlterColumn {
434− fn temporary_column_name(&self, ctx: &MigrationContext) -> String {
435− format!("{}_new_{}", ctx.prefix(), self.column)
436− }
437−
438− fn up_trigger_name(&self, ctx: &MigrationContext) -> String {
439− format!("{}_alter_column_up_trigger", ctx.prefix())
440− }
441
333
442− fn down_trigger_name(&self, ctx: &MigrationContext) -> String {
334+ // Drop temporary column
443− format!("{}_alter_column_down_trigger", ctx.prefix_inverse())
335+ let query = format!(
444− }
336+ "
445−
337+ ALTER TABLE {table}
446− fn not_null_constraint_name(&self, ctx: &MigrationContext) -> String {
338+ DROP COLUMN IF EXISTS {temp_column};
447− format!("{}_alter_column_temporary", ctx.prefix())
339+ ",
448− }
340+ table = self.table,
449−
341+ temp_column = self.temporary_column_name(ctx),
450− fn temp_index_name(&self, ctx: &MigrationContext, index_oid: u32) -> String {
342+ );
451− format!("{}_alter_column_temp_index_{}", ctx.prefix(), index_oid)
343+ db.run(&query)?;
452− }
453
344
454− fn can_short_circuit(&self) -> bool {
345+ Ok(())
455− self.changes.name.is_some()
456− && self.changes.data_type.is_none()
457− && self.changes.nullable.is_none()
458− && self.changes.default.is_none()
459 }
346 }
460}
347}
src/migrations/common.rs+37−137
@@ -1,17 +1,20 @@
1−use anyhow::anyhow;
2use postgres::types::{FromSql, ToSql};
1use postgres::types::{FromSql, ToSql};
3use serde::{Deserialize, Serialize};
2use serde::{Deserialize, Serialize};
4
3
5use crate::db::Conn;
4use crate::db::Conn;
6
5
7−#[derive(Serialize, Deserialize, Clone, Debug)]
6+#[derive(Serialize, Deserialize, Debug)]
8pub struct Column {
7pub struct Column {
9 pub name: String,
8 pub name: String,
9+
10 #[serde(rename = "type")]
10 #[serde(rename = "type")]
11 pub data_type: String,
11 pub data_type: String,
12+
12 #[serde(default = "nullable_default")]
13 #[serde(default = "nullable_default")]
13 pub nullable: bool,
14 pub nullable: bool,
15+
14 pub default: Option<String>,
16 pub default: Option<String>,
17+
15 pub generated: Option<String>,
18 pub generated: Option<String>,
16}
19}
17
20
@@ -19,13 +22,6 @@ fn nullable_default() -> bool {
19 true
22 true
20}
23}
21
24
22−#[derive(Serialize, Deserialize, Clone, Debug)]
23−pub struct ForeignKey {
24− pub columns: Vec<String>,
25− pub referenced_table: String,
26− pub referenced_columns: Vec<String>,
27−}
28−
29#[derive(Debug)]
25#[derive(Debug)]
30struct PostgresRawValue {
26struct PostgresRawValue {
31 bytes: Vec<u8>,
27 bytes: Vec<u8>,
@@ -69,35 +65,24 @@ impl ToSql for PostgresRawValue {
69 postgres::types::to_sql_checked!();
65 postgres::types::to_sql_checked!();
70}
66}
71
67
72−pub fn batch_touch_rows(
68+pub fn batch_touch_rows(db: &mut dyn Conn, table: &str, column: &str) -> anyhow::Result<()> {
73− db: &mut dyn Conn,
74− table: &str,
75− column: Option<&str>,
76−) -> anyhow::Result<()> {
77 const BATCH_SIZE: u16 = 1000;
69 const BATCH_SIZE: u16 = 1000;
78
70
71+ db.query("SET reshape.is_old_schema = 'YES'")?;
72+
79 let mut cursor: Option<PostgresRawValue> = None;
73 let mut cursor: Option<PostgresRawValue> = None;
80
74
81 loop {
75 loop {
82 let mut params: Vec<&(dyn ToSql + Sync)> = Vec::new();
76 let mut params: Vec<&(dyn ToSql + Sync)> = Vec::new();
83
77
84− let primary_key = get_primary_key_columns_for_table(db, table)?;
78+ let primary_key = get_primary_key_columns_for_table(db, &table)?;
85−
86− // If no column to touch is passed, we default to the first primary key column (just to make some "update")
87− let touched_column = match column {
88− Some(column) => column,
89− None => primary_key.first().unwrap(),
90− };
91−
92 let primary_key_columns = primary_key.join(", ");
79 let primary_key_columns = primary_key.join(", ");
93
80
94 let primary_key_where = primary_key
81 let primary_key_where = primary_key
95 .iter()
82 .iter()
96 .map(|column| {
83 .map(|column| {
97 format!(
84 format!(
98− r#"
99− "{table}"."{column}" = rows."{column}"
85+ "{table}.{column} = rows.{column}",
100− "#,
101 table = table,
86 table = table,
102 column = column,
87 column = column,
103 )
88 )
@@ -107,7 +92,7 @@ pub fn batch_touch_rows(
107
92
108 let returning_columns = primary_key
93 let returning_columns = primary_key
109 .iter()
94 .iter()
110− .map(|column| format!("rows.\"{}\"", column))
95+ .map(|column| format!("rows.{}", column))
111 .collect::<Vec<String>>()
96 .collect::<Vec<String>>()
112 .join(", ");
97 .join(", ");
113
98
@@ -123,25 +108,31 @@ pub fn batch_touch_rows(
123 };
108 };
124
109
125 let query = format!(
110 let query = format!(
126− r#"
111+ "
127− WITH rows AS (
112+ WITH rows AS (
128− SELECT {primary_key_columns}
113+ SELECT {primary_key_columns}
129− FROM public."{table}"
114+ FROM public.{table}
130− {cursor_where}
115+ {cursor_where}
131− ORDER BY {primary_key_columns}
116+ ORDER BY {primary_key_columns}
132− LIMIT {batch_size}
117+ LIMIT {batch_size}
133− ), update AS (
118+ ), update AS (
134− UPDATE public."{table}" "{table}"
119+ UPDATE public.{table}
135− SET "{touched_column}" = "{table}"."{touched_column}"
120+ SET {column} = {column}
136− FROM rows
121+ FROM rows
137− WHERE {primary_key_where}
122+ WHERE {primary_key_where}
138− RETURNING {returning_columns}
123+ RETURNING {returning_columns}
139− )
124+ )
140− SELECT LAST_VALUE(({primary_key_columns})) OVER () AS last_value
125+ SELECT LAST_VALUE(({primary_key_columns})) OVER () AS last_value
141− FROM update
126+ FROM update
142− LIMIT 1
127+ LIMIT 1
143− "#,
128+ ",
129+ table = table,
130+ primary_key_columns = primary_key_columns,
131+ cursor_where = cursor_where,
144 batch_size = BATCH_SIZE,
132 batch_size = BATCH_SIZE,
133+ column = column,
134+ primary_key_where = primary_key_where,
135+ returning_columns = returning_columns,
145 );
136 );
146 let last_value = db
137 let last_value = db
147 .query_with_params(&query, &params)?
138 .query_with_params(&query, &params)?
@@ -155,6 +146,8 @@ pub fn batch_touch_rows(
155 cursor = last_value
146 cursor = last_value
156 }
147 }
157
148
149+ db.query("SET reshape.is_old_schema = ''")?;
150+
158 Ok(())
151 Ok(())
159}
152}
160
153
@@ -180,96 +173,3 @@ fn get_primary_key_columns_for_table(
180
173
181 Ok(primary_key_columns)
174 Ok(primary_key_columns)
182}
175}
183−
184−pub struct Index {
185− pub name: String,
186− pub oid: u32,
187− pub unique: bool,
188− pub index_type: String,
189−}
190−
191−pub fn get_indices_for_column(
192− db: &mut dyn Conn,
193− table: &str,
194− column: &str,
195−) -> anyhow::Result<Vec<Index>> {
196− let indices = db
197− .query(&format!(
198− "
199− SELECT
200− i.relname AS name,
201− i.oid AS oid,
202− ix.indisunique AS unique,
203− am.amname AS type
204− FROM pg_index ix
205− JOIN pg_class t ON t.oid = ix.indrelid
206− JOIN pg_class i ON i.oid = ix.indexrelid
207− JOIN pg_am am ON i.relam = am.oid
208− JOIN pg_attribute a ON
209− a.attrelid = t.oid AND
210− a.attnum = ANY(ix.indkey)
211− WHERE
212− t.relname = '{table}' AND
213− a.attname = '{column}'
214− ",
215− table = table,
216− column = column,
217− ))?
218− .iter()
219− .map(|row| Index {
220− name: row.get("name"),
221− oid: row.get("oid"),
222− unique: row.get("unique"),
223− index_type: row.get("type"),
224− })
225− .collect();
226−
227− Ok(indices)
228−}
229−
230−pub fn get_index_columns(db: &mut dyn Conn, index_name: &str) -> anyhow::Result<Vec<String>> {
231− // Get all columns which are part of the index in order
232− let (table_oid, column_nums) = db
233− .query(&format!(
234− "
235− SELECT t.oid AS table_oid, ix.indkey::INTEGER[] AS columns
236− FROM pg_index ix
237− JOIN pg_class t ON t.oid = ix.indrelid
238− JOIN pg_class i ON i.oid = ix.indexrelid
239− WHERE
240− i.relname = '{index_name}'
241− ",
242− index_name = index_name,
243− ))?
244− .first()
245− .map(|row| {
246− (
247− row.get::<'_, _, u32>("table_oid"),
248− row.get::<'_, _, Vec<i32>>("columns"),
249− )
250− })
251− .ok_or_else(|| anyhow!("failed to get columns for index"))?;
252−
253− // Get the name of each of the columns, still in order
254− column_nums
255− .iter()
256− .map(|column_num| -> anyhow::Result<String> {
257− let name: String = db
258− .query(&format!(
259− "
260− SELECT attname AS name
261− FROM pg_attribute
262− WHERE attrelid = {table_oid}
263− AND attnum = {column_num};
264− ",
265− table_oid = table_oid,
266− column_num = column_num,
267− ))?
268− .first()
269− .map(|row| row.get("name"))
270− .ok_or_else(|| anyhow!("expected to find column"))?;
271−
272− Ok(name)
273− })
274− .collect::<anyhow::Result<Vec<String>>>()
275−}
src/migrations/create_enum.rsdeleted−83
@@ -1,83 +0,0 @@
1−use super::{Action, MigrationContext};
2−use crate::{
3− db::{Conn, Transaction},
4− schema::Schema,
5−};
6−use anyhow::Context;
7−use serde::{Deserialize, Serialize};
8−
9−#[derive(Serialize, Deserialize, Debug)]
10−pub struct CreateEnum {
11− pub name: String,
12− pub values: Vec<String>,
13−}
14−
15−#[typetag::serde(name = "create_enum")]
16−impl Action for CreateEnum {
17− fn describe(&self) -> String {
18− format!("Creating enum \"{}\"", self.name)
19− }
20−
21− fn run(
22− &self,
23− _ctx: &MigrationContext,
24− db: &mut dyn Conn,
25− _schema: &Schema,
26− ) -> anyhow::Result<()> {
27− // Check if enum already exists. CREATE TYPE doesn't have
28− // a IF NOT EXISTS option so we have to do it manually.
29− let enum_exists = !db
30− .query(&format!(
31− "
32− SELECT typname
33− FROM pg_catalog.pg_type
34− WHERE typcategory = 'E'
35− AND typname = '{name}'
36− ",
37− name = self.name,
38− ))?
39− .is_empty();
40− if enum_exists {
41− return Ok(());
42− }
43−
44− let values_def: Vec<String> = self
45− .values
46− .iter()
47− .map(|value| format!("'{}'", value))
48− .collect();
49−
50− db.run(&format!(
51− r#"
52− CREATE TYPE "{name}" AS ENUM ({values})
53− "#,
54− name = self.name,
55− values = values_def.join(", "),
56− ))
57− .context("failed to create enum")?;
58−
59− Ok(())
60− }
61−
62− fn complete<'a>(
63− &self,
64− _ctx: &MigrationContext,
65− _db: &'a mut dyn Conn,
66− ) -> anyhow::Result<Option<Transaction<'a>>> {
67− Ok(None)
68− }
69−
70− fn update_schema(&self, _ctx: &MigrationContext, _schema: &mut Schema) {}
71−
72− fn abort(&self, _ctx: &MigrationContext, db: &mut dyn Conn) -> anyhow::Result<()> {
73− db.run(&format!(
74− r#"
75− DROP TYPE IF EXISTS {name}
76− "#,
77− name = self.name,
78− ))
79− .context("failed to drop enum")?;
80−
81− Ok(())
82− }
83−}
src/migrations/create_table.rs+29−177
@@ -1,12 +1,5 @@
1−use std::collections::HashMap;
2−
3−use super::{common::ForeignKey, Action, Column, MigrationContext};
1+use super::{Action, Column, Context};
4−use crate::{
5− db::{Conn, Transaction},
6− migrations::common,
7− schema::Schema,
2+use crate::{db::Conn, schema::Schema};
8−};
9−use anyhow::Context;
10use serde::{Deserialize, Serialize};
3use serde::{Deserialize, Serialize};
11
4
12#[derive(Serialize, Deserialize, Debug)]
5#[derive(Serialize, Deserialize, Debug)]
@@ -14,24 +7,14 @@ pub struct CreateTable {
14 pub name: String,
7 pub name: String,
15 pub columns: Vec<Column>,
8 pub columns: Vec<Column>,
16 pub primary_key: Vec<String>,
9 pub primary_key: Vec<String>,
17−
18− #[serde(default)]
19 pub foreign_keys: Vec<ForeignKey>,
10 pub foreign_keys: Vec<ForeignKey>,
20−
21− pub up: Option<Transformation>,
22}
11}
23
12
24#[derive(Serialize, Deserialize, Debug)]
13#[derive(Serialize, Deserialize, Debug)]
25−pub struct Transformation {
14+pub struct ForeignKey {
26− table: String,
15+ pub columns: Vec<String>,
27− values: HashMap<String, String>,
16+ pub referenced_table: String,
28− upsert_constraint: Option<String>,
17+ pub referenced_columns: Vec<String>,
29−}
30−
31−impl CreateTable {
32− fn trigger_name(&self, ctx: &MigrationContext) -> String {
33− format!("{}_create_table_{}", ctx.prefix(), self.name)
34− }
35}
18}
36
19
37#[typetag::serde(name = "create_table")]
20#[typetag::serde(name = "create_table")]
@@ -40,17 +23,12 @@ impl Action for CreateTable {
40 format!("Creating table \"{}\"", self.name)
23 format!("Creating table \"{}\"", self.name)
41 }
24 }
42
25
43− fn run(
26+ fn run(&self, _ctx: &Context, db: &mut dyn Conn, _schema: &Schema) -> anyhow::Result<()> {
44− &self,
45− ctx: &MigrationContext,
46− db: &mut dyn Conn,
47− schema: &Schema,
48− ) -> anyhow::Result<()> {
49 let mut definition_rows: Vec<String> = self
27 let mut definition_rows: Vec<String> = self
50 .columns
28 .columns
51 .iter()
29 .iter()
52 .map(|column| {
30 .map(|column| {
53− let mut parts = vec![format!("\"{}\"", column.name), column.data_type.to_string()];
31+ let mut parts = vec![column.name.to_string(), column.data_type.to_string()];
54
32
55 if let Some(default) = &column.default {
33 if let Some(default) = &column.default {
56 parts.push("DEFAULT".to_string());
34 parts.push("DEFAULT".to_string());
@@ -70,166 +48,40 @@ impl Action for CreateTable {
70 })
48 })
71 .collect();
49 .collect();
72
50
73− let primary_key_columns = self
51+ let primary_key_columns = self.primary_key.join(", ");
74− .primary_key
75− .iter()
76− // Add quotes around all column names
77− .map(|col| format!("\"{}\"", col))
78− .collect::<Vec<String>>()
79− .join(", ");
80 definition_rows.push(format!("PRIMARY KEY ({})", primary_key_columns));
52 definition_rows.push(format!("PRIMARY KEY ({})", primary_key_columns));
81
53
82 for foreign_key in &self.foreign_keys {
54 for foreign_key in &self.foreign_keys {
83− // Add quotes around all column names
84− let columns: Vec<String> = foreign_key
85− .columns
86− .iter()
87− .map(|col| format!("\"{}\"", col))
88− .collect();
89−
90− let referenced_table = schema.get_table(db, &foreign_key.referenced_table)?;
91− let referenced_columns: Vec<String> = referenced_table
92− .real_column_names(&foreign_key.referenced_columns)
93− .map(|col| format!("\"{}\"", col))
94− .collect();
95−
96 definition_rows.push(format!(
55 definition_rows.push(format!(
97− r#"
98− FOREIGN KEY ({columns}) REFERENCES "{table}" ({referenced_columns})
56+ "FOREIGN KEY ({columns}) REFERENCES {table} ({referenced_columns})",
99− "#,
100− columns = columns.join(", "),
57+ columns = foreign_key.columns.join(", "),
101− table = referenced_table.real_name,
58+ table = foreign_key.referenced_table,
102− referenced_columns = referenced_columns.join(", "),
59+ referenced_columns = foreign_key.referenced_columns.join(", "),
103 ));
60 ));
104 }
61 }
105
62
106− let query = &format!(
63+ db.run(&format!(
107− r#"
108− CREATE TABLE "{name}" (
64+ "CREATE TABLE {} (
109− {definition}
65+ {}
110− )
111− "#,
66+ )",
112− name = self.name,
67+ self.name,
113− definition = definition_rows.join(",\n"),
68+ definition_rows.join(",\n"),
114− );
69+ ))?;
115− db.run(query).context("failed to create table")?;
116−
117− if let Some(Transformation {
118− table: from_table,
119− values,
120− upsert_constraint,
121− }) = &self.up
122− {
123− let from_table = schema.get_table(db, &from_table)?;
124−
125− let declarations: Vec<String> = from_table
126− .columns
127− .iter()
128− .map(|column| {
129− format!(
130− "{alias} public.{table}.{real_name}%TYPE := NEW.{real_name};",
131− table = from_table.real_name,
132− alias = column.name,
133− real_name = column.real_name,
134− )
135− })
136− .collect();
137−
138− let (insert_columns, insert_values): (Vec<&str>, Vec<&str>) = values
139− .iter()
140− .map(|(k, v)| -> (&str, &str) { (k, v) }) // Force &String to &str
141− .unzip();
142−
143− let update_set: Vec<String> = values
144− .iter()
145− .map(|(field, value)| format!("\"{field}\" = {value}"))
146− .collect();
147−
148− // Constraint to check for conflicts. Defaults to the primary key constraint.
149− let conflict_constraint_name = match upsert_constraint {
150− Some(custom_constraint) => custom_constraint.clone(),
151− _ => format!("{table}_pkey", table = self.name),
152− };
153−
154− // Add triggers to fill in values as they are inserted/updated
155− let query = format!(
156− r#"
157− CREATE OR REPLACE FUNCTION {trigger_name}()
158− RETURNS TRIGGER AS $$
159− #variable_conflict use_variable
160− BEGIN
161− IF NOT reshape.is_new_schema() THEN
162− DECLARE
163− {declarations}
164− BEGIN
165− INSERT INTO public."{changed_table_real}" ({columns})
166− VALUES ({values})
167− ON CONFLICT ON CONSTRAINT "{conflict_constraint_name}"
168− DO UPDATE SET
169− {updates};
170− END;
171− END IF;
172− RETURN NEW;
173− END
174− $$ language 'plpgsql';
175−
176− DROP TRIGGER IF EXISTS "{trigger_name}" ON "{from_table_real}";
177− CREATE TRIGGER "{trigger_name}" BEFORE UPDATE OR INSERT ON "{from_table_real}" FOR EACH ROW EXECUTE PROCEDURE {trigger_name}();
178− "#,
179− changed_table_real = self.name,
180− from_table_real = from_table.real_name,
181− trigger_name = self.trigger_name(ctx),
182− declarations = declarations.join("\n"),
183− columns = insert_columns.join(", "),
184− values = insert_values.join(", "),
185− updates = update_set.join(",\n"),
186− );
187− db.run(&query).context("failed to create up trigger")?;
188−
189− // Backfill values in batches by touching the from table
190− common::batch_touch_rows(db, &from_table.real_name, None)
191− .context("failed to batch update existing rows")?;
192− }
193−
194 Ok(())
70 Ok(())
195 }
71 }
196
72
197− fn complete<'a>(
73+ fn complete(&self, _ctx: &Context, _db: &mut dyn Conn, _schema: &Schema) -> anyhow::Result<()> {
198− &self,
74+ // Do nothing
199− ctx: &MigrationContext,
200− db: &'a mut dyn Conn,
201− ) -> anyhow::Result<Option<Transaction<'a>>> {
202− // Remove triggers and procedures
203− let query = format!(
204− r#"
205− DROP FUNCTION IF EXISTS "{trigger_name}" CASCADE;
206− "#,
207− trigger_name = self.trigger_name(ctx),
208− );
209− db.run(&query).context("failed to drop up trigger")?;
210−
211− Ok(None)
75+ Ok(())
212 }
76 }
213
77
214− fn update_schema(&self, _ctx: &MigrationContext, _schema: &mut Schema) {}
78+ fn update_schema(&self, _ctx: &Context, _schema: &mut Schema) -> anyhow::Result<()> {
215−
79+ Ok(())
216− fn abort(&self, ctx: &MigrationContext, db: &mut dyn Conn) -> anyhow::Result<()> {
80+ }
217− // Remove triggers and procedures
218− let query = format!(
219− r#"
220− DROP FUNCTION IF EXISTS "{trigger_name}" CASCADE;
221− "#,
222− trigger_name = self.trigger_name(ctx),
223− );
224− db.run(&query).context("failed to drop up trigger")?;
225
81
226− db.run(&format!(
82+ fn abort(&self, _ctx: &Context, db: &mut dyn Conn) -> anyhow::Result<()> {
227− r#"
228− DROP TABLE IF EXISTS "{name}"
83+ let query = format!("DROP TABLE IF EXISTS {table}", table = self.name,);
229− "#,
84+ db.run(&query)?;
230− name = self.name,
231− ))
232− .context("failed to drop table")?;
233
85
234 Ok(())
86 Ok(())
235 }
87 }
src/migrations/custom.rsdeleted−61
@@ -1,61 +0,0 @@
1−use super::{Action, MigrationContext};
2−use crate::{
3− db::{Conn, Transaction},
4− schema::Schema,
5−};
6−use serde::{Deserialize, Serialize};
7−
8−#[derive(Serialize, Deserialize, Debug)]
9−pub struct Custom {
10− #[serde(default)]
11− pub start: Option<String>,
12−
13− #[serde(default)]
14− pub complete: Option<String>,
15−
16− #[serde(default)]
17− pub abort: Option<String>,
18−}
19−
20−#[typetag::serde(name = "custom")]
21−impl Action for Custom {
22− fn describe(&self) -> String {
23− "Running custom migration".to_string()
24− }
25−
26− fn run(
27− &self,
28− _ctx: &MigrationContext,
29− db: &mut dyn Conn,
30− _schema: &Schema,
31− ) -> anyhow::Result<()> {
32− if let Some(start_query) = &self.start {
33− println!("Running query: {}", start_query);
34− db.run(start_query)?;
35− }
36−
37− Ok(())
38− }
39−
40− fn complete<'a>(
41− &self,
42− _ctx: &MigrationContext,
43− db: &'a mut dyn Conn,
44− ) -> anyhow::Result<Option<Transaction<'a>>> {
45− if let Some(complete_query) = &self.complete {
46− db.run(complete_query)?;
47− }
48−
49− Ok(None)
50− }
51−
52− fn update_schema(&self, _ctx: &MigrationContext, _schema: &mut Schema) {}
53−
54− fn abort(&self, _ctx: &MigrationContext, db: &mut dyn Conn) -> anyhow::Result<()> {
55− if let Some(abort_query) = &self.abort {
56− db.run(abort_query)?;
57− }
58−
59− Ok(())
60− }
61−}
src/migrations/mod.rs+11−43
@@ -1,7 +1,4 @@
1−use crate::{
2− db::{Conn, Transaction},
3− schema::Schema,
1+use crate::{db::Conn, schema::Schema};
4−};
5use core::fmt::Debug;
2use core::fmt::Debug;
6use serde::{Deserialize, Serialize};
3use serde::{Deserialize, Serialize};
7
4
@@ -10,7 +7,7 @@ mod common;
10pub use common::Column;
7pub use common::Column;
11
8
12mod create_table;
9mod create_table;
13−pub use create_table::CreateTable;
10+pub use create_table::{CreateTable, ForeignKey};
14
11
15mod alter_column;
12mod alter_column;
16pub use alter_column::{AlterColumn, ColumnChanges};
13pub use alter_column::{AlterColumn, ColumnChanges};
@@ -22,10 +19,7 @@ mod remove_column;
22pub use remove_column::RemoveColumn;
19pub use remove_column::RemoveColumn;
23
20
24mod add_index;
21mod add_index;
25−pub use add_index::{AddIndex, Index};
22+pub use add_index::AddIndex;
26−
27−mod remove_index;
28−pub use remove_index::RemoveIndex;
29
23
30mod remove_table;
24mod remove_table;
31pub use remove_table::RemoveTable;
25pub use remove_table::RemoveTable;
@@ -33,21 +27,6 @@ pub use remove_table::RemoveTable;
33mod rename_table;
27mod rename_table;
34pub use rename_table::RenameTable;
28pub use rename_table::RenameTable;
35
29
36−mod create_enum;
37−pub use create_enum::CreateEnum;
38−
39−mod remove_enum;
40−pub use remove_enum::RemoveEnum;
41−
42−mod custom;
43−pub use custom::Custom;
44−
45−mod add_foreign_key;
46−pub use add_foreign_key::AddForeignKey;
47−
48−mod remove_foreign_key;
49−pub use remove_foreign_key::RemoveForeignKey;
50−
51#[derive(Serialize, Deserialize, Debug)]
30#[derive(Serialize, Deserialize, Debug)]
52pub struct Migration {
31pub struct Migration {
53 pub name: String,
32 pub name: String,
@@ -85,22 +64,16 @@ impl Clone for Migration {
85 }
64 }
86}
65}
87
66
88−pub struct MigrationContext {
67+pub struct Context {
89 migration_index: usize,
68 migration_index: usize,
90 action_index: usize,
69 action_index: usize,
91− existing_schema_name: Option<String>,
92}
70}
93
71
94−impl MigrationContext {
72+impl Context {
95− pub fn new(
96− migration_index: usize,
73+ pub fn new(migration_index: usize, action_index: usize) -> Self {
97− action_index: usize,
74+ Context {
98− existing_schema_name: Option<String>,
99− ) -> Self {
100− MigrationContext {
101 migration_index,
75 migration_index,
102 action_index,
76 action_index,
103− existing_schema_name,
104 }
77 }
105 }
78 }
106
79
@@ -123,13 +96,8 @@ impl MigrationContext {
123#[typetag::serde(tag = "type")]
96#[typetag::serde(tag = "type")]
124pub trait Action: Debug {
97pub trait Action: Debug {
125 fn describe(&self) -> String;
98 fn describe(&self) -> String;
126− fn run(&self, ctx: &MigrationContext, db: &mut dyn Conn, schema: &Schema)
99+ fn run(&self, ctx: &Context, db: &mut dyn Conn, schema: &Schema) -> anyhow::Result<()>;
127− -> anyhow::Result<()>;
100+ fn complete(&self, ctx: &Context, db: &mut dyn Conn, schema: &Schema) -> anyhow::Result<()>;
128− fn complete<'a>(
129− &self,
130− ctx: &MigrationContext,
131− db: &'a mut dyn Conn,
132− ) -> anyhow::Result<Option<Transaction<'a>>>;
133− fn update_schema(&self, ctx: &MigrationContext, schema: &mut Schema);
101+ fn update_schema(&self, ctx: &Context, schema: &mut Schema) -> anyhow::Result<()>;
134− fn abort(&self, ctx: &MigrationContext, db: &mut dyn Conn) -> anyhow::Result<()>;
102+ fn abort(&self, ctx: &Context, db: &mut dyn Conn) -> anyhow::Result<()>;
135}
103}
src/migrations/remove_column.rs+55−390
@@ -1,31 +1,16 @@
1−use super::{common, Action, MigrationContext};
1+use super::{Action, Context};
2−use crate::{
3− db::{Conn, Transaction},
4− schema::Schema,
2+use crate::{db::Conn, schema::Schema};
5−};
6−use anyhow::{anyhow, bail, Context};
7use serde::{Deserialize, Serialize};
3use serde::{Deserialize, Serialize};
8
4
9#[derive(Serialize, Deserialize, Debug)]
5#[derive(Serialize, Deserialize, Debug)]
10pub struct RemoveColumn {
6pub struct RemoveColumn {
11 pub table: String,
7 pub table: String,
12 pub column: String,
8 pub column: String,
13− pub down: Option<Transformation>,
9+ pub down: Option<String>,
14−}
15−
16−#[derive(Serialize, Deserialize, Debug)]
17−#[serde(untagged)]
18−pub enum Transformation {
19− Simple(String),
20− Update {
21− table: String,
22− value: String,
23− r#where: String,
24− },
25}
10}
26
11
27impl RemoveColumn {
12impl RemoveColumn {
28− fn trigger_name(&self, ctx: &MigrationContext) -> String {
13+ fn trigger_name(&self, ctx: &Context) -> String {
29 format!(
14 format!(
30 "{}_remove_column_{}_{}",
15 "{}_remove_column_{}_{}",
31 ctx.prefix(),
16 ctx.prefix(),
@@ -33,33 +18,6 @@ impl RemoveColumn {
33 self.column
18 self.column
34 )
19 )
35 }
20 }
36−
37− fn reverse_trigger_name(&self, ctx: &MigrationContext) -> String {
38− format!(
39− "{}_remove_column_{}_{}_rev",
40− ctx.prefix(),
41− self.table,
42− self.column
43− )
44− }
45−
46− fn not_null_constraint_trigger_name(&self, ctx: &MigrationContext) -> String {
47− format!(
48− "{}_remove_column_{}_{}_nn",
49− ctx.prefix(),
50− self.table,
51− self.column
52− )
53− }
54−
55− fn not_null_constraint_name(&self, ctx: &MigrationContext) -> String {
56− format!(
57− "{}_add_column_not_null_{}_{}",
58− ctx.prefix(),
59− self.table,
60− self.column
61− )
62− }
63}
21}
64
22
65#[typetag::serde(name = "remove_column")]
23#[typetag::serde(name = "remove_column")]
@@ -71,19 +29,11 @@ impl Action for RemoveColumn {
71 )
29 )
72 }
30 }
73
31
74− fn run(
32+ fn run(&self, ctx: &Context, db: &mut dyn Conn, schema: &Schema) -> anyhow::Result<()> {
75− &self,
76− ctx: &MigrationContext,
77− db: &mut dyn Conn,
78− schema: &Schema,
79− ) -> anyhow::Result<()> {
80− let table = schema.get_table(db, &self.table)?;
81− let column = table
82− .get_column(&self.column)
83− .ok_or_else(|| anyhow!("no such column {} exists", self.column))?;
84−
85 // Add down trigger
33 // Add down trigger
86 if let Some(down) = &self.down {
34 if let Some(down) = &self.down {
35+ let table = schema.get_table(db, &self.table)?;
36+
87 let declarations: Vec<String> = table
37 let declarations: Vec<String> = table
88 .columns
38 .columns
89 .iter()
39 .iter()
@@ -97,357 +47,72 @@ impl Action for RemoveColumn {
97 })
47 })
98 .collect();
48 .collect();
99
49
100− if let Transformation::Simple(down) = down {
101− let query = format!(
50+ let query = format!(
102− r#"
51+ "
103− CREATE OR REPLACE FUNCTION {trigger_name}()
52+ CREATE OR REPLACE FUNCTION {trigger_name}()
104− RETURNS TRIGGER AS $$
53+ RETURNS TRIGGER AS $$
105− BEGIN
54+ BEGIN
106− IF reshape.is_new_schema() THEN
55+ IF NEW.{column_name} IS NULL THEN
107− DECLARE
56+ DECLARE
108− {declarations}
109− BEGIN
110− NEW.{column_name} = {down};
111− END;
112− END IF;
113− RETURN NEW;
114− END
115− $$ language 'plpgsql';
116−
117− DROP TRIGGER IF EXISTS "{trigger_name}" ON "{table}";
118− CREATE TRIGGER "{trigger_name}" BEFORE UPDATE OR INSERT ON "{table}" FOR EACH ROW EXECUTE PROCEDURE {trigger_name}();
119− "#,
120− column_name = self.column,
121− trigger_name = self.trigger_name(ctx),
122− down = down,
123− table = self.table,
124− declarations = declarations.join("\n"),
57+ {declarations}
125− );
126− db.run(&query).context("failed to create down trigger")?;
127− }
128−
129− if let Transformation::Update {
130− table: from_table,
131− value,
132− r#where,
133− } = down
134− {
135− let existing_schema_name = match &ctx.existing_schema_name {
136− Some(name) => name,
137− None => bail!("can't use update without previous migration"),
138− };
139−
140− let from_table = schema.get_table(db, &from_table)?;
141−
142− let maybe_null_check = if !column.nullable {
143− // Replace NOT NULL constraint with a constraint trigger that only triggers on the old schema.
144− // We will add a null check to the down function on the new schema below as well to cover both cases.
145− // As we are using a complex down function, we must remove the NOT NULL check for the new schema.
146− // NOT NULL is not checked at the end of a transaction, but immediately upon update.
147− let query = format!(
148− r#"
149− CREATE OR REPLACE FUNCTION {trigger_name}()
150− RETURNS TRIGGER AS $$
151 BEGIN
58 BEGIN
152− IF NOT reshape.is_new_schema() THEN
59+ NEW.{column_name} = {down};
153− IF NEW.{column} IS NULL THEN
154− RAISE EXCEPTION '{column} can not be null';
155− END IF;
60+ END;
156− END IF;
61+ END IF;
157− RETURN NEW;
62+ RETURN NEW;
158− END
63+ END
159− $$ language 'plpgsql';
64+ $$ language 'plpgsql';
160−
65+
161− DROP TRIGGER IF EXISTS "{trigger_name}" ON "{table}";
66+ DROP TRIGGER IF EXISTS {trigger_name} ON {table};
162−
163− CREATE CONSTRAINT TRIGGER "{trigger_name}"
164− AFTER INSERT OR UPDATE
165− ON "{table}"
166− FOR EACH ROW
167− EXECUTE PROCEDURE {trigger_name}();
67+ CREATE TRIGGER {trigger_name} BEFORE UPDATE OR INSERT ON {table} FOR EACH ROW EXECUTE PROCEDURE {trigger_name}();
168− "#,
68+ ",
169− table = self.table,
69+ column_name = self.column,
170− trigger_name = self.not_null_constraint_trigger_name(ctx),
70+ trigger_name = self.trigger_name(&ctx),
171− column = self.column,
71+ down = down,
172− );
173− db.run(&query)
174− .context("failed to create null constraint trigger")?;
175−
176− db.run(&format!(
177− r#"
178− ALTER TABLE {table}
179− ALTER COLUMN {column}
180− DROP NOT NULL
181− "#,
182− table = self.table,
72+ table = self.table,
183− column = self.column
184− ))
185− .context("failed to remove column not null constraint")?;
186−
187− format!(
188− r#"
189− IF {value} IS NULL THEN
190− RAISE EXCEPTION '{column_name} can not be null';
191− END IF;
192− "#,
193− column_name = self.column,
194− )
195− } else {
196− "".to_string()
197− };
198−
199− let into_variables = from_table
200− .columns
201− .iter()
202− .map(|column| {
203− format!(
204− "NEW.{real_name} AS {alias}",
205− alias = column.name,
206− real_name = column.real_name,
207− )
208− })
209− .collect::<Vec<String>>()
210− .join(", ");
211−
212− let query = format!(
213− r#"
214− CREATE OR REPLACE FUNCTION {trigger_name}()
215− RETURNS TRIGGER AS $$
216− #variable_conflict use_variable
217− BEGIN
218− IF reshape.is_new_schema() THEN
219− DECLARE
220− {from_table} record;
221− BEGIN
222− SELECT {into_variables}
223− INTO {from_table};
224−
225− {maybe_null_check}
226−
227− -- Don't trigger reverse trigger when making this update
228− perform set_config('reshape.disable_triggers', 'TRUE', TRUE);
229−
230− UPDATE "migration_{existing_schema_name}"."{changed_table}" "{changed_table}"
231− SET "{column_name}" = {value}
232− WHERE {where};
233−
234− perform set_config('reshape.disable_triggers', '', TRUE);
235− END;
236− END IF;
237− RETURN NEW;
238− END
239− $$ language 'plpgsql';
240−
241− DROP TRIGGER IF EXISTS "{trigger_name}" ON "{from_table_real}";
242− CREATE TRIGGER "{trigger_name}" BEFORE UPDATE OR INSERT ON "{from_table_real}" FOR EACH ROW EXECUTE PROCEDURE {trigger_name}();
243− "#,
244− changed_table = self.table,
245− from_table = from_table.name,
246− from_table_real = from_table.real_name,
247− column_name = self.column,
248− trigger_name = self.trigger_name(ctx),
249− );
250− db.run(&query).context("failed to create down trigger")?;
251−
252− let changed_into_variables = table
253− .columns
254− .iter()
255− .map(|column| {
256− format!(
257− "NEW.{real_name} AS {alias}",
258− alias = column.name,
259− real_name = column.real_name,
260− )
261− })
262− .collect::<Vec<String>>()
263− .join(", ");
264−
265− let from_table_columns = from_table
266− .columns
267− .iter()
268− .map(|column| format!("{} as {}", column.real_name, column.name))
269− .collect::<Vec<String>>()
270− .join(", ");
271−
272− let query = format!(
273− r#"
274− CREATE OR REPLACE FUNCTION {trigger_name}()
275− RETURNS TRIGGER AS $$
276− #variable_conflict use_variable
277− BEGIN
278− IF reshape.is_new_schema() AND NOT current_setting('reshape.disable_triggers', TRUE) = 'TRUE' THEN
279− DECLARE
280− {changed_table} record;
281− __temp_row record;
282− BEGIN
283− SELECT {changed_into_variables}
284− INTO {changed_table};
285−
286− SELECT *
287− INTO __temp_row
288− FROM (
289− SELECT {from_table_columns}
290− FROM public.{from_table_real}
291− ) {from_table}
292− WHERE {where};
293−
294− DECLARE
295− {from_table} record;
296− BEGIN
297− {from_table} := __temp_row;
298− NEW.{column_name_real} = {value};
299− END;
300− END;
301− END IF;
302− RETURN NEW;
303− END
304− $$ language 'plpgsql';
305−
306− DROP TRIGGER IF EXISTS "{trigger_name}" ON "{changed_table_real}";
307− CREATE TRIGGER "{trigger_name}" BEFORE UPDATE OR INSERT ON "{changed_table_real}" FOR EACH ROW EXECUTE PROCEDURE {trigger_name}();
308− "#,
309− changed_table = table.name,
310− changed_table_real = table.real_name,
311− from_table = from_table.name,
312− from_table_real = from_table.real_name,
313− column_name_real = column.real_name,
314− trigger_name = self.reverse_trigger_name(ctx),
315− // declarations = declarations.join("\n"),
73+ declarations = declarations.join("\n"),
316− );
74+ );
317− db.run(&query)
75+ db.run(&query)?;
318− .context("failed to create reverse down trigger")?;
319− }
320 }
76 }
321
77
322 Ok(())
78 Ok(())
323 }
79 }
324
80
325− fn complete<'a>(
81+ fn complete(&self, ctx: &Context, db: &mut dyn Conn, _schema: &Schema) -> anyhow::Result<()> {
326− &self,
327− ctx: &MigrationContext,
328− db: &'a mut dyn Conn,
329− ) -> anyhow::Result<Option<Transaction<'a>>> {
330− let indices = common::get_indices_for_column(db, &self.table, &self.column)
331− .context("failed getting column indices")?;
332−
333− for index in indices {
334− db.run(&format!(
335− "
336− DROP INDEX CONCURRENTLY IF EXISTS {name}
337− ",
338− name = index.name,
339− ))
340− .context("failed to drop index")?;
341− }
342−
343 // Remove column, function and trigger
82 // Remove column, function and trigger
344 let query = format!(
83 let query = format!(
345− r#"
84+ "
346− ALTER TABLE "{table}"
85+ ALTER TABLE {table}
347− DROP COLUMN IF EXISTS "{column}";
86+ DROP COLUMN {column};
348
87
349− DROP FUNCTION IF EXISTS "{trigger_name}" CASCADE;
88+ DROP TRIGGER IF EXISTS {trigger_name} ON {table};
350− DROP FUNCTION IF EXISTS "{reverse_trigger_name}" CASCADE;
351− DROP FUNCTION IF EXISTS "{null_trigger_name}" CASCADE;
89+ DROP FUNCTION IF EXISTS {trigger_name};
352− "#,
90+ ",
353 table = self.table,
91 table = self.table,
354 column = self.column,
92 column = self.column,
355− trigger_name = self.trigger_name(ctx),
93+ trigger_name = self.trigger_name(&ctx),
356− reverse_trigger_name = self.reverse_trigger_name(ctx),
357− null_trigger_name = self.not_null_constraint_trigger_name(ctx),
358 );
94 );
359− db.run(&query)
95+ db.run(&query)?;
360− .context("failed to drop column and down trigger")?;
361−
362− Ok(None)
363− }
364
96
365− fn update_schema(&self, _ctx: &MigrationContext, schema: &mut Schema) {
97+ Ok(())
366− schema.change_table(&self.table, |table_changes| {
367− table_changes.change_column(&self.column, |column_changes| {
368− column_changes.set_removed();
369− })
370− });
371 }
98 }
372
99
373− fn abort(&self, ctx: &MigrationContext, db: &mut dyn Conn) -> anyhow::Result<()> {
100+ fn update_schema(&self, _ctx: &Context, schema: &mut Schema) -> anyhow::Result<()> {
374− // We might have temporaily removed the NOT NULL check and have to reinstate it
101+ schema.set_column_hidden(&self.table, &self.column);
375− let has_not_null_function = !db
376− .query_with_params(
377− "
378− SELECT routine_name
379− FROM information_schema.routines
380− WHERE routine_schema = 'public'
381− AND routine_name = $1
382− ",
383− &[&self.not_null_constraint_trigger_name(ctx)],
384− )
385− .context("failed to get any NOT NULL function")?
386− .is_empty();
387−
388− if has_not_null_function {
389− // Make column NOT NULL again without taking any long lived locks with a temporary constraint
390− let query = format!(
391− r#"
392− ALTER TABLE "{table}"
393− ADD CONSTRAINT "{constraint_name}"
394− CHECK ("{column}" IS NOT NULL) NOT VALID
395− "#,
396− table = self.table,
397− constraint_name = self.not_null_constraint_name(ctx),
398− column = self.column,
399− );
400− db.run(&query)
401− .context("failed to add NOT NULL constraint")?;
402−
403− let query = format!(
404− r#"
405− ALTER TABLE "{table}"
406− VALIDATE CONSTRAINT "{constraint_name}"
407− "#,
408− table = self.table,
409− constraint_name = self.not_null_constraint_name(ctx),
410− );
411− db.run(&query)
412− .context("failed to validate NOT NULL constraint")?;
413−
414− // This ALTER TABLE call will not require any exclusive locks as it can use the validated constraint from above
415− db.run(&format!(
416− r#"
417− ALTER TABLE {table}
418− ALTER COLUMN {column}
419− SET NOT NULL
420− "#,
421− table = self.table,
422− column = self.column
423− ))
424− .context("failed to reinstate column NOT NULL")?;
425
102
426− // Drop the temporary constraint
103+ Ok(())
427− let query = format!(
428− r#"
429− ALTER TABLE "{table}"
430− DROP CONSTRAINT "{constraint_name}"
431− "#,
432− table = self.table,
433− constraint_name = self.not_null_constraint_name(ctx),
434− );
435− db.run(&query)
436− .context("failed to drop NOT NULL constraint")?;
437− }
104+ }
438
105
106+ fn abort(&self, ctx: &Context, db: &mut dyn Conn) -> anyhow::Result<()> {
439 // Remove function and trigger
107 // Remove function and trigger
440− db.run(&format!(
108+ db.query(&format!(
441− r#"
109+ "
442− DROP FUNCTION IF EXISTS "{trigger_name}" CASCADE;
110+ DROP TRIGGER IF EXISTS {trigger_name} ON {table};
443− DROP FUNCTION IF EXISTS "{reverse_trigger_name}" CASCADE;
444− DROP FUNCTION IF EXISTS "{null_trigger_name}" CASCADE;
111+ DROP FUNCTION IF EXISTS {trigger_name};
445− "#,
112+ ",
446− trigger_name = self.trigger_name(ctx),
113+ table = self.table,
447− reverse_trigger_name = self.reverse_trigger_name(ctx),
114+ trigger_name = self.trigger_name(&ctx),
448− null_trigger_name = self.not_null_constraint_trigger_name(ctx),
115+ ))?;
449− ))
450− .context("failed to drop down trigger")?;
451
116
452 Ok(())
117 Ok(())
453 }
118 }
src/migrations/remove_enum.rsdeleted−51
@@ -1,51 +0,0 @@
1−use super::{Action, MigrationContext};
2−use crate::{
3− db::{Conn, Transaction},
4− schema::Schema,
5−};
6−use anyhow::Context;
7−use serde::{Deserialize, Serialize};
8−
9−#[derive(Serialize, Deserialize, Debug)]
10−pub struct RemoveEnum {
11− #[serde(rename = "enum")]
12− pub enum_name: String,
13−}
14−
15−#[typetag::serde(name = "remove_enum")]
16−impl Action for RemoveEnum {
17− fn describe(&self) -> String {
18− format!("Removing enum \"{}\"", self.enum_name)
19− }
20−
21− fn run(
22− &self,
23− _ctx: &MigrationContext,
24− _db: &mut dyn Conn,
25− _schema: &Schema,
26− ) -> anyhow::Result<()> {
27− Ok(())
28− }
29−
30− fn complete<'a>(
31− &self,
32− _ctx: &MigrationContext,
33− db: &'a mut dyn Conn,
34− ) -> anyhow::Result<Option<Transaction<'a>>> {
35− db.run(&format!(
36− r#"
37− DROP TYPE IF EXISTS {name}
38− "#,
39− name = self.enum_name,
40− ))
41− .context("failed to drop enum")?;
42−
43− Ok(None)
44− }
45−
46− fn update_schema(&self, _ctx: &MigrationContext, _schema: &mut Schema) {}
47−
48− fn abort(&self, _ctx: &MigrationContext, _db: &mut dyn Conn) -> anyhow::Result<()> {
49− Ok(())
50− }
51−}
src/migrations/remove_foreign_key.rsdeleted−91
@@ -1,91 +0,0 @@
1−use super::{Action, MigrationContext};
2−use crate::{
3− db::{Conn, Transaction},
4− schema::Schema,
5−};
6−use anyhow::{anyhow, Context};
7−use serde::{Deserialize, Serialize};
8−
9−#[derive(Serialize, Deserialize, Debug)]
10−pub struct RemoveForeignKey {
11− table: String,
12− foreign_key: String,
13−}
14−
15−#[typetag::serde(name = "remove_foreign_key")]
16−impl Action for RemoveForeignKey {
17− fn describe(&self) -> String {
18− format!(
19− "Removing foreign key \"{}\" from table \"{}\"",
20− self.foreign_key, self.table
21− )
22− }
23−
24− fn run(
25− &self,
26− _ctx: &MigrationContext,
27− db: &mut dyn Conn,
28− schema: &Schema,
29− ) -> anyhow::Result<()> {
30− // The foreign key is only removed once the migration is completed.
31− // Removing it earlier would be hard/undesirable for several reasons:
32− // - Postgres doesn't have an easy way to temporarily disable a foreign key check.
33− // If it did, we could disable the FK for the new schema.
34− // - Even if we could, it probably wouldn't be a good idea as it would cause temporary
35− // inconsistencies for the old schema which still expects the FK to hold.
36− // - For the same reason, we can't remove the FK when the migration is first applied.
37− // If the migration was to be aborted, then the FK would have to be recreated with
38− // the risk that it would no longer be valid.
39−
40− // Ensure foreign key exists
41− let table = schema.get_table(db, &self.table)?;
42− let fk_exists = !db
43− .query(&format!(
44− r#"
45− SELECT constraint_name
46− FROM information_schema.table_constraints
47− WHERE
48− constraint_type = 'FOREIGN KEY' AND
49− table_name = '{table_name}' AND
50− constraint_name = '{foreign_key}'
51− "#,
52− table_name = table.real_name,
53− foreign_key = self.foreign_key,
54− ))
55− .context("failed to check for foreign key")?
56− .is_empty();
57−
58− if !fk_exists {
59− return Err(anyhow!(
60− "no foreign key \"{}\" exists on table \"{}\"",
61− self.foreign_key,
62− self.table
63− ));
64− }
65−
66− Ok(())
67− }
68−
69− fn complete<'a>(
70− &self,
71− _ctx: &MigrationContext,
72− db: &'a mut dyn Conn,
73− ) -> anyhow::Result<Option<Transaction<'a>>> {
74− db.run(&format!(
75− r#"
76− ALTER TABLE {table}
77− DROP CONSTRAINT IF EXISTS {foreign_key}
78− "#,
79− table = self.table,
80− foreign_key = self.foreign_key,
81− ))
82− .context("failed to remove foreign key")?;
83− Ok(None)
84− }
85−
86− fn update_schema(&self, _ctx: &MigrationContext, _schema: &mut Schema) {}
87−
88− fn abort(&self, _ctx: &MigrationContext, _db: &mut dyn Conn) -> anyhow::Result<()> {
89− Ok(())
90− }
91−}
src/migrations/remove_index.rsdeleted−51
@@ -1,51 +0,0 @@
1−use super::{Action, MigrationContext};
2−use crate::{
3− db::{Conn, Transaction},
4− schema::Schema,
5−};
6−use anyhow::Context;
7−use serde::{Deserialize, Serialize};
8−
9−#[derive(Serialize, Deserialize, Debug)]
10−pub struct RemoveIndex {
11− pub index: String,
12−}
13−
14−#[typetag::serde(name = "remove_index")]
15−impl Action for RemoveIndex {
16− fn describe(&self) -> String {
17− format!("Removing index \"{}\"", self.index)
18− }
19−
20− fn run(
21− &self,
22− _ctx: &MigrationContext,
23− _db: &mut dyn Conn,
24− _schema: &Schema,
25− ) -> anyhow::Result<()> {
26− // Do nothing, the index isn't removed until completion
27− Ok(())
28− }
29−
30− fn complete<'a>(
31− &self,
32− _ctx: &MigrationContext,
33− db: &'a mut dyn Conn,
34− ) -> anyhow::Result<Option<Transaction<'a>>> {
35− db.run(&format!(
36− r#"
37− DROP INDEX CONCURRENTLY IF EXISTS "{name}"
38− "#,
39− name = self.index
40− ))
41− .context("failed to drop index")?;
42−
43− Ok(None)
44− }
45−
46− fn update_schema(&self, _ctx: &MigrationContext, _schema: &mut Schema) {}
47−
48− fn abort(&self, _ctx: &MigrationContext, _db: &mut dyn Conn) -> anyhow::Result<()> {
49− Ok(())
50− }
51−}
src/migrations/remove_table.rs+14−27
@@ -1,9 +1,5 @@
1−use super::{Action, MigrationContext};
1+use super::{Action, Context};
2−use crate::{
3− db::{Conn, Transaction},
4− schema::Schema,
2+use crate::{db::Conn, schema::Schema};
5−};
6−use anyhow::Context;
7use serde::{Deserialize, Serialize};
3use serde::{Deserialize, Serialize};
8
4
9#[derive(Serialize, Deserialize, Debug)]
5#[derive(Serialize, Deserialize, Debug)]
@@ -17,39 +13,30 @@ impl Action for RemoveTable {
17 format!("Removing table \"{}\"", self.table)
13 format!("Removing table \"{}\"", self.table)
18 }
14 }
19
15
20− fn run(
16+ fn run(&self, _ctx: &Context, _db: &mut dyn Conn, _schema: &Schema) -> anyhow::Result<()> {
21− &self,
22− _ctx: &MigrationContext,
23− _db: &mut dyn Conn,
24− _schema: &Schema,
25− ) -> anyhow::Result<()> {
26 Ok(())
17 Ok(())
27 }
18 }
28
19
29− fn complete<'a>(
20+ fn complete(&self, _ctx: &Context, db: &mut dyn Conn, _schema: &Schema) -> anyhow::Result<()> {
30− &self,
31− _ctx: &MigrationContext,
32− db: &'a mut dyn Conn,
33− ) -> anyhow::Result<Option<Transaction<'a>>> {
34 // Remove table
21 // Remove table
35 let query = format!(
22 let query = format!(
36− r#"
23+ "
37− DROP TABLE IF EXISTS "{table}";
24+ DROP TABLE {table};
38− "#,
25+ ",
39 table = self.table,
26 table = self.table,
40 );
27 );
41− db.run(&query).context("failed to drop table")?;
28+ db.run(&query)?;
42
29
43− Ok(None)
30+ Ok(())
44 }
31 }
45
32
46− fn update_schema(&self, _ctx: &MigrationContext, schema: &mut Schema) {
33+ fn update_schema(&self, _ctx: &Context, schema: &mut Schema) -> anyhow::Result<()> {
47− schema.change_table(&self.table, |table_changes| {
34+ schema.set_table_hidden(&self.table);
48− table_changes.set_removed();
35+
49− });
36+ Ok(())
50 }
37 }
51
38
52− fn abort(&self, _ctx: &MigrationContext, _db: &mut dyn Conn) -> anyhow::Result<()> {
39+ fn abort(&self, _ctx: &Context, _db: &mut dyn Conn) -> anyhow::Result<()> {
53 Ok(())
40 Ok(())
54 }
41 }
55}
42}
src/migrations/rename_table.rs+15−28
@@ -1,9 +1,5 @@
1−use super::{Action, MigrationContext};
1+use super::{Action, Context};
2−use crate::{
3− db::{Conn, Transaction},
4− schema::Schema,
2+use crate::{db::Conn, schema::Schema};
5−};
6−use anyhow::Context;
7use serde::{Deserialize, Serialize};
3use serde::{Deserialize, Serialize};
8
4
9#[derive(Serialize, Deserialize, Debug)]
5#[derive(Serialize, Deserialize, Debug)]
@@ -18,41 +14,32 @@ impl Action for RenameTable {
18 format!("Renaming table \"{}\" to \"{}\"", self.table, self.new_name)
14 format!("Renaming table \"{}\" to \"{}\"", self.table, self.new_name)
19 }
15 }
20
16
21− fn run(
17+ fn run(&self, _ctx: &Context, _db: &mut dyn Conn, _schema: &Schema) -> anyhow::Result<()> {
22− &self,
23− _ctx: &MigrationContext,
24− _db: &mut dyn Conn,
25− _schema: &Schema,
26− ) -> anyhow::Result<()> {
27 Ok(())
18 Ok(())
28 }
19 }
29
20
30− fn complete<'a>(
21+ fn complete(&self, _ctx: &Context, db: &mut dyn Conn, _schema: &Schema) -> anyhow::Result<()> {
31− &self,
32− _ctx: &MigrationContext,
33− db: &'a mut dyn Conn,
34− ) -> anyhow::Result<Option<Transaction<'a>>> {
35 // Rename table
22 // Rename table
36 let query = format!(
23 let query = format!(
37− r#"
24+ "
38− ALTER TABLE IF EXISTS "{table}"
25+ ALTER TABLE {table}
39− RENAME TO "{new_name}"
26+ RENAME TO {new_name}
40− "#,
27+ ",
41 table = self.table,
28 table = self.table,
42 new_name = self.new_name,
29 new_name = self.new_name,
43 );
30 );
44− db.run(&query).context("failed to rename table")?;
31+ db.run(&query)?;
45
32
46− Ok(None)
33+ Ok(())
47 }
34 }
48
35
49− fn update_schema(&self, _ctx: &MigrationContext, schema: &mut Schema) {
36+ fn update_schema(&self, _ctx: &Context, schema: &mut Schema) -> anyhow::Result<()> {
50− schema.change_table(&self.table, |table_changes| {
37+ schema.set_table_alias(&self.table, &self.new_name);
51− table_changes.set_name(&self.new_name);
38+
52− });
39+ Ok(())
53 }
40 }
54
41
55− fn abort(&self, _ctx: &MigrationContext, _db: &mut dyn Conn) -> anyhow::Result<()> {
42+ fn abort(&self, _ctx: &Context, _db: &mut dyn Conn) -> anyhow::Result<()> {
56 Ok(())
43 Ok(())
57 }
44 }
58}
45}
src/schema.rs+139−186
@@ -1,140 +1,144 @@
1use crate::db::Conn;
1use crate::db::Conn;
2+use anyhow::anyhow;
3+use bimap::BiMap;
2−use std::collections::{HashMap, HashSet};
4+use std::collections::{hash_map::Entry, HashMap, HashSet};
3−
5+
4−// Schema tracks changes made to tables and columns during a migration.
5−// These changes are not applied until the migration is completed but
6−// need to be taken into consideration when creating views for a migration
7−// and when a user references a table or column in a migration.
8−//
9−// The changes to a table are tracked by a `TableChanges` struct. The possible
10−// changes are:
11−// - Changing the name which updates `current_name`.
12−// - Removing which sets the `removed` flag.
13−//
14−// Changes to a column are tracked by a `ColumnChanges` struct which reside in
15−// the corresponding `TableChanges`. The possible changes are:
16−// - Changing the name which updates `current_name`.
17−// - Changing the backing column which will add the new column to the end of
18−// `intermediate_columns`. This is used when temporary columns are
19−// introduced which will eventually replace the current column.
20−// - Removing which sets the `removed` flag.
21−//
22−// Schema provides some schema introspection methods, `get_tables` and `get_table`,
23−// which will retrieve the current schema from the database and apply the changes.
24#[derive(Debug)]
6#[derive(Debug)]
25pub struct Schema {
7pub struct Schema {
26− table_changes: Vec<TableChanges>,
8+ table_alias_to_name: BiMap<String, String>,
9+ hidden_tables: HashSet<String>,
10+ table_schemas_by_name: HashMap<String, TableSchema>,
27}
11}
28
12
29impl Schema {
13impl Schema {
30 pub fn new() -> Schema {
14 pub fn new() -> Schema {
31 Schema {
15 Schema {
32− table_changes: Vec::new(),
16+ table_alias_to_name: BiMap::new(),
17+ hidden_tables: HashSet::new(),
18+ table_schemas_by_name: HashMap::new(),
33 }
19 }
34 }
20 }
35
21
36− pub fn change_table<F>(&mut self, current_name: &str, f: F)
22+ pub fn set_table_alias(&mut self, current_name: &str, alias: &str) {
37− where
23+ self.table_alias_to_name
38− F: FnOnce(&mut TableChanges),
39− {
40− let table_change_index = self
41− .table_changes
42− .iter()
43− .position(|table| table.current_name == current_name)
44− .unwrap_or_else(|| {
45− let new_changes = TableChanges::new(current_name.to_string());
24+ .insert(alias.to_string(), current_name.to_string());
46− self.table_changes.push(new_changes);
47− self.table_changes.len() - 1
48− });
25+ }
49
26
50− let table_changes = &mut self.table_changes[table_change_index];
27+ pub fn set_table_hidden(&mut self, table: &str) {
51− f(table_changes)
28+ let real_name = self
29+ .get_table_real_name(table)
30+ .unwrap_or_else(|| table.to_string());
31+ self.hidden_tables.insert(real_name);
52 }
32 }
53−}
54
33
55−impl Default for Schema {
34+ pub fn set_column_alias(&mut self, table: &str, current_name: &str, alias: &str) {
56− fn default() -> Self {
35+ let table_real_name = self
57− Self::new()
36+ .get_table_real_name(table)
37+ .unwrap_or_else(|| table.to_string());
38+
39+ let column = match self.table_schemas_by_name.entry(table_real_name) {
40+ Entry::Occupied(o) => o.into_mut(),
41+ Entry::Vacant(v) => v.insert(TableSchema::new()),
42+ };
43+
44+ column
45+ .column_alias_to_name
46+ .insert(alias.to_string(), current_name.to_string());
58 }
47 }
59−}
60
48
61−#[derive(Debug)]
49+ pub fn set_column_hidden(&mut self, table: &str, name: &str) {
62−pub struct TableChanges {
50+ let table_real_name = self
63− current_name: String,
51+ .get_table_real_name(table)
64− real_name: String,
52+ .unwrap_or_else(|| table.to_string());
65− column_changes: Vec<ColumnChanges>,
53+ let column = match self.table_schemas_by_name.entry(table_real_name) {
66− removed: bool,
54+ Entry::Occupied(o) => o.into_mut(),
55+ Entry::Vacant(v) => v.insert(TableSchema::new()),
67−}
56+ };
68
57
69−impl TableChanges {
70− fn new(name: String) -> Self {
71− Self {
72− current_name: name.to_string(),
58+ column.hidden_columns.insert(name.to_string());
73− real_name: name,
74− column_changes: Vec::new(),
75− removed: false,
76− }
77 }
59 }
78
60
79− pub fn set_name(&mut self, name: &str) {
61+ fn get_table_real_name(&self, name: &str) -> Option<String> {
80− self.current_name = name.to_string();
62+ self.table_alias_to_name
63+ .get_by_left(name)
64+ .map(|real_name| real_name.to_string())
81 }
65 }
82
66
83− pub fn change_column<F>(&mut self, current_name: &str, f: F)
67+ fn get_table_alias_from_real_name<'a>(&'a self, real_name: &'a str) -> Option<String> {
84− where
68+ self.table_alias_to_name
85− F: FnOnce(&mut ColumnChanges),
69+ .get_by_right(real_name)
86− {
70+ .map(|name| name.to_string())
87− let column_change_index = self
88− .column_changes
89− .iter()
90− .position(|column| column.current_name == current_name)
91− .unwrap_or_else(|| {
92− let new_changes = ColumnChanges::new(current_name.to_string());
93− self.column_changes.push(new_changes);
94− self.column_changes.len() - 1
95− });
71+ }
96
72
97− let column_changes = &mut self.column_changes[column_change_index];
73+ fn is_table_hidden(&self, table: &str) -> bool {
98− f(column_changes)
74+ let table_real_name = self
75+ .get_table_real_name(table)
76+ .unwrap_or_else(|| table.to_string());
77+ self.hidden_tables.contains(&table_real_name)
99 }
78 }
100
79
101− pub fn set_removed(&mut self) {
80+ fn get_column_real_name<'a>(&'a self, table: &'a str, name: &'a str) -> Option<&'a str> {
102− self.removed = true;
81+ let table_real_name = self
82+ .get_table_real_name(table)
83+ .unwrap_or_else(|| table.to_string());
84+
85+ self.table_schemas_by_name
86+ .get(&table_real_name)
87+ .map(|column| column.get_column_real_name(name))
103 }
88 }
104−}
105
89
106−#[derive(Debug)]
90+ fn get_column_alias_from_real_name(&self, table: &str, real_name: &str) -> Option<String> {
107−pub struct ColumnChanges {
91+ let table_real_name = self
108− current_name: String,
92+ .get_table_real_name(table)
109− backing_columns: Vec<String>,
93+ .unwrap_or_else(|| table.to_string());
110− removed: bool,
111−}
112
94
113−impl ColumnChanges {
95+ self.table_schemas_by_name
114− fn new(name: String) -> Self {
96+ .get(&table_real_name)
115− Self {
97+ .and_then(|column| column.get_column_alias_from_real_name(real_name))
116− current_name: name.to_string(),
117− backing_columns: vec![name],
118− removed: false,
119− }
120 }
98 }
121
99
122− pub fn set_name(&mut self, name: &str) {
100+ fn is_column_hidden(&self, table: &str, name: &str) -> bool {
101+ let table_real_name = self
102+ .get_table_real_name(table)
103+ .unwrap_or_else(|| table.to_string());
104+ self.table_schemas_by_name
105+ .get(&table_real_name)
106+ .map(|column| {
107+ let alias = column
108+ .get_column_alias_from_real_name(name)
123− self.current_name = name.to_string();
109+ .unwrap_or_else(|| name.to_string());
110+ column.hidden_columns.contains(&alias)
111+ })
112+ .unwrap_or(false)
124 }
113 }
114+}
115+
116+#[derive(Debug)]
117+struct TableSchema {
118+ column_alias_to_name: BiMap<String, String>,
119+ hidden_columns: HashSet<String>,
120+}
125
121
126− pub fn set_column(&mut self, column_name: &str) {
122+impl TableSchema {
127− self.backing_columns.push(column_name.to_string())
123+ fn new() -> TableSchema {
124+ TableSchema {
125+ column_alias_to_name: BiMap::new(),
126+ hidden_columns: HashSet::new(),
127+ }
128 }
128 }
129
129
130− pub fn set_removed(&mut self) {
130+ fn get_column_real_name<'a>(&'a self, name: &'a str) -> &'a str {
131− self.removed = true;
131+ if let Some(real_name) = self.column_alias_to_name.get_by_left(name) {
132+ real_name
133+ } else {
134+ name
135+ }
132 }
136 }
133
137
134− fn real_name(&self) -> &str {
138+ fn get_column_alias_from_real_name(&self, real_name: &str) -> Option<String> {
135− self.backing_columns
139+ self.column_alias_to_name
136− .last()
140+ .get_by_right(real_name)
137− .expect("backing_columns should never be empty")
141+ .map(|name| name.to_string())
138 }
142 }
139}
143}
140
144
@@ -151,7 +155,6 @@ pub struct Column {
151 pub real_name: String,
155 pub real_name: String,
152 pub data_type: String,
156 pub data_type: String,
153 pub nullable: bool,
157 pub nullable: bool,
154− pub default: Option<String>,
155}
158}
156
159
157impl Schema {
160impl Schema {
@@ -165,51 +168,31 @@ impl Schema {
165 )?
168 )?
166 .iter()
169 .iter()
167 .map(|row| row.get::<'_, _, String>("table_name"))
170 .map(|row| row.get::<'_, _, String>("table_name"))
168− .filter_map(|real_name| {
171+ .filter(|real_name| !self.is_table_hidden(real_name))
169− let table_changes = self
170− .table_changes
171− .iter()
172− .find(|changes| changes.real_name == real_name);
173−
174− // Skip table if it has been removed
175− if let Some(changes) = table_changes {
176− if changes.removed {
177− return None;
178− }
179− }
180−
181− Some(self.get_table_by_real_name(db, &real_name))
172+ .map(|real_name| self.get_table_by_real_name(db, &real_name))
182− })
183 .collect()
173 .collect()
184 }
174 }
185
175
186 pub fn get_table(&self, db: &mut dyn Conn, table_name: &str) -> anyhow::Result<Table> {
176 pub fn get_table(&self, db: &mut dyn Conn, table_name: &str) -> anyhow::Result<Table> {
187− let table_changes = self
177+ let real_table_name = self
188− .table_changes
178+ .get_table_real_name(table_name)
189− .iter()
190− .find(|changes| changes.current_name == table_name);
191−
192− let real_table_name = table_changes
193− .map(|changes| changes.real_name.to_string())
194 .unwrap_or_else(|| table_name.to_string());
179 .unwrap_or_else(|| table_name.to_string());
195−
196 self.get_table_by_real_name(db, &real_table_name)
180 self.get_table_by_real_name(db, &real_table_name)
197 }
181 }
198
182
199− fn get_table_by_real_name(
183+ pub fn get_table_by_real_name(
200 &self,
184 &self,
201 db: &mut dyn Conn,
185 db: &mut dyn Conn,
202 real_table_name: &str,
186 real_table_name: &str,
203 ) -> anyhow::Result<Table> {
187 ) -> anyhow::Result<Table> {
204− let table_changes = self
188+ if self.is_table_hidden(real_table_name) {
205− .table_changes
189+ return Err(anyhow!("no table named {}", real_table_name));
206− .iter()
190+ }
207− .find(|changes| changes.real_name == real_table_name);
208
191
209− let real_columns: Vec<(String, String, bool, Option<String>)> = db
192+ let real_columns: Vec<(String, String, bool)> = db
210 .query(&format!(
193 .query(&format!(
211 "
194 "
212− SELECT column_name, CASE WHEN data_type = 'USER-DEFINED' THEN udt_name ELSE data_type END, is_nullable, column_default
195+ SELECT column_name, data_type, is_nullable
213 FROM information_schema.columns
196 FROM information_schema.columns
214 WHERE table_name = '{table}' AND table_schema = 'public'
197 WHERE table_name = '{table}' AND table_schema = 'public'
215 ORDER BY ordinal_position
198 ORDER BY ordinal_position
@@ -222,84 +205,54 @@ impl Schema {
222 row.get("column_name"),
205 row.get("column_name"),
223 row.get("data_type"),
206 row.get("data_type"),
224 row.get::<'_, _, String>("is_nullable") == "YES",
207 row.get::<'_, _, String>("is_nullable") == "YES",
225− row.get("column_default"),
226 )
208 )
227 })
209 })
228 .collect();
210 .collect();
229
211
230− let mut ignore_columns: HashSet<String> = HashSet::new();
231− let mut aliases: HashMap<String, &str> = HashMap::new();
232−
233− if let Some(changes) = table_changes {
234− for column_changes in &changes.column_changes {
235− if column_changes.removed {
236− ignore_columns.insert(column_changes.real_name().to_string());
237− } else {
238− aliases.insert(
239− column_changes.real_name().to_string(),
240− &column_changes.current_name,
241− );
242− }
243−
244− let (_, rest) = column_changes
245− .backing_columns
246− .split_last()
247− .expect("backing_columns should never be empty");
248−
249− for column in rest {
250− ignore_columns.insert(column.to_string());
251− }
252− }
253− }
254−
255 let mut columns: Vec<Column> = Vec::new();
212 let mut columns: Vec<Column> = Vec::new();
256
213
257− for (real_name, data_type, nullable, default) in real_columns {
214+ for (column_name, data_type, nullable) in real_columns {
258− if ignore_columns.contains(&*real_name) {
215+ if self.is_column_hidden(real_table_name, &column_name) {
259 continue;
216 continue;
260 }
217 }
261
218
262− let name = aliases
219+ if is_column_temporary(&column_name) {
263− .get(&real_name)
220+ continue;
264− .map(|alias| alias.to_string())
221+ }
222+
223+ let (name, real_name) = if let Some(alias) =
224+ self.get_column_alias_from_real_name(real_table_name, &column_name)
225+ {
226+ (alias, column_name)
227+ } else {
228+ let real_name = self
229+ .get_column_real_name(real_table_name, &column_name)
230+ .unwrap_or(&column_name);
265− .unwrap_or_else(|| real_name.to_string());
231+ (column_name.to_string(), real_name.to_string())
232+ };
266
233
267 columns.push(Column {
234 columns.push(Column {
268 name,
235 name,
269 real_name,
236 real_name,
270 data_type,
237 data_type,
271 nullable,
238 nullable,
272− default,
273 });
239 });
274 }
240 }
275
241
276− let current_table_name = table_changes
242+ let table_name = self
277− .map(|changes| changes.current_name.as_ref())
243+ .get_table_alias_from_real_name(real_table_name)
278− .unwrap_or_else(|| real_table_name);
244+ .unwrap_or_else(|| real_table_name.to_string());
279
245
280 let table = Table {
246 let table = Table {
281− name: current_table_name.to_string(),
247+ name: table_name,
282 real_name: real_table_name.to_string(),
248 real_name: real_table_name.to_string(),
283− columns,
249+ columns: columns,
284 };
250 };
285
251
286 Ok(table)
252 Ok(table)
287 }
253 }
288}
254}
289
255
290−impl Table {
256+fn is_column_temporary(name: &str) -> bool {
291− pub fn real_column_names<'a>(
257+ name.starts_with("__reshape_")
292− &'a self,
293− columns: &'a [String],
294− ) -> impl Iterator<Item = &'a String> {
295− columns.iter().map(|name| {
296− self.get_column(name)
297− .map(|col| &col.real_name)
298− .unwrap_or(name)
299− })
300− }
301−
302− pub fn get_column(&self, name: &str) -> Option<&Column> {
303− self.columns.iter().find(|column| column.name == name)
304− }
305}
258}
src/state.rs+88−200
@@ -4,51 +4,43 @@ use anyhow::anyhow;
4use serde::{Deserialize, Serialize};
4use serde::{Deserialize, Serialize};
5use version::version;
5use version::version;
6
6
7−#[derive(Serialize, Deserialize, Clone, Debug)]
7+#[derive(Serialize, Deserialize, Debug)]
8+pub struct State {
9+ pub version: String,
10+ pub status: Status,
11+ pub current_migration: Option<String>,
12+ pub migrations: Vec<Migration>,
13+}
14+
15+#[derive(Serialize, Deserialize, Debug)]
8−#[serde(tag = "state")]
16+#[serde(tag = "status")]
9−pub enum State {
17+pub enum Status {
10 #[serde(rename = "idle")]
18 #[serde(rename = "idle")]
11 Idle,
19 Idle,
12
20
13− #[serde(rename = "applying")]
14− Applying { migrations: Vec<Migration> },
15−
16 #[serde(rename = "in_progress")]
21 #[serde(rename = "in_progress")]
17 InProgress { migrations: Vec<Migration> },
22 InProgress { migrations: Vec<Migration> },
18−
19− #[serde(rename = "completing")]
20− Completing {
21− migrations: Vec<Migration>,
22− current_migration_index: usize,
23− current_action_index: usize,
24− },
25−
26− #[serde(rename = "aborting")]
27− Aborting {
28− migrations: Vec<Migration>,
29− last_migration_index: usize,
30− last_action_index: usize,
31− },
32}
23}
33
24
34impl State {
25impl State {
35− pub fn load(db: &mut impl Conn) -> anyhow::Result<State> {
26+ pub fn load(db: &mut impl Conn) -> State {
36− Self::ensure_schema_and_table(db)?;
27+ Self::ensure_schema_and_table(db);
37
28
29+ let results = db
38− let results = db.query("SELECT value FROM reshape.data WHERE key = 'state'")?;
30+ .query("SELECT value FROM reshape.data WHERE key = 'state'")
31+ .unwrap();
39
32
40− let state = match results.first() {
33+ match results.first() {
41 Some(row) => {
34 Some(row) => {
42 let json: serde_json::Value = row.get(0);
35 let json: serde_json::Value = row.get(0);
43− serde_json::from_value(json)?
36+ serde_json::from_value(json).unwrap()
44 }
37 }
45 None => Default::default(),
38 None => Default::default(),
46− };
39+ }
47− Ok(state)
48 }
40 }
49
41
50 pub fn save(&self, db: &mut impl Conn) -> anyhow::Result<()> {
42 pub fn save(&self, db: &mut impl Conn) -> anyhow::Result<()> {
51− Self::ensure_schema_and_table(db)?;
43+ Self::ensure_schema_and_table(db);
52
44
53 let json = serde_json::to_value(self)?;
45 let json = serde_json::to_value(self)?;
54 db.query_with_params(
46 db.query_with_params(
@@ -61,212 +53,108 @@ impl State {
61 pub fn clear(&mut self, db: &mut impl Conn) -> anyhow::Result<()> {
53 pub fn clear(&mut self, db: &mut impl Conn) -> anyhow::Result<()> {
62 db.run("DROP SCHEMA reshape CASCADE")?;
54 db.run("DROP SCHEMA reshape CASCADE")?;
63
55
64− *self = Self::default();
56+ let default = Self::default();
57+ self.status = default.status;
58+ self.current_migration = default.current_migration;
59+ self.migrations = default.migrations;
65
60
66 Ok(())
61 Ok(())
67 }
62 }
68
63
69− // Complete will change the state from Completing to Idle
64+ pub fn set_migrations<T>(&mut self, migrations: T) -> Result<(), anyhow::Error>
70− pub fn complete(&mut self, db: &mut impl Conn) -> anyhow::Result<()> {
65+ where
71− let current_state = std::mem::replace(self, Self::Idle);
66+ T: IntoIterator<Item = Migration>,
72−
67+ {
73− match current_state {
68+ let mut new_iter = migrations.into_iter();
74− Self::Completing { migrations, .. } => {
75− // Add migrations and update state in a transaction to ensure atomicity
76− let mut transaction = db.transaction()?;
77− save_migrations(&mut transaction, &migrations)?;
78− self.save(&mut transaction)?;
79− transaction.commit()?;
80− }
81− _ => {
82− // Move old state back
83− *self = current_state;
84
69
70+ // Ensure the new migration match up with the existing ones
71+ for pair in self.migrations.iter().zip(new_iter.by_ref()) {
72+ let (existing, ref new) = pair;
73+ if existing != new {
85 return Err(anyhow!(
74 return Err(anyhow!(
86− "couldn't update state to be completed, not in Completing state"
75+ "existing migration {} does not match new migration {}",
76+ existing.name,
77+ new.name
87 ));
78 ));
88 }
79 }
89 }
80 }
90
81
82+ // Add any new migrations
83+ self.migrations.extend(new_iter);
91 Ok(())
84 Ok(())
92 }
85 }
93
86
94− pub fn applying(&mut self, new_migrations: Vec<Migration>) {
87+ pub fn add_migrations<'a>(&mut self, new_migrations: impl IntoIterator<Item = &'a Migration>) {
95− *self = Self::Applying {
96− migrations: new_migrations,
97− };
98− }
99−
100− pub fn in_progress(&mut self, new_migrations: Vec<Migration>) {
101− *self = Self::InProgress {
102− migrations: new_migrations,
88+ for migration in new_migrations.into_iter() {
103− };
104− }
105−
106− pub fn completing(
107− &mut self,
108− migrations: Vec<Migration>,
109− current_migration_index: usize,
110− current_action_index: usize,
111− ) {
112− *self = Self::Completing {
113− migrations,
89+ self.migrations.push(migration.clone());
114− current_migration_index,
115− current_action_index,
116− }
117− }
118−
119− pub fn aborting(
120− &mut self,
121− migrations: Vec<Migration>,
122− last_migration_index: usize,
123− last_action_index: usize,
124− ) {
125− *self = Self::Aborting {
126− migrations,
127− last_migration_index,
128− last_action_index,
129 }
90 }
130 }
91 }
131
92
93+ // Complete will change the status from InProgress to Idle
132− fn ensure_schema_and_table(db: &mut impl Conn) -> anyhow::Result<()> {
94+ pub fn complete(&mut self) -> anyhow::Result<()> {
133− db.run("CREATE SCHEMA IF NOT EXISTS reshape")?;
95+ let current_status = std::mem::replace(&mut self.status, Status::Idle);
134
96
135− // Create data table which will be a key-value table containing
97+ match current_status {
136− // the version and current state.
98+ Status::Idle => {
137− db.run("CREATE TABLE IF NOT EXISTS reshape.data (key TEXT PRIMARY KEY, value JSONB)")?;
99+ // Move old status back
138−
100+ self.status = current_status;
139− // Create migrations table which will store all completed migrations
101+ return Err(anyhow!("status is not in progress"));
140− db.run(
102+ }
141− "
103+ Status::InProgress { mut migrations } => {
142− CREATE TABLE IF NOT EXISTS reshape.migrations (
104+ let target_migration = migrations.last().unwrap().name.to_string();
143− index INTEGER GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
105+ self.migrations.append(&mut migrations);
144− name TEXT NOT NULL,
106+ self.current_migration = Some(target_migration);
145− description TEXT,
107+ }
146− actions JSONB NOT NULL,
108+ }
147− completed_at TIMESTAMP DEFAULT NOW()
148− )
149− ",
150− )?;
151−
152− // Update the current version
153− let encoded_version = serde_json::to_value(version!().to_string())?;
154− db.query_with_params(
155− "
156− INSERT INTO reshape.data (key, value)
157− VALUES ('version', $1)
158− ON CONFLICT (key) DO UPDATE SET value = $1
159− ",
160− &[&encoded_version],
161− )?;
162
109
163 Ok(())
110 Ok(())
164 }
111 }
165−}
166
112
167−impl Default for State {
113+ pub fn in_progress(&mut self, new_migrations: Vec<Migration>) {
168− fn default() -> Self {
114+ self.status = Status::InProgress {
169− Self::Idle
115+ migrations: new_migrations,
116+ };
170 }
117 }
171−}
172−
173−pub fn current_migration(db: &mut dyn Conn) -> anyhow::Result<Option<String>> {
174− let name: Option<String> = db
175− .query(
176− "
177− SELECT name
178− FROM reshape.migrations
179− ORDER BY index DESC
180− LIMIT 1
181− ",
182− )?
183− .first()
184− .map(|row| row.get("name"));
185− Ok(name)
186−}
187−
188−pub fn remaining_migrations(
189− db: &mut impl Conn,
190− new_migrations: impl IntoIterator<Item = Migration>,
191−) -> anyhow::Result<Vec<Migration>> {
192− let mut new_iter = new_migrations.into_iter();
193−
194− // Ensure the new migrations match up with the existing ones
195− let mut highest_index: Option<i32> = None;
196− loop {
197− let migrations = get_migrations(db, highest_index)?;
198− if migrations.is_empty() {
199− break;
200− }
201−
202− for (index, existing) in migrations {
203− highest_index = Some(index);
204
118
205− let new = match new_iter.next() {
119+ pub fn get_remaining_migrations(
206− Some(migration) => migration,
120+ &self,
207− None => {
121+ new_migrations: impl IntoIterator<Item = Migration>,
208− return Err(anyhow!(
122+ ) -> anyhow::Result<Vec<Migration>> {
209− "existing migration {} doesn't exist in local migrations",
123+ let mut new_iter = new_migrations.into_iter();
210− existing
211− ))
212− }
213− };
214
124
125+ // Ensure the new migration match up with the existing ones
126+ for pair in self.migrations.iter().zip(new_iter.by_ref()) {
127+ let (existing, ref new) = pair;
215− if existing != new.name {
128+ if existing != new {
216 return Err(anyhow!(
129 return Err(anyhow!(
217 "existing migration {} does not match new migration {}",
130 "existing migration {} does not match new migration {}",
218− existing,
131+ existing.name,
219 new.name
132 new.name
220 ));
133 ));
221 }
134 }
222 }
135 }
223− }
224
136
225− // Return the remaining migrations
226− let items: Vec<Migration> = new_iter.collect();
137+ let items: Vec<Migration> = new_iter.collect();
227− Ok(items)
228−}
229
138
230−fn get_migrations(
231− db: &mut impl Conn,
232− index_larger_than: Option<i32>,
233−) -> anyhow::Result<Vec<(i32, String)>> {
234− let rows = if let Some(index_larger_than) = index_larger_than {
235− db.query_with_params(
236− "
237− SELECT index, name
238− FROM reshape.migrations
239− WHERE index > $1
240− ORDER BY index ASC
241− LIMIT 100
242− ",
243− &[&index_larger_than],
244− )?
245− } else {
246− db.query(
247− "
248− SELECT index, name
249− FROM reshape.migrations
139+ // Return the remaining migrations
250− LIMIT 100
140+ Ok(items)
251− ",
252− )?
253− };
141+ }
254
142
255− let migrations = rows
143+ fn ensure_schema_and_table(db: &mut impl Conn) {
256− .iter()
144+ db.run("CREATE SCHEMA IF NOT EXISTS reshape").unwrap();
257− .map(|row| (row.get("index"), row.get("name")))
258− .collect();
259− Ok(migrations)
260−}
261
145
262−fn save_migrations(db: &mut impl Conn, migrations: &[Migration]) -> anyhow::Result<()> {
146+ db.run("CREATE TABLE IF NOT EXISTS reshape.data (key TEXT PRIMARY KEY, value JSONB)")
263− for migration in migrations {
147+ .unwrap();
264− let encoded_actions = serde_json::to_value(&migration.actions)?;
265− db.query_with_params(
266− "INSERT INTO reshape.migrations(name, description, actions) VALUES ($1, $2, $3)",
267− &[&migration.name, &migration.description, &encoded_actions],
268− )?;
269 }
148 }
149+}
270
150
271− Ok(())
151+impl Default for State {
152+ fn default() -> Self {
153+ State {
154+ version: version!().to_string(),
155+ status: Status::Idle,
156+ current_migration: None,
157+ migrations: vec![],
158+ }
159+ }
272}
160}
tests/add_column.rs+262−316
@@ -1,60 +1,86 @@
1+use reshape::migrations::{AddColumn, Column, CreateTable, Migration};
2+use reshape::Status;
3+
1mod common;
4mod common;
2−use common::Test;
3
5
4#[test]
6#[test]
5fn add_column() {
7fn add_column() {
6− let mut test = Test::new("Add column");
8+ let (mut reshape, mut old_db, mut new_db) = common::setup();
7−
9+
8− test.first_migration(
10+ let create_users_table = Migration::new("create_users_table", None).with_action(CreateTable {
9− r#"
10− name = "create_user_table"
11−
12− [[actions]]
13− type = "create_table"
14− name = "users"
11+ name: "users".to_string(),
15− primary_key = ["id"]
12+ primary_key: vec!["id".to_string()],
16−
13+ foreign_keys: vec![],
17− [[actions.columns]]
14+ columns: vec![
18− name = "id"
15+ Column {
19− type = "INTEGER"
16+ name: "id".to_string(),
20−
17+ data_type: "SERIAL".to_string(),
21− [[actions.columns]]
18+ nullable: true,
22− name = "name"
19+ default: None,
23− type = "TEXT"
20+ generated: None,
24− "#,
21+ },
22+ Column {
23+ name: "name".to_string(),
24+ data_type: "TEXT".to_string(),
25+ nullable: false,
26+ default: None,
27+ generated: None,
28+ },
29+ ],
30+ });
31+ let add_first_last_name_columns = Migration::new("add_first_and_last_name_columns", None)
32+ .with_action(AddColumn {
33+ table: "users".to_string(),
34+ column: Column {
35+ name: "first".to_string(),
36+ data_type: "TEXT".to_string(),
37+ nullable: false,
38+ default: None,
39+ generated: None,
40+ },
41+ up: Some("(STRING_TO_ARRAY(name, ' '))[1]".to_string()),
42+ })
43+ .with_action(AddColumn {
44+ table: "users".to_string(),
45+ column: Column {
46+ name: "last".to_string(),
47+ data_type: "TEXT".to_string(),
48+ nullable: false,
49+ default: None,
50+ generated: None,
51+ },
52+ up: Some("(STRING_TO_ARRAY(name, ' '))[2]".to_string()),
53+ });
54+
55+ let first_migrations = vec![create_users_table.clone()];
56+ let second_migrations = vec![
57+ create_users_table.clone(),
58+ add_first_last_name_columns.clone(),
59+ ];
60+
61+ // Run first migration, should automatically finish
62+ reshape.migrate(first_migrations.clone()).unwrap();
63+ assert!(matches!(reshape.state.status, Status::Idle));
64+ assert_eq!(
65+ Some(&create_users_table.name),
66+ reshape.state.current_migration.as_ref()
25 );
67 );
26
68
27− test.second_migration(
69+ // Update search paths
28− r#"
70+ old_db
29− name = "add_first_and_last_name_columns"
71+ .simple_query(&reshape::schema_query_for_migration(
30−
72+ &first_migrations.last().unwrap().name,
31− [[actions]]
73+ ))
32− type = "add_column"
74+ .unwrap();
33− table = "users"
75+ new_db
34−
76+ .simple_query(&reshape::schema_query_for_migration(
35− up = "(STRING_TO_ARRAY(name, ' '))[1]"
77+ &first_migrations.last().unwrap().name,
36−
78+ ))
37− [actions.column]
79+ .unwrap();
38− name = "first"
39− type = "TEXT"
40− nullable = false
41−
42− [[actions]]
43− type = "add_column"
44− table = "users"
45−
46− up = "(STRING_TO_ARRAY(name, ' '))[2]"
47−
48− [actions.column]
49− name = "last"
50− type = "TEXT"
51− nullable = false
52− "#,
53− );
54
80
55− test.after_first(|db| {
56− // Insert some test users
81+ // Insert some test users
82+ new_db
57− db.simple_query(
83+ .simple_query(
58 "
84 "
59 INSERT INTO users (id, name) VALUES
85 INSERT INTO users (id, name) VALUES
60 (1, 'John Doe'),
86 (1, 'John Doe'),
@@ -62,300 +88,220 @@ fn add_column() {
62 ",
88 ",
63 )
89 )
64 .unwrap();
90 .unwrap();
65− });
66
91
67− test.intermediate(|old_db, new_db| {
92+ // Run second migration
68− // Check that the existing users have the new columns populated
93+ reshape.migrate(second_migrations.clone()).unwrap();
69− let expected = vec![("John", "Doe"), ("Jane", "Doe")];
94+ new_db
70− assert!(new_db
95+ .simple_query(&reshape::schema_query_for_migration(
71− .query("SELECT first, last FROM users ORDER BY id", &[],)
96+ &second_migrations.last().unwrap().name,
72− .unwrap()
97+ ))
73− .iter()
74− .map(|row| (row.get("first"), row.get("last")))
75− .eq(expected));
76−
77− // Insert data using old schema and make sure the new columns are populated
78− old_db
79− .simple_query("INSERT INTO users (id, name) VALUES (3, 'Test Testsson')")
80− .unwrap();
81− let (first_name, last_name): (String, String) = new_db
82− .query_one("SELECT first, last from users WHERE id = 3", &[])
83− .map(|row| (row.get("first"), row.get("last")))
84− .unwrap();
85− assert_eq!(
86− ("Test", "Testsson"),
87− (first_name.as_ref(), last_name.as_ref())
88− );
89− });
90−
91− test.after_completion(|db| {
92− let expected = vec![("John", "Doe"), ("Jane", "Doe"), ("Test", "Testsson")];
93− assert!(db
94− .query("SELECT first, last FROM users ORDER BY id", &[],)
95− .unwrap()
98+ .unwrap();
96− .iter()
97− .map(|row| (row.get("first"), row.get("last")))
98− .eq(expected));
99− });
100
99
101− test.after_abort(|db| {
100+ // Check that the existing users have the new columns populated
102− let expected = vec![("John Doe"), ("Jane Doe"), ("Test Testsson")];
101+ let expected = vec![("John", "Doe"), ("Jane", "Doe")];
103− assert!(db
102+ assert!(new_db
104− .query("SELECT name FROM users ORDER BY id", &[],)
103+ .query("SELECT first, last FROM users ORDER BY id", &[],)
105− .unwrap()
104+ .unwrap()
106− .iter()
105+ .iter()
107− .map(|row| row.get::<'_, _, String>("name"))
106+ .map(|row| (row.get("first"), row.get("last")))
108− .eq(expected));
107+ .eq(expected));
108+
109+ // Insert data using old schema and make sure the new columns are populated
110+ old_db
111+ .simple_query("INSERT INTO users (id, name) VALUES (3, 'Test Testsson')")
112+ .unwrap();
113+ let (first_name, last_name): (String, String) = new_db
114+ .query_one("SELECT first, last from users WHERE id = 3", &[])
115+ .map(|row| (row.get("first"), row.get("last")))
116+ .unwrap();
117+ assert_eq!(
118+ ("Test", "Testsson"),
119+ (first_name.as_ref(), last_name.as_ref())
109− });
120+ );
110
121
111− test.run()
122+ reshape.complete_migration().unwrap();
112}
123}
113
124
114#[test]
125#[test]
115fn add_column_nullable() {
126fn add_column_nullable() {
116− let mut test = Test::new("Add nullable column");
127+ let (mut reshape, mut old_db, mut new_db) = common::setup();
117−
128+
118− test.first_migration(
129+ let create_users_table = Migration::new("create_users_table", None).with_action(CreateTable {
119− r#"
130+ name: "users".to_string(),
120− name = "create_users_table"
131+ primary_key: vec!["id".to_string()],
132+ foreign_keys: vec![],
133+ columns: vec![Column {
134+ name: "id".to_string(),
135+ data_type: "INTEGER".to_string(),
136+ nullable: true,
137+ default: None,
138+ generated: None,
139+ }],
140+ });
141+ let add_name_column = Migration::new("add_nullable_name_column", None).with_action(AddColumn {
142+ table: "users".to_string(),
143+ column: Column {
144+ name: "name".to_string(),
145+ data_type: "TEXT".to_string(),
146+ nullable: true,
147+ default: None,
148+ generated: None,
149+ },
150+ up: None,
151+ });
121
152
122− [[actions]]
153+ let first_migrations = vec![create_users_table.clone()];
123− type = "create_table"
154+ let second_migrations = vec![create_users_table.clone(), add_name_column.clone()];
124− name = "users"
125− primary_key = ["id"]
126
155
127− [[actions.columns]]
156+ // Run first migration, should automatically finish
128− name = "id"
157+ reshape.migrate(first_migrations.clone()).unwrap();
129− type = "INTEGER"
158+ assert!(matches!(reshape.state.status, Status::Idle));
130− "#,
159+ assert_eq!(
160+ Some(&create_users_table.name),
161+ reshape.state.current_migration.as_ref()
131 );
162 );
132
163
133− test.second_migration(
164+ // Update search paths
134− r#"
165+ old_db
135− name = "add_nullable_name_column"
166+ .simple_query(&reshape::schema_query_for_migration(
136−
167+ &first_migrations.last().unwrap().name,
137− [[actions]]
168+ ))
138− type = "add_column"
169+ .unwrap();
139− table = "users"
170+ new_db
140−
171+ .simple_query(&reshape::schema_query_for_migration(
141− [actions.column]
172+ &first_migrations.last().unwrap().name,
142− name = "name"
173+ ))
143− type = "TEXT"
174+ .unwrap();
144− "#,
145− );
146
175
147− test.after_first(|db| {
148− // Insert some test values
176+ // Insert some test values
177+ new_db
149− db.simple_query(
178+ .simple_query(
150 "
179 "
151− INSERT INTO users (id) VALUES (1), (2);
180+ INSERT INTO users (id) VALUES
181+ (1),
182+ (2);
152 ",
183 ",
153 )
184 )
154 .unwrap();
185 .unwrap();
155− });
156
186
157− test.intermediate(|old_db, new_db| {
187+ // Run second migration
158− // Ensure existing data got updated
188+ reshape.migrate(second_migrations.clone()).unwrap();
159− let expected: Vec<Option<String>> = vec![None, None];
189+ new_db
160− assert!(new_db
190+ .simple_query(&reshape::schema_query_for_migration(
161− .query("SELECT name FROM users ORDER BY id", &[],)
191+ &second_migrations.last().unwrap().name,
162− .unwrap()
192+ ))
163− .iter()
164− .map(|row| row.get::<_, Option<String>>("name"))
165− .eq(expected));
166−
167− // Insert data using old schema and ensure new column is NULL
168− old_db
169− .simple_query("INSERT INTO users (id) VALUES (3)")
170− .unwrap();
171− let name: Option<String> = new_db
172− .query_one("SELECT name from users WHERE id = 3", &[])
173− .map(|row| (row.get("name")))
174− .unwrap();
175− assert_eq!(None, name);
176−
177− // Ensure data can be inserted against new schema
178− new_db
179− .simple_query("INSERT INTO users (id, name) VALUES (4, 'Test Testsson'), (5, NULL)")
180− .unwrap();
193+ .unwrap();
181− });
182
194
183− test.after_completion(|db| {
195+ // Ensure existing data got updated
184− let expected: Vec<Option<String>> =
196+ let expected: Vec<Option<String>> = vec![None, None];
185− vec![None, None, None, Some("Test Testsson".to_string()), None];
197+ assert!(new_db
186− let result: Vec<Option<String>> = db
187− .query("SELECT id, name FROM users ORDER BY id", &[])
198+ .query("SELECT name FROM users ORDER BY id", &[],)
188− .unwrap()
199+ .unwrap()
189− .iter()
200+ .iter()
190− .map(|row| row.get("name"))
201+ .map(|row| row.get::<_, Option<String>>("name"))
191− .collect();
202+ .eq(expected));
192−
203+
204+ // Insert data using old schema and ensure new column is NULL
205+ old_db
206+ .simple_query("INSERT INTO users (id) VALUES (3)")
207+ .unwrap();
208+ let name: Option<String> = new_db
209+ .query_one("SELECT name from users WHERE id = 3", &[])
210+ .map(|row| (row.get("name")))
211+ .unwrap();
193− assert_eq!(result, expected);
212+ assert_eq!(None, name);
194− });
195
213
196− test.run();
214+ // Ensure data can be inserted against new schema
215+ new_db
216+ .simple_query("INSERT INTO users (id, name) VALUES (4, 'Test Testsson'), (5, NULL)")
217+ .unwrap();
218+
219+ reshape.complete_migration().unwrap();
197}
220}
198
221
199#[test]
222#[test]
200fn add_column_with_default() {
223fn add_column_with_default() {
201− let mut test = Test::new("Add column with default value");
224+ let (mut reshape, mut old_db, mut new_db) = common::setup();
202−
225+
203− test.first_migration(
226+ let create_users_table = Migration::new("create_users_table", None).with_action(CreateTable {
204− r#"
205− name = "create_users_table"
206−
207− [[actions]]
208− type = "create_table"
209− name = "users"
227+ name: "users".to_string(),
210− primary_key = ["id"]
228+ primary_key: vec!["id".to_string()],
211−
229+ foreign_keys: vec![],
212− [[actions.columns]]
230+ columns: vec![Column {
213− name = "id"
231+ name: "id".to_string(),
214− type = "INTEGER"
232+ data_type: "INTEGER".to_string(),
215− "#,
216− );
217−
218− test.second_migration(
219− r#"
220− name = "add_name_column_with_default"
221−
222− [[actions]]
223− type = "add_column"
224− table = "users"
225−
226− [actions.column]
227− name = "name"
228− type = "TEXT"
229− nullable = false
233+ nullable: true,
230− default = "'DEFAULT'"
234+ default: None,
231− "#,
235+ generated: None,
232− );
236+ }],
233−
234− test.after_first(|db| {
235− // Insert some test values
236− db.simple_query("INSERT INTO users (id) VALUES (1), (2)")
237− .unwrap();
238 });
237 });
239−
238+ let add_name_column =
240− test.intermediate(|old_db, new_db| {
239+ Migration::new("add_name_column_with_default", None).with_action(AddColumn {
241− // Ensure existing data got updated with defaults
240+ table: "users".to_string(),
242− let expected = vec!["DEFAULT".to_string(), "DEFAULT".to_string()];
241+ column: Column {
243− assert!(new_db
242+ name: "name".to_string(),
244− .query("SELECT name FROM users ORDER BY id", &[],)
243+ data_type: "TEXT".to_string(),
245− .unwrap()
244+ nullable: false,
246− .iter()
245+ default: Some("'DEFAULT'".to_string()),
247− .map(|row| row.get::<_, String>("name"))
246+ generated: None,
248− .eq(expected));
247+ },
249−
248+ up: None,
250− // Insert data using old schema and ensure new column gets the default value
249+ });
251− old_db
250+
252− .simple_query("INSERT INTO users (id) VALUES (3)")
251+ let first_migrations = vec![create_users_table.clone()];
253− .unwrap();
252+ let second_migrations = vec![create_users_table.clone(), add_name_column.clone()];
254− let name: String = new_db
253+
255− .query_one("SELECT name from users WHERE id = 3", &[])
254+ // Run first migration, should automatically finish
256− .map(|row| row.get("name"))
255+ reshape.migrate(first_migrations.clone()).unwrap();
257− .unwrap();
256+ assert!(matches!(reshape.state.status, Status::Idle));
258− assert_eq!("DEFAULT", name);
257+ assert_eq!(
259− });
258+ Some(&create_users_table.name),
260−
259+ reshape.state.current_migration.as_ref()
261− test.run();
262−}
263−
264−#[test]
265−fn add_column_with_complex_up() {
266− let mut test = Test::new("Add column complex");
267−
268− test.first_migration(
269− r#"
270− name = "create_tables"
271−
272− [[actions]]
273− type = "create_table"
274− name = "users"
275− primary_key = ["id"]
276−
277− [[actions.columns]]
278− name = "id"
279− type = "INTEGER"
280−
281− [[actions.columns]]
282− name = "email"
283− type = "TEXT"
284−
285− [[actions]]
286− type = "create_table"
287− name = "profiles"
288− primary_key = ["user_id"]
289−
290− [[actions.columns]]
291− name = "user_id"
292− type = "INTEGER"
293− "#,
294 );
260 );
295
261
296− test.second_migration(
262+ // Update search paths
297− r#"
263+ old_db
298− name = "add_profiles_email_column"
264+ .simple_query(&reshape::schema_query_for_migration(
299−
265+ &first_migrations.last().unwrap().name,
300− [[actions]]
266+ ))
301− type = "add_column"
267+ .unwrap();
302− table = "profiles"
268+ new_db
303−
269+ .simple_query(&reshape::schema_query_for_migration(
304− [actions.column]
270+ &first_migrations.last().unwrap().name,
305− name = "email"
271+ ))
306− type = "TEXT"
272+ .unwrap();
307− nullable = false
308
273
309− [actions.up]
274+ // Insert some test values
310− table = "users"
275+ new_db
311− value = "users.email"
276+ .simple_query("INSERT INTO users (id) VALUES (1), (2)")
312− where = "profiles.user_id = users.id"
277+ .unwrap();
313− "#,
314− );
315
278
316− test.after_first(|db| {
279+ // Run second migration
317− db.simple_query("INSERT INTO users (id, email) VALUES (1, 'test@example.com')")
280+ reshape.migrate(second_migrations.clone()).unwrap();
318− .unwrap();
281+ new_db
319− db.simple_query("INSERT INTO profiles (user_id) VALUES (1)")
282+ .simple_query(&reshape::schema_query_for_migration(
283+ &second_migrations.last().unwrap().name,
284+ ))
320− .unwrap();
285+ .unwrap();
321− });
322
286
323− test.intermediate(|old_db, new_db| {
287+ // Ensure existing data got updated with defaults
324− // Ensure email was backfilled on profiles
288+ let expected = vec!["DEFAULT".to_string(), "DEFAULT".to_string()];
325− let email: String = new_db
289+ assert!(new_db
326− .query(
290+ .query("SELECT name FROM users ORDER BY id", &[],)
327− "
328− SELECT email
329− FROM profiles
330− WHERE user_id = 1
331− ",
332− &[],
333− )
334− .unwrap()
291+ .unwrap()
335− .first()
292+ .iter()
336− .map(|row| row.get("email"))
293+ .map(|row| row.get::<_, String>("name"))
337− .unwrap();
294+ .eq(expected));
338− assert_eq!("test@example.com", email);
295+
339−
296+ // Insert data using old schema and ensure new column gets the default value
340− // Ensure email change in old schema is propagated to profiles table in new schema
341− old_db
297+ old_db
342− .simple_query("UPDATE users SET email = 'test2@example.com' WHERE id = 1")
298+ .simple_query("INSERT INTO users (id) VALUES (3)")
343− .unwrap();
299+ .unwrap();
344− let email: String = new_db
300+ let name: String = new_db
345− .query(
301+ .query_one("SELECT name from users WHERE id = 3", &[])
346− "
347− SELECT email
348− FROM profiles
349− WHERE user_id = 1
350− ",
351− &[],
352− )
353− .unwrap()
354− .first()
355− .map(|row| row.get("email"))
302+ .map(|row| row.get("name"))
356− .unwrap();
303+ .unwrap();
357− assert_eq!("test2@example.com", email);
304+ assert_eq!("DEFAULT", name);
358− });
359
305
360− test.run();
306+ reshape.complete_migration().unwrap();
361}
307}
tests/add_foreign_key.rsdeleted−166
@@ -1,166 +0,0 @@
1−mod common;
2−use common::Test;
3−
4−#[test]
5−fn add_foreign_key() {
6− let mut test = Test::new("Add foreign key");
7−
8− test.first_migration(
9− r#"
10− name = "create_user_table"
11−
12− [[actions]]
13− type = "create_table"
14− name = "users"
15− primary_key = ["id"]
16−
17− [[actions.columns]]
18− name = "id"
19− type = "INTEGER"
20−
21− [[actions]]
22− type = "create_table"
23− name = "items"
24− primary_key = ["id"]
25−
26− [[actions.columns]]
27− name = "id"
28− type = "INTEGER"
29−
30− [[actions.columns]]
31− name = "user_id"
32− type = "INTEGER"
33− "#,
34− );
35−
36− test.second_migration(
37− r#"
38− name = "add_foreign_key"
39−
40− [[actions]]
41− type = "add_foreign_key"
42− table = "items"
43−
44− [actions.foreign_key]
45− columns = ["user_id"]
46− referenced_table = "users"
47− referenced_columns = ["id"]
48− "#,
49− );
50−
51− test.after_first(|db| {
52− // Insert some test users
53− db.simple_query("INSERT INTO users (id) VALUES (1), (2)")
54− .unwrap();
55− });
56−
57− test.intermediate(|db, _| {
58− // Ensure items can be inserted if they reference valid users
59− db.simple_query("INSERT INTO items (id, user_id) VALUES (1, 1), (2, 2)")
60− .unwrap();
61−
62− // Ensure items can't be inserted if they don't reference valid users
63− let result = db.simple_query("INSERT INTO items (id, user_id) VALUES (3, 3)");
64− assert!(result.is_err(), "expected insert to fail");
65− });
66−
67− test.after_completion(|db| {
68− // Ensure items can be inserted if they reference valid users
69− db.simple_query("INSERT INTO items (id, user_id) VALUES (3, 1), (4, 2)")
70− .unwrap();
71−
72− // Ensure items can't be inserted if they don't reference valid users
73− let result = db.simple_query("INSERT INTO items (id, user_id) VALUES (5, 3)");
74− assert!(result.is_err(), "expected insert to fail");
75−
76− // Ensure foreign key exists with the right name
77− let foreign_key_name: Option<String> = db
78− .query(
79− "
80− SELECT tc.constraint_name
81− FROM information_schema.table_constraints AS tc
82− WHERE tc.constraint_type = 'FOREIGN KEY' AND tc.table_name='items';
83− ",
84− &[],
85− )
86− .unwrap()
87− .first()
88− .map(|row| row.get(0));
89− assert_eq!(Some("items_user_id_fkey".to_string()), foreign_key_name);
90− });
91−
92− test.after_abort(|db| {
93− // Ensure foreign key doesn't exist
94− let fk_does_not_exist = db
95− .query(
96− "
97− SELECT tc.constraint_name
98− FROM information_schema.table_constraints AS tc
99− WHERE tc.constraint_type = 'FOREIGN KEY' AND tc.table_name='items';
100− ",
101− &[],
102− )
103− .unwrap()
104− .is_empty();
105− assert!(fk_does_not_exist);
106− });
107−
108− test.run()
109−}
110−
111−#[test]
112−fn add_invalid_foreign_key() {
113− let mut test = Test::new("Add invalid foreign key");
114−
115− test.first_migration(
116− r#"
117− name = "create_user_table"
118−
119− [[actions]]
120− type = "create_table"
121− name = "users"
122− primary_key = ["id"]
123−
124− [[actions.columns]]
125− name = "id"
126− type = "INTEGER"
127−
128− [[actions]]
129− type = "create_table"
130− name = "items"
131− primary_key = ["id"]
132−
133− [[actions.columns]]
134− name = "id"
135− type = "INTEGER"
136−
137− [[actions.columns]]
138− name = "user_id"
139− type = "INTEGER"
140− "#,
141− );
142−
143− test.second_migration(
144− r#"
145− name = "add_foreign_key"
146−
147− [[actions]]
148− type = "add_foreign_key"
149− table = "items"
150−
151− [actions.foreign_key]
152− columns = ["user_id"]
153− referenced_table = "users"
154− referenced_columns = ["id"]
155− "#,
156− );
157−
158− test.after_first(|db| {
159− // Insert some items which don't reference a valid user
160− db.simple_query("INSERT INTO items (id, user_id) VALUES (1, 1), (2, 2)")
161− .unwrap();
162− });
163−
164− test.expect_failure();
165− test.run()
166−}
tests/add_index.rs+65−216
@@ -1,223 +1,72 @@
1+use reshape::migrations::{AddIndex, Column, CreateTable, Migration};
2+
1mod common;
3mod common;
2−use common::Test;
3
4
4#[test]
5#[test]
5fn add_index() {
6fn add_index() {
6− let mut test = Test::new("Add index");
7+ let (mut reshape, mut old_db, mut new_db) = common::setup();
7−
8+
8− test.first_migration(
9+ let create_table_migration =
9− r#"
10+ Migration::new("create_users_table", None).with_action(CreateTable {
10− name = "create_users_table"
11+ name: "users".to_string(),
11−
12+ primary_key: vec!["id".to_string()],
12− [[actions]]
13+ foreign_keys: vec![],
13− type = "create_table"
14+ columns: vec![
14− name = "users"
15+ Column {
15− primary_key = ["id"]
16+ name: "id".to_string(),
16−
17+ data_type: "INTEGER".to_string(),
17− [[actions.columns]]
18+ nullable: true,
18− name = "id"
19+ default: None,
19− type = "INTEGER"
20+ generated: None,
20−
21+ },
21− [[actions.columns]]
22+ Column {
22− name = "name"
23+ name: "name".to_string(),
23− type = "TEXT"
24+ data_type: "TEXT".to_string(),
24− "#,
25+ nullable: false,
25− );
26+ default: None,
26−
27+ generated: None,
27− test.second_migration(
28+ },
28− r#"
29+ ],
29− name = "add_users_name_index"
30+ });
30−
31+ let add_index_migration = Migration::new("add_name_index", None).with_action(AddIndex {
31− [[actions]]
32+ table: "users".to_string(),
32− type = "add_index"
33+ name: "name_idx".to_string(),
33− table = "users"
34+ columns: vec!["name".to_string()],
34−
35− [actions.index]
36− name = "name_idx"
37− columns = ["name"]
38− "#,
39− );
40−
41− test.intermediate(|db, _| {
42− // Ensure index is valid and ready
43− let (is_ready, is_valid): (bool, bool) = db
44− .query(
45− "
46− SELECT pg_index.indisready, pg_index.indisvalid
47− FROM pg_catalog.pg_index
48− JOIN pg_catalog.pg_class ON pg_index.indexrelid = pg_class.oid
49− WHERE pg_class.relname = 'name_idx'
50− ",
51− &[],
52− )
53− .unwrap()
54− .first()
55− .map(|row| (row.get("indisready"), row.get("indisvalid")))
56− .unwrap();
57−
58− assert!(is_ready, "expected index to be ready");
59− assert!(is_valid, "expected index to be valid");
60− });
61−
62− test.after_completion(|db| {
63− // Ensure index is valid and ready
64− let (is_ready, is_valid): (bool, bool) = db
65− .query(
66− "
67− SELECT pg_index.indisready, pg_index.indisvalid
68− FROM pg_catalog.pg_index
69− JOIN pg_catalog.pg_class ON pg_index.indexrelid = pg_class.oid
70− WHERE pg_class.relname = 'name_idx'
71− ",
72− &[],
73− )
74− .unwrap()
75− .first()
76− .map(|row| (row.get("indisready"), row.get("indisvalid")))
77− .unwrap();
78−
79− assert!(is_ready, "expected index to be ready");
80− assert!(is_valid, "expected index to be valid");
81− });
82−
83− test.run();
84−}
85−
86−#[test]
87−fn add_index_unique() {
88− let mut test = Test::new("Add unique index");
89−
90− test.first_migration(
91− r#"
92− name = "create_users_table"
93−
94− [[actions]]
95− type = "create_table"
96− name = "users"
97− primary_key = ["id"]
98−
99− [[actions.columns]]
100− name = "id"
101− type = "INTEGER"
102−
103− [[actions.columns]]
104− name = "name"
105− type = "TEXT"
106− "#,
107− );
108−
109− test.second_migration(
110− r#"
111− name = "add_name_index"
112−
113− [[actions]]
114− type = "add_index"
115− table = "users"
116−
117− [actions.index]
118− name = "name_idx"
119− columns = ["name"]
120− unique = true
121− "#,
122− );
123−
124− test.intermediate(|db, _| {
125− // Ensure index is valid, ready and unique
126− let (is_ready, is_valid, is_unique): (bool, bool, bool) = db
127− .query(
128− "
129− SELECT pg_index.indisready, pg_index.indisvalid, pg_index.indisunique
130− FROM pg_catalog.pg_index
131− JOIN pg_catalog.pg_class ON pg_index.indexrelid = pg_class.oid
132− WHERE pg_class.relname = 'name_idx'
133− ",
134− &[],
135− )
136− .unwrap()
137− .first()
138− .map(|row| {
139− (
140− row.get("indisready"),
141− row.get("indisvalid"),
142− row.get("indisunique"),
143− )
144− })
145− .unwrap();
146−
147− assert!(is_ready, "expected index to be ready");
148− assert!(is_valid, "expected index to be valid");
149− assert!(is_unique, "expected index to be unique");
150− });
151−
152− test.run();
153−}
154−
155−#[test]
156−fn add_index_with_type() {
157− let mut test = Test::new("Add GIN index");
158−
159− test.first_migration(
160− r#"
161− name = "create_users_table"
162−
163− [[actions]]
164− type = "create_table"
165− name = "users"
166− primary_key = ["id"]
167−
168− [[actions.columns]]
169− name = "id"
170− type = "INTEGER"
171−
172− [[actions.columns]]
173− name = "data"
174− type = "JSONB"
175− "#,
176− );
177−
178− test.second_migration(
179− r#"
180− name = "add_data_index"
181−
182− [[actions]]
183− type = "add_index"
184− table = "users"
185−
186− [actions.index]
187− name = "data_idx"
188− columns = ["data"]
189− type = "gin"
190− "#,
191− );
192−
193− test.intermediate(|db, _| {
194− // Ensure index is valid, ready and has the right type
195− let (is_ready, is_valid, index_type): (bool, bool, String) = db
196− .query(
197− "
198− SELECT pg_index.indisready, pg_index.indisvalid, pg_am.amname
199− FROM pg_catalog.pg_index
200− JOIN pg_catalog.pg_class ON pg_index.indexrelid = pg_class.oid
201− JOIN pg_catalog.pg_am ON pg_class.relam = pg_am.oid
202− WHERE pg_class.relname = 'data_idx'
203− ",
204− &[],
205− )
206− .unwrap()
207− .first()
208− .map(|row| {
209− (
210− row.get("indisready"),
211− row.get("indisvalid"),
212− row.get("amname"),
213− )
214− })
215− .unwrap();
216−
217− assert!(is_ready, "expected index to be ready");
218− assert!(is_valid, "expected index to be valid");
219− assert_eq!("gin", index_type, "expected index type to be GIN");
220 });
35 });
221
36
222− test.run();
37+ let first_migrations = vec![create_table_migration.clone()];
38+ let second_migrations = vec![create_table_migration.clone(), add_index_migration.clone()];
39+
40+ // Run migrations
41+ reshape.migrate(first_migrations.clone()).unwrap();
42+ reshape.migrate(second_migrations.clone()).unwrap();
43+
44+ // Update schemas of Postgres connections
45+ let old_schema_query =
46+ reshape::schema_query_for_migration(&first_migrations.last().unwrap().name);
47+ let new_schema_query =
48+ reshape::schema_query_for_migration(&second_migrations.last().unwrap().name);
49+ println!("{}", new_schema_query);
50+ old_db.simple_query(&old_schema_query).unwrap();
51+ new_db.simple_query(&new_schema_query).unwrap();
52+
53+ // Ensure index is valid and ready
54+ let result: Vec<(bool, bool)> = new_db
55+ .query(
56+ "
57+ SELECT pg_index.indisready, pg_index.indisvalid
58+ FROM pg_catalog.pg_index
59+ JOIN pg_catalog.pg_class ON pg_index.indexrelid = pg_class.oid
60+ WHERE pg_class.relname = 'name_idx'
61+ ",
62+ &[],
63+ )
64+ .unwrap()
65+ .iter()
66+ .map(|row| (row.get("indisready"), row.get("indisvalid")))
67+ .collect();
68+
69+ assert_eq!(vec![(true, true)], result);
70+
71+ reshape.complete_migration().unwrap();
223}
72}
tests/alter_column.rs+348−660
@@ -1,45 +1,66 @@
1+use reshape::migrations::{AlterColumn, Column, ColumnChanges, CreateTable, Migration};
2+use reshape::Status;
3+
1mod common;
4mod common;
2−use common::Test;
3
5
4#[test]
6#[test]
5fn alter_column_data() {
7fn alter_column_data() {
6− let mut test = Test::new("Alter column");
8+ let (mut reshape, mut old_db, mut new_db) = common::setup();
7−
9+
8− test.first_migration(
10+ let create_users_table = Migration::new("create_users_table", None).with_action(CreateTable {
9− r#"
11+ name: "users".to_string(),
10− name = "create_user_table"
12+ primary_key: vec!["id".to_string()],
11−
13+ foreign_keys: vec![],
12− [[actions]]
14+ columns: vec![
13− type = "create_table"
15+ Column {
14− name = "users"
16+ name: "id".to_string(),
15− primary_key = ["id"]
17+ data_type: "INTEGER".to_string(),
18+ nullable: true,
19+ default: None,
20+ generated: None,
21+ },
22+ Column {
23+ name: "name".to_string(),
24+ data_type: "TEXT".to_string(),
25+ nullable: false,
26+ default: None,
27+ generated: None,
28+ },
29+ ],
30+ });
31+ let uppercase_name = Migration::new("uppercase_name", None).with_action(AlterColumn {
32+ table: "users".to_string(),
33+ column: "name".to_string(),
34+ up: Some("UPPER(name)".to_string()),
35+ down: Some("LOWER(name)".to_string()),
36+ changes: ColumnChanges {
37+ data_type: None,
38+ nullable: None,
39+ name: None,
40+ },
41+ });
16
42
17− [[actions.columns]]
43+ let first_migrations = vec![create_users_table.clone()];
18− name = "id"
44+ let second_migrations = vec![create_users_table.clone(), uppercase_name.clone()];
19− type = "INTEGER"
20
45
21− [[actions.columns]]
46+ // Run first migration, should automatically finish
22− name = "name"
47+ reshape.migrate(first_migrations.clone()).unwrap();
23− type = "TEXT"
48+ assert!(matches!(reshape.state.status, Status::Idle));
24− "#,
49+ assert_eq!(
50+ Some(&create_users_table.name),
51+ reshape.state.current_migration.as_ref()
25 );
52 );
26
53
27− test.second_migration(
54+ // Update search paths
28− r#"
55+ old_db
29− name = "uppercase_name"
56+ .simple_query(&reshape::schema_query_for_migration(
30−
57+ &first_migrations.last().unwrap().name,
31− [[actions]]
58+ ))
32− type = "alter_column"
59+ .unwrap();
33− table = "users"
34− column = "name"
35− up = "UPPER(name)"
36− down = "LOWER(name)"
37− "#,
38− );
39
60
40− test.after_first(|db| {
61+ // Insert some test users
41− // Insert some test users
62+ old_db
42− db.simple_query(
63+ .simple_query(
43 "
64 "
44 INSERT INTO users (id, name) VALUES
65 INSERT INTO users (id, name) VALUES
45 (1, 'john Doe'),
66 (1, 'john Doe'),
@@ -47,81 +68,103 @@ fn alter_column_data() {
47 ",
68 ",
48 )
69 )
49 .unwrap();
70 .unwrap();
50− });
51
71
52− test.intermediate(|old_db, new_db| {
72+ // Run second migration
53− // Check that the existing users has the altered data
73+ reshape.migrate(second_migrations.clone()).unwrap();
54− let expected = vec!["JOHN DOE", "JANE DOE"];
74+ new_db
55− assert!(new_db
75+ .simple_query(&reshape::schema_query_for_migration(
56− .query("SELECT name FROM users ORDER BY id", &[],)
76+ &second_migrations.last().unwrap().name,
57− .unwrap()
77+ ))
58− .iter()
78+ .unwrap();
59− .map(|row| row.get::<_, String>("name"))
79+
60− .eq(expected));
80+ // Check that the existing users has the altered data
61−
81+ let expected = vec!["JOHN DOE", "JANE DOE"];
62− // Insert data using old schema and make sure the new schema gets correct values
82+ assert!(new_db
63− old_db
83+ .query("SELECT name FROM users ORDER BY id", &[],)
64− .simple_query("INSERT INTO users (id, name) VALUES (3, 'test testsson')")
84+ .unwrap()
65− .unwrap();
85+ .iter()
66− let result = new_db
86+ .map(|row| row.get::<_, String>("name"))
67− .query_one("SELECT name from users WHERE id = 3", &[])
87+ .eq(expected));
68− .unwrap();
88+
69− assert_eq!("TEST TESTSSON", result.get::<_, &str>("name"));
89+ // Insert data using old schema and make sure the new schema gets correct values
70−
90+ old_db
71− // Insert data using new schema and make sure the old schema gets correct values
91+ .simple_query("INSERT INTO users (id, name) VALUES (3, 'test testsson')")
72− new_db
92+ .unwrap();
73− .simple_query("INSERT INTO users (id, name) VALUES (4, 'TEST TESTSSON')")
93+ let result = new_db
74− .unwrap();
94+ .query_one("SELECT name from users WHERE id = 3", &[])
75− let result = old_db
95+ .unwrap();
76− .query_one("SELECT name from users WHERE id = 4", &[])
96+ assert_eq!("TEST TESTSSON", result.get::<_, &str>("name"));
77− .unwrap();
97+
78− assert_eq!("test testsson", result.get::<_, &str>("name"));
98+ // Insert data using new schema and make sure the old schema gets correct values
79− });
99+ new_db
100+ .simple_query("INSERT INTO users (id, name) VALUES (4, 'TEST TESTSSON')")
101+ .unwrap();
102+ let result = old_db
103+ .query_one("SELECT name from users WHERE id = 4", &[])
104+ .unwrap();
105+ assert_eq!("test testsson", result.get::<_, &str>("name"));
80
106
81− test.run();
107+ reshape.complete_migration().unwrap();
82}
108}
83
109
84#[test]
110#[test]
85fn alter_column_set_not_null() {
111fn alter_column_set_not_null() {
86− let mut test = Test::new("Set column not null");
112+ let (mut reshape, mut old_db, mut new_db) = common::setup();
87−
113+
88− test.first_migration(
114+ let create_users_table = Migration::new("create_users_table", None).with_action(CreateTable {
89− r#"
115+ name: "users".to_string(),
90− name = "create_user_table"
116+ primary_key: vec!["id".to_string()],
91−
117+ foreign_keys: vec![],
92− [[actions]]
118+ columns: vec![
93− type = "create_table"
119+ Column {
94− name = "users"
120+ name: "id".to_string(),
95− primary_key = ["id"]
121+ data_type: "INTEGER".to_string(),
122+ nullable: true,
123+ default: None,
124+ generated: None,
125+ },
126+ Column {
127+ name: "name".to_string(),
128+ data_type: "TEXT".to_string(),
129+ nullable: true,
130+ default: None,
131+ generated: None,
132+ },
133+ ],
134+ });
135+ let set_name_not_null = Migration::new("set_name_not_null", None).with_action(AlterColumn {
136+ table: "users".to_string(),
137+ column: "name".to_string(),
138+ up: Some("COALESCE(name, 'TEST_DEFAULT_VALUE')".to_string()),
139+ down: Some("name".to_string()),
140+ changes: ColumnChanges {
141+ data_type: None,
142+ nullable: Some(false),
143+ name: None,
144+ },
145+ });
96
146
97− [[actions.columns]]
147+ let first_migrations = vec![create_users_table.clone()];
98− name = "id"
148+ let second_migrations = vec![create_users_table.clone(), set_name_not_null.clone()];
99− type = "INTEGER"
100
149
101− [[actions.columns]]
150+ // Run first migration, should automatically finish
102− name = "name"
151+ reshape.migrate(first_migrations.clone()).unwrap();
103− type = "TEXT"
152+ assert!(matches!(reshape.state.status, Status::Idle));
104− "#,
153+ assert_eq!(
154+ Some(&create_users_table.name),
155+ reshape.state.current_migration.as_ref()
105 );
156 );
106
157
107− test.second_migration(
158+ // Update search paths
108− r#"
159+ old_db
109− name = "set_name_not_null"
160+ .simple_query(&reshape::schema_query_for_migration(
110−
161+ &first_migrations.last().unwrap().name,
111− [[actions]]
162+ ))
112− type = "alter_column"
163+ .unwrap();
113− table = "users"
114− column = "name"
115− up = "COALESCE(name, 'TEST_DEFAULT_VALUE')"
116−
117− [actions.changes]
118− nullable = false
119− "#,
120− );
121
164
122− test.after_first(|db| {
165+ // Insert some test users
123− // Insert some test users
166+ old_db
124− db.simple_query(
167+ .simple_query(
125 "
168 "
126 INSERT INTO users (id, name) VALUES
169 INSERT INTO users (id, name) VALUES
127 (1, 'John Doe'),
170 (1, 'John Doe'),
@@ -129,180 +172,104 @@ fn alter_column_set_not_null() {
129 ",
172 ",
130 )
173 )
131 .unwrap();
174 .unwrap();
132− });
133−
134− test.intermediate(|old_db, new_db| {
135− // Check that existing users got the correct values
136− let expected = vec!["John Doe", "TEST_DEFAULT_VALUE"];
137− assert!(new_db
138− .query("SELECT name FROM users ORDER BY id", &[],)
139− .unwrap()
140− .iter()
141− .map(|row| row.get::<_, String>("name"))
142− .eq(expected));
143−
144− // Insert data using old schema and make sure the new schema gets correct values
145− old_db
146− .simple_query("INSERT INTO users (id, name) VALUES (3, NULL)")
147− .unwrap();
148− let result = new_db
149− .query_one("SELECT name from users WHERE id = 3", &[])
150− .unwrap();
151− assert_eq!("TEST_DEFAULT_VALUE", result.get::<_, &str>("name"));
152−
153− // Insert data using new schema and make sure the old schema gets correct values
154− new_db
155− .simple_query("INSERT INTO users (id, name) VALUES (4, 'Jane Doe')")
156− .unwrap();
157− let result = old_db
158− .query_one("SELECT name from users WHERE id = 4", &[])
159− .unwrap();
160− assert_eq!("Jane Doe", result.get::<_, &str>("name"));
161−
162− // Ensure NULL can't be inserted using the new schema
163− let result = new_db.simple_query("INSERT INTO users (id, name) VALUES (5, NULL)");
164− assert!(result.is_err(), "expected insert to fail");
165− });
166−
167− test.after_completion(|db| {
168− // Ensure NULL can't be inserted
169− let result = db.simple_query("INSERT INTO users (id, name) VALUES (5, NULL)");
170− assert!(result.is_err(), "expected insert to fail");
171− });
172−
173− test.after_abort(|db| {
174− // Ensure NULL can be inserted
175− let result = db.simple_query("INSERT INTO users (id, name) VALUES (5, NULL)");
176− assert!(result.is_ok(), "expected insert to succeed");
177− });
178
175
179− test.run();
176+ // Run second migration
180−}
177+ reshape.migrate(second_migrations.clone()).unwrap();
181−
178+ new_db
182−#[test]
179+ .simple_query(&reshape::schema_query_for_migration(
183−fn alter_column_set_nullable() {
180+ &second_migrations.last().unwrap().name,
184− let mut test = Test::new("Set column nullable");
181+ ))
185−
186− test.first_migration(
187− r#"
188− name = "create_user_table"
189−
190− [[actions]]
191− type = "create_table"
192− name = "users"
193− primary_key = ["id"]
194−
195− [[actions.columns]]
196− name = "id"
197− type = "INTEGER"
198−
199− [[actions.columns]]
200− name = "name"
201− type = "TEXT"
202− nullable = false
203− "#,
204− );
205−
206− test.second_migration(
207− r#"
208− name = "set_name_nullable"
209−
210− [[actions]]
211− type = "alter_column"
212− table = "users"
213− column = "name"
214− down = "COALESCE(name, 'TEST_DEFAULT_VALUE')"
215−
216− [actions.changes]
217− nullable = true
218− "#,
219− );
220−
221− test.after_first(|db| {
222− // Insert a test user
223− db.simple_query(
224− "
225− INSERT INTO users (id, name) VALUES
226− (1, 'John Doe')
227− ",
228− )
229 .unwrap();
182 .unwrap();
230− });
231−
232− test.intermediate(|old_db, new_db| {
233− // Insert data using new schema and make sure the old schema gets correct values
234− new_db
235− .simple_query("INSERT INTO users (id, name) VALUES (2, NULL)")
236− .unwrap();
237− let result = old_db
238− .query_one("SELECT name from users WHERE id = 2", &[])
239− .unwrap();
240− assert_eq!("TEST_DEFAULT_VALUE", result.get::<_, &str>("name"));
241−
242− // Ensure NULL can't be inserted using the old schema
243− let result = old_db.simple_query("INSERT INTO users (id, name) VALUES (3, NULL)");
244− assert!(result.is_err(), "expected insert to fail");
245−
246− // Ensure NULL can be inserted using the new schema
247− let result = new_db.simple_query("INSERT INTO users (id, name) VALUES (4, NULL)");
248− assert!(result.is_ok(), "expected insert to succeed");
249− });
250
183
251− test.after_completion(|db| {
184+ // Check that existing users got the correct values
252− // Ensure NULL can be inserted
185+ let expected = vec!["John Doe", "TEST_DEFAULT_VALUE"];
253− let result = db.simple_query("INSERT INTO users (id, name) VALUES (5, NULL)");
186+ assert!(new_db
254− assert!(result.is_ok(), "expected insert to succeed");
187+ .query("SELECT name FROM users ORDER BY id", &[],)
255− });
188+ .unwrap()
189+ .iter()
190+ .map(|row| row.get::<_, String>("name"))
191+ .eq(expected));
192+
193+ // Insert data using old schema and make sure the new schema gets correct values
194+ old_db
195+ .simple_query("INSERT INTO users (id, name) VALUES (3, NULL)")
196+ .unwrap();
197+ let result = new_db
198+ .query_one("SELECT name from users WHERE id = 3", &[])
199+ .unwrap();
200+ assert_eq!("TEST_DEFAULT_VALUE", result.get::<_, &str>("name"));
256
201
257− test.after_abort(|db| {
202+ // Insert data using new schema and make sure the old schema gets correct values
258− // Ensure NULL can't be inserted
203+ new_db
259− let result = db.simple_query("INSERT INTO users (id, name) VALUES (5, NULL)");
204+ .simple_query("INSERT INTO users (id, name) VALUES (4, 'Jane Doe')")
260− assert!(result.is_err(), "expected insert to fail");
205+ .unwrap();
261− });
206+ let result = old_db
207+ .query_one("SELECT name from users WHERE id = 4", &[])
208+ .unwrap();
209+ assert_eq!("Jane Doe", result.get::<_, &str>("name"));
262
210
263− test.run();
211+ reshape.complete_migration().unwrap();
264}
212}
265
213
266#[test]
214#[test]
267fn alter_column_rename() {
215fn alter_column_rename() {
268− let mut test = Test::new("Rename column");
216+ let (mut reshape, mut old_db, mut new_db) = common::setup();
269−
217+
270− test.first_migration(
218+ let create_users_table = Migration::new("create_users_table", None).with_action(CreateTable {
271− r#"
219+ name: "users".to_string(),
272− name = "create_user_table"
220+ primary_key: vec!["id".to_string()],
273−
221+ foreign_keys: vec![],
274− [[actions]]
222+ columns: vec![
275− type = "create_table"
223+ Column {
276− name = "users"
224+ name: "id".to_string(),
277− primary_key = ["id"]
225+ data_type: "INTEGER".to_string(),
278−
226+ nullable: true,
279− [[actions.columns]]
227+ default: None,
280− name = "id"
228+ generated: None,
281− type = "INTEGER"
229+ },
282−
230+ Column {
283− [[actions.columns]]
231+ name: "name".to_string(),
284− name = "name"
232+ data_type: "TEXT".to_string(),
285− type = "TEXT"
233+ nullable: true,
286− "#,
234+ default: None,
235+ generated: None,
236+ },
237+ ],
238+ });
239+ let rename_to_full_name =
240+ Migration::new("rename_to_full_name", None).with_action(AlterColumn {
241+ table: "users".to_string(),
242+ column: "name".to_string(),
243+ up: None, // up and down are not required when only renaming a column
244+ down: None,
245+ changes: ColumnChanges {
246+ data_type: None,
247+ nullable: None,
248+ name: Some("full_name".to_string()),
249+ },
250+ });
251+
252+ let first_migrations = vec![create_users_table.clone()];
253+ let second_migrations = vec![create_users_table.clone(), rename_to_full_name.clone()];
254+
255+ // Run first migration, should automatically finish
256+ reshape.migrate(first_migrations.clone()).unwrap();
257+ assert!(matches!(reshape.state.status, Status::Idle));
258+ assert_eq!(
259+ Some(&create_users_table.name),
260+ reshape.state.current_migration.as_ref()
287 );
261 );
288
262
289− test.second_migration(
263+ // Update search paths
290− r#"
264+ old_db
291− name = "set_name_not_null"
265+ .simple_query(&reshape::schema_query_for_migration(
292−
266+ &first_migrations.last().unwrap().name,
293− [[actions]]
267+ ))
294− type = "alter_column"
268+ .unwrap();
295− table = "users"
296− column = "name"
297−
298− [actions.changes]
299− name = "full_name"
300− "#,
301− );
302
269
303− test.after_first(|db| {
270+ // Insert some test data
304− // Insert some test data
271+ old_db
305− db.simple_query(
272+ .simple_query(
306 "
273 "
307 INSERT INTO users (id, name) VALUES
274 INSERT INTO users (id, name) VALUES
308 (1, 'John Doe'),
275 (1, 'John Doe'),
@@ -310,69 +277,97 @@ fn alter_column_rename() {
310 ",
277 ",
311 )
278 )
312 .unwrap();
279 .unwrap();
313− });
314
280
315− test.intermediate(|_, new_db| {
281+ // Run second migration
316− // Check that existing values can be queried using new column name
282+ reshape.migrate(second_migrations.clone()).unwrap();
317− let expected = vec!["John Doe", "Jane Doe"];
283+ new_db
318− assert!(new_db
284+ .simple_query(&reshape::schema_query_for_migration(
319− .query("SELECT full_name FROM users ORDER BY id", &[],)
285+ &second_migrations.last().unwrap().name,
320− .unwrap()
286+ ))
321− .iter()
287+ .unwrap();
322− .map(|row| row.get::<_, String>("full_name"))
323− .eq(expected));
324− });
325
288
326− test.run();
289+ // Check that existing values can be queried using new column name
290+ let expected = vec!["John Doe", "Jane Doe"];
291+ assert!(new_db
292+ .query("SELECT full_name FROM users ORDER BY id", &[],)
293+ .unwrap()
294+ .iter()
295+ .map(|row| row.get::<_, String>("full_name"))
296+ .eq(expected));
297+
298+ reshape.complete_migration().unwrap();
327}
299}
328
300
329#[test]
301#[test]
330fn alter_column_multiple() {
302fn alter_column_multiple() {
331− let mut test = Test::new("Alter column value multiple times");
303+ let (mut reshape, mut old_db, mut new_db) = common::setup();
332−
304+
333− test.first_migration(
305+ let create_users_table = Migration::new("create_users_table", None).with_action(CreateTable {
334− r#"
306+ name: "users".to_string(),
335− name = "create_user_table"
307+ primary_key: vec!["id".to_string()],
336−
308+ foreign_keys: vec![],
337− [[actions]]
309+ columns: vec![
338− type = "create_table"
310+ Column {
339− name = "users"
311+ name: "id".to_string(),
340− primary_key = ["id"]
312+ data_type: "INTEGER".to_string(),
341−
313+ nullable: true,
342− [[actions.columns]]
314+ default: None,
343− name = "id"
315+ generated: None,
344− type = "INTEGER"
316+ },
345−
317+ Column {
346− [[actions.columns]]
318+ name: "counter".to_string(),
347− name = "counter"
319+ data_type: "INTEGER".to_string(),
348− type = "INTEGER"
320+ nullable: false,
349− nullable = false
321+ default: None,
350− "#,
322+ generated: None,
323+ },
324+ ],
325+ });
326+ let increment_counter_twice = Migration::new("increment_counter_twice", None)
327+ .with_action(AlterColumn {
328+ table: "users".to_string(),
329+ column: "counter".to_string(),
330+ up: Some("counter + 1".to_string()),
331+ down: Some("counter - 1".to_string()),
332+ changes: ColumnChanges {
333+ data_type: None,
334+ nullable: None,
335+ name: None,
336+ },
337+ })
338+ .with_action(AlterColumn {
339+ table: "users".to_string(),
340+ column: "counter".to_string(),
341+ up: Some("counter + 1".to_string()),
342+ down: Some("counter - 1".to_string()),
343+ changes: ColumnChanges {
344+ data_type: None,
345+ nullable: None,
346+ name: None,
347+ },
348+ });
349+
350+ let first_migrations = vec![create_users_table.clone()];
351+ let second_migrations = vec![create_users_table.clone(), increment_counter_twice.clone()];
352+
353+ // Run first migration, should automatically finish
354+ reshape.migrate(first_migrations.clone()).unwrap();
355+ assert!(matches!(reshape.state.status, Status::Idle));
356+ assert_eq!(
357+ Some(&create_users_table.name),
358+ reshape.state.current_migration.as_ref()
351 );
359 );
352
360
353− test.second_migration(
361+ // Update search paths
354− r#"
362+ old_db
355− name = "increment_counter_twice"
363+ .simple_query(&reshape::schema_query_for_migration(
356−
364+ &first_migrations.last().unwrap().name,
357− [[actions]]
365+ ))
358− type = "alter_column"
366+ .unwrap();
359− table = "users"
360− column = "counter"
361− up = "counter + 1"
362− down = "counter - 1"
363−
364− [[actions]]
365− type = "alter_column"
366− table = "users"
367− column = "counter"
368− up = "counter + 1"
369− down = "counter - 1"
370− "#,
371− );
372
367
373− test.after_first(|db| {
368+ // Insert some test data
374− // Insert some test data
369+ old_db
375− db.simple_query(
370+ .simple_query(
376 "
371 "
377 INSERT INTO users (id, counter) VALUES
372 INSERT INTO users (id, counter) VALUES
378 (1, 0),
373 (1, 0),
@@ -380,355 +375,48 @@ fn alter_column_multiple() {
380 ",
375 ",
381 )
376 )
382 .unwrap();
377 .unwrap();
383− });
384−
385− test.intermediate(|old_db, new_db| {
386− // Check that the existing data has been updated
387− let expected = vec![2, 102];
388− let results: Vec<i32> = new_db
389− .query("SELECT counter FROM users ORDER BY id", &[])
390− .unwrap()
391− .iter()
392− .map(|row| row.get::<_, i32>("counter"))
393− .collect();
394− assert_eq!(expected, results);
395−
396− // Update data using old schema and make sure it was updated for the new schema
397− old_db
398− .query("UPDATE users SET counter = 50 WHERE id = 1", &[])
399− .unwrap();
400− let result: i32 = new_db
401− .query("SELECT counter FROM users WHERE id = 1", &[])
402− .unwrap()
403− .iter()
404− .map(|row| row.get("counter"))
405− .nth(0)
406− .unwrap();
407− assert_eq!(52, result);
408−
409− // Update data using new schema and make sure it was updated for the old schema
410− new_db
411− .query("UPDATE users SET counter = 50 WHERE id = 1", &[])
412− .unwrap();
413− let result: i32 = old_db
414− .query("SELECT counter FROM users WHERE id = 1", &[])
415− .unwrap()
416− .iter()
417− .map(|row| row.get("counter"))
418− .nth(0)
419− .unwrap();
420− assert_eq!(48, result);
421− });
422−
423− test.run();
424−}
425−
426−#[test]
427−fn alter_column_default() {
428− let mut test = Test::new("Change default value for column");
429−
430− test.first_migration(
431− r#"
432− name = "create_user_table"
433−
434− [[actions]]
435− type = "create_table"
436− name = "users"
437− primary_key = ["id"]
438−
439− [[actions.columns]]
440− name = "id"
441− type = "INTEGER"
442−
443− [[actions.columns]]
444− name = "name"
445− type = "TEXT"
446− nullable = false
447− default = "'DEFAULT'"
448− "#,
449− );
450−
451− test.second_migration(
452− r#"
453− name = "change_name_default"
454−
455− [[actions]]
456− type = "alter_column"
457− table = "users"
458− column = "name"
459−
460− [actions.changes]
461− default = "'NEW DEFAULT'"
462− "#,
463− );
464
378
465− test.after_first(|db| {
379+ // Run second migration
466− // Insert a test user
380+ reshape.migrate(second_migrations.clone()).unwrap();
467− db.simple_query(
381+ new_db
468− "
382+ .simple_query(&reshape::schema_query_for_migration(
469− INSERT INTO users (id) VALUES (1)
383+ &second_migrations.last().unwrap().name,
470− ",
384+ ))
471− )
472 .unwrap();
385 .unwrap();
473− });
474−
475− test.intermediate(|old_db, new_db| {
476− // Check that the existing users has the old default value
477− let expected = vec!["DEFAULT"];
478− assert!(new_db
479− .query("SELECT name FROM users", &[],)
480− .unwrap()
481− .iter()
482− .map(|row| row.get::<_, String>("name"))
483− .eq(expected));
484−
485− // Insert data using old schema and make those get the old default value
486− old_db
487− .simple_query("INSERT INTO users (id) VALUES (2)")
488− .unwrap();
489− let result = new_db
490− .query_one("SELECT name from users WHERE id = 2", &[])
491− .unwrap();
492− assert_eq!("DEFAULT", result.get::<_, &str>("name"));
493−
494− // Insert data using new schema and make sure it gets the new default value
495− new_db
496− .simple_query("INSERT INTO users (id) VALUES (3)")
497− .unwrap();
498− let result = old_db
499− .query_one("SELECT name from users WHERE id = 3", &[])
500− .unwrap();
501− assert_eq!("NEW DEFAULT", result.get::<_, &str>("name"));
502− });
503−
504− test.run();
505−}
506−
507−#[test]
508−fn alter_column_with_index() {
509− let mut test = Test::new("Alter column with index");
510−
511− test.first_migration(
512− r#"
513− name = "create_user_table"
514−
515− [[actions]]
516− type = "create_table"
517− name = "users"
518− primary_key = ["id"]
519−
520− [[actions.columns]]
521− name = "id"
522− type = "INTEGER"
523−
524− [[actions.columns]]
525− name = "first_name"
526− type = "TEXT"
527−
528− [[actions.columns]]
529− name = "last_name"
530− type = "TEXT"
531−
532− [[actions]]
533− type = "add_index"
534− table = "users"
535−
536− [actions.index]
537− name = "users_name_idx"
538− columns = ["first_name", "last_name"]
539− "#,
540− );
541−
542− test.second_migration(
543− r#"
544− name = "uppercase_last_name"
545−
546− [[actions]]
547− type = "alter_column"
548− table = "users"
549− column = "last_name"
550− up = "UPPER(last_name)"
551− down = "LOWER(last_name)"
552− "#,
553− );
554−
555− test.after_completion(|db| {
556− // Make sure index still exists
557− let result: i64 = db
558− .query(
559− "
560− SELECT COUNT(*)
561− FROM pg_catalog.pg_index
562− JOIN pg_catalog.pg_class ON pg_index.indexrelid = pg_class.oid
563− WHERE pg_class.relname = 'users_name_idx'
564− ",
565− &[],
566− )
567− .unwrap()
568− .first()
569− .map(|row| row.get(0))
570− .unwrap();
571− assert_eq!(1, result, "expected index to still exist");
572− });
573−
574− test.run();
575−}
576−
577−#[test]
578−fn alter_column_with_unique_index() {
579− let mut test = Test::new("Alter column with unique index");
580−
581− test.first_migration(
582− r#"
583− name = "create_user_table"
584−
585− [[actions]]
586− type = "create_table"
587− name = "users"
588− primary_key = ["id"]
589−
590− [[actions.columns]]
591− name = "id"
592− type = "INTEGER"
593−
594− [[actions.columns]]
595− name = "name"
596− type = "TEXT"
597−
598− [[actions]]
599− type = "add_index"
600− table = "users"
601−
602− [actions.index]
603− name = "name_idx"
604− columns = ["name"]
605− unique = true
606− "#,
607− );
608−
609− test.second_migration(
610− r#"
611− name = "uppercase_name"
612−
613− [[actions]]
614− type = "alter_column"
615− table = "users"
616− column = "name"
617− up = "UPPER(name)"
618− down = "LOWER(name)"
619− "#,
620− );
621−
622− test.after_first(|db| {
623− db.simple_query("INSERT INTO users (id, name) VALUES (1, 'Test')")
624− .unwrap();
625− });
626−
627− test.intermediate(|old_db, new_db| {
628− // Try inserting a value which duplicates the uppercase value of an existing row
629− let result = new_db.simple_query("INSERT INTO users (id, name) VALUES (2, 'TEST')");
630− assert!(
631− result.is_err(),
632− "expected duplicate insert to new schema to fail"
633− );
634−
635− // Try inserting a value which duplicates the lowercase value of an existing row
636− new_db
637− .simple_query("INSERT INTO users (id, name) VALUES (2, 'JOHN')")
638− .unwrap();
639− let result = old_db.simple_query("INSERT INTO users (id, name) VALUES (3, 'john')");
640− assert!(
641− result.is_err(),
642− "expected duplicate insert to old schema to fail"
643− );
644− });
645−
646− test.after_completion(|db| {
647− // Make sure index still exists
648− let is_unique: bool = db
649− .query(
650− "
651− SELECT pg_index.indisunique
652− FROM pg_catalog.pg_index
653− JOIN pg_catalog.pg_class ON pg_index.indexrelid = pg_class.oid
654− WHERE pg_class.relname = 'name_idx'
655− ",
656− &[],
657− )
658− .unwrap()
659− .first()
660− .map(|row| row.get("indisunique"))
661− .unwrap();
662− assert!(is_unique, "expected index to still be unique");
663− });
664−
665− test.run();
666−}
667−
668−#[test]
669−fn alter_column_with_hash_index() {
670− let mut test = Test::new("Alter column with custom index type");
671−
672− test.first_migration(
673− r#"
674− name = "create_user_table"
675−
676− [[actions]]
677− type = "create_table"
678− name = "users"
679− primary_key = ["id"]
680−
681− [[actions.columns]]
682− name = "id"
683− type = "INTEGER"
684−
685− [[actions.columns]]
686− name = "name"
687− type = "TEXT"
688−
689− [[actions]]
690− type = "add_index"
691− table = "users"
692−
693− [actions.index]
694− name = "name_idx"
695− columns = ["name"]
696− type = "hash"
697− "#,
698− );
699
386
700− test.second_migration(
387+ // Check that the existing data has been updated
701− r#"
388+ let expected = vec![2, 102];
702− name = "uppercase_name"
389+ let results: Vec<i32> = new_db
703−
390+ .query("SELECT counter FROM users ORDER BY id", &[])
704− [[actions]]
391+ .unwrap()
705− type = "alter_column"
392+ .iter()
706− table = "users"
393+ .map(|row| row.get::<_, i32>("counter"))
707− column = "name"
394+ .collect();
708− up = "UPPER(name)"
395+ assert_eq!(expected, results);
709− down = "LOWER(name)"
396+
710− "#,
397+ // Update data using old schema and make sure it was updated for the new schema
711− );
398+ old_db
712−
399+ .query("UPDATE users SET counter = 50 WHERE id = 1", &[])
713− test.after_completion(|db| {
400+ .unwrap();
714− // Make sure index still has type GIN
401+ let result: i32 = new_db
715− let index_type: String = db
402+ .query("SELECT counter FROM users WHERE id = 1", &[])
716− .query(
403+ .unwrap()
717− "
404+ .iter()
718− SELECT pg_am.amname
405+ .map(|row| row.get("counter"))
719− FROM pg_catalog.pg_index
406+ .nth(0)
720− JOIN pg_catalog.pg_class ON pg_index.indexrelid = pg_class.oid
407+ .unwrap();
721− JOIN pg_catalog.pg_am ON pg_class.relam = pg_am.oid
408+ assert_eq!(52, result);
722− WHERE pg_class.relname = 'name_idx'
723− ",
724− &[],
725− )
726− .unwrap()
727− .first()
728− .map(|row| row.get("amname"))
729− .unwrap();
730− assert_eq!("hash", index_type);
731− });
732
409
733− test.run();
410+ // Update data using new schema and make sure it was updated for the old schema
411+ new_db
412+ .query("UPDATE users SET counter = 50 WHERE id = 1", &[])
413+ .unwrap();
414+ let result: i32 = old_db
415+ .query("SELECT counter FROM users WHERE id = 1", &[])
416+ .unwrap()
417+ .iter()
418+ .map(|row| row.get("counter"))
419+ .nth(0)
420+ .unwrap();
421+ assert_eq!(48, result);
734}
422}
tests/common.rs+9−304
@@ -1,310 +1,15 @@
1−use colored::Colorize;
2use postgres::{Client, NoTls};
1use postgres::{Client, NoTls};
3−use reshape::{migrations::Migration, Reshape};
2+use reshape::Reshape;
4
3
5−pub struct Test<'a> {
4+pub fn setup() -> (Reshape, Client, Client) {
6− name: &'a str,
5+ let connection_string = std::env::var("POSTGRES_CONNECTION_STRING")
7− reshape: Reshape,
6+ .unwrap_or("postgres://postgres:postgres@localhost/reshape_test".to_string());
8− old_db: Client,
9− new_db: Client,
10
7
11− first_migration: Option<Migration>,
8+ let old_db = Client::connect(&connection_string, NoTls).unwrap();
12− second_migration: Option<Migration>,
9+ let new_db = Client::connect(&connection_string, NoTls).unwrap();
13− expect_failure: bool,
14
10
15− clear_fn: Option<fn(&mut Client) -> ()>,
11+ let mut reshape = Reshape::new(&connection_string).unwrap();
16− after_first_fn: Option<fn(&mut Client) -> ()>,
12+ reshape.remove().unwrap();
17− intermediate_fn: Option<fn(&mut Client, &mut Client) -> ()>,
18− after_completion_fn: Option<fn(&mut Client) -> ()>,
19− after_abort_fn: Option<fn(&mut Client) -> ()>,
20−}
21−
22−impl Test<'_> {
23− pub fn new<'a>(name: &'a str) -> Test<'a> {
24− let connection_string = std::env::var("POSTGRES_CONNECTION_STRING")
25− .unwrap_or("postgres://postgres:postgres@localhost/reshape_test".to_string());
26−
27− let old_db = Client::connect(&connection_string, NoTls).unwrap();
28− let new_db = Client::connect(&connection_string, NoTls).unwrap();
29−
30− let reshape = Reshape::new(&connection_string).unwrap();
31−
32− Test {
33− name,
34− reshape,
35− old_db,
36− new_db,
37− first_migration: None,
38− second_migration: None,
39− expect_failure: false,
40− clear_fn: None,
41− after_first_fn: None,
42− intermediate_fn: None,
43− after_completion_fn: None,
44− after_abort_fn: None,
45− }
46− }
47−
48− pub fn first_migration(&mut self, migration: &str) -> &mut Self {
49− self.first_migration = Some(Self::parse_migration(migration));
50− self
51− }
52−
53− #[allow(dead_code)]
54− pub fn second_migration(&mut self, migration: &str) -> &mut Self {
55− self.second_migration = Some(Self::parse_migration(migration));
56− self
57− }
58−
59− #[allow(dead_code)]
60− pub fn clear(&mut self, f: fn(&mut Client) -> ()) -> &mut Self {
61− self.clear_fn = Some(f);
62− self
63− }
64−
65− #[allow(dead_code)]
66− pub fn after_first(&mut self, f: fn(&mut Client) -> ()) -> &mut Self {
67− self.after_first_fn = Some(f);
68− self
69− }
70−
71− #[allow(dead_code)]
72− pub fn intermediate(&mut self, f: fn(&mut Client, &mut Client) -> ()) -> &mut Self {
73− self.intermediate_fn = Some(f);
74− self
75− }
76−
77− #[allow(dead_code)]
78− pub fn after_completion(&mut self, f: fn(&mut Client) -> ()) -> &mut Self {
79− self.after_completion_fn = Some(f);
80− self
81− }
82−
83− #[allow(dead_code)]
84− pub fn after_abort(&mut self, f: fn(&mut Client) -> ()) -> &mut Self {
85− self.after_abort_fn = Some(f);
86− self
87− }
88−
89− #[allow(dead_code)]
90− pub fn expect_failure(&mut self) {
91− self.expect_failure = true;
92− }
93−
94− fn parse_migration(encoded: &str) -> Migration {
95− toml::from_str(encoded).unwrap()
96− }
97−}
98−
99−enum RunType {
100− Simple,
101− Completion,
102− Abort,
103−}
104−
105−impl Test<'_> {
106− #[allow(dead_code)]
107− pub fn run(&mut self) {
108− if self.second_migration.is_some() {
109− // Run to completion
110− print_heading(&format!("Test completion: {}", self.name));
111− self.run_internal(RunType::Completion);
112−
113− // Run and abort
114− print_heading(&format!("Test abort: {}", self.name));
115− self.run_internal(RunType::Abort);
116− } else {
117− print_heading(&format!("Test: {}", self.name));
118− self.run_internal(RunType::Simple);
119− }
120− }
121−
122− fn run_internal(&mut self, run_type: RunType) {
123− print_subheading("Clearing database");
124− self.reshape.remove().unwrap();
125−
126− if let Some(clear_fn) = self.clear_fn {
127− clear_fn(&mut self.old_db);
128− }
129−
130− // Apply first migration, will automatically complete
131− print_subheading("Applying first migration");
132− let first_migration = self
133− .first_migration
134− .as_ref()
135− .expect("no starting migration set");
136− self.reshape.migrate(vec![first_migration.clone()]).unwrap();
137−
138− // Update search path
139− self.old_db
140− .simple_query(&reshape::schema_query_for_migration(&first_migration.name))
141− .unwrap();
142−
143− // Automatically complete first migration
144− self.reshape.complete().unwrap();
145−
146− // Run setup function
147− if let Some(after_first_fn) = self.after_first_fn {
148− print_subheading("Running setup and first checks");
149− after_first_fn(&mut self.old_db);
150− print_success();
151− }
152−
153− // Apply second migration
154− if let Some(second_migration) = &self.second_migration {
155− if self.expect_failure {
156− print_subheading("Applying second migration (expecting failure)");
157− let result = self
158− .reshape
159− .migrate(vec![first_migration.clone(), second_migration.clone()]);
160−
161− if result.is_ok() {
162− panic!("expected second migration to fail");
163− }
164− } else {
165− print_subheading("Applying second migration");
166− self.reshape
167− .migrate(vec![first_migration.clone(), second_migration.clone()])
168− .unwrap();
169− }
170−
171− // Update search path
172− self.new_db
173− .simple_query(&reshape::schema_query_for_migration(&second_migration.name))
174− .unwrap();
175−
176− if let Some(intermediate_fn) = self.intermediate_fn {
177− print_subheading("Running intermediate checks");
178− intermediate_fn(&mut self.old_db, &mut self.new_db);
179− print_success();
180− }
181−
182− match run_type {
183− RunType::Completion => {
184− print_subheading("Completing");
185− self.reshape.complete().unwrap();
186−
187− if let Some(after_completion_fn) = self.after_completion_fn {
188− print_subheading("Running post-completion checks");
189− after_completion_fn(&mut self.new_db);
190− print_success();
191− }
192− }
193− RunType::Abort => {
194− print_subheading("Aborting");
195− self.reshape.abort().unwrap();
196−
197− if let Some(after_abort_fn) = self.after_abort_fn {
198− print_subheading("Running post-abort checks");
199− after_abort_fn(&mut self.old_db);
200− print_success();
201− }
202− }
203− _ => {}
204− }
205− }
206−
207− print_subheading("Checking cleanup");
208− assert_cleaned_up(&mut self.new_db);
209− print_success();
210− }
211−}
212−
213−fn print_heading(text: &str) {
214− let delimiter = std::iter::repeat("=").take(80).collect::<String>();
215−
216− println!();
217− println!();
218− println!("{}", delimiter.blue().bold());
219− println!("{}", add_spacer(text, "=").blue().bold());
220− println!("{}", delimiter.blue().bold());
221−}
222−
223−fn print_subheading(text: &str) {
224− println!();
225− println!("{}", add_spacer(text, "=").blue());
226−}
227−
228−fn print_success() {
229− println!("{}", add_spacer("Success", "=").green());
230−}
231−
232−fn add_spacer(text: &str, char: &str) -> String {
233− const TARGET_WIDTH: usize = 80;
234− let num_of_chars = (TARGET_WIDTH - text.len() - 2) / 2;
235− let spacer = std::iter::repeat(char)
236− .take(num_of_chars)
237− .collect::<String>();
238−
239− let extra = if text.len() % 2 == 0 { "" } else { char };
240−
241− format!("{spacer} {text} {spacer}{extra}", spacer = spacer)
242−}
243−
244−pub fn assert_cleaned_up(db: &mut Client) {
245− // Make sure no temporary columns remain
246− let temp_columns: Vec<String> = db
247− .query(
248− "
249− SELECT column_name
250− FROM information_schema.columns
251− WHERE table_schema = 'public'
252− AND column_name LIKE '__reshape%'
253− ",
254− &[],
255− )
256− .unwrap()
257− .iter()
258− .map(|row| row.get(0))
259− .collect();
260−
261− assert!(
262− temp_columns.is_empty(),
263− "expected no temporary columns to exist, found: {}",
264− temp_columns.join(", ")
265− );
266−
267− // Make sure no triggers remain
268− let triggers: Vec<String> = db
269− .query(
270− "
271− SELECT trigger_name
272− FROM information_schema.triggers
273− WHERE trigger_schema = 'public'
274− AND trigger_name LIKE '__reshape%'
275− ",
276− &[],
277− )
278− .unwrap()
279− .iter()
280− .map(|row| row.get(0))
281− .collect();
282−
283− assert!(
284− triggers.is_empty(),
285− "expected no triggers to exist, found: {}",
286− triggers.join(", ")
287− );
288−
289− // Make sure no functions remain
290− let functions: Vec<String> = db
291− .query(
292− "
293− SELECT routine_name
294− FROM information_schema.routines
295− WHERE routine_schema = 'public'
296− AND routine_name LIKE '__reshape%'
297− ",
298− &[],
299− )
300− .unwrap()
301− .iter()
302− .map(|row| row.get(0))
303− .collect();
304
13
305− assert!(
14+ (reshape, old_db, new_db)
306− functions.is_empty(),
307− "expected no functions to exist, found: {}",
308− functions.join(", ")
309− );
310}
15}
tests/complex.rsdeleted−379
@@ -1,379 +0,0 @@
1−mod common;
2−use common::Test;
3−
4−#[test]
5−fn move_column_between_tables() {
6− let mut test = Test::new("Move column between tables");
7−
8− test.first_migration(
9− r#"
10− name = "create_tables"
11−
12− [[actions]]
13− type = "create_table"
14− name = "users"
15− primary_key = ["id"]
16−
17− [[actions.columns]]
18− name = "id"
19− type = "INTEGER"
20−
21− [[actions.columns]]
22− name = "email"
23− type = "TEXT"
24−
25− [[actions]]
26− type = "create_table"
27− name = "profiles"
28− primary_key = ["id"]
29−
30− [[actions.columns]]
31− name = "id"
32− type = "INTEGER"
33−
34− [[actions.columns]]
35− name = "user_id"
36− type = "INTEGER"
37− nullable = false
38− "#,
39− );
40−
41− test.second_migration(
42− r#"
43− name = "move_email_column"
44−
45− [[actions]]
46− type = "add_column"
47− table = "profiles"
48−
49− [actions.column]
50− name = "email"
51− type = "TEXT"
52− nullable = false
53−
54− # When `users` is updated in the old schema, we write the email value to `profiles`
55− # When `profiles` is updated in the old schema, the equivalent `users.email` will also be updated
56− [actions.up]
57− table = "users"
58− value = "users.email"
59− where = "profiles.user_id = users.id"
60−
61− [[actions]]
62− type = "remove_column"
63− table = "users"
64− column = "email"
65−
66− # When `profiles` is changed in the new schema, we write the email address back to the removed column
67− [actions.down]
68− table = "profiles"
69− value = "profiles.email"
70− where = "users.id = profiles.user_id"
71− "#,
72− );
73−
74− test.after_first(|db| {
75− db.simple_query("INSERT INTO users (id, email) VALUES (1, 'test1@test.com')")
76− .unwrap();
77− db.simple_query("INSERT INTO users (id, email) VALUES (2, 'test2@test.com')")
78− .unwrap();
79−
80− db.simple_query("INSERT INTO profiles (id, user_id) VALUES (1, 1)")
81− .unwrap();
82− db.simple_query("INSERT INTO profiles (id, user_id) VALUES (2, 2)")
83− .unwrap();
84− });
85−
86− test.intermediate(|old_db, new_db| {
87− // Ensure emails were backfilled into profiles
88− let profiles_emails: Vec<String> = new_db
89− .query(
90− r#"
91− SELECT email
92− FROM profiles
93− ORDER BY id
94− "#,
95− &[],
96− )
97− .unwrap()
98− .iter()
99− .map(|row| row.get("email"))
100− .collect();
101− assert_eq!(vec!("test1@test.com", "test2@test.com"), profiles_emails);
102−
103− // Ensure insert in old schema updates new
104− old_db
105− .simple_query("INSERT INTO users (id, email) VALUES (3, 'test3@test.com')")
106− .unwrap();
107− old_db
108− .simple_query("INSERT INTO profiles (id, user_id) VALUES (3, 3)")
109− .unwrap();
110− let new_email: String = new_db
111− .query("SELECT email FROM profiles WHERE id = 3", &[])
112− .unwrap()
113− .first()
114− .map(|row| row.get("email"))
115− .unwrap();
116− assert_eq!("test3@test.com", new_email);
117−
118− // Ensure updates in old schema updates new
119− old_db
120− .simple_query("UPDATE users SET email = 'test3+updated@test.com' WHERE id = 3")
121− .unwrap();
122− let new_email: String = new_db
123− .query("SELECT email FROM profiles WHERE id = 3", &[])
124− .unwrap()
125− .first()
126− .map(|row| row.get("email"))
127− .unwrap();
128− assert_eq!("test3+updated@test.com", new_email);
129−
130− // Ensure insert in new schema updates old
131− new_db
132− .simple_query(
133− "INSERT INTO profiles (id, user_id, email) VALUES (4, 4, 'test4@test.com')",
134− )
135− .unwrap();
136− new_db
137− .simple_query("INSERT INTO users (id) VALUES (4)")
138− .unwrap();
139− let old_email: String = old_db
140− .query("SELECT email FROM users WHERE id = 4", &[])
141− .unwrap()
142− .first()
143− .map(|row| row.get("email"))
144− .unwrap();
145− assert_eq!("test4@test.com", old_email);
146−
147− // Ensure update in new schema updates old
148− new_db
149− .simple_query("UPDATE profiles SET email = 'test4+updated@test.com' WHERE id = 4")
150− .unwrap();
151− let old_email: String = old_db
152− .query("SELECT email FROM users WHERE id = 4", &[])
153− .unwrap()
154− .first()
155− .map(|row| row.get("email"))
156− .unwrap();
157− assert_eq!("test4+updated@test.com", old_email);
158− });
159−
160− test.run();
161−}
162−
163−#[test]
164−fn extract_relation_into_new_table() {
165− let mut test = Test::new("Extract relation into new table");
166−
167− test.first_migration(
168− r#"
169− name = "create_tables"
170−
171− [[actions]]
172− type = "create_table"
173− name = "accounts"
174− primary_key = ["id"]
175−
176− [[actions.columns]]
177− name = "id"
178− type = "INTEGER"
179−
180− [[actions]]
181− type = "create_table"
182− name = "users"
183− primary_key = ["id"]
184−
185− [[actions.columns]]
186− name = "id"
187− type = "INTEGER"
188−
189− [[actions.columns]]
190− name = "account_id"
191− type = "INTEGER"
192− nullable = false
193−
194− [[actions.columns]]
195− name = "account_role"
196− type = "TEXT"
197− nullable = false
198− "#,
199− );
200−
201− test.second_migration(
202− r#"
203− name = "add_account_user_connection"
204−
205− [[actions]]
206− type = "create_table"
207− name = "user_account_connections"
208− primary_key = ["account_id", "user_id"]
209−
210− [[actions.columns]]
211− name = "account_id"
212− type = "INTEGER"
213−
214− [[actions.columns]]
215− name = "user_id"
216− type = "INTEGER"
217−
218− [[actions.columns]]
219− name = "role"
220− type = "TEXT"
221− nullable = false
222−
223− [actions.up]
224− table = "users"
225− values = { user_id = "id", account_id = "account_id", role = "UPPER(account_role)" }
226− where = "user_account_connections.user_id = users.id"
227−
228− [[actions]]
229− type = "remove_column"
230− table = "users"
231− column = "account_id"
232−
233− [actions.down]
234− table = "user_account_connections"
235− value = "user_account_connections.account_id"
236− where = "users.id = user_account_connections.user_id"
237−
238− [[actions]]
239− type = "remove_column"
240− table = "users"
241− column = "account_role"
242−
243− [actions.down]
244− table = "user_account_connections"
245− value = "LOWER(user_account_connections.role)"
246− where = "users.id = user_account_connections.user_id"
247− "#,
248− );
249−
250− test.after_first(|db| {
251− db.simple_query("INSERT INTO accounts (id) VALUES (1)")
252− .unwrap();
253− db.simple_query("INSERT INTO users (id, account_id, account_role) VALUES (1, 1, 'admin')")
254− .unwrap();
255− });
256−
257− test.intermediate(|old_db, new_db| {
258− // Ensure connections was backfilled
259− let rows: Vec<(i32, i32, String)> = new_db
260− .query(
261− "
262− SELECT account_id, user_id, role
263− FROM user_account_connections
264− ",
265− &[],
266− )
267− .unwrap()
268− .iter()
269− .map(|row| (row.get("account_id"), row.get("user_id"), row.get("role")))
270− .collect();
271− assert_eq!(1, rows.len());
272−
273− let row = rows.first().unwrap();
274− assert_eq!(1, row.0);
275− assert_eq!(1, row.1);
276− assert_eq!("ADMIN", row.2);
277−
278− // Ensure inserted user in old schema creates a new connection
279− old_db
280− .simple_query(
281− "INSERT INTO users (id, account_id, account_role) VALUES (2, 1, 'developer')",
282− )
283− .unwrap();
284− assert!(
285− new_db
286− .query(
287− "
288− SELECT account_id, user_id, role
289− FROM user_account_connections
290− WHERE account_id = 1 AND user_id = 2 AND role = 'DEVELOPER'
291− ",
292− &[],
293− )
294− .unwrap()
295− .len()
296− == 1
297− );
298−
299− // Ensure NOT NULL constraint still applies to old schema
300− let result = old_db
301− .simple_query(
302− "INSERT INTO users (id, account_id, account_role) VALUES (2, NULL, 'developer')",
303− );
304− assert!(result.is_err());
305−
306− // Ensure updated user role in old schema updates connection in new schema
307− old_db
308− .simple_query("UPDATE users SET account_role = 'admin' WHERE id = 2")
309− .unwrap();
310− assert!(
311− new_db
312− .query(
313− "
314− SELECT account_id, user_id, role
315− FROM user_account_connections
316− WHERE account_id = 1 AND user_id = 2 AND role = 'ADMIN'
317− ",
318− &[],
319− )
320− .unwrap()
321− .len()
322− == 1
323− );
324−
325− // Ensure updated connection in new schema updates old schema user
326− new_db
327− .simple_query(
328− "UPDATE user_account_connections SET role = 'DEVELOPER' WHERE account_id = 1 AND user_id = 2",
329− )
330− .unwrap();
331− assert!(
332− old_db
333− .query(
334− "
335− SELECT id
336− FROM users
337− WHERE id = 2 AND account_id = 1 AND account_role = 'developer'
338− ",
339− &[],
340− )
341− .unwrap()
342− .len()
343− == 1
344− );
345−
346− // Ensure insert of user with connection through new schema updates user in old schema
347− new_db
348− .simple_query(
349− r#"
350− BEGIN;
351− INSERT INTO users (id) VALUES (3);
352− INSERT INTO user_account_connections (user_id, account_id, role) VALUES (3, 1, 'DEVELOPER');
353− COMMIT;
354− "#,
355− )
356− .unwrap();
357− new_db
358− .simple_query(
359− "",
360− )
361− .unwrap();
362− assert!(
363− old_db
364− .query(
365− "
366− SELECT id
367− FROM users
368− WHERE id = 3 AND account_id = 1 AND account_role = 'developer'
369− ",
370− &[],
371− )
372− .unwrap()
373− .len()
374− == 1
375− );
376− });
377−
378− test.run();
379−}
tests/create_enum.rsdeleted−41
@@ -1,41 +0,0 @@
1−mod common;
2−use common::Test;
3−
4−#[test]
5−fn create_enum() {
6− let mut test = Test::new("Create enum");
7−
8− test.first_migration(
9− r#"
10− name = "create_enum_and_table"
11−
12− [[actions]]
13− type = "create_enum"
14− name = "mood"
15− values = ["happy", "ok", "sad"]
16−
17− [[actions]]
18− type = "create_table"
19− name = "updates"
20− primary_key = ["id"]
21−
22− [[actions.columns]]
23− name = "id"
24− type = "INTEGER"
25−
26− [[actions.columns]]
27− name = "status"
28− type = "mood"
29− "#,
30− );
31−
32− test.after_first(|db| {
33− // Valid enum values should succeed
34− db.simple_query(
35− "INSERT INTO updates (id, status) VALUES (1, 'happy'), (2, 'ok'), (3, 'sad')",
36− )
37− .unwrap();
38− });
39−
40− test.run();
41−}
tests/create_table.rs+198−187
@@ -1,200 +1,211 @@
1+use reshape::{
2+ migrations::{Column, CreateTable, ForeignKey, Migration},
3+ Status,
4+};
5+
1mod common;
6mod common;
2−use common::Test;
3
7
4#[test]
8#[test]
5fn create_table() {
9fn create_table() {
6− let mut test = Test::new("Create table");
10+ let (mut reshape, mut db, _) = common::setup();
7−
11+
8− test.first_migration(
12+ let create_table_migration =
9− r#"
13+ Migration::new("create_users_table", None).with_action(CreateTable {
10− name = "create_users_table"
14+ name: "users".to_string(),
11−
15+ primary_key: vec!["id".to_string()],
12− [[actions]]
16+ foreign_keys: vec![],
13− type = "create_table"
17+ columns: vec![
14− name = "users"
18+ Column {
15− primary_key = ["id"]
19+ name: "id".to_string(),
16−
20+ data_type: "INTEGER".to_string(),
17− [[actions.columns]]
21+ nullable: true,
18− name = "id"
22+ default: None,
19− type = "INTEGER"
23+ generated: Some("ALWAYS AS IDENTITY".to_string()),
20− generated = "ALWAYS AS IDENTITY"
24+ },
21−
25+ Column {
22− [[actions.columns]]
26+ name: "name".to_string(),
23− name = "name"
27+ data_type: "TEXT".to_string(),
24− type = "TEXT"
28+ nullable: true,
25−
29+ default: None,
26− [[actions.columns]]
30+ generated: None,
27− name = "created_at"
31+ },
28− type = "TIMESTAMP"
32+ Column {
29− nullable = false
33+ name: "created_at".to_string(),
30− default = "NOW()"
34+ data_type: "TIMESTAMP".to_string(),
31− "#,
35+ nullable: false,
36+ default: Some("NOW()".to_string()),
37+ generated: None,
38+ },
39+ ],
40+ });
41+
42+ reshape
43+ .migrate(vec![create_table_migration.clone()])
44+ .unwrap();
45+ assert!(matches!(reshape.state.status, Status::Idle));
46+ assert_eq!(
47+ Some(&create_table_migration.name),
48+ reshape.state.current_migration.as_ref()
32 );
49 );
33
50
34− test.after_first(|db| {
51+ // Ensure table was created
35− // Ensure table was created
52+ let result = db
36− let result = db
53+ .query_opt(
37− .query_opt(
54+ "
38− "
55+ SELECT table_name
39− SELECT table_name
56+ FROM information_schema.tables
40− FROM information_schema.tables
57+ WHERE table_name = 'users' AND table_schema = 'public'",
41− WHERE table_name = 'users' AND table_schema = 'public'",
58+ &[],
42− &[],
59+ )
43− )
60+ .unwrap();
44− .unwrap();
61+ assert!(result.is_some());
45− assert!(result.is_some());
62+
46−
63+ // Ensure table has the right columns
47− // Ensure table has the right columns
64+ let result = db
48− let result = db
65+ .query(
49− .query(
66+ "
50− "
67+ SELECT column_name, column_default, is_nullable, data_type
51− SELECT column_name, column_default, is_nullable, data_type
68+ FROM information_schema.columns
52− FROM information_schema.columns
69+ WHERE table_name = 'users' AND table_schema = 'public'
53− WHERE table_name = 'users' AND table_schema = 'public'
70+ ORDER BY ordinal_position",
54− ORDER BY ordinal_position",
71+ &[],
55− &[],
72+ )
56− )
73+ .unwrap();
57− .unwrap();
74+
58−
75+ // id column
59− // id column
76+ let id_row = &result[0];
60− let id_row = &result[0];
77+ assert_eq!("id", id_row.get::<_, String>("column_name"));
61− assert_eq!("id", id_row.get::<_, String>("column_name"));
78+ assert!(id_row.get::<_, Option<String>>("column_default").is_none());
62− assert!(id_row.get::<_, Option<String>>("column_default").is_none());
79+ assert_eq!("NO", id_row.get::<_, String>("is_nullable"));
63− assert_eq!("NO", id_row.get::<_, String>("is_nullable"));
80+ assert_eq!("integer", id_row.get::<_, String>("data_type"));
64− assert_eq!("integer", id_row.get::<_, String>("data_type"));
81+
65−
82+ // name column
66− // name column
83+ let name_row = &result[1];
67− let name_row = &result[1];
84+ assert_eq!("name", name_row.get::<_, String>("column_name"));
68− assert_eq!("name", name_row.get::<_, String>("column_name"));
85+ assert!(name_row
69− assert!(name_row
86+ .get::<_, Option<String>>("column_default")
70− .get::<_, Option<String>>("column_default")
87+ .is_none());
71− .is_none());
88+ assert_eq!("YES", name_row.get::<_, String>("is_nullable"));
72− assert_eq!("YES", name_row.get::<_, String>("is_nullable"));
89+ assert_eq!("text", name_row.get::<_, String>("data_type"));
73− assert_eq!("text", name_row.get::<_, String>("data_type"));
90+
74−
91+ // created_at column
75− // created_at column
92+ let created_at_column = &result[2];
76− let created_at_column = &result[2];
93+ assert_eq!(
77− assert_eq!(
94+ "created_at",
78− "created_at",
95+ created_at_column.get::<_, String>("column_name")
79− created_at_column.get::<_, String>("column_name")
96+ );
80− );
97+ assert!(created_at_column
81− assert!(created_at_column
98+ .get::<_, Option<String>>("column_default")
82− .get::<_, Option<String>>("column_default")
99+ .is_some());
83− .is_some());
100+ assert_eq!("NO", created_at_column.get::<_, String>("is_nullable"));
84− assert_eq!("NO", created_at_column.get::<_, String>("is_nullable"));
101+ assert_eq!(
85− assert_eq!(
102+ "timestamp without time zone",
86− "timestamp without time zone",
103+ created_at_column.get::<_, String>("data_type")
87− created_at_column.get::<_, String>("data_type")
104+ );
88− );
89−
90− // Ensure the primary key has the right columns
91− let primary_key_columns: Vec<String> = db
92− .query(
93− "
94− SELECT a.attname AS column
95− FROM pg_index i
96− JOIN pg_attribute a ON a.attrelid = i.indrelid AND a.attnum = ANY(i.indkey)
97− JOIN pg_class t ON t.oid = i.indrelid
98− WHERE t.relname = 'users' AND i.indisprimary
99− ",
100− &[],
101− )
102− .unwrap()
103− .iter()
104− .map(|row| row.get("column"))
105− .collect();
106−
107− assert_eq!(vec!["id"], primary_key_columns);
108− });
109
105
110− test.run();
106+ // Ensure the primary key has the right columns
107+ let primary_key_columns: Vec<String> = db
108+ .query(
109+ "
110+ SELECT a.attname AS column
111+ FROM pg_index i
112+ JOIN pg_attribute a ON a.attrelid = i.indrelid AND a.attnum = ANY(i.indkey)
113+ WHERE i.indrelid = 'users'::regclass AND i.indisprimary
114+ ",
115+ &[],
116+ )
117+ .unwrap()
118+ .iter()
119+ .map(|row| row.get("column"))
120+ .collect();
121+
122+ assert_eq!(vec!["id"], primary_key_columns);
111}
123}
112
124
113#[test]
125#[test]
114fn create_table_with_foreign_keys() {
126fn create_table_with_foreign_keys() {
115− let mut test = Test::new("Create table");
127+ let (mut reshape, mut db, _) = common::setup();
116−
128+
117− test.first_migration(
129+ let create_table_migration =
118− r#"
130+ Migration::new("create_users_table", None).with_action(CreateTable {
119− name = "create_users_table"
131+ name: "users".to_string(),
120−
132+ primary_key: vec!["id".to_string()],
121− [[actions]]
133+ foreign_keys: vec![],
122− type = "create_table"
134+ columns: vec![Column {
123− name = "users"
135+ name: "id".to_string(),
124− primary_key = ["id"]
136+ data_type: "SERIAL".to_string(),
125−
137+ nullable: true, // Will be ignored by Postgres as the column is a SERIAL
126− [[actions.columns]]
138+ default: None,
127− name = "id"
139+ generated: None,
128− type = "INTEGER"
140+ }],
129− generated = "ALWAYS AS IDENTITY"
141+ });
130−
142+
131− [[actions.columns]]
143+ let create_second_table_migration =
132− name = "name"
144+ Migration::new("create_items_table", None).with_action(CreateTable {
133− type = "TEXT"
145+ name: "items".to_string(),
134−
146+ primary_key: vec!["id".to_string()],
135− [[actions.columns]]
147+ foreign_keys: vec![ForeignKey {
136− name = "created_at"
148+ columns: vec!["user_id".to_string()],
137− type = "TIMESTAMP"
149+ referenced_table: "users".to_string(),
138− nullable = false
150+ referenced_columns: vec!["id".to_string()],
139− default = "NOW()"
151+ }],
140−
152+ columns: vec![
141− [[actions]]
153+ Column {
142− type = "create_table"
154+ name: "id".to_string(),
143− name = "items"
155+ data_type: "SERIAL".to_string(),
144− primary_key = ["id"]
156+ nullable: true,
145−
157+ default: None,
146− [[actions.columns]]
158+ generated: None,
147− name = "id"
159+ },
148− type = "INTEGER"
160+ Column {
149−
161+ name: "user_id".to_string(),
150− [[actions.columns]]
162+ data_type: "INTEGER".to_string(),
151− name = "user_id"
163+ nullable: false,
152− type = "INTEGER"
164+ default: None,
153− nullable = false
165+ generated: None,
154−
166+ },
155− [[actions.foreign_keys]]
167+ ],
156− columns = ["user_id"]
168+ });
157− referenced_table = "users"
169+
158− referenced_columns = ["id"]
170+ reshape
159− "#,
171+ .migrate(vec![
160− );
172+ create_table_migration.clone(),
161−
173+ create_second_table_migration.clone(),
162− test.after_first(|db| {
174+ ])
163− let foreign_key_columns: Vec<(String, String, String)> = db
175+ .unwrap();
164− .query(
176+
165− "
177+ let foreign_key_columns: Vec<(String, String, String)> = db
166− SELECT
178+ .query(
167− kcu.column_name,
179+ "
168− ccu.table_name AS foreign_table_name,
180+ SELECT
169− ccu.column_name AS foreign_column_name
181+ kcu.column_name,
170− FROM
182+ ccu.table_name AS foreign_table_name,
171− information_schema.table_constraints AS tc
183+ ccu.column_name AS foreign_column_name
172− JOIN information_schema.key_column_usage AS kcu
184+ FROM
173− ON tc.constraint_name = kcu.constraint_name
185+ information_schema.table_constraints AS tc
174− AND tc.table_schema = kcu.table_schema
186+ JOIN information_schema.key_column_usage AS kcu
175− JOIN information_schema.constraint_column_usage AS ccu
187+ ON tc.constraint_name = kcu.constraint_name
176− ON ccu.constraint_name = tc.constraint_name
188+ AND tc.table_schema = kcu.table_schema
177− AND ccu.table_schema = tc.table_schema
189+ JOIN information_schema.constraint_column_usage AS ccu
178− WHERE tc.constraint_type = 'FOREIGN KEY' AND tc.table_name='items';
190+ ON ccu.constraint_name = tc.constraint_name
179− ",
191+ AND ccu.table_schema = tc.table_schema
180− &[],
192+ WHERE tc.constraint_type = 'FOREIGN KEY' AND tc.table_name='items';
193+ ",
194+ &[],
195+ )
196+ .unwrap()
197+ .iter()
198+ .map(|row| {
199+ (
200+ row.get("column_name"),
201+ row.get("foreign_table_name"),
202+ row.get("foreign_column_name"),
181 )
203 )
182− .unwrap()
204+ })
183− .iter()
205+ .collect();
184− .map(|row| {
206+
185− (
207+ assert_eq!(
186− row.get("column_name"),
208+ vec![("user_id".to_string(), "users".to_string(), "id".to_string())],
187− row.get("foreign_table_name"),
209+ foreign_key_columns
188− row.get("foreign_column_name"),
210+ );
189− )
190− })
191− .collect();
192−
193− assert_eq!(
194− vec![("user_id".to_string(), "users".to_string(), "id".to_string())],
195− foreign_key_columns
196− );
197− });
198−
199− test.run();
200}
211}
tests/custom.rsdeleted−128
@@ -1,128 +0,0 @@
1−mod common;
2−use common::Test;
3−
4−#[test]
5−fn custom_enable_extension() {
6− let mut test = Test::new("Custom migration");
7−
8− test.clear(|db| {
9− db.simple_query(
10− "
11− DROP EXTENSION IF EXISTS bloom;
12− DROP EXTENSION IF EXISTS btree_gin;
13− DROP EXTENSION IF EXISTS btree_gist;
14− ",
15− )
16− .unwrap();
17− });
18−
19− test.first_migration(
20− r#"
21− name = "empty_migration"
22−
23− [[actions]]
24− type = "custom"
25− "#,
26− );
27−
28− test.second_migration(
29− r#"
30− name = "enable_extensions"
31−
32− [[actions]]
33− type = "custom"
34−
35− start = """
36− CREATE EXTENSION IF NOT EXISTS bloom;
37− CREATE EXTENSION IF NOT EXISTS btree_gin;
38− """
39−
40− complete = "CREATE EXTENSION IF NOT EXISTS btree_gist"
41−
42− abort = """
43− DROP EXTENSION IF EXISTS bloom;
44− DROP EXTENSION IF EXISTS btree_gin;
45− """
46− "#,
47− );
48−
49− test.intermediate(|db, _| {
50− let bloom_activated = !db
51− .query("SELECT * FROM pg_extension WHERE extname = 'bloom'", &[])
52− .unwrap()
53− .is_empty();
54− assert!(bloom_activated);
55−
56− let btree_gin_activated = !db
57− .query(
58− "SELECT * FROM pg_extension WHERE extname = 'btree_gin'",
59− &[],
60− )
61− .unwrap()
62− .is_empty();
63− assert!(btree_gin_activated);
64−
65− let btree_gist_activated = !db
66− .query(
67− "SELECT * FROM pg_extension WHERE extname = 'btree_gist'",
68− &[],
69− )
70− .unwrap()
71− .is_empty();
72− assert!(!btree_gist_activated);
73− });
74−
75− test.after_completion(|db| {
76− let bloom_activated = !db
77− .query("SELECT * FROM pg_extension WHERE extname = 'bloom'", &[])
78− .unwrap()
79− .is_empty();
80− assert!(bloom_activated);
81−
82− let btree_gin_activated = !db
83− .query(
84− "SELECT * FROM pg_extension WHERE extname = 'btree_gin'",
85− &[],
86− )
87− .unwrap()
88− .is_empty();
89− assert!(btree_gin_activated);
90−
91− let btree_gist_activated = !db
92− .query(
93− "SELECT * FROM pg_extension WHERE extname = 'btree_gist'",
94− &[],
95− )
96− .unwrap()
97− .is_empty();
98− assert!(btree_gist_activated);
99− });
100−
101− test.after_abort(|db| {
102− let bloom_activated = !db
103− .query("SELECT * FROM pg_extension WHERE extname = 'bloom'", &[])
104− .unwrap()
105− .is_empty();
106− assert!(!bloom_activated);
107−
108− let btree_gin_activated = !db
109− .query(
110− "SELECT * FROM pg_extension WHERE extname = 'btree_gin'",
111− &[],
112− )
113− .unwrap()
114− .is_empty();
115− assert!(!btree_gin_activated);
116−
117− let btree_gist_activated = !db
118− .query(
119− "SELECT * FROM pg_extension WHERE extname = 'btree_gist'",
120− &[],
121− )
122− .unwrap()
123− .is_empty();
124− assert!(!btree_gist_activated);
125− });
126−
127− test.run();
128−}
tests/failure.rsdeleted−51
@@ -1,51 +0,0 @@
1−mod common;
2−use common::Test;
3−
4−#[test]
5−fn invalid_migration() {
6− let mut test = Test::new("Invalid migration");
7−
8− test.first_migration(
9− r#"
10− name = "invalid_migration"
11−
12− [[actions]]
13− type = "create_table"
14− name = "users"
15− primary_key = ["id"]
16−
17− [[actions.columns]]
18− name = "id"
19− type = "INTEGER"
20− "#,
21− );
22−
23− test.second_migration(
24− r#"
25− name = "add_invalid_column"
26−
27− [[actions]]
28− type = "add_column"
29− table = "users"
30−
31− up = "INVALID SQL"
32−
33− [actions.column]
34− name = "first"
35− type = "TEXT"
36− "#,
37− );
38−
39− // Insert a test user
40− test.after_first(|db| {
41− db.simple_query(
42− "
43− INSERT INTO users (id) VALUES (1)
44− ",
45− )
46− .unwrap();
47− });
48−
49− test.expect_failure();
50− test.run();
51−}
tests/remove_column.rs+75−210
@@ -1,217 +1,82 @@
1+use reshape::migrations::{Column, CreateTable, Migration, RemoveColumn};
2+
1mod common;
3mod common;
2−use common::Test;
3
4
4#[test]
5#[test]
5fn remove_column() {
6fn remove_column() {
6− let mut test = Test::new("Remove column");
7+ let (mut reshape, mut old_db, mut new_db) = common::setup();
7−
8+
8− test.first_migration(
9+ let create_table_migration =
9− r#"
10+ Migration::new("create_users_table", None).with_action(CreateTable {
10− name = "create_user_table"
11+ name: "users".to_string(),
11−
12+ primary_key: vec!["id".to_string()],
12− [[actions]]
13+ foreign_keys: vec![],
13− type = "create_table"
14+ columns: vec![
14− name = "users"
15+ Column {
15− primary_key = ["id"]
16+ name: "id".to_string(),
16−
17+ data_type: "INTEGER".to_string(),
17− [[actions.columns]]
18+ nullable: true,
18− name = "id"
19+ default: None,
19− type = "INTEGER"
20+ generated: None,
20−
21+ },
21− [[actions.columns]]
22+ Column {
22− name = "name"
23+ name: "name".to_string(),
23− type = "TEXT"
24+ data_type: "TEXT".to_string(),
24− "#,
25+ nullable: false,
25− );
26+ default: None,
26−
27+ generated: None,
27− test.second_migration(
28+ },
28− r#"
29+ ],
29− name = "remove_name_column"
30+ });
30−
31+ let remove_column_migration =
31− [[actions]]
32+ Migration::new("remove_name_column", None).with_action(RemoveColumn {
32− type = "remove_column"
33+ table: "users".to_string(),
33− table = "users"
34+ column: "name".to_string(),
34− column = "name"
35+ down: Some("'TEST_DOWN_VALUE'".to_string()),
35− down = "'TEST_DOWN_VALUE'"
36+ });
36− "#,
37+
38+ let first_migrations = vec![create_table_migration.clone()];
39+ let second_migrations = vec![
40+ create_table_migration.clone(),
41+ remove_column_migration.clone(),
42+ ];
43+
44+ // Run migrations
45+ reshape.migrate(first_migrations.clone()).unwrap();
46+ reshape.migrate(second_migrations.clone()).unwrap();
47+
48+ // Update schemas of Postgres connections
49+ let old_schema_query =
50+ reshape::schema_query_for_migration(&first_migrations.last().unwrap().name);
51+ let new_schema_query =
52+ reshape::schema_query_for_migration(&second_migrations.last().unwrap().name);
53+ old_db.simple_query(&old_schema_query).unwrap();
54+ new_db.simple_query(&new_schema_query).unwrap();
55+
56+ // Insert using old schema and ensure it can be retrieved through new schema
57+ old_db
58+ .simple_query("INSERT INTO users(id, name) VALUES (1, 'John Doe')")
59+ .unwrap();
60+ let results = new_db
61+ .query("SELECT id FROM users WHERE id = 1", &[])
62+ .unwrap();
63+ assert_eq!(1, results.len());
64+ assert_eq!(1, results[0].get::<_, i32>("id"));
65+
66+ // Ensure the name column is not accesible through the new schema
67+ assert!(new_db.query("SELECT id, name FROM users", &[]).is_err());
68+
69+ // Insert using new schema and ensure the down function is correctly applied
70+ new_db
71+ .simple_query("INSERT INTO users(id) VALUES (2)")
72+ .unwrap();
73+ let result = old_db
74+ .query_opt("SELECT name FROM users WHERE id = 2", &[])
75+ .unwrap();
76+ assert_eq!(
77+ Some("TEST_DOWN_VALUE"),
78+ result.as_ref().map(|row| row.get("name"))
37 );
79 );
38
80
39− test.intermediate(|old_db, new_db| {
81+ reshape.complete_migration().unwrap();
40− // Insert using old schema and ensure it can be retrieved through new schema
41− old_db
42− .simple_query("INSERT INTO users(id, name) VALUES (1, 'John Doe')")
43− .unwrap();
44− let results = new_db
45− .query("SELECT id FROM users WHERE id = 1", &[])
46− .unwrap();
47− assert_eq!(1, results.len());
48− assert_eq!(1, results[0].get::<_, i32>("id"));
49−
50− // Ensure the name column is not accesible through the new schema
51− assert!(new_db.query("SELECT id, name FROM users", &[]).is_err());
52−
53− // Insert using new schema and ensure the down function is correctly applied
54− new_db
55− .simple_query("INSERT INTO users(id) VALUES (2)")
56− .unwrap();
57− let result = old_db
58− .query_opt("SELECT name FROM users WHERE id = 2", &[])
59− .unwrap();
60− assert_eq!(
61− Some("TEST_DOWN_VALUE"),
62− result.as_ref().map(|row| row.get("name"))
63− );
64− });
65−
66− test.run();
67−}
68−
69−#[test]
70−fn remove_column_with_index() {
71− let mut test = Test::new("Remove column");
72−
73− test.first_migration(
74− r#"
75− name = "create_user_table"
76−
77− [[actions]]
78− type = "create_table"
79− name = "users"
80− primary_key = ["id"]
81−
82− [[actions.columns]]
83− name = "id"
84− type = "INTEGER"
85−
86− [[actions.columns]]
87− name = "name"
88− type = "TEXT"
89−
90− [[actions]]
91− type = "add_index"
92− table = "users"
93−
94− [actions.index]
95− name = "name_idx"
96− columns = ["name"]
97− "#,
98− );
99−
100− test.second_migration(
101− r#"
102− name = "remove_name_column"
103−
104− [[actions]]
105− type = "remove_column"
106− table = "users"
107− column = "name"
108− down = "'TEST_DOWN_VALUE'"
109− "#,
110− );
111−
112− test.after_completion(|db| {
113− // Ensure index has been removed after the migration is complete
114− let count: i64 = db
115− .query(
116− "
117− SELECT COUNT(*)
118− FROM pg_catalog.pg_index
119− JOIN pg_catalog.pg_class ON pg_index.indexrelid = pg_class.oid
120− WHERE pg_class.relname = 'name_idx'
121− ",
122− &[],
123− )
124− .unwrap()
125− .first()
126− .map(|row| row.get(0))
127− .unwrap();
128−
129− assert_eq!(0, count, "expected index to not exist");
130− });
131−
132− test.run();
133−}
134−
135−#[test]
136−fn remove_column_with_complex_down() {
137− let mut test = Test::new("Remove column complex");
138−
139− test.first_migration(
140− r#"
141− name = "create_tables"
142−
143− [[actions]]
144− type = "create_table"
145− name = "users"
146− primary_key = ["id"]
147−
148− [[actions.columns]]
149− name = "id"
150− type = "INTEGER"
151−
152− [[actions.columns]]
153− name = "email"
154− type = "TEXT"
155−
156− [[actions]]
157− type = "create_table"
158− name = "profiles"
159− primary_key = ["user_id"]
160−
161− [[actions.columns]]
162− name = "user_id"
163− type = "INTEGER"
164−
165− [[actions.columns]]
166− name = "email"
167− type = "TEXT"
168− "#,
169− );
170−
171− test.second_migration(
172− r#"
173− name = "remove_users_email_column"
174−
175− [[actions]]
176− type = "remove_column"
177− table = "users"
178− column = "email"
179−
180− [actions.down]
181− table = "profiles"
182− value = "profiles.email"
183− where = "users.id = profiles.user_id"
184− "#,
185− );
186−
187− test.after_first(|db| {
188− db.simple_query("INSERT INTO users (id, email) VALUES (1, 'test@example.com')")
189− .unwrap();
190− db.simple_query("INSERT INTO profiles (user_id, email) VALUES (1, 'test@example.com')")
191− .unwrap();
192− });
193−
194− test.intermediate(|old_db, new_db| {
195− new_db
196− .simple_query("UPDATE profiles SET email = 'test2@example.com' WHERE user_id = 1")
197− .unwrap();
198−
199− // Ensure new email was propagated to users table in old schema
200− let email: String = old_db
201− .query(
202− "
203− SELECT email
204− FROM users
205− WHERE id = 1
206− ",
207− &[],
208− )
209− .unwrap()
210− .first()
211− .map(|row| row.get("email"))
212− .unwrap();
213− assert_eq!("test2@example.com", email);
214− });
215−
216− test.run();
217}
82}
tests/remove_enum.rsdeleted−69
@@ -1,69 +0,0 @@
1−mod common;
2−use common::Test;
3−
4−#[test]
5−fn remove_enum() {
6− let mut test = Test::new("Remove enum");
7−
8− test.first_migration(
9− r#"
10− name = "create_enum"
11−
12− [[actions]]
13− type = "create_enum"
14− name = "mood"
15− values = ["happy", "ok", "sad"]
16− "#,
17− );
18−
19− test.second_migration(
20− r#"
21− name = "remove_enum"
22−
23− [[actions]]
24− type = "remove_enum"
25− enum = "mood"
26− "#,
27− );
28−
29− test.after_first(|db| {
30− // Ensure enum was created
31− let enum_exists = !db
32− .query(
33− "
34− SELECT typname
35− FROM pg_catalog.pg_type
36− WHERE typcategory = 'E'
37− AND typname = 'mood'
38− ",
39− &[],
40− )
41− .unwrap()
42− .is_empty();
43−
44− assert!(enum_exists, "expected mood enum to have been created");
45− });
46−
47− test.after_completion(|db| {
48− // Ensure enum was removed after completion
49− let enum_does_not_exist = db
50− .query(
51− "
52− SELECT typname
53− FROM pg_catalog.pg_type
54− WHERE typcategory = 'E'
55− AND typname = 'mood'
56− ",
57− &[],
58− )
59− .unwrap()
60− .is_empty();
61−
62− assert!(
63− enum_does_not_exist,
64− "expected mood enum to have been removed"
65− );
66− });
67−
68− test.run();
69−}
tests/remove_foreign_key.rsdeleted−124
@@ -1,124 +0,0 @@
1−mod common;
2−use common::Test;
3−
4−#[test]
5−fn remove_foreign_key() {
6− let mut test = Test::new("Remove foreign key");
7−
8− test.first_migration(
9− r#"
10− name = "create_tables"
11−
12− [[actions]]
13− type = "create_table"
14− name = "users"
15− primary_key = ["id"]
16−
17− [[actions.columns]]
18− name = "id"
19− type = "INTEGER"
20−
21− [[actions]]
22− type = "create_table"
23− name = "items"
24− primary_key = ["id"]
25−
26− [[actions.columns]]
27− name = "id"
28− type = "INTEGER"
29−
30− [[actions.columns]]
31− name = "user_id"
32− type = "INTEGER"
33−
34− [[actions.foreign_keys]]
35− columns = ["user_id"]
36− referenced_table = "users"
37− referenced_columns = ["id"]
38− "#,
39− );
40−
41− test.second_migration(
42− r#"
43− name = "remove_foreign_key"
44−
45− [[actions]]
46− type = "remove_foreign_key"
47− table = "items"
48− foreign_key = "items_user_id_fkey"
49− "#,
50− );
51−
52− test.after_first(|db| {
53− // Insert some test users
54− db.simple_query("INSERT INTO users (id) VALUES (1), (2)")
55− .unwrap();
56− });
57−
58− test.intermediate(|old_db, new_db| {
59− // Ensure items can't be inserted if they don't reference valid users
60− // The foreign key is only removed when the migration is completed so
61− // it should still be enforced for the new and old schema.
62− let result = old_db.simple_query("INSERT INTO items (id, user_id) VALUES (3, 3)");
63− assert!(
64− result.is_err(),
65− "expected insert against old schema to fail"
66− );
67−
68− let result = new_db.simple_query("INSERT INTO items (id, user_id) VALUES (3, 3)");
69− assert!(
70− result.is_err(),
71− "expected insert against new schema to fail"
72− );
73− });
74−
75− test.after_completion(|db| {
76− // Ensure items can be inserted even if they don't reference valid users
77− let result = db
78− .simple_query("INSERT INTO items (id, user_id) VALUES (5, 3)")
79− .map(|_| ());
80− assert!(
81− result.is_ok(),
82− "expected insert to not fail, got {:?}",
83− result
84− );
85−
86− // Ensure foreign key doesn't exist
87− let foreign_keys = db
88− .query(
89− "
90− SELECT tc.constraint_name
91− FROM information_schema.table_constraints AS tc
92− WHERE tc.constraint_type = 'FOREIGN KEY' AND tc.table_name='items';
93− ",
94− &[],
95− )
96− .unwrap();
97− assert!(
98− foreign_keys.is_empty(),
99− "expected no foreign keys to exist on items table"
100− );
101− });
102−
103− test.after_abort(|db| {
104− // Ensure items can't be inserted if they don't reference valid users
105− let result = db.simple_query("INSERT INTO items (id, user_id) VALUES (3, 3)");
106− assert!(result.is_err(), "expected insert to fail");
107−
108− // Ensure foreign key still exists
109− let fk_exists = !db
110− .query(
111− "
112− SELECT tc.constraint_name
113− FROM information_schema.table_constraints AS tc
114− WHERE tc.constraint_type = 'FOREIGN KEY' AND tc.table_name='items';
115− ",
116− &[],
117− )
118− .unwrap()
119− .is_empty();
120− assert!(fk_exists);
121− });
122−
123− test.run()
124−}
tests/remove_index.rsdeleted−86
@@ -1,86 +0,0 @@
1−mod common;
2−use common::Test;
3−
4−#[test]
5−fn remove_index() {
6− let mut test = Test::new("Remove index");
7−
8− test.first_migration(
9− r#"
10− name = "create_users_table"
11−
12− [[actions]]
13− type = "create_table"
14− name = "users"
15− primary_key = ["id"]
16−
17− [[actions.columns]]
18− name = "id"
19− type = "INTEGER"
20−
21− [[actions.columns]]
22− name = "name"
23− type = "TEXT"
24−
25− [[actions]]
26− type = "add_index"
27− table = "users"
28−
29− [actions.index]
30− name = "name_idx"
31− columns = ["name"]
32− "#,
33− );
34−
35− test.second_migration(
36− r#"
37− name = "remove_name_index"
38−
39− [[actions]]
40− type = "remove_index"
41− index = "name_idx"
42− "#,
43− );
44−
45− test.intermediate(|db, _| {
46− // Ensure index is still valid and ready during the migration
47− let result: Vec<(bool, bool)> = db
48− .query(
49− "
50− SELECT pg_index.indisready, pg_index.indisvalid
51− FROM pg_catalog.pg_index
52− JOIN pg_catalog.pg_class ON pg_index.indexrelid = pg_class.oid
53− WHERE pg_class.relname = 'name_idx'
54− ",
55− &[],
56− )
57− .unwrap()
58− .iter()
59− .map(|row| (row.get("indisready"), row.get("indisvalid")))
60− .collect();
61−
62− assert_eq!(vec![(true, true)], result);
63− });
64−
65− test.after_completion(|db| {
66− // Ensure index has been removed after the migration is complete
67− let count: i64 = db
68− .query(
69− "
70− SELECT COUNT(*)
71− FROM pg_catalog.pg_index
72− JOIN pg_catalog.pg_class ON pg_index.indexrelid = pg_class.oid
73− WHERE pg_class.relname = 'name_idx'
74− ",
75− &[],
76− )
77− .unwrap()
78− .first()
79− .map(|row| row.get(0))
80− .unwrap();
81−
82− assert_eq!(0, count, "expected index to not exist");
83− });
84−
85− test.run();
86−}
tests/remove_table.rs+49−39
@@ -1,44 +1,54 @@
1+use reshape::migrations::{Column, CreateTable, Migration, RemoveTable};
2+
1mod common;
3mod common;
2−use common::Test;
3
4
4#[test]
5#[test]
5fn remove_table() {
6fn remove_table() {
6− let mut test = Test::new("Remove table");
7+ let (mut reshape, mut old_db, mut new_db) = common::setup();
7−
8+
8− test.first_migration(
9+ let create_table_migration =
9− r#"
10+ Migration::new("create_users_table", None).with_action(CreateTable {
10− name = "create_users_table"
11+ name: "users".to_string(),
11−
12+ primary_key: vec!["id".to_string()],
12− [[actions]]
13+ foreign_keys: vec![],
13− type = "create_table"
14+ columns: vec![Column {
14− name = "users"
15+ name: "id".to_string(),
15− primary_key = ["id"]
16+ data_type: "INTEGER".to_string(),
16−
17+ nullable: false,
17− [[actions.columns]]
18+ default: None,
18− name = "id"
19+ generated: None,
19− type = "INTEGER"
20+ }],
20− "#,
21+ });
21− );
22+ let remove_table_migration =
22−
23+ Migration::new("remove_users_table", None).with_action(RemoveTable {
23− test.second_migration(
24+ table: "users".to_string(),
24− r#"
25+ });
25− name = "remove_users_table"
26+
26−
27+ let first_migrations = vec![create_table_migration.clone()];
27− [[actions]]
28+ let second_migrations = vec![
28− type = "remove_table"
29+ create_table_migration.clone(),
29− table = "users"
30+ remove_table_migration.clone(),
30− "#,
31+ ];
31− );
32+
32−
33+ // Run migrations
33− test.intermediate(|old_db, new_db| {
34+ reshape.migrate(first_migrations.clone()).unwrap();
34− // Make sure inserts work against the old schema
35+ reshape.migrate(second_migrations.clone()).unwrap();
35− old_db
36+
36− .simple_query("INSERT INTO users(id) VALUES (1)")
37+ // Update schemas of Postgres connections
37− .unwrap();
38+ let old_schema_query =
38−
39+ reshape::schema_query_for_migration(&first_migrations.last().unwrap().name);
39− // Ensure the table is not accessible through the new schema
40+ let new_schema_query =
40− assert!(new_db.query("SELECT id FROM users", &[]).is_err());
41+ reshape::schema_query_for_migration(&second_migrations.last().unwrap().name);
41− });
42+ old_db.simple_query(&old_schema_query).unwrap();
42−
43+ new_db.simple_query(&new_schema_query).unwrap();
43− test.run();
44+
45+ // Make sure inserts work against the old schema
46+ old_db
47+ .simple_query("INSERT INTO users(id) VALUES (1)")
48+ .unwrap();
49+
50+ // Ensure the table is not accessible through the new schema
51+ assert!(new_db.query("SELECT id FROM users", &[]).is_err());
52+
53+ reshape.complete_migration().unwrap();
44}
54}
tests/rename_table.rs+66−56
@@ -1,70 +1,80 @@
1+use reshape::migrations::{Column, CreateTable, Migration, RenameTable};
2+
1mod common;
3mod common;
2−use common::Test;
3
4
4#[test]
5#[test]
5fn rename_table() {
6fn rename_table() {
6− let mut test = Test::new("Rename table");
7+ let (mut reshape, mut old_db, mut new_db) = common::setup();
7
8
8− test.first_migration(
9+ let create_table_migration =
9− r#"
10+ Migration::new("create_users_table", None).with_action(CreateTable {
10− name = "create_users_table"
11+ name: "users".to_string(),
11−
12+ primary_key: vec!["id".to_string()],
12− [[actions]]
13+ foreign_keys: vec![],
13− type = "create_table"
14+ columns: vec![Column {
14− name = "users"
15+ name: "id".to_string(),
15− primary_key = ["id"]
16+ data_type: "INTEGER".to_string(),
17+ nullable: false,
18+ default: None,
19+ generated: None,
20+ }],
21+ });
22+ let rename_table_migration = Migration::new("rename_users_table_to_customers", None)
23+ .with_action(RenameTable {
24+ table: "users".to_string(),
25+ new_name: "customers".to_string(),
26+ });
16
27
17− [[actions.columns]]
28+ let first_migrations = vec![create_table_migration.clone()];
18− name = "id"
29+ let second_migrations = vec![
19− type = "INTEGER"
30+ create_table_migration.clone(),
20− "#,
31+ rename_table_migration.clone(),
21− );
32+ ];
22
33
23− test.second_migration(
34+ // Run migrations
24− r#"
35+ reshape.migrate(first_migrations.clone()).unwrap();
25− name = "rename_users_table_to_customers"
36+ reshape.migrate(second_migrations.clone()).unwrap();
26
37
27− [[actions]]
38+ // Update schemas of Postgres connections
28− type = "rename_table"
39+ let old_schema_query =
29− table = "users"
40+ reshape::schema_query_for_migration(&first_migrations.last().unwrap().name);
30− new_name = "customers"
41+ let new_schema_query =
31− "#,
42+ reshape::schema_query_for_migration(&second_migrations.last().unwrap().name);
32− );
43+ old_db.simple_query(&old_schema_query).unwrap();
44+ new_db.simple_query(&new_schema_query).unwrap();
45+
46+ // Make sure inserts work using both the old and new name
47+ old_db
48+ .simple_query("INSERT INTO users(id) VALUES (1)")
49+ .unwrap();
50+ new_db
51+ .simple_query("INSERT INTO customers(id) VALUES (2)")
52+ .unwrap();
33
53
34− test.intermediate(|old_db, new_db| {
54+ // Ensure the table can be queried using both the old and new name
35− // Make sure inserts work using both the old and new name
55+ let expected: Vec<i32> = vec![1, 2];
56+ assert_eq!(
57+ expected,
36 old_db
58 old_db
37− .simple_query("INSERT INTO users(id) VALUES (1)")
59+ .query("SELECT id FROM users ORDER BY id", &[])
38− .unwrap();
60+ .unwrap()
61+ .iter()
62+ .map(|row| row.get::<_, i32>("id"))
63+ .collect::<Vec<i32>>()
64+ );
65+ assert_eq!(
66+ expected,
39 new_db
67 new_db
40− .simple_query("INSERT INTO customers(id) VALUES (2)")
68+ .query("SELECT id FROM customers ORDER BY id", &[])
41− .unwrap();
69+ .unwrap()
42−
70+ .iter()
43− // Ensure the table can be queried using both the old and new name
71+ .map(|row| row.get::<_, i32>("id"))
44− let expected: Vec<i32> = vec![1, 2];
72+ .collect::<Vec<i32>>()
45− assert_eq!(
73+ );
46− expected,
47− old_db
48− .query("SELECT id FROM users ORDER BY id", &[])
49− .unwrap()
50− .iter()
51− .map(|row| row.get::<_, i32>("id"))
52− .collect::<Vec<i32>>()
53− );
54− assert_eq!(
55− expected,
56− new_db
57− .query("SELECT id FROM customers ORDER BY id", &[])
58− .unwrap()
59− .iter()
60− .map(|row| row.get::<_, i32>("id"))
61− .collect::<Vec<i32>>()
62− );
63
74
64− // Ensure the table can't be queried using the wrong name for the schema
75+ // Ensure the table can't be queried using the wrong name for the schema
65− assert!(old_db.simple_query("SELECT id FROM customers").is_err());
76+ assert!(old_db.simple_query("SELECT id FROM customers").is_err());
66− assert!(new_db.simple_query("SELECT id FROM users").is_err());
77+ assert!(new_db.simple_query("SELECT id FROM users").is_err());
67− });
68
78
69− test.run();
79+ reshape.complete_migration().unwrap();
70}
80}