我需要创建一个脚本来删除并重新创建具有依赖顺序的PostgreSQL数据库视图
我尝试使用以下python代码:
# Copyleft ....
import os,sys,shutil,re,glob, getopt
import datetime
#import ogr
#open PostGIS connection
import psycopg2
conn = psycopg2.connect(dbname='XXXXX', port=5432, user='XXXXX', password='XXXXXX', host='XXXXXXX')
# Open a cursor to perform database operations
curr = conn.cursor()
conn.autocommit = True
#create the log file
f1=open('./log_cambio_CRS.txt', 'w')
#create the backup SQL file
ora=datetime.datetime.now()
ora_file=ora.strftime("%Y%m%d_%H%M%S")
nomefile='{0}_backup_viste_SIT2017.sql'.format(ora_file)
f2=open(nomefile, 'w')
#select
sql: str = 'SELECT t.table_schema, t.table_name, t.view_definition, row_number() over() as rowid ' \
'FROM information_schema.views t ' \
'where table_schema not in (\'gdo\', \'information_schema\', \'pg_catalog\', \'cron\', \'public\') ' \
'order by rowid desc;'
print(sql)
curr.execute(sql)
for result in curr:
schema=result[0]
table=result[1]
definition=result[2]
f2.write('CREATE OR REPLACE {0}.{1} AS\n {2}'.format(schema,table,definition))
f2.write('\n\n-- **************************************************\n\n')
curr.close
# new query to drop views - the order need to be the reverse
curr = conn.cursor()
#select
sql: str = 'SELECT t.table_schema, t.table_name ' \
'FROM information_schema.views t ' \
'where table_schema not in (\'gdo\', \'information_schema\', \'pg_catalog\', \'cron\',\'public\');'
print(sql)
curr.execute(sql)
for result in curr:
schema=result[0]
table=result[1]
drop_sql='DROP VIEW {0}.{1};'.format(schema,table);
print(drop_sql)
#curr.execute(drop_sql)
curr.close
curr = conn.cursor()
问题与查询有关
SELECT t.table_schema, t.table_name, t.view_definition, row_number() over() as rowid
FROM information_schema.views t
where table_schema not in ('gdo', 'information_schema', 'pg_catalog', 'cron', 'public')
order by rowid desc;
我不确定创建视图的顺序是否正确。例如,SQL的第一个视图可能依赖于尚未创建的视图,因此SQL将无法工作!
答案 0 :(得分:1)
我部分解决了问题(仅适用于未还原的数据库),并针对需要相同解决方案的人们发布答案:
解决方案是使用包含 relfilenode 字段的 pg_class 表。
创建的SQL备份脚本使用以下规则对视图进行排序:
order by relfilenode;
当我放下视图时,以相反的方式对其进行排序:
order by relfilenode DESC;
用于获取视图定义的查询示例如下:
SELECT t.table_schema, t.table_name, t.view_definition,
row_number() over() as rowid , p.relfilenode
FROM information_schema.views t, pg_class p
where table_schema not in ('gdo', 'information_schema', 'pg_catalog', 'cron', 'public')
and p.relname=t.table_name
order by p.relfilenode;
我希望它会有用,但是我们需要使用 pg_depend 和/或 pg_history
的更好的解决方案有什么例子吗?