rapid-db
Version:
Rapid Database Interface
109 lines (100 loc) • 3.08 kB
JavaScript
/**
* Copyright (c) 2017 Lucky Byte, Inc.
*/
const debug = require('debug')('db');
const winston = require('winston');
const pgp = require('./lib/init');
const notify = require('./lib/notify');
/*
* 数据库对象,在初始化后有效,这是系统默认数据库
*/
global._unique_db = null;
/**
* 初始化数据库
*
* 参数
* connection_url: 数据库连接 URL
* notify_source: 系统通知来源,字符串
* 返回
* 数据库对象,之后可以用来执行 SQL 语句
*/
exports.init = (connection_url, notify_source) => {
if (!connection_url) {
throw new Error('初始化数据库连接 URL 无效');
}
if (notify_source) {
notify.set_source(notify_source);
}
global._unique_db = pgp(connection_url);
return global._unique_db;
}
/**
* 关闭所有数据库连接
*/
exports.deinit = () => {
pgp.end();
}
/**
* 连接数据库,这个函数和 init 基本一样,区别在于 init 会将建立的数据库连接
* 作为系统的默认数据库,而 connect 不会。
*
* 如果系统只有一个数据库,则调用 init 就足够了,如果系统需要连接多个数据库,
* 则调用 connect 分别进行连接,使用返回的数据库对象操作不同的数据库。
*
* 参数
* connection_url: 数据库连接 URL
* 返回
* 数据库对象,之后可以用来执行 SQL 语句
*/
exports.connect = (connection_url) => {
if (!connection_url) {
throw new Error('初始化数据库连接 URL 无效');
}
return pgp(connection_url);
}
/**
* 调用 pgp.helpers.insert() 方法生成 SQL 语句,然后调用
* db.none() 方法执行数据库操作
*
* 参数
* data: 参考 pgp.helpers.insert()
* table: 参考 pgp.helpers.insert()
* db: 可选的,数据库对象,如果为 null,则使用 _unique_db
* 返回
* 无
*/
exports.insert = async (data, table, db) => {
db = db || _unique_db;
if (!db) {
throw new Error('数据库对象无效,检查是否已初始化数据库');
}
const sql = pgp.helpers.insert(data, null, table);
await db.none(sql);
}
/**
* 调用 pgp.helpers.update() 方法生成 SQL 语句,然后调用
* db.none() 方法执行数据库操作
*
* 参数
* data: 参考 pgp.helpers.update()
* table: 参考 pgp.helpers.update()
* where: SQL where 条件子句
* db: 可选的,数据库对象,如果为 null,则使用 _unique_db
* 返回
* 无
*/
exports.update = async (data, table, where, db) => {
db = db || _unique_db;
if (!db) {
throw new Error('数据库对象无效,检查是否已初始化数据库');
}
const sql = pgp.helpers.update(data, null, table) + ` WHERE ${where}`;
await db.none(sql);
}
exports.helpers = pgp.helpers;
exports.as = pgp.as;
exports.new_order_id = require('./lib/new_order_id');
exports.cardbin = require('./lib/cardbin');
exports.notify = notify;
exports.trades = require('./lib/trades');
exports.new_token = require('./lib/new_token');