Skip to content

Commit

Permalink
Merge pull request #7 from enes-sahin/develop
Browse files Browse the repository at this point in the history
Enabling Pool Connection
  • Loading branch information
enes-sahin authored Jun 5, 2020
2 parents fd3dd77 + 4299d61 commit d3143e3
Show file tree
Hide file tree
Showing 3 changed files with 88 additions and 51 deletions.
42 changes: 34 additions & 8 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,19 +2,20 @@
# fluent-mysql


![Image of version](https://img.shields.io/badge/npm-v1.1.0-blue)
![Image of version](https://img.shields.io/badge/npm-v1.2.0-blue)
![Image of version](https://img.shields.io/badge/licence-MIT-yellowgreen)

**fluent-mysql** is a query builder for MySQL. It performs basic database operations using [mysql](https://www.npmjs.com/package/mysql) library.

* It is a **ES5** compatible.
* It is **ES5** compatible.

*Inspired by [Laravel Query Builder](https://laravel.com/docs/master/queries)*

## Table of Contents

- [Installation](#installation)
- [Connection to Database](#connection-to-database)
- [Pooling connections](#pooling-connections)
- [Selections](#selections)
- [table()](#table)
- [select()](#select)
Expand Down Expand Up @@ -86,11 +87,11 @@ The parameters are the same with [mysql](https://www.npmjs.com/package/mysql) li
const DB = require('fluent-mysql');

let connection = DB.connect({
host : 'host',
user : 'user',
password : 'password',
port : 'port',
database : 'database'
host : process.env.DB_HOST,
user : process.env.DB_USER,
password : process.env.DB_PASSWORD,
port : process.env.DB_PORT,
database : process.env.DB_DATABASE,
});

connection.then(result => {
Expand All @@ -103,6 +104,31 @@ connection.then(result => {

```

## Pooling connections
This function provides connection pooling using createPool(config).
This function gets pool connection, query and release it.


```js
const DB = require('fluent-mysql');

DB.createPool({
host : process.env.DB_HOST,
user : process.env.DB_USER,
password : process.env.DB_PASSWORD,
port : process.env.DB_PORT,
database : process.env.DB_DATABASE,
});

let query = DB.table('users').get();

query.then(results => {
//...
}
}).catch(err => console.log(err));

```

## Selections

### table()
Expand Down Expand Up @@ -186,7 +212,7 @@ users.then( result => {

You can also write your own query with `query` method.
```js
let users = DB.query(`SELECT * FROM users WHERE name = "John"`).get();
let users = DB.query(`SELECT * FROM users WHERE name = "John"`);

users.then( results => {
//...
Expand Down
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "fluent-mysql",
"version": "1.1.0",
"version": "1.2.0",
"description": "MySQL query builder to perform database operations",
"main": "./lib/index.js",
"dependencies": {
Expand Down
95 changes: 53 additions & 42 deletions src/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ const mysql = require('mysql');
* Mysql Database class
*
* @property {Object} connection
* @property {object} pool
* @property {string} tableName
* @property {array} whereArray
* @property {array} orWhereArray
Expand Down Expand Up @@ -41,37 +42,9 @@ const mysql = require('mysql');

class Database {
constructor() {
this.connection = null;
this.tableName = null;
this.whereArray = [];
this.orWhereArray = [];
this.whereBetweenArray = [];
this.orWhereBetweenArray = [];
this.whereNotBetweenArray = [];
this.orWhereNotBetweenArray = [];
this.whereInArray = [];
this.whereNotInArray = [];
this.orWhereInArray = [];
this.orWhereNotInArray = [];
this.whereNullArray = [];
this.orWhereNullArray = [];
this.whereNotNullArray = [];
this.orWhereNotNullArray = [];
this.selections = '*';
this.distinctClause = '';
this.findId = null;
this.orderType = null;
this.orderColumn = null;
this.fetchFirst = false;
this.existsQuery = false;
this.joins = [];
this.leftJoins = [];
this.rightJoins = [];
this.groupByColumn = null;
this.havingArray = [];
this.limitNumber = null;
this.offsetNumber = null;
this.hasCount = false;
this.connection = null;
this.pool = null;
this.setPropertiesToDefault();
}

/**
Expand Down Expand Up @@ -117,6 +90,38 @@ class Database {
this.connection.end();
}

/**
* @param {object} params
* @return {void}
*/
createPool = (params) => {
let pool = mysql.createPool(params);
this.pool = pool;
}

/**
* @return {object} - Promise
*/
getPoolConnection = () => {
let self = this;
return new Promise( (resolve, reject) => {
self.pool.getConnection(function(err, connection) {
if (err) {
reject(err);
}
self.connection = connection;
resolve(connection);
});
});
};

/**
* @return {void}
*/
releasePool = () => {
this.connection.release();
};

/**
* Creates join statement if any and returns it
*
Expand Down Expand Up @@ -333,7 +338,7 @@ class Database {

let orderByStatement = '';
if(this.orderType != null && this.orderColumn != null) {
orderbyStatement = ` ORDER BY ${this.orderColumn} ${this.orderType} `;
orderByStatement = ` ORDER BY ${this.orderColumn} ${this.orderType} `;
}
return orderByStatement;
}
Expand Down Expand Up @@ -417,19 +422,20 @@ class Database {
let fetchFirst = this.fetchFirst;
let hasCount = this.hasCount;
let findId = this.findId;
let connection = this.pool !== null ? this.pool : this.connection;
let self = this;

return new Promise( (resolve, reject) => {
this.connection.query(this.getQueryStatement('get'), function (error, results, fields) {
connection.query(this.getQueryStatement('get'), function (error, results, fields) {
if (error) reject( error );

// if exists() method is used
if(existsQuery){
resolve(results.length > 0);
resolve(self.json(results[0].count) > 0);
} else {
// Only get first result
if(fetchFirst == true || findId != null){
resolve(self.json(results[0]));
resolve(results.length ? self.json(results[0]) : self.json(results));
} if(hasCount == true){
resolve(self.json(results[0].count));
} else {
Expand All @@ -447,9 +453,10 @@ class Database {
* @return {Object} - Promise
*/
insert = params => {
let connection = this.pool !== null ? this.pool : this.connection;
let self = this;
return new Promise( (resolve, reject) => {
this.connection.query(this.getQueryStatement('insert'), params, function (error, results, fields) {
connection.query(this.getQueryStatement('insert'), params, function (error, results, fields) {
if (error) reject( error );
resolve(self.json(results));
});
Expand All @@ -463,9 +470,10 @@ class Database {
* @return {Object} - Promise
*/
insertOrUpdate = params => {
let connection = this.pool !== null ? this.pool : this.connection;
let self = this;
return new Promise( (resolve, reject) => {
this.connection.query(this.getQueryStatement('insertOrUpdate'), [params, params], function (error, results, fields) {
connection.query(this.getQueryStatement('insertOrUpdate'), [params, params], function (error, results, fields) {
if (error) reject( error );
resolve(self.json(results));
});
Expand All @@ -479,10 +487,11 @@ class Database {
* @return {Object} - Promise
*/
update = params => {
let connection = this.pool !== null ? this.pool : this.connection;
let self = this;
return new Promise( (resolve, reject) => {
console.log(this.getQueryStatement('update'));
this.connection.query(this.getQueryStatement('update'), params, function (error, results, fields) {
connection.query(this.getQueryStatement('update'), params, function (error, results, fields) {
if (error) reject( error );
resolve(self.json(results));
});
Expand All @@ -496,9 +505,10 @@ class Database {
* @return {Object} - Promise
*/
delete = () => {
let connection = this.pool !== null ? this.pool : this.connection;
let self = this;
return new Promise( (resolve, reject) => {
this.connection.query(this.getQueryStatement('delete'), function (error, results, fields) {
connection.query(this.getQueryStatement('delete'), function (error, results, fields) {
if (error) reject( error );
resolve(self.json(results));
});
Expand All @@ -514,8 +524,9 @@ class Database {
*/
query = queryStatement => {
let self = this;
let connection = this.pool !== undefined ? this.pool : this.connection;
return new Promise( (resolve, reject) => {
this.connection.query(queryStatement, function (error, results, fields) {
connection.query(queryStatement, function (error, results, fields) {
if (error) reject( error );
resolve(self.json(results));
});
Expand Down Expand Up @@ -753,7 +764,7 @@ class Database {
* @param {string} orderType
* @return {Database}
*/
orderby = (column, orderType) => {
orderBy = (column, orderType) => {
if( ['asc', 'desc', 'ASC', 'DESC'].includes(orderType) ) {
this.orderType = orderType;
this.orderColumn = column;
Expand Down Expand Up @@ -953,7 +964,7 @@ class Database {
this.orWhereInArray = [];
this.orWhereNotInArray = [];
this.whereNullArray = [];
this.orwhereNullArray = [];
this.orWhereNullArray = [];
this.whereNotNullArray = [];
this.orWhereNotNullArray = [];
this.selections = '*';
Expand Down

0 comments on commit d3143e3

Please sign in to comment.