title: node-postgres create database
body: <p>I am using <a href="https://github.com/brianc/node-postgres">node-postgres</a>, and at the beginning of my application I want to check whether the database exists or not. So my workflow idea is as following:</p>
  
  <ol>
  <li>Check whether <code>myDb</code> is existing</li>
  <li>If it is there, create the tables</li>
  <li>If not, then create first the database, then tables</li>
  </ol>
  
  <p>As you see it is a really easy process, however, the driver implementation requires to have a database name <code>postgres://username:password@host/database</code> to be connected, which means you need to connect to a database first. </p>
  
  <p>So what I am doing now is to connect to <code>postgres</code> database 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:</p>
  
  <pre><code>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...)';
          });
      });
  });
  </code></pre>
  
  <p>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.</p>