node-postgres create database

后端 未结 4 1804
孤城傲影
孤城傲影 2021-01-03 20:45

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:

  1. Check
相关标签:
4条回答
  • 2021-01-03 20:56

    I've just written a module for that: 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.

    0 讨论(0)
  • 2021-01-03 21:03

    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 done from pg.connect(conn, (err, client, done) => {}). This will release the connection and bring back to pool.

     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()
    })
    
    0 讨论(0)
  • 2021-01-03 21:05

    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.

    It's not because of the driver implementation, it's PostgreSQL itself. It's the same with any other language or driver.

    A client needs to be connected to a database in order to do anything, including a CREATE DATABASE. Besides the postgres database, template1 is often used for this purpose too.

    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.

    0 讨论(0)
  • 2021-01-03 21:06

    Install

    npm install --save -g pgtools
    

    CLI Example

    createdbjs my_awesome_db --user=admin --password=admin
    
    0 讨论(0)
提交回复
热议问题