1.0.8 • Published 5 years ago

node-postgresql v1.0.8

Weekly downloads
1
License
ISC
Repository
-
Last release
5 years ago

node-postgresql

系统要求

需支持es6环境

Class

  • PostgreSQL
  • Transaction

PostgreSQL 方法说明

构造函数
const options = {
    user: 'admin',
    password: '12345678',
	host: 'localhost',				//可选,默认localhost
	port: 5432,						//可选,默认5432
	max: 10,						//连接池连接数量,可选,默认10
	idleTimeoutMillis: 30000,		//连接最大空闲时间,可选,默认30000
	database: 'sample',				
	initSQL: 'path/to/sqlfile' 		//可选,仅供sync方法使用。
};
const pg = new PostgreSQL(options);
同步数据库(sync)

读取options.initSQL所指向文件包含的sql并执行执行,初始化数据库。

const pg = new PostgreSQL(options);
pg.sync().then(() => console.log('sync success');)

无初始化数据库需要无需调用

查询(query)
const pg = new PostgreSQL(options);
pg.query('select * from users').then(result => console.log(result));

//输出结构如下:
{ 
	command: 'SELECT', 
	rowCount: 1, 
	rows: [...], 
	fields: [...] 
}

其中fileds为rows返回结果中各字段的类型描述
获取事务对象(transaction)

事务对象为Transaction实例,两种方式获取事务对象:

const pg = new PostgreSQL(options);

//自动事务
pg.transaction(t => {
	//do something
})

//手动事务
pg.transaction().then(t => {
	//do something
})

Transaction 方法说明

构造

无需手动构造,通过PostgreSQL::transaction方法获取。

查询(query)

同PostgreSQL::query方法

开始事务(begin)

开始事务时调用。

提交事务(commit)

查询成功,提交事务时调用。

回滚事务(rollback)

查询出错,回滚事务时调用

事务使用示例
//自动事务对象使用示例

//自动事务对象在调用transaction时需传递一个function作为参数,
//系统以事务对象作为参数回调这个function,
//所有该次事务相关查询在该function中处理即可。

const pg = new PostgreSQL(options);

pg.transaction(t => {
	//无需调用t.begin
	return t.query('some sql')
		.then(() => {
			return t.query('some sql');
		})事务
})
.then(() => {
	//无需调用t.commit
})
.catch((err) => {
	//无需调用t.rollback
});


//手动事务对象使用示例
const pg = new PostgreSQL(options);

pg.transaction()
	.then(t => {
				//开始事务
		return t.begin()	
					.then(() => {
						return t.query('some sql');
					})
					.then(() => {
						return t.query('some sql');
					})
					.then(() => {
						//提交事务
						return t.commit();
					})
					.catch(err => {
						//回滚事务
						t.rollback();
					})
	})
1.0.8

5 years ago

1.0.7

5 years ago

1.0.6

7 years ago

1.0.5

7 years ago

1.0.4

7 years ago

1.0.3

7 years ago

1.0.1

7 years ago

1.0.0

7 years ago