How to retrieve DDL of a postgres table using Java JDBC?

712 Views Asked by At

There is a requirement to update the table frequently by truncating and then populating it again using a dump file. While doing that I first delete the reference keys. This reduces the time of populating the table. Can I retrieve below similar output i.e. DDL of a table using Java JDBC? I tried DatabaseMetaData methods to get DDL of the table, but found no useful method which will do this.

health=# \d system_user
                        Table "public.system_user"

|    Column    |          Type          | Collation | Nullable | Default |
|--------------+------------------------+-----------+----------+---------|
| user_id      | bigint                 |           | not null |         |
| email        | character varying(255) |           | not null |         |
| first_name   | text                   |           | not null |         |
| last_name    | text                   |           | not null |         |
| password     | character varying(255) |           | not null |         |
| phone_number | character varying(255) |           | not null |         |
| provider_id  | bigint                 |           |          |         |

Indexes:
    "system_user_pkey" PRIMARY KEY, btree (user_id)
Foreign-key constraints:
    "fka48037dbd736797" FOREIGN KEY (provider_id) REFERENCES provider(provider_id)
Referenced by:
    TABLE "annotation_project_annotator" CONSTRAINT "annotation_project_annotator_fk_1" FOREIGN KEY (annotator) REFERENCES system_user(user_id) ON DELETE RESTRICT
    TABLE "annotation_project" CONSTRAINT "annotation_project_fk_2" FOREIGN KEY (supervisor) REFERENCES system_user(user_id) ON DELETE RESTRICT
    TABLE "annotation_project" CONSTRAINT "annotation_project_fk_3" FOREIGN KEY (created_by) REFERENCES system_user(user_id) ON DELETE RESTRICT
    TABLE "annotation_project" CONSTRAINT "annotation_project_fk_4" FOREIGN KEY (updated_by) REFERENCES system_user(user_id) ON DELETE RESTRICT
    TABLE "grammar" CONSTRAINT "fk10b467a7b7ea696d" FOREIGN KEY (user_id) REFERENCES system_user(user_id)
    TABLE "manual_annotation" CONSTRAINT "fk2a02e148b7ea696d" FOREIGN KEY (user_id) REFERENCES system_user(user_id)
1

There are 1 best solutions below

0
On

Start psql with the -E option and run \d system_user, then you will get the SQL statements that psql uses to retrieve the data it needs for that output. This should get you on your way to query the metadata.