node-mysql-query-utils
A MySQL query builder and helper for Node.js.
Installation
npm install node-mysql-query-utils
or
yarn add node-mysql-query-utils
Usage
Common usage
import { DatabaseManagement, TableModel, SQLBuilder, sqlHelper } from "node-mysql-query-utils";
DatabaseManagement.connectMultipleDatabases([
{
identifierName: 'mainDB',
config: {
host: "localhost",
user: "root",
password: "password",
database: "test_db",
},
}
]);
const mainDB = DatabaseManagement.getInstance('mainDB');
const columns = sqlHelper.createColumns([
"user_id",
"ctime",
"utime",
"email",
"mobile",
"password",
"is_active",
"is_deleted",
]);
export const userAccountModel = mainDB.createTableModel({
tableName: "user_account",
primaryKey: "user_id",
columns,
centralFields: {
ctimeField: 'ctime',
utimeField: 'utime',
isActiveField: 'is_active',
isDeletedField: 'is_deleted',
statusField: 'status',
}
});
const [user] = await userModel.findOne({ where: { user_id: 1234 } }).executeQuery();
const users = await userModel.findAll().executeQuery();
const updatedOneUser = await userModel.updateOne({
where: { user_id: 1052 },
data: { email: '123@gmail.com' }
}).executeQuery()
const deletedOneUser = await userModel.removeOne({
where: { user_id: { ">": 1234 } },
orderBy: [{ field: 'user_id', direction: 'ASC' }]
}).executeQuery()
const deletedAllUsers = await userModel.remove({ where: { user_id: 1234 } }).executeQuery()
const softDeletedUser = await userModel.softDelete({
where: { user_id: 1234 },
value: 1,
options: { enableTimestamps: true, deleteField: 'is_deleted', utimeField: 'utime' }
}).executeQuery();
const patchedActiveField = await userModel.patchSingleField({
patchField: 'is_active',
where: { user_id: 1234 },
value: 1,
options: { enableTimestamps: true, utimeField: 'utime' }
}).executeQuery();
Database Management
The DatabaseManagement
class is a singleton class that helps manage database connections. It supports connecting to single or multiple databases and provides a way to retrieve instances of the connections.
Example
Single database connection
import { DatabaseManagement } from "node-mysql-query-utils";
import { ConnectionOptions } from "mysql2/promise";
const config: ConnectionOptions = {
host: "localhost",
user: "root",
password: "password",
database: "test_db",
};
DatabaseManagement.connectSingleDatabase("mainDB", config);
const dbInstance = DatabaseManagement.getInstance("mainDB");
Multiple database connections
import { DatabaseManagement } from "node-mysql-query-utils";
import { type DatabaseConnectionConfig } from "node-mysql-query-utils/dist/dto/types";
const configs: DatabaseConnectionConfig[] = [
{
identifierName: "mainDB",
config: {
host: "localhost",
user: "root",
password: "password",
database: "main_db",
},
},
{
identifierName: "analyticsDB",
config: {
host: "localhost",
user: "root",
password: "password",
database: "analytics_db",
},
},
];
DatabaseManagement.connectMultipleDatabases(configs);
const mainDBInstance = DatabaseManagement.getInstance("mainDB");
const analyticsDBInstance = DatabaseManagement.getInstance("analyticsDB");
Summary
- Example: Shows how to connect to a single database and retrieve the instance.
- Connecting to Multiple Databases: Demonstrates how to connect to multiple databases and retrieve their instances.
- API: Documents the main methods of the [
DatabaseManagement
] class.
Table Model
The TableModel
class provides a way to build a table model from a JSON object. The table model can be used to create a table in a database.
Example
import {
DatabaseManagement,
TableModel,
sqlHelper,
} from "node-mysql-query-utils";
const dbInstance = DatabaseManagement.getInstance("mainDB");
const columns = sqlHelper.createColumns([
"user_id",
"ctime",
"utime",
"email",
"mobile",
"password",
"is_active",
"is_deleted",
]);
const userAccountModel = master.createTableModel({
tableName: "user_account",
primaryKey: "user_id",
columns,
});
const userAccountModel = new TableModel({
tableName: "user_account",
primaryKey: "user_id",
columns,
queryFn: db.query.bind(db),
});
Query Function
The queryFn is an optional function that should match the following type definition:
type QueryFunction = <T>(sql: string, params?: any[]) => Promise<T>;
Summary
- Example: Shows how to create a table model for a user table.
- API: Documents the main methods of the [
TableModel
] class.
SQL Builder
The SQLBuilder
class provides a way to build SQL queries for CRUD operations.
Example
import { SQLBuilder, sqlHelper } from "node-mysql-query-utils";
const tableName = "user_account";
const sqlBuilder = new SQLBuilder();
const columns = sqlHelper.createColumns([
"user_id",
"ctime",
"utime",
"email",
"mobile",
"password",
"is_active",
"is_deleted",
]);
const sqlBuilder = new SQLBuilder<typeof columns[number]>();
const sqlBuilder = new SQLBuilder(db.query.bind(db));
const sqlBuilder = new SQLBuilder<typeof columns[number], any>(db.query.bind(db));
const { sql, params } = sqlBuilder.select().from(tableName).buildQuery();
const [sql, params] = sqlBuilder.select().from(tableName).buildQuery();
const result = await db.query(sql, params);
const result = await sqlBuilder.select().from(tableName).executeQuery();
.select() Method
const [sql, params] = sqlBuilder.select().from(tableName).buildQuery();
const [sql, params] = sqlBuilder.select("*").from(tableName).buildQuery();
const [sql, params] = sqlBuilder
.select(["user_id", "email"])
.from(tableName)
.buildQuery();
const [sql, params] = sqlBuilder
.select([{ user_id: "id", mobile: "user_mobile" }, { email: "user_email" }])
.from(tableName)
.buildQuery();
const [sql, params] = sqlBuilder.select("user_id").from(tableName).buildQuery();
.from() Method
const [sql, params] = sqlBuilder.select().from("user_account").buildQuery();
const [sql, params] = sqlBuilder
.select()
.from("user_account", "u")
.buildQuery();
const [sql, params] = sqlBuilder.select().from("user_account u").buildQuery();
.join() Method
const [sql, params] = sqlBuilder
.select()
.from("user_account", "u")
.join(
"INNER",
"user_profile_pic",
"up",
"u.user_profile_pic_id = up.user_profile_pic_id"
)
.buildQuery();
const [sql, params] = sqlBuilder
.select()
.from("user_account", "u")
.join(
"LEFT",
"user_profile_pic",
"up",
"u.user_profile_pic_id = up.user_profile_pic_id"
)
.buildQuery();
const [sql, params] = sqlBuilder
.select()
.from("user_account", "u")
.join(
"RIGHT",
"user_profile_pic",
"up",
"u.user_profile_pic_id = up.user_profile_pic_id"
)
.buildQuery();
Only provide third argument if no alias is needed
const [sql, params] = sqlBuilder
.select()
.from("user_account", "u")
.join(
"INNER",
"user_profile_pic",
"u.user_profile_pic_id = user_profile_pic.user_profile_pic_id"
)
.buildQuery();
.where() Method
const [sql, params] = sqlBuilder
.select()
.from("user_account")
.where({
email: "123@gmail.com",
user_id: { ">": 123 },
user_id: { "<": 123 },
nickname: { IS_NOT_NULL: true },
is_active: { BETWEEN: [0, 1] },
status: { IN: [1, 2, 3, 4] },
"u.user_id": { "!=": 1 },
})
.buildQuery();
Supported Operators:
=
!=
>
<
>=
<=
LIKE
IN
BETWEEN
NOT_BETWEEN
IS_NULL
IS_NOT_NULL
.orderBy() Method
const [sql, params] = sqlBuilder
.select()
.from("user_account")
.orderBy([{ field: "email", direction: "ASC" }])
.buildQuery();
const [sql, params] = sqlBuilder
.select()
.from("user_account")
.orderBy([
{ field: "email", direction: "ASC" },
{ field: "user_id", direction: "DESC" },
])
.buildQuery();
.limit() and .offset() Methods
const [sql, params] = sqlBuilder
.select()
.from("user_account")
.limit(10)
.buildQuery();
const [sql, params] = sqlBuilder
.select()
.from("user_account")
.limit(10)
.offset(5)
.buildQuery();
.insert() Method
const [sql, params] = sqlBuilder
.insert('user_account', {email: '123@gmail.com'}, {
enableTimestamps = false,
ctimeField = 'ctime',
utimeField = 'utime',
ctimeValue = Math.floor(Date.now() / 1000),
utimeValue = Math.floor(Date.now() / 1000)
})
.buildQuery();
.update() Method
const [sql, params] = sqlBuilder
.update('user_account', {email: '123@gmail.com'}, {
enableTimestamps = false,
utimeField = 'utime',
utimeValue = Math.floor(Date.now() / 1000)
})
.where({user_id: 1})
.buildQuery();
const [sql, params] = sqlBuilder
.update('user_account')
.set({email: '123@gmail.com'})
.where({user_id: 1})
.buildQuery();
.delete() Method
const [sql, params] = sqlBuilder.deleteFrom('user_account').buildQuery();
const [sql, params] = sqlBuilder.deleteFrom('user_account')
.where({user_id: 1})
.buildQuery();
const [sql, params] = sqlBuilder.deleteFrom('user_account')
.where({user_id: {">": 1}})
.limit(1)
.buildQuery();
Changelog
Detailed changes for each version are documented in the CHANGELOG.md file.