PyGreSQL以交互方式运行SQL

时间:2016-07-15 20:23:00

标签: psql greenplum pygresql

我有一个GreenPlum数据库,我正在尝试创建几个外部表。

我使用PyGreSQL包与数据库连接。

但是,我无法逃脱\i(或\dt\du\dv)。

db.query("\i h1/ext/eng/ext_eng" + i + ".sql")

pg.ProgrammingError: ERROR: syntax error at or near "\"

我已尝试"\\i"" '\i' "和其他组合。

1 个答案:

答案 0 :(得分:1)

我不确定通用客户端是否可以使用这些别名。

首先使用Python读取文件\i,然后使用h1/ext/eng/ext_eng.sql将生成的SQL文本流式传输到PyGreSQL,可以避免db.query()

至于\ dt,\ du和\ dv - 可以通过从psql提示符运行\set ECHO_HIDDEN来查看SQL等价物,然后发出每个以查看真正的定义。我已将结果包括在内。

\ DT:

SELECT n.nspname as "Schema",
  c.relname as "Name",
  CASE c.relkind WHEN 'r' THEN 'table' WHEN 'v' THEN 'view' WHEN 'i' THEN 'index' WHEN 'S' THEN 'sequence' WHEN 's' THEN 'special' END as "Type",
  pg_catalog.pg_get_userbyid(c.relowner) as "Owner", CASE c.relstorage WHEN 'h' THEN 'heap' WHEN 'x' THEN 'external' WHEN 'a' THEN 'append only' WHEN 'v' THEN 'none' WHEN 'c' THEN 'append only columnar' WHEN 'p' THEN 'parquet' WHEN 'f' THEN 'foreign' END as "Storage"

FROM pg_catalog.pg_class c
     LEFT JOIN pg_catalog.pg_namespace n ON n.oid = c.relnamespace
WHERE c.relkind IN ('r','')
AND c.relstorage IN ('h', 'a', 'c', 'p','')
      AND n.nspname <> 'pg_catalog'
      AND n.nspname <> 'information_schema'
      AND n.nspname !~ '^pg_toast'
  AND pg_catalog.pg_table_is_visible(c.oid)
ORDER BY 1,2;

\ DU:

SELECT r.rolname, r.rolsuper, r.rolinherit,
  r.rolcreaterole, r.rolcreatedb, r.rolcanlogin,
  r.rolconnlimit,
  ARRAY(SELECT b.rolname
        FROM pg_catalog.pg_auth_members m
        JOIN pg_catalog.pg_roles b ON (m.roleid = b.oid)
        WHERE m.member = r.oid) as memberof
FROM pg_catalog.pg_roles r
ORDER BY 1;

\ DV:

SELECT n.nspname as "Schema",
  c.relname as "Name",
  CASE c.relkind WHEN 'r' THEN 'table' WHEN 'v' THEN 'view' WHEN 'i' THEN 'index' WHEN 'S' THEN 'sequence' WHEN 's' THEN 'special' END as "Type",
  pg_catalog.pg_get_userbyid(c.relowner) as "Owner", CASE c.relstorage WHEN 'h' THEN 'heap' WHEN 'x' THEN 'external' WHEN 'a' THEN 'append only' WHEN 'v' THEN 'none' WHEN 'c' THEN 'append only columnar' WHEN 'p' THEN 'parquet' WHEN 'f' THEN 'foreign' END as "Storage"

FROM pg_catalog.pg_class c
     LEFT JOIN pg_catalog.pg_namespace n ON n.oid = c.relnamespace
WHERE c.relkind IN ('v','')
AND c.relstorage IN ('v','')
      AND n.nspname <> 'pg_catalog'
      AND n.nspname <> 'information_schema'
      AND n.nspname !~ '^pg_toast'
  AND pg_catalog.pg_table_is_visible(c.oid)
ORDER BY 1,2;

它并不理想,但您可以使用这些代码等效替换\ d引用。