Skip to content

Commit

Permalink
Added sqlQueryScalar and fixed documentation on sqlQuery
Browse files Browse the repository at this point in the history
  • Loading branch information
mpscholten committed Oct 1, 2020
1 parent f155170 commit e295a21
Show file tree
Hide file tree
Showing 2 changed files with 22 additions and 4 deletions.
8 changes: 5 additions & 3 deletions Guide/database.markdown
Original file line number Diff line number Diff line change
Expand Up @@ -234,13 +234,15 @@ do
result :: Project <- sqlQuery "SELECT * FROM projects WHERE id = ?" (Only id)
```
You can query any kind of information, not only records:
### Scalar Results
The `sqlQuery` function always returns a list of rows as the result. When the result of your query is a single value (such as a integer or a string) use `sqlQueryScalar`:
```haskell
do
count :: Int <- sqlQuery "SELECT COUNT(*) FROM projects" []
count :: Int <- sqlQueryScalar "SELECT COUNT(*) FROM projects" ()
randomString :: Text <- sqlQuery "SELECT md5(random()::text)" []
randomString :: Text <- sqlQueryScalar "SELECT md5(random()::text)" ()
```
## Create
Expand Down
18 changes: 17 additions & 1 deletion IHP/ModelSupport.hs
Original file line number Diff line number Diff line change
Expand Up @@ -234,13 +234,29 @@ instance Default (PrimaryKey model) => Default (Id' model) where
--
-- __Example:__
--
-- > users <- sqlQuery "SELECT id, firstname, lastname FROM users"
-- > users <- sqlQuery "SELECT id, firstname, lastname FROM users" ()
--
-- Take a look at "IHP.QueryBuilder" for a typesafe approach on building simple queries.
sqlQuery :: (?modelContext :: ModelContext) => (PG.ToRow q, PG.FromRow r) => Query -> q -> IO [r]
sqlQuery = let ModelContext { databaseConnection } = ?modelContext in PG.query databaseConnection
{-# INLINE sqlQuery #-}

-- | Runs a raw sql query which results in a single scalar value such as an integer or string
--
-- __Example:__
--
-- > usersCount <- sqlQuery "SELECT COUNT(*) FROM users"
--
-- Take a look at "IHP.QueryBuilder" for a typesafe approach on building simple queries.
sqlQueryScalar :: (?modelContext :: ModelContext) => (PG.ToRow q, FromField value) => Query -> q -> IO value
sqlQueryScalar query parameters = do
let ModelContext { databaseConnection } = ?modelContext
result <- PG.query databaseConnection query parameters
pure case result of
[PG.Only result] -> result
_ -> error "sqlQueryScalar: Expected a scalar result value"
{-# INLINE sqlQueryScalar #-}

-- | Returns the table name of a given model.
--
-- __Example:__
Expand Down

0 comments on commit e295a21

Please sign in to comment.