Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Added an example showing programmatic usuage of sync-db Node/JS #29

Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -171,6 +171,7 @@ await db.transaction(async trx => {
## Examples

1. [Node MSSQL Sample (JavaScript)](examples/node-app-mssql)
2. [Node MSSQL Programmatic API (JavaScript)](examples/node-mssql-programmatic-use)

## Changelog

Expand Down
3 changes: 3 additions & 0 deletions examples/node-mssql-programmatic-use/.babelrc
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
{
"presets": ["@babel/preset-env"]
}
16 changes: 16 additions & 0 deletions examples/node-mssql-programmatic-use/.eslintrc
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
{
"env": {
"node": true,
"es6": true
},
"extends": [
"eslint-config-leapfrog"
],
"parserOptions": {
"ecmaVersion": 2017,
"sourceType": "module"
},
"rules": {
"no-console": 0
}
}
2 changes: 2 additions & 0 deletions examples/node-mssql-programmatic-use/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
connections.sync-db.json
node_modules
9 changes: 9 additions & 0 deletions examples/node-mssql-programmatic-use/Dockerfile
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
FROM node:10

WORKDIR /app/

COPY . .

RUN yarn

CMD yarn sync-db && yarn start
96 changes: 96 additions & 0 deletions examples/node-mssql-programmatic-use/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,96 @@
# Node MSSQL Programmatic API Example (JavaScript)

Sample project for Microsoft SQL Server using programmatic API.

## Setup

Install dependencies.

```bash
$ yarn
```

Configure database connection(s) in the `connections.sync-db.json`.

```bash
$ cp connections.sync-db.json.example connections.sync-db.json
```

## Running

Run the command below to perform a migration:

```
$ yarn migrate
```

Run `sync-db` to synchronize all database objects (views, functions, procedures, schemas, etc) in the configured database(s).

```
$ yarn sync-db
```

Run the sample node app.

```
$ yarn start
```

**Output**

```
List of table names in the database:
[ 'knex_migrations', 'knex_migrations_lock', 'users', 'tasks' ]

List of user names in the database:
[
'sa',
'public',
'sysadmin',
'securityadmin',
'serveradmin',
'setupadmin',
'processadmin',
'diskadmin',
'dbcreator',
'bulkadmin',
'##MS_SQLResourceSigningCertificate##',
'##MS_SQLReplicationSigningCertificate##',
'##MS_SQLAuthenticatorCertificate##',
'##MS_PolicySigningCertificate##',
'##MS_SmoExtendedSigningCertificate##',
'##MS_PolicyEventProcessingLogin##',
'##MS_PolicyTsqlExecutionLogin##',
'##MS_AgentSigningCertificate##',
'BUILTIN\\Administrators',
'NT AUTHORITY\\NETWORK SERVICE',
'NT AUTHORITY\\SYSTEM'
]

Calculations:
{ 'Sum of 6 and 7': 13, 'Product of 6 and 7': 42, 'Square of 6': 36 }

Current date time: 2019-11-28T10:09:36.507Z
```

## Docker

Set `DB_PASSWORD` (password for `SA` user) in environment. e.g.

```bash
$ export DB_PASSWORD=Password@123
```

Configure database connection(s) in the `connections.sync-db.json`. Use same `password` as `DB_PASSWORD`
Note: `host` has to be the service name of docker container for `mssql`.

```bash
$ cp connections.sync-db.json.docker connections.sync-db.json
```

Then run (in order).

```bash
$ docker-compose up mssql
$ docker-compose up app
```
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
{
"connections": [
{
"id": "db1",
"host": "mssql",
"port": 1433,
"user": "sa",
"database": "master",
"password": "Password@123",
"client": "mssql"
}
]
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
{
"connections": [
{
"id": "db1",
"host": "localhost",
"port": 1433,
"user": "db1user",
"database": "db1",
"password": "password",
"client": "mssql"
}
]
}
15 changes: 15 additions & 0 deletions examples/node-mssql-programmatic-use/docker-compose.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
version: "3.3"

services:
mssql:
container_name: "example-mssql"
image: "mcr.microsoft.com/mssql/server:2017-GA-ubuntu"
ports:
- "1433:1433"
environment:
ACCEPT_EULA: "Y"
SA_PASSWORD: ${DB_PASSWORD}

app:
container_name: "example-app"
build: .
11 changes: 11 additions & 0 deletions examples/node-mssql-programmatic-use/knexfile.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
require('@babel/register');
const { connections } = require('./connections.sync-db.json');

module.exports = {
client: 'mssql',
connection: connections[0],
migrations: {
directory: './src/migrations',
tableName: 'knex_migrations'
}
};
27 changes: 27 additions & 0 deletions examples/node-mssql-programmatic-use/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
{
"name": "node-mssql-programmatic-use",
"description": "Sample project using Programmatic API.",
"scripts": {
"lint": "eslint src/index.js",
"lint:fix": "eslint --fix src/index.js",
"sync-db": "babel-node src/sync-db.js",
"start": "yarn lint && babel-node src/index.js",
"make": "knex --knexfile=knexfile.js migrate:make",
"migrate": "knex --knexfile=knexfile.js migrate:latest",
"rollback": "knex --knexfile=knexfile.js migrate:rollback"
},
"dependencies": {
"@leapfrogtechnology/sync-db": "^1.0.0-alpha.4",
"knex": "^0.19.2",
"mssql": "^5.1.0"
},
"license": "MIT",
"devDependencies": {
"@babel/core": "^7.7.4",
"@babel/node": "^7.7.4",
"@babel/preset-env": "^7.7.4",
"@babel/register": "^7.7.4",
"eslint": "^6.2.2",
"eslint-config-leapfrog": "^2.0.1"
}
}
38 changes: 38 additions & 0 deletions examples/node-mssql-programmatic-use/src/index.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
/**
* Demonstrates use of sync-db to create functions, procedures and views in MSSQL.
*/
const knex = require('knex');

const { connections } = require('../connections.sync-db.json');

(async () => {
try {

// Getting knex instance of mssql database with id db1.
const db = knex({
client: 'mssql',
connection: connections.find(({ id }) => id === 'db1')
});

const tables = await db.raw('SELECT * FROM utils.vw_table_names');
const users = await db.raw('SELECT * FROM utils.vw_user_names');
const [{ result: product }] = await db.raw('SELECT utils.product(6, 7) AS result;');
const [{ result: sum }] = await db.raw('SELECT dbo.sum(6, 7) AS result;');
const [{ result: square }] = await db.raw('SELECT dbo.square(6) AS result;');
const [{ result: date }] = await db.raw('EXEC utils.get_date;');

console.log('\nList of table names in the database:\n', tables.map(({ name }) => name));
console.log('\nList of user names in the database:\n', users.map(({ name }) => name));
console.log('\nCalculations:\n', {
'Sum of 6 and 7': sum,
'Product of 6 and 7': product,
'Square of 6': square
});
console.log('\nCurrent date time:', date);

process.exit(0);
} catch (err) {
console.log(err);
process.exit(-1);
}
})();
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
/**
* Create table `users`.
*
* @param {Knex} knex
* @returns {Promise<any>}
*/
export function up(knex) {
return knex.schema.createTable('users', table => {
table.increments();
table.string('email').notNullable();
table.string('password').notNullable();
table.timestamp('created_at').defaultTo(knex.fn.now());
table.timestamp('updated_at').defaultTo(knex.fn.now());
});
}

/**
* Drop table `users`.
*
* @param {Knex} knex
* @returns {Promise<any>}
*/
export function down(knex) {
return knex.schema.dropTable('users');
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
/**
* Create table `tasks`.
*
* @param {Knex} knex
* @returns {Promise<any>}
*/
export function up(knex) {
return knex.schema.createTable('tasks', table => {
table.increments();
table.string('title').notNullable();
table.string('description').notNullable();
table
.boolean('is_complete')
.notNullable()
.defaultTo(false);
table
.integer('user_id')
.references('id')
.inTable('users');
table.timestamp('created_at').defaultTo(knex.fn.now());
table.timestamp('updated_at').defaultTo(knex.fn.now());
});
}

/**
* Drop table `tasks`.
*
* @param {Knex} knex
* @returns {Promise<any>}
*/
export function down(knex) {
return knex.schema.dropTable('tasks');
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
--
-- Calculate square of a number.
--
CREATE FUNCTION [dbo].square(@x INT) RETURNS INT
AS
BEGIN
RETURN @x * @x;
END
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
--
-- Calculate sum of two numbers.
--
CREATE FUNCTION [dbo].sum(@a INT, @b INT) RETURNS INT
AS
BEGIN
RETURN @a + @b;
END
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
--
-- Calculate multiplication of two numbers.
--
CREATE FUNCTION [utils].product(@a INT, @b INT) RETURNS INT
AS
BEGIN
RETURN @a * @b;
END
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
--
-- Procedure that select GETDATE function.
--
CREATE PROCEDURE [utils].get_date
AS
BEGIN
SELECT GETDATE() AS result;
END
4 changes: 4 additions & 0 deletions examples/node-mssql-programmatic-use/src/sql/schema/utils.sql
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
--
-- Database schema that holds utility DB views, procedures and functions.
--
CREATE SCHEMA utils;
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
--
-- View to fetch table names in the database.
--
CREATE VIEW [utils].vw_table_names
AS (
SELECT t.name
FROM sys.tables t
);
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
--
-- View to fetch server login names.
--
CREATE VIEW [utils].vw_user_names
AS (
SELECT name
FROM sys.server_principals
);
14 changes: 14 additions & 0 deletions examples/node-mssql-programmatic-use/src/sync-db.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
import { synchronize, loadConfig, resolveConnections } from '@leapfrogtechnology/sync-db';

(async () => {
try {
const config = await loadConfig(); // Load sync-db.yml
const connections = await resolveConnections(); // Load connections.sync-db.json

// Invoke the command.
await synchronize(config, connections);
process.exit(0);
} catch (error) {
process.exit(-1);
}
})();
Loading