简体   繁体   中英

Postgres - run \c command in github actions

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?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM