Last active
September 17, 2020 19:05
-
-
Save beaucollins/5424f9663df48bc02ffa62256f27f5a0 to your computer and use it in GitHub Desktop.
This file contains hidden or 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
| import knex, { Client } from 'knex'; | |
| type Result = | |
| | [success: true, database: string] | |
| | [success: false, database: string, reason: Error]; | |
| const ENV = process.env.NODE_ENV ?? 'development'; | |
| function createClient() { | |
| if (ENV !== 'development') { | |
| throw new Error(`Only development ${ENV}`); | |
| } | |
| return knex({ | |
| client: 'pg', | |
| connection: { | |
| host: process.env.DB_HOST, | |
| user: process.env.DB_USER, | |
| password: process.env.DB_PASSWORD, | |
| }, | |
| }); | |
| } | |
| function eachDatabase( | |
| task: (database: string) => string | |
| ): (databases: string[]) => Promise<Result[]> { | |
| return async (databases) => { | |
| const client = createClient(); | |
| try { | |
| const results: Result[] = []; | |
| for (const database of databases) { | |
| results.push( | |
| await client.raw(task(database)).then( | |
| () => [true, database], | |
| (error) => [false, database, error] | |
| ) | |
| ); | |
| } | |
| return results; | |
| } finally { | |
| client.destroy(); | |
| } | |
| }; | |
| } | |
| const destroyDatabases = eachDatabase( | |
| (database) => `DROP DATABASE ${database}` | |
| ); | |
| const createDatabases = eachDatabase( | |
| (database) => | |
| `CREATE DATABASE ${database} WITH OWNER = postgres ENCODING = 'UTF8' LC_COLLATE = 'en_US.utf8' LC_CTYPE = 'en_US.utf8' TABLESPACE = pg_default CONNECTION_LIMIT = -1;` | |
| ); | |
| if (!module.parent) { | |
| const options = process.argv.slice(process.argv.indexOf(__filename) + 1); | |
| const task = | |
| options.length > 0 | |
| ? options[0] === 'destroy' | |
| ? 'destroy' | |
| : 'create' | |
| : 'create'; | |
| const fn = task === 'destroy' ? destroyDatabases : createDatabases; | |
| const DATABASES = ['shard0000', 'global', 'sparta']; | |
| process.stdout.write(`Task: ${task}\n`); | |
| fn(DATABASES).then( | |
| (results) => | |
| results.forEach((result) => { | |
| if (result[0]) { | |
| process.stdout.write(`Succeeded ${result[1]}\n`); | |
| } else { | |
| process.stdout.write(`Failed ${result[1]}: ${result[2].message}\n`); | |
| } | |
| }), | |
| (error) => process.stderr.write(`Unexpected error: ${error.message}\n`) | |
| ); | |
| } |
Author
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Create databases:
Destroy databases: