0

In GitHub actions, I am running a JavaScript file which connects to PostgreSQL and creates the table and extension for the database.

my script looks like this:

const { Client } = require('pg')

const pgclient = new Client({
  host: process.env.POSTGRES_HOST,
  port: process.env.POSTGRES_PORT,
  user: process.env.POSTGRES_USER,
  password: process.env.POSTGRES_PASSWORD,
  database: process.env.POSTGRES_DB,
})

pgclient.connect()

const createDB = `
    drop database mydb;
    create database mydb;
    \c mydb;
    CREATE EXTENSION "pgcrypto";
`

pgclient.query(createDB, (err, res) => {
  if (err) throw err
  pgclient.end()
})

When I run the script, I get an error

error: syntax error at or near "c"

Which I am guessing is coming from \c flag.

How do I use PostgreSQL commands like this?

3
  • is it that you have to escape the \? Therefore \\c ? Commented Jul 31, 2020 at 5:23
  • @Carter changed \c to \\c and now I get syntax error at or near "\" haha Commented Jul 31, 2020 at 5:31
  • what if you just type in there instead connect to mydb. I think the issue is you might be mixing command line and SQL, but you are in sql at that point not in a command line it seems. Commented Jul 31, 2020 at 5:36

1 Answer 1

1

you can not use \c here because it is a psql meta-command, which I think you do not use here: See https://www.postgresql.org/docs/current/app-psql.html.

You need to reconnect to the new DB like so:

const pgclient_mydb = new Client({
  host: process.env.POSTGRES_HOST,
  port: process.env.POSTGRES_PORT,
  user: process.env.POSTGRES_USER,
  password: process.env.POSTGRES_PASSWORD,
  database: 'mydb',
})

pgclient_mydb.connect()

See also https://stackoverflow.com/a/43670984/10743176

Sign up to request clarification or add additional context in comments.

Comments

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.