Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Commit bb1e9dd

Browse files
author
Marcin K
committed
Describe database transactions
1 parent d90f7d5 commit bb1e9dd

File tree

1 file changed

+16
-0
lines changed

1 file changed

+16
-0
lines changed

TUTORIAL.md

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -42,6 +42,22 @@ DROP TABLE IF EXISTS users;
4242
```
4343
By adding `IF EXISTS/IF NOT EXISTS` we are making migrations idempotent - we can run the same sql code twice in a row with the same result. This makes our migrations more robust. On the other hand, it causes slightly less control over database schema - e.g. let's say you forgot to drop the table in down migration. You run down migration - the table is still there. When you run up migration again - `CREATE TABLE` would return an error, helping you find an issue in down migration, while `CREATE TABLE IF NOT EXISTS` would not. Use those conditions wisely.
4444

45+
In case you would like to run several commands/queries in one migration, you should wrap them in a transaction (if your database supports it).
46+
In our postgres example it would be (migration up):
47+
```
48+
BEGIN;
49+
50+
CREATE TYPE enum_mood AS ENUM (
51+
'happy',
52+
'sad',
53+
'neutral'
54+
);
55+
ALTER TABLE users ADD COLUMN mood enum_mood;
56+
57+
COMMIT;
58+
```
59+
This way if one of commands fails, our database will remain unchanged.
60+
4561
## Run migrations
4662
```
4763
migrate -database ${POSTGRESQL_URL} -path db/migrations up

0 commit comments

Comments
 (0)