Skip to content

Commit

Permalink
Schema support for PostgreSQL backend
Browse files Browse the repository at this point in the history
  • Loading branch information
arrowd committed Jan 27, 2023
1 parent e465627 commit dbc038e
Showing 1 changed file with 12 additions and 5 deletions.
17 changes: 12 additions & 5 deletions persistent-postgresql/Database/Persist/Postgresql.hs
Original file line number Diff line number Diff line change
Expand Up @@ -437,7 +437,7 @@ createBackend logFunc serverVersion smap conn =
, connCommit = const $ PG.commit conn
, connRollback = const $ PG.rollback conn
, connEscapeFieldName = escapeF
, connEscapeTableName = escapeE . getEntityDBName
, connEscapeTableName = \entDef -> prependSchemaAndEscape entDef $ getEntityDBName entDef
, connEscapeRawName = escape
, connNoLimit = "LIMIT ALL"
, connRDBMS = "postgresql"
Expand Down Expand Up @@ -760,7 +760,8 @@ getColumns :: (Text -> IO Statement)
-> EntityDef -> [Column]
-> IO [Either Text (Either Column (ConstraintNameDB, [FieldNameDB]))]
getColumns getter def cols = do
let sqlv = T.concat
let tableSchema = fromMaybe "current_schema()" (getEntityDBSchema def)
sqlv = T.concat
[ "SELECT "
, "column_name "
, ",is_nullable "
Expand All @@ -772,7 +773,7 @@ getColumns getter def cols = do
, ",character_maximum_length "
, "FROM information_schema.columns "
, "WHERE table_catalog=current_database() "
, "AND table_schema=current_schema() "
, "AND table_schema=" <> tableSchema <> " "
, "AND table_name=? "
]

Expand All @@ -797,7 +798,7 @@ getColumns getter def cols = do
, "information_schema.table_constraints AS k "
, "WHERE c.table_catalog=current_database() "
, "AND c.table_catalog=k.table_catalog "
, "AND c.table_schema=current_schema() "
, "AND c.table_schema=" <> tableSchema <> " "
, "AND c.table_schema=k.table_schema "
, "AND c.table_name=? "
, "AND c.table_name=k.table_name "
Expand Down Expand Up @@ -1338,6 +1339,12 @@ showAlter table (DropReference cname) = T.concat
, escapeC cname
]

prependSchemaAndEscape :: EntityDef -> EntityNameDB -> Text
prependSchemaAndEscape entDef entDBName = case getEntityDBSchema entDef of
Nothing -> escapeE entDBName
Just "public" -> escapeE entDBName
Just schema -> escape schema <> "." <> escapeE entDBName

-- | Get the SQL string for the table that a PeristEntity represents.
-- Useful for raw SQL queries.
tableName :: (PersistEntity record) => record -> Text
Expand Down Expand Up @@ -1574,7 +1581,7 @@ mockMigration mig = do
, connCommit = undefined
, connRollback = undefined
, connEscapeFieldName = escapeF
, connEscapeTableName = escapeE . getEntityDBName
, connEscapeTableName = \entDef -> prependSchemaAndEscape entDef $ getEntityDBName entDef
, connEscapeRawName = escape
, connNoLimit = undefined
, connRDBMS = undefined
Expand Down

0 comments on commit dbc038e

Please sign in to comment.