[PATCH] Add pg_get_database_ddl() function to reconstruct CREATE DATABASE statement
[PATCH] Add pg_get_database_ddl() function to reconstruct CREATE DATABASE statement
I’m submitting a patch as part of the broader Retail DDL Functions project described by Andrew Dunstan https://www.postgresql.org/message-id/945db7c5-be75-45bf-b55b-cb1e56f2e3e9%40dunslane.net
This patch adds a new system function pg_get_database_ddl(database_name/database_oid, pretty), which reconstructs the CREATE DATABASE statement for a given database name or database oid. When the pretty flag is set to true, the function returns a neatly formatted, multi-line DDL statement instead of a single-line statement.
Usage examples:
1) SELECT pg_get_database_ddl('test_get_database_ddl_builtin'); -- non-pretty formatted DDL
pg_get_database_ddl
-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
CREATE DATABASE test_get_database_ddl_builtin WITH OWNER = regress_ddl_database ENCODING = "UTF8" LC_COLLATE = "C" LC_CTYPE = "C" BUILTIN_LOCALE = "C.UTF-8" COLLATION_VERSION = "1" LOCALE_PROVIDER = 'builtin' TABLESPACE = pg_default ALLOW_CONNECTIONS = true CONNECTION LIMIT = -1;
2) SELECT pg_get_database_ddl('test_get_database_ddl_builtin', true); -- pretty formatted DDL
CREATE DATABASE test_get_database_ddl_builtin
WITH
OWNER = regress_ddl_database
ENCODING = "UTF8"
LC_COLLATE = "C"
LC_CTYPE = "C"
BUILTIN_LOCALE = "C.UTF-8"
COLLATION_VERSION = "1"
LOCALE_PROVIDER = 'builtin'
TABLESPACE = pg_default
ALLOW_CONNECTIONS = true
CONNECTION LIMIT = -1;
3) SELECT pg_get_database_ddl(16835); -- non-pretty formatted DDL for OID
4) SELECT pg_get_database_ddl(16835, true); -- pretty formatted DDL for OID
The patch includes documentation, in-code comments, and regression tests, all of which pass successfully.
Note: To run the regression tests, particularly the pg_upgrade tests successfully, I had to add a helper function, ddl_filter (in database.sql), which removes locale and collation-related information from the pg_get_database_ddl output.
Regards,
Akshay Joshi
EDB (EnterpriseDB)
Re: [PATCH] Add pg_get_database_ddl() function to reconstruct CREATE DATABASE statement
On 11/12/25 8:04 PM, Akshay Joshi wrote:
> Hi Hackers,
>
> I’m submitting a patch as part of the broader Retail DDL Functions
> project described by Andrew Dunstan https://www.postgresql.org/message-
> id/945db7c5-be75-45bf-b55b-cb1e56f2e3e9%40dunslane.net www.postgresql.org/message-id/945db7c5-be75-45bf-b55b-
> cb1e56f2e3e9%40dunslane.net>
>
> This patch adds a new system function pg_get_database_ddl(database_name/
> database_oid, pretty), which reconstructs the CREATE DATABASE statement
> for a given database name or database oid. When the pretty flag is set
> to true, the function returns a neatly formatted, multi-line DDL
> statement instead of a single-line statement.
>
> *Usage examples:*
>
> 1) SELECT pg_get_database_ddl('test_get_database_ddl_builtin'); --
> *non-pretty formatted DDL*
>
>
> pg_get_database_ddl
> -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
> CREATE DATABASE test_get_database_ddl_builtin WITH OWNER =
> regress_ddl_database ENCODING = "UTF8" LC_COLLATE = "C" LC_CTYPE = "C"
> BUILTIN_LOCALE = "C.UTF-8" COLLATION_VERSION = "1" LOCALE_PROVIDER =
> 'builtin' TABLESPACE = pg_default ALLOW_CONNECTIONS = true CONNECTION
> LIMIT = -1;
>
>
> 2) SELECT pg_get_database_ddl('test_get_database_ddl_builtin', true);
> -- *pretty formatted DDL*
>
> CREATE DATABASE test_get_database_ddl_builtin
> WITH
> OWNER = regress_ddl_database
> ENCODING = "UTF8"
> LC_COLLATE = "C"
> LC_CTYPE = "C"
> BUILTIN_LOCALE = "C.UTF-8"
> COLLATION_VERSION = "1"
> LOCALE_PROVIDER = 'builtin'
> TABLESPACE = pg_default
> ALLOW_CONNECTIONS = true
> CONNECTION LIMIT = -1;
>
> 3) SELECT pg_get_database_ddl(16835); -- *non-pretty formatted DDL
> for OID*
> 4) SELECT pg_get_database_ddl(16835, true); -- *pretty formatted DDL
> for OID*
>
> The patch includes documentation, in-code comments, and regression
> tests, all of which pass successfully.
> *
> **Note:* To run the regression tests, particularly the pg_upgrade tests
> successfully, I had to add a helper function, ddl_filter (in
> database.sql), which removes locale and collation-related information
> from the pg_get_database_ddl output.
>
I think we should check the connection permissions here. Otherwise:
postgres=> SELECT pg_database_size('testdb');
ERROR: permission denied for database testdb
postgres=> SELECT pg_get_database_ddl('testdb');
pg_get_database_ddl
-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
CREATE DATABASE testdb WITH OWNER = quanzl ENCODING = "UTF8"
LC_COLLATE = "zh_CN.UTF-8" LC_CTYPE = "zh_CN.UTF-8" LOCALE_PROVIDER =
'libc' TABLESPACE = pg_default ALLOW_CONNECTIONS = true CONNECTION LIMIT
= -1;
(1 row)
Users without connection permissions should not generate DDL.
Regards,
Quan Zongliang
> -----
> Regards,
> Akshay Joshi
> EDB (EnterpriseDB)
>
>
>
Re: [PATCH] Add pg_get_database_ddl() function to reconstruct CREATE DATABASE statement
On 11/13/25 12:17 PM, Quan Zongliang wrote:
>
>
> On 11/12/25 8:04 PM, Akshay Joshi wrote:
>> Hi Hackers,
>>
>> I’m submitting a patch as part of the broader Retail DDL Functions
>> project described by Andrew Dunstan https://www.postgresql.org/
>> message- id/945db7c5-be75-45bf-b55b-cb1e56f2e3e9%40dunslane.net
>> > cb1e56f2e3e9%40dunslane.net>
>>
>> This patch adds a new system function
>> pg_get_database_ddl(database_name/ database_oid, pretty), which
>> reconstructs the CREATE DATABASE statement for a given database name
>> or database oid. When the pretty flag is set to true, the function
>> returns a neatly formatted, multi-line DDL statement instead of a
>> single-line statement.
>>
>> *Usage examples:*
>>
>> 1) SELECT pg_get_database_ddl('test_get_database_ddl_builtin'); --
>> *non-pretty formatted DDL*
>> pg_get_database_ddl
>> -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
>> CREATE DATABASE test_get_database_ddl_builtin WITH OWNER =
>> regress_ddl_database ENCODING = "UTF8" LC_COLLATE = "C" LC_CTYPE = "C"
>> BUILTIN_LOCALE = "C.UTF-8" COLLATION_VERSION = "1" LOCALE_PROVIDER =
>> 'builtin' TABLESPACE = pg_default ALLOW_CONNECTIONS = true CONNECTION
>> LIMIT = -1;
>>
>>
>> 2) SELECT pg_get_database_ddl('test_get_database_ddl_builtin', true);
>> -- *pretty formatted DDL*
>>
>> CREATE DATABASE test_get_database_ddl_builtin
>> WITH
>> OWNER = regress_ddl_database
>> ENCODING = "UTF8"
>> LC_COLLATE = "C"
>> LC_CTYPE = "C"
>> BUILTIN_LOCALE = "C.UTF-8"
>> COLLATION_VERSION = "1"
>> LOCALE_PROVIDER = 'builtin'
>> TABLESPACE = pg_default
>> ALLOW_CONNECTIONS = true
>> CONNECTION LIMIT = -1;
>>
>> 3) SELECT pg_get_database_ddl(16835); -- *non-pretty formatted
>> DDL for OID*
>> 4) SELECT pg_get_database_ddl(16835, true); -- *pretty formatted DDL
>> for OID*
>>
>> The patch includes documentation, in-code comments, and regression
>> tests, all of which pass successfully.
>> *
>> **Note:* To run the regression tests, particularly the pg_upgrade
>> tests successfully, I had to add a helper function, ddl_filter (in
>> database.sql), which removes locale and collation-related information
>> from the pg_get_database_ddl output.
>>
> I think we should check the connection permissions here. Otherwise:
>
> postgres=> SELECT pg_database_size('testdb');
> ERROR: permission denied for database testdb
> postgres=> SELECT pg_get_database_ddl('testdb');
>
> pg_get_database_ddl
> -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
> CREATE DATABASE testdb WITH OWNER = quanzl ENCODING = "UTF8"
> LC_COLLATE = "zh_CN.UTF-8" LC_CTYPE = "zh_CN.UTF-8" LOCALE_PROVIDER =
> 'libc' TABLESPACE = pg_default ALLOW_CONNECTIONS = true CONNECTION LIMIT
> = -1;
> (1 row)
>
> Users without connection permissions should not generate DDL.
>
The "dbOwner" is defined as a null pointer.
char *dbOwner = NULL;
Later, there might be a risk of it not being assigned a value.
if (OidIsValid(dbForm->datdba))
dbOwner = GetUserNameFromId(dbForm->datdba, false);
Although there is no problem in normal circumstances here. Many parts of
the existing code have not been checked either. Since this possibility
exists, it should be checked before using it. Just like the function
roles_is_member_of (acl.c).
if (dbOwner)
get_formatted_string(&buf, prettyFlags, 1, "OWNER = %s",
quote_identifier(dbOwner));
> Regards,
> Quan Zongliang
>
>> -----
>> Regards,
>> Akshay Joshi
>> EDB (EnterpriseDB)
>>
>>
>>
>
>
Re: [PATCH] Add pg_get_database_ddl() function to reconstruct CREATE DATABASE statement
On 11/12/25 8:04 PM, Akshay Joshi wrote:
> Hi Hackers,
>
> I’m submitting a patch as part of the broader Retail DDL Functions
> project described by Andrew Dunstan https://www.postgresql.org/message-
> id/945db7c5-be75-45bf-b55b-cb1e56f2e3e9%40dunslane.net <https://
> www.postgresql.org/message-id/945db7c5-be75-45bf-b55b-
> cb1e56f2e3e9%40dunslane.net>
>
> This patch adds a new system function pg_get_database_ddl(database_name/
> database_oid, pretty), which reconstructs the CREATE DATABASE statement
> for a given database name or database oid. When the pretty flag is set
> to true, the function returns a neatly formatted, multi-line DDL
> statement instead of a single-line statement.
>
> *Usage examples:*
>
> 1) SELECT pg_get_database_ddl('test_get_database_ddl_builtin'); --
> *non-pretty formatted DDL*
>
>
> pg_get_database_ddl
> -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
> CREATE DATABASE test_get_database_ddl_builtin WITH OWNER =
> regress_ddl_database ENCODING = "UTF8" LC_COLLATE = "C" LC_CTYPE = "C"
> BUILTIN_LOCALE = "C.UTF-8" COLLATION_VERSION = "1" LOCALE_PROVIDER =
> 'builtin' TABLESPACE = pg_default ALLOW_CONNECTIONS = true CONNECTION
> LIMIT = -1;
>
>
> 2) SELECT pg_get_database_ddl('test_get_database_ddl_builtin', true);
> -- *pretty formatted DDL*
>
> CREATE DATABASE test_get_database_ddl_builtin
> WITH
> OWNER = regress_ddl_database
> ENCODING = "UTF8"
> LC_COLLATE = "C"
> LC_CTYPE = "C"
> BUILTIN_LOCALE = "C.UTF-8"
> COLLATION_VERSION = "1"
> LOCALE_PROVIDER = 'builtin'
> TABLESPACE = pg_default
> ALLOW_CONNECTIONS = true
> CONNECTION LIMIT = -1;
>
> 3) SELECT pg_get_database_ddl(16835); -- *non-pretty formatted DDL
> for OID*
> 4) SELECT pg_get_database_ddl(16835, true); -- *pretty formatted DDL
> for OID*
>
> The patch includes documentation, in-code comments, and regression
> tests, all of which pass successfully.
> *
> **Note:* To run the regression tests, particularly the pg_upgrade tests
> successfully, I had to add a helper function, ddl_filter (in
> database.sql), which removes locale and collation-related information
> from the pg_get_database_ddl output.
>
I think we should check the connection permissions here. Otherwise:
postgres=> SELECT pg_database_size('testdb');
ERROR: permission denied for database testdb
postgres=> SELECT pg_get_database_ddl('testdb');
pg_get_database_ddl
-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
CREATE DATABASE testdb WITH OWNER = quanzl ENCODING = "UTF8"
LC_COLLATE = "zh_CN.UTF-8" LC_CTYPE = "zh_CN.UTF-8" LOCALE_PROVIDER =
'libc' TABLESPACE = pg_default ALLOW_CONNECTIONS = true CONNECTION LIMIT
= -1;
(1 row)
Users without connection permissions should not generate DDL.
pg_database_size() requires CONNECT or pg_read_all_stats privileges since it accesses on-disk storage details of a database, which are treated as sensitive information. In contrast, other system functions might not need such privileges because they operate within the connected database or reveal less sensitive data.
In my view, the pg_get_database_ddl() function should not require CONNECT or pg_read_all_stats privileges for consistency and security.
Regards,
Quan Zongliang
> -----
> Regards,
> Akshay Joshi
> EDB (EnterpriseDB)
>
>
>
Re: [PATCH] Add pg_get_database_ddl() function to reconstruct CREATE DATABASE statement
On 11/13/25 12:17 PM, Quan Zongliang wrote:
>
>
> On 11/12/25 8:04 PM, Akshay Joshi wrote:
>> Hi Hackers,
>>
>> I’m submitting a patch as part of the broader Retail DDL Functions
>> project described by Andrew Dunstan https://www.postgresql.org/
>> message- id/945db7c5-be75-45bf-b55b-cb1e56f2e3e9%40dunslane.net
>> <https:// www.postgresql.org/message-id/945db7c5-be75-45bf-b55b-
>> cb1e56f2e3e9%40dunslane.net>
>>
>> This patch adds a new system function
>> pg_get_database_ddl(database_name/ database_oid, pretty), which
>> reconstructs the CREATE DATABASE statement for a given database name
>> or database oid. When the pretty flag is set to true, the function
>> returns a neatly formatted, multi-line DDL statement instead of a
>> single-line statement.
>>
>> *Usage examples:*
>>
>> 1) SELECT pg_get_database_ddl('test_get_database_ddl_builtin'); --
>> *non-pretty formatted DDL*
>> pg_get_database_ddl
>> -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
>> CREATE DATABASE test_get_database_ddl_builtin WITH OWNER =
>> regress_ddl_database ENCODING = "UTF8" LC_COLLATE = "C" LC_CTYPE = "C"
>> BUILTIN_LOCALE = "C.UTF-8" COLLATION_VERSION = "1" LOCALE_PROVIDER =
>> 'builtin' TABLESPACE = pg_default ALLOW_CONNECTIONS = true CONNECTION
>> LIMIT = -1;
>>
>>
>> 2) SELECT pg_get_database_ddl('test_get_database_ddl_builtin', true);
>> -- *pretty formatted DDL*
>>
>> CREATE DATABASE test_get_database_ddl_builtin
>> WITH
>> OWNER = regress_ddl_database
>> ENCODING = "UTF8"
>> LC_COLLATE = "C"
>> LC_CTYPE = "C"
>> BUILTIN_LOCALE = "C.UTF-8"
>> COLLATION_VERSION = "1"
>> LOCALE_PROVIDER = 'builtin'
>> TABLESPACE = pg_default
>> ALLOW_CONNECTIONS = true
>> CONNECTION LIMIT = -1;
>>
>> 3) SELECT pg_get_database_ddl(16835); -- *non-pretty formatted
>> DDL for OID*
>> 4) SELECT pg_get_database_ddl(16835, true); -- *pretty formatted DDL
>> for OID*
>>
>> The patch includes documentation, in-code comments, and regression
>> tests, all of which pass successfully.
>> *
>> **Note:* To run the regression tests, particularly the pg_upgrade
>> tests successfully, I had to add a helper function, ddl_filter (in
>> database.sql), which removes locale and collation-related information
>> from the pg_get_database_ddl output.
>>
> I think we should check the connection permissions here. Otherwise:
>
> postgres=> SELECT pg_database_size('testdb');
> ERROR: permission denied for database testdb
> postgres=> SELECT pg_get_database_ddl('testdb');
>
> pg_get_database_ddl
> -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
> CREATE DATABASE testdb WITH OWNER = quanzl ENCODING = "UTF8"
> LC_COLLATE = "zh_CN.UTF-8" LC_CTYPE = "zh_CN.UTF-8" LOCALE_PROVIDER =
> 'libc' TABLESPACE = pg_default ALLOW_CONNECTIONS = true CONNECTION LIMIT
> = -1;
> (1 row)
>
> Users without connection permissions should not generate DDL.
>
The "dbOwner" is defined as a null pointer.
char *dbOwner = NULL;
Later, there might be a risk of it not being assigned a value.
if (OidIsValid(dbForm->datdba))
dbOwner = GetUserNameFromId(dbForm->datdba, false);
Although there is no problem in normal circumstances here. Many parts of
the existing code have not been checked either. Since this possibility
exists, it should be checked before using it. Just like the function
roles_is_member_of (acl.c).
if (dbOwner)
get_formatted_string(&buf, prettyFlags, 1, "OWNER = %s",
quote_identifier(dbOwner));
> Regards,
> Quan Zongliang
>
>> -----
>> Regards,
>> Akshay Joshi
>> EDB (EnterpriseDB)
>>
>>
>>
>
>
Re: [PATCH] Add pg_get_database_ddl() function to reconstruct CREATE DATABASE statement
On 11/13/25 4:30 PM, Akshay Joshi wrote:
>
> On Thu, Nov 13, 2025 at 9:47 AM Quan Zongliang > wrote:
>
>
>
> On 11/12/25 8:04 PM, Akshay Joshi wrote:
> > Hi Hackers,
> >
> > I’m submitting a patch as part of the broader Retail DDL Functions
> > project described by Andrew Dunstan https://www.postgresql.org/
> message-
> > id/945db7c5-be75-45bf-b55b-cb1e56f2e3e9%40dunslane.net
> > www.postgresql.org/message-id/945db7c5-be75-45bf-b55b- www.postgresql.org/message-id/945db7c5-be75-45bf-b55b->
> > cb1e56f2e3e9%40dunslane.net >
> >
> > This patch adds a new system function
> pg_get_database_ddl(database_name/
> > database_oid, pretty), which reconstructs the CREATE DATABASE
> statement
> > for a given database name or database oid. When the pretty flag
> is set
> > to true, the function returns a neatly formatted, multi-line DDL
> > statement instead of a single-line statement.
> >
> > *Usage examples:*
> >
> > 1) SELECT pg_get_database_ddl('test_get_database_ddl_builtin'); --
> > *non-pretty formatted DDL*
> >
> >
> > pg_get_database_ddl
> >
> -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
> > CREATE DATABASE test_get_database_ddl_builtin WITH OWNER =
> > regress_ddl_database ENCODING = "UTF8" LC_COLLATE = "C" LC_CTYPE
> = "C"
> > BUILTIN_LOCALE = "C.UTF-8" COLLATION_VERSION = "1" LOCALE_PROVIDER =
> > 'builtin' TABLESPACE = pg_default ALLOW_CONNECTIONS = true
> CONNECTION
> > LIMIT = -1;
> >
> >
> > 2) SELECT pg_get_database_ddl('test_get_database_ddl_builtin',
> true);
> > -- *pretty formatted DDL*
> >
> > CREATE DATABASE test_get_database_ddl_builtin
> > WITH
> > OWNER = regress_ddl_database
> > ENCODING = "UTF8"
> > LC_COLLATE = "C"
> > LC_CTYPE = "C"
> > BUILTIN_LOCALE = "C.UTF-8"
> > COLLATION_VERSION = "1"
> > LOCALE_PROVIDER = 'builtin'
> > TABLESPACE = pg_default
> > ALLOW_CONNECTIONS = true
> > CONNECTION LIMIT = -1;
> >
> > 3) SELECT pg_get_database_ddl(16835); -- *non-pretty
> formatted DDL
> > for OID*
> > 4) SELECT pg_get_database_ddl(16835, true); -- *pretty formatted
> DDL
> > for OID*
> >
> > The patch includes documentation, in-code comments, and regression
> > tests, all of which pass successfully.
> > *
> > **Note:* To run the regression tests, particularly the pg_upgrade
> tests
> > successfully, I had to add a helper function, ddl_filter (in
> > database.sql), which removes locale and collation-related
> information
> > from the pg_get_database_ddl output.
> >
> I think we should check the connection permissions here. Otherwise:
>
> postgres=> SELECT pg_database_size('testdb');
> ERROR: permission denied for database testdb
> postgres=> SELECT pg_get_database_ddl('testdb');
>
> pg_get_database_ddl
> -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
> CREATE DATABASE testdb WITH OWNER = quanzl ENCODING = "UTF8"
> LC_COLLATE = "zh_CN.UTF-8" LC_CTYPE = "zh_CN.UTF-8" LOCALE_PROVIDER =
> 'libc' TABLESPACE = pg_default ALLOW_CONNECTIONS = true CONNECTION
> LIMIT
> = -1;
> (1 row)
>
> Users without connection permissions should not generate DDL.
>
>
> pg_database_size() requires CONNECT or pg_read_all_stats privileges
> since it accesses on-disk storage details of a database, which are
> treated as sensitive information. In contrast, other system functions
> might not need such privileges because they operate within the connected
> database or reveal less sensitive data.
>
> In my view, the pg_get_database_ddl() function *should not* require
> CONNECT or pg_read_all_stats privileges for consistency and security.
>
Agree.
But what about the following scenario? If there is no permission to
access pg_database. Shouldn't the DDL be returned?
postgres=> SELECT * FROM pg_database;
ERROR: permission denied for table pg_database
postgres=> SELECT pg_get_database_ddl('testdb');
>
> Regards,
> Quan Zongliang
>
> > -----
> > Regards,
> > Akshay Joshi
> > EDB (EnterpriseDB)
> >
> >
> >
>
Re: [PATCH] Add pg_get_database_ddl() function to reconstruct CREATE DATABASE statement
On 11/13/25 8:28 PM, Álvaro Herrera wrote:
>> But what about the following scenario? If there is no permission to access
>> pg_database. Shouldn't the DDL be returned?
>>
>> postgres=> SELECT * FROM pg_database;
>> ERROR: permission denied for table pg_database
>> postgres=> SELECT pg_get_database_ddl('testdb');
>
> Hmm, what scenario is this? Did you purposefully REVOKE the SELECT
> privileges from pg_database somehow?
>
Yes. I revoked the access permission using the REVOKE command.
The pg_get_xxx_ddl function is actually revealing system information to
the users. This is equivalent to accessing the corresponding system
table. So I think we should consider this issue.
The access permission to the system tables has been revoked. This user
is unable to directly view the contents of the system tables from the
client side via SQL. However, it is still possible to obtain the object
definitions (which was previously inaccessible) through pg_get_xxx_ddl.
This is more like a security flaw.
A more specific example. Originally, it was impossible to obtain the
definition of "testdb" by accessing pg_database:
postgres=> SELECT * FROM pg_database WHERE datname='testdb';
ERROR: permission denied for table pg_database
And after having this function. However, users can view these in another
format.
postgres=> SELECT pg_get_database_ddl('testdb');
------------- ...
CREATE DATABASE testdb WITH OWNER = quanzl ENCODING = "UTF8" ...
Perhaps it's just that I'm overthinking things. What do you think about it?
Re: [PATCH] Add pg_get_database_ddl() function to reconstruct CREATE DATABASE statement
On Thu, Nov 13, 2025 at 02:02:30PM +0530, Akshay Joshi wrote:
> On Thu, Nov 13, 2025 at 10:18 AM Quan Zongliang
> wrote:
>
> >
> >
> > On 11/13/25 12:17 PM, Quan Zongliang wrote:
> > >
> > >
> > > On 11/12/25 8:04 PM, Akshay Joshi wrote:
> > >> Hi Hackers,
> > >>
> > >> I’m submitting a patch as part of the broader Retail DDL Functions
> > >> project described by Andrew Dunstan https://www.postgresql.org/
> > >> message- id/945db7c5-be75-45bf-b55b-cb1e56f2e3e9%40dunslane.net
> > >> > >> cb1e56f2e3e9%40dunslane.net>
> > >>
> > >> This patch adds a new system function
> > >> pg_get_database_ddl(database_name/ database_oid, pretty), which
> > >> reconstructs the CREATE DATABASE statement for a given database name
> > >> or database oid. When the pretty flag is set to true, the function
> > >> returns a neatly formatted, multi-line DDL statement instead of a
> > >> single-line statement.
> > >>
> > >> *Usage examples:*
> > >>
> > >> 1) SELECT pg_get_database_ddl('test_get_database_ddl_builtin'); --
> > >> *non-pretty formatted DDL*
> > >> pg_get_database_ddl
> > >>
> > -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
> > >> CREATE DATABASE test_get_database_ddl_builtin WITH OWNER =
> > >> regress_ddl_database ENCODING = "UTF8" LC_COLLATE = "C" LC_CTYPE = "C"
> > >> BUILTIN_LOCALE = "C.UTF-8" COLLATION_VERSION = "1" LOCALE_PROVIDER =
> > >> 'builtin' TABLESPACE = pg_default ALLOW_CONNECTIONS = true CONNECTION
> > >> LIMIT = -1;
> > >>
> > >>
> > >> 2) SELECT pg_get_database_ddl('test_get_database_ddl_builtin', true);
> > >> -- *pretty formatted DDL*
> > >>
> > >> CREATE DATABASE test_get_database_ddl_builtin
> > >> WITH
> > >> OWNER = regress_ddl_database
> > >> ENCODING = "UTF8"
> > >> LC_COLLATE = "C"
> > >> LC_CTYPE = "C"
> > >> BUILTIN_LOCALE = "C.UTF-8"
> > >> COLLATION_VERSION = "1"
> > >> LOCALE_PROVIDER = 'builtin'
> > >> TABLESPACE = pg_default
> > >> ALLOW_CONNECTIONS = true
> > >> CONNECTION LIMIT = -1;
> > >>
> > >> 3) SELECT pg_get_database_ddl(16835); -- *non-pretty formatted
> > >> DDL for OID*
> > >> 4) SELECT pg_get_database_ddl(16835, true); -- *pretty formatted DDL
> > >> for OID*
> > >>
> > >> The patch includes documentation, in-code comments, and regression
> > >> tests, all of which pass successfully.
> > >> *
> > >> **Note:* To run the regression tests, particularly the pg_upgrade
> > >> tests successfully, I had to add a helper function, ddl_filter (in
> > >> database.sql), which removes locale and collation-related information
> > >> from the pg_get_database_ddl output.
> > >>
> > > I think we should check the connection permissions here. Otherwise:
> > >
> > > postgres=> SELECT pg_database_size('testdb');
> > > ERROR: permission denied for database testdb
> > > postgres=> SELECT pg_get_database_ddl('testdb');
> > >
> > > pg_get_database_ddl
> > >
> > -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
> > > CREATE DATABASE testdb WITH OWNER = quanzl ENCODING = "UTF8"
> > > LC_COLLATE = "zh_CN.UTF-8" LC_CTYPE = "zh_CN.UTF-8" LOCALE_PROVIDER =
> > > 'libc' TABLESPACE = pg_default ALLOW_CONNECTIONS = true CONNECTION LIMIT
> > > = -1;
> > > (1 row)
> > >
> > > Users without connection permissions should not generate DDL.
> > >
> >
> > The "dbOwner" is defined as a null pointer.
> > char *dbOwner = NULL;
> >
> > Later, there might be a risk of it not being assigned a value.
> > if (OidIsValid(dbForm->datdba))
> > dbOwner = GetUserNameFromId(dbForm->datdba, false);
> >
> > Although there is no problem in normal circumstances here. Many parts of
> > the existing code have not been checked either. Since this possibility
> > exists, it should be checked before using it. Just like the function
> > roles_is_member_of (acl.c).
> >
> > if (dbOwner)
> > get_formatted_string(&buf, prettyFlags, 1, "OWNER = %s",
> > quote_identifier(dbOwner));
> >
>
> Fixed the given review comment. I've attached the v2 patch ready for
> review.
>
Thanks for updating the patch, some comments on v2.
1.
Should we merge the functions pg_get_database_ddl(oid, [boolean]) and
pg_get_database_ddl(name, [boolean]) in documentation, following the
precedent set by pg_database_size in func-admin.sgml.
2.
+ * noOfTabChars - indent with specified no of tabs.
How about using 'indent with specified number of tab characters'?
And for variable noOfTabChars, I'd like use nTabs or nTabChars.
3.
+/*
+ * pg_get_database_ddl_oid
+ *
+ * Generate a CREATE DATABASE statement for the specified database oid.
+ *
+ * dbName - Name of the database for which to generate the DDL.
+ * pretty - If true, format the DDL with indentation and line breaks.
+ */
A copy-paste error resulted in an incorrect comments (dbName).
--
Best regards,
Japin Li
ChengDu WenWu Information Technology Co., LTD.
Re: [PATCH] Add pg_get_database_ddl() function to reconstruct CREATE DATABASE statement
Hi Akshay, I quick went through the patch, I do see some problems, but I need some time to wrap up, so I will do a deep review next week. In the meantime, I want to first ask that why there is no privilege check? I think that’s a serious issue. > On Nov 13, 2025, at 16:32, Akshay Joshi wrote: > > > Best regards, -- Chao Li (Evan) HighGo Software Co., Ltd. https://www.highgo.com/
Re: [PATCH] Add pg_get_database_ddl() function to reconstruct CREATE DATABASE statement
On 2025-Nov-13, Quan Zongliang wrote:
> A more specific example. Originally, it was impossible to obtain the
> definition of "testdb" by accessing pg_database:
>
> postgres=> SELECT * FROM pg_database WHERE datname='testdb';
> ERROR: permission denied for table pg_database
Hmm. So I was thinking that running things in this mode (where catalog
access is restricted) has never been supported. But you're right that
we would be opening a hole that we don't have today, because if the
admin closes down permissions on pg_database, then this new function
would be a way to obtain information that the user can't currently
obtain.
My further point was to be that you still need to obtain a list of
database names or OIDs in order to do anything of value. But it turns
out that this is extremely easy and quick to do, with something like
SELECT i, pg_describe_object('pg_database'::regclass, i, 0)
FROM generate_series(1, 1_000_000) i
WHERE pg_describe_object('pg_database'::regclass, i, 0) IS NOT NULL;
... and with this function, the user could again obtain everything about
the database even when they can't read the catalog directly.
Maybe checking privs for the database being dumped is enough protection
against this -- the equivalent of has_database_privilege( ..., 'CONNECT')
I suppose.
--
Álvaro Herrera PostgreSQL Developer — https://www.EnterpriseDB.com/
"¿Qué importan los años? Lo que realmente importa es comprobar que
a fin de cuentas la mejor edad de la vida es estar vivo" (Mafalda)
Re: [PATCH] Add pg_get_database_ddl() function to reconstruct CREATE DATABASE statement
On Thu, Nov 13, 2025 at 02:02:30PM +0530, Akshay Joshi wrote:
> On Thu, Nov 13, 2025 at 10:18 AM Quan Zongliang <quanzongliang@yeah.net>
> wrote:
>
> >
> >
> > On 11/13/25 12:17 PM, Quan Zongliang wrote:
> > >
> > >
> > > On 11/12/25 8:04 PM, Akshay Joshi wrote:
> > >> Hi Hackers,
> > >>
> > >> I’m submitting a patch as part of the broader Retail DDL Functions
> > >> project described by Andrew Dunstan https://www.postgresql.org/
> > >> message- id/945db7c5-be75-45bf-b55b-cb1e56f2e3e9%40dunslane.net
> > >> <https:// www.postgresql.org/message-id/945db7c5-be75-45bf-b55b-
> > >> cb1e56f2e3e9%40dunslane.net>
> > >>
> > >> This patch adds a new system function
> > >> pg_get_database_ddl(database_name/ database_oid, pretty), which
> > >> reconstructs the CREATE DATABASE statement for a given database name
> > >> or database oid. When the pretty flag is set to true, the function
> > >> returns a neatly formatted, multi-line DDL statement instead of a
> > >> single-line statement.
> > >>
> > >> *Usage examples:*
> > >>
> > >> 1) SELECT pg_get_database_ddl('test_get_database_ddl_builtin'); --
> > >> *non-pretty formatted DDL*
> > >> pg_get_database_ddl
> > >>
> > -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
> > >> CREATE DATABASE test_get_database_ddl_builtin WITH OWNER =
> > >> regress_ddl_database ENCODING = "UTF8" LC_COLLATE = "C" LC_CTYPE = "C"
> > >> BUILTIN_LOCALE = "C.UTF-8" COLLATION_VERSION = "1" LOCALE_PROVIDER =
> > >> 'builtin' TABLESPACE = pg_default ALLOW_CONNECTIONS = true CONNECTION
> > >> LIMIT = -1;
> > >>
> > >>
> > >> 2) SELECT pg_get_database_ddl('test_get_database_ddl_builtin', true);
> > >> -- *pretty formatted DDL*
> > >>
> > >> CREATE DATABASE test_get_database_ddl_builtin
> > >> WITH
> > >> OWNER = regress_ddl_database
> > >> ENCODING = "UTF8"
> > >> LC_COLLATE = "C"
> > >> LC_CTYPE = "C"
> > >> BUILTIN_LOCALE = "C.UTF-8"
> > >> COLLATION_VERSION = "1"
> > >> LOCALE_PROVIDER = 'builtin'
> > >> TABLESPACE = pg_default
> > >> ALLOW_CONNECTIONS = true
> > >> CONNECTION LIMIT = -1;
> > >>
> > >> 3) SELECT pg_get_database_ddl(16835); -- *non-pretty formatted
> > >> DDL for OID*
> > >> 4) SELECT pg_get_database_ddl(16835, true); -- *pretty formatted DDL
> > >> for OID*
> > >>
> > >> The patch includes documentation, in-code comments, and regression
> > >> tests, all of which pass successfully.
> > >> *
> > >> **Note:* To run the regression tests, particularly the pg_upgrade
> > >> tests successfully, I had to add a helper function, ddl_filter (in
> > >> database.sql), which removes locale and collation-related information
> > >> from the pg_get_database_ddl output.
> > >>
> > > I think we should check the connection permissions here. Otherwise:
> > >
> > > postgres=> SELECT pg_database_size('testdb');
> > > ERROR: permission denied for database testdb
> > > postgres=> SELECT pg_get_database_ddl('testdb');
> > >
> > > pg_get_database_ddl
> > >
> > -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
> > > CREATE DATABASE testdb WITH OWNER = quanzl ENCODING = "UTF8"
> > > LC_COLLATE = "zh_CN.UTF-8" LC_CTYPE = "zh_CN.UTF-8" LOCALE_PROVIDER =
> > > 'libc' TABLESPACE = pg_default ALLOW_CONNECTIONS = true CONNECTION LIMIT
> > > = -1;
> > > (1 row)
> > >
> > > Users without connection permissions should not generate DDL.
> > >
> >
> > The "dbOwner" is defined as a null pointer.
> > char *dbOwner = NULL;
> >
> > Later, there might be a risk of it not being assigned a value.
> > if (OidIsValid(dbForm->datdba))
> > dbOwner = GetUserNameFromId(dbForm->datdba, false);
> >
> > Although there is no problem in normal circumstances here. Many parts of
> > the existing code have not been checked either. Since this possibility
> > exists, it should be checked before using it. Just like the function
> > roles_is_member_of (acl.c).
> >
> > if (dbOwner)
> > get_formatted_string(&buf, prettyFlags, 1, "OWNER = %s",
> > quote_identifier(dbOwner));
> >
>
> Fixed the given review comment. I've attached the v2 patch ready for
> review.
>
Thanks for updating the patch, some comments on v2.
1.
Should we merge the functions pg_get_database_ddl(oid, [boolean]) and
pg_get_database_ddl(name, [boolean]) in documentation, following the
precedent set by pg_database_size in func-admin.sgml.
2.
+ * noOfTabChars - indent with specified no of tabs.
How about using 'indent with specified number of tab characters'?
And for variable noOfTabChars, I'd like use nTabs or nTabChars.
3.
+/*
+ * pg_get_database_ddl_oid
+ *
+ * Generate a CREATE DATABASE statement for the specified database oid.
+ *
+ * dbName - Name of the database for which to generate the DDL.
+ * pretty - If true, format the DDL with indentation and line breaks.
+ */
A copy-paste error resulted in an incorrect comments (dbName).
All the review comments have been addressed in v3 patch.
--
Best regards,
Japin Li
ChengDu WenWu Information Technology Co., LTD.
Re: [PATCH] Add pg_get_database_ddl() function to reconstruct CREATE DATABASE statement
Attached is the v3 patch ready for review.
On 2025-Nov-13, Quan Zongliang wrote:
> A more specific example. Originally, it was impossible to obtain the
> definition of "testdb" by accessing pg_database:
>
> postgres=> SELECT * FROM pg_database WHERE datname='testdb';
> ERROR: permission denied for table pg_database
Hmm. So I was thinking that running things in this mode (where catalog
access is restricted) has never been supported. But you're right that
we would be opening a hole that we don't have today, because if the
admin closes down permissions on pg_database, then this new function
would be a way to obtain information that the user can't currently
obtain.
My further point was to be that you still need to obtain a list of
database names or OIDs in order to do anything of value. But it turns
out that this is extremely easy and quick to do, with something like
SELECT i, pg_describe_object('pg_database'::regclass, i, 0)
FROM generate_series(1, 1_000_000) i
WHERE pg_describe_object('pg_database'::regclass, i, 0) IS NOT NULL;
... and with this function, the user could again obtain everything about
the database even when they can't read the catalog directly.
Maybe checking privs for the database being dumped is enough protection
against this -- the equivalent of has_database_privilege( ..., 'CONNECT')
I suppose.
--
Álvaro Herrera PostgreSQL Developer — https://www.EnterpriseDB.com/
"¿Qué importan los años? Lo que realmente importa es comprobar que
a fin de cuentas la mejor edad de la vida es estar vivo" (Mafalda)
Re: [PATCH] Add pg_get_database_ddl() function to reconstruct CREATE DATABASE statement
Hi Akshay,
I just reviewed v3 and got some comments:
> On Nov 17, 2025, at 22:34, Akshay Joshi wrote:
>
> All the review comments have been addressed in v3 patch.
1 - ruleutils.c
```
+ if (dbForm->datconnlimit != 0)
+ get_formatted_string(&buf, prettyFlags, 1, "CONNECTION LIMIT = %d",
+ dbForm->datconnlimit);
```
I think this is wrong. Default value of CONNECTION_LIMIT is -1 rather than 0. 0 means no connection is allowed, users should intentionally set the value, thus 0 should be printed.
2 - ruleutils.c
```
+ if (!attrIsNull)
+ get_formatted_string(&buf, prettyFlags, 1, "ICU_RULES = %s",
+ quote_identifier(TextDatumGetCString(dbValue)));
```
ICU_RULES should be omitted if provider is not icu.
3 - ruleutils.c
```
+ if (!HeapTupleIsValid(tupleDatabase))
+ ereport(ERROR,
+ errcode(ERRCODE_UNDEFINED_OBJECT),
+ errmsg("database with oid %d does not exist", dbOid));
```
I believe all existing code use %u to format oid. I ever raised the same comment to the other get_xxx_ddl patch.
4 - ruleutils.c
```
+ /*
+ * User must have connect privilege for target database.
+ */
+ aclresult = object_aclcheck(DatabaseRelationId, dbOid, GetUserId(),
+ ACL_CONNECT);
+ if (aclresult != ACLCHECK_OK)
+ {
+ aclcheck_error(aclresult, OBJECT_DATABASE,
+ get_database_name(dbOid));
+ }
```
I don’t think CONNECT privilege is good enough. By default, a new user gets CONNECT privilege via the PUBLIC role. I just did a quick test to confirm that.
```
# Create a new cluster
% initdb .
% pg_ctl -D . start
% createdb evantest
% createdb evan
# connect to the db
% psql -d evantest -U evan
psql (19devel)
Type "help" for help. # Got into the database successfully
# Without any privilege grant, the user can get ddl of the system database, which seems not good
evantest=> select pg_get_database_ddl('postgres', true);
pg_get_database_ddl
------------------------------------
CREATE DATABASE postgres +
WITH +
OWNER = chaol +
ENCODING = "UTF8" +
LC_COLLATE = "en_US.UTF-8"+
LC_CTYPE = "en_US.UTF-8" +
LOCALE_PROVIDER = 'libc' +
TABLESPACE = pg_default +
ALLOW_CONNECTIONS = true +
CONNECTION LIMIT = -1;
(1 row)
```
IMO, only super user and database owner should be to get ddl of the database.
5 - as you can see from the above test output, “+” in the end of every line is weird.
6 - “WITH” has the same indent as the parameters, which doesn’t good look. If we look at the doc https://www.postgresql.org/docs/18/sql-createdatabase.html, “WITH” takes the first level of indent, and parameters take the second level of indent.
7 - For those parameters that have default values should be omitted. For example:
```
evantest=> select pg_get_database_ddl('evantest', true);
pg_get_database_ddl
------------------------------------
CREATE DATABASE evantest +
WITH +
OWNER = chaol +
ENCODING = "UTF8" +
LC_COLLATE = "en_US.UTF-8"+
LC_CTYPE = "en_US.UTF-8" +
LOCALE_PROVIDER = 'libc' +
TABLESPACE = pg_default +
ALLOW_CONNECTIONS = true +
CONNECTION LIMIT = -1;
(1 row)
```
I created the database “evantest” without providing any parameter. I think at least OWNER, TABLESPACE and ALLOW_CNONNECTIONS should be omitted. For CONNECTION LIMIT, you already have a logic to omit it but the logic has some problem as comment 1.
8 - ruleutils.c
```
+/*
+ * get_formatted_string
+ *
+ * Return a formatted version of the string.
+ *
+ * prettyFlags - Based on prettyFlags the output includes tabs (\t) and
+ * newlines (\n).
+ * nTabChars - indent with specified number of tab characters.
+ * fmt - printf-style format string used by appendStringInfoVA.
+ */
+static void
+get_formatted_string(StringInfo buf, int prettyFlags, int nTabChars, const char *fmt,...)
```
I don’t feel good with this function, but not because of the implementation of the function.
I have reviewed a bunch of get_xxx_ddl patches submitted by different persons. All of them are under a big project, however, looks like to me that all authors work independently without properly coordinated. A function like this one should be common for all those patches. Maybe Alvaro can help here, pushing a common function that is used to format DDL and requesting all patches to use the function.
Best regards,
--
Chao Li (Evan)
HighGo Software Co., Ltd.
https://www.highgo.com/
Re: [PATCH] Add pg_get_database_ddl() function to reconstruct CREATE DATABASE statement
Hi Akshay,
I just reviewed v3 and got some comments:
> On Nov 17, 2025, at 22:34, Akshay Joshi <akshay.joshi@enterprisedb.com> wrote:
>
> All the review comments have been addressed in v3 patch.
1 - ruleutils.c
```
+ if (dbForm->datconnlimit != 0)
+ get_formatted_string(&buf, prettyFlags, 1, "CONNECTION LIMIT = %d",
+ dbForm->datconnlimit);
```
I think this is wrong. Default value of CONNECTION_LIMIT is -1 rather than 0. 0 means no connection is allowed, users should intentionally set the value, thus 0 should be printed.
2 - ruleutils.c
```
+ if (!attrIsNull)
+ get_formatted_string(&buf, prettyFlags, 1, "ICU_RULES = %s",
+ quote_identifier(TextDatumGetCString(dbValue)));
```
ICU_RULES should be omitted if provider is not icu.
3 - ruleutils.c
```
+ if (!HeapTupleIsValid(tupleDatabase))
+ ereport(ERROR,
+ errcode(ERRCODE_UNDEFINED_OBJECT),
+ errmsg("database with oid %d does not exist", dbOid));
```
I believe all existing code use %u to format oid. I ever raised the same comment to the other get_xxx_ddl patch.
Fixed all above in the attached v4 patch.
4 - ruleutils.c
```
+ /*
+ * User must have connect privilege for target database.
+ */
+ aclresult = object_aclcheck(DatabaseRelationId, dbOid, GetUserId(),
+ ACL_CONNECT);
+ if (aclresult != ACLCHECK_OK)
+ {
+ aclcheck_error(aclresult, OBJECT_DATABASE,
+ get_database_name(dbOid));
+ }
```
I don’t think CONNECT privilege is good enough. By default, a new user gets CONNECT privilege via the PUBLIC role. I just did a quick test to confirm that.
```
# Create a new cluster
% initdb .
% pg_ctl -D . start
% createdb evantest
% createdb evan
# connect to the db
% psql -d evantest -U evan
psql (19devel)
Type "help" for help. # Got into the database successfully
# Without any privilege grant, the user can get ddl of the system database, which seems not good
evantest=> select pg_get_database_ddl('postgres', true);
pg_get_database_ddl
------------------------------------
CREATE DATABASE postgres +
WITH +
OWNER = chaol +
ENCODING = "UTF8" +
LC_COLLATE = "en_US.UTF-8"+
LC_CTYPE = "en_US.UTF-8" +
LOCALE_PROVIDER = 'libc' +
TABLESPACE = pg_default +
ALLOW_CONNECTIONS = true +
CONNECTION LIMIT = -1;
(1 row)
```
IMO, only super user and database owner should be to get ddl of the database.
I wasn't entirely sure, but after reviewing the pg_database_size() function, I've concluded that its usage extends beyond the Superuser and Database Owner. Specifically, other roles can view the database size if they have the CONNECT privilege or are Members of the pg_read_all_stats role.
5 - as you can see from the above test output, “+” in the end of every line is weird.
The plus sign (+) is merely an artifact of psql's output formatting when a result cell contains a newline character (\n). It serves as a visual cue to the user that the data continues on the next line. This is confirmed by the absence of the + sign when viewing the same data in a different client, such as pgAdmin." To suppress this visual cue in psql, you can use the command: \pset format unaligned
6 - “WITH” has the same indent as the parameters, which doesn’t good look. If we look at the doc https://www.postgresql.org/docs/18/sql-createdatabase.html, “WITH” takes the first level of indent, and parameters take the second level of indent.
Fixed in the v4 patch and followed the docs.
7 - For those parameters that have default values should be omitted. For example:
```
evantest=> select pg_get_database_ddl('evantest', true);
pg_get_database_ddl
------------------------------------
CREATE DATABASE evantest +
WITH +
OWNER = chaol +
ENCODING = "UTF8" +
LC_COLLATE = "en_US.UTF-8"+
LC_CTYPE = "en_US.UTF-8" +
LOCALE_PROVIDER = 'libc' +
TABLESPACE = pg_default +
ALLOW_CONNECTIONS = true +
CONNECTION LIMIT = -1;
(1 row)
```
I created the database “evantest” without providing any parameter. I think at least OWNER, TABLESPACE and ALLOW_CNONNECTIONS should be omitted. For CONNECTION LIMIT, you already have a logic to omit it but the logic has some problem as comment 1.
IMHO, parameters with default values should not be omitted from the output of the pg_get_xxx_ddl functions. The primary purpose of these functions is to accurately reconstruct the DDL. Including all parameters ensures clarity, as not everyone is familiar with the default value of every single parameter.
8 - ruleutils.c
```
+/*
+ * get_formatted_string
+ *
+ * Return a formatted version of the string.
+ *
+ * prettyFlags - Based on prettyFlags the output includes tabs (\t) and
+ * newlines (\n).
+ * nTabChars - indent with specified number of tab characters.
+ * fmt - printf-style format string used by appendStringInfoVA.
+ */
+static void
+get_formatted_string(StringInfo buf, int prettyFlags, int nTabChars, const char *fmt,...)
```
I don’t feel good with this function, but not because of the implementation of the function.
I have reviewed a bunch of get_xxx_ddl patches submitted by different persons. All of them are under a big project, however, looks like to me that all authors work independently without properly coordinated. A function like this one should be common for all those patches. Maybe Alvaro can help here, pushing a common function that is used to format DDL and requesting all patches to use the function.
Yes, all pg_get_xxx_ddl functions are part of a larger project, and different authors have implemented output formatting in different ways; some implementations may lack formatting altogether. Yes I agree one common function should be developed and committed so that all other authors can reuse it, ensuring consistency across the entire suite of DDL functions."
Best regards,
--
Chao Li (Evan)
HighGo Software Co., Ltd.
https://www.highgo.com/
Re: [PATCH] Add pg_get_database_ddl() function to reconstruct CREATE DATABASE statement
Hi Akshay,
Thanks for updating the patch.
On Tue, 18 Nov 2025 at 13:33, Akshay Joshi wrote:
> Hi Chao
>
> Thanks for reviewing my patch.
>
> On Tue, Nov 18, 2025 at 5:59 AM Chao Li wrote:
>
> Hi Akshay,
>
> I just reviewed v3 and got some comments:
>
> > On Nov 17, 2025, at 22:34, Akshay Joshi wrote:
> >
> > All the review comments have been addressed in v3 patch.
>
> 1 - ruleutils.c
> ```
> + if (dbForm->datconnlimit != 0)
> + get_formatted_string(&buf, prettyFlags, 1, "CONNECTION LIMIT = %d",
> + dbForm->datconnlimit);
> ```
>
> I think this is wrong. Default value of CONNECTION_LIMIT is -1 rather than 0. 0 means no connection is allowed, users
> should intentionally set the value, thus 0 should be printed.
>
> 2 - ruleutils.c
> ```
> + if (!attrIsNull)
> + get_formatted_string(&buf, prettyFlags, 1, "ICU_RULES = %s",
> + quote_identifier(TextDatumGetCString(dbValue)));
> ```
>
> ICU_RULES should be omitted if provider is not icu.
>
> 3 - ruleutils.c
> ```
> + if (!HeapTupleIsValid(tupleDatabase))
> + ereport(ERROR,
> + errcode(ERRCODE_UNDEFINED_OBJECT),
> + errmsg("database with oid %d does not exist", dbOid));
> ```
>
> I believe all existing code use %u to format oid. I ever raised the same comment to the other get_xxx_ddl patch.
>
> Fixed all above in the attached v4 patch.
1.
Since the STRATEGY and OID parameters are not being reconstructed, should we
document this behavior?
postgres=# CREATE DATABASE mydb WITH STRATEGY file_copy OID 19876 IS_TEMPLATE true;
CREATE DATABASE
postgres=# SELECT pg_get_database_ddl('mydb', true);
pg_get_database_ddl
--------------------------------------------
CREATE DATABASE mydb +
WITH OWNER = japin +
ENCODING = "UTF8" +
LC_COLLATE = "en_US.UTF-8"+
LC_CTYPE = "en_US.UTF-8" +
COLLATION_VERSION = "2.39"+
LOCALE_PROVIDER = 'libc' +
TABLESPACE = pg_default +
ALLOW_CONNECTIONS = true +
CONNECTION LIMIT = -1 +
IS_TEMPLATE = true;
(1 row)
2.
We can restrict the scope of the dbTablespace variable as follows:
+ if (OidIsValid(dbForm->dattablespace))
+ {
+ char *dbTablespace = get_tablespace_name(dbForm->dattablespace);
+ if (dbTablespace)
+ get_formatted_string(&buf, prettyFlags, 2, "TABLESPACE = %s",
+ quote_identifier(dbTablespace));
+ }
> >
> > 7 - For those parameters that have default values should be omitted. For
> > example:
> > ```
> > evantest=> select pg_get_database_ddl('evantest', true);
> > pg_get_database_ddl
> > ------------------------------------
> > CREATE DATABASE evantest +
> > WITH +
> > OWNER = chaol +
> > ENCODING = "UTF8" +
> > LC_COLLATE = "en_US.UTF-8"+
> > LC_CTYPE = "en_US.UTF-8" +
> > LOCALE_PROVIDER = 'libc' +
> > TABLESPACE = pg_default +
> > ALLOW_CONNECTIONS = true +
> > CONNECTION LIMIT = -1;
> > (1 row)
> > ```
> >
> > I created the database “evantest” without providing any parameter. I think
> > at least OWNER, TABLESPACE and ALLOW_CNONNECTIONS should be omitted. For
> > CONNECTION LIMIT, you already have a logic to omit it but the logic has
> > some problem as comment 1.
> >
>
>
>
> IMHO, parameters with default values *should not* be omitted from the
> output of the pg_get_xxx_ddl functions. The primary purpose of these
> functions is to accurately reconstruct the DDL. Including all parameters
> ensures clarity, as not everyone is familiar with the default value of
> every single parameter.
+1
--
Regards,
Japin Li
ChengDu WenWu Information Technology Co., Ltd.
Re: [PATCH] Add pg_get_database_ddl() function to reconstruct CREATE DATABASE statement
Hello, One thing I realized a few days ago is that since commit bd09f024a1bb we have type regdatabase, so instead of having two functions (one taking name and one taking Oid), we should have just one, taking regdatabase, just like the functions for producing DDL for other object types that have corresponding reg* type. Regards, -- Álvaro Herrera PostgreSQL Developer — https://www.EnterpriseDB.com/
Re: [PATCH] Add pg_get_database_ddl() function to reconstruct CREATE DATABASE statement
Hi Akshay,
Thanks for updating the patch.
On Tue, 18 Nov 2025 at 13:33, Akshay Joshi <akshay.joshi@enterprisedb.com> wrote:
> Hi Chao
>
> Thanks for reviewing my patch.
>
> On Tue, Nov 18, 2025 at 5:59 AM Chao Li <li.evan.chao@gmail.com> wrote:
>
> Hi Akshay,
>
> I just reviewed v3 and got some comments:
>
> > On Nov 17, 2025, at 22:34, Akshay Joshi <akshay.joshi@enterprisedb.com> wrote:
> >
> > All the review comments have been addressed in v3 patch.
>
> 1 - ruleutils.c
> ```
> + if (dbForm->datconnlimit != 0)
> + get_formatted_string(&buf, prettyFlags, 1, "CONNECTION LIMIT = %d",
> + dbForm->datconnlimit);
> ```
>
> I think this is wrong. Default value of CONNECTION_LIMIT is -1 rather than 0. 0 means no connection is allowed, users
> should intentionally set the value, thus 0 should be printed.
>
> 2 - ruleutils.c
> ```
> + if (!attrIsNull)
> + get_formatted_string(&buf, prettyFlags, 1, "ICU_RULES = %s",
> + quote_identifier(TextDatumGetCString(dbValue)));
> ```
>
> ICU_RULES should be omitted if provider is not icu.
>
> 3 - ruleutils.c
> ```
> + if (!HeapTupleIsValid(tupleDatabase))
> + ereport(ERROR,
> + errcode(ERRCODE_UNDEFINED_OBJECT),
> + errmsg("database with oid %d does not exist", dbOid));
> ```
>
> I believe all existing code use %u to format oid. I ever raised the same comment to the other get_xxx_ddl patch.
>
> Fixed all above in the attached v4 patch.
1.
Since the STRATEGY and OID parameters are not being reconstructed, should we
document this behavior?
postgres=# CREATE DATABASE mydb WITH STRATEGY file_copy OID 19876 IS_TEMPLATE true;
CREATE DATABASE
postgres=# SELECT pg_get_database_ddl('mydb', true);
pg_get_database_ddl
--------------------------------------------
CREATE DATABASE mydb +
WITH OWNER = japin +
ENCODING = "UTF8" +
LC_COLLATE = "en_US.UTF-8"+
LC_CTYPE = "en_US.UTF-8" +
COLLATION_VERSION = "2.39"+
LOCALE_PROVIDER = 'libc' +
TABLESPACE = pg_default +
ALLOW_CONNECTIONS = true +
CONNECTION LIMIT = -1 +
IS_TEMPLATE = true;
(1 row)
The
FormData_pg_database structure does not expose the database STRATEGY, and reconstructing the OID serves no practical purpose. If the majority agrees, I can extend the DDL to include OID.
2.
We can restrict the scope of the dbTablespace variable as follows:
+ if (OidIsValid(dbForm->dattablespace))
+ {
+ char *dbTablespace = get_tablespace_name(dbForm->dattablespace);
+ if (dbTablespace)
+ get_formatted_string(&buf, prettyFlags, 2, "TABLESPACE = %s",
+ quote_identifier(dbTablespace));
+ }
Will fix this in the next patch.
> >
> > 7 - For those parameters that have default values should be omitted. For
> > example:
> > ```
> > evantest=> select pg_get_database_ddl('evantest', true);
> > pg_get_database_ddl
> > ------------------------------------
> > CREATE DATABASE evantest +
> > WITH +
> > OWNER = chaol +
> > ENCODING = "UTF8" +
> > LC_COLLATE = "en_US.UTF-8"+
> > LC_CTYPE = "en_US.UTF-8" +
> > LOCALE_PROVIDER = 'libc' +
> > TABLESPACE = pg_default +
> > ALLOW_CONNECTIONS = true +
> > CONNECTION LIMIT = -1;
> > (1 row)
> > ```
> >
> > I created the database “evantest” without providing any parameter. I think
> > at least OWNER, TABLESPACE and ALLOW_CNONNECTIONS should be omitted. For
> > CONNECTION LIMIT, you already have a logic to omit it but the logic has
> > some problem as comment 1.
> >
>
>
>
> IMHO, parameters with default values *should not* be omitted from the
> output of the pg_get_xxx_ddl functions. The primary purpose of these
> functions is to accurately reconstruct the DDL. Including all parameters
> ensures clarity, as not everyone is familiar with the default value of
> every single parameter.
+1
--
Regards,
Japin Li
ChengDu WenWu Information Technology Co., Ltd.
Re: [PATCH] Add pg_get_database_ddl() function to reconstruct CREATE DATABASE statement
Will work on it and send the updated patch.
Hello,
One thing I realized a few days ago is that since commit bd09f024a1bb we
have type regdatabase, so instead of having two functions (one taking
name and one taking Oid), we should have just one, taking regdatabase,
just like the functions for producing DDL for other object types that
have corresponding reg* type.
Regards,
--
Álvaro Herrera PostgreSQL Developer — https://www.EnterpriseDB.com/
Re: [PATCH] Add pg_get_database_ddl() function to reconstruct CREATE DATABASE statement
On Wed, 19 Nov 2025 at 16:36, Akshay Joshi wrote:
> On Wed, Nov 19, 2025 at 3:48 PM Japin Li wrote:
>
> Hi Akshay,
>
> Thanks for updating the patch.
>
> On Tue, 18 Nov 2025 at 13:33, Akshay Joshi wrote:
> > Hi Chao
> >
> > Thanks for reviewing my patch.
> >
> > On Tue, Nov 18, 2025 at 5:59 AM Chao Li wrote:
> >
> > Hi Akshay,
> >
> > I just reviewed v3 and got some comments:
> >
> > > On Nov 17, 2025, at 22:34, Akshay Joshi wrote:
> > >
> > > All the review comments have been addressed in v3 patch.
> >
> > 1 - ruleutils.c
> > ```
> > + if (dbForm->datconnlimit != 0)
> > + get_formatted_string(&buf, prettyFlags, 1, "CONNECTION LIMIT = %d",
> > + dbForm->datconnlimit);
> > ```
> >
> > I think this is wrong. Default value of CONNECTION_LIMIT is -1 rather than 0. 0 means no connection is allowed,
> users
> > should intentionally set the value, thus 0 should be printed.
> >
> > 2 - ruleutils.c
> > ```
> > + if (!attrIsNull)
> > + get_formatted_string(&buf, prettyFlags, 1, "ICU_RULES = %s",
> > + quote_identifier(TextDatumGetCString(dbValue)));
> > ```
> >
> > ICU_RULES should be omitted if provider is not icu.
> >
> > 3 - ruleutils.c
> > ```
> > + if (!HeapTupleIsValid(tupleDatabase))
> > + ereport(ERROR,
> > + errcode(ERRCODE_UNDEFINED_OBJECT),
> > + errmsg("database with oid %d does not exist", dbOid));
> > ```
> >
> > I believe all existing code use %u to format oid. I ever raised the same comment to the other get_xxx_ddl patch.
> >
> > Fixed all above in the attached v4 patch.
>
> 1.
> Since the STRATEGY and OID parameters are not being reconstructed, should we
> document this behavior?
>
> postgres=# CREATE DATABASE mydb WITH STRATEGY file_copy OID 19876 IS_TEMPLATE true;
> CREATE DATABASE
> postgres=# SELECT pg_get_database_ddl('mydb', true);
> pg_get_database_ddl
> --------------------------------------------
> CREATE DATABASE mydb +
> WITH OWNER = japin +
> ENCODING = "UTF8" +
> LC_COLLATE = "en_US.UTF-8"+
> LC_CTYPE = "en_US.UTF-8" +
> COLLATION_VERSION = "2.39"+
> LOCALE_PROVIDER = 'libc' +
> TABLESPACE = pg_default +
> ALLOW_CONNECTIONS = true +
> CONNECTION LIMIT = -1 +
> IS_TEMPLATE = true;
> (1 row)
>
> The FormData_pg_database structure does not expose the database STRATEGY,
Yes, it's not exposed.
> and reconstructing the OID serves no practical
> purpose. If the majority agrees, I can extend the DDL to include OID.
I'm not insisting on reconstructing those parameters; I mean, we can provide
a sentence to describe this behavior.
--
Regards,
Japin Li
ChengDu WenWu Information Technology Co., Ltd.
Re: [PATCH] Add pg_get_database_ddl() function to reconstruct CREATE DATABASE statement
Hello,
One thing I realized a few days ago is that since commit bd09f024a1bb we
have type regdatabase, so instead of having two functions (one taking
name and one taking Oid), we should have just one, taking regdatabase,
just like the functions for producing DDL for other object types that
have corresponding reg* type.
Implemented in the suggested solution. Attached is the v5 patch for review.
Regards,
--
Álvaro Herrera PostgreSQL Developer — https://www.EnterpriseDB.com/
Re: [PATCH] Add pg_get_database_ddl() function to reconstruct CREATE DATABASE statement
On Thu, Nov 20, 2025, at 6:18 AM, Akshay Joshi wrote:
>
> Implemented in the suggested solution. Attached is the v5 patch for review.
>
I reviewed your patch and have some suggestions for this patch.
* You shouldn't include the property if the value is default. A long command
adds nothing. Clarity? Tell someone that needs to select, copy and paste a
long statement. It is a good goal to provide a short command to reconstruct
the object. If you don't know why it didn't include CONNECTION LIMIT, it is
time to check the manual again.
$ psql -AtqX -c "SELECT pg_get_database_ddl('postgres')" -d postgres
CREATE DATABASE postgres WITH OWNER = euler ENCODING = "UTF8" LC_COLLATE = "pt_BR.UTF-8" LC_CTYPE = "pt_BR.UTF-8" COLLATION_VERSION = "2.36" LOCALE_PROVIDER = 'libc' TABLESPACE = pg_default ALLOW_CONNECTIONS = true CONNECTION LIMIT = -1;
* Use single quotes. The encoding, locale, lc_collate, lc_type,
collation_version and some other properties should use single quotes. The
locale_provider doesn't need a single quote because it is an enum. See how
pg_dumpall constructs the command. Use simple_quote_literal.
$ pg_dumpall --binary-upgrade | grep 'p5'
-- Database "p5" dump
-- Name: p5; Type: DATABASE; Schema: -; Owner: euler
CREATE DATABASE p5 WITH TEMPLATE = template0 OID = 16392 STRATEGY = FILE_COPY ENCODING = 'UTF8' LOCALE_PROVIDER = libc LOCALE = 'en_US.UTF-8' COLLATION_VERSION = '2.36';
ALTER DATABASE p5 OWNER TO euler;
\connect p5
* OWNER. There is no guarantee that the owner exists in the cluster you will
use this output. That's something that pg_dumpall treats separately (see
above). Does it mean we should include the owner? No. We can make it an
option.
* LOCALE. Why didn't you include it? I know there are some combinations that
does not work together but this function can provide a minimal set of
properties related to locale.
postgres=# CREATE DATABASE p6 LOCALE_PROVIDER builtin LOCALE 'C' TEMPLATE template0;
CREATE DATABASE
* STRATEGY. Although this is a runtime property, it should be an option.
* TEMPLATE. Ditto.
* options. Since I mentioned options for some properties (owner, strategy,
template), these properties can be accommodated as a VARIADIC argument. The
function signature can be something like
pg_get_database_ddl(oid, VARIADIC options text[])
I would include the pretty print into options too.
* Tabs. I don't think we use tabs to format output. Use spaces. A good practice
is to use EXPLAIN style (2 spaces)and depending on the nesting, 4 spaces are
fine too.
$ psql -AtqX -c "SELECT pg_get_database_ddl('postgres', true)" -d postgres
CREATE DATABASE postgres
WITH OWNER = euler
ENCODING = "UTF8"
LC_COLLATE = "pt_BR.UTF-8"
LC_CTYPE = "pt_BR.UTF-8"
COLLATION_VERSION = "2.36"
LOCALE_PROVIDER = 'libc'
TABLESPACE = pg_default
ALLOW_CONNECTIONS = true
CONNECTION LIMIT = -1;
* permission. I don't think you need to check for permissions inside the
function. I wouldn't want a different behavior than pg_dump(all). You can
always adjust it in system_functions.sql.
* typo.
+--
+-- Reconsturct DDL
+--
s/Reconsturct/Reconstruct/
--
Euler Taveira
EDB https://www.enterprisedb.com/
Re: [PATCH] Add pg_get_database_ddl() function to reconstruct CREATE DATABASE statement
On Thu, Dec 11, 2025 at 7:29 PM Euler Taveira wrote:
>
> On Thu, Nov 20, 2025, at 6:18 AM, Akshay Joshi wrote:
> >
> > Implemented in the suggested solution. Attached is the v5 patch for review.
> >
>
> I reviewed your patch and have some suggestions for this patch.
>
> * You shouldn't include the property if the value is default. A long command
> adds nothing. Clarity? Tell someone that needs to select, copy and paste a
> long statement. It is a good goal to provide a short command to reconstruct
> the object. If you don't know why it didn't include CONNECTION LIMIT, it is
> time to check the manual again.
>
> $ psql -AtqX -c "SELECT pg_get_database_ddl('postgres')" -d postgres
> CREATE DATABASE postgres WITH OWNER = euler ENCODING = "UTF8" LC_COLLATE = "pt_BR.UTF-8" LC_CTYPE = "pt_BR.UTF-8" COLLATION_VERSION = "2.36" LOCALE_PROVIDER = 'libc' TABLESPACE = pg_default ALLOW_CONNECTIONS = true CONNECTION LIMIT = -1;
>
Is there any way to obtain the default values directly from the source
code itself, or do I need to refer to the documentation? If we rely on
the documentation and compare against that, then in the future, if the
default values change, we would also need to update our logic
accordingly.
Constantly having to check the documentation for default values may
feel annoying to some users. Some users run queries with parameters
such as encoding, connection limit, and locale using their default
values. When they call the pg_get_database_ddl function, it
reconstructs the short command based on those defaults.
I am still open to updating my code.
> * Use single quotes. The encoding, locale, lc_collate, lc_type,
> collation_version and some other properties should use single quotes. The
> locale_provider doesn't need a single quote because it is an enum. See how
> pg_dumpall constructs the command. Use simple_quote_literal.
>
I’ll update this in my next patch.
> $ pg_dumpall --binary-upgrade | grep 'p5'
> -- Database "p5" dump
> -- Name: p5; Type: DATABASE; Schema: -; Owner: euler
> CREATE DATABASE p5 WITH TEMPLATE = template0 OID = 16392 STRATEGY = FILE_COPY ENCODING = 'UTF8' LOCALE_PROVIDER = libc LOCALE = 'en_US.UTF-8' COLLATION_VERSION = '2.36';
> ALTER DATABASE p5 OWNER TO euler;
> \connect p5
>
> * OWNER. There is no guarantee that the owner exists in the cluster you will
> use this output. That's something that pg_dumpall treats separately (see
> above). Does it mean we should include the owner? No. We can make it an
> option.
>
If I understand correctly, the owner should be an option provided by
the caller of the function, and we reconstruct the Database DDL using
that specified owner. Is that right?
If so, then in my humble opinion, this is not truly a reconstruction
of the existing database object.
> * LOCALE. Why didn't you include it? I know there are some combinations that
> does not work together but this function can provide a minimal set of
> properties related to locale.
>
> postgres=# CREATE DATABASE p6 LOCALE_PROVIDER builtin LOCALE 'C' TEMPLATE template0;
> CREATE DATABASE
>
For LOCALE where the provider is libc, datlocale is NULL. For builtin
and icu, I have already added the following condition in the code:
if (!attrIsNull && dbForm->datlocprovider == COLLPROVIDER_BUILTIN)
get_formatted_string(&buf, prettyFlags, 2, "BUILTIN_LOCALE = %s",
quote_identifier(TextDatumGetCString(dbValue)));
else if (!attrIsNull && dbForm->datlocprovider == COLLPROVIDER_ICU)
get_formatted_string(&buf, prettyFlags, 2, "ICU_LOCALE = %s",
quote_identifier(TextDatumGetCString(dbValue)));
> * STRATEGY. Although this is a runtime property, it should be an option.
>
> * TEMPLATE. Ditto.
>
> * options. Since I mentioned options for some properties (owner, strategy,
> template), these properties can be accommodated as a VARIADIC argument. The
> function signature can be something like
>
> pg_get_database_ddl(oid, VARIADIC options text[])
>
> I would include the pretty print into options too.
>
Same comment as the one I gave for the Owner, if you are referring to
these as options to the function.
> * Tabs. I don't think we use tabs to format output. Use spaces. A good practice
> is to use EXPLAIN style (2 spaces)and depending on the nesting, 4 spaces are
> fine too.
>
> $ psql -AtqX -c "SELECT pg_get_database_ddl('postgres', true)" -d postgres
> CREATE DATABASE postgres
> WITH OWNER = euler
> ENCODING = "UTF8"
> LC_COLLATE = "pt_BR.UTF-8"
> LC_CTYPE = "pt_BR.UTF-8"
> COLLATION_VERSION = "2.36"
> LOCALE_PROVIDER = 'libc'
> TABLESPACE = pg_default
> ALLOW_CONNECTIONS = true
> CONNECTION LIMIT = -1;
>
I received a review comment suggesting the use of tabs. I also looked
up PostgreSQL best practices on google, which recommend using tabs for
indentation and spaces for alignment. I’m open to updating my code
accordingly.
> * permission. I don't think you need to check for permissions inside the
> function. I wouldn't want a different behavior than pg_dump(all). You can
> always adjust it in system_functions.sql.
>
We’ve already had extensive discussions on this topic in the same
email thread, and ultimately we decided to add the permission check.
> * typo.
>
> +--
> +-- Reconsturct DDL
> +--
>
> s/Reconsturct/Reconstruct/
>
I’ll update this in my next patch.
>
> --
> Euler Taveira
> EDB https://www.enterprisedb.com/
Re: [PATCH] Add pg_get_database_ddl() function to reconstruct CREATE DATABASE statement
On Fri, Dec 12, 2025, at 7:52 AM, Akshay Joshi wrote: > On Thu, Dec 11, 2025 at 7:29 PM Euler Taveira wrote: >> > Is there any way to obtain the default values directly from the source > code itself, or do I need to refer to the documentation? If we rely on > the documentation and compare against that, then in the future, if the > default values change, we would also need to update our logic > accordingly. > No, you need to check the documentation. If you are changing the default value, you are breaking compatibility; that rarely happens. If we are really concern about this fact, you can add a test case that creates the object without properties (all default values) and another with all default properties and then compare the output. > Constantly having to check the documentation for default values may > feel annoying to some users. Some users run queries with parameters > such as encoding, connection limit, and locale using their default > values. When they call the pg_get_database_ddl function, it > reconstructs the short command based on those defaults. > Encoding and locale, ok but I doubt about connection limit. postgres=# SELECT current_user; current_user -------------- euler (1 row) postgres=# CREATE DATABASE foo; CREATE DATABASE postgres=# CREATE DATABASE bar OWNER euler; CREATE DATABASE When you are learning a new command, you generally don't set the default value for a property just to be correct. I'm not saying this function shouldn't include OWNER. I'm just suggesting it to be optional. See some arguments below. >> * OWNER. There is no guarantee that the owner exists in the cluster you will >> use this output. That's something that pg_dumpall treats separately (see >> above). Does it mean we should include the owner? No. We can make it an >> option. >> > If I understand correctly, the owner should be an option provided by > the caller of the function, and we reconstruct the Database DDL using > that specified owner. Is that right? > If so, then in my humble opinion, this is not truly a reconstruction > of the existing database object. > No. My idea is to have something like the pg_dump --no-owner option. This is important if you are transporting the objects from one cluster to another one. Owner might be different. That's why I'm suggesting it should be optional. It means flexibility. See pg_dump output format that always apply the OWNER as a separate ALTER command. >> * options. Since I mentioned options for some properties (owner, strategy, >> template), these properties can be accommodated as a VARIADIC argument. The >> function signature can be something like >> >> pg_get_database_ddl(oid, VARIADIC options text[]) >> >> I would include the pretty print into options too. >> > Same comment as the one I gave for the Owner, if you are referring to > these as options to the function. > Let me elaborate a bit. As I suggested you can control the output with options. Why? Flexibility. Why am I suggesting such a general purpose implementation? See some of the use cases. 1. object DDL. Check DDL to recreate the object. It is not the exact DDL that the user informed but it produces the same result. 2. clone tool. Clone the objects to recreate the environment for another customer. These objects can be created in the same cluster or in another one. (Of course, global objects don't apply for the same cluster.) 3. dump tool. Dump the commands to recreate the existing objects. 4. diff tool. There are tools like pgquarrel [1] that queries the catalog and compare the results to create commands to turn the target database into the source database. The general purpose functions can be used if the object doesn't exist in the target database. (Of course, it doesn't apply for global objects but again it is a good UI to have all of these pg_get_OBJECT_ddl functions using the same approach.) 5. logical replication. These pg_get_OBJECT_ddl functions can be good candidates to be used in the initial schema replication and even in the DDL replication (if the object doesn't exist in the target database). The "options" parameter is to get the DDL command to serve any of these use cases. There are some properties in a certain object that you *don't* want for whatever reason. See some --no-OBJECT options in pg_dump. Let's say you don't want the TABLESPACE or the table access method while getting the CREATE TABLE DDL because it is different in the other database. > I received a review comment suggesting the use of tabs. I also looked > up PostgreSQL best practices on google, which recommend using tabs for > indentation and spaces for alignment. I’m open to updating my code > accordingly. > I didn't check all of the possible output but the majority uses space instead of tabs. Check psql. If you check the git history (git log --grep=tabs), you will notice that tabs are removed from source code. >> * permission. I don't think you need to check for permissions inside the >> function. I wouldn't want a different behavior than pg_dump(all). You can >> always adjust it in system_functions.sql. >> > We’ve already had extensive discussions on this topic in the same > email thread, and ultimately we decided to add the permission check. > That's fair. Again, I expect that all of these pg_get_OBJECT_ddl functions use the same approach. We can always relax this restriction in the future. -- Euler Taveira EDB https://www.enterprisedb.com/
Re: [PATCH] Add pg_get_database_ddl() function to reconstruct CREATE DATABASE statement
On Fri, Dec 12, 2025, at 7:52 AM, Akshay Joshi wrote:On Thu, Dec 11, 2025 at 7:29 PM Euler Taveira <euler@eulerto.com> wrote:Is there any way to obtain the default values directly from the source code itself, or do I need to refer to the documentation? If we rely on the documentation and compare against that, then in the future, if the default values change, we would also need to update our logic accordingly.No, you need to check the documentation. If you are changing the default value, you are breaking compatibility; that rarely happens. If we are really concern about this fact, you can add a test case that creates the object without properties (all default values) and another with all default properties and then compare the output.
Maybe the function should have a VERBOSE option that emits all the defaults.
Constantly having to check the documentation for default values may feel annoying to some users. Some users run queries with parameters such as encoding, connection limit, and locale using their default values. When they call the pg_get_database_ddl function, it reconstructs the short command based on those defaults.Encoding and locale, ok but I doubt about connection limit. postgres=# SELECT current_user; current_user -------------- euler (1 row) postgres=# CREATE DATABASE foo; CREATE DATABASE postgres=# CREATE DATABASE bar OWNER euler; CREATE DATABASE When you are learning a new command, you generally don't set the default value for a property just to be correct. I'm not saying this function shouldn't include OWNER. I'm just suggesting it to be optional. See some arguments below.* OWNER. There is no guarantee that the owner exists in the cluster you will use this output. That's something that pg_dumpall treats separately (see above). Does it mean we should include the owner? No. We can make it an option.If I understand correctly, the owner should be an option provided by the caller of the function, and we reconstruct the Database DDL using that specified owner. Is that right? If so, then in my humble opinion, this is not truly a reconstruction of the existing database object.No. My idea is to have something like the pg_dump --no-owner option. This is important if you are transporting the objects from one cluster to another one. Owner might be different. That's why I'm suggesting it should be optional. It means flexibility. See pg_dump output format that always apply the OWNER as a separate ALTER command.
+1
* options. Since I mentioned options for some properties (owner, strategy, template), these properties can be accommodated as a VARIADIC argument. The function signature can be something like pg_get_database_ddl(oid, VARIADIC options text[]) I would include the pretty print into options too.Same comment as the one I gave for the Owner, if you are referring to these as options to the function.Let me elaborate a bit. As I suggested you can control the output with options. Why? Flexibility. Why am I suggesting such a general purpose implementation? See some of the use cases. 1. object DDL. Check DDL to recreate the object. It is not the exact DDL that the user informed but it produces the same result. 2. clone tool. Clone the objects to recreate the environment for another customer. These objects can be created in the same cluster or in another one. (Of course, global objects don't apply for the same cluster.) 3. dump tool. Dump the commands to recreate the existing objects. 4. diff tool. There are tools like pgquarrel [1] that queries the catalog and compare the results to create commands to turn the target database into the source database. The general purpose functions can be used if the object doesn't exist in the target database. (Of course, it doesn't apply for global objects but again it is a good UI to have all of these pg_get_OBJECT_ddl functions using the same approach.) 5. logical replication. These pg_get_OBJECT_ddl functions can be good candidates to be used in the initial schema replication and even in the DDL replication (if the object doesn't exist in the target database). The "options" parameter is to get the DDL command to serve any of these use cases. There are some properties in a certain object that you *don't* want for whatever reason. See some --no-OBJECT options in pg_dump. Let's say you don't want the TABLESPACE or the table access method while getting the CREATE TABLE DDL because it is different in the other database.
+1
I received a review comment suggesting the use of tabs. I also looked up PostgreSQL best practices on google, which recommend using tabs for indentation and spaces for alignment. I’m open to updating my code accordingly.I didn't check all of the possible output but the majority uses space instead of tabs. Check psql. If you check the git history (git log --grep=tabs), you will notice that tabs are removed from source code.
We should follow the pretty printing style in ruleutils.c, which uses spaces.
* permission. I don't think you need to check for permissions inside the function. I wouldn't want a different behavior than pg_dump(all). You can always adjust it in system_functions.sql.We’ve already had extensive discussions on this topic in the same email thread, and ultimately we decided to add the permission check.That's fair. Again, I expect that all of these pg_get_OBJECT_ddl functions use the same approach. We can always relax this restriction in the future.
+1
cheers
andrew
-- Andrew Dunstan EDB: https://www.enterprisedb.com
Re: [PATCH] Add pg_get_database_ddl() function to reconstruct CREATE DATABASE statement
I have incorporated Euler’s changes, which modify the declaration and definition of the pg_get_database_ddl function. Please find the attached v6 patch, which is now ready for review. The following updates have been made:
Function signature updated to: pg_get_database_ddl(database_id regdatabase, VARIADIC ddl_options text[])
Added options --no-owner and --no-tablespace to omit the OWNER and TABLESPACE clauses from the reconstructed DDL.
Moved the "pretty" parameter into ddl_options for formatted output.
Properties such as ENCODING, LOCALE_PROVIDER, TABLESPACE, CONNECTION LIMIT, and ALLOW_CONNECTIONS are omitted if they are set to default values.
Introduced the --with-defaults option to include clauses for parameters even when they are at their default values.
Standardized formatting to use spaces instead of tabs.
Usage examples:
- SELECT pg_get_database_ddl('postgres'); // Non pretty-formatted DDL
- SELECT pg_get_database_ddl(16835); // Non pretty-formatted DDL
- SELECT pg_get_database_ddl('postgres', 'pretty'); // pretty-formatted DDL
- SELECT pg_get_database_ddl('postgres', '--no-owner', '--no-tablespace'); // Omits the Owner and Tablespace clause from the DDL.
- SELECT pg_get_database_ddl('postgres', 'pretty', '--with-defaults'); // Includes clauses for parameters that are currently at their default values.
On 2025-12-12 Fr 10:19 AM, Euler Taveira wrote:On Fri, Dec 12, 2025, at 7:52 AM, Akshay Joshi wrote:On Thu, Dec 11, 2025 at 7:29 PM Euler Taveira <euler@eulerto.com> wrote:Is there any way to obtain the default values directly from the source code itself, or do I need to refer to the documentation? If we rely on the documentation and compare against that, then in the future, if the default values change, we would also need to update our logic accordingly.No, you need to check the documentation. If you are changing the default value, you are breaking compatibility; that rarely happens. If we are really concern about this fact, you can add a test case that creates the object without properties (all default values) and another with all default properties and then compare the output.
Maybe the function should have a VERBOSE option that emits all the defaults.
Constantly having to check the documentation for default values may feel annoying to some users. Some users run queries with parameters such as encoding, connection limit, and locale using their default values. When they call the pg_get_database_ddl function, it reconstructs the short command based on those defaults.Encoding and locale, ok but I doubt about connection limit. postgres=# SELECT current_user; current_user -------------- euler (1 row) postgres=# CREATE DATABASE foo; CREATE DATABASE postgres=# CREATE DATABASE bar OWNER euler; CREATE DATABASE When you are learning a new command, you generally don't set the default value for a property just to be correct. I'm not saying this function shouldn't include OWNER. I'm just suggesting it to be optional. See some arguments below.* OWNER. There is no guarantee that the owner exists in the cluster you will use this output. That's something that pg_dumpall treats separately (see above). Does it mean we should include the owner? No. We can make it an option.If I understand correctly, the owner should be an option provided by the caller of the function, and we reconstruct the Database DDL using that specified owner. Is that right? If so, then in my humble opinion, this is not truly a reconstruction of the existing database object.No. My idea is to have something like the pg_dump --no-owner option. This is important if you are transporting the objects from one cluster to another one. Owner might be different. That's why I'm suggesting it should be optional. It means flexibility. See pg_dump output format that always apply the OWNER as a separate ALTER command.
+1
* options. Since I mentioned options for some properties (owner, strategy, template), these properties can be accommodated as a VARIADIC argument. The function signature can be something like pg_get_database_ddl(oid, VARIADIC options text[]) I would include the pretty print into options too.Same comment as the one I gave for the Owner, if you are referring to these as options to the function.Let me elaborate a bit. As I suggested you can control the output with options. Why? Flexibility. Why am I suggesting such a general purpose implementation? See some of the use cases. 1. object DDL. Check DDL to recreate the object. It is not the exact DDL that the user informed but it produces the same result. 2. clone tool. Clone the objects to recreate the environment for another customer. These objects can be created in the same cluster or in another one. (Of course, global objects don't apply for the same cluster.) 3. dump tool. Dump the commands to recreate the existing objects. 4. diff tool. There are tools like pgquarrel [1] that queries the catalog and compare the results to create commands to turn the target database into the source database. The general purpose functions can be used if the object doesn't exist in the target database. (Of course, it doesn't apply for global objects but again it is a good UI to have all of these pg_get_OBJECT_ddl functions using the same approach.) 5. logical replication. These pg_get_OBJECT_ddl functions can be good candidates to be used in the initial schema replication and even in the DDL replication (if the object doesn't exist in the target database). The "options" parameter is to get the DDL command to serve any of these use cases. There are some properties in a certain object that you *don't* want for whatever reason. See some --no-OBJECT options in pg_dump. Let's say you don't want the TABLESPACE or the table access method while getting the CREATE TABLE DDL because it is different in the other database.
+1
I received a review comment suggesting the use of tabs. I also looked up PostgreSQL best practices on google, which recommend using tabs for indentation and spaces for alignment. I’m open to updating my code accordingly.I didn't check all of the possible output but the majority uses space instead of tabs. Check psql. If you check the git history (git log --grep=tabs), you will notice that tabs are removed from source code.
We should follow the pretty printing style in ruleutils.c, which uses spaces.
* permission. I don't think you need to check for permissions inside the function. I wouldn't want a different behavior than pg_dump(all). You can always adjust it in system_functions.sql.We’ve already had extensive discussions on this topic in the same email thread, and ultimately we decided to add the permission check.That's fair. Again, I expect that all of these pg_get_OBJECT_ddl functions use the same approach. We can always relax this restriction in the future.
+1
cheers
andrew
-- Andrew Dunstan EDB: https://www.enterprisedb.com
Re: [PATCH] Add pg_get_database_ddl() function to reconstruct CREATE DATABASE statement
1) Implement uint64 for the flags to provide capacity for up to 64 distinct options.
2) Refactorparse_ddl_optionsto return the flag set directly rather than using an out parameter.
Please find the attached v7 patch, which is now ready for review.
I have incorporated Euler’s changes, which modify the declaration and definition of the pg_get_database_ddl function. Please find the attached v6 patch, which is now ready for review. The following updates have been made:
Function signature updated to: pg_get_database_ddl(database_id regdatabase, VARIADIC ddl_options text[])
Added options --no-owner and --no-tablespace to omit the OWNER and TABLESPACE clauses from the reconstructed DDL.
Moved the "pretty" parameter into ddl_options for formatted output.
Properties such as ENCODING, LOCALE_PROVIDER, TABLESPACE, CONNECTION LIMIT, and ALLOW_CONNECTIONS are omitted if they are set to default values.
Introduced the --with-defaults option to include clauses for parameters even when they are at their default values.
Standardized formatting to use spaces instead of tabs.
Usage examples:
- SELECT pg_get_database_ddl('postgres'); // Non pretty-formatted DDL
- SELECT pg_get_database_ddl(16835); // Non pretty-formatted DDL
- SELECT pg_get_database_ddl('postgres', 'pretty'); // pretty-formatted DDL
- SELECT pg_get_database_ddl('postgres', '--no-owner', '--no-tablespace'); // Omits the Owner and Tablespace clause from the DDL.
- SELECT pg_get_database_ddl('postgres', 'pretty', '--with-defaults'); // Includes clauses for parameters that are currently at their default values.
On Thu, Jan 8, 2026 at 4:57 AM Andrew Dunstan <andrew@dunslane.net> wrote:
On 2025-12-12 Fr 10:19 AM, Euler Taveira wrote:On Fri, Dec 12, 2025, at 7:52 AM, Akshay Joshi wrote:On Thu, Dec 11, 2025 at 7:29 PM Euler Taveira <euler@eulerto.com> wrote:Is there any way to obtain the default values directly from the source code itself, or do I need to refer to the documentation? If we rely on the documentation and compare against that, then in the future, if the default values change, we would also need to update our logic accordingly.No, you need to check the documentation. If you are changing the default value, you are breaking compatibility; that rarely happens. If we are really concern about this fact, you can add a test case that creates the object without properties (all default values) and another with all default properties and then compare the output.
Maybe the function should have a VERBOSE option that emits all the defaults.
Constantly having to check the documentation for default values may feel annoying to some users. Some users run queries with parameters such as encoding, connection limit, and locale using their default values. When they call the pg_get_database_ddl function, it reconstructs the short command based on those defaults.Encoding and locale, ok but I doubt about connection limit. postgres=# SELECT current_user; current_user -------------- euler (1 row) postgres=# CREATE DATABASE foo; CREATE DATABASE postgres=# CREATE DATABASE bar OWNER euler; CREATE DATABASE When you are learning a new command, you generally don't set the default value for a property just to be correct. I'm not saying this function shouldn't include OWNER. I'm just suggesting it to be optional. See some arguments below.* OWNER. There is no guarantee that the owner exists in the cluster you will use this output. That's something that pg_dumpall treats separately (see above). Does it mean we should include the owner? No. We can make it an option.If I understand correctly, the owner should be an option provided by the caller of the function, and we reconstruct the Database DDL using that specified owner. Is that right? If so, then in my humble opinion, this is not truly a reconstruction of the existing database object.No. My idea is to have something like the pg_dump --no-owner option. This is important if you are transporting the objects from one cluster to another one. Owner might be different. That's why I'm suggesting it should be optional. It means flexibility. See pg_dump output format that always apply the OWNER as a separate ALTER command.
+1
* options. Since I mentioned options for some properties (owner, strategy, template), these properties can be accommodated as a VARIADIC argument. The function signature can be something like pg_get_database_ddl(oid, VARIADIC options text[]) I would include the pretty print into options too.Same comment as the one I gave for the Owner, if you are referring to these as options to the function.Let me elaborate a bit. As I suggested you can control the output with options. Why? Flexibility. Why am I suggesting such a general purpose implementation? See some of the use cases. 1. object DDL. Check DDL to recreate the object. It is not the exact DDL that the user informed but it produces the same result. 2. clone tool. Clone the objects to recreate the environment for another customer. These objects can be created in the same cluster or in another one. (Of course, global objects don't apply for the same cluster.) 3. dump tool. Dump the commands to recreate the existing objects. 4. diff tool. There are tools like pgquarrel [1] that queries the catalog and compare the results to create commands to turn the target database into the source database. The general purpose functions can be used if the object doesn't exist in the target database. (Of course, it doesn't apply for global objects but again it is a good UI to have all of these pg_get_OBJECT_ddl functions using the same approach.) 5. logical replication. These pg_get_OBJECT_ddl functions can be good candidates to be used in the initial schema replication and even in the DDL replication (if the object doesn't exist in the target database). The "options" parameter is to get the DDL command to serve any of these use cases. There are some properties in a certain object that you *don't* want for whatever reason. See some --no-OBJECT options in pg_dump. Let's say you don't want the TABLESPACE or the table access method while getting the CREATE TABLE DDL because it is different in the other database.
+1
I received a review comment suggesting the use of tabs. I also looked up PostgreSQL best practices on google, which recommend using tabs for indentation and spaces for alignment. I’m open to updating my code accordingly.I didn't check all of the possible output but the majority uses space instead of tabs. Check psql. If you check the git history (git log --grep=tabs), you will notice that tabs are removed from source code.
We should follow the pretty printing style in ruleutils.c, which uses spaces.
* permission. I don't think you need to check for permissions inside the function. I wouldn't want a different behavior than pg_dump(all). You can always adjust it in system_functions.sql.We’ve already had extensive discussions on this topic in the same email thread, and ultimately we decided to add the permission check.That's fair. Again, I expect that all of these pg_get_OBJECT_ddl functions use the same approach. We can always relax this restriction in the future.
+1
cheers
andrew
-- Andrew Dunstan EDB: https://www.enterprisedb.com
Re: [PATCH] Add pg_get_database_ddl() function to reconstruct CREATE DATABASE statement
Following Alvaro's suggestion to use DefElem syntax, I have modified the code to support key-value pairs.
I have attached two different patches :
v7-0001: Uses the double-dash syntax.
v7-0002: Uses the DefElem syntax.
Usage Example for double-dash approach:
SELECT pg_get_database_ddl('postgres', '--no-owner', '--no-tablespace'); -- Omit Owner and Tablespace clauses.
SELECT pg_get_database_ddl('postgres', 'pretty', '--with-defaults'); -- Includes clauses for parameters at their default values.
Usage Example for DefElem approach: The DefElem implementation supports various boolean values (no, false, 0) and is case-insensitive.
SELECT pg_get_database_ddl('postgres', 'owner=no', 'tablespace=false'); -- Omits Owner and Tablespace clauses.
SELECT pg_get_database_ddl('postgres', 'pretty', 'defaults=yes'); -- Includes clauses for parameters at their default values.
SELECT pg_get_database_ddl('postgres', 'pretty', 'defaults'); -- Includes clauses for parameters at their default values.
Please suggest which approach is preferred. The patches are ready for review.
1) Implement uint64 for the flags to provide capacity for up to 64 distinct options.
2) Refactorparse_ddl_optionsto return the flag set directly rather than using an out parameter.
Please find the attached v7 patch, which is now ready for review.On Wed, Jan 14, 2026 at 9:18 PM Akshay Joshi <akshay.joshi@enterprisedb.com> wrote:I have incorporated Euler’s changes, which modify the declaration and definition of the pg_get_database_ddl function. Please find the attached v6 patch, which is now ready for review. The following updates have been made:
Function signature updated to: pg_get_database_ddl(database_id regdatabase, VARIADIC ddl_options text[])
Added options --no-owner and --no-tablespace to omit the OWNER and TABLESPACE clauses from the reconstructed DDL.
Moved the "pretty" parameter into ddl_options for formatted output.
Properties such as ENCODING, LOCALE_PROVIDER, TABLESPACE, CONNECTION LIMIT, and ALLOW_CONNECTIONS are omitted if they are set to default values.
Introduced the --with-defaults option to include clauses for parameters even when they are at their default values.
Standardized formatting to use spaces instead of tabs.
Usage examples:
- SELECT pg_get_database_ddl('postgres'); // Non pretty-formatted DDL
- SELECT pg_get_database_ddl(16835); // Non pretty-formatted DDL
- SELECT pg_get_database_ddl('postgres', 'pretty'); // pretty-formatted DDL
- SELECT pg_get_database_ddl('postgres', '--no-owner', '--no-tablespace'); // Omits the Owner and Tablespace clause from the DDL.
- SELECT pg_get_database_ddl('postgres', 'pretty', '--with-defaults'); // Includes clauses for parameters that are currently at their default values.
On Thu, Jan 8, 2026 at 4:57 AM Andrew Dunstan <andrew@dunslane.net> wrote:
On 2025-12-12 Fr 10:19 AM, Euler Taveira wrote:On Fri, Dec 12, 2025, at 7:52 AM, Akshay Joshi wrote:On Thu, Dec 11, 2025 at 7:29 PM Euler Taveira <euler@eulerto.com> wrote:Is there any way to obtain the default values directly from the source code itself, or do I need to refer to the documentation? If we rely on the documentation and compare against that, then in the future, if the default values change, we would also need to update our logic accordingly.No, you need to check the documentation. If you are changing the default value, you are breaking compatibility; that rarely happens. If we are really concern about this fact, you can add a test case that creates the object without properties (all default values) and another with all default properties and then compare the output.
Maybe the function should have a VERBOSE option that emits all the defaults.
Constantly having to check the documentation for default values may feel annoying to some users. Some users run queries with parameters such as encoding, connection limit, and locale using their default values. When they call the pg_get_database_ddl function, it reconstructs the short command based on those defaults.Encoding and locale, ok but I doubt about connection limit. postgres=# SELECT current_user; current_user -------------- euler (1 row) postgres=# CREATE DATABASE foo; CREATE DATABASE postgres=# CREATE DATABASE bar OWNER euler; CREATE DATABASE When you are learning a new command, you generally don't set the default value for a property just to be correct. I'm not saying this function shouldn't include OWNER. I'm just suggesting it to be optional. See some arguments below.* OWNER. There is no guarantee that the owner exists in the cluster you will use this output. That's something that pg_dumpall treats separately (see above). Does it mean we should include the owner? No. We can make it an option.If I understand correctly, the owner should be an option provided by the caller of the function, and we reconstruct the Database DDL using that specified owner. Is that right? If so, then in my humble opinion, this is not truly a reconstruction of the existing database object.No. My idea is to have something like the pg_dump --no-owner option. This is important if you are transporting the objects from one cluster to another one. Owner might be different. That's why I'm suggesting it should be optional. It means flexibility. See pg_dump output format that always apply the OWNER as a separate ALTER command.
+1
* options. Since I mentioned options for some properties (owner, strategy, template), these properties can be accommodated as a VARIADIC argument. The function signature can be something like pg_get_database_ddl(oid, VARIADIC options text[]) I would include the pretty print into options too.Same comment as the one I gave for the Owner, if you are referring to these as options to the function.Let me elaborate a bit. As I suggested you can control the output with options. Why? Flexibility. Why am I suggesting such a general purpose implementation? See some of the use cases. 1. object DDL. Check DDL to recreate the object. It is not the exact DDL that the user informed but it produces the same result. 2. clone tool. Clone the objects to recreate the environment for another customer. These objects can be created in the same cluster or in another one. (Of course, global objects don't apply for the same cluster.) 3. dump tool. Dump the commands to recreate the existing objects. 4. diff tool. There are tools like pgquarrel [1] that queries the catalog and compare the results to create commands to turn the target database into the source database. The general purpose functions can be used if the object doesn't exist in the target database. (Of course, it doesn't apply for global objects but again it is a good UI to have all of these pg_get_OBJECT_ddl functions using the same approach.) 5. logical replication. These pg_get_OBJECT_ddl functions can be good candidates to be used in the initial schema replication and even in the DDL replication (if the object doesn't exist in the target database). The "options" parameter is to get the DDL command to serve any of these use cases. There are some properties in a certain object that you *don't* want for whatever reason. See some --no-OBJECT options in pg_dump. Let's say you don't want the TABLESPACE or the table access method while getting the CREATE TABLE DDL because it is different in the other database.
+1
I received a review comment suggesting the use of tabs. I also looked up PostgreSQL best practices on google, which recommend using tabs for indentation and spaces for alignment. I’m open to updating my code accordingly.I didn't check all of the possible output but the majority uses space instead of tabs. Check psql. If you check the git history (git log --grep=tabs), you will notice that tabs are removed from source code.
We should follow the pretty printing style in ruleutils.c, which uses spaces.
* permission. I don't think you need to check for permissions inside the function. I wouldn't want a different behavior than pg_dump(all). You can always adjust it in system_functions.sql.We’ve already had extensive discussions on this topic in the same email thread, and ultimately we decided to add the permission check.That's fair. Again, I expect that all of these pg_get_OBJECT_ddl functions use the same approach. We can always relax this restriction in the future.
+1
cheers
andrew
-- Andrew Dunstan EDB: https://www.enterprisedb.com
Re: [PATCH] Add pg_get_database_ddl() function to reconstruct CREATE DATABASE statement
In my previous email, I included two different patches (for two separate approaches) from different branches. As a result, CommitFest is indicating that a rebase is required.
Apologies for the inconvenience, I’m still getting familiar with the process.
Attached are the patches, layered one on top of the other, representing two approaches:
- Double Dash: v8-0001-Add-pg_get_database_ddl-function-to-reconstruct-double-dash.patch
- DefElem (Key-Value): v8-0002-Add-pg_get_database_ddl-function-to-reconstruct-DefElem.patch
I am now submitting the v8 patches, which are ready for review. Please let me know which approach you find more suitable and preferable.
All,
Following Alvaro's suggestion to use DefElem syntax, I have modified the code to support key-value pairs.
I have attached two different patches :
v7-0001: Uses the double-dash syntax.
v7-0002: Uses the DefElem syntax.
Usage Example for double-dash approach:
SELECT pg_get_database_ddl('postgres', '--no-owner', '--no-tablespace'); -- Omit Owner and Tablespace clauses.
SELECT pg_get_database_ddl('postgres', 'pretty', '--with-defaults'); -- Includes clauses for parameters at their default values.
Usage Example for DefElem approach: The DefElem implementation supports various boolean values (no, false, 0) and is case-insensitive.
SELECT pg_get_database_ddl('postgres', 'owner=no', 'tablespace=false'); -- Omits Owner and Tablespace clauses.
SELECT pg_get_database_ddl('postgres', 'pretty', 'defaults=yes'); -- Includes clauses for parameters at their default values.
SELECT pg_get_database_ddl('postgres', 'pretty', 'defaults'); -- Includes clauses for parameters at their default values.
Please suggest which approach is preferred. The patches are ready for review.On Fri, Jan 16, 2026 at 12:53 PM Akshay Joshi <akshay.joshi@enterprisedb.com> wrote:
1) Implement uint64 for the flags to provide capacity for up to 64 distinct options.
2) Refactorparse_ddl_optionsto return the flag set directly rather than using an out parameter.
Please find the attached v7 patch, which is now ready for review.On Wed, Jan 14, 2026 at 9:18 PM Akshay Joshi <akshay.joshi@enterprisedb.com> wrote:I have incorporated Euler’s changes, which modify the declaration and definition of the pg_get_database_ddl function. Please find the attached v6 patch, which is now ready for review. The following updates have been made:
Function signature updated to: pg_get_database_ddl(database_id regdatabase, VARIADIC ddl_options text[])
Added options --no-owner and --no-tablespace to omit the OWNER and TABLESPACE clauses from the reconstructed DDL.
Moved the "pretty" parameter into ddl_options for formatted output.
Properties such as ENCODING, LOCALE_PROVIDER, TABLESPACE, CONNECTION LIMIT, and ALLOW_CONNECTIONS are omitted if they are set to default values.
Introduced the --with-defaults option to include clauses for parameters even when they are at their default values.
Standardized formatting to use spaces instead of tabs.
Usage examples:
- SELECT pg_get_database_ddl('postgres'); // Non pretty-formatted DDL
- SELECT pg_get_database_ddl(16835); // Non pretty-formatted DDL
- SELECT pg_get_database_ddl('postgres', 'pretty'); // pretty-formatted DDL
- SELECT pg_get_database_ddl('postgres', '--no-owner', '--no-tablespace'); // Omits the Owner and Tablespace clause from the DDL.
- SELECT pg_get_database_ddl('postgres', 'pretty', '--with-defaults'); // Includes clauses for parameters that are currently at their default values.
On Thu, Jan 8, 2026 at 4:57 AM Andrew Dunstan <andrew@dunslane.net> wrote:
On 2025-12-12 Fr 10:19 AM, Euler Taveira wrote:On Fri, Dec 12, 2025, at 7:52 AM, Akshay Joshi wrote:On Thu, Dec 11, 2025 at 7:29 PM Euler Taveira <euler@eulerto.com> wrote:Is there any way to obtain the default values directly from the source code itself, or do I need to refer to the documentation? If we rely on the documentation and compare against that, then in the future, if the default values change, we would also need to update our logic accordingly.No, you need to check the documentation. If you are changing the default value, you are breaking compatibility; that rarely happens. If we are really concern about this fact, you can add a test case that creates the object without properties (all default values) and another with all default properties and then compare the output.
Maybe the function should have a VERBOSE option that emits all the defaults.
Constantly having to check the documentation for default values may feel annoying to some users. Some users run queries with parameters such as encoding, connection limit, and locale using their default values. When they call the pg_get_database_ddl function, it reconstructs the short command based on those defaults.Encoding and locale, ok but I doubt about connection limit. postgres=# SELECT current_user; current_user -------------- euler (1 row) postgres=# CREATE DATABASE foo; CREATE DATABASE postgres=# CREATE DATABASE bar OWNER euler; CREATE DATABASE When you are learning a new command, you generally don't set the default value for a property just to be correct. I'm not saying this function shouldn't include OWNER. I'm just suggesting it to be optional. See some arguments below.* OWNER. There is no guarantee that the owner exists in the cluster you will use this output. That's something that pg_dumpall treats separately (see above). Does it mean we should include the owner? No. We can make it an option.If I understand correctly, the owner should be an option provided by the caller of the function, and we reconstruct the Database DDL using that specified owner. Is that right? If so, then in my humble opinion, this is not truly a reconstruction of the existing database object.No. My idea is to have something like the pg_dump --no-owner option. This is important if you are transporting the objects from one cluster to another one. Owner might be different. That's why I'm suggesting it should be optional. It means flexibility. See pg_dump output format that always apply the OWNER as a separate ALTER command.
+1
* options. Since I mentioned options for some properties (owner, strategy, template), these properties can be accommodated as a VARIADIC argument. The function signature can be something like pg_get_database_ddl(oid, VARIADIC options text[]) I would include the pretty print into options too.Same comment as the one I gave for the Owner, if you are referring to these as options to the function.Let me elaborate a bit. As I suggested you can control the output with options. Why? Flexibility. Why am I suggesting such a general purpose implementation? See some of the use cases. 1. object DDL. Check DDL to recreate the object. It is not the exact DDL that the user informed but it produces the same result. 2. clone tool. Clone the objects to recreate the environment for another customer. These objects can be created in the same cluster or in another one. (Of course, global objects don't apply for the same cluster.) 3. dump tool. Dump the commands to recreate the existing objects. 4. diff tool. There are tools like pgquarrel [1] that queries the catalog and compare the results to create commands to turn the target database into the source database. The general purpose functions can be used if the object doesn't exist in the target database. (Of course, it doesn't apply for global objects but again it is a good UI to have all of these pg_get_OBJECT_ddl functions using the same approach.) 5. logical replication. These pg_get_OBJECT_ddl functions can be good candidates to be used in the initial schema replication and even in the DDL replication (if the object doesn't exist in the target database). The "options" parameter is to get the DDL command to serve any of these use cases. There are some properties in a certain object that you *don't* want for whatever reason. See some --no-OBJECT options in pg_dump. Let's say you don't want the TABLESPACE or the table access method while getting the CREATE TABLE DDL because it is different in the other database.
+1
I received a review comment suggesting the use of tabs. I also looked up PostgreSQL best practices on google, which recommend using tabs for indentation and spaces for alignment. I’m open to updating my code accordingly.I didn't check all of the possible output but the majority uses space instead of tabs. Check psql. If you check the git history (git log --grep=tabs), you will notice that tabs are removed from source code.
We should follow the pretty printing style in ruleutils.c, which uses spaces.
* permission. I don't think you need to check for permissions inside the function. I wouldn't want a different behavior than pg_dump(all). You can always adjust it in system_functions.sql.We’ve already had extensive discussions on this topic in the same email thread, and ultimately we decided to add the permission check.That's fair. Again, I expect that all of these pg_get_OBJECT_ddl functions use the same approach. We can always relax this restriction in the future.
+1
cheers
andrew
-- Andrew Dunstan EDB: https://www.enterprisedb.com
Re: [PATCH] Add pg_get_database_ddl() function to reconstruct CREATE DATABASE statement
On Wed, Jan 21, 2026 at 03:01:44PM +0530, Akshay Joshi wrote: > In my previous email, I included two different patches (for two separate > approaches) from different branches. As a result, CommitFest is indicating > that a rebase is required. > > Apologies for the inconvenience, I’m still getting familiar with the > process. > > Attached are the patches, layered one on top of the other, representing two > approaches: > > - *Double Dash*: > v8-0001-Add-pg_get_database_ddl-function-to-reconstruct-double-dash.patch > - *DefElem (Key-Value)*: > v8-0002-Add-pg_get_database_ddl-function-to-reconstruct-DefElem.patch > > I am now submitting the *v8 patches*, which are ready for review. Please > let me know which approach you find more suitable and preferable. I have some documentation style suggestions that I've also attached as a patch: * Update the pg_get_database_ddl() definitions in the func-info table to list the multiple database way to reference a database, similar to pg_database_size() * Shorten the argument description for OID and name, again similar to pg_database_size()'s style * Shorten ddl_options argument description to simply options, to match the style of how other functions in the docs describe optional parameters * Remove the redundant explanation of the optional parameters in the individual function's description, and instead refer the reader to the explanation following the table * Some word choice and phrasing changes in the pg_get_database_ddl function description to be grammatically closer to something like pg_restore_relation_stats() I hope that is helpful... Regards, Mark -- Mark Wong EDB https://enterprisedb.com
Re: [PATCH] Add pg_get_database_ddl() function to reconstruct CREATE DATABASE statement
On Wed, Jan 21, 2026 at 3:02 PM Akshay Joshi
wrote:
>
> In my previous email, I included two different patches (for two separate approaches) from different branches. As a result, CommitFest is indicating that a rebase is required.
>
> Apologies for the inconvenience, I’m still getting familiar with the process.
>
> Attached are the patches, layered one on top of the other, representing two approaches:
>
> Double Dash: v8-0001-Add-pg_get_database_ddl-function-to-reconstruct-double-dash.patch
> DefElem (Key-Value): v8-0002-Add-pg_get_database_ddl-function-to-reconstruct-DefElem.patch
>
> I am now submitting the v8 patches, which are ready for review. Please let me know which approach you find more suitable and preferable.
>
>
I took a quick look at the v8 patches. I am not yet sure which
approach is superior, but here are some review for 0001:
+
+ pretty: Adds newlines and indentation for
better readability.
+
Could we use phrasing similar to what is used elsewhere in the
documentation? For reference, please see sgml/func/func-info.sgml
--
+
+
+ --no-owner: Omits the
OWNER clause from
+ the reconstructed statement.
+
+
+
+
+ --no-tablespace: Omits the
TABLESPACE clause.
+
+
+
+
+ --with-defaults: Includes clauses for
parameters that are
+ currently at their default values (e.g., CONNECTION
LIMIT -1),
+ which are normally omitted for brevity.
+
+
Formatting is inconsistent; some options include the -- prefix while
others do not. I think we should simply avoid the prefix entirely.
--
/* Standard conversion of a "bool pretty" option to detailed flags */
#define GET_PRETTY_FLAGS(pretty) \
((pretty) ? (PRETTYFLAG_PAREN | PRETTYFLAG_INDENT | PRETTYFLAG_SCHEMA) \
: PRETTYFLAG_INDENT)
+#define GET_DDL_PRETTY_FLAGS(pretty) \
+ ((pretty) ? (PRETTYFLAG_PAREN | PRETTYFLAG_INDENT | PRETTYFLAG_SCHEMA) \
+ : 0)
+
I am a bit confused -- why do we need a separate
GET_DDL_PRETTY_FLAGS() function?
--
+CREATE OR REPLACE FUNCTION
+ pg_get_database_ddl(database_id regdatabase, VARIADIC ddl_options
text[] DEFAULT '{}')
+RETURNS text
+LANGUAGE internal
+AS 'pg_get_database_ddl';
+
I don't see any REVOKE EXECUTE ON FUNCTION for this function.
--
+/**
+ * parse_ddl_options - Generic helper to parse variadic text options
+ * ddl_options: The ArrayType from PG_GETARG_ARRAYTYPE_P
+ * flags: Bitmask to set options while parsing DDL options.
+ */
+static uint64
+parse_ddl_options(ArrayType *ddl_options)
I believe this should be in a separate patch so that it can be reused
by others working on similar projects. It shouldn't be specific to
this patch.
--
+ /* If it's with defaults, we skip default encoding check */
+ if (is_with_defaults ||
+ (pg_strcasecmp(pg_encoding_to_char(dbform->encoding),
+ DDL_DEFAULTS.DATABASE.ENCODING) != 0))
Comment doesn't quite match the logic in the condition.
Regards,
Amul
Re: [PATCH] Add pg_get_database_ddl() function to reconstruct CREATE DATABASE statement
On Mon, Feb 23, 2026 at 6:50 PM Amul Sul wrote:
>
> On Wed, Jan 21, 2026 at 3:02 PM Akshay Joshi
> wrote:
> >
> > In my previous email, I included two different patches (for two separate approaches) from different branches. As a result, CommitFest is indicating that a rebase is required.
> >
> > Apologies for the inconvenience, I’m still getting familiar with the process.
> >
> > Attached are the patches, layered one on top of the other, representing two approaches:
> >
> > Double Dash: v8-0001-Add-pg_get_database_ddl-function-to-reconstruct-double-dash.patch
> > DefElem (Key-Value): v8-0002-Add-pg_get_database_ddl-function-to-reconstruct-DefElem.patch
> >
> > I am now submitting the v8 patches, which are ready for review. Please let me know which approach you find more suitable and preferable.
> >
> >
>
> I took a quick look at the v8 patches. I am not yet sure which
> approach is superior, but here are some review for 0001:
>
> +
> + pretty: Adds newlines and indentation for
> better readability.
> +
>
> Could we use phrasing similar to what is used elsewhere in the
> documentation? For reference, please see sgml/func/func-info.sgml
> --
>
> +
> +
> + --no-owner: Omits the
> OWNER clause from
> + the reconstructed statement.
> +
> +
> +
> +
> + --no-tablespace: Omits the
> TABLESPACE clause.
> +
> +
> +
> +
> + --with-defaults: Includes clauses for
> parameters that are
> + currently at their default values (e.g., CONNECTION
> LIMIT -1),
> + which are normally omitted for brevity.
> +
> +
>
> Formatting is inconsistent; some options include the -- prefix while
> others do not. I think we should simply avoid the prefix entirely.
Mark Wong has provided a patch (v8-0003-doc-suggestions.patch) on top
of my changes, which should resolve the issues mentioned above.
> --
>
> /* Standard conversion of a "bool pretty" option to detailed flags */
> #define GET_PRETTY_FLAGS(pretty) \
> ((pretty) ? (PRETTYFLAG_PAREN | PRETTYFLAG_INDENT | PRETTYFLAG_SCHEMA) \
> : PRETTYFLAG_INDENT)
>
> +#define GET_DDL_PRETTY_FLAGS(pretty) \
> + ((pretty) ? (PRETTYFLAG_PAREN | PRETTYFLAG_INDENT | PRETTYFLAG_SCHEMA) \
> + : 0)
> +
>
> I am a bit confused -- why do we need a separate
> GET_DDL_PRETTY_FLAGS() function?
> --
If we use the existing GET_PRETTY_FLAGS, it returns PRETTYFLAG_INDENT
even when pretty is false. However, for Reconstruction DDL, do not
apply indentation if pretty is false.
>
> +CREATE OR REPLACE FUNCTION
> + pg_get_database_ddl(database_id regdatabase, VARIADIC ddl_options
> text[] DEFAULT '{}')
> +RETURNS text
> +LANGUAGE internal
> +AS 'pg_get_database_ddl';
> +
>
> I don't see any REVOKE EXECUTE ON FUNCTION for this function.
> --
Other pg_get_*def functions don't have REVOKE: Functions like
pg_get_viewdef, pg_get_indexdef, pg_get_functiondef,
pg_get_triggerdef, and pg_get_constraintdef are all publicly
accessible none have it. pg_get_database_ddl is purely informational;
it reconstructs CREATE DATABASE DDL from data already visible in the
pg_database system catalog. Any user who can query pg_database already
has access to this information.
I can add, if the above explanation is wrong. Just let me know.
>
> +/**
> + * parse_ddl_options - Generic helper to parse variadic text options
> + * ddl_options: The ArrayType from PG_GETARG_ARRAYTYPE_P
> + * flags: Bitmask to set options while parsing DDL options.
> + */
> +static uint64
> +parse_ddl_options(ArrayType *ddl_options)
>
> I believe this should be in a separate patch so that it can be reused
> by others working on similar projects. It shouldn't be specific to
> this patch.
> --
I have added two generic functions, parse_ddl_options and
get_formatted_string, which will be required by future
pg_get__ddl patches. Is it acceptable to submit a patch
containing only these generic functions before they are actively used?
>
> + /* If it's with defaults, we skip default encoding check */
> + if (is_with_defaults ||
> + (pg_strcasecmp(pg_encoding_to_char(dbform->encoding),
> + DDL_DEFAULTS.DATABASE.ENCODING) != 0))
>
>
> Comment doesn't quite match the logic in the condition.
Will update this in my next patch. When we decide which approach to follow:
1) Double Dash:
v8-0001-Add-pg_get_database_ddl-function-to-reconstruct-double-dash.patch
2) DefElem (Key-Value):
v8-0002-Add-pg_get_database_ddl-function-to-reconstruct-DefElem.patch
>
> Regards,
> Amul
Re: [PATCH] Add pg_get_database_ddl() function to reconstruct CREATE DATABASE statement
On Mon, Feb 23, 2026 at 7:27 PM Akshay Joshi
wrote:
>
> On Mon, Feb 23, 2026 at 6:50 PM Amul Sul wrote:
> > [....]
> > /* Standard conversion of a "bool pretty" option to detailed flags */
> > #define GET_PRETTY_FLAGS(pretty) \
> > ((pretty) ? (PRETTYFLAG_PAREN | PRETTYFLAG_INDENT | PRETTYFLAG_SCHEMA) \
> > : PRETTYFLAG_INDENT)
> >
> > +#define GET_DDL_PRETTY_FLAGS(pretty) \
> > + ((pretty) ? (PRETTYFLAG_PAREN | PRETTYFLAG_INDENT | PRETTYFLAG_SCHEMA) \
> > + : 0)
> > +
> >
> > I am a bit confused -- why do we need a separate
> > GET_DDL_PRETTY_FLAGS() function?
> > --
>
> If we use the existing GET_PRETTY_FLAGS, it returns PRETTYFLAG_INDENT
> even when pretty is false. However, for Reconstruction DDL, do not
> apply indentation if pretty is false.
>
However, in the patch, you're calling it conditionally; specifically,
when the pretty argument is true, it gets called with a value of 1.
Also, instead of 1 it should be 'true'.
> >
> > +CREATE OR REPLACE FUNCTION
> > + pg_get_database_ddl(database_id regdatabase, VARIADIC ddl_options
> > text[] DEFAULT '{}')
> > +RETURNS text
> > +LANGUAGE internal
> > +AS 'pg_get_database_ddl';
> > +
> >
> > I don't see any REVOKE EXECUTE ON FUNCTION for this function.
> > --
>
> Other pg_get_*def functions don't have REVOKE: Functions like
> pg_get_viewdef, pg_get_indexdef, pg_get_functiondef,
> pg_get_triggerdef, and / are all publicly
> accessible none have it. pg_get_database_ddl is purely informational;
> it reconstructs CREATE DATABASE DDL from data already visible in the
> pg_database system catalog. Any user who can query pg_database already
> has access to this information.
>
> I can add, if the above explanation is wrong. Just let me know.
>
I think you are correct -- not needed.
> >
> > +/**
> > + * parse_ddl_options - Generic helper to parse variadic text options
> > + * ddl_options: The ArrayType from PG_GETARG_ARRAYTYPE_P
> > + * flags: Bitmask to set options while parsing DDL options.
> > + */
> > +static uint64
> > +parse_ddl_options(ArrayType *ddl_options)
> >
> > I believe this should be in a separate patch so that it can be reused
> > by others working on similar projects. It shouldn't be specific to
> > this patch.
> > --
>
> I have added two generic functions, parse_ddl_options and
> get_formatted_string, which will be required by future
> pg_get__ddl patches. Is it acceptable to submit a patch
> containing only these generic functions before they are actively used?
>
Yes, that should be a completely separate patch. You can submit it in
this thread as part of the same series.
> >
> > + /* If it's with defaults, we skip default encoding check */
> > + if (is_with_defaults ||
> > + (pg_strcasecmp(pg_encoding_to_char(dbform->encoding),
> > + DDL_DEFAULTS.DATABASE.ENCODING) != 0))
> >
> >
> > Comment doesn't quite match the logic in the condition.
>
> Will update this in my next patch. When we decide which approach to follow:
> 1) Double Dash:
> v8-0001-Add-pg_get_database_ddl-function-to-reconstruct-double-dash.patch
> 2) DefElem (Key-Value):
> v8-0002-Add-pg_get_database_ddl-function-to-reconstruct-DefElem.patch
>
That’s a bit subjective, as different people will likely have
different opinions. I prefer the first version without the -- prefix,
since the counterpart would be the default behavior. For example, if
"no-tablespace" is not specified, the tablespace would be included in
the DDL dump by default.
Regards,
Amul
Re: [PATCH] Add pg_get_database_ddl() function to reconstruct CREATE DATABASE statement
On 2026-Feb-24, Amul Sul wrote: > On Mon, Feb 23, 2026 at 7:27 PM Akshay Joshi > wrote: > > > > On Mon, Feb 23, 2026 at 6:50 PM Amul Sul wrote: > > > > > > + /* If it's with defaults, we skip default encoding check */ > > > + if (is_with_defaults || > > > + (pg_strcasecmp(pg_encoding_to_char(dbform->encoding), > > > + DDL_DEFAULTS.DATABASE.ENCODING) != 0)) > > > > > > > > > Comment doesn't quite match the logic in the condition. > > > > Will update this in my next patch. When we decide which approach to follow: > > 1) Double Dash: > > v8-0001-Add-pg_get_database_ddl-function-to-reconstruct-double-dash.patch > > 2) DefElem (Key-Value): > > v8-0002-Add-pg_get_database_ddl-function-to-reconstruct-DefElem.patch > > That’s a bit subjective, as different people will likely have > different opinions. I prefer the first version without the -- prefix, > since the counterpart would be the default behavior. For example, if > "no-tablespace" is not specified, the tablespace would be included in > the DDL dump by default. I'm surprised to not have seen an update on this topic following the discovery by Mark Wong that commit d32d1463995c (in branch 18) already established a convention for passing arguments to functions: use argument pairs to variadic functions, the way pg_restore_relation_stats() and pg_restore_attribute_stats() work. While I like my previous suggestion of using DefElems better, I think it's more sensible to follow this established precedent and not innovate on this. Regards -- Álvaro Herrera 48°01'N 7°57'E — https://www.EnterpriseDB.com/
Re: [PATCH] Add pg_get_database_ddl() function to reconstruct CREATE DATABASE statement
On Wed, Feb 25, 2026, at 8:53 AM, Álvaro Herrera wrote: > > I'm surprised to not have seen an update on this topic following the > discovery by Mark Wong that commit d32d1463995c (in branch 18) already > established a convention for passing arguments to functions: use argument > pairs to variadic functions, the way pg_restore_relation_stats() and > pg_restore_attribute_stats() work. While I like my previous suggestion > of using DefElems better, I think it's more sensible to follow this > established precedent and not innovate on this. > This convention is much older than the referred commit. It predates from the logical decoding (commit b89e151054a0). See pg_logical_slot_get_changes_guts() that is an internal function for pg_logical_slot_FOO_changes(). It seems a good idea to have a central function to validate the variadic parameter for all of these functions. -- Euler Taveira EDB https://www.enterprisedb.com/
Re: [PATCH] Add pg_get_database_ddl() function to reconstruct CREATE DATABASE statement
This patch incorporates Mark Wong’s documentation updates, Amul’s one review comment, and the majority of Euler’s comments.
New changes:
- Supports flexible DDL options as key-value pairs:
- pretty - Format output for readability
- owner - Include OWNER clause
- tablespace - Include TABLESPACE clause
- defaults - Include parameters even if it is set to default value.
- Option values accept: 'yes'/'on'/true/'1' (or their negatives)
Usage Examples:
-- Basic usage with options
SELECT pg_get_database_ddl('mydb', 'owner', 'yes', 'defaults', 'yes');
-- Pretty-printed output without owner and tablespace
SELECT pg_get_database_ddl('mydb', 'owner', 'no', 'tablespace', 'no', 'pretty', 'on');
-- Using boolean values
SELECT pg_get_database_ddl('mydb', 'owner', false, 'defaults', true);
-- Using OID
SELECT pg_get_database_ddl(16384, 'pretty', 'yes');
Note: To keep things clean, I’ve moved the logic into two generic functions (get_formatted_string and parse_ddl_options) and a common DDLOptionDef struct. This should simplify the work for the rest of the pg_get_<object>_ddl patches.
Attached is the v9 patch which is ready for review.
On Wed, Feb 25, 2026, at 8:53 AM, Álvaro Herrera wrote:
>
> I'm surprised to not have seen an update on this topic following the
> discovery by Mark Wong that commit d32d1463995c (in branch 18) already
> established a convention for passing arguments to functions: use argument
> pairs to variadic functions, the way pg_restore_relation_stats() and
> pg_restore_attribute_stats() work. While I like my previous suggestion
> of using DefElems better, I think it's more sensible to follow this
> established precedent and not innovate on this.
>
This convention is much older than the referred commit. It predates from the
logical decoding (commit b89e151054a0). See pg_logical_slot_get_changes_guts()
that is an internal function for pg_logical_slot_FOO_changes(). It seems a
good idea to have a central function to validate the variadic parameter for all
of these functions.
--
Euler Taveira
EDB https://www.enterprisedb.com/
Re: [PATCH] Add pg_get_database_ddl() function to reconstruct CREATE DATABASE statement
On Fri, 27 Feb 2026 at 17:52, Akshay Joshi wrote:
> Following suggestions from Alvaro and Mark, I have re-implemented this feature using variadic
> function argument pairs.
> This patch incorporates Mark Wong’s documentation updates, Amul’s one review comment, and the
> majority of Euler’s comments.
>
> New changes:
> - Supports flexible DDL options as key-value pairs:
> - pretty - Format output for readability
> - owner - Include OWNER clause
> - tablespace - Include TABLESPACE clause
> - defaults - Include parameters even if it is set to default value.
> - Option values accept: 'yes'/'on'/true/'1' (or their negatives)
>
> Usage Examples:
> -- Basic usage with options
> SELECT pg_get_database_ddl('mydb', 'owner', 'yes', 'defaults', 'yes');
> -- Pretty-printed output without owner and tablespace
> SELECT pg_get_database_ddl('mydb', 'owner', 'no', 'tablespace', 'no', 'pretty', 'on');
> -- Using boolean values
> SELECT pg_get_database_ddl('mydb', 'owner', false, 'defaults', true);
> -- Using OID
> SELECT pg_get_database_ddl(16384, 'pretty', 'yes');
>
> Note: To keep things clean, I’ve moved the logic into two generic functions (get_formatted_string
> and parse_ddl_options) and a common DDLOptionDef struct. This should simplify the work for the
> rest of the pg_get__ddl patches.
>
> Attached is the v9 patch which is ready for review.
>
> On Thu, Feb 26, 2026 at 2:49 AM Euler Taveira wrote:
>
> On Wed, Feb 25, 2026, at 8:53 AM, Álvaro Herrera wrote:
> >
> > I'm surprised to not have seen an update on this topic following the
> > discovery by Mark Wong that commit d32d1463995c (in branch 18) already
> > established a convention for passing arguments to functions: use argument
> > pairs to variadic functions, the way pg_restore_relation_stats() and
> > pg_restore_attribute_stats() work. While I like my previous suggestion
> > of using DefElems better, I think it's more sensible to follow this
> > established precedent and not innovate on this.
> >
>
> This convention is much older than the referred commit. It predates from the
> logical decoding (commit b89e151054a0). See pg_logical_slot_get_changes_guts()
> that is an internal function for pg_logical_slot_FOO_changes(). It seems a
> good idea to have a central function to validate the variadic parameter for all
> of these functions.
>
Thanks for updating the patch, here are some comments on v9.
1.
+ uint64 flag; /* Flag to set */
Do we actually need 64 bits for this flag field?
2.
+ /* Indent with spaces */
+ for (int i = 0; i < nSpaces; i++)
+ {
+ appendStringInfoChar(buf, ' ');
+ }
How about using appendStringInfoSpaces(buf, nSpaces) instead?
3.
+ /* If no options provided (VARIADIC NULL), return the empty bitmask */
+ if (nargs < 0)
+ return flags;
+
+ ...
+
+ /* No arguments provided */
+ if (nargs == 0)
+ return flags;
These two conditions are identical — how about just `if (nargs <= 0)`?
4.
+ /* Arguments must come in name/value pairs */
+ if (nargs % 2 != 0)
+ ereport(ERROR,
+ (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
+ errmsg("argument list must have even number of elements"),
+ errhint("The arguments of %s must consist of alternating keys and values.",
+ "pg_get_database_ddl()")));
Should we align this with stats_fill_fcinfo_from_arg_pairs()?
Suggested wording:
errmsg("variadic arguments must be name/value pairs")
5.
+ /* Key must not be null */
+ if (nulls[i])
+ ereport(ERROR,
+ (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
+ errmsg("argument %d: key must not be null", i + 1)));
+
Suggested wording:
errmsg("name at variadic position %d is null")
6.
+ /* Key must be text type */
+ if (types[i] != TEXTOID)
+ ereport(ERROR,
+ (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
+ errmsg("argument %d: key must be text type", i + 1)));
Suggested wording:
errmsg("name at variadic position %d has type %s, expected type %s")
7.
+ ereport(ERROR,
+ (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
+ errmsg("argument %d: value for key \"%s\" must be boolean or text type",
+ i + 2, name)));
Suggested wording:
errmsg("argument \"%s\" has type %s, execpted type boolean or text")
See stats_check_arg_type().
8.
+ for (i = 0; i < nargs; i += 2)
+ {
We can narrow the scope of `i` by declaring it in the for initializer.
9.
+ {
+ bool found = false;
+ int j;
+
+ for (j = 0; j < lengthof(ddl_option_defs); j++)
+ {
Minor style improvements:
- We can (and should) declare `j` inside its for-loop initializer, just like `i`.
- Move the declaration of `found` up to the top of the outer for-loop scope.
This allows us to remove the unnecessary braces around the loop body.
--
Regards,
Japin Li
ChengDu WenWu Information Technology Co., Ltd.
Re: [PATCH] Add pg_get_database_ddl() function to reconstruct CREATE DATABASE statement
On Wed, 04 Mar 2026 at 16:39, Japin Li wrote:
> On Fri, 27 Feb 2026 at 17:52, Akshay Joshi wrote:
>> Following suggestions from Alvaro and Mark, I have re-implemented this feature using variadic
>> function argument pairs.
>> This patch incorporates Mark Wong’s documentation updates, Amul’s one review comment, and the
>> majority of Euler’s comments.
>>
>> New changes:
>> - Supports flexible DDL options as key-value pairs:
>> - pretty - Format output for readability
>> - owner - Include OWNER clause
>> - tablespace - Include TABLESPACE clause
>> - defaults - Include parameters even if it is set to default value.
>> - Option values accept: 'yes'/'on'/true/'1' (or their negatives)
>>
>> Usage Examples:
>> -- Basic usage with options
>> SELECT pg_get_database_ddl('mydb', 'owner', 'yes', 'defaults', 'yes');
>> -- Pretty-printed output without owner and tablespace
>> SELECT pg_get_database_ddl('mydb', 'owner', 'no', 'tablespace', 'no', 'pretty', 'on');
>> -- Using boolean values
>> SELECT pg_get_database_ddl('mydb', 'owner', false, 'defaults', true);
>> -- Using OID
>> SELECT pg_get_database_ddl(16384, 'pretty', 'yes');
>>
>> Note: To keep things clean, I’ve moved the logic into two generic functions (get_formatted_string
>> and parse_ddl_options) and a common DDLOptionDef struct. This should simplify the work for the
>> rest of the pg_get__ddl patches.
>>
>> Attached is the v9 patch which is ready for review.
>>
>> On Thu, Feb 26, 2026 at 2:49 AM Euler Taveira wrote:
>>
>> On Wed, Feb 25, 2026, at 8:53 AM, Álvaro Herrera wrote:
>> >
>> > I'm surprised to not have seen an update on this topic following the
>> > discovery by Mark Wong that commit d32d1463995c (in branch 18) already
>> > established a convention for passing arguments to functions: use argument
>> > pairs to variadic functions, the way pg_restore_relation_stats() and
>> > pg_restore_attribute_stats() work. While I like my previous suggestion
>> > of using DefElems better, I think it's more sensible to follow this
>> > established precedent and not innovate on this.
>> >
>>
>> This convention is much older than the referred commit. It predates from the
>> logical decoding (commit b89e151054a0). See pg_logical_slot_get_changes_guts()
>> that is an internal function for pg_logical_slot_FOO_changes(). It seems a
>> good idea to have a central function to validate the variadic parameter for all
>> of these functions.
>>
>
> Thanks for updating the patch, here are some comments on v9.
>
> 1.
> + uint64 flag; /* Flag to set */
>
> Do we actually need 64 bits for this flag field?
>
> 2.
> + /* Indent with spaces */
> + for (int i = 0; i < nSpaces; i++)
> + {
> + appendStringInfoChar(buf, ' ');
> + }
>
> How about using appendStringInfoSpaces(buf, nSpaces) instead?
>
> 3.
> + /* If no options provided (VARIADIC NULL), return the empty bitmask */
> + if (nargs < 0)
> + return flags;
> +
> + ...
> +
> + /* No arguments provided */
> + if (nargs == 0)
> + return flags;
>
> These two conditions are identical — how about just `if (nargs <= 0)`?
>
> 4.
> + /* Arguments must come in name/value pairs */
> + if (nargs % 2 != 0)
> + ereport(ERROR,
> + (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
> + errmsg("argument list must have even number of elements"),
> + errhint("The arguments of %s must consist of alternating keys and values.",
> + "pg_get_database_ddl()")));
>
> Should we align this with stats_fill_fcinfo_from_arg_pairs()?
>
> Suggested wording:
> errmsg("variadic arguments must be name/value pairs")
>
> 5.
> + /* Key must not be null */
> + if (nulls[i])
> + ereport(ERROR,
> + (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
> + errmsg("argument %d: key must not be null", i + 1)));
> +
>
> Suggested wording:
>
> errmsg("name at variadic position %d is null")
>
> 6.
> + /* Key must be text type */
> + if (types[i] != TEXTOID)
> + ereport(ERROR,
> + (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
> + errmsg("argument %d: key must be text type", i + 1)));
>
> Suggested wording:
>
> errmsg("name at variadic position %d has type %s, expected type %s")
>
> 7.
> + ereport(ERROR,
> + (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
> + errmsg("argument %d: value for key \"%s\" must be boolean or text type",
> + i + 2, name)));
>
> Suggested wording:
>
> errmsg("argument \"%s\" has type %s, execpted type boolean or text")
>
> See stats_check_arg_type().
>
> 8.
> + for (i = 0; i < nargs; i += 2)
> + {
>
> We can narrow the scope of `i` by declaring it in the for initializer.
>
> 9.
> + {
> + bool found = false;
> + int j;
> +
> + for (j = 0; j < lengthof(ddl_option_defs); j++)
> + {
>
> Minor style improvements:
>
> - We can (and should) declare `j` inside its for-loop initializer, just like `i`.
> - Move the declaration of `found` up to the top of the outer for-loop scope.
> This allows us to remove the unnecessary braces around the loop body.
>
After playing with this patch, I’m seeing the following output:
# select pg_get_database_ddl('postgres'::regdatabase, 'defaults', true, 'pretty', true, 'pretty', false);
pg_get_database_ddl
------------------------------------
CREATE DATABASE postgres +
WITH +
OWNER = japin +
ENCODING = 'UTF8' +
LC_COLLATE = 'en_US.UTF-8'+
LC_CTYPE = 'en_US.UTF-8' +
COLLATION_VERSION = '2.39'+
LOCALE_PROVIDER = libc +
TABLESPACE = pg_default +
ALLOW_CONNECTIONS = true +
CONNECTION LIMIT = -1;
(1 row)
Is this the expected behavior?
--
Regards,
Japin Li
ChengDu WenWu Information Technology Co., Ltd.
Re: [PATCH] Add pg_get_database_ddl() function to reconstruct CREATE DATABASE statement
On 2026-Mar-04, Japin Li wrote:
> After playing with this patch, I’m seeing the following output:
>
> # select pg_get_database_ddl('postgres'::regdatabase, 'defaults', true, 'pretty', true, 'pretty', false);
I think this should throw an error that 'pretty' was contradictorily
specified twice. (Maybe also an error if an option appears twice,
period.)
--
Álvaro Herrera 48°01'N 7°57'E — https://www.EnterpriseDB.com/
Re: [PATCH] Add pg_get_database_ddl() function to reconstruct CREATE DATABASE statement
Thanks for the review, Japin. I’ve addressed all of your comments. I also added a check to throw an error if an option appears more than once.
Attached is the v10 patch, now ready for further review.
On 2026-Mar-04, Japin Li wrote:
> After playing with this patch, I’m seeing the following output:
>
> # select pg_get_database_ddl('postgres'::regdatabase, 'defaults', true, 'pretty', true, 'pretty', false);
I think this should throw an error that 'pretty' was contradictorily
specified twice. (Maybe also an error if an option appears twice,
period.)
--
Álvaro Herrera 48°01'N 7°57'E — https://www.EnterpriseDB.com/
Re: [PATCH] Add pg_get_database_ddl() function to reconstruct CREATE DATABASE statement
On Wed, 04 Mar 2026 at 18:29, Akshay Joshi wrote:
> Thanks for the review, Japin. I’ve addressed all of your comments. I also added a check to throw an error if an option
> appears more than once.
>
> Attached is the v10 patch, now ready for further review.
>
Thanks for updating the patch. Here are some comments on v10.
1.
+ * db_oid - OID/Name of the database for which to generate the DDL.
Should the comment be updated? The code only accepts an OID for `db_oid`,
database names are not supported.
2.
+ /* Set the OWNER in the DDL if owner is not omitted */
+ if (OidIsValid(dbform->datdba) && !(ddl_flags & PG_DDL_NO_OWNER))
+ {
+ get_formatted_string(&buf, pretty_flags, 8, "OWNER = %s",
+ quote_identifier(dbowner));
+ }
`dbowner` is only needed inside this `if` — how about declaring it there to
reduce its scope?
3.
+ /* If is_with_defaults is true, then we skip default encoding check */
+ if (is_with_defaults ||
+ (pg_strcasecmp(pg_encoding_to_char(dbform->encoding),
+ DDL_DEFAULTS.DATABASE.ENCODING) != 0))
+ {
+ get_formatted_string(&buf, pretty_flags, 8, "ENCODING = %s",
+ quote_literal_cstr(
+ pg_encoding_to_char(dbform->encoding)));
+ }
How about cache the result of `pg_encoding_to_char()` in a local variable to
avoid calling it twice?
--
Regards,
Japin Li
ChengDu WenWu Information Technology Co., Ltd.
Re: [PATCH] Add pg_get_database_ddl() function to reconstruct CREATE DATABASE statement
I’ve addressed all of your comments.
Attached is the v11 patch, now ready for further review.
On Wed, 04 Mar 2026 at 18:29, Akshay Joshi <akshay.joshi@enterprisedb.com> wrote:
> Thanks for the review, Japin. I’ve addressed all of your comments. I also added a check to throw an error if an option
> appears more than once.
>
> Attached is the v10 patch, now ready for further review.
>
Thanks for updating the patch. Here are some comments on v10.
1.
+ * db_oid - OID/Name of the database for which to generate the DDL.
Should the comment be updated? The code only accepts an OID for `db_oid`,
database names are not supported.
2.
+ /* Set the OWNER in the DDL if owner is not omitted */
+ if (OidIsValid(dbform->datdba) && !(ddl_flags & PG_DDL_NO_OWNER))
+ {
+ get_formatted_string(&buf, pretty_flags, 8, "OWNER = %s",
+ quote_identifier(dbowner));
+ }
`dbowner` is only needed inside this `if` — how about declaring it there to
reduce its scope?
3.
+ /* If is_with_defaults is true, then we skip default encoding check */
+ if (is_with_defaults ||
+ (pg_strcasecmp(pg_encoding_to_char(dbform->encoding),
+ DDL_DEFAULTS.DATABASE.ENCODING) != 0))
+ {
+ get_formatted_string(&buf, pretty_flags, 8, "ENCODING = %s",
+ quote_literal_cstr(
+ pg_encoding_to_char(dbform->encoding)));
+ }
How about cache the result of `pg_encoding_to_char()` in a local variable to
avoid calling it twice?
--
Regards,
Japin Li
ChengDu WenWu Information Technology Co., Ltd.
Re: [PATCH] Add pg_get_database_ddl() function to reconstruct CREATE DATABASE statement
+SELECT ddl_filter(pg_get_database_ddl('regression_utf8', 'defaults', true, 'tablespace', false));
+ ddl_filter
+----------------------------------------------------------------------------------------------------------------------------------------------------------
+ CREATE DATABASE regression_utf8 WITH OWNER = regress_datdba_after ENCODING = 'UTF8' ALLOW_CONNECTIONS = true CONNECTION LIMIT = 123 IS_TEMPLATE = false;
+(1 row)
+
+SELECT ddl_filter(pg_get_database_ddl('regression_utf8', 'owner', false));
+ ddl_filter
+--------------------------------------------------------------
+ CREATE DATABASE regression_utf8 WITH CONNECTION LIMIT = 123;
+(1 row)
+
+-- With No Tablespace
+SELECT ddl_filter(pg_get_database_ddl('regression_utf8', 'defaults', true, 'tablespace', false));
+ ddl_filter
+----------------------------------------------------------------------------------------------------------------------------------------------------------
+ CREATE DATABASE regression_utf8 WITH OWNER = regress_datdba_after ENCODING = 'UTF8' ALLOW_CONNECTIONS = true CONNECTION LIMIT = 123 IS_TEMPLATE = false;
+(1 row)
I’ve addressed all of your comments.
Attached is the v11 patch, now ready for further review.
On Wed, Mar 4, 2026 at 7:31 PM Japin Li <japinli@hotmail.com> wrote:On Wed, 04 Mar 2026 at 18:29, Akshay Joshi <akshay.joshi@enterprisedb.com> wrote:
> Thanks for the review, Japin. I’ve addressed all of your comments. I also added a check to throw an error if an option
> appears more than once.
>
> Attached is the v10 patch, now ready for further review.
>
Thanks for updating the patch. Here are some comments on v10.
1.
+ * db_oid - OID/Name of the database for which to generate the DDL.
Should the comment be updated? The code only accepts an OID for `db_oid`,
database names are not supported.
2.
+ /* Set the OWNER in the DDL if owner is not omitted */
+ if (OidIsValid(dbform->datdba) && !(ddl_flags & PG_DDL_NO_OWNER))
+ {
+ get_formatted_string(&buf, pretty_flags, 8, "OWNER = %s",
+ quote_identifier(dbowner));
+ }
`dbowner` is only needed inside this `if` — how about declaring it there to
reduce its scope?
3.
+ /* If is_with_defaults is true, then we skip default encoding check */
+ if (is_with_defaults ||
+ (pg_strcasecmp(pg_encoding_to_char(dbform->encoding),
+ DDL_DEFAULTS.DATABASE.ENCODING) != 0))
+ {
+ get_formatted_string(&buf, pretty_flags, 8, "ENCODING = %s",
+ quote_literal_cstr(
+ pg_encoding_to_char(dbform->encoding)));
+ }
How about cache the result of `pg_encoding_to_char()` in a local variable to
avoid calling it twice?
--
Regards,
Japin Li
ChengDu WenWu Information Technology Co., Ltd.
Rafia Sabih
Re: [PATCH] Add pg_get_database_ddl() function to reconstruct CREATE DATABASE statement
On 2026-Mar-05, Rafia Sabih wrote: > Also, the option strategy is missing in the output, is it deliberate? > If yes, why? Yeah, the copying strategy is not integral part of the resulting database: we don't store anywhere, how exactly the database was copied. So it cannot be reproduced, and therefore it would be pointless to try to emit something; or at least I cannot imagine a principled reason to choose any one particular strategy here. -- Álvaro Herrera 48°01'N 7°57'E — https://www.EnterpriseDB.com/ "Por suerte hoy explotó el califont porque si no me habría muerto de aburrido" (Papelucho)
Re: [PATCH] Add pg_get_database_ddl() function to reconstruct CREATE DATABASE statement
I like the idea for this patch and find this useful.I have few comments for the patch, looking at the test cases added in the patch, it is not clear to me what is the default value for each of the options. For example, in
Following the postgresql documentation, I created
ddl_defaults.h to handle default options. This will be used across all database objects in future pg_get_<object>_ddl patches.+-- With No Tablespace
+SELECT ddl_filter(pg_get_database_ddl('regression_utf8', 'defaults', true, 'tablespace', false));
+ ddl_filter
+----------------------------------------------------------------------------------------------------------------------------------------------------------
+ CREATE DATABASE regression_utf8 WITH OWNER = regress_datdba_after ENCODING = 'UTF8' ALLOW_CONNECTIONS = true CONNECTION LIMIT = 123 IS_TEMPLATE = false;
+(1 row)
+owner option is omitted but the output contains the owner information. So does it mean that the default value for each option is true?But that doesn't seem so, because omitting pretty option, doesn't give output in pretty, rather pretty is used only when provided.I find this rather confusing, it is worth documenting what is the default value for each of these options.
In my view, every database has an owner; it's a required attribute, not an optional one with a "default" value. The OWNER clause is correctly controlled only by the PG_DDL_NO_OWNER flag. Users must explicitly provide ('owner', false/'no'/'off') to opt out of including ownership info in the DDL. When comparing the Owner and Pretty options: by default, the Owner is included in the DDL reconstruction, whereas the Pretty option is set to false by default.
In my initial patches, I used flags like --no-owner and --no-tablespace because they are very intuitive for users. However, reviewers noted that this style is unique to pg_dump and not used elsewhere. Consequently, I switched to the existing name-value pair format using VARIADIC arguments.
Similarly, what is the expected behaviour when defaults option is not provided,+-- With No Owner
+SELECT ddl_filter(pg_get_database_ddl('regression_utf8', 'owner', false));
+ ddl_filter
+--------------------------------------------------------------
+ CREATE DATABASE regression_utf8 WITH CONNECTION LIMIT = 123;
+(1 row)
+
+-- With No Tablespace
+SELECT ddl_filter(pg_get_database_ddl('regression_utf8', 'defaults', true, 'tablespace', false));
+ ddl_filter
+----------------------------------------------------------------------------------------------------------------------------------------------------------
+ CREATE DATABASE regression_utf8 WITH OWNER = regress_datdba_after ENCODING = 'UTF8' ALLOW_CONNECTIONS = true CONNECTION LIMIT = 123 IS_TEMPLATE = false;
+(1 row)Why is connection_limit present in both of these cases...?Another thing, what is the significance of having defaults option, because I think that knowing non-default values could be more useful, or atleast there should be a way to know the non-default options for the database.
The defaults option is false by default; if a user does not specify it, the reconstructed DDL only includes non-default parameters. In my opinion, we should retain this flag for users who wish to see all available parameters for easier manual editing later. While simple database objects have fewer parameters, this flag is essential for complex TABLE or FUNCTION syntax where the parameter list is extensive.
Also, the option strategy is missing in the output, is it deliberate? If yes, why?
On Thu, 5 Mar 2026 at 01:50, Akshay Joshi <akshay.joshi@enterprisedb.com> wrote:I’ve addressed all of your comments.
Attached is the v11 patch, now ready for further review.
On Wed, Mar 4, 2026 at 7:31 PM Japin Li <japinli@hotmail.com> wrote:On Wed, 04 Mar 2026 at 18:29, Akshay Joshi <akshay.joshi@enterprisedb.com> wrote:
> Thanks for the review, Japin. I’ve addressed all of your comments. I also added a check to throw an error if an option
> appears more than once.
>
> Attached is the v10 patch, now ready for further review.
>
Thanks for updating the patch. Here are some comments on v10.
1.
+ * db_oid - OID/Name of the database for which to generate the DDL.
Should the comment be updated? The code only accepts an OID for `db_oid`,
database names are not supported.
2.
+ /* Set the OWNER in the DDL if owner is not omitted */
+ if (OidIsValid(dbform->datdba) && !(ddl_flags & PG_DDL_NO_OWNER))
+ {
+ get_formatted_string(&buf, pretty_flags, 8, "OWNER = %s",
+ quote_identifier(dbowner));
+ }
`dbowner` is only needed inside this `if` — how about declaring it there to
reduce its scope?
3.
+ /* If is_with_defaults is true, then we skip default encoding check */
+ if (is_with_defaults ||
+ (pg_strcasecmp(pg_encoding_to_char(dbform->encoding),
+ DDL_DEFAULTS.DATABASE.ENCODING) != 0))
+ {
+ get_formatted_string(&buf, pretty_flags, 8, "ENCODING = %s",
+ quote_literal_cstr(
+ pg_encoding_to_char(dbform->encoding)));
+ }
How about cache the result of `pg_encoding_to_char()` in a local variable to
avoid calling it twice?
--
Regards,
Japin Li
ChengDu WenWu Information Technology Co., Ltd.--Regards,
Rafia SabihCYBERTEC PostgreSQL International GmbH
Re: [PATCH] Add pg_get_database_ddl() function to reconstruct CREATE DATABASE statement
On Thu, Mar 5, 2026 at 8:15 PM Rafia Sabih <rafia.pghackers@gmail.com> wrote:I like the idea for this patch and find this useful.I have few comments for the patch, looking at the test cases added in the patch, it is not clear to me what is the default value for each of the options. For example, in
Following the postgresql documentation, I createdddl_defaults.hto handle default options. This will be used across all database objects in futurepg_get_<object>_ddlpatches.
+-- With No Tablespace
+SELECT ddl_filter(pg_get_database_ddl('regression_utf8', 'defaults', true, 'tablespace', false));
+ ddl_filter
+----------------------------------------------------------------------------------------------------------------------------------------------------------
+ CREATE DATABASE regression_utf8 WITH OWNER = regress_datdba_after ENCODING = 'UTF8' ALLOW_CONNECTIONS = true CONNECTION LIMIT = 123 IS_TEMPLATE = false;
+(1 row)
+owner option is omitted but the output contains the owner information. So does it mean that the default value for each option is true?But that doesn't seem so, because omitting pretty option, doesn't give output in pretty, rather pretty is used only when provided.I find this rather confusing, it is worth documenting what is the default value for each of these options.
In my view, every database has an owner; it's a required attribute, not an optional one with a "default" value. The OWNER clause is correctly controlled only by the PG_DDL_NO_OWNER flag. Users must explicitly provide ('owner', false/'no'/'off') to opt out of including ownership info in the DDL. When comparing the Owner and Pretty options: by default, the Owner is included in the DDL reconstruction, whereas the Pretty option is set to false by default.
+ <literal>'pretty', true</literal> (or <literal>'pretty', 'yes'</literal>):
+ Adds newlines and indentation for better readability.
In my initial patches, I used flags like --no-owner and --no-tablespace because they are very intuitive for users. However, reviewers noted that this style is unique to pg_dump and not used elsewhere. Consequently, I switched to the existing name-value pair format using VARIADIC arguments.Similarly, what is the expected behaviour when defaults option is not provided,+-- With No Owner
+SELECT ddl_filter(pg_get_database_ddl('regression_utf8', 'owner', false));
+ ddl_filter
+--------------------------------------------------------------
+ CREATE DATABASE regression_utf8 WITH CONNECTION LIMIT = 123;
+(1 row)
+
+-- With No Tablespace
+SELECT ddl_filter(pg_get_database_ddl('regression_utf8', 'defaults', true, 'tablespace', false));
+ ddl_filter
+----------------------------------------------------------------------------------------------------------------------------------------------------------
+ CREATE DATABASE regression_utf8 WITH OWNER = regress_datdba_after ENCODING = 'UTF8' ALLOW_CONNECTIONS = true CONNECTION LIMIT = 123 IS_TEMPLATE = false;
+(1 row)Why is connection_limit present in both of these cases...?Another thing, what is the significance of having defaults option, because I think that knowing non-default values could be more useful, or atleast there should be a way to know the non-default options for the database.
The defaults option is false by default; if a user does not specify it, the reconstructed DDL only includes non-default parameters. In my opinion, we should retain this flag for users who wish to see all available parameters for easier manual editing later. While simple database objects have fewer parameters, this flag is essential for complex TABLE or FUNCTION syntax where the parameter list is extensive.
Also, the option strategy is missing in the output, is it deliberate? If yes, why?On Thu, 5 Mar 2026 at 01:50, Akshay Joshi <akshay.joshi@enterprisedb.com> wrote:I’ve addressed all of your comments.
Attached is the v11 patch, now ready for further review.
On Wed, Mar 4, 2026 at 7:31 PM Japin Li <japinli@hotmail.com> wrote:On Wed, 04 Mar 2026 at 18:29, Akshay Joshi <akshay.joshi@enterprisedb.com> wrote:
> Thanks for the review, Japin. I’ve addressed all of your comments. I also added a check to throw an error if an option
> appears more than once.
>
> Attached is the v10 patch, now ready for further review.
>
Thanks for updating the patch. Here are some comments on v10.
1.
+ * db_oid - OID/Name of the database for which to generate the DDL.
Should the comment be updated? The code only accepts an OID for `db_oid`,
database names are not supported.
2.
+ /* Set the OWNER in the DDL if owner is not omitted */
+ if (OidIsValid(dbform->datdba) && !(ddl_flags & PG_DDL_NO_OWNER))
+ {
+ get_formatted_string(&buf, pretty_flags, 8, "OWNER = %s",
+ quote_identifier(dbowner));
+ }
`dbowner` is only needed inside this `if` — how about declaring it there to
reduce its scope?
3.
+ /* If is_with_defaults is true, then we skip default encoding check */
+ if (is_with_defaults ||
+ (pg_strcasecmp(pg_encoding_to_char(dbform->encoding),
+ DDL_DEFAULTS.DATABASE.ENCODING) != 0))
+ {
+ get_formatted_string(&buf, pretty_flags, 8, "ENCODING = %s",
+ quote_literal_cstr(
+ pg_encoding_to_char(dbform->encoding)));
+ }
How about cache the result of `pg_encoding_to_char()` in a local variable to
avoid calling it twice?
--
Regards,
Japin Li
ChengDu WenWu Information Technology Co., Ltd.--Regards,
Rafia SabihCYBERTEC PostgreSQL International GmbH
Rafia Sabih
Re: [PATCH] Add pg_get_database_ddl() function to reconstruct CREATE DATABASE statement
Attached is the v12 patch, now ready for further review.
On Thu, 5 Mar 2026 at 08:16, Akshay Joshi <akshay.joshi@enterprisedb.com> wrote:On Thu, Mar 5, 2026 at 8:15 PM Rafia Sabih <rafia.pghackers@gmail.com> wrote:I like the idea for this patch and find this useful.I have few comments for the patch, looking at the test cases added in the patch, it is not clear to me what is the default value for each of the options. For example, in
Following the postgresql documentation, I createdddl_defaults.hto handle default options. This will be used across all database objects in futurepg_get_<object>_ddlpatches.
+-- With No Tablespace
+SELECT ddl_filter(pg_get_database_ddl('regression_utf8', 'defaults', true, 'tablespace', false));
+ ddl_filter
+----------------------------------------------------------------------------------------------------------------------------------------------------------
+ CREATE DATABASE regression_utf8 WITH OWNER = regress_datdba_after ENCODING = 'UTF8' ALLOW_CONNECTIONS = true CONNECTION LIMIT = 123 IS_TEMPLATE = false;
+(1 row)
+owner option is omitted but the output contains the owner information. So does it mean that the default value for each option is true?But that doesn't seem so, because omitting pretty option, doesn't give output in pretty, rather pretty is used only when provided.I find this rather confusing, it is worth documenting what is the default value for each of these options.
In my view, every database has an owner; it's a required attribute, not an optional one with a "default" value. The OWNER clause is correctly controlled only by the PG_DDL_NO_OWNER flag. Users must explicitly provide ('owner', false/'no'/'off') to opt out of including ownership info in the DDL. When comparing the Owner and Pretty options: by default, the Owner is included in the DDL reconstruction, whereas the Pretty option is set to false by default.Right, I think this needs to be added in the documentation as part of this patch. Basically, here<para>
+ <literal>'pretty', true</literal> (or <literal>'pretty', 'yes'</literal>):
+ Adds newlines and indentation for better readability.+ </para>it needs to have a line more saying, by default this option is off. Similarly for other options, like for the owner it is by default true, etc.In my initial patches, I used flags like --no-owner and --no-tablespace because they are very intuitive for users. However, reviewers noted that this style is unique to pg_dump and not used elsewhere. Consequently, I switched to the existing name-value pair format using VARIADIC arguments.Similarly, what is the expected behaviour when defaults option is not provided,+-- With No Owner
+SELECT ddl_filter(pg_get_database_ddl('regression_utf8', 'owner', false));
+ ddl_filter
+--------------------------------------------------------------
+ CREATE DATABASE regression_utf8 WITH CONNECTION LIMIT = 123;
+(1 row)
+
+-- With No Tablespace
+SELECT ddl_filter(pg_get_database_ddl('regression_utf8', 'defaults', true, 'tablespace', false));
+ ddl_filter
+----------------------------------------------------------------------------------------------------------------------------------------------------------
+ CREATE DATABASE regression_utf8 WITH OWNER = regress_datdba_after ENCODING = 'UTF8' ALLOW_CONNECTIONS = true CONNECTION LIMIT = 123 IS_TEMPLATE = false;
+(1 row)Why is connection_limit present in both of these cases...?Another thing, what is the significance of having defaults option, because I think that knowing non-default values could be more useful, or atleast there should be a way to know the non-default options for the database.
The defaults option is false by default; if a user does not specify it, the reconstructed DDL only includes non-default parameters. In my opinion, we should retain this flag for users who wish to see all available parameters for easier manual editing later. While simple database objects have fewer parameters, this flag is essential for complex TABLE or FUNCTION syntax where the parameter list is extensive.This information should also be included in the documentation.Also, the option strategy is missing in the output, is it deliberate? If yes, why?On Thu, 5 Mar 2026 at 01:50, Akshay Joshi <akshay.joshi@enterprisedb.com> wrote:I’ve addressed all of your comments.
Attached is the v11 patch, now ready for further review.
On Wed, Mar 4, 2026 at 7:31 PM Japin Li <japinli@hotmail.com> wrote:On Wed, 04 Mar 2026 at 18:29, Akshay Joshi <akshay.joshi@enterprisedb.com> wrote:
> Thanks for the review, Japin. I’ve addressed all of your comments. I also added a check to throw an error if an option
> appears more than once.
>
> Attached is the v10 patch, now ready for further review.
>
Thanks for updating the patch. Here are some comments on v10.
1.
+ * db_oid - OID/Name of the database for which to generate the DDL.
Should the comment be updated? The code only accepts an OID for `db_oid`,
database names are not supported.
2.
+ /* Set the OWNER in the DDL if owner is not omitted */
+ if (OidIsValid(dbform->datdba) && !(ddl_flags & PG_DDL_NO_OWNER))
+ {
+ get_formatted_string(&buf, pretty_flags, 8, "OWNER = %s",
+ quote_identifier(dbowner));
+ }
`dbowner` is only needed inside this `if` — how about declaring it there to
reduce its scope?
3.
+ /* If is_with_defaults is true, then we skip default encoding check */
+ if (is_with_defaults ||
+ (pg_strcasecmp(pg_encoding_to_char(dbform->encoding),
+ DDL_DEFAULTS.DATABASE.ENCODING) != 0))
+ {
+ get_formatted_string(&buf, pretty_flags, 8, "ENCODING = %s",
+ quote_literal_cstr(
+ pg_encoding_to_char(dbform->encoding)));
+ }
How about cache the result of `pg_encoding_to_char()` in a local variable to
avoid calling it twice?
--
Regards,
Japin Li
ChengDu WenWu Information Technology Co., Ltd.--Regards,
Rafia SabihCYBERTEC PostgreSQL International GmbH--Regards,
Rafia SabihCYBERTEC PostgreSQL International GmbH
Re: [PATCH] Add pg_get_database_ddl() function to reconstruct CREATE DATABASE statement
Hi, Akshay
On Fri, 06 Mar 2026 at 17:21, Akshay Joshi wrote:
> I have updated the documentation.
> Attached is the v12 patch, now ready for further review.
>
Thanks for updating the patch.
I might not have expressed myself clearly in my last email — apologies.
Here's a diff that should make it clearer.
diff --git a/src/backend/utils/adt/ruleutils.c b/src/backend/utils/adt/ruleutils.c
index bbf82c1d6c0..1ed56ee71ab 100644
--- a/src/backend/utils/adt/ruleutils.c
+++ b/src/backend/utils/adt/ruleutils.c
@@ -13859,7 +13859,6 @@ parse_ddl_options(FunctionCallInfo fcinfo, int variadic_start)
bool *nulls;
Oid *types;
int nargs;
- bool found = false;
/* Extract variadic arguments */
nargs = extract_variadic_args(fcinfo, variadic_start, true,
@@ -13887,8 +13886,7 @@ parse_ddl_options(FunctionCallInfo fcinfo, int variadic_start)
{
char *name;
bool bval;
-
- found = false;
+ bool found = false;
/* Key must not be null */
if (nulls[i])
@@ -13925,8 +13923,8 @@ parse_ddl_options(FunctionCallInfo fcinfo, int variadic_start)
if (!parse_bool(valstr, &bval))
ereport(ERROR,
(errcode(ERRCODE_INVALID_PARAMETER_VALUE),
- errmsg("argument %d: invalid value \"%s\" for key \"%s\"",
- i + 2, valstr, name),
+ errmsg("value for option \"%s\" at position %d has invalid value \"%s\"",
+ name, i + 2, valstr),
errhint("Valid values are: true, false, yes, no, 1, 0, on, off.")));
pfree(valstr);
}
@@ -13934,8 +13932,8 @@ parse_ddl_options(FunctionCallInfo fcinfo, int variadic_start)
{
ereport(ERROR,
(errcode(ERRCODE_INVALID_PARAMETER_VALUE),
- errmsg("argument %d: value for key \"%s\" must be boolean or text type",
- i + 2, name)));
+ errmsg("value for option \"%s\" at position %d has type %s, expected type boolean or text",
+ name, i + 2, format_type_be(types[i + 1]))));
}
/*
@@ -13983,7 +13981,7 @@ parse_ddl_options(FunctionCallInfo fcinfo, int variadic_start)
/*
* pg_get_database_ddl
*
- * Generate a CREATE DATABASE statement for the specified database name or oid.
+ * Generate a CREATE DATABASE statement for the specified database oid.
*
* db_oid - OID of the database for which to generate the DDL.
* options - Variadic name/value pairs to modify the output.
--
Regards,
Japin Li
ChengDu WenWu Information Technology Co., Ltd.
Re: [PATCH] Add pg_get_database_ddl() function to reconstruct CREATE DATABASE statement
CREATE DATABASE is derived from the template database (template1) rather than being a static value.Attached is the v13 patch, now ready for further review.
Hi, Akshay
On Fri, 06 Mar 2026 at 17:21, Akshay Joshi <akshay.joshi@enterprisedb.com> wrote:
> I have updated the documentation.
> Attached is the v12 patch, now ready for further review.
>
Thanks for updating the patch.
I might not have expressed myself clearly in my last email — apologies.
Here's a diff that should make it clearer.
diff --git a/src/backend/utils/adt/ruleutils.c b/src/backend/utils/adt/ruleutils.c
index bbf82c1d6c0..1ed56ee71ab 100644
--- a/src/backend/utils/adt/ruleutils.c
+++ b/src/backend/utils/adt/ruleutils.c
@@ -13859,7 +13859,6 @@ parse_ddl_options(FunctionCallInfo fcinfo, int variadic_start)
bool *nulls;
Oid *types;
int nargs;
- bool found = false;
/* Extract variadic arguments */
nargs = extract_variadic_args(fcinfo, variadic_start, true,
@@ -13887,8 +13886,7 @@ parse_ddl_options(FunctionCallInfo fcinfo, int variadic_start)
{
char *name;
bool bval;
-
- found = false;
+ bool found = false;
/* Key must not be null */
if (nulls[i])
@@ -13925,8 +13923,8 @@ parse_ddl_options(FunctionCallInfo fcinfo, int variadic_start)
if (!parse_bool(valstr, &bval))
ereport(ERROR,
(errcode(ERRCODE_INVALID_PARAMETER_VALUE),
- errmsg("argument %d: invalid value \"%s\" for key \"%s\"",
- i + 2, valstr, name),
+ errmsg("value for option \"%s\" at position %d has invalid value \"%s\"",
+ name, i + 2, valstr),
errhint("Valid values are: true, false, yes, no, 1, 0, on, off.")));
pfree(valstr);
}
@@ -13934,8 +13932,8 @@ parse_ddl_options(FunctionCallInfo fcinfo, int variadic_start)
{
ereport(ERROR,
(errcode(ERRCODE_INVALID_PARAMETER_VALUE),
- errmsg("argument %d: value for key \"%s\" must be boolean or text type",
- i + 2, name)));
+ errmsg("value for option \"%s\" at position %d has type %s, expected type boolean or text",
+ name, i + 2, format_type_be(types[i + 1]))));
}
/*
@@ -13983,7 +13981,7 @@ parse_ddl_options(FunctionCallInfo fcinfo, int variadic_start)
/*
* pg_get_database_ddl
*
- * Generate a CREATE DATABASE statement for the specified database name or oid.
+ * Generate a CREATE DATABASE statement for the specified database oid.
*
* db_oid - OID of the database for which to generate the DDL.
* options - Variadic name/value pairs to modify the output.
--
Regards,
Japin Li
ChengDu WenWu Information Technology Co., Ltd.
Re: [PATCH] Add pg_get_database_ddl() function to reconstruct CREATE DATABASE statement
On Mon, 9 Mar 2026 at 17:08, Akshay Joshi wrote:
>
> I have resolved the review comments. Removed the hardcoded 'utf-8' encoding, the logic now retrieves the encoding dynamically. This ensures accuracy because the default encoding for CREATE DATABASE is derived from the template database (template1) rather than being a static value.
>
> Attached is the v13 patch, now ready for further review.
>
> On Fri, Mar 6, 2026 at 8:13 PM Japin Li wrote:
>>
>>
>> Hi, Akshay
>>
>> On Fri, 06 Mar 2026 at 17:21, Akshay Joshi wrote:
>> > I have updated the documentation.
>> > Attached is the v12 patch, now ready for further review.
>> >
>>
>> Thanks for updating the patch.
>>
>> I might not have expressed myself clearly in my last email — apologies.
>> Here's a diff that should make it clearer.
>>
>> diff --git a/src/backend/utils/adt/ruleutils.c b/src/backend/utils/adt/ruleutils.c
>> index bbf82c1d6c0..1ed56ee71ab 100644
>> --- a/src/backend/utils/adt/ruleutils.c
>> +++ b/src/backend/utils/adt/ruleutils.c
>> @@ -13859,7 +13859,6 @@ parse_ddl_options(FunctionCallInfo fcinfo, int variadic_start)
>> bool *nulls;
>> Oid *types;
>> int nargs;
>> - bool found = false;
>>
>> /* Extract variadic arguments */
>> nargs = extract_variadic_args(fcinfo, variadic_start, true,
>> @@ -13887,8 +13886,7 @@ parse_ddl_options(FunctionCallInfo fcinfo, int variadic_start)
>> {
>> char *name;
>> bool bval;
>> -
>> - found = false;
>> + bool found = false;
>>
>> /* Key must not be null */
>> if (nulls[i])
>> @@ -13925,8 +13923,8 @@ parse_ddl_options(FunctionCallInfo fcinfo, int variadic_start)
>> if (!parse_bool(valstr, &bval))
>> ereport(ERROR,
>> (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
>> - errmsg("argument %d: invalid value \"%s\" for key \"%s\"",
>> - i + 2, valstr, name),
>> + errmsg("value for option \"%s\" at position %d has invalid value \"%s\"",
>> + name, i + 2, valstr),
>> errhint("Valid values are: true, false, yes, no, 1, 0, on, off.")));
>> pfree(valstr);
>> }
>> @@ -13934,8 +13932,8 @@ parse_ddl_options(FunctionCallInfo fcinfo, int variadic_start)
>> {
>> ereport(ERROR,
>> (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
>> - errmsg("argument %d: value for key \"%s\" must be boolean or text type",
>> - i + 2, name)));
>> + errmsg("value for option \"%s\" at position %d has type %s, expected type boolean or text",
>> + name, i + 2, format_type_be(types[i + 1]))));
>> }
>>
>> /*
>> @@ -13983,7 +13981,7 @@ parse_ddl_options(FunctionCallInfo fcinfo, int variadic_start)
>> /*
>> * pg_get_database_ddl
>> *
>> - * Generate a CREATE DATABASE statement for the specified database name or oid.
>> + * Generate a CREATE DATABASE statement for the specified database oid.
>> *
>> * db_oid - OID of the database for which to generate the DDL.
>> * options - Variadic name/value pairs to modify the output.
>>
>> --
>> Regards,
>> Japin Li
>> ChengDu WenWu Information Technology Co., Ltd.
Hi!
I noticed this in v13: DDLOptionDef is missing from typedefs.list.
This results in pgident to incorrectly format sources.
--
Best regards,
Kirill Reshke
Re: [PATCH] Add pg_get_database_ddl() function to reconstruct CREATE DATABASE statement
Attached is the v14 patch, now ready for further review.
On Mon, 9 Mar 2026 at 17:08, Akshay Joshi <akshay.joshi@enterprisedb.com> wrote:
>
> I have resolved the review comments. Removed the hardcoded 'utf-8' encoding, the logic now retrieves the encoding dynamically. This ensures accuracy because the default encoding for CREATE DATABASE is derived from the template database (template1) rather than being a static value.
>
> Attached is the v13 patch, now ready for further review.
>
> On Fri, Mar 6, 2026 at 8:13 PM Japin Li <japinli@hotmail.com> wrote:
>>
>>
>> Hi, Akshay
>>
>> On Fri, 06 Mar 2026 at 17:21, Akshay Joshi <akshay.joshi@enterprisedb.com> wrote:
>> > I have updated the documentation.
>> > Attached is the v12 patch, now ready for further review.
>> >
>>
>> Thanks for updating the patch.
>>
>> I might not have expressed myself clearly in my last email — apologies.
>> Here's a diff that should make it clearer.
>>
>> diff --git a/src/backend/utils/adt/ruleutils.c b/src/backend/utils/adt/ruleutils.c
>> index bbf82c1d6c0..1ed56ee71ab 100644
>> --- a/src/backend/utils/adt/ruleutils.c
>> +++ b/src/backend/utils/adt/ruleutils.c
>> @@ -13859,7 +13859,6 @@ parse_ddl_options(FunctionCallInfo fcinfo, int variadic_start)
>> bool *nulls;
>> Oid *types;
>> int nargs;
>> - bool found = false;
>>
>> /* Extract variadic arguments */
>> nargs = extract_variadic_args(fcinfo, variadic_start, true,
>> @@ -13887,8 +13886,7 @@ parse_ddl_options(FunctionCallInfo fcinfo, int variadic_start)
>> {
>> char *name;
>> bool bval;
>> -
>> - found = false;
>> + bool found = false;
>>
>> /* Key must not be null */
>> if (nulls[i])
>> @@ -13925,8 +13923,8 @@ parse_ddl_options(FunctionCallInfo fcinfo, int variadic_start)
>> if (!parse_bool(valstr, &bval))
>> ereport(ERROR,
>> (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
>> - errmsg("argument %d: invalid value \"%s\" for key \"%s\"",
>> - i + 2, valstr, name),
>> + errmsg("value for option \"%s\" at position %d has invalid value \"%s\"",
>> + name, i + 2, valstr),
>> errhint("Valid values are: true, false, yes, no, 1, 0, on, off.")));
>> pfree(valstr);
>> }
>> @@ -13934,8 +13932,8 @@ parse_ddl_options(FunctionCallInfo fcinfo, int variadic_start)
>> {
>> ereport(ERROR,
>> (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
>> - errmsg("argument %d: value for key \"%s\" must be boolean or text type",
>> - i + 2, name)));
>> + errmsg("value for option \"%s\" at position %d has type %s, expected type boolean or text",
>> + name, i + 2, format_type_be(types[i + 1]))));
>> }
>>
>> /*
>> @@ -13983,7 +13981,7 @@ parse_ddl_options(FunctionCallInfo fcinfo, int variadic_start)
>> /*
>> * pg_get_database_ddl
>> *
>> - * Generate a CREATE DATABASE statement for the specified database name or oid.
>> + * Generate a CREATE DATABASE statement for the specified database oid.
>> *
>> * db_oid - OID of the database for which to generate the DDL.
>> * options - Variadic name/value pairs to modify the output.
>>
>> --
>> Regards,
>> Japin Li
>> ChengDu WenWu Information Technology Co., Ltd.
Hi!
I noticed this in v13: DDLOptionDef is missing from typedefs.list.
This results in pgident to incorrectly format sources.
--
Best regards,
Kirill Reshke
Re: [PATCH] Add pg_get_database_ddl() function to reconstruct CREATE DATABASE statement
Hello
Is ruleutils.c the best place for this function?
It's already huge, and it has a different scope: "Functions to convert
stored expressions/querytrees back to source text"
+ /* Fetch the value of COLLATION_VERSION */
+ dbvalue = SysCacheGetAttr(DATABASEOID, tuple_database,
+ Anum_pg_database_datcollversion, &attr_isnull);
+ if (!attr_isnull)
+ get_formatted_string(&buf, pretty_flags, 8, "COLLATION_VERSION = %s",
+ quote_literal_cstr(TextDatumGetCString(dbvalue)));
pg_dumpall only shows this for binary upgrade, otherwise skips it. Is
it okay for this command to print it by default, shouldn't it depend
on is_with_defaults or something similar?
+#ifndef DDL_DEFAULTS_H
+#define DDL_DEFAULTS_H
+
+static const struct
+{
+ struct
+ {
....
This file seems strange. A static const struct in a header with
uppercase names doesn't seem to follow postgres conventions?
DATCONNLIMIT_UNLIMITED alredy exists as a definition, and probably
should be used instead or referenced, or the existing uses should
refer to the new way of defining it.
+ /* Fetch the value of LC_COLLATE */
+ dbvalue = SysCacheGetAttr(DATABASEOID, tuple_database,
+ Anum_pg_database_datcollate, &attr_isnull);
+ if (!attr_isnull)
+ get_formatted_string(&buf, pretty_flags, 8, "LC_COLLATE = %s",
+ quote_literal_cstr(TextDatumGetCString(dbvalue)));
+ /* Fetch the value of LC_CTYPE */
+ dbvalue = SysCacheGetAttr(DATABASEOID, tuple_database,
+ Anum_pg_database_datctype, &attr_isnull);
Can these be ever nulls?
Also, pg_dump only emits LOCALE if ctype==collate, shouldn't this
follow the same pattern?
+ else if (is_with_defaults)
+ get_formatted_string(&buf, pretty_flags, 8, "LOCALE_PROVIDER = libc");
Doesn't pg_dump always emit this? Shouldn't this function follow the
same convention? Emitting it seems to be a safer default, in case
postgres ever changes this.
+ /* Build the CREATE DATABASE statement */
+ appendStringInfo(&buf, "CREATE DATABASE %s",
+ quote_identifier(dbform->datname.data));
+ get_formatted_string(&buf, pretty_flags, 4, "WITH");
Shouldn't we only emit "WITH" if it is actually followed by something,
not unconditionally?
+/*
+ * get_formatted_string
+ *
+ * Return a formatted version of the string.
But it's a void function.
+ else if (!attr_isnull)
+ get_formatted_string(&buf, pretty_flags, 8, "LOCALE = %s",
+ quote_literal_cstr(TextDatumGetCString(dbvalue)));
+
Can this ever happen, shouldn't it be an assertion instead?
Re: [PATCH] Add pg_get_database_ddl() function to reconstruct CREATE DATABASE statement
Hello
Is ruleutils.c the best place for this function?
It's already huge, and it has a different scope: "Functions to convert
stored expressions/querytrees back to source text"
Created the
ddlutils.c file.
+ /* Fetch the value of COLLATION_VERSION */
+ dbvalue = SysCacheGetAttr(DATABASEOID, tuple_database,
+ Anum_pg_database_datcollversion, &attr_isnull);
+ if (!attr_isnull)
+ get_formatted_string(&buf, pretty_flags, 8, "COLLATION_VERSION = %s",
+ quote_literal_cstr(TextDatumGetCString(dbvalue)));
pg_dumpall only shows this for binary upgrade, otherwise skips it. Is
it okay for this command to print it by default, shouldn't it depend
on is_with_defaults or something similar?
Shows only when `is_with_defaults` is true.
+#ifndef DDL_DEFAULTS_H
+#define DDL_DEFAULTS_H
+
+static const struct
+{
+ struct
+ {
....
This file seems strange. A static const struct in a header with
uppercase names doesn't seem to follow postgres conventions?
DATCONNLIMIT_UNLIMITED alredy exists as a definition, and probably
should be used instead or referenced, or the existing uses should
refer to the new way of defining it.
Removed the header file and implemented an alternative logic. Note that a similar file may be necessary in the future to handle default values for other pg_get_<object>_ddl.
+ /* Fetch the value of LC_COLLATE */
+ dbvalue = SysCacheGetAttr(DATABASEOID, tuple_database,
+ Anum_pg_database_datcollate, &attr_isnull);
+ if (!attr_isnull)
+ get_formatted_string(&buf, pretty_flags, 8, "LC_COLLATE = %s",
+ quote_literal_cstr(TextDatumGetCString(dbvalue)));
+ /* Fetch the value of LC_CTYPE */
+ dbvalue = SysCacheGetAttr(DATABASEOID, tuple_database,
+ Anum_pg_database_datctype, &attr_isnull);
Can these be ever nulls?
Also, pg_dump only emits LOCALE if ctype==collate, shouldn't this
follow the same pattern?
+ else if (is_with_defaults)
+ get_formatted_string(&buf, pretty_flags, 8, "LOCALE_PROVIDER = libc");
Doesn't pg_dump always emit this? Shouldn't this function follow the
same convention? Emitting it seems to be a safer default, in case
postgres ever changes this.
+ /* Build the CREATE DATABASE statement */
+ appendStringInfo(&buf, "CREATE DATABASE %s",
+ quote_identifier(dbform->datname.data));
+ get_formatted_string(&buf, pretty_flags, 4, "WITH");
Shouldn't we only emit "WITH" if it is actually followed by something,
not unconditionally?
+/*
+ * get_formatted_string
+ *
+ * Return a formatted version of the string.
But it's a void function.
+ else if (!attr_isnull)
+ get_formatted_string(&buf, pretty_flags, 8, "LOCALE = %s",
+ quote_literal_cstr(TextDatumGetCString(dbvalue)));
+
Can this ever happen, shouldn't it be an assertion instead?
Fixed all the preceding review comments.
Attached is the v15 patch, now ready for further review.