Skip to content

Commit

Permalink
First version
Browse files Browse the repository at this point in the history
  • Loading branch information
gregberge committed Feb 6, 2018
1 parent 1c0d80e commit 7552eb2
Show file tree
Hide file tree
Showing 21 changed files with 4,716 additions and 0 deletions.
14 changes: 14 additions & 0 deletions .babelrc
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
{
"presets": [
[
"env",
{
"loose": true,
"targets": {
"node": "8.4"
}
}
]
],
"plugins": ["transform-object-rest-spread", "transform-class-properties"]
}
2 changes: 2 additions & 0 deletions .eslintignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
node_modules/
lib/
12 changes: 12 additions & 0 deletions .eslintrc.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
module.exports = {
root: true,
extends: ['airbnb-base', 'prettier'],
parser: 'babel-eslint',
parserOptions: {
ecmaVersion: 2018,
sourceType: 'module',
},
env: {
node: true,
},
}
3 changes: 3 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
node_modules/
lib/
db/
5 changes: 5 additions & 0 deletions .prettierrc
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
{
"singleQuote": true,
"trailingComma": "all",
"semi": false
}
10 changes: 10 additions & 0 deletions .travis.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
language: node_js
notifications:
email: false
services:
- postgresql
addons:
postgresql: '9.6'
node_js:
- 8
- 9
7 changes: 7 additions & 0 deletions LICENSE
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
Copyright 2018 Smooth Code

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
71 changes: 71 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,71 @@
# Knex Scripts

Knex utilities to interact with Postgres database.

```
npm install knex-scripts
```

## Command Line Usage

```
Usage: knex-scripts [options] [command]
Options:
-V, --version output the version number
--docker Use docker.
--knexfile [path] Specify the knexfile path.
--cwd [path] Specify the working directory.
--env [name] environment, default: process.env.NODE_ENV || development
-h, --help output usage information
Commands:
create Create database.
drop Drop database.
dump Dump database.
load Load database.
truncate Truncate all tables.
```

## Node API Usage

```js
import knex from 'knex'
import { truncate } from 'knex-scripts'
import config from './knexfile'

// Truncate all database
truncate({ getKnex: () => knex(config) })
.then(() => console.log('Truncated'))
.catch(console.error)
```

## Configuration

```js
// knexfile.js
const config = {
knexScripts: {
docker: false,
structurePath: 'db/structure.sql',
},
development: {
client: 'postgresql',
connection: {
user: 'postgres',
database: 'development',
timezone: 'utc',
},
},
}

module.exports = config
```

## License

MIT
3 changes: 3 additions & 0 deletions bin/knex-scripts
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
#!/usr/bin/env node

require('../lib/cli')
9 changes: 9 additions & 0 deletions docker-compose.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
version: '2'
services:
postgres:
image: postgres:9.6
ports:
- '5432:5432'
volumes:
- ${PWD}/db:${PWD}/db
- ${PWD}/docker-entrypoint-initdb.d:/docker-entrypoint-initdb.d
13 changes: 13 additions & 0 deletions knexfile.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
/* eslint-disable global-require */
const config = {
development: {
client: 'postgresql',
connection: {
user: 'postgres',
database: 'development',
timezone: 'utc',
},
},
}

module.exports = config
45 changes: 45 additions & 0 deletions package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
{
"name": "knex-scripts",
"version": "0.0.1",
"description": "Knex utilities to interact with Postgres database.",
"main": "lib/index.js",
"author": "Greg Bergé <[email protected]>",
"license": "MIT",
"scripts": {
"build": "babel -d lib src",
"lint": "eslint .",
"prebuild": "rm -rf lib",
"test": "yarn lint && yarn build && bin/knex-scripts create && bin/knex-scripts dump && bin/knex-scripts load && bin/knex-scripts drop",
"release": "yarn build && standard-version && conventional-github-releaser -p angular"
},
"bin": {
"knex-scripts": "bin/knex-scripts"
},
"dependencies": {
"chalk": "^2.3.0",
"commander": "^2.14.0",
"interpret": "^1.1.0",
"liftoff": "^2.5.0",
"minimist": "^1.2.0",
"mkdirp": "^0.5.1",
"mz": "^2.7.0",
"tildify": "^1.2.0",
"v8flags": "^3.0.1"
},
"devDependencies": {
"babel-cli": "^6.26.0",
"babel-eslint": "^8.2.1",
"babel-plugin-transform-class-properties": "^6.24.1",
"babel-plugin-transform-object-rest-spread": "^6.26.0",
"babel-preset-env": "^1.6.1",
"conventional-github-releaser": "^2.0.0",
"eslint": "^4.17.0",
"eslint-config-airbnb-base": "^12.1.0",
"eslint-config-prettier": "^2.9.0",
"eslint-plugin-import": "^2.8.0",
"knex": "^0.14.2",
"pg": "^7.4.1",
"prettier": "^1.10.2",
"standard-version": "^4.3.0"
}
}
166 changes: 166 additions & 0 deletions src/cli.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,166 @@
/* eslint-disable no-console, global-require, import/no-dynamic-require */
import Liftoff from 'liftoff'
import v8flags from 'v8flags'
import { jsVariants } from 'interpret'
import commander from 'commander'
import chalk from 'chalk'
import tildify from 'tildify'
import minimist from 'minimist'
import { join } from 'path'
import cliPkg from '../package.json'
import create from './create'
import drop from './drop'
import dump from './dump'
import load from './load'
import truncate from './truncate'

const argv = minimist(process.argv.slice(2))

function exit(text) {
if (text instanceof Error) {
console.error(chalk.red(text.stack))
} else {
console.error(chalk.red(text))
}
process.exit(1)
}

const cli = new Liftoff({
name: 'knex',
extensions: jsVariants,
v8flags,
})

function checkLocalModule(env) {
if (!env.modulePath) {
console.log(
chalk.red('No local knex install found in:'),
chalk.magenta(tildify(env.cwd)),
)
exit('Try running: npm install knex.')
}
}

function initConfig(env) {
checkLocalModule(env)

if (!env.configPath) {
exit('No knexfile found in this directory. Specify a path with --knexfile')
}

if (process.cwd() !== env.cwd) {
process.chdir(env.cwd)
console.log('Working directory changed to', chalk.magenta(tildify(env.cwd)))
}

const defaultEnv = 'development'
let config = require(env.configPath)
let environment = commander.env || process.env.NODE_ENV

if (!environment && typeof config[defaultEnv] === 'object') {
environment = defaultEnv
}

const knexScriptsConfig = config.knexScripts || {}

if (environment) {
console.log('Using environment:', chalk.magenta(environment))
config = config[environment] || config
}

if (!config) {
console.log(chalk.red('Warning: unable to read knexfile config'))
process.exit(1)
}

if (argv.debug !== undefined) config.debug = argv.debug
const knex = require(env.modulePath)
return {
getKnex: () => knex(config),
knexConfig: config,
env: environment,
structurePath: knexScriptsConfig.structurePath || 'db/structure.sql',
migrationsPath: join(process.cwd(), 'migrations'),
docker:
commander.docker !== undefined
? commander.docker
: knexScriptsConfig.docker,
}
}

function invoke(env) {
commander
.version(
chalk`{blue Knex Scripts version: {green ${cliPkg.version}}}\n` +
chalk`{blue Knex version: {green ${env.modulePackage.version}}}\n`,
)
.option('--docker', 'Use docker.')
.option('--knexfile [path]', 'Specify the knexfile path.')
.option('--cwd [path]', 'Specify the working directory.')
.option(
'--env [name]',
'environment, default: process.env.NODE_ENV || development',
)

commander
.command('create')
.description('Create database.')
.action(() => {
const config = initConfig(env)
return create(config)
.then(() => console.log(chalk.green(`Database created.`)))
.catch(exit)
})

commander
.command('drop')
.description('Drop database.')
.action(() => {
const config = initConfig(env)
return drop(config)
.then(() => console.log(chalk.green(`Database dropped.`)))
.catch(exit)
})

commander
.command('dump')
.description('Dump database.')
.action(() => {
const config = initConfig(env)
return dump(config)
.then(() => console.log(chalk.green(`Dump created.`)))
.catch(exit)
})

commander
.command('load')
.description('Load database.')
.action(() => {
const config = initConfig(env)
return load(config)
.then(() => console.log(chalk.green(`Database loaded.`)))
.catch(exit)
})

commander
.command('truncate')
.description('Truncate all tables.')
.action(() => {
const config = initConfig(env)
return truncate(config)
.then(() => console.log(chalk.green(`Database truncated.`)))
.catch(exit)
})

commander.parse(process.argv)
}

cli.launch(
{
cwd: argv.cwd,
configPath: argv.knexfile,
require: argv.require,
completion: argv.completion,
},
invoke,
)
19 changes: 19 additions & 0 deletions src/create.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
/* eslint-disable max-len */
import { exec } from 'mz/child_process'
import { preventEnv } from './utils'

async function create({ docker, env, knexConfig }) {
preventEnv('production', env)

const command = docker
? `docker-compose run postgres createdb --host postgres --username ${
knexConfig.connection.user
} ${knexConfig.connection.database}`
: `createdb --username ${knexConfig.connection.user} ${
knexConfig.connection.database
}`

return exec(command)
}

export default create
Loading

0 comments on commit 7552eb2

Please sign in to comment.