-
Notifications
You must be signed in to change notification settings - Fork 9
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Introduce Postgres DB Adapter #1157
Merged
habdelra
merged 9 commits into
main
from
cs-6463-document-and-setup-postgres-for-dev-environments
Apr 11, 2024
Merged
Changes from all commits
Commits
Show all changes
9 commits
Select commit
Hold shift + click to select a range
27c1672
Create Postgres DB Adapter
habdelra 5e639f1
add developer docs
habdelra 1211a3f
cleanup comments
habdelra 63df061
convert migration to CJS file. when run via commandline node-pg-migra…
habdelra 4bf01d4
remove unnecessary lint rule
habdelra 5908089
ignore eslintrc file
habdelra 172c248
remove need for postgres password in dev/test envs
habdelra 4f84983
cleanup test db's
habdelra b4063ab
don't add env name to db (our tests take care of this automatically)
habdelra File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
File renamed without changes.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,17 @@ | ||
'use strict'; | ||
|
||
module.exports = { | ||
root: true, | ||
parser: '@typescript-eslint/parser', | ||
parserOptions: { | ||
sourceType: 'script', | ||
}, | ||
env: { | ||
browser: false, | ||
node: true, | ||
}, | ||
extends: ['plugin:n/recommended'], | ||
rules: { | ||
camelcase: 'off', | ||
}, | ||
}; |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,62 @@ | ||
exports.up = (pgm) => { | ||
pgm.createTable('indexed_cards', { | ||
card_url: { type: 'varchar', notNull: true }, | ||
realm_version: { type: 'varchar', notNull: true }, | ||
realm_url: { type: 'varchar', notNull: true }, | ||
pristine_doc: 'jsonb', | ||
search_doc: 'jsonb', | ||
error_doc: 'jsonb', | ||
deps: 'jsonb', | ||
types: 'jsonb', | ||
embedded_html: 'varchar', | ||
isolated_html: 'varchar', | ||
indexed_at: 'integer', | ||
is_deleted: 'boolean', | ||
}); | ||
pgm.sql('ALTER TABLE indexed_cards SET UNLOGGED'); | ||
pgm.addConstraint('indexed_cards', 'indexed_cards_pkey', { | ||
primaryKey: ['card_url', 'realm_version'], | ||
}); | ||
pgm.createIndex('indexed_cards', ['realm_version']); | ||
pgm.createIndex('indexed_cards', ['realm_url']); | ||
|
||
pgm.createTable('realm_versions', { | ||
realm_url: { type: 'varchar', notNull: true }, | ||
current_version: { type: 'integer', notNull: true }, | ||
}); | ||
|
||
pgm.sql('ALTER TABLE realm_versions SET UNLOGGED'); | ||
pgm.addConstraint('realm_versions', 'realm_versions_pkey', { | ||
primaryKey: ['realm_url'], | ||
}); | ||
pgm.createIndex('realm_versions', ['current_version']); | ||
|
||
pgm.createType('job_statuses', ['unfulfilled', 'resolved', 'rejected']); | ||
pgm.createTable('jobs', { | ||
id: 'id', // shorthand for primary key that is an auto incremented id | ||
category: { | ||
type: 'varchar', | ||
notNull: true, | ||
}, | ||
args: 'jsonb', | ||
status: { | ||
type: 'job_statuses', | ||
default: 'unfulfilled', | ||
notNull: true, | ||
}, | ||
created_at: { | ||
type: 'timestamp', | ||
notNull: true, | ||
default: pgm.func('current_timestamp'), | ||
}, | ||
finished_at: { | ||
type: 'timestamp', | ||
}, | ||
queue: { | ||
type: 'varchar', | ||
notNull: true, | ||
}, | ||
result: 'jsonb', | ||
}); | ||
pgm.sql('ALTER TABLE jobs SET UNLOGGED'); | ||
}; |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,100 @@ | ||
import { | ||
type DBAdapter, | ||
type PgPrimitive, | ||
type ExecuteOptions, | ||
} from '@cardstack/runtime-common'; | ||
import migrate from 'node-pg-migrate'; | ||
import { join } from 'path'; | ||
import { Pool, Client } from 'pg'; | ||
|
||
import postgresConfig from './pg-config'; | ||
|
||
function config() { | ||
return postgresConfig({ | ||
database: 'boxel', | ||
}); | ||
} | ||
|
||
export default class PgAdapter implements DBAdapter { | ||
private pool: Pool; | ||
|
||
constructor() { | ||
let { user, host, database, password, port } = config(); | ||
console.log(`connecting to DB ${user}@${host}:${port}/${database}`); | ||
this.pool = new Pool({ | ||
user, | ||
host, | ||
database, | ||
password, | ||
port, | ||
}); | ||
} | ||
|
||
async startClient() { | ||
await this.migrateDb(); | ||
} | ||
|
||
async close() { | ||
if (this.pool) { | ||
await this.pool.end(); | ||
} | ||
} | ||
|
||
async execute( | ||
sql: string, | ||
opts?: ExecuteOptions, | ||
): Promise<Record<string, PgPrimitive>[]> { | ||
let client = await this.pool.connect(); | ||
try { | ||
let { rows } = await client.query({ text: sql, values: opts?.bind }); | ||
return rows; | ||
} catch (e: any) { | ||
console.error( | ||
`Error executing SQL ${e.result.message}:\n${sql}${ | ||
opts?.bind ? ' with bindings: ' + JSON.stringify(opts?.bind) : '' | ||
}`, | ||
e, | ||
); | ||
throw e; | ||
} finally { | ||
client.release(); | ||
} | ||
} | ||
|
||
private async migrateDb() { | ||
const config = postgresConfig(); | ||
let client = new Client( | ||
Object.assign({}, config, { database: 'postgres' }), | ||
); | ||
try { | ||
await client.connect(); | ||
let response = await client.query( | ||
`select count(*)=1 as has_database from pg_database where datname=$1`, | ||
[config.database], | ||
); | ||
if (!response.rows[0].has_database) { | ||
await client.query(`create database ${config.database}`); | ||
} | ||
} finally { | ||
client.end(); | ||
} | ||
|
||
await migrate({ | ||
direction: 'up', | ||
migrationsTable: 'migrations', | ||
singleTransaction: true, | ||
checkOrder: false, | ||
databaseUrl: { | ||
user: config.user, | ||
host: config.host, | ||
database: config.database, | ||
password: config.password, | ||
port: config.port, | ||
}, | ||
count: Infinity, | ||
dir: join(__dirname, 'migrations'), | ||
ignorePattern: '.*\\.eslintrc\\.js', | ||
log: (...args) => console.log(...args), | ||
}); | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,11 @@ | ||
import { type ClientConfig } from 'pg'; | ||
|
||
export default function postgresConfig(defaultConfig: ClientConfig = {}) { | ||
return Object.assign({}, defaultConfig, { | ||
host: process.env.PGHOST || 'localhost', | ||
port: process.env.PGPORT || '5432', | ||
user: process.env.PGUSER || 'postgres', | ||
password: process.env.PGPASSWORD || undefined, | ||
database: process.env.PGDATABASE || 'postgres', | ||
}); | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,7 @@ | ||
#!/bin/sh | ||
|
||
databases=$(docker exec boxel-pg psql -U postgres -w -lqt | cut -d \| -f 1 | grep -E 'test_db_' | tr -d ' ') | ||
|
||
for db in $databases; do | ||
docker exec boxel-pg dropdb -U postgres -w $db | ||
done |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,8 @@ | ||
#! /bin/sh | ||
if [ -z "$(docker ps -f name=boxel-pg --all --format '{{.Names}}')" ]; then | ||
# running postgres on port 5435 so it doesn't collide with native postgres | ||
# that may be running on your system | ||
docker run --name boxel-pg -e POSTGRES_HOST_AUTH_METHOD=trust -p 5435:5432 -d postgres >/dev/null | ||
else | ||
docker start boxel-pg >/dev/null | ||
fi |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,2 @@ | ||
#! /bin/sh | ||
docker stop boxel-pg >/dev/null |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Should we also add support for rollbacks by providing direction (up, down) as a param to
migrateDb
?There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
So you can run migrations from the command line to go up or down. But when the realm server spins up we don’t want to run migrations down—ever.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
(I’ll add docs for running migrations from command line as well as generating the schema file for sql lite as part of the same PR)