Skip to content

Commit d7474a4

Browse files
authored
Merge pull request #1376 from digitallyinduced/jannis/sqlQueryScalarMaybe
add sqlQueryScalarMaybe
2 parents 3b66d8d + 2ec3ba7 commit d7474a4

File tree

1 file changed

+21
-0
lines changed

1 file changed

+21
-0
lines changed

IHP/ModelSupport.hs

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -426,6 +426,27 @@ sqlQueryScalar theQuery theParameters = do
426426
_ -> error "sqlQueryScalar: Expected a scalar result value"
427427
{-# INLINABLE sqlQueryScalar #-}
428428

429+
-- | Runs a raw sql query which results in a single scalar value such as an integer or string, or nothing
430+
--
431+
-- __Example:__
432+
--
433+
-- > usersCount <- sqlQueryScalarOrNothing "SELECT COUNT(*) FROM users"
434+
--
435+
-- Take a look at "IHP.QueryBuilder" for a typesafe approach on building simple queries.
436+
sqlQueryScalarOrNothing :: (?modelContext :: ModelContext) => (PG.ToRow q, Show q, FromField value) => Query -> q -> IO (Maybe value)
437+
sqlQueryScalarOrNothing theQuery theParameters = do
438+
result <- measureTimeIfLogging
439+
(withDatabaseConnection \connection -> enhanceSqlError theQuery theParameters do
440+
PG.query connection theQuery theParameters
441+
)
442+
theQuery
443+
theParameters
444+
pure case result of
445+
[] -> Nothing
446+
[PG.Only result] -> Just result
447+
_ -> error "sqlQueryScalarOrNothing: Expected a scalar result value or an empty result set"
448+
{-# INLINABLE sqlQueryScalarOrNothing #-}
449+
429450
-- | Executes the given block with a database transaction
430451
--
431452
-- __Example:__

0 commit comments

Comments
 (0)