Last active
November 1, 2021 18:29
-
-
Save claudiohilario/5eb1e8aca2780bfe569a12f22f0301e1 to your computer and use it in GitHub Desktop.
Knex PG Example DbCreator class
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
const knex = require("knex"); | |
class DbCreator { | |
/** | |
* | |
* Usage example: | |
* const DbCreator = require('./DbCreator) | |
* const dbConfigs = { | |
* host: "127.0.0.1", | |
* user: "postgres", | |
* password: "123456", | |
* charset: "utf8", | |
* }; | |
* | |
* const dbCreator = new DbCreator(dbConfigs); | |
* const hasDb = await dbCreator.existsDatabase("db_name"); | |
* if(!hasDb) { | |
* await dbCreator.createDatabase("db_name"); | |
* } | |
* await dbCreator.dropDatabase("db_name"); | |
* | |
* @param {Object} dbConfigs - pg configs | |
* @param {Object} dbConfigs.host - pg host | |
* @param {Object} dbConfigs.user - pg user | |
* @param {Object} dbConfigs.password - pg password | |
* @param {Object} dbConfigs.charset - pg charset | |
*/ | |
constructor(dbConfigs) { | |
this.knexConfig = { | |
client: "pg", | |
connection: { | |
host: dbConfigs.host, | |
user: dbConfigs.user, | |
password: dbConfigs.password, | |
charset: dbConfigs.charset || "utf8", | |
}, | |
}; | |
this.knex = {}; | |
} | |
createConnection() { | |
this.destroyConnection(); | |
this.knex = knex(this.knexConfig); | |
} | |
destroyConnection() { | |
this.knex.destroy && this.knex.destroy(); | |
} | |
async existsDatabase(dbName) { | |
try { | |
this.createConnection(); | |
const query = `SELECT 1 FROM pg_database WHERE datname = '${dbName}'`; | |
const result = await this.knex.raw(query); | |
return !!result.rowCount; | |
} catch (err) { | |
throw err; | |
} finally { | |
this.destroyConnection(); | |
} | |
} | |
async createDatabase(dbName) { | |
try { | |
this.createConnection(); | |
const query = `CREATE DATABASE ${dbName}`; | |
const result = await this.knex.raw(query); | |
return !!result.rowCount; | |
} catch (err) { | |
throw err; | |
} finally { | |
this.destroyConnection(); | |
} | |
} | |
async dropDatabase(dbName) { | |
try { | |
this.createConnection(); | |
const query = `DROP DATABASE IF EXISTS ${dbName}`; | |
const result = await this.knex.raw(query); | |
return !!result.rowCount; | |
} catch (err) { | |
throw err; | |
} finally { | |
this.destroyConnection(); | |
} | |
} | |
} | |
module.exports = DbCreator; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment