kylefarris / node-querybuilder

Node QueryBuilder Adapter for Node.js (tags: nodejs, node, mysql, active record, activerecord, querybuilder, query builder)
49 stars 19 forks source link

Promise feature added #52

Closed AbhijetPokhrel closed 5 years ago

AbhijetPokhrel commented 5 years ago

Added promise API in query execution stage. A demo test can be done as

/**
 * A demo and test for promise feature
 * - Set DB info in settings object
 * - Set test databae name in DB_NAME
 */

const
    settings = {
        host: 'localhost',
        user: 'root',
        password: ''
    },
    mysql = require("mysql"),
    con = mysql.createConnection(settings);

/**
 * test database name and table name
 */
const
    DB_NAME = "node_q",
    TABLE_NAME = "users";

/**
 * Query builder object
 * We will set it form promise returned by setUpQb function
 */
let qb = null;

/**
 * chaining promise in here
 */
checkDB()
    .then(createDB)
    .then(() => settings.database = DB_NAME)
    .then(setUpQb) //from here the real game starts
    .then(createTable) //create a table by query execution
    .then(inserUser) //insert single data
    .then(insertBatch) //insert batch data
    .then(select) //select a user
    .then(res => {//select response here
        console.log({ res })
    })
    .then(updateUser) //update a user infos
    .then(dropDatabase) //finally drop the database
    .catch(err => {//catch if anything goes wrong
        console.log({ err })
    })//promise chain ends

/**
 * delete databse node_q if it exists
 */
function checkDB() {
    return new Promise((resolve, reject) => {
        con.query(`DROP DATABASE IF EXISTS ${DB_NAME}`, (err, result) => {
            if (err) { reject(err); return; }
            resolve();
        })

    })
}

/**
 * Create a DB named node_q
 * this is an example on RAW query exection
 */
function createDB() {
    console.log("create DB")
    return new Promise((resolve, reject) => {
        con.query(`CREATE DATABASE ${DB_NAME}`, (err, result) => {
            if (err) { reject(err); return; }
            resolve(result);
        })

    })
}

/**
 * Set up the query builder
 */
function setUpQb() {
    console.log("setup QB")
    qb = require('./index').QueryBuilder(settings, 'mysql', 'single');
}

/**
 * Query execution here
 */
function createTable() {
    let sql = `CREATE TABLE ${TABLE_NAME} (` +
        "id INT(6) UNSIGNED AUTO_INCREMENT PRIMARY KEY," +
        "firstname VARCHAR(30) NOT NULL," +
        "lastname VARCHAR(30) NOT NULL," +
        "email VARCHAR(50)," +
        "reg_date TIMESTAMP" +
        ")";
    return qb.query(sql)
}

/**
 * Single insert
 */
function inserUser() {
    let user = { firstname: 'Hari', lastname: 'Lama', email: 'hari@nodeqbuilder.com' };
    return qb.insert(TABLE_NAME, user)
}

/**
 * Battch insert
 */
function insertBatch() {
    let users = [
        { firstname: 'Ram', lastname: 'Bhandari', email: 'ram@nodeqbuilder.com' },
        { firstname: 'Pradeep', lastname: 'aryal', email: 'pradeep@nodeqbuilder.com' },
        { firstname: 'Iswar', lastname: 'Bhandari', email: 'iswar@nodeqbuilder.com' }
    ];
    return qb.insert_batch(TABLE_NAME, users);
}

/**
 * Select a data
 */
function select() {
    return qb.select('*').where({ 'id >': 0 }).from(TABLE_NAME).get()
}

/**
 * Update a data
 */
function updateUser() {
    return qb.update(TABLE_NAME, { firstname: 'Hari@Harry' }, { firstname: 'Hari' })
}

/**
 * Finally drop the database
 */
function dropDatabase() {
    return new Promise((resolve, reject) => {
        con.query(`DROP DATABASE ${DB_NAME}`, function (err) {

            if (err) reject(err);
            resolve()
        });
    })
}
kylefarris commented 5 years ago

Thanks so much for this PR @AbhijetPokhrel. I wasn't able directly merge this PR into the master branch but I was able to use your code to great degree and I'm happy to say that as of v2.1.0, this library offically supports the promises!

I appreciate your contribution very much, though, I am sad that I couldn't get it done sooner or merge your PR directly.