-
Notifications
You must be signed in to change notification settings - Fork 63
/
migration.sh
66 lines (53 loc) · 2.19 KB
/
migration.sh
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
#!/bin/bash
set -e
PRISMA_MIGRATIONS_TABLE="_prisma_migrations"
# Extract DB_HOST and DB_PORT from POSTGRES_HOST
DB_HOST=$(echo $POSTGRES_HOST | cut -d':' -f1)
DB_PORT=$(echo $POSTGRES_HOST | cut -d':' -f2)
# Default to port 5432 if DB_PORT is not set
if [ -z "$DB_PORT" ]; then
DB_PORT=5432
fi
# Export PGPASSWORD so psql can use it
export PGPASSWORD=$POSTGRES_PASSWORD
# Check if the _prisma_migrations table exists
TABLE_EXISTS=$(psql -U $POSTGRES_USER -h $DB_HOST -d $POSTGRES_DATABASE -p $DB_PORT -t -c "SELECT to_regclass('$PRISMA_MIGRATIONS_TABLE');")
# Function to rename the _prisma_migrations table
rename_migrations_table() {
echo "Renaming $PRISMA_MIGRATIONS_TABLE table to ${PRISMA_MIGRATIONS_TABLE}_old..."
psql -U $POSTGRES_USER -h $DB_HOST -d $POSTGRES_DATABASE -p $DB_PORT -c "ALTER TABLE $PRISMA_MIGRATIONS_TABLE RENAME TO ${PRISMA_MIGRATIONS_TABLE}_old;"
}
# Function to resolve initial migration
resolve_init_migration() {
echo "Resolving initial migration..."
npx prisma migrate resolve --applied 0_init
}
# Function to apply migrations
apply_migrations() {
echo "Applying migrations..."
npx prisma migrate deploy
}
# Main logic
if [ "$TABLE_EXISTS" == " " ]; then
echo "The $PRISMA_MIGRATIONS_TABLE table does not exist. Proceeding to apply migrations."
resolve_init_migration
else
echo "The $PRISMA_MIGRATIONS_TABLE table exists. Proceeding to apply migrations."
# Check if the 0_init migration exists
INIT_MIGRATION=$(psql -U $POSTGRES_USER -h $DB_HOST -d $POSTGRES_DATABASE -p $DB_PORT -t -c "SELECT migration_name FROM $PRISMA_MIGRATIONS_TABLE WHERE migration_name = '0_init' AND logs NOT like '%failed%';")
if [ -z "$INIT_MIGRATION" ]; then
echo "The 0_init migration was not found. Truncating the _prisma_migrations table and applying migrations."
rename_migrations_table
resolve_init_migration
else
echo "The 0_init migration was found. Proceeding to apply migrations."
apply_migrations
fi
echo "Migration process completed."
fi
# if NEXT_PUBLIC_ENVIRONMENT is set to production, run the production build
if [ "$NEXT_PUBLIC_ENVIRONMENT" == "production" ]; then
npm start
else
npm run dev
fi