执行多个查询时,“psql -c”和“psql -f”有什么区别?

4

我正在尝试执行两个SQL命令(创建新模式和表),以一种方式使得如果执行失败可以回滚这两个命令。我连接的数据库是AWS Redshift。

create schema if not exists test_schema;
create table test_schema.test_table as select 1;

最初我尝试使用Python编程方式执行这些命令,使用了psycopg2和pyodbc,但是遇到了以下错误:

ERROR:  schema "test_schema" does not exist

我发现它失败的原因是第一个命令没有被提交,所以我尝试打开自动提交模式,并用"begin/end"块包装语句来修复它,但这并没有帮助。
当我使用psql CLI运行以下命令时,一切都按预期工作(没有"schema does not exist"错误,并且在回滚后,模式和表都消失了):
dev=# begin;
BEGIN
dev=# create schema test_schema;
CREATE SCHEMA
dev=# create table test_schema.test_table as select 1;
SELECT
dev=# rollback;
ROLLBACK

我尝试通过在命令行中运行以下内容来获得相同的结果:

psql -c "begin; create schema test_schema; create table test_schema.test_table as select 1;"

这会导致相同的错误:
ERROR: schema "test_schema" does not exist

然而,当我将上述代码放入文件中并运行相同的命令时,这次使用-f选项,它就可以正常工作:

psql -f create_schema_and_table.sql

我的问题是:

  1. "psql -c"和"psql -f"执行查询有什么区别?

  2. 如何使用Python以编程方式实现相同的结果?

非常感谢!

1个回答

0

我不知道你做错了什么,你的“psql -c”命令完全正常:

ads@diamond:~$ psql -c "begin; create schema test_schema; create table test_schema.test_table as select 1;" postgres
SELECT 1

psql会将整个字符串发送到服务器并在一个事务中执行。您的问题是使用“begin”开始了一个事务,但从未提交。因此,在psql运行结束时,所有更改都将被回滚。下一个psql命令将找不到模式或表。但只要一切都保持在单个psql调用中,同一命令中的后续查询可以看到新创建的对象。

您的查询字符串应该像这样:

begin; create schema test_schema; create table test_schema.test_table as select 1; commit;

或者更简单:

create schema test_schema; create table test_schema.test_table as select 1;

两种方法都可以。


谢谢您的建议,但我仍然收到相同的错误消息。我没有提到我正在连接到Redshift。 - Alla Bongard

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接