有没有一个简单的函数,可以测试在PostgreSQL中是否存在视图? 对于表,我正在使用类似以下内容的东西:
但是由于我的代码还可以接受视图,因此我需要使用类似这样的查询:
这是它的工作原理:
table_name <- 'tmp.test'
con <- c('a','b','c','d','5432')
drv <- dbDriver("PostgreSQL")
con <- dbConnect(drv, user=con[1], password=con[2], dbname=con[3], host=con[4],
port=con[5])
table_exists <- dbExistsTable(con,table_name)
dbDisconnect(con)
但是由于我的代码还可以接受视图,因此我需要使用类似这样的查询:
table_name <- 'tmp.test'
con <- c('a','b','c','d','5432')
drv <- dbDriver("PostgreSQL")
con <- dbConnect(drv, user=con[1], password=con[2], dbname=con[3], host=con[4],
port=con[5])
sql <- paste0("select count(*) > 0 from information_schema.tables
where table_schema || '.' || table_name = '", table_name,"'")
table_exists <- dbGetQuery(con,sql)[1,1]
dbDisconnect(con)
这个方法可以工作,但感觉好像错过了一些现有的 R 函数。
更新:对于那些感兴趣的人,这是 PostgreSQL 中 dbExistsTable
方法的定义:
setMethod("dbExistsTable",
signature(conn="PostgreSQLConnection", name="character"),
def = function(conn, name, ...){
qlength <- length(name)
if(qlength == 1){
currentschema <- dbGetQuery(conn, "SELECT current_schema()")
res <- dbGetQuery(conn,
paste("select tablename from pg_tables where ",
"schemaname !='information_schema' and schemaname !='pg_catalog' ",
"and schemaname='", postgresqlEscapeStrings(conn, currentschema[[1]]), "' ",
"and tablename='", postgresqlEscapeStrings(conn, name), "'", sep=""))
}
else{
if(qlength == 2){
res <- dbGetQuery(conn,
paste("select tablename from pg_tables where ",
"schemaname !='information_schema' and schemaname !='pg_catalog' ",
"and schemaname='", postgresqlEscapeStrings(conn, name[1]), "' ",
"and tablename='", postgresqlEscapeStrings(conn, name[2]), "'", sep=""))
}
}
return(as.logical(dim(res)[1]))
},
valueClass = "logical"
)
这是它的工作原理:
- 可以使用一个或两个元素的字符向量指定名称
- 如果名称只有一个元素,则在
current_schema
(search_path
中的第一个模式)中搜索表 - 如果名称有两个元素,则假定第一个是模式,第二个是表的实际名称
注意事项:
- 只搜索表,不搜索视图(因为使用了
pg_tables
) information_schema
和pg_catalog
被排除在搜索范围之外
dbTableExists
函数也不接受视图?奇怪。通常,像这样的函数实际上会接受任何关系 - 视图、表、序列、外部表等。 - Craig Ringerpg_tables
中的内容。也许我应该提出一个新的方法,类似于dbExistsRelation
,或者它适用于其他 RDBMs 的视图,但对于 PostgreSQL 来说是错误的。 - Tomas Greif