Skip to content

Instantly share code, notes, and snippets.

@begriffs
Created February 8, 2016 22:28
Show Gist options
  • Select an option

  • Save begriffs/de97bc4c73262f362dd9 to your computer and use it in GitHub Desktop.

Select an option

Save begriffs/de97bc4c73262f362dd9 to your computer and use it in GitHub Desktop.
Lock row exclusive on update requests
diff --git a/src/PostgREST/App.hs b/src/PostgREST/App.hs
index d1d27b4..b701501 100644
--- a/src/PostgREST/App.hs
+++ b/src/PostgREST/App.hs
@@ -53,6 +53,7 @@ import PostgREST.QueryBuilder ( callProc
, addRelations
, createReadStatement
, createWriteStatement
+ , lockRowExclusive
, ResultsWithCount
)
@@ -124,6 +125,7 @@ app dbStructure conf reqBody req =
Left e -> return $ responseLBS status400 [jsonH] $ cs e
Right (sq,mq) -> do
let stm = createWriteStatement qi sq mq False (iPreferRepresentation apiRequest) [] (contentType == TextCSV) payload
+ lockRowExclusive qi
row <- H.query uniform stm
let (_, queryTotal, _, body) = extractQueryResult row
r = contentRangeH 0 (toInteger $ queryTotal-1) (toInteger <$> Just queryTotal)
diff --git a/src/PostgREST/QueryBuilder.hs b/src/PostgREST/QueryBuilder.hs
index 0da8118..103999e 100644
--- a/src/PostgREST/QueryBuilder.hs
+++ b/src/PostgREST/QueryBuilder.hs
@@ -19,6 +19,7 @@ module PostgREST.QueryBuilder (
, createReadStatement
, createWriteStatement
, inTransaction
+ , lockRowExclusive
, operators
, pgFmtIdent
, pgFmtLit
@@ -361,6 +362,11 @@ requestToQuery schema (DbMutate (Delete mainTbl conditions)) =
("WHERE " <> intercalate " AND " ( map (pgFmtCondition qi ) conditions )) `emptyOnNull` conditions
]
+lockRowExclusive :: QualifiedIdentifier -> H.Session ()
+lockRowExclusive qi =
+ H.sql [qc| LOCK TABLE {fromQi qi} IN SHARE ROW EXCLUSIVE MODE; |]
+
+
sourceCTEName :: SqlFragment
sourceCTEName = "pg_source"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment