Skip to content

Commit

Permalink
No commit message
Browse files Browse the repository at this point in the history
  • Loading branch information
natew committed Jan 27, 2025
1 parent e441fe2 commit 5fb5d96
Show file tree
Hide file tree
Showing 5 changed files with 104 additions and 61 deletions.
2 changes: 1 addition & 1 deletion apps/chat/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -79,6 +79,7 @@
"virtua": "^0.39.2"
},
"devDependencies": {
"kysely-ctl": "^0.10.1",
"@actions/core": "^1.11.1",
"@actions/exec": "^1.1.1",
"@react-native-community/cli": "15.1.3",
Expand All @@ -87,7 +88,6 @@
"@types/aws-lambda": "8.10.147",
"@types/pg": "^8.11.10",
"dotenv": "^16.4.7",
"kysely-ctl": "^0.10.1",
"sst": "^3.4.46",
"tsx": "^4.19.0",
"unicode-emoji": "^2.6.0"
Expand Down
61 changes: 61 additions & 0 deletions apps/chat/src/postgres/migrate.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,61 @@
import type { PoolClient } from 'pg'
import { getClient } from './migrations/_lib'
import { readdir } from 'node:fs/promises'
import { join } from 'node:path'

type Migration = {
name: string
up?: (client: PoolClient) => Promise<void>
// down?: (client: PoolClient) => Promise<void>
}

async function migrate() {
const client = await getClient()

try {
await client.query('BEGIN')
await client.query(`
CREATE TABLE IF NOT EXISTS migrations (
id SERIAL PRIMARY KEY,
name VARCHAR(255) NOT NULL,
run_on TIMESTAMP NOT NULL DEFAULT NOW()
)
`)

const appliedMigrations = await client.query('SELECT name FROM migrations')
const appliedMigrationNames = new Set(appliedMigrations.rows.map((row) => row.name))

const migrationsDir = join(__dirname, 'migrations')
const files = await readdir(migrationsDir)
const migrationFiles = files.filter((file) => /^\d+.*\.ts$/.test(file)).sort()

const migrations: Migration[] = await Promise.all(
migrationFiles.map(async (file) => {
if (appliedMigrationNames.has(file)) {
return null
}
const migration = await import(join(migrationsDir, file))
return { ...migration, name: file }
})
).then((migrations) => migrations.filter(Boolean) as Migration[])

for (const migration of migrations) {
try {
await migration.up?.(client)
await client.query('INSERT INTO migrations (name) VALUES ($1)', [migration.name])
} catch (e) {
await client.query('ROLLBACK')
throw e
}
}

await client.query('COMMIT')
} catch (e) {
await client.query('ROLLBACK')
throw e
} finally {
client.release()
}
}

migrate()
20 changes: 20 additions & 0 deletions apps/chat/src/postgres/migrations/0-init.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
import * as unicodeEmoji from 'unicode-emoji'
import { getClient, randomId } from './_lib'
import type { PoolClient } from 'pg'

export async function up(client: PoolClient) {
const emojis = unicodeEmoji.getEmojis()
await client.query('BEGIN')
const insertText = `
INSERT INTO reaction(id, value, keyword, "createdAt", "updatedAt")
VALUES ($1, $2, $3, DEFAULT, DEFAULT)
ON CONFLICT DO NOTHING;
`
for (let emoji of emojis) {
const values = [randomId(), emoji.emoji, toKeyword(emoji.description)]
await client.query(insertText, values)
}
await client.query('COMMIT')
}

const toKeyword = (description: string) => description.split(' ').join('_')
22 changes: 22 additions & 0 deletions apps/chat/src/postgres/migrations/_lib.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
import pg from 'pg'

export const randomId = () => Math.random().toString(36).slice(2)

export const getClient = async (tries = 0): Promise<pg.PoolClient> => {
try {
const connectionString = process.env.ZERO_UPSTREAM_DB?.replace('127.0.0.1', 'pgdb') || ''
console.info(`Connecting to: ${connectionString}`)
const pool = new pg.Pool({
connectionString,
})
return await pool.connect()
} catch (err) {
if (tries > 5) {
console.error(`Cannot connect :/`)
process.exit(1)
}
console.error(`Failed to connect to the database.\n${err}\nRetrying in 8 seconds...`)
await new Promise((res) => setTimeout(res, 8000))
return await getClient(tries + 1)
}
}
60 changes: 0 additions & 60 deletions apps/chat/src/postgres/seed.ts

This file was deleted.

0 comments on commit 5fb5d96

Please sign in to comment.