
/*=============================================================================================
	author:ZhaoJun
	version:1.2
	email:2732810281@qq.com
=============================================================================================*/


//严格模式
/*-------------------------------------------------------------------------------------------*/	
'use strict';
/*-------------------------------------------------------------------------------------------*/	
    
var postgresql=require("pg");

//postgresql 初始化
/*-------------------------------------------------------------------------------------------*/	    
    
class db_postgresql
{
	static async con() 
	{	
        const cdb=$DbMysql.$opt
        for (const key in cdb) 
        {
			let cur=cdb[key]
			$DbPg.$con[key]=new postgresql.Pool(cur);
			if($DbPg.$con[key])
			{
				console.info(`postgresql进程：`+process.pid+`------初始化成功[${key}]`);
			}
			else
			{
				console.error(`postgresql进程：`+process.pid+`------初始化错误[${key}]`);
			}
        }
	};

	static query(sql,key='main',tag,descript='')
	{
		if(!sql)return false;
		if($DbPg.$info.sqlAble)console.info(`[postgresql-${descript?descript:'请求'}]\r\n`,sql.replace(/(\s*?)(\S.*?[\n|$])/g,'$2'));

		function cal(resolve,reject)
		{
			function my(e,con,done)
			{
				if(e)
				{
					if(con)
					{
						done();
					}
					reject(e);
				}
				else
				{	
					function bac(err,row)
					{
						if($DbPg.$info.sqlBackAble)console.info(`[postgresql-${descript?descript:'请求'}]返回\r\n`,row);
						if(err)
						{
							done();
							reject(err);
						}
						else
						{
							if(!tag)
							{
								done();
								resolve(row);
							} 
							else
							{
								resolve({result:row,con:con,done:done});
							}
						}
					}
					con.query(sql,bac);
				}
			}
			$DbPg.$con[key].connect(my);   		 		
		}
		return new Promise(cal);
	}

	static async lastid(con,tag)
	{
		if(!con)con=this;
		let result=await db_postgresql.transactionQuery(con,'select @@IDENTITY as id');

		result=result.result;
		if(result)
		{
			return result[0]['id'];
		}
		if(tag)$Sys.err({message:"没发现id"});
		throw Error();
	}

	static async transactionQuery(con,sql,descript='')
	{
		if(!sql)
		{
			sql=con;
			con=this;
			if(!sql)return false;
			if($DbPg.$info.sqlAble)console.info(`[postgresql-transaction-${descript?descript:'请求'}]\r\n`,sql.replace(/(\s*?)(\S.*?[\n|$])/g,'$2'));

			return new Promise
			(
				function(resolve,reject)
				{
					con.query
					(
						sql,
						function(err,row)
						{
							if(err)
							{
								reject(err);
							}
							else
							{
								if($DbPg.$info.sqlBackAble)console.info(`[postgresql-transaction-${descript?descript:'请求'}]返回\r\n`,row);
								resolve(row);
							}
						},undefined,descript
					)
				}
			)
		}
		else
		{
			if($DbPg.$info.sqlAble)console.info(`[postgresql-transaction-${descript?descript:'请求'}]\r\n`,sql.replace(/(\s*?)(\S.*?[\n|$])/g,'$2'));
			return new Promise
			(
				function(resolve,reject)
				{
					con.query
					(
						sql,
						function(err,row)
						{
							if(err)
							{
								reject(err);
							}
							else
							{
								if($DbPg.$info.sqlBackAble)console.info(`[postgresql-transaction-${descript?descript:'请求'}]返回\r\n`,row);
								resolve({result:row,con:con});
							}
						},undefined,descript
					)
				}
			)
		}
	}

	static async transaction(fun,db='main')
	{
		var result=await db_postgresql.query('begin',db,true)
		try 
		{
			result.con.querys=db_postgresql.transactionQuery
			result.con.lastid=db_postgresql.lastid
			let res=await fun(result.con)
			await db_postgresql.transactionQuery(result.con,'commit');
			return (typeof res != 'undefined')?res:true;
		} 
		catch (error) 
		{
			await db_postgresql.transactionQuery(result.con,'rollback');
			console.error('[postgresql事物]出错：',error);
			$Sys.err(error);
			return false;
		}
		finally
		{
			result.done();
		}                 
	}
	
	static close(pool)
	{
		pool.end();
	}
}

module.exports=db_postgresql;