On Fri, Jun 5, 2026 at 10:08 PM Tom Lane <[email protected]> wrote:
>
> Heikki Linnakangas <[email protected]> writes:
> > On 5 June 2026 10:48:00 EEST, Chao Li <[email protected]> wrote:
> >> evantest=# create domain d_div as int check (1 / (value - 1) > 0);
> >> CREATE DOMAIN
> >> evantest=# create table t (a int);
> >> CREATE TABLE
> >> evantest=# alter table t add column b d_div default 1;
> >> ERROR: division by zero
>
> > It seems totally reasonable to get an error in that case. '1' is not a
> > valid value for the datatype, whether or not there are any rows in the
> > table.
>
> I think there's reason for concern here, which is that we do not throw
> an error for the apparently equivalent case
>
> regression=# create table t2 (a int, b d_div default 1);
> CREATE TABLE
>
> This will give you an error at INSERT, but not CREATE. So this
> is inconsistent, as well as different from the pre-v19 behavior.
>
> Concretely, I'm pretty sure it is a hazard for pg_dump, which thinks
> it can freely transform bits of CREATE operations into ALTERs.
> I didn't try to make an example case, but I suspect it is now possible
> to create a database that will fail dump/restore because of this
> inconsistency.
Per the docs [1], we have two relevant forms:
ALTER [ COLUMN ] column_name SET DEFAULT expression
ADD [ COLUMN ] [ IF NOT EXISTS ] column_name data_type ... [ DEFAULT
default_expr ]
ATExecColumnDefault -> AddRelationNewConstraints does NOT evaluate the
default expression.
So ALTER COLUMN SET DEFAULT will never error out on a bad expression
because it is never evaluated at DDL time.
ALTER TABLE ADD COLUMN with a DEFAULT: pg_dump.c will never emit such a command.
You can verify this by searching for the keyword "add" in
src/bin/pg_dump/pg_dump.c, and looking at each occurrence one by one.
Looking at dumpTableSchema() confirms the same: we do not produce
command: ALTER TABLE ADD COLUMN.
See dumpTableSchema below comments related FOR LOOP part also
/*
* Dump additional per-column properties that we can't handle in the
* main CREATE TABLE command.
*/
[1] https://www.postgresql.org/docs/current/sql-altertable.html
--------------------------------------------
create or replace function dummy() returns numeric AS $$
BEGIN
RETURN 1/0;
END$$ immutable LANGUAGE plpgsql;
create table t1(a numeric default dummy());
alter table t1 add column b numeric default dummy();
ERROR: division by zero
CONTEXT: PL/pgSQL expression "1/0"
PL/pgSQL function dummy() line 3 at RETURN
As you can see, if pg_dump somehow converted the CREATE default expression into
an ALTER TABLE ADD COLUMN DEFAULT, we would already be facing this issue.
Am I missing something?
--
jian
https://www.enterprisedb.com/