Skip to content

Commit 21385f4

Browse files
committed
Add Drizzle Tracks Migrations In A Log Table as a Drizzle TIL
1 parent 5b47326 commit 21385f4

File tree

2 files changed

+41
-1
lines changed

2 files changed

+41
-1
lines changed

README.md

+2-1
Original file line numberDiff line numberDiff line change
@@ -10,7 +10,7 @@ pairing with smart people at Hashrocket.
1010

1111
For a steady stream of TILs, [sign up for my newsletter](https://crafty-builder-6996.ck.page/e169c61186).
1212

13-
_1489 TILs and counting..._
13+
_1490 TILs and counting..._
1414

1515
---
1616

@@ -212,6 +212,7 @@ _1489 TILs and counting..._
212212
### Drizzle
213213

214214
- [Create bigint Identity Column For Primary Key](drizzle/create-bigint-identity-column-for-primary-key.md)
215+
- [Drizzle Tracks Migrations In A Log Table](drizzle/drizzle-tracks-migrations-in-a-log-table.md)
215216
- [Get Fields For Inserted Row](drizzle/get-fields-for-inserted-row.md)
216217

217218
### Elixir
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,39 @@
1+
# Drizzle Tracks Migrations In A Log Table
2+
3+
When I generate (`npx drizzle-kit generate`) and apply (`npx drizzle-kit
4+
migrate`) schema migrations against my database with Drizzle, there are SQL
5+
files that get created and run.
6+
7+
How does Drizzle know which SQL files have been run and which haven't?
8+
9+
Like many SQL schema migration tools, it uses a table in the database to record
10+
this metadata. Drizzle defaults to calling this table `__drizzle_migrations`
11+
and puts it in the `drizzle` schema (which is like a database namespace).
12+
13+
Let's take a look at this table for a project with two migrations:
14+
15+
```sql
16+
postgres> \d drizzle.__drizzle_migrations
17+
Table "drizzle.__drizzle_migrations"
18+
Column | Type | Collation | Nullable | Default
19+
------------+---------+-----------+----------+----------------------------------------------------------
20+
id | integer | | not null | nextval('drizzle.__drizzle_migrations_id_seq'::regclass)
21+
hash | text | | not null |
22+
created_at | bigint | | |
23+
Indexes:
24+
"__drizzle_migrations_pkey" PRIMARY KEY, btree (id)
25+
26+
postgres> select * from drizzle.__drizzle_migrations;
27+
id | hash | created_at
28+
----+------------------------------------------------------------------+---------------
29+
1 | 8961353bf66f9b3fe1a715f6ea9d9ef2bc65697bb8a5c2569df939a61e72a318 | 1730219291288
30+
2 | b75e61451e2ce37d831608b1bc9231bf3af09e0ab54bf169be117de9d4ff6805 | 1730224013018
31+
(2 rows)
32+
```
33+
34+
Notice that Drizzle stores each migration record as [a SHA256 hash of the
35+
migration
36+
file](https://github.com/drizzle-team/drizzle-orm/blob/526996bd2ea20d5b1a0d65e743b47e23329d441c/drizzle-orm/src/migrator.ts#L52)
37+
and a timestamp of when the migration was run.
38+
39+
[source](https://orm.drizzle.team/docs/drizzle-kit-migrate#applied-migrations-log-in-the-database)

0 commit comments

Comments
 (0)