PHP: PGSQL driver and AutoCommit?
Asked Answered
E

1

5

I use pg_connect, and pg_query in a project. But I'm really not sure that is pg_connect using AutoCommit mode or not?

It is important question, because I need to write some block under transaction, and if one of the statements would be ignored by the server, the database would be inconsistent...

Also interesting question that do pg_query a commit after execution?

For example:

pg_query('begin; update table1...; update table2...; commit');

is same as

pg_query('begin;');
pg_query('update table1...;');
pg_query('update table2...;');
pg_query('commit');

and is the

pg_query('begin; update table1...; update table2...; commit');

working in AutoCommit mode, so begin and commit is nevertheless?

Thanks for your help: dd

Eloquence answered 14/3, 2012 at 15:5 Comment(0)
P
9

First, there is no AutoCommit mode in PostgreSQL and the pg_* functions of the PHP API do not try to emulate one.

pg_query's doc says

When multiple statements are passed to the function, they are automatically executed as one transaction, unless there are explicit BEGIN/COMMIT commands included in the query string

So it guarantees that pg_query("UPDATE1 ..; UPDATE2...") executes in one transaction and has an all-or-nothing effect on the data.

The sequence

pg_query("BEGIN");
pg_query("UPDATE1...");
pg_query("UPDATE2..");
pg_query("COMMIT");

is equivalent to pg_query("UPDATE1 ..; UPDATE2...") with regard to data integrity (half-finished state cannot happen).

As for the note "unless there are explicit BEGIN/COMMIT...", it is relevant only if these are not at the beginning and end of the entire chain of SQL statements. That is, pg_query("BEGIN; update1; update2; COMMIT;"); is equivalent to pg_query("update1; update2;") but (obviously) not equivalent to pg_query("update1; COMMIT; update2;")

Poltroon answered 14/3, 2012 at 22:57 Comment(3)
What about this, this a new feature? postgresql.org/docs/9.3/static/ecpg-sql-set-autocommit.htmlNoncombatant
@Eddified: no, this is old. ECPG implicitly opens transactions and it's called "autcommit off". See Managing TransactionsImpacted
@DanielVérité Please check #70542665Anisette

© 2022 - 2024 — McMap. All rights reserved.