Completely copying a postgres table with SQL

前端 未结 7 1253
春和景丽
春和景丽 2021-01-30 06:13

DISCLAIMER: This question is similar to the stack overflow question here, but none of those answers work for my problem, as I will explain later.

I\'m t

7条回答
  •  佛祖请我去吃肉
    2021-01-30 07:03

    WARNING:

    All the answers which use pg_dump and any sort of regular expression to replace the name of the source table are really dangerous. What if your data contains the substring that you are trying to replace? You will end up changing your data!

    I propose a two-pass solution:

    1. eliminate data lines from the dump using some data-specific regexp
    2. perform search-and-replace on the remaining lines

    Here's an example written in Ruby:

    ruby -pe 'gsub(/(members?)/, "\\1_copy_20130320") unless $_ =~ /^\d+\t.*(?:t|f)$/' < members-production-20130320.sql > copy_members_table-20130320.sql
    

    In the above I am trying to copy "members" table into "members_copy_20130320". My data-specific regexp is /^\d+\t.*(?:t|f)$/

    The above type of solution works for me. Caveat emptor...

    edit:

    OK, here's another way in pseudo-shell syntax for the regexp-averse people:

    1. pg_dump -s -t mytable mydb > mytable_schema.sql
    2. search-and-replace table name in mytable_schema.sql > mytable_copy_schema.sql
    3. psql -f mytable_copy_schema.sql mydb

    4. pg_dump -a -t mytable mydb > mytable_data.sql

    5. replace "mytable" in the few SQL statement preceding the data section
    6. psql -f mytable_data.sql mydb

提交回复
热议问题