postgresql比對數據庫結構、導入、導出等腳本

-----------------------------強行刪除數據庫-----------------------------

SELECT pg_terminate_backend(pg_stat_activity.pid) FROM pg_stat_activity WHERE datname='dbname' AND pid<>pg_backend_pid();  
DROP DATABASE dbname;

-----------------------------創建數據庫實例-----------------------------

create database dbname owner postgres;

-----------------------------導入、導出(需要輸入密碼)-----------------------------

#備份結構 
pg_dump -h 172.16.100.209  -p 9999 -U postgres -s khb_001_hazcj_080 > /tmp/khb_001_hazcj_080.backup
#備份數據 
pg_dump -h 172.16.100.209  -p 9999 -U postgres -a khb_001_hazcj_080 > /tmp/khb_001_hazcj_080_data.backup  
#恢復結構
psql -d test -h 192.168.171.129 -p 5432 -U postgres -f /tmp/khb_001_hazcj_080.backup 
#恢復數據
psql -d test -h 192.168.171.129 -p 5432 -U postgres -f /tmp/khb_001_hazcj_080_data.backup 
#說明:-h主機名 -p端口 -U用戶名 -s只備份機構 -a只備份數據

-----------------------------導入、導出(無需輸入密碼,但是pg_hba.conf需要設置trust)-----------------------------

#備份結構
pg_dump -s "host=172.16.100.103 port=5432 user=postgres password=postgres dbname=postgres" > /tmp/test.backup
#備份數據
pg_dump -a "host=172.16.100.103 port=5432 user=postgres password=postgres dbname=postgres" > /tmp/test_data.backup
#恢復結構
psql "host=192.168.171.129 port=5432 user=postgres password=postgres dbname=test2" -f /tmp/test.backup
#恢復數據
psql "host=192.168.171.129 port=5432 user=postgres password=postgres dbname=test2" -f /tmp/test_data.backup

-----------------------------比對數據庫表名、字段、字段類型、是否爲空-----------------------------

SELECT R.relname,string_agg (R.fields, ';' ORDER BY R.fields ) AS filedtext 
FROM
	(
	SELECT T.relname,concat ( T.attnum, '|', T.TYPE, '|', T.NAME, '|',T.NOTNULL) AS fields 
	FROM
		(
		SELECT 
		  A.attnum,
			C.relname,
			concat_ws('',T.typname,SUBSTRING ( format_type ( A.atttypid, A.atttypmod ) FROM '\(.*\)' )) AS TYPE,
			A.attname AS NAME,
			A.attnotnull AS NOTNULL 
		FROM
			pg_class AS C,
			pg_attribute AS A,
			pg_type AS T
		WHERE
			A.attrelid = C.oid 
			AND A.atttypid = T.oid
			AND A.attnum > 0 
		) T INNER JOIN ( SELECT tablename FROM pg_tables WHERE schemaname = 'public' ) K ON K.tablename = T.relname 
	ORDER BY T.attnum 
	) R 
GROUP BY R.relname ORDER BY R.relname

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章