@beenotung/ better-sqlite3- helper (英语)
用于此工作的节点包装库 较好的sqlite3 ("Node.js中SQLite3最快最简单的库"). 它旨在为节点提供简单的服务器-应用程序,并提供一些新的功能和一个迁移系统.
此软件包来自 更好的 sqlite3 帮助器 以 考托。大多数修改是回转的,但有一些 拖动请求 还有待处理.
在4.x版本中新建
- 断开: 叉入
@beenotung/better-sqlite3-helpernpm 释放 - 断开 : 较好的sqlite3 现在使用第12版.
- 事业:
@types/better-sqlite3添加为可选和同行依赖 - 成就: 建立数据库连接时自动设置同步文件
- 补丁: 为创建 DB 新实例而修正类型签名
- 弦:不再取决于
mkdirp,使用自fs换成
3.0版本中新建
较好的sqlite3 现在使用版本7. 这意味着“记忆”选项被删除(使用路径) :memory: - 也在第2版中工作),对Node.js < 10版本的支持被删除。 对于更古老的节点版本,您可以继续使用此库的第二版.
2.0 版本中新建
更好- sqlite3 版本 5 的所有命令( 如 函数 财务报告和审定财务报表 备份)现在也可以使用. 版本4的指令被删除. 此外,现在还有此库的TypeScript声明文件.
如何安装
安装到例如
npm i @beenotung/better-sqlite3-helper
如何使用
在每一个文件中,您想要访问 sqlite3 数据库只需要库并立即使用它.
任何服务费.js
const DB = require('@beenotung/better-sqlite3-helper')
let row = DB().queryFirstRow('SELECT * FROM users WHERE id=?', userId);
console.log(row.firstName, row.lastName, row.email);
要设置数据库,请创建 sql- 文件名称 001-init.sql 在一个 migrations-你的节目本部.
~/移民/001-init.sql
-- Up
CREATE TABLE `users` (
id INTEGER PRIMARY KEY,
firstName TEXT NOT NULL,
lastName TEXT NOT NULL,
email TEXT NOT NULL
);
-- Down
DROP TABLE IF EXISTS `users`;
就这样!
一个全球实例
一个普通而简单的应用程序大多只有一个数据库。 为了让班级管理更加简单,这个库为您做访问控制——主要是作为一个单子. (但您可以创建一个新实例来访问其他数据库 。)
数据库装入懒惰. 只有第一次使用时,数据库才会从文件中读出,开始迁移,并设置出日记-mode WAL. 数据库的默认目录是 './data/sqlite3.db'。 。 。 .
如果您想要更改默认值, 您可以在服务器代码开头给库打电话一次, 从而设置它 :
指数.js
const DB = require('@beenotung/better-sqlite3-helper')
// The first call creates the global instance with your settings
DB({
path: './data/sqlite3.db', // this is the default
readonly: false, // read only
fileMustExist: false, // throw error if database not exists
WAL: true, // automatically enable 'PRAGMA journal_mode = WAL'
migrate: { // disable completely by setting `migrate: false`
force: false, // set to 'last' to automatically reapply the last migration-file
table: 'migration', // name of the database table that is used to keep track
migrationsPath: './migrations' // path of the migration-files
}
})
在此之后, 您可以使用没有参数的库 :
另一个 APIFile.js
const DB = require('@beenotung/better-sqlite3-helper')
// a second call directly returns the global instance
let row = DB().queryFirstRow('SELECT * FROM users WHERE id=?', userId);
console.log(row.firstName, row.lastName, row.email);
新函数
此类执行快捷方法 较好的sqlite3。 。 。 .
// shorthand for db.prepare('SELECT * FROM users').all();
let allUsers = DB().query('SELECT * FROM users');
// result: [{id: 1, firstName: 'a', lastName: 'b', email: '[email protected]'},{},...]
// result for no result: []
// shorthand for db.prepare('SELECT * FROM users WHERE id=?').get(userId);
let row = DB().queryFirstRow('SELECT * FROM users WHERE id=?', userId);
// result: {id: 1, firstName: 'a', lastName: 'b', email: '[email protected]'}
// result for no result: undefined
// shorthand for db.prepare('SELECT * FROM users WHERE id=?').get(999) || {};
let {id, firstname} = DB().queryFirstRowObject('SELECT * FROM users WHERE id=?', userId);
// result: id = 1; firstName = 'a'
// result for no result: id = undefined; firstName = undefined
// shorthand for db.prepare('SELECT * FROM users WHERE id=?').pluck(true).get(userId);
let email = DB().queryFirstCell('SELECT email FROM users WHERE id=?', userId);
// result: '[email protected]'
// result for no result: undefined
// shorthand for db.prepare('SELECT * FROM users').all().map(e => e.email);
let emails = DB().queryColumn('email', 'SELECT email FROM users');
// result: ['[email protected]', '[email protected]', ...]
// result for no result: []
// shorthand for db.prepare('SELECT * FROM users').all().reduce((o, e) => {o[e.lastName] = e.email; return o;}, {});
let emailsByLastName = DB().queryKeyAndColumn('lastName', 'email', 'SELECT lastName, name FROM users');
// result: {b: '[email protected]', c: '[email protected]', ...}
// result for no result: {}
插入、更新和替换
有简指 update, (中文(简体) ), insert, (中文(简体) ), replace 财务报告和审定财务报表 delete它们旨在使CRUD-Rest-API功能的编程更加简单. 与一个 blacklist 或一个 whitelist 甚至有可能将请求的查询(或正文)直接发送到数据库中.
更新
// const numberOfChangedRows = DB().update(table, data, where, whitelist = undefined)
// simple use with a object as where and no whitelist
DB().update('users', {
lastName: 'Mustermann',
firstName: 'Max'
}, {
email: '[email protected]'
})
// data from a request and a array as a where and only editing of lastName and firstName is allowed
DB().update('users', req.body, ['email = ?', req.body.email], ['lastName', 'firstName'])
// update with blacklist (id and email is not allowed; only valid columns of the table are allowed) and where is a shorthand for ['id = ?', req.body.id]
DB().updateWithBlackList('users', req.body, req.body.id, ['id', 'email'])
插入和替换
// const lastInsertID = DB().insert(table, datas, whitelist = undefined)
// const lastInsertID = DB().replace(table, datas, whitelist = undefined)
// simple use with an object and no whitelist
DB().insert('users', {
lastName: 'Mustermann',
firstName: 'Max',
email: '[email protected]'
})
// inserting two users
DB().insert('users', [{
lastName: 'Mustermann',
firstName: 'Max',
email: '[email protected]'
}, {
lastName: 'Mustermann2',
firstName: 'Max2',
email: '[email protected]'
}])
// data from a request and only lastName and firstName are set
DB().replace('users', req.body, ['lastName', 'firstName'])
// replace with blacklist (id and email is not allowed; only valid columns of the table are allowed)
DB().replaceWithBlackList('users', req.body, ['id', 'email']) // or insertWithBlackList
删除
//delete the user with an id of 4
DB().delete('users', {id: 4})
试试抓住
如果您想要将无效值放入数据库, 函数会丢出一个错误 。 所以别忘了用 try-catch。这里有一个特快服务器的例子:
const { Router } = require('express')
const bodyParser = require('body-parser')
const DB = require('@beenotung/better-sqlite3-helper')
router.patch('/user/:id', bodyParser.json(), function (req, res, next) {
try {
if (!req.params.id) {
res.status(400).json({error: 'missing id'})
return
}
DB().updateWithBlackList(
'users',
req.body,
req.params.id,
['id']
)
res.statusCode(200)
} catch (e) {
console.error(e)
res.status(503).json({error: e.message})
}
})
移徙
这个图书馆的迁移模仿了优秀的迁徙系统 块状 由克里亚索德所著.
要使用此特性, 您必须创建 migrations- 书在你的根。 内部创建 sql- 在上下段分隔的文件:
migrations/001-initial-schema.sql
-- Up
CREATE TABLE Category (id INTEGER PRIMARY KEY, name TEXT);
CREATE TABLE Post (id INTEGER PRIMARY KEY, categoryId INTEGER, title TEXT,
CONSTRAINT Post_fk_categoryId FOREIGN KEY (categoryId)
REFERENCES Category (id) ON UPDATE CASCADE ON DELETE CASCADE);
INSERT INTO Category (id, name) VALUES (1, 'Business');
INSERT INTO Category (id, name) VALUES (2, 'Technology');
-- Down
DROP TABLE Category
DROP TABLE Post;
migrations/002-missing-index.sql
-- Up
CREATE INDEX Post_ix_categoryId ON Post (categoryId);
-- Down
DROP INDEX Post_ix_categoryId;
文件需要编号 。 它们在数据库首次使用前自动被执行.
页:1:对于开发环境,在研究数据库计划时,您可能想要设置
force: 'last' (默认) false),这将迫使迁移的API在Node.js应用启动时每次再次回滚并重新应用最新的迁移. 见"全球案例".
也可以给出一系列变化.
const DB = require('@beenotung/better-sqlite3-helper')
const db = new DB({
migrate: {
migrations: [
`-- Up
CREATE TABLE Setting (
key TEXT NOT NULL UNIQUE,
value BLOB,
type INT NOT NULL DEFAULT 0,
PRIMARY KEY(key)
);
CREATE INDEX IF NOT EXISTS Setting_index_key ON Setting (key);
-- Down
DROP INDEX IF EXISTS Setting_index_key;
DROP TABLE IF EXISTS Setting;
`,
`-- Up
INSERT INTO Setting (key, value, type) VALUES ('test', 'now', 0);
INSERT INTO Setting (key, value, type) VALUES ('testtest', 'nownow', 6);
-- Down
DELETE FROM Setting WHERE key = 'test';
DELETE FROM Setting WHERE key = 'testtest';
`
]
}
})