0

I have a package for npm that I have built locally for a couple of months. In order to have it work properly, it requires access to a PostgreSQL database. Therefore it needs to, preferably, auto-run a script that creates the database and the tables.

Is this possible, and if possible, where can I make such script? I'd like to automate as much as possible when npm install runs.

Golo Roden
  • 140,679
  • 96
  • 298
  • 425
OFRBG
  • 1,653
  • 14
  • 28
  • I tried looking for information on running a script that creates databases, taking into account the user who is running npm, but there are nothing to be found. That's why I ask here. – OFRBG Aug 28 '17 at 04:56

1 Answers1

0

Have nmp invoke psql -qAtX -v ON_ERRORS_STOP=1 -f my_script.sql and error if it returns nonzero. It should be just like running any other command in your install script.

You can have psql connect to the postgres database initially, then

CREATE DATABASE mydb;
\c mydb

reconnect to the new DB. But personally, I'd have one psql invocation create the DB, then another connect to the new DB. It simplifies error handling.

You can set the postgres instance to connect to via environment variables PGUSER, PGHOST, PGDATABASE, etc (see the psql manual) or via parameters passed to the command.

psql will default to the name of the current unix/windows user account if one isn't specified.

Craig Ringer
  • 307,061
  • 76
  • 688
  • 778
  • Thanks you very much. I found no information on this earlier. – OFRBG Aug 28 '17 at 05:08
  • Just posted regarding this: https://mail.google.com/mail/u/1/?ui=2&ik=cee2ba9a0e&jsver=-8Gn2zfonJc.en_GB.&view=om&th=15e2746f665bc23b – Craig Ringer Aug 28 '17 at 05:19
  • Note that I'm assuming you have a pre-existing postgres instance to connect to, and just need to populate it. If you need to create a postgres instance you'll need to run `initdb` too. Note, please **do not use the default postgres port** if your app installer creates its own postgres instance. – Craig Ringer Aug 28 '17 at 05:50
  • I appreciate the clear answer. Do you mind if I ask here how do run two clusters and choose to which one to connect? – OFRBG Aug 28 '17 at 06:18
  • @O.VonSeckendorff Start them on different ports. Connect by choosing which port to connect to. See also https://stackoverflow.com/q/14314026/398670 – Craig Ringer Aug 28 '17 at 06:22