10

Is there a command for connecting to a database within an SQL file?

I want to create a database and then immediately begin populating it with tables and data. All contained within a single .sql file. I'm not aware of anything that replaces the \c shell command?

Example SQL file:

CREATE DATABASE mydb;
CREATE USER myusername WITH PASSWORD 'mypassword';
GRANT ALL PRIVILEGES ON DATABASE mydb TO myusername;
CONNECT TO mydb USER myusername; --<-- something like this?

CREATE TABLE administrator (
    id integer NOT NULL,
    admin_name character varying(150),
    password character varying(255),
    active boolean,
    "timestamp" timestamp without time zone,
    email character varying(255)
);


ALTER TABLE administrator OWNER TO myusername;

CONNECT is the closest thing I've found in the documentation, but it's encountering syntax errors. I couldn't find a wrapper that specifies where the tables should go either?

ERROR: syntax error at or near "CONNECT"

7
  • have you tried pg_restore? Commented Dec 7, 2018 at 6:11
  • 1
    \c should work provided you use psql to run that SQL script Commented Dec 7, 2018 at 7:04
  • 2
    \c is a psql command, not a shell command. You can use it inside .sql script Commented Dec 7, 2018 at 7:39
  • 3
    If your client does not have an equivalent to psql's \c, then no, you cannot do that from inside the script. Commented Dec 7, 2018 at 7:41
  • 2
    In PostgreSQL you establish a connection to a specific database when setting up a session. CREATE DATABASE creates a new database, so you need to establish a new connection if you want to send SQL commands to this new database. This is different from MS SQL Server, where you always connect to the server, not a specific database, and can use the "use" command to send commands to any database of your server. There you can even use tables from several databases within a single SELECT statement by fully qualifying them. PostgreSQL regards databases as separate and closed entities. Commented Dec 9, 2018 at 21:12

1 Answer 1

3

Add the below statement instead of connect to db

\c mydb;

The reorder statements of execution should be

CREATE DATABASE mydb;
\c mydb;
CREATE USER myusername WITH PASSWORD 'mypassword';
GRANT ALL PRIVILEGES ON DATABASE mydb TO myusername;

CREATE TABLE administrator (
    id integer NOT NULL,
    admin_name character varying(150),
    password character varying(255),
    active boolean,
    "timestamp" timestamp without time zone,
    email character varying(255)
);


ALTER TABLE administrator OWNER TO myusername;
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.