Self-Realization PostgreSQL Nodejs Drive, share to everyone

Source: Internet
Author: User
Tags mongodb find postgresql version git clone

PostgreSQL performance does not lose MySQL, and support many advanced features, so I wrote this project, according to LIBPG C drive, encapsulated the Nodejs driver.

Project Address:

git clone https://code.csdn.net/limite_god/pgsql.git

Development difficulties, features to be implemented, features

1, Nodejs v0.12.0 began, the API has a lot of changes, familiar with these changes for a lot of time;

2, Libpg-c API familiar, all English, have a line to look carefully;

3, makefile, the knowledge is miscellaneous and fine, only wrote a Linux under the compilation;

4, LIBPG's Executeparam method is not implemented, so added escape connection pool, specifically to handle escape;

5, data type support, now only LIBPG Int4 and int8 have been converted, other formats will return strings (such as the date);

6, the connection pool uses Nodejs's eventemitter realization, the SQL command will queue up when the pressure is big, this piece of strategy is very important, involves the nodejs core thought, tries to exert the slow speed resource maximum performance, pool.js, everybody may examine;

7, Database object Cmpool and Trpool, espool,cm processing no need to declare a transaction SQL,TR used to specifically perform transactional connection, ES is specifically used to escape string;

8, the API to do as far as possible to the caller the greatest freedom, coordination of resources to drive.

9, many local comments are missing, waiting to be added later;

10, table realizes the class MongoDB Find,update,remove,save, can pass the options parameter, the options parameter temporarily only supports 4 key,ret,sort,limit,offset;

11, I will continue to maintain the project, add more features, there are suggestions please leave a message.


Environment preparation

Operating system centos6+, installing Nodejs version V0.12.0+,postgresql version 9.4.1

It is necessary to note that both Nodejs and PostgreSQL need to be installed from the source code, postgress installation directory using the default directory,/usr/local/pgsql/, if your directory is different, please modify the project and directory makefile


Downloading the code and compiling the module is not registered in the official module, so it is best to execute it in the Node_modules directory of your Nodejs program.
git clone https://code.csdn.net/limite_god/pgsql.git

CD Pgsqlmake

Project makefile only support Linux, and its simple, the most likely to occur two kinds of errors, one kind is the header file can not find, one kind is the method implementation is not.
If the header file is not found 1, check Nodejs and postgres whether to install 2, check the makefile header file scan directory and your system's installation directory is consistent, if not consistent, please modify
If the prompt method implementation is not found this is generally because your system has not put postgres dynamic library into the system scan path
Try adding/etc/ld.so.conf.d/pgsql.conf, add a line/usr/local/pgsql/lib (the path to your PG dynamic library), and then execute the Ldconfig

DEMO
var async = require (' async ');
var pgsql = require (' Pgsql '); var DataBase = Pgsql. Database;var Table = Pgsql. Table;var Column = Pgsql. Column;var db = new DataBase ({URL: "host=127.0.0.1 dbname=test user=postgres", cmpoolsize:20,//via Table.find,update , remove,save Use this connection pool connection Trpoolsize:5,//db.getconn get connection is this connection pool connection Espoolsize:1//This connection pool is dedicated to perform escape}); var te sttable = new Table ("Test", [New column ("id", "SERIAL", 0, "primary key"), new Column ("Index", "SERIAL", 0, ""), new column ("Name", "Text",-1, ""), new column ("description", "Text",-1, "")]); testtable.collist[' Description '].escape = true; The text needs to be escaped db.put (testtable); Async.waterfall ([function (CB) {//Connection database Db.init (function (err, data) {C            Onsole.log (data);        CB (ERR);    });        }, function (CB) {var t = db.get ("test");        Console.log (T.GETDDL ());            T.find ({Id:3}, {}, function (err, data) {Console.log (data);        CB (ERR);    }); }, FunCtion (CB) {var t = db.get ("test");            var doc = {$set: {name: "Just a Test."        }        };            T.update ({id:3}, doc, function (err, data) {Console.log (data);        CB (ERR);    });        }, function (CB) {var t = db.get ("test");        var options = {limit:10, offset:0, sort:{id:-1}};            T.find ({Id:3}, {}, Options, function (err, data) {Console.log (data);        CB (ERR);    });        }, function (CB)//save a set {var t = db.get ("test");            T.save ({name: "liming", Description: ' a\ ' B '}, function (err, data) {Console.log (data);        CB (ERR);    });        }, function (CB)//Save record and return the self-growing id {var t = db.get ("test");        var options = {ret:{id:1}}; T.save ({name: "liming", Description: ' a\ ' B '}, options, function (Err, data) {Console.log (data);        CB (ERR);    });        }, function (CB) {var t = db.get ("test");            T.remove ({name: "test222"}, function (err, data) {Console.log (data);        CB (ERR);    });            }, function (CB)//cross-table statement, use Db.execute to directly execute {db.execute ("SELECT * from Customer", function (err, data) {            Console.log (data);        CB (ERR);    });        },/* Execute transaction */function (CB) {Db.getconn (err, conn) {CB (ERR, conn);    });            }, function (conn, CB) {Conn.execute ("BEGIN", function (err, data) {Console.log (data);        CB (ERR, conn);    });            }, function (conn, CB) {Conn.execute ("DECLARE myportal CURSOR for SELECT * from Test", function (err, data) {            Console.log (data);        CB (ERR, conn);    });        }, function (conn, CB) {var hasnext = true;      Async.whilst (//Conditional function () {          return hasnext;  True, the second function continues execution, otherwise, the loop}, function (WHILECB) {///Loop body Conn.execute ("FETCH NEXT in                        Myportal ", function (err, data) {if (data && data.affected > 0) {                    Console.log (data);                    } else {hasnext = false;                } WHILECB (ERR);            });            }, function (err) {//here If the condition is not met, or an exception occurs CB (ERR, conn);    }        );            }, function (conn, CB) {Conn.execute ("CLOSE myportal", function (err, data) {Console.log (data);        CB (ERR, conn);    });            }, function (conn, CB) {Conn.execute ("END", function (err, data) {Console.log (data);        CB (ERR, conn);    }); }], function (ERR, conn) {if (conn) {////Use end connection, remember to return to connection pool DB.UNLOCK (conn);        } if (err) {Console.log ("The error is:");    Console.error (ERR); }});

The output is as follows:
Init success!create table Test (ID SERIAL primary key, index SERIAL, name text, description text); select * FROM Test whe Re (id = ' 3 ') {affected:0, rst: []}update Test Set name = ' Just a test. ' WHERE (id = ' 3 ') {affected:0, rst: []}select * FROM test where (id = ' 3 ') the ORDER BY id desc-Limit 10{affected:0, rst: []}insert into Test (name,description) VALUES (' L IMing ', ' a ' B ') {affected:1, rst: []}insert into Test (name,description) VALUES (' liming ', ' a ' ' B ') returning id{affected:1        , rst: [{id:23}]}delete from test where (name = ' test222 ') {affected:0, rst: []} {affected:1, rst: [{id:1,  Username: ' liming ', Password: ' 123456 ', reg_time: ' 2015-03-25 22:26:30 ', Type:1, status:1 }]} {affected:0, rst: []} {affected:0, rst: []} {affected:1, rst: [{id:18, index:18, Name: ' Liming ', descript  Ion: ' A\ ' B '}]} {affected:1, rst: [{id:19, index:19, Name: ' Liming ', Description: ' a\ ' B '}]} {affected:1, rst: [{id:20, index:20,Name: ' liming ', Description: ' a\ ' B '}} {affected:1, rst: [{id:21, index:21, Name: ' Liming ', Description: ' a\ ' B '} } {affected:1, rst: [{id:22, index:22, Name: ' Liming ', Description: ' a\ ' B '}]} {affected:1, rst: [{id:23, index:23, Name: ' Liming ', Description: ' a\ ' B '}]} {affected:0, rst: []} {affected:0, rst: []}


Self-Realization PostgreSQL Nodejs Drive, share to everyone

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.