3

I am trying to drop a database called test from node.js postgres sql but it is not working.

var express = require('express');
var app = express();
var pg = require('pg');
var pgp = require('pg-promise')();

// Connect to PostgreSQL database
var connectionString = process.env.DATABASE_URL || 'postgres://postgres:pass123@localhost:5432/test';
var db = pgp(connectionString);
db.connect();


  db.query("DROP DATABASE test").then(function()
  {
    //createDatabases(db);
  }).catch(function(err)
  {
    console.log(err);
  });

But I am getting an error

{ [error: cannot drop the currently open database]
  name: 'error',
  length: 87,
  severity: 'ERROR',
  code: '55006',
  detail: undefined,
  hint: undefined,
  position: undefined,
  internalPosition: undefined,
  internalQuery: undefined,
  where: undefined,
  schema: undefined,
  table: undefined,
  column: undefined,
  dataType: undefined,
  constraint: undefined,
  file: 'dbcommands.c',
  line: '834',
  routine: 'dropdb' }

Does anyone know how to fix it?

Thanks

1
  • You shouldn't call db.connect(); there. And you shouldn't include pg there. Commented Aug 7, 2016 at 18:00

1 Answer 1

6

As the error says, you can't be connected to the DB in question to drop it. You can connect to a different DB in order to do so, or use a tool like pgtools

var pgtools = require('pgtools');

// This can also be a connection string
// (in which case the database part is ignored and replaced with postgres)

const config = {
  user: 'postgres',
  password: 'some pass',
  port: 5432,
  host: 'localhost'
}


pgtools.dropdb(config, 'test-db', function (err, res) {
  if (err) {
    console.error(err);
    process.exit(-1);
  }
  console.log(res);
});
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks for posting this, just confirmed this worked very well, running from win10 git bash!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.