是否可以通过 RPostgresql 运行 Postgres 反斜杠命令?

Is it possible to run Postgres backslash commands via RPostgresql?

Postgres 有许多方便的 "backslash" 命令(例如 \dt\du\l 等)。我想通过 RPostgresql 接口 运行 这些。我尝试了以下方法:

drv = dbDriver("PostgreSQL")
con <- dbConnect(drv, 
                 dbname = "my_database", 
                 host = "**********", 
                 port = ****, 
                 user = "******", 
                 password = "******")

dbExecute(con, "\dt")

# Close PostgreSQL connection  
dbDisconnect(con) 

但是,我收到以下错误:

Error in postgresqlExecStatement(conn, statement, ...) : 
RS-DBI driver: (could not Retrieve the result : ERROR:  syntax error at or 
near "\"
LINE 1: \dt
        ^
)

是否可以从 RPostgresql 中 运行 这些?还是反斜杠命令仅限于命令行 psql

反斜杠命令由 psql CLI 工具解释,底层客户端库不知道它们是什么,PostgreSQL 服务器也不知道。 RPostgresql 将使用客户端库(或者可能直接使用 PostgreSQL 协议与服务器通信),因此反斜杠命令将不可用。

然而,反斜杠命令大多只是访问 PostgreSQL 系统表的查询的方便包装器。 psql has a -E switch 让您看到这些查询:

-E
--echo-hidden
Echo the actual queries generated by \d and other backslash commands. You can use this to study psql's internal operations. This is equivalent to setting the variable ECHO_HIDDEN to on.

所以你可以 运行 psql -E ... 看看,例如 \dt 是如何实现的:

=> \dt
********* 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' WHEN 'p' THEN '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','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;
**************************

                       List of relations
...

然后 运行 SQL 就像 RPostgre 中的任何其他查询一样 SQL.