简体   繁体   中英

PSQL: current transaction is aborted, commands ignored until end of transaction block

I want to write script for create database with tables in PostgreSQL. I created deploy_db.bat :

@echo off
"C:\Program Files\PostgreSQL\9.4\bin\psql.exe" -h localhost -p 5433 -U postgres -d postgres -f run_main.sql
pause

my run_main.sql:

BEGIN;
\i create_db.sql
\i tableA.sql
COMMIT;

create_db.sql:

CREATE DATABASE test;

DROP SCHEMA IF EXISTS test CASCADE;

CREATE SCHEMA test
  AUTHORIZATION postgres;

tableA.sql:

CREATE TABLE test.tableA(
  id serial PRIMARY KEY,
  name text,
  age INTEGER
);

So, I run deploy_db.bat and see:

BEGIN
psql:create_db.sql:1: ERROR: CREATE DATABASE cannot run inside a transaction block
psql:create_db.sql:3: ERROR: current transaction is aborted, commands ignored until end of transaction block
ROLLBACK

But, Why? How can resolved it?

You issued BEGIN which started a transaction, then CREATE DATABASE which produced the error message because you ran it inside the transaction.

You could just move the CREATE DATABASE statement before the BEGIN , that would get rid of the error message.

But reading your SQL script I suspect that you want to create the new schema and table in the newly created database, which is not what will happen with your script. Rather, the schema and the table will be created in the database postgres .

To change that, your script should look like this:

CREATE DATABASE test;

-- connect to that database
\connect test

-- now create your schema and your table
CREATE SCHEMA ...
CREATE TABLE ...

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