Skip to content

Commit e522b7e

Browse files
feat: load connection string from env var (#8142)
When the `NETLIFY_DB_URL` environment variable is present, the `db connect` command will use that as the connection string instead of the database. This makes it possible for agent runners to connect to the database of the corresponding deploy preview.
1 parent 2a8f7c0 commit e522b7e

File tree

2 files changed

+23
-1
lines changed

2 files changed

+23
-1
lines changed

src/commands/database/connect.ts

Lines changed: 12 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,17 @@ export interface ConnectOptions {
1111
json?: boolean
1212
}
1313

14+
function redactConnectionString(connectionString: string): string {
15+
try {
16+
const url = new URL(connectionString)
17+
url.username = ''
18+
url.password = ''
19+
return url.toString()
20+
} catch {
21+
return 'database'
22+
}
23+
}
24+
1425
export const connect = async (options: ConnectOptions, command: BaseCommand): Promise<void> => {
1526
const buildDir = command.netlify.site.root ?? command.project.root ?? command.project.baseDirectory
1627
if (!buildDir) {
@@ -26,7 +37,7 @@ export const connect = async (options: ConnectOptions, command: BaseCommand): Pr
2637
return
2738
}
2839

29-
log(`Connected to ${connectionString}`)
40+
log(`Connected to ${redactConnectionString(connectionString)}`)
3041

3142
// --query: one-shot mode
3243
if (options.query) {

src/commands/database/db-connection.ts

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -25,6 +25,17 @@ interface RawDBConnection {
2525
}
2626

2727
export async function connectRawClient(buildDir: string): Promise<RawDBConnection> {
28+
const envConnectionString = process.env.NETLIFY_DB_URL
29+
if (envConnectionString) {
30+
const client = new Client({ connectionString: envConnectionString })
31+
await client.connect()
32+
return {
33+
client,
34+
connectionString: envConnectionString,
35+
cleanup: () => client.end(),
36+
}
37+
}
38+
2839
const state = new LocalState(buildDir)
2940
const storedConnectionString = state.get('dbConnectionString')
3041

0 commit comments

Comments
 (0)