on main help sign in
reshape/README.md
771 lines 24 kB history raw
1# Reshape
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)
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)!
7Reshape 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/).
9Designed for Postgres 12 and later.
11- [How it works](#how-it-works)
12- [Getting started](#getting-started)
13 - [Installation](#installation)
14 - [Creating your first migration](#creating-your-first-migration)
15 - [Preparing your application](#preparing-your-application)
16 - [Running your migration](#running-your-migration)
17 - [Using during development](#using-during-development)
18- [Writing migrations](#writing-migrations)
19 - [Basics](#basics)
20 - [Tables](#tables)
21 - [Create table](#create-table)
22 - [Rename table](#rename-table)
23 - [Remove table](#remove-table)
24 - [Add foreign key](#add-foreign-key)
25 - [Remove foreign key](#remove-foreign-key)
26 - [Columns](#columns)
27 - [Add column](#add-column)
28 - [Alter column](#alter-column)
29 - [Remove column](#remove-column)
30 - [Indices](#indices)
31 - [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)
39 - [`reshape migration start`](#reshape-migration-start)
40 - [`reshape migration complete`](#reshape-migration-complete)
41 - [`reshape migration abort`](#reshape-migration-abort)
42 - [`reshape schema-query`](#reshape-schema-query)
43 - [Connection options](#connection-options)
44- [License](#license)
46## How it works
48Reshape 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:
501. **Start migration** (`reshape migration start`): Sets up views and triggers to ensure both the new and old schema are usable at the same time.
512. **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.
523. **Complete migration** (`reshape migration complete`): Removes the old schema and any intermediate data and triggers.
54If the application deployment fails, you should run `reshape migration abort` which will roll back any changes made by `reshape migration start` without losing data.
56## Getting started
58### Installation
60#### Binaries
62Binaries are available for macOS and Linux under [Releases](https://github.com/fabianlindfors/reshape/releases).
64#### Cargo
66Reshape can be installed using [Cargo](https://doc.rust-lang.org/cargo/) (requires Rust 1.58 or later):
68```shell
69cargo install reshape
70```
72#### Docker
74Reshape is available as a Docker image on [Docker Hub](https://hub.docker.com/repository/docker/fabianlindfors/reshape).
76```shell
77docker run -v $(pwd):/usr/share/app fabianlindfors/reshape reshape migration start
78```
80### Creating your first migration
82Each 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.
84Let'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`:
86```toml
87[[actions]]
88type = "create_table"
89name = "users"
90primary_key = ["id"]
92 [[actions.columns]]
93 name = "id"
94 type = "INTEGER"
95 generated = "ALWAYS AS IDENTITY"
97 [[actions.columns]]
98 name = "name"
99 type = "TEXT"
100```
102This is the equivalent of running `CREATE TABLE users (id INTEGER GENERATED ALWAYS AS IDENTITY, name TEXT)`.
104### Preparing your application
106Reshape 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:
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)
113If 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:
115```python
116# Example for Python
117reshape_schema_query = os.getenv("RESHAPE_SCHEMA_QUERY")
118db.execute(reshape_schema_query)
119```
121### Running your migration
123To create your new `users` table, run:
125```bash
126reshape migration start --complete
127```
129We 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.
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.
133### Using during development
135When 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`.
137## Writing migrations
139### Basics
141Every migration consists of one or more actions. The actions will be run sequentially. Here's an example of a migration with two actions to create two tables, `customers` and `products`:
143```toml
144[[actions]]
145type = "create_table"
146name = "customers"
147primary_key = ["id"]
149 [[actions.columns]]
150 name = "id"
151 type = "INTEGER"
152 generated = "ALWAYS AS IDENTITY"
154[[actions]]
155type = "create_table"
156name = "products"
157primary_key = ["sku"]
159 [[actions.columns]]
160 name = "sku"
161 type = "TEXT"
162```
164Every action has a `type`. The supported types are detailed below.
166### Tables
168#### Create table
170The `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.
172_Example: create a `customers` table with a few columns and a primary key_
174```toml
175[[actions]]
176type = "create_table"
177name = "customers"
178primary_key = ["id"]
180 [[actions.columns]]
181 name = "id"
182 type = "INTEGER"
183 generated = "ALWAYS AS IDENTITY"
185 [[actions.columns]]
186 name = "name"
187 type = "TEXT"
189 # Columns default to nullable
190 nullable = false
192 # default can be any valid SQL value, in this case a string literal
193 default = "'PLACEHOLDER'"
194```
196_Example: create `users` and `items` tables with a foreign key between them_
198```toml
199[[actions]]
200type = "create_table"
201name = "users"
202primary_key = ["id"]
204 [[actions.columns]]
205 name = "id"
206 type = "INTEGER"
207 generated = "ALWAYS AS IDENTITY"
209[[actions]]
210type = "create_table"
211name = "items"
212primary_key = ["id"]
214 [[actions.columns]]
215 name = "id"
216 type = "INTEGER"
217 generated = "ALWAYS AS IDENTITY"
219 [[actions.columns]]
220 name = "user_id"
221 type = "INTEGER"
223 [[actions.foreign_keys]]
224 columns = ["user_id"]
225 referenced_table = "users"
226 referenced_columns = ["id"]
227```
229_Example: create `profiles` table based on existing `users` table_
231```toml
232[[actions]]
233type = "create_table"
234name = "profiles"
235primary_key = ["user_id"]
237 [[actions.columns]]
238 name = "user_id"
239 type = "INTEGER"
241 [[actions.columns]]
242 name = "user_email"
243 type = "TEXT"
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```
252#### Rename table
254The `rename_table` action will change the name of an existing table.
256_Example: change name of `users` table to `customers`_
258```toml
259[[actions]]
260type = "rename_table"
261table = "users"
262new_name = "customers"
263```
265#### Remove table
267The `remove_table` action will remove an existing table.
269_Example: remove `users` table_
271```toml
272[[actions]]
273type = "remove_table"
274table = "users"
275```
277#### Add foreign key
279The `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.
281_Example: create foreign key from `items` to `users` table_
283```toml
284[[actions]]
285type = "add_foreign_key"
286table = "items"
288 [actions.foreign_key]
289 columns = ["user_id"]
290 referenced_table = "users"
291 referenced_columns = ["id"]
292```
294#### Remove foreign key
296The `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.
298_Example: remove foreign key `items_user_id_fkey` from `users` table_
300```toml
301[[actions]]
302type = "remove_foreign_key"
303table = "items"
304foreign_key = "items_user_id_fkey"
305```
307### Columns
309#### Add column
311The `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)).
313_Example: add a new column `reference` to table `products`_
315```toml
316[[actions]]
317type = "add_column"
318table = "products"
320 [actions.column]
321 name = "reference"
322 type = "INTEGER"
323 nullable = false
324 default = "10"
325```
327_Example: replace an existing `name` column with two new columns, `first_name` and `last_name`_
329```toml
330[[actions]]
331type = "add_column"
332table = "users"
334# Extract the first name from the existing name column
335up = "(STRING_TO_ARRAY(name, ' '))[1]"
337 [actions.column]
338 name = "first_name"
339 type = "TEXT"
342[[actions]]
343type = "add_column"
344table = "users"
346# Extract the last name from the existing name column
347up = "(STRING_TO_ARRAY(name, ' '))[2]"
349 [actions.column]
350 name = "last_name"
351 type = "TEXT"
354[[actions]]
355type = "remove_column"
356table = "users"
357column = "name"
359# Reconstruct name column by concatenating first and last name
360down = "first_name || ' ' || last_name"
361```
363_Example: extract nested value from unstructured JSON `data` column to new `name` column_
365```toml
366[[actions]]
367type = "add_column"
368table = "users"
370# #>> '{}' converts the JSON string value to TEXT
371up = "data['path']['to']['value'] #>> '{}'"
373 [actions.column]
374 name = "name"
375 type = "TEXT"
376```
378_Example: duplicate `email` column from `users` to `profiles` table_
380```toml
381# `profiles` has `user_id` column which maps to `users.id`
382[[actions]]
383type = "add_column"
384table = "profiles"
386 [actions.column]
387 name = "email"
388 type = "TEXT"
389 nullable = false
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```
398#### Alter column
400The `alter_column` action enables many different changes to an existing column, for example renaming, changing type and changing existing values.
402When 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.
404_Example: rename `last_name` column on `users` table to `family_name`_
406```toml
407[[actions]]
408type = "alter_column"
409table = "users"
410column = "last_name"
412 [actions.changes]
413 name = "family_name"
414```
416_Example: change the type of `reference` column from `INTEGER` to `TEXT`_
418```toml
419[[actions]]
420type = "alter_column"
421table = "users"
422column = "reference"
424up = "CAST(reference AS TEXT)" # Converts from integer value to text
425down = "CAST(reference AS INTEGER)" # Converts from text value to integer
427 [actions.changes]
428 type = "TEXT" # Previous type was 'INTEGER'
429```
431_Example: increment all values of an `index` column by one_
433```toml
434[[actions]]
435type = "alter_column"
436table = "users"
437column = "index"
439up = "index + 1" # Increment for new schema
440down = "index - 1" # Decrement to revert for old schema
442 [actions.changes]
443 name = "index"
444```
446_Example: make `name` column not nullable_
448```toml
449[[actions]]
450type = "alter_column"
451table = "users"
452column = "name"
454# Use "N/A" for any rows that currently have a NULL name
455up = "COALESCE(name, 'N/A')"
457 [actions.changes]
458 nullable = false
459```
461_Example: change default value of `created_at` column to current time_
463```toml
464[[actions]]
465type = "alter_column"
466table = "users"
467column = "created_at"
469 [actions.changes]
470 default = "NOW()"
471```
473#### Remove column
475The `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.
477Any indices that cover the column will be removed.
479_Example: remove column `name` from table `users`_
481```toml
482[[actions]]
483type = "remove_column"
484table = "users"
485column = "name"
487# Use a default value of "N/A" for the old schema when inserting/updating rows
488down = "'N/A'"
489```
491_Example: remove `email` column from `users` table and use column from `profiles` table instead_
493```toml
494[[actions]]
495type = "remove_column"
496table = "users"
497column = "email"
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```
507### Indices
509#### Add index
511The `add_index` action will add a new index to an existing table.
513_Example: create a `users` table with a unique index on the `name` column_
515```toml
516[[actions]]
517type = "create_table"
518name = "users"
519primary_key = "id"
521 [[actions.columns]]
522 name = "id"
523 type = "INTEGER"
524 generated = "ALWAYS AS IDENTITY"
526 [[actions.columns]]
527 name = "name"
528 type = "TEXT"
530[[actions]]
531type = "add_index"
532table = "users"
534 [actions.index]
535 name = "name_idx"
536 columns = ["name"]
538 # Defaults to false
539 unique = true
540```
542_Example: add GIN index to `data` column on `products` table_
544```toml
545[[actions]]
546type = "add_index"
547table = "products"
549 [actions.index]
550 name = "data_idx"
551 columns = ["data"]
553 # One of: btree (default), hash, gist, spgist, gin, brin
554 type = "gin"
555```
557#### Remove index
559The `remove_index` action will remove an existing index. The index won't actually be removed until the migration is completed.
561_Example: remove the `name_idx` index_
563```toml
564[[actions]]
565type = "remove_index"
566index = "name_idx"
567```
569### Enums
571#### Create enum
573The `create_enum` action will create a new [enum type](https://www.postgresql.org/docs/current/datatype-enum.html) with the specified values.
575_Example: add a new `mood` enum type with three possible values_
577```toml
578[[actions]]
579type = "create_enum"
580name = "mood"
581values = ["happy", "ok", "sad"]
582```
584#### Remove enum
586The `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.
588_Example: remove the `mood` enum type_
590```toml
591[[actions]]
592type = "remove_enum"
593enum = "mood"
594```
596### Custom
598The `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.
600There 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.
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`
606_Example: enable PostGIS and pg_stat_statements extensions_
608```toml
609[[actions]]
610type = "custom"
612start = """
613 CREATE EXTENSION IF NOT EXISTS postgis;
614 CREATE EXTENSION IF NOT EXISTS pg_stat_statements;
615"""
617abort = """
618 DROP EXTENSION IF EXISTS postgis;
619 DROP EXTENSION IF EXISTS pg_stat_statements;
620"""
621```
623### Complex changes across tables
625The `up` and `down` options available when creating tables, adding columns and removing columns can also perform more complex changes that span tables.
627_Example: move `email` column from `users` to `profiles` table_
629```toml
630[[actions]]
631type = "add_column"
632table = "profiles"
634 [actions.column]
635 name = "email"
636 type = "TEXT"
637 nullable = false
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"
645[[actions]]
646type = "remove_column"
647table = "users"
648column = "email"
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```
657_Example: turn a 1:N relationship between `users` and `accounts` into N:M and change the format of the associated `role`_
659```toml
660# Add `user_account_connections` as a junction table
661[[actions]]
662type = "create_table"
663name = "user_account_connections"
664primary_key = ["account_id", "user_id"]
666 [[actions.columns]]
667 name = "account_id"
668 type = "INTEGER"
670 [[actions.columns]]
671 name = "user_id"
672 type = "INTEGER"
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
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"
686[[actions]]
687type = "remove_column"
688table = "users"
689column = "account_id"
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"
697[[actions]]
698type = "remove_column"
699table = "users"
700column = "account_role"
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```
709## Commands and options
711### `reshape migration start`
713Starts 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`.
715#### Options
717_See also [Connection options](#connection-options)_
719| Option | Default | Description |
720| ------------------ | ------------- | --------------------------------------------------------------------------------------------------------------- |
721| `--complete`, `-c` | `false` | Automatically complete migration after applying it. |
722| `--dirs` | `migrations/` | Directories to search for migration files. Multiple directories can be specified using `--dirs dir1 dir2 dir3`. |
724### `reshape migration complete`
726Completes migrations previously started with `reshape migration complete`.
728#### Options
730See [Connection options](#connection-options)
732### `reshape migration abort`
734Aborts any migrations which haven't yet been completed.
736#### Options
738See [Connection options](#connection-options)
740### `reshape schema-query`
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`).
744If your application is written in Rust, we recommend using the [Rust helper library](https://github.com/fabianlindfors/reshape-helper/) instead.
746The query should look something like `SET search_path TO migration_1_initial_migration`.
748#### Options
750| Option | Default | Description |
751| -------- | ------------- | --------------------------------------------------------------------------------------------------------------- |
752| `--dirs` | `migrations/` | Directories to search for migration files. Multiple directories can be specified using `--dirs dir1 dir2 dir3`. |
754### Connection options
756The 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.
758All options can also be set using environment variables instead of flags. If a `.env` file exists, then variables will be automatically loaded from there.
760| Option | Default | Environment variable | Description |
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 |
769## License
771Reshape is released under the [MIT license](https://choosealicense.com/licenses/mit/).