omega
omega

Reputation: 43843

How to drop a database in postgres sql using node.js?

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

Upvotes: 3

Views: 3852

Answers (1)

Paul
Paul

Reputation: 36319

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);
});

Upvotes: 6

Related Questions