【问题标题】:DDL change in multiple postgresql instances at the same time?同时在多个postgresql实例中更改DDL?
【发布时间】:2012-09-12 07:28:01
【问题描述】:

在 1 台服务器上运行 4 个 postgresql 实例。我想同时对所有这些进行 ddl 更改。

我该怎么做?

【问题讨论】:

  • 感谢您删除转发。

标签: postgresql database-schema ddl database-administration


【解决方案1】:

编写一个 shell 脚本(如果您使用 *nix)或.cmd 批处理文件/.vbs(如果您使用 Windows)来执行此操作。让脚本调用 psql -f /path/to/ddl.sql 和 IP/端口、数据库名称等。

或者,使用具有适当 PostgreSQL 绑定的 Python 等语言编写脚本。让脚本循环遍历数据库并为每个数据库运行 DDL。例如,在 Python 中,以下(未经测试的)脚本应该可以解决问题:

import psycopg2
conn_definitions = [
    "dbname=db1 port=5432 host=127.0.0.1",
    "dbname=db2 port=5432 host=127.0.0.1",
    "dbname=db3 port=5432 host=127.0.0.1",
    "dbname=db4 port=5432 host=127.0.0.1",
]
ddl = """
    CREATE TABLE blah (
        blah integer
    );
    CREATE INDEX blah_blah_idx ON blah(blah);
"""
connections = []
cursors = []
for conn_info in conn_definitions:
    conn = psycopg2.connect(conn_info)
    curs = conn.cursor()
    cursors.append(curs)
    connections.append(conn)
 for curs in cursors:
    curs.execute("BEGIN;")
 for curs in cursors:
    curs.execute(ddl)
 for curs in cursors:
    curs.execute("COMMIT;")
 for conn in connections:
    conn.close()

如果需要,可以通过将 DDL 拆分为循环遍历的语句数组来进行增强,这样您就可以执行每个语句的错误处理。

您还可以通过为每个主机连接到一个 DB 并运行 select datname from pg_database 来获取其他 DB 的列表来动态生成连接。

【讨论】:

  • 感谢您的回答,但这不是我正在寻找的答案。
  • @TraviJuu 然后你需要澄清你的问题以详细解释你做什么想要什么,因为这解释了如何按照你的要求去做。您可以编辑您的问题以添加更多信息。
  • 使用触发器和dblink?
  • @TraviJuu PostgreSQL 没有 DDL 触发器,因此您不能通过 dblink 使一个数据库中的 DDL 更改触发其他数据库中的 DDL 更改。同样,您需要更详细地解释您想要做什么以及为什么。编辑您的问题并详细说明。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-04-13
  • 2012-11-07
  • 2015-04-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多