From: | "Walter Dörwald " <walter(at)livinglogic(dot)de> |
---|---|
To: | "Igor Korot" <ikorot01(at)gmail(dot)com> |
Cc: | "pgsql-generallists(dot)postgresql(dot)org" <pgsql-general(at)lists(dot)postgresql(dot)org>, pgsql-general <pgsql-general(at)postgresql(dot)org> |
Subject: | Re: Get the table creation DDL |
Date: | 2022-07-11 08:11:08 |
Message-ID: | 1B921E2A-3DD3-4419-9D81-108EE88449B5@livinglogic.de |
Views: | Raw Message | Whole Thread | Download mbox | Resend email |
Thread: | |
Lists: | pgsql-general |
On 10 Jul 2022, at 17:40, Igor Korot wrote:
> Hi,
> Is there a query I can execute that will give me CREATE TABLE()
> command
> used to create a table?
>
> Thank you.
I am using the following query for that:
```sql
select
a.attname,
a.attnum,
a.attnotnull,
pg_catalog.format_type(a.atttypid, a.atttypmod) as column_type,
case
when d.adrelid is not null then pg_catalog.pg_get_expr(d.adbin,
d.adrelid)
else null
end as default_value
from
pg_catalog.pg_class c
join
pg_catalog.pg_attribute a on c.oid = a.attrelid and a.attnum > 0 and
not a.attisdropped
join
pg_catalog.pg_namespace n on c.relnamespace = n.oid
left outer join
pg_catalog.pg_attrdef d on d.adrelid = a.attrelid and d.adnum =
a.attnum and a.atthasdef
where
c.relname = %s and
n.nspname = %s
order by
attnum
;
```
and the following Python code to format the `create table` statement:
```python
sql = f"create table {schema}.{name}\n"
sql += f"(\n"
for (last, column) in islast(cursor):
column_term = "" if last else ","
notnull = " not null" if column.attnotnull else ""
default = f" default {column.default_value}" if column.default_value is
not None else ""
sql += f"\t{column.attname}
{column.column_type}{default}{notnull}{column_term}\n"
sql += f");"
return sql
```
Servus,
Walter
From | Date | Subject | |
---|---|---|---|
Next Message | Aleš Zelený | 2022-07-11 08:50:23 | PostgreSQL 14.4 ERROR: out of memory issues |
Previous Message | Ken Yeung | 2022-07-11 05:37:51 | Problem upgrading from 10 to 14 with pg_upgrade: unexpected error upgrading "template1" database for some clusters |