api_postgre
v0.0.2
Published
一个基于Node.js的PostgreSQL数据库链式调用库,支持类型校验、事务、SQL生成等功能,适合高效开发PostgreSQL应用。
Readme
api_postgre
一个基于Node.js的PostgreSQL数据库链式调用库,支持类型校验、事务、SQL生成等功能,适合高效开发PostgreSQL应用。
安装
npm install api_postgre快速开始
1. 初始化数据库连接
import { DB } from "api_postgre"
await DB.connect({
applicationName: "myapp",
port: 5432,
hostname: "localhost",
database: "testdb",
user: "postgres",
password: "yourpassword",
poolNum: 10
})2. 链式构建SQL并执行
import { Sql } from "api_postgre"
// 查询
await new Sql("users").where({ name: "张三" }).findOne()
// 查询多条
await new Sql("users").limit(2).total().find()
// 插入
await new Sql("users").insert({ name: "李四", age: 20 })
// 更新
await new Sql("users").where({ id: 1 }).update({ age: 21 })
// 删除
await new Sql("users").where({ id: 1 }).delete()
// 逻辑删除,更新某条数据删除标识
await new Sql("users").where({ id: 1 }).remove({ isDel: 1 })
// 指定表架构,默认public
await new Sql("users").schema("user").where({ name: "张三" }).findOne()
4. 事务支持
const tx = await DB.createTransaction()
try {
await new Sql("users").transaction(tx).insert({ name: "事务用户1" })
await new Sql("users").transaction(tx).insert({ name: "事务用户2" })
await tx.commit()
} catch (e) {
await tx.rollback()
} finally {
tx.release()
}5. 定义数据模型(可选)
import { Schema } from "api_postgre"
const userSchema = new Schema({
id: { type: Number, required: true },
name: { type: String, required: true },
age: { type: Number }
})
console.log(userSchema.create({id: 1, name: "用户", age: 18}))
主要特性
- 链式调用构建SQL
- 支持事务
- 类型校验与Schema定义
License
MIT
