|
1 | 1 | /* eslint-disable no-console */
|
2 | 2 | import { spawn } from 'node:child_process'
|
3 | 3 | import fs from 'node:fs'
|
| 4 | +import net from 'node:net' |
4 | 5 | import path from 'node:path'
|
5 | 6 | import process from 'node:process'
|
6 | 7 | import { findBinaryInPath } from '../utils'
|
@@ -54,21 +55,39 @@ async function createPostgreSQLDatabase(dbName: string, options: DatabaseOptions
|
54 | 55 |
|
55 | 56 | try {
|
56 | 57 | // Ensure server is accepting TCP connections before attempting to create DB
|
57 |
| - const pgIsReady = findBinaryInPath('pg_isready') || 'pg_isready' |
| 58 | + const maxAttempts = 20 |
58 | 59 | let ready = false
|
59 |
| - for (let i = 0; i < 12; i++) { |
60 |
| - try { |
61 |
| - await executeCommand([pgIsReady, '-h', host, '-p', String(port)]) |
| 60 | + for (let i = 0; i < maxAttempts; i++) { |
| 61 | + const attempt = await new Promise<boolean>((resolve) => { |
| 62 | + const socket = net.connect({ host, port, timeout: 1000 }, () => { |
| 63 | + socket.end() |
| 64 | + resolve(true) |
| 65 | + }) |
| 66 | + socket.on('error', () => resolve(false)) |
| 67 | + socket.on('timeout', () => { |
| 68 | + socket.destroy() |
| 69 | + resolve(false) |
| 70 | + }) |
| 71 | + }) |
| 72 | + if (attempt) { |
62 | 73 | ready = true
|
63 | 74 | break
|
64 | 75 | }
|
65 |
| - catch { |
66 |
| - await new Promise(r => setTimeout(r, 500 + i * 250)) |
67 |
| - } |
| 76 | + await new Promise(r => setTimeout(r, 250 + i * 150)) |
68 | 77 | }
|
69 | 78 | if (!ready) {
|
70 |
| - throw new Error('PostgreSQL not accepting connections yet') |
| 79 | + // As a fallback, try pg_isready if available |
| 80 | + const pgIsReady = findBinaryInPath('pg_isready') || 'pg_isready' |
| 81 | + try { |
| 82 | + await executeCommand([pgIsReady, '-h', host, '-p', String(port)]) |
| 83 | + ready = true |
| 84 | + } |
| 85 | + catch {} |
71 | 86 | }
|
| 87 | + if (!ready) |
| 88 | + throw new Error('PostgreSQL not accepting connections yet') |
| 89 | + // Small grace period after accept |
| 90 | + await new Promise(r => setTimeout(r, 250)) |
72 | 91 |
|
73 | 92 | // Check if database exists
|
74 | 93 | const checkCommand = ['psql', '-h', host, '-p', String(port), '-U', user, '-lqt']
|
|
0 commit comments