Backup of PostgreSQL database design - without data

前端 未结 4 1747
独厮守ぢ
独厮守ぢ 2021-01-17 08:31

I have tried to find a way to backup my database design without including the data stored in the database. Actually, one might say that I want to have a file that holds all

4条回答
  •  清歌不尽
    2021-01-17 09:03

    The pg_dump utility is distributed with Postgres in the bin directory. The utility accepts many options as documented, and the format is:

    pg_dump  
    

    To answer specifically the question here, open a Command Prompt window (Shell in *nix), and navigate to the Postgres bin directory. Then issue the following command (Windows syntax shown):

    > set DB_NAME=mydatabase
    > pg_dump.exe --username=postgres --schema-only %DB_NAME% >%DB_NAME%-schema.sql
    

    The DB_NAME environment variable is purely for convenience, and the name can be inlined for simplicity.

    The --username switch is required in most cases, as you are probably not logged in to your OS as a valid Postgres user.

    The --schema-only switch indicates that you only want the DDL statements, without the actual data.

    The >%DATABASE_NAME%-schema.sql portion redirects the output from the console to a file named %DATABASE_NAME%-schema.sql, in this example "mydatabase-schema.sql".

    The produced file is a valid SQL script, which can be executed via any valid client in order to recreate all the objects.

    Here are a couple of other useful examples:

    I usually prefix MATERIALIZED VIEWs with mv_, so to dump the definitions for only the relations that start with "mv_*" I use:

    > pg_dump --username=postgres --schema-only --table=mv_* %DB_NAME% >%DB_NAME%-matviews.sql
    

    Use multiple --table= arguments for multiple patterns.

    To script only the POST-DATA objects, e.g. indexes, triggers, etc., use --section=post-data

    > pg_dump --username=postgres --section=post-data %DB_NAME% >%DB_NAME%-post-data.sql
    

    This assumes default host, port, authentication, etc. To specify non-default settings refer to the documentation

提交回复
热议问题