Skip to content

Commit 70aa6c5

Browse files
committed
Use migrate! macro
We refactor the docker-compose.yml to not use an external Dockerfile to copy the migrations over. This lets sqlx properly apply migrations itself when creating the database.
1 parent 46f0c17 commit 70aa6c5

File tree

3 files changed

+3
-48
lines changed

3 files changed

+3
-48
lines changed

Dockerfile.database

Lines changed: 0 additions & 4 deletions
This file was deleted.

docker-compose.yml

Lines changed: 1 addition & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -2,9 +2,7 @@ version: "3.8"
22

33
services:
44
db:
5-
build:
6-
context: .
7-
dockerfile: Dockerfile.database
5+
image: postgres
86
restart: always
97
environment:
108
# these parameters may be set in .env file, or through normal env setting

src/initialize_database.rs

Lines changed: 2 additions & 41 deletions
Original file line numberDiff line numberDiff line change
@@ -1,47 +1,8 @@
11
use error_stack::Result;
22
use sqlx::{Pool, Postgres};
33

4-
pub async fn initialize_database(conn: &Pool<Postgres>) -> Result<(), sqlx::Error> {
5-
// create the supermarket table
6-
sqlx::query(
7-
r#"CREATE TABLE IF NOT EXISTS countdown_products (
8-
id SERIAL PRIMARY KEY,
9-
name VARCHAR(255) NOT NULL,
10-
barcode VARCHAR(13) NOT NULL,
11-
sku VARCHAR(10) NOT NULL UNIQUE
12-
)"#,
13-
)
14-
.execute(conn)
15-
.await?;
16-
17-
sqlx::query(
18-
r#"CREATE TABLE IF NOT EXISTS products (
19-
id SERIAL PRIMARY KEY,
20-
countdown_id INT,
21-
22-
CONSTRAINT fk_countdown_product
23-
FOREIGN KEY(countdown_id)
24-
REFERENCES countdown_products(id)
25-
)"#,
26-
)
27-
.execute(conn)
28-
.await?;
29-
30-
sqlx::query(
31-
r#"CREATE TABLE IF NOT EXISTS prices (
32-
id SERIAL PRIMARY KEY,
33-
product_id INTEGER NOT NULL,
34-
time TIMESTAMPTZ NOT NULL DEFAULT NOW(),
35-
cost_in_cents INTEGER NOT NULL,
36-
supermarket VARCHAR(255) NOT NULL,
37-
38-
CONSTRAINT fk_product
39-
FOREIGN KEY(product_id)
40-
REFERENCES products(id)
41-
)"#,
42-
)
43-
.execute(conn)
44-
.await?;
4+
pub async fn initialize_database(conn: &Pool<Postgres>) -> Result<(), sqlx::migrate::MigrateError> {
5+
sqlx::migrate!().run(conn).await?;
456

467
Ok(())
478
}

0 commit comments

Comments
 (0)