Generate SQL to update primary key

后端 未结 4 1485
滥情空心
滥情空心 2020-12-15 06:56

I want to change a primary key and all table rows which reference to this value.

# table master
master_id|name
===============
foo|bar

# table detail
detail         


        
4条回答
  •  孤城傲影
    2020-12-15 07:18

    I found a dirty solution: in psql the command \d master_table show the relevant information. With some text magic, it is possible to extract the needed information:

    echo "UPDATE master_table SET id='NEW' WHERE id='OLD';" > tmp/foreign-keys.txt
    
    psql -c '\d master_table' | grep -P 'TABLE.*CONSTRAINT.*FOREIGN KEY'  \
                                     >> tmp/foreign-keys.txt
    
    reprec '.*TABLE ("[^"]*") CONSTRAINT[^(]*\(([^)]*)\).*' \
            "UPDATE \1 set \2='NEW' WHERE \2='OLD';" \
             tmp/foreign-keys.txt 
    
    psql -1 -f tmp/foreign-keys.txt 
    

    Result:

    UPDATE "master_table" SET id='NEW' WHERE id='OLD';
    UPDATE "other_table" SET master_id='NEW' WHERE master_id='OLD';
    ...
    

    But better solutions are welcome.

提交回复
热议问题