• Stars
    star
    142
  • Rank 258,495 (Top 6 %)
  • Language
    JavaScript
  • License
    ISC License
  • Created over 8 years ago
  • Updated over 2 years ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

Utility for create, drop, truncate etc. administrative database operations.

Build Status Coverage Status Greenkeeper badge

Pretty useful when writing scripts to initialize database for fresh install or dropping / creating new database when running tests and for truncating database between tests.

Library uses knex connection for non administrative queries, but also creates priviliged connection directly with driver with superuser privileges for creating and dropping databases / roles.

Supported Databases

  • PostgreSQL
  • MySQL
  • SQLite3 (partial support even though most of the functions won't make sense with this)
  • Oracle DB Express (TBD)
  • MSSQL (TBD if we can get integration tests to run automatically)

Install

You need to install knex, database driver and knex-db-manager

npm install knex-db-manager knex pg pg-escape

API & Usage

Database manager is initialized with normal knex configuration and with superuser account which should be able to create / drop roles and databases.

Initialization:

let config = {
  knex: {
    // just the usual knex configuration
    client: 'postgres',
    connection: {
      host: 'localhost',
      database: 'appdb',
      user: 'dbowneruser',
      password: 'dbownerpassword',
    },
    pool: {
      min: 0,
      max: 10,
    },
    migrations: {
      directory: __dirname + '/migrations',
    },
  },
  dbManager: {
    // db manager related configuration
    collate: ['fi_FI.UTF-8', 'Finnish_Finland.1252'],
    superUser: 'userwithrightstocreateusersanddatabases',
    superPassword: 'privilegeduserpassword',
    populatePathPattern: 'data/**/*.js', // glob format for searching seeds
  },
};

let dbManager = require('knex-db-manager').databaseManagerFactory(config);

createDbOwnerIfNotExist(): Promise<void>

Creates the user, which is described in knex configuration. This user is used as the database owner when creating new databases.

let promise = dbManager.createDbOwnerIfNotExist();

createDb(dbName?: string): Promise<void>

Creates database described in knex configuration or by given name. Owner of the created database is set to be the config.knex.connection.user.

dbName is the name of the database to be created, if not given the name is read from config.knex.connection.database.

Read database from config.knex.connection.database:

let promise = dbManager.createDb();

By given name:

let promise = dbManager.createDb('brave-new-db');

dropDb(dbName?: string): Promise<void>

Drops database described in knex configuration or by given name. Note that if there are any active connections to the database that is being dropped, the drop command might fail.

dbName is the name of the database to be dropped, if not given the name is read from config.knex.connection.database.

Drop database config.knex.connection.database:

let promise = dbManager.dropDb();

By specific name:

let promise = dbManager.dropDb('brave-new-db');

copyDb(fromDbName: string, toDbName: string): Promise<void>

Clones database to another name remotely on db serverside (may be useful e.g. to make backup before running migrations).

New database toDatabaseName will be created containing a copy of fromDbName.

Note: This method is not supported with MySQL (yet).

Making copy of DB:

let promise = dbManager.copyDb('brave-new-db', 'brave-new-db-copy');

truncateDb(ignoreTables?: string[]): Promise<void>

Truncate tables of the database and reset corresponding id sequences.

ignoreTables list of tables names which should not be truncated.

Truncate database config.knex.connection.database:

let promise = dbManager.truncateDb();

ignore certain tables:

let promise = dbManager.truncateDb(['migrations']);

updateIdSequences(): Promise<void>

Updates all primary key id sequences to be biggest id in table + 1. So after running this next INSERT to table will get valid id for the row from the sequence.

This was motivated by some people who liked to create test data with hard coded ids, so this helps them to make app to work normally after adding rows to tables, which has not used id sequence to get ids.

The function assumes that the primary key for each table is called id.

Note: This method is not supported with MySQL (yet).

Reset sequence of database config.knex.connection.database:

let promise = dbManager.updateIdSequences();

populateDb(glob: string): Promise<void>

Finds knex seed files by pattern and populate database with them.

glob is a pattern to match files to be ran, if not given the name is read from config.dbManager.populatePathPattern.

Get database from config.knex.connection.database and pattern from config.dbManager.populatePathPattern:

let promise = dbManager.populateDb();

with pattern:

let promise = dbManager.populateDb(path.join(__dirname, 'seeds', 'test-*'));

migrateDb(): Promise<void>

Runs knex migrations configured in knex config.

Get database from config.knex.connection.database:

let promise = dbManager.migrateDb();

dbVersion(): Promise<string>

Checks which migrations has been ran to database.

Expects that migration name starts with timestamp.

If no migrations has been run, promise resolves to 'none'. Otherwise resolves to first numbers of latest migration file ran e.g. for 20141024070315_test_schema.js version will be '20141024070315'.

Get database from config.knex.connection.database:

let promise = dbManager.dbVersion();

close(): Promise<void>

Closes the single privileged connection and all normal knex connections.

Kill database connection:

let promise = dbManager.close();

closeKnex(): Promise<void>

Closes knex connection which is made to the database for unprivileged queries. Sometimes this is needed e.g. for being able to drop database.

Close knex connection

let promise = dbManager.closeKnex();

knexInstance(): QueryBuilder

Returns knex query builder bound to configured database.

Get database from config.knex.connection.database:

let knex = dbManager.knexInstance();
knex('table')
  .where('id', 1)
  .then((rows) => {
    console.log('Query was ran with db owner privileges', rows);
  });

More Repositories

1

objection.js

An SQL-friendly ORM for Node.js
JavaScript
7,249
star
2

tarn.js

Simple and robust resource pool for node.js
JavaScript
472
star
3

objection-graphql

GraphQL schema generator for objection.js
JavaScript
307
star
4

venia

Clojure(Script) graphql query generation
Clojure
197
star
5

objection-find

Build search queries for objection.js models using HTTP query parameters.
JavaScript
102
star
6

db-errors

Unified node.js error API for mysql, postgres and sqlite3
JavaScript
85
star
7

objection-db-errors

A plugin that provides better database error handling for objection.js
JavaScript
71
star
8

wordpress-theme-base

Theme base for WordPress, ES2017+ & PHP7+
PHP
63
star
9

objection-rest

REST API generator for objection.js models
JavaScript
30
star
10

satakieli

Satakieli is a i18n library that provides identical API for ClojureScript and Clojure programmers. Localized messages can be written using ICU MessageFormat syntax.
Clojure
26
star
11

wordpress

Addons for WordPress development, using Seravo/wordpress as base
JavaScript
24
star
12

logspout-gelf

Logspout with GELF adapter
Dockerfile
15
star
13

gocd-slack-task

Go CD plugin allowing to send messages to Slack
Java
13
star
14

travis-oracledb-xe

Script and guide to setup Oracle Database Express Edition on Travis CI (without need to create Oracle account)
Shell
13
star
15

summer-2018

JavaScript
6
star
16

spring-boot-word-to-html-example

Java
6
star
17

alkobot

TypeScript
6
star
18

dodo.js

JavaScript
5
star
19

teatime-2018

Teatime 2018 demo project. See https://vincitteatime.fi/
JavaScript
5
star
20

heroku-buildpack-java-nodejs

Heroku buildpack for Java applications with Node.JS and npm.
Shell
4
star
21

multi-user-test-runner

JUnit test runner for running authorization unit/integration tests with multiple users and roles
Java
4
star
22

slurp

JavaScript
3
star
23

proxios

Magical ES6 Proxy wrapper for axios
3
star
24

ffmpeg

C
2
star
25

opendatatre

Open Data TRE Meetup example
JavaScript
2
star
26

wordpress-demo

Demo project, hosted in 5$ Digital Ocean LEMP one click app
PHP
2
star
27

get-a-room

PWA for making ad hoc room reservations easy in Google Workspace environment.
TypeScript
1
star
28

curd

Hassle-free CRUD operations
Clojure
1
star
29

VISDOM-Roadmapper

Roadmapper tool developed as part of ITEA 3 VISDOM project.
TypeScript
1
star
30

pfsense-fauxer

Simple client lib for communicating with pfSense faux-api qith node.
JavaScript
1
star
31

dodo-core-features

Dodo.js framework's core features (cors, auth, gzip, cookies, logging, etc.)
JavaScript
1
star
32

mml-mapserver

Docker image and instructions to serve MML maastokartta
HTML
1
star
33

multi-user-test-runner-examples

Test project for testing multi-user-test-runner
Java
1
star
34

dodo-objection

Objection.js ORM plugin for Dodo.js framework
JavaScript
1
star
35

fastest-tester

Tester for the Fastest test framework
JavaScript
1
star
36

lunch-assistant

Hackfest 2023 Kuopio team lunch assistant
TypeScript
1
star