获取任何Postgres元命令的等效SQL查询


11

我希望标题是可自我描述的。我希望能够以某种方式将任何Postgres元命令转换为其相应/底层的SQL查询,至少要了解有关Postgres及其在表中存储元信息的方式的更多信息。

有什么想法可能吗?

例如:

当连接到数据库EXAMPLE时, \dtSELECT table_schema,table_name FROM information_schema.tables ORDER BY table_schema,table_name;返回相同的结果。

如果可能,我想找到一种SELECT table_schema,table_name FROM information_schema.tables ORDER BY table_schema,table_name;在输入\dt函数/宏/任何内容时获取值的方法。

Answers:


17

简单且非常有用:您可以使用适当的开关(-E)启动psql以获取信息。

me@mystation:~/ > psql -E 
psql (9.3.11)
Type "help" for help.
me@mystation # \d
********* QUERY **********
SELECT n.nspname as "Schema",
  c.relname as "Name",
  CASE c.relkind WHEN 'r' THEN 'table' WHEN 'v' THEN 'view' WHEN 'm' THEN 'materialized view' WHEN 'i' THEN 'index' WHEN 'S' THEN 'sequence' WHEN 's' THEN 'special' WHEN 'f' THEN 'foreign table' END as "Type",
  pg_catalog.pg_get_userbyid(c.relowner) as "Owner"
FROM pg_catalog.pg_class c
     LEFT JOIN pg_catalog.pg_namespace n ON n.oid = c.relnamespace
WHERE c.relkind IN ('r','v','m','S','f','')
      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;

有关更多信息,请访问http://www.postgresql.org/docs/current/static/app-psql.html。一旦进入psql,您还可以设置ECHO_HIDDEN变量。


1
非常有前途!但是,当我尝试使用“ psql -E mytable”获取表定义时,它报告了几个查询,当单独发出这些查询时,这些查询均未返回任何有用的信息,因此发生了未报告的情况。
philwalk '18
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.