Skip to content

Commit 4c6f250

Browse files
author
Johannes Gerer
committed
Fix postgresql Migration bug, where migration are not performed or fail because of objects that exist outside of the current schema
1 parent 6d134f7 commit 4c6f250

File tree

1 file changed

+14
-6
lines changed

1 file changed

+14
-6
lines changed

persistent-postgresql/Database/Persist/Postgresql.hs

Lines changed: 14 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -539,8 +539,7 @@ doesTableExist getter (DBName name) = do
539539
stmt <- getter sql
540540
with (stmtQuery stmt vals) (\src -> runConduit $ src .| start)
541541
where
542-
sql = "SELECT COUNT(*) FROM pg_catalog.pg_tables WHERE schemaname != 'pg_catalog'"
543-
<> " AND schemaname != 'information_schema' AND tablename=?"
542+
sql = "SELECT COUNT(*) FROM pg_catalog.pg_tables WHERE schemaname == current_schema() AND tablename=?"
544543
vals = [PersistText name]
545544

546545
start = await >>= maybe (error "No results when checking doesTableExist") start'
@@ -684,10 +683,9 @@ getColumns getter def cols = do
684683
,"c.column_name "
685684
,"FROM information_schema.key_column_usage c, "
686685
,"information_schema.table_constraints k "
687-
,"WHERE c.table_catalog=current_database() "
688-
,"AND c.table_catalog=k.table_catalog "
689-
,"AND c.table_schema=current_schema() "
690-
,"AND c.table_schema=k.table_schema "
686+
,"WHERE "
687+
, currentSchemaAndCatalog "c"
688+
, currentSchemaAndCatalog "k"
691689
,"AND c.table_name=? "
692690
,"AND c.table_name=k.table_name "
693691
,"AND c.column_name <> ? "
@@ -727,6 +725,13 @@ getColumns getter def cols = do
727725
cols <- helper
728726
return $ col' : cols
729727

728+
currentSchemaAndCatalog :: Text -> Text
729+
currentSchemaAndCatalog table = "(" <> T.intercalate " AND " conds <> ")"
730+
where conds = (table <>) <$> [".table_catalog = current_database()"
731+
,".constraint_catalog = current_database()"
732+
,".table_schema = current_schema()"
733+
,".constraint_schema = current_schema()"]
734+
730735
-- | Check if a column name is listed as the "safe to remove" in the entity
731736
-- list.
732737
safeToRemove :: EntityDef -> DBName -> Bool
@@ -812,6 +817,9 @@ getColumn getter tableName' [PersistText columnName, PersistText isNullable, Per
812817
,"information_schema.key_column_usage kcu, "
813818
,"information_schema.table_constraints tc "
814819
,"WHERE tc.constraint_type='FOREIGN KEY' "
820+
, currentSchemaAndCatalog "ccu"
821+
, currentSchemaAndCatalog "kcu"
822+
, currentSchemaAndCatalog "tc"
815823
,"AND kcu.constraint_name=tc.constraint_name "
816824
,"AND ccu.constraint_name=kcu.constraint_name "
817825
,"AND kcu.ordinal_position=1 "

0 commit comments

Comments
 (0)