-
Notifications
You must be signed in to change notification settings - Fork 8
Expand file tree
/
Copy pathdocker-entrypoint.sh
More file actions
264 lines (215 loc) · 5.4 KB
/
Copy pathdocker-entrypoint.sh
File metadata and controls
264 lines (215 loc) · 5.4 KB
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
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
#!/bin/sh
set -eu
node <<'NODE'
const net = require("net");
const databaseUrl = process.env.DATABASE_URL;
if (!databaseUrl) {
console.error("DATABASE_URL is not set.");
process.exit(1);
}
const url = new URL(databaseUrl);
const host = url.hostname;
const port = Number(url.port || 5432);
const timeoutMs = 90_000;
const intervalMs = 2_000;
const startedAt = Date.now();
function check() {
const socket = net.createConnection({ host, port });
socket.once("connect", () => {
socket.end();
console.log(`Database is reachable at ${host}:${port}.`);
process.exit(0);
});
socket.once("error", (error) => {
socket.destroy();
if (Date.now() - startedAt >= timeoutMs) {
console.error(`Database is not reachable at ${host}:${port}: ${error.message}`);
process.exit(1);
}
console.log(`Waiting for database at ${host}:${port}...`);
setTimeout(check, intervalMs);
});
}
check();
NODE
if [ -d /app/prisma/migrations ] && [ "$(find /app/prisma/migrations -mindepth 1 -maxdepth 1 | wc -l)" -gt 0 ]; then
db_action="$(node <<'NODE'
const { PrismaClient } = require("@prisma/client");
const prisma = new PrismaClient();
async function main() {
const tableRows = await prisma.$queryRaw`
SELECT table_name
FROM information_schema.tables
WHERE table_schema = 'public'
AND table_type = 'BASE TABLE'
`;
const enumRows = await prisma.$queryRaw`
SELECT typname
FROM pg_type t
JOIN pg_namespace n ON n.oid = t.typnamespace
WHERE n.nspname = 'public'
AND t.typtype = 'e'
`;
const tables = new Set(tableRows.map((row) => row.table_name));
const hasMigrationTable = tables.has("_prisma_migrations");
const appTables = [...tables].filter(
(table) => table !== "_prisma_migrations"
);
const hasEnums = enumRows.length > 0;
let failedMigrations = [];
let migrationCount = 0;
if (hasMigrationTable) {
failedMigrations = await prisma.$queryRaw`
SELECT migration_name
FROM "_prisma_migrations"
WHERE finished_at IS NULL
AND rolled_back_at IS NULL
`;
const migrationCountResult = await prisma.$queryRaw`
SELECT COUNT(*)::int AS count
FROM "_prisma_migrations"
`;
migrationCount = migrationCountResult[0].count;
}
/**
* STATE #1
* Fresh database
*/
if (
appTables.length === 0 &&
!hasMigrationTable &&
!hasEnums
) {
console.error(
"Fresh database detected. Applying migrations."
);
console.log("migrate");
return;
}
/**
* STATE #2
* Existing schema without Prisma migration history
*/
if (
appTables.length > 0 &&
!hasMigrationTable
) {
console.error(
"Application tables exist but Prisma migration history table is missing."
);
console.error(
"Database state is inconsistent."
);
console.log("blocked");
return;
}
/**
* STATE #3
* Prisma migration history exists
*/
if (hasMigrationTable) {
if (
migrationCount === 0 &&
(
appTables.length > 0 ||
hasEnums
)
) {
console.error(
"Database contains schema objects but Prisma migration history is empty."
);
console.error(
"Database state is inconsistent."
);
console.error(
"Do not delete records from _prisma_migrations manually."
);
console.log("blocked");
return;
}
if (failedMigrations.length > 0) {
console.error(
`Failed Prisma migrations detected: ${failedMigrations
.map((row) => row.migration_name)
.join(", ")}`
);
console.error(
"Resolve the failed migration before starting Doktainer."
);
console.log("blocked");
return;
}
console.error(
"Prisma migration history detected. Applying pending migrations."
);
console.log("migrate");
return;
}
/**
* STATE #4
* Partial schema / inconsistent state
*/
console.error("");
console.error(
"Database appears to be partially initialized."
);
console.error(
"Found Prisma objects without a valid schema state."
);
console.error("");
console.error(
"This may happen when:"
);
console.error(
"- a migration failed previously"
);
console.error(
"- the database was partially restored"
);
console.error(
"- schema objects were created manually"
);
console.error("");
console.error(
"Doktainer will not automatically modify the database."
);
console.error(
"Manual intervention is required."
);
console.log("blocked");
}
main()
.catch((error) => {
console.error(error);
console.log("blocked");
})
.finally(async () => {
await prisma.$disconnect();
});
NODE
)"
case "$db_action" in
migrate)
npx prisma migrate deploy
;;
push)
npx prisma db push
;;
blocked)
exit 1
;;
*)
echo "Unknown database setup action: $db_action" >&2
exit 1
;;
esac
else
npx prisma db push
fi
node dist/server/index.js &
api_pid=$!
cleanup() {
kill "$api_pid" 2>/dev/null || true
}
trap cleanup INT TERM EXIT
exec node_modules/.bin/next start -p 3000 -H 0.0.0.0