1

I have an install script that can create a db, with
(sql ddl)create database if not exist.
Since Postgres works differently the script doesn't work.
So I build a special case for Postgres and used the
(commandline) createdb -U ... command for generating a database.
It works so far, but Postgres requests the password a second time.

Following this thread i found out that
I can provide the password with the var PGPASSWORD
Following this thread i came up with a solution:
(php)

exec(' set PGPASSWORD=$password && createdb -U "$username" -h "$host" "$dbname" ')

(simplified escapes)

but this returns an error:
createdb: could not connect with template1: FATAL: Password authentication for user »postgres« failed (translated)

I am not familiar with commandline and its characteristics ->
I am not sure if I did a grave unnoticed misstake there, i am sorry if i did

I will implement now a version where Postgres asks the user a second time,
but it would be cool if you find a solution where the user doesn't have to type password twice

Jannis
  • 166
  • 1
  • 10

1 Answers1

0

Why use an operating system command? You can do the same thing with SQL: Simply connect to the postgres database (or any other database) and run

CREATE DATABASE dbname
Laurenz Albe
  • 209,280
  • 17
  • 206
  • 263
  • As far as i know: one can only connect to an existing database with Postgres, when the sql 'create database' is already done – Jannis Jan 17 '20 at 10:24
  • Right, you have to connect to a different, already existing, database. Typically `postgres`, like I wrote in my answer. – Laurenz Albe Jan 17 '20 at 11:10
  • I would require the db admin to leave the default database undeleted, if i am doing this, and the script would fail if the postgres default db would be deleted or the user has no rights for the default db: => this is a dirty way – Jannis Jan 17 '20 at 11:25
  • What you don't realize is that `createdb` does the same thing under the hood: it connects to `postgres`, if that doesn't exist, to `template1`, and runs `CREATE DATABASE`. So if a SQL is more convenient for you than a shell script, you might as well do that instead. – Laurenz Albe Jan 17 '20 at 12:36