node.js node-postgres 创建数据库
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/20813154/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
node-postgres create database
提问by anvarik
I am using node-postgres, and at the beginning of my application I want to check whether the database exists or not. So my workflow idea is as following:
我正在使用node-postgres,在我的应用程序开始时,我想检查数据库是否存在。所以我的工作流程想法如下:
- Check whether
myDbis existing - If it is there, create the tables
- If not, then create first the database, then tables
- 检查是否
myDb存在 - 如果存在,则创建表
- 如果没有,则先创建数据库,然后创建表
As you see it is a really easy process, however, the driver implementation requires to have a database name postgres://username:password@host/databaseto be connected, which means you need to connect to a database first.
如您所见,这是一个非常简单的过程,但是,驱动程序实现需要有一个postgres://username:password@host/database要连接的数据库名称,这意味着您需要先连接到数据库。
So what I am doing now is to connect to postgresdatabase at the beginning, making a query to create database, cathing the exception if it is already there, then closing my connection and connecting to the newly created database, then creating the tables. Here is the code:
所以我现在正在做的是postgres在开始时连接到数据库,进行查询以创建数据库,如果异常已经存在,则捕获异常,然后关闭我的连接并连接到新创建的数据库,然后创建表。这是代码:
var conStringPri = 'postgres://' + username + ':' + password + '@' + host +
'/postgres';
var conStringPost = 'postgres://' + username + ':' + password + '@' + host +
'/' + dbName;
pg.connect(conStringPri, function(err, client, done) { // connect to postgres db
if (err)
console.log('Error while connecting: ' + err);
client.query('CREATE DATABASE ' + dbName, function(err) { // create user's db
if (err)
console.log('ignoring the error'); // ignore if the db is there
client.end(); // close the connection
// create a new connection to the new db
pg.connect(conStringPost, function(err, clientOrg, done) {
// create the table
clientOrg.query('CREATE TABLE IF NOT EXISTS ' + tableName + ' ' +
'(...some sql...)';
});
});
});
As you see I am opening and closing the connection twice, and this way seems wrong to me. I'll be glad if you propose a better way, or maybe explain how did you accomplish this.
如您所见,我打开和关闭连接两次,这种方式对我来说似乎是错误的。如果您提出更好的方法,或者解释一下您是如何做到这一点的,我会很高兴。
回答by Daniel Vérité
As you see it is a really easy process, however, the driver implementation requires to have a database name postgres://username:password@host/database to be connected, which means you need to connect to a database first.
如您所见,这是一个非常简单的过程,但是,驱动程序实现需要连接数据库名称 postgres://username:password@host/database,这意味着您需要先连接到数据库。
It's not because of the driver implementation, it's PostgreSQL itself. It's the same with any other language or driver.
这不是因为驱动程序实现,而是 PostgreSQL 本身。任何其他语言或驱动程序都是如此。
A client needs to be connected to a database in order to do anything, including a CREATE DATABASE. Besides the postgresdatabase, template1is often used for this purpose too.
客户端需要连接到数据库才能执行任何操作,包括CREATE DATABASE. 除了postgres数据库,template1也经常用于此目的。
Then, since you must connect to the freshly created database to create objects inside it, there's no way to avoid opening another connection.
然后,由于您必须连接到新创建的数据库才能在其中创建对象,因此无法避免打开另一个连接。
In short, what you're doing can't be simplified, it's already optimal.
简而言之,您所做的事情不能简化,它已经是最佳的。
回答by Olivier Lalonde
I've just written a module for that: https://github.com/olalonde/pgtools
我刚刚为此编写了一个模块:https: //github.com/olalonde/pgtools
var pgtools = require('pgtools');
pgtools.createdb({
user: 'postgres',
password: 'some pass',
port: 5432,
host: 'localhost'
}, 'test-db', function (err, res) {
if (err) {
console.error(err);
process.exit(-1);
}
console.log(res);
});
Hopefully it can make your code a bit cleaner.
希望它可以使您的代码更简洁一些。
回答by Redd.o
This is a bit old but I just want to share how I handled this kind of setup.
这有点旧,但我只想分享我如何处理这种设置。
You need to call the third param from the callback which is the donefrom pg.connect(conn, (err, client, done) => {}). This will release the connection and bring back to pool.
您需要从回调中调用第三个参数,即donefrom pg.connect(conn, (err, client, done) => {})。这将释放连接并带回池。
async.series([
done => {
pg.connect(connPrimary, (err, client, releaseConn) => {
if (err) return done(err)
client.query(`CREATE DATABASE ${conf.database}`, (err) => {
if (err && !~err.message.indexOf('already exists')) {
return done(err)
}
client.end()
releaseConn()
done()
})
})
},
done => {
let connSecondary = `postgres://${conf.user}:${conf.password}@${conf.host}:${conf.port}/${conf.database}`
pg.connect(connSecondary, (err, client, releaseConn) => {
if (err) return done(err)
let createTableQuery = `CREATE TABLE IF NOT EXISTS test_table(_id bigint primary key, co2_field varchar(40) NOT NULL, temp_field int NOT NULL, quality_field decimal NOT NULL, reading_time_field timestamp NULL)`
client.query(createTableQuery, err => {
if (err) return done(err)
releaseConn()
done()
})
})
}
], err => {
should.ifError(err)
doneInit()
})
回答by аlex dyky?
Install
安装
npm install --save -g pgtools
CLI Example
命令行示例
createdbjs my_awesome_db --user=admin --password=admin

