packages feed

hasql-th-kronor (empty) → 0.5.1.1

raw patch · 15 files changed

+2395/−0 lines, 15 filesdep +basedep +containersdep +contravariant

Dependencies added: base, containers, contravariant, foldl, hasql, hasql-th-kronor, postgresql-syntax-kronor, template-haskell, template-haskell-compat-v0208, text, transformers, uuid, vector

Files

+ CHANGELOG.md view
@@ -0,0 +1,3 @@+# v0.5.1.1++- Conform to the new `hasql` API (v2.0)
+ LICENSE view
@@ -0,0 +1,22 @@+Copyright (c) 2015, Nikita Volkov++Permission is hereby granted, free of charge, to any person+obtaining a copy of this software and associated documentation+files (the "Software"), to deal in the Software without+restriction, including without limitation the rights to use,+copy, modify, merge, publish, distribute, sublicense, and/or sell+copies of the Software, and to permit persons to whom the+Software is furnished to do so, subject to the following+conditions:++The above copyright notice and this permission notice shall be+included in all copies or substantial portions of the Software.++THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,+EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES+OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND+NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT+HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,+WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING+FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR+OTHER DEALINGS IN THE SOFTWARE.
+ README.md view
@@ -0,0 +1,178 @@+# Summary++An extension library for the ["hasql"](https://github.com/nikita-volkov/hasql) Postgres driver, bringing compile-time syntax checking of queries atop of a great simplification of declaration of statements. All the user needs to do is just specify SQL.++Here's a brief example of how it works:++> **Note:** these quasiquoters require the `QuasiQuotes` language extension.+> In a Haskell module, add `{-# LANGUAGE QuasiQuotes #-}`; in GHCi, run+> `:set -XQuasiQuotes`.++```haskell+{-# LANGUAGE QuasiQuotes #-}++selectUserDetails :: Statement Int32 (Maybe (Text, Text, Maybe Text))+selectUserDetails =+  [maybeStatement|+    select name :: text, email :: text, phone :: text?+    from "user"+    where id = $1 :: int4+    |]+```++As you can see, it completely eliminates the need to deal with codecs. The quasiquoters directly produce `Statement`, which you can then [`dimap`](https://hackage.haskell.org/package/profunctors-5.5.1/docs/Data-Profunctor.html#v:dimap) over using its `Profunctor` instance to get to your domain types.++<details>+<summary>Examples of mapping to custom types</summary>++```haskell+newtype UserId = UserId Int32++data UserDetails = UserDetails {+  _name :: Text,+  _email :: Text,+  _phone :: Maybe Text+}++selectUserDetails :: Statement UserId (Maybe UserDetails)+selectUserDetails =+  dimap+    (\ (UserId a) -> a)+    (\ case+      Just (a, b, c) -> Just (UserDetails a b c)+      Nothing -> Nothing)+    [maybeStatement|+      select name :: text, email :: text, phone :: text?+      from "user"+      where id = $1 :: int4+      |]+```++Using some Haskell's advanced techniques and the ["tuple"](http://hackage.haskell.org/package/tuple) library we can reduce the boilerplate in the previous definition:++```haskell+import Data.Tuple.Curry -- from the "tuple" library++selectUserDetails :: Statement UserId (Maybe UserDetails)+selectUserDetails =+  dimap coerce (fmap (uncurryN UserDetails))+    [maybeStatement|+      select name :: text, email :: text, phone :: text?+      from "user"+      where id = $1 :: int4+      |]+```++</details>++# Status++The library supports almost all of Postgresql syntax available for preparable statements. This includes Select, Insert, Update and Delete among others. The only thing that is not supported yet is some of its very rarely used XML-related features.++## Quality++The parser and renderer get heavily tested using the following property: rendering a random AST then parsing it should produce the same AST. This pretty much covers most possible reasons for bugs in the library.++# Implementation++This library internally implements a port of the original Postgres SQL syntax parser. It might sound like an overkill, but there really were no better options.++Unfortunately Postgres doesn't export it's own parser in any of its distributions, so there's no C-library to link to and wrap.++Isolating the original C-code and including it in a Haskell project is also not an option, because it's heavily based on code generators and complex make-file instructions. Maintaining such a codebase also seems like a non-viable option.++Fortunately the original parser is implemented using a declarative notation (the one which the mentioned code generators work with). It being declarative makes the process of porting to Haskell quite straight-forward. ++Also for the purposes of this library we need access to the full syntax tree for extracting data on placeholders and statement results. Quick and dirty hacks won't do.++For these reasons it's been decided to port the original parser and AST as close as possible to Haskell using the "megaparsec" library.++# Error messages++The parser turns out to be actually better than the one in Postgres in terms of error-reporting. That's because of Haskell's superabilities in the area of parsing compared to C. The library uses the ["megaparsec"](http://hackage.haskell.org/package/megaparsec) library and the ["headed-megaparsec"](http://hackage.haskell.org/package/headed-megaparsec) extension for it. As the result of that, the error messages produced by this parser are more informative than the ones in Postgres. Following are a few examples.++## Error example 1++Consider the following broken statement:++```sql+select 1 from a where b >= 3 && b < 4+```++It is incorrect, because it uses `&&` instead of `and`. But here's what Postgres' original parser says about it:++```+ERROR:  syntax error at or near "<"+LINE 1: select 1 from a where b >= 3 && b < 4;+                                          ^+```++Here's what "hasql-th" says:++```+  |+2 |     select 1 from a where b >= 3 && b < 4;+  |                                  ^+unexpected '&'+```++## Error example 2++It's not obvious what is wrong in the following statement either:++```sql+insert into user (name) values ($1)+```++The Postgres parser doesn't help much:++```+ERROR:  syntax error at or near "user"+LINE 1: insert into user (name) values ($1);+                    ^+```++Here's what "hasql-th" says though:++```+  |+2 |       insert into user (name) values ($1)+  |                       ^+Reserved keyword "user" used as an identifier. If that's what you intend, you have to wrap it in double quotes.+```++## Error example 3++It turns out that the original Postgres parser never produces any other messages than the opaque "syntax error at or near". "hasql-th" on the other hand is quite descriptive. E.g., here's how it gradually guides to insert the missing expected pieces.++Input:++```haskell+[resultlessStatement|insert into |]+```++Error:++```+  |+1 | insert into +  |             ^+unexpected end of input+expecting identifier or white space+```++Input:++```haskell+[resultlessStatement|insert into a |]+```++Error:++```+  |+1 | insert into a +  |               ^+unexpected end of input+expecting "default", "overriding", "select", "values", '(', white space, or with clause+```
+ hasql-th-kronor.cabal view
@@ -0,0 +1,145 @@+cabal-version: 3.0+name: hasql-th-kronor+version: 0.5.1.1+category: Hasql, Database, PostgreSQL, Template Haskell+synopsis: Template Haskell utilities for Hasql, with Kronor's quasiquote extensions+description:+  Kronor's fork of "hasql-th", an extension-library for Hasql,+  bringing compile-time syntax checking,+  great simplification of declaration of statements and+  other TemplateHaskell-based utilities.++  The quasiquotes also accept Haskell function, constructor and record+  targets in the select list, and Haskell fields on parameter placeholders+  (documented in "Hasql.TH"). It exposes the same modules as "hasql-th" and+  parses with "postgresql-syntax-kronor".++  For details please see <https://github.com/kronor-io/hasql-th the readme>.++homepage: https://github.com/kronor-io/hasql-th+bug-reports: https://github.com/kronor-io/hasql-th/issues+author: Nikita Volkov <nikita.y.volkov@mail.ru>+maintainer: José Lorenzo Rodríguez <lorenzo@kronor.io>+copyright: (c) 2015, Nikita Volkov+license: MIT+license-file: LICENSE+extra-doc-files:+  CHANGELOG.md+  README.md++source-repository head+  type: git+  location: https://github.com/kronor-io/hasql-th+  branch: hackage++common base+  default-language: Haskell2010+  default-extensions:+    ApplicativeDo+    Arrows+    BangPatterns+    ConstraintKinds+    DataKinds+    DefaultSignatures+    DeriveDataTypeable+    DeriveFoldable+    DeriveFunctor+    DeriveGeneric+    DeriveTraversable+    DuplicateRecordFields+    EmptyDataDecls+    FlexibleContexts+    FlexibleInstances+    FunctionalDependencies+    GADTs+    GeneralizedNewtypeDeriving+    LambdaCase+    LiberalTypeSynonyms+    MagicHash+    MultiParamTypeClasses+    MultiWayIf+    NoImplicitPrelude+    NoMonomorphismRestriction+    OverloadedStrings+    ParallelListComp+    PatternGuards+    QuasiQuotes+    RankNTypes+    RecordWildCards+    ScopedTypeVariables+    StandaloneDeriving+    TemplateHaskell+    TupleSections+    TypeFamilies+    TypeOperators+    UnboxedTuples++common executable+  import: base+  ghc-options:+    -O2+    -threaded+    -with-rtsopts=-N+    -rtsopts+    -funbox-strict-fields++common test+  import: base+  ghc-options:+    -threaded+    -with-rtsopts=-N++library+  import: base+  hs-source-dirs: src/library+  exposed-modules:+    Hasql.TH+    Hasql.TH.Construction.Exp+    Hasql.TH.Extraction.ChildExprList+    Hasql.TH.Extraction.Exp+    Hasql.TH.Extraction.InputTypeList+    Hasql.TH.Extraction.OutputHsTarget+    Hasql.TH.Extraction.OutputTypeList+    Hasql.TH.Extraction.PlaceholderTypeMap+    Hasql.TH.Extraction.PrimitiveType+    Hasql.TH.Prelude++  build-depends:+    base >=4.11 && <5,+    containers >=0.6 && <0.9,+    contravariant >=1.5.2 && <2,+    foldl >=1.4.5 && <2,+    hasql >=1.10 && <1.11 || >=2.0 && <2.1,+    postgresql-syntax-kronor ^>=0.5.0.3,+    template-haskell >=2.8 && <3,+    template-haskell-compat-v0208 >=0.1.9 && <0.2,+    text >=1 && <3,+    transformers >=0.5 && <0.7,+    uuid >=1.3 && <2,+    vector >=0.12 && <0.14,++-- Write the smoke test's spliced code to dist-newstyle, to read what each+-- extension expands to: cabal test -f dump-splices+flag dump-splices+  description: Dump the smoke test's Template Haskell splices to files.+  default: False+  manual: True++test-suite smoke+  type: exitcode-stdio-1.0+  default-language: Haskell2010+  hs-source-dirs: smoke+  main-is: Main.hs++  if flag(dump-splices)+    ghc-options:+      -ddump-splices+      -ddump-to-file+      -dsuppress-uniques++  build-depends:+    base >=4.11 && <5,+    hasql >=2.0 && <2.1,+    hasql-th-kronor,+    text >=1 && <3,+    vector >=0.12 && <0.14,
+ smoke/Main.hs view
@@ -0,0 +1,153 @@+{-# LANGUAGE OverloadedRecordDot #-}+{-# LANGUAGE OverloadedStrings #-}+{-# LANGUAGE QuasiQuotes #-}++-- |+-- A module that exists to be compiled. Every binding below is a quasiquote+-- using one of the extensions, given an explicit type signature that the+-- generated code has to agree with, so that a wrong mapping lambda is a+-- compile error rather than something to eyeball.+--+-- Built with @-ddump-splices@; the dump is checked in as @smoke/splices.txt@.+module Main (main) where++import Data.Int (Int32, Int64)+import Data.Text (Text)+import Data.Vector (Vector)+import Hasql.Statement (Statement)+import Hasql.TH++-- * The Haskell side++data User = User+  { userId :: Int64,+    userName :: Text+  }+  deriving (Show)++defaultUser :: User+defaultUser = User 0 "anonymous"++mkUser :: Int64 -> Text -> User+mkUser = User++widen :: Int32 -> Int64+widen = fromIntegral++data Flag = Flag+  deriving (Show)++data Note = Note Int64 (Maybe Text)+  deriving (Show)++mkNote :: Int64 -> Maybe Text -> Note+mkNote = Note++data Merchant = Merchant+  { merchantId :: Int32,+    signatureKey :: Text+  }++-- * The statements++-- | Function target with arguments. One target over two columns, so the+-- mapping lambda must be @\\(fn1, fn2) -> mkUser fn1 fn2@ and not wrap the+-- result in a one-element tuple.+functionTarget :: Statement () User+functionTarget =+  [singletonStatement|+    select $mkUser (id :: int8, name :: text) from "user"+    |]++-- | Nullary target: a bare value, consuming no columns. Upper case, so it+-- becomes a @ConE@ and the @all VarE@ guard does not swallow the mapping.+--+-- Two sibling columns rather than one, because @mkMapping@ takes the+-- single-column branch whenever the statement returns one column and that+-- branch keeps only the first target. A nullary target next to exactly one+-- SQL column therefore drops the column; that is the 0.4 fork's behaviour,+-- preserved here deliberately.+nullaryTarget :: Statement () (Flag, Int64, Text)+nullaryTarget =+  [singletonStatement|+    select $Flag (), id :: int8, name :: text from "user"+    |]++-- | Upper-case name is a data constructor.+constructorTarget :: Statement () User+constructorTarget =+  [singletonStatement|+    select $User (id :: int8, name :: text) from "user"+    |]++-- | Record construction.+recordConstruction :: Statement () User+recordConstruction =+  [singletonStatement|+    select $User {userId = id :: int8, userName = name :: text} from "user"+    |]++-- | Record update: lower-case name, so @RecUpdE@ over the named value.+recordUpdate :: Statement () User+recordUpdate =+  [singletonStatement|+    select $defaultUser {userName = name :: text} from "user"+    |]++-- | A function target nested inside a record field.+nestedTarget :: Statement () User+nestedTarget =+  [singletonStatement|+    select $User {userId = $widen (id :: int4), userName = name :: text} from "user"+    |]++-- | Haskell and plain SQL targets in one select list.+mixedTargets :: Statement () (User, Text)+mixedTargets =+  [singletonStatement|+    select $mkUser (id :: int8, name :: text), created :: text from "user"+    |]++-- | Two fields off one parameter plus a bare second parameter. The statement+-- takes @(Merchant, Text)@, not three separate parameters.+paramFields :: Statement (Merchant, Text) Int64+paramFields =+  [singletonStatement|+    select id :: int8 from "user"+    where merchant = $1.$merchantId :: int4+      and key = $1.$signatureKey :: text+      and status = $2 :: text+    |]++-- | A single parameter with a field is a bare lambda pattern, not a+-- one-element tuple pattern.+singleParamField :: Statement Merchant Int64+singleParamField =+  [singletonStatement|+    select id :: int8 from "user" where merchant = $1.$merchantId :: int4+    |]++-- | Nullability marker inside a Haskell target: @text?@ decodes to+-- @Maybe Text@, so @mkNote@ is applied at that type.+nullableInTarget :: Statement () Note+nullableInTarget =+  [singletonStatement|+    select $mkNote (id :: int8, note :: text?) from "note"+    |]++-- | No extension at all. The splice for this one must be exactly what+-- upstream emits: no @fmap@, no @contramap@.+plainStatement :: Statement (Int32, Text) (Vector (Int64, Text))+plainStatement =+  [vectorStatement|+    select id :: int8, name :: text from "user" where merchant = $1 :: int4 and status = $2 :: text+    |]++main :: IO ()+main =+  mapM_+    putStrLn+    [ "functionTarget, nullaryTarget, constructorTarget, recordConstruction,",+      "recordUpdate, nestedTarget, mixedTargets, paramFields, singleParamField,",+      "nullableInTarget and plainStatement all compiled."+    ]
+ src/library/Hasql/TH.hs view
@@ -0,0 +1,346 @@+module Hasql.TH+  ( -- * Statements++    -- |+    --  Quasiquoters in this category produce Hasql `Statement`s,+    --  checking the correctness of SQL at compile-time.+    --+    --  To extract the information about parameters and results of the statement,+    --  the quoter requires you to explicitly specify the Postgres types for placeholders and results.+    --+    --  Here's an example of how to use it:+    --+    --  Enable the @QuasiQuotes@ language extension in any module that uses+    --  these quasiquoters:+    --+    --  >{-# LANGUAGE QuasiQuotes #-}+    --+    --  >selectUserDetails :: Statement Int32 (Maybe (Text, Text, Maybe Text))+    --  >selectUserDetails =+    --  >  [maybeStatement|+    --  >    select name :: text, email :: text, phone :: text?+    --  >    from "user"+    --  >    where id = $1 :: int4+    --  >    |]+    --+    --  As you can see, it completely eliminates the need to mess with codecs.+    --  The quasiquoters directly produce `Statement`,+    --  which you can then `Data.Profunctor.dimap` over using its `Data.Profunctor.Profunctor` instance to get to your domain types.+    --+    --  == Type mappings+    --+    --  === Primitives+    --+    --  Following is a list of supported Postgres types and their according types on the Haskell end.+    --+    --  - @bool@ - `Bool`+    --  - @int2@ - `Int16`+    --  - @int4@ - `Int32`+    --  - @int8@ - `Int64`+    --  - @float4@ - `Float`+    --  - @float8@ - `Double`+    --  - @numeric@ - `Data.Scientific.Scientific`+    --  - @char@ - `Char`+    --  - @text@ - `Data.Text.Text`+    --  - @bytea@ - `Data.ByteString.ByteString`+    --  - @date@ - `Data.Time.Day`+    --  - @timestamp@ - `Data.Time.LocalTime`+    --  - @timestamptz@ - `Data.Time.UTCTime`+    --  - @time@ - `Data.Time.TimeOfDay`+    --  - @timetz@ - @(`Data.Time.TimeOfDay`, `Data.Time.TimeZone`)@+    --  - @interval@ - `Data.Time.DiffTime`+    --  - @uuid@ - `Data.UUID.UUID`+    --  - @inet@ - @(`Network.IP.Addr.NetAddr` `Network.IP.Addr.IP`)@+    --  - @json@ - `Data.Aeson.Value`+    --  - @jsonb@ - `Data.Aeson.Value`+    --+    --  === Arrays+    --+    --  Array mappings are also supported.+    --  They are specified according to Postgres syntax: by appending one or more @[]@ to the primitive type,+    --  depending on how many dimensions the array has.+    --  On the Haskell end array is mapped to generic `Data.Vector.Generic.Vector`,+    --  allowing you to choose which particular vector implementation to map to.+    --+    --  === Nulls+    --+    --  As you might have noticed in the example,+    --  we introduce one change to the Postgres syntax in the way+    --  the typesignatures are parsed:+    --  we interpret question-marks in them as specification of nullability.+    --  Here's more examples of that:+    --+    --  >>> :t [singletonStatement| select a :: int4? |]+    --  ...+    --    :: Statement () (Maybe Int32)+    --+    --  You can use it to specify the nullability of array elements:+    --+    --  >>> :t [singletonStatement| select a :: int4?[] |]+    --  ...+    --    :: Data.Vector.Generic.Base.Vector v (Maybe Int32) =>+    --       Statement () (v (Maybe Int32))+    --+    --  And of arrays themselves:+    --+    --  >>> :t [singletonStatement| select a :: int4?[]? |]+    --  ...+    --    :: Data.Vector.Generic.Base.Vector v (Maybe Int32) =>+    --       Statement () (Maybe (v (Maybe Int32)))++    --  === Haskell function and constructor targets+    --+    --  A select-list target may be a Haskell function or data constructor+    --  applied to the columns that follow it, written @$name (col1, col2)@.+    --  The columns are decoded as usual and the result of the application+    --  becomes that position of the row.+    --+    --  >>> data User = User { userId :: Int32, userName :: Text }+    --  >>> :t [singletonStatement| select $User (id :: int4, name :: text) from "user" |]+    --  ... :: Statement () User+    --+    --  A name whose first character is upper case is treated as a data+    --  constructor, any other name as an ordinary function, so+    --  @$mkUser (...)@ calls the function @mkUser@. Applications nest, and a+    --  target list may freely mix Haskell targets with plain SQL ones. Writing+    --  no arguments at all, @$defaultUser ()@, is a bare value rather than an+    --  application and consumes no columns.+    --+    --  === Haskell record targets+    --+    --  A target written @$name {field = col, ...}@ builds or updates a record.+    --  An upper-case name is record construction, a lower-case one is record+    --  update of the value that name refers to.+    --+    --  >>> :t [singletonStatement| select $User {userId = id :: int4, userName = name :: text} from "user" |]+    --  ... :: Statement () User+    --+    --  Field values are themselves targets, so they may be nested Haskell+    --  targets rather than plain columns.+    --+    --  === Haskell fields on parameter placeholders+    --+    --  A placeholder may select a field of the Haskell value it is given,+    --  written @$1.$field@. Every distinct @(placeholder, field)@ pair becomes+    --  one parameter of the emitted statement, and the statement's parameter+    --  type is the tuple of the /original/ placeholders, so several fields of+    --  one value cost one parameter rather than several.+    --+    --  >>> data Merchant = Merchant { merchantId :: Int32, signatureKey :: Text }+    --  >>> :{+    --    :t [singletonStatement|+    --         select id :: int4 from "user"+    --         where merchant = $1.$merchantId :: int4+    --           and key = $1.$signatureKey :: text+    --           and status = $2 :: text+    --         |]+    --  :}+    --  ... :: Statement (Merchant, Text) Int32+    --+    --  This requires @OverloadedRecordDot@ at the use site, since the emitted+    --  code selects the fields with it. Repeating a pair reuses its parameter,+    --  and a bare @$1@ is a different parameter from @$1.$field@.++    -- ** Row-parsing statements+    singletonStatement,+    maybeStatement,+    vectorStatement,+    foldStatement,++    -- ** Row-ignoring statements+    resultlessStatement,+    rowsAffectedStatement,++    -- * SQL Strings++    -- |+    -- Text-producing quasiquoters performing no compile-time checking.+    uncheckedSql,+    uncheckedSqlFile,+  )+where++import qualified Data.Text as Text+import qualified Hasql.TH.Construction.Exp as Exp+import qualified Hasql.TH.Extraction.Exp as ExpExtraction+import Hasql.TH.Prelude hiding (exp)+import Language.Haskell.TH.Quote+import Language.Haskell.TH.Syntax+import qualified PostgresqlSyntax as Ast++-- * Helpers++exp :: (String -> Q Exp) -> QuasiQuoter+exp =+  let unsupported _ = fail "Unsupported"+   in \exp -> QuasiQuoter exp unsupported unsupported unsupported++expParser :: (Text -> Either Text Exp) -> QuasiQuoter+expParser parser =+  exp $ \inputString -> either (fail . Text.unpack) return $ parser $ fromString inputString++expPreparableStmtAstParser :: (Ast.PreparableStmt -> Ast.InputParams -> Either Text Exp) -> QuasiQuoter+expPreparableStmtAstParser parser =+  expParser $ \input -> do+    ast <- Ast.parse settings input+    -- 'lower' numbers the placeholders as they fall in the tree that will+    -- actually be rendered - the one with the Haskell targets erased - but+    -- hands back the tree that still carries them, because the row decoder is+    -- built by walking those targets. Erasure happens in+    -- "Hasql.TH.Extraction.Exp" on the way to the SQL text.+    let (loweredAst, inputParams) = Ast.lower ast+    parser loweredAst inputParams+  where+    settings =+      mconcat+        [ Ast.nullabilityMarkers True,+          Ast.haskellTargets True,+          Ast.haskellParamFields True+        ]++-- * Statement++-- |+-- @+-- :: `Statement` params row+-- @+--+-- Statement producing exactly one result row.+--+-- Will cause the running session to fail with the+-- `Hasql.Session.UnexpectedAmountOfRows` error if it's any other.+--+-- === __Examples__+--+-- >>> :t [singletonStatement|select 1 :: int2|]+-- ... :: Statement () Int16+--+-- >>> :{+--   :t [singletonStatement|+--        insert into "user" (email, name)+--        values ($1 :: text, $2 :: text)+--        returning id :: int4+--        |]+-- :}+-- ...+-- ... :: Statement (Text, Text) Int32+--+-- Incorrect SQL:+--+-- >>> :t [singletonStatement|elect 1|]+-- ...+--   |+-- 1 | elect 1+--   | ^+-- ...+singletonStatement :: QuasiQuoter+singletonStatement = expPreparableStmtAstParser (ExpExtraction.undecodedStatement Exp.singleRowResultDecoder)++-- |+-- @+-- :: `Statement` params (Maybe row)+-- @+--+-- Statement producing one row or none.+--+-- === __Examples__+--+-- >>> :t [maybeStatement|select 1 :: int2|]+-- ... :: Statement () (Maybe Int16)+maybeStatement :: QuasiQuoter+maybeStatement = expPreparableStmtAstParser (ExpExtraction.undecodedStatement Exp.rowMaybeResultDecoder)++-- |+-- @+-- :: `Statement` params (`Vector` row)+-- @+--+-- Statement producing a vector of rows.+--+-- === __Examples__+--+-- >>> :t [vectorStatement|select 1 :: int2|]+-- ... :: Statement () (Vector Int16)+vectorStatement :: QuasiQuoter+vectorStatement = expPreparableStmtAstParser (ExpExtraction.undecodedStatement Exp.rowVectorResultDecoder)++-- |+-- @+-- :: `Fold` row folding -> `Statement` params folding+-- @+--+-- Function from `Fold` over rows to a statement producing the result of folding.+-- Use this when you need to aggregate rows customly.+--+-- === __Examples__+--+-- >>> :t [foldStatement|select 1 :: int2|]+-- ... :: Fold Int16 b -> Statement () b+foldStatement :: QuasiQuoter+foldStatement = expPreparableStmtAstParser ExpExtraction.foldStatement++-- |+-- @+-- :: `Statement` params ()+-- @+--+-- Statement producing no results.+--+-- === __Examples__+--+-- >>> :t [resultlessStatement|insert into "user" (name, email) values ($1 :: text, $2 :: text)|]+-- ...+-- ... :: Statement (Text, Text) ()+resultlessStatement :: QuasiQuoter+resultlessStatement = expPreparableStmtAstParser (ExpExtraction.undecodedStatement (const Exp.noResultResultDecoder))++-- |+-- @+-- :: `Statement` params Int64+-- @+--+-- Statement counting the rows it affects.+--+-- === __Examples__+--+-- >>> :t [rowsAffectedStatement|delete from "user" where password is null|]+-- ...+-- ... :: Statement () Int64+rowsAffectedStatement :: QuasiQuoter+rowsAffectedStatement = expPreparableStmtAstParser (ExpExtraction.undecodedStatement (const Exp.rowsAffectedResultDecoder))++-- * SQL Strings++-- |+-- Quoter of a multiline Unicode SQL string,+-- which gets converted into a format ready to be used for declaration of statements.+uncheckedSql :: QuasiQuoter+uncheckedSql = exp $ return . Exp.text . fromString++-- |+-- Read an SQL-file, containing multiple statements,+-- and produce an expression of type 'Text'.+--+-- Allows to store plain SQL in external files and read it at compile time.+--+-- E.g.,+--+-- >migration1 :: Hasql.Session.Session ()+-- >migration1 = Hasql.Session.script [uncheckedSqlFile|migrations/1.sql|]+uncheckedSqlFile :: QuasiQuoter+uncheckedSqlFile = quoteFile uncheckedSql++-- * Tests++-- $+-- >>> :t [maybeStatement| select (password = $2 :: text) :: bool, id :: int4 from "user" where "email" = $1 :: text |]+-- ...+-- ... Statement (Text, Text) (Maybe (Bool, Int32))+--+-- >>> :t [maybeStatement| select id :: int4 from application where pub_key = $1 :: uuid and sec_key_pt1 = $2 :: int8 and sec_key_pt2 = $3 :: int8 |]+-- ...+-- ... Statement (UUID, Int64, Int64) (Maybe Int32)+--+-- >>> :t [singletonStatement| select 1 :: int4 from a left join b on b.id = a.id |]+-- ...+-- ... Statement () Int32
+ src/library/Hasql/TH/Construction/Exp.hs view
@@ -0,0 +1,265 @@+-- |+-- Expression construction.+module Hasql.TH.Construction.Exp where++import Data.List (sortOn)+import qualified Data.Map.Strict as Map+import qualified Data.Text as Text+import qualified Data.Vector.Generic as Vector+import qualified Hasql.Decoders as Decoders+import qualified Hasql.Encoders as Encoders+import qualified Hasql.Statement as Statement+import Hasql.TH.Prelude hiding (sequence_)+import qualified Hasql.TH.Prelude as Prelude+import Language.Haskell.TH.Syntax+import qualified TemplateHaskell.Compat.V0208 as Compat++-- * Helpers++appList :: Exp -> [Exp] -> Exp+appList = foldl' AppE++text :: Text -> Exp+text x = AppE (VarE 'Text.pack) (LitE (StringL (Text.unpack x)))++integral :: (Integral a) => a -> Exp+integral x = LitE (IntegerL (fromIntegral x))++list :: (a -> Exp) -> [a] -> Exp+list renderer x = ListE (map renderer x)++string :: String -> Exp+string x = LitE (StringL x)++char :: Char -> Exp+char x = LitE (CharL x)++sequence_ :: [Exp] -> Exp+sequence_ = foldl' andThen pureUnit++pureUnit :: Exp+pureUnit = AppE (VarE 'Prelude.pure) (TupE [])++andThen :: Exp -> Exp -> Exp+andThen exp1 exp2 = AppE (AppE (VarE '(*>)) exp1) exp2++tuple :: Int -> Exp+tuple = ConE . tupleDataName++splitTupleAt :: Int -> Int -> Exp+splitTupleAt arity position =+  let nameByIndex index = Name (OccName ('_' : show index)) NameS+      names = enumFromTo 0 (pred arity) & map nameByIndex+      pats = names & map VarP+      pat = TupP pats+      exps = names & map VarE+      body = splitAt position exps & \(a, b) -> Compat.tupE [Compat.tupE a, Compat.tupE b]+   in LamE [pat] body++-- |+-- Given a list of divisible functor expressions,+-- constructs an expression, which composes them together into+-- a single divisible functor, parameterized by a tuple of according arity.+contrazip :: [Exp] -> Exp+contrazip = \case+  hd : [] -> hd+  hd : tl -> appList (VarE 'divide) [splitTupleAt (succ (length tl)) 1, hd, contrazip tl]+  [] ->+    SigE+      (VarE 'conquer)+      ( let fName = mkName "f"+         in ForallT+              [Compat.specifiedPlainTV fName]+              [AppT (ConT ''Divisible) (VarT fName)]+              (AppT (VarT fName) (TupleT 0))+      )++-- |+-- Given a list of applicative functor expressions,+-- constructs an expression, which composes them together into+-- a single applicative functor, parameterized by a tuple of according arity.+--+-- >>> $(return (cozip [])) :: Maybe ()+-- Just ()+--+-- >>> $(return (cozip (fmap (AppE (ConE 'Just) . LitE . IntegerL) [1,2,3]))) :: Maybe (Int, Int, Int)+-- Just (1,2,3)+cozip :: [Exp] -> Exp+cozip = \case+  hd : [] -> hd+  hd : tl ->+    let len = length tl + 1+     in foldl'+          (\a b -> AppE (AppE (VarE '(<*>)) a) b)+          (AppE (AppE (VarE 'fmap) (tuple len)) hd)+          tl+  [] -> AppE (VarE 'pure) (TupE [])++-- * Kronor extensions++-- |+-- Build the lambda that maps the tuple of Haskell-level parameters the user+-- writes onto the dense tuple of placeholders the lowered SQL actually has.+--+-- The input is the mapping produced by+-- 'PostgresqlSyntax.Lowering.renameParams': it keys each placeholder by its+-- original @$n@ index and, for an interpolated one, the record field it+-- selects, and maps that to the dense slot.+--+-- The lambda\'s arity is the number of distinct /original/ indices, and its+-- body is the tuple of slot expressions in dense-slot order. So a statement+-- written with @$1.merchantId@, @$1.signatureKey@ and @$2@ gives+--+-- @\\(_1, _2) -> (_1.merchantId, _1.signatureKey, _2)@+--+-- A single original parameter binds a plain variable rather than a+-- one-element tuple pattern. 'Nothing' comes back when the lambda would be+-- the identity - no parameters at all, or none interpolated and none+-- renumbered - and the caller then emits no @contramap@, so a statement using+-- no extension compiles to exactly what upstream emits.+mkParamsMapping :: Map (Int, Maybe Text) Int -> Maybe Exp+mkParamsMapping params =+  let paramsList = sortOn snd (Map.toList params)+      numOrigParams = length (nubBy ((==) `on` (fst . fst)) paramsList)+      tupPats = VarP . mkName . ("_" ++) . show <$> [1 .. numOrigParams]+      rExps =+        ( \(origParam, mHsIdent) ->+            let var = VarE (mkName ("_" <> show origParam))+             in maybe var (GetFieldE var . Text.unpack) mHsIdent+        )+          . fst+          <$> paramsList+      rExp = if length rExps == 1 then head rExps else TupE (Just <$> rExps)+      isIdentity = all (\((orig, field), slot) -> isNothing field && orig == slot) paramsList+   in if null rExps || isIdentity+        then Nothing+        else+          pure+            ( if length tupPats == 1+                then LamE tupPats rExp+                else LamE [TupP tupPats] rExp+            )++-- |+-- Build the lambda that maps the tuple of @n@ decoded columns onto the tuple+-- of Haskell target expressions.+--+-- The column variables are named @fn1@ ... @fnN@, matching the names+-- "Hasql.TH.Extraction.OutputHsTarget" gives them, and there are three shapes:+-- one column binds a plain variable, one target over several columns binds a+-- tuple pattern and returns that single expression unwrapped rather than as a+-- one-element tuple, and anything else returns the tuple of targets.+mkMapping :: Int -> [Exp] -> Exp+mkMapping i exps =+  let tupPats = VarP . mkName . ("fn" ++) . show <$> [1 .. i]+   in if length tupPats == 1+        then LamE tupPats (head exps)+        else+          if length exps == 1+            then LamE [TupP tupPats] (head exps)+            else LamE [TupP tupPats] (TupE (Just <$> exps))++-- | @contramap mapper mappee@.+lmapExp :: Exp -> Exp -> Exp+lmapExp mapper mappee = AppE (AppE (VarE 'contramap) mapper) mappee++-- | @fmap mapper mappee@.+fmapExp :: Exp -> Exp -> Exp+fmapExp mapper mappee = AppE (AppE (VarE 'fmap) mapper) mappee++-- |+-- Lambda expression, which destructures 'Fold'.+foldLam :: (Exp -> Exp -> Exp -> Exp) -> Exp+foldLam body =+  let stepVarName = mkName "progress"+      initVarName = mkName "start"+      extractVarName = mkName "finish"+   in LamE+        [ Compat.conP+            'Fold+            [ VarP stepVarName,+              VarP initVarName,+              VarP extractVarName+            ]+        ]+        (body (VarE stepVarName) (VarE initVarName) (VarE extractVarName))++-- * Statement++statement :: Exp -> Exp -> Exp -> Exp+statement sql encoder decoder =+  appList (VarE 'Statement.preparable) [sql, encoder, decoder]++noResultResultDecoder :: Exp+noResultResultDecoder = VarE 'Decoders.noResult++rowsAffectedResultDecoder :: Exp+rowsAffectedResultDecoder = VarE 'Decoders.rowsAffected++singleRowResultDecoder :: Exp -> Exp+singleRowResultDecoder = 'Decoders.singleRow & VarE & AppE++rowMaybeResultDecoder :: Exp -> Exp+rowMaybeResultDecoder = AppE (VarE 'Decoders.rowMaybe)++rowVectorResultDecoder :: Exp -> Exp+rowVectorResultDecoder = AppE (VarE 'Decoders.rowVector)++foldStatement :: Exp -> Exp -> Exp -> Exp+foldStatement sql encoder rowDecoder' =+  foldLam (\step init extract -> statement sql encoder (foldResultDecoder step init extract rowDecoder'))++foldResultDecoder :: Exp -> Exp -> Exp -> Exp -> Exp+foldResultDecoder step init extract rowDecoder' =+  appList (VarE 'fmap) [extract, appList (VarE 'Decoders.foldlRows) [step, init, rowDecoder']]++unidimensionalParamEncoder :: Bool -> Exp -> Exp+unidimensionalParamEncoder nullable =+  applyParamToEncoder . applyNullabilityToEncoder nullable++multidimensionalParamEncoder :: Bool -> Int -> Bool -> Exp -> Exp+multidimensionalParamEncoder nullable dimensionality arrayNull =+  applyParamToEncoder+    . applyNullabilityToEncoder arrayNull+    . AppE (VarE 'Encoders.array)+    . applyArrayDimensionalityToEncoder dimensionality+    . applyNullabilityToEncoder nullable++applyParamToEncoder :: Exp -> Exp+applyParamToEncoder = AppE (VarE 'Encoders.param)++applyNullabilityToEncoder :: Bool -> Exp -> Exp+applyNullabilityToEncoder nullable = AppE (VarE (if nullable then 'Encoders.nullable else 'Encoders.nonNullable))++applyArrayDimensionalityToEncoder :: Int -> Exp -> Exp+applyArrayDimensionalityToEncoder levels =+  if levels > 0+    then AppE (AppE (VarE 'Encoders.dimension) (VarE 'Vector.foldl')) . applyArrayDimensionalityToEncoder (pred levels)+    else AppE (VarE 'Encoders.element)++rowDecoder :: [Exp] -> Exp+rowDecoder = cozip++unidimensionalColumnDecoder :: Bool -> Exp -> Exp+unidimensionalColumnDecoder nullable =+  applyColumnToDecoder . applyNullabilityToDecoder nullable++multidimensionalColumnDecoder :: Bool -> Int -> Bool -> Exp -> Exp+multidimensionalColumnDecoder nullable dimensionality arrayNull =+  applyColumnToDecoder+    . applyNullabilityToDecoder arrayNull+    . AppE (VarE 'Decoders.array)+    . applyArrayDimensionalityToDecoder dimensionality+    . applyNullabilityToDecoder nullable++applyColumnToDecoder :: Exp -> Exp+applyColumnToDecoder = AppE (VarE 'Decoders.column)++applyNullabilityToDecoder :: Bool -> Exp -> Exp+applyNullabilityToDecoder nullable = AppE (VarE (if nullable then 'Decoders.nullable else 'Decoders.nonNullable))++applyArrayDimensionalityToDecoder :: Int -> Exp -> Exp+applyArrayDimensionalityToDecoder levels =+  if levels > 0+    then AppE (AppE (VarE 'Decoders.dimension) (VarE 'Vector.replicateM)) . applyArrayDimensionalityToDecoder (pred levels)+    else AppE (VarE 'Decoders.element)
+ src/library/Hasql/TH/Extraction/ChildExprList.hs view
@@ -0,0 +1,621 @@+{-# OPTIONS_GHC -Wno-unused-binds -Wno-unused-imports -Wno-name-shadowing -Wno-incomplete-patterns -Wno-unused-matches -Wno-missing-methods -Wno-unused-record-wildcards -Wno-redundant-constraints -Wno-deprecations -Wno-missing-signatures #-}++module Hasql.TH.Extraction.ChildExprList where++import Hasql.TH.Prelude hiding (bit, fromList, sortBy)+import PostgresqlSyntax++-- * Types++data ChildExpr = AChildExpr AExpr | BChildExpr BExpr | CChildExpr CExpr+  deriving (Show, Eq, Ord)++-- |+-- Dives one level of recursion.+childExpr = \case+  AChildExpr a -> aChildExpr a+  BChildExpr a -> bChildExpr a+  CChildExpr a -> cChildExpr a++aChildExpr = \case+  CExprAExpr a -> cChildExpr a+  TypecastAExpr a b -> aExpr a <> typename b+  CollateAExpr a b -> aExpr a <> anyName b+  AtTimeZoneAExpr a b -> aExpr a <> aExpr b+  PlusAExpr a -> aExpr a+  MinusAExpr a -> aExpr a+  SymbolicBinOpAExpr a b c -> aExpr a <> symbolicExprBinOp b <> aExpr c+  PrefixQualOpAExpr a b -> qualOp a <> aExpr b+  AndAExpr a b -> aExpr a <> aExpr b+  OrAExpr a b -> aExpr a <> aExpr b+  NotAExpr a -> aExpr a+  VerbalExprBinOpAExpr a b c d e -> aExpr a <> verbalExprBinOp c <> aExpr d <> foldMap aExpr e+  ReversableOpAExpr a b c -> aExpr a <> aExprReversableOp c+  IsnullAExpr a -> aExpr a+  NotnullAExpr a -> aExpr a+  OverlapsAExpr a b -> row a <> row b+  SubqueryAExpr a b c d -> aExpr a <> subqueryOp b <> subType c <> either selectWithParens aExpr d+  UniqueAExpr a -> selectWithParens a+  DefaultAExpr -> []++bChildExpr = \case+  CExprBExpr a -> cChildExpr a+  TypecastBExpr a b -> bExpr a <> typename b+  PlusBExpr a -> bExpr a+  MinusBExpr a -> bExpr a+  SymbolicBinOpBExpr a b c -> bExpr a <> symbolicExprBinOp b <> bExpr c+  QualOpBExpr a b -> qualOp a <> bExpr b+  IsOpBExpr a b c -> bExpr a <> bExprIsOp c++cChildExpr = \case+  ColumnrefCExpr a -> columnref a+  AexprConstCExpr a -> aexprConst a+  ParamCExpr a b -> foldMap indirection b+  InParensCExpr a b -> aExpr a <> foldMap indirection b+  CaseCExpr a -> caseExpr a+  FuncCExpr a -> funcExpr a+  SelectWithParensCExpr a b -> selectWithParens a <> foldMap indirection b+  ExistsCExpr a -> selectWithParens a+  ArrayCExpr a -> either selectWithParens arrayExpr a+  ExplicitRowCExpr a -> explicitRow a+  ImplicitRowCExpr a -> implicitRow a+  GroupingCExpr a -> exprList a++preparableStmt = \case+  SelectPreparableStmt a -> selectStmt a+  InsertPreparableStmt a -> insertStmt a+  UpdatePreparableStmt a -> updateStmt a+  DeletePreparableStmt a -> deleteStmt a+  CallPreparableStmt a -> callStmt a++-- * Call++callStmt (CallStmt a) = funcApplication a++-- * Insert++insertStmt (InsertStmt a b c d e) =+  foldMap withClause a+    <> insertTarget b+    <> insertRest c+    <> foldMap onConflict d+    <> foldMap returningClause e++insertTarget (InsertTarget a b) = qualifiedName a <> colId b++insertRest = \case+  SelectInsertRest a b c -> foldMap insertColumnList a <> foldMap overrideKind b <> selectStmt c+  DefaultValuesInsertRest -> []++overrideKind _ = []++insertColumnList (InsertColumnList a) = foldMap insertColumnItem a++insertColumnItem (InsertColumnItem a b) = colId a <> foldMap indirection b++onConflict (OnConflict a b) = foldMap confExpr a <> onConflictDo b++onConflictDo = \case+  UpdateOnConflictDo b c -> setClauseList b <> foldMap aExpr c+  NothingOnConflictDo -> []++confExpr = \case+  WhereConfExpr a b -> indexParams a <> foldMap aExpr b+  ConstraintConfExpr a -> name a++returningClause (ReturningClause a) = targetList a++-- * Update++updateStmt (UpdateStmt a b c d e f) =+  foldMap withClause a+    <> relationExprOptAlias b+    <> setClauseList c+    <> foldMap fromClause d+    <> foldMap whereOrCurrentClause e+    <> foldMap returningClause f++setClauseList (SetClauseList a) = foldMap setClause a++setClause = \case+  TargetSetClause a b -> setTarget a <> aExpr b+  TargetListSetClause a b -> setTargetList a <> aExpr b++setTarget (SetTarget a b) = colId a <> foldMap indirection b++setTargetList (SetTargetList a) = foldMap setTarget a++-- * Delete++deleteStmt (DeleteStmt a b c d e) =+  foldMap withClause a+    <> relationExprOptAlias b+    <> foldMap usingClause c+    <> foldMap whereOrCurrentClause d+    <> foldMap returningClause e++usingClause (UsingClause a) = fromList a++-- * Select++selectStmt = \case+  NoParensSelectStmt a -> selectNoParens a+  WithParensSelectStmt a -> selectWithParens a++selectNoParens (SelectNoParens a b c d e) =+  foldMap withClause a+    <> selectClause b+    <> foldMap sortClause c+    <> foldMap selectLimit d+    <> foldMap forLockingClause e++selectWithParens = \case+  NoParensSelectWithParens a -> selectNoParens a+  WithParensSelectWithParens a -> selectWithParens a++withClause (WithClause _ a) = foldMap commonTableExpr a++commonTableExpr (CommonTableExpr a b c d) = preparableStmt d++selectLimit = \case+  LimitOffsetSelectLimit a b -> limitClause a <> offsetClause b+  OffsetLimitSelectLimit a b -> offsetClause a <> limitClause b+  LimitSelectLimit a -> limitClause a+  OffsetSelectLimit a -> offsetClause a++limitClause = \case+  LimitLimitClause a b -> selectLimitValue a <> foldMap aExpr b+  FetchOnlyLimitClause a b c -> foldMap selectFetchFirstValue b++offsetClause = \case+  ExprOffsetClause a -> aExpr a+  FetchFirstOffsetClause a b -> selectFetchFirstValue a++selectFetchFirstValue = \case+  ExprSelectFetchFirstValue a -> cExpr a+  NumSelectFetchFirstValue _ _ -> []++selectLimitValue = \case+  ExprSelectLimitValue a -> aExpr a+  AllSelectLimitValue -> []++forLockingClause = \case+  ItemsForLockingClause a -> foldMap forLockingItem a+  ReadOnlyForLockingClause -> []++forLockingItem (ForLockingItem a b c) =+  foldMap (foldMap qualifiedName) b++selectClause = \case+  SimpleSelectSelectClause a -> simpleSelect a+  WithParensSelectClause a -> selectWithParens a++simpleSelect = \case+  NormalSimpleSelect a b c d e f g ->+    foldMap targeting a+      <> foldMap intoClause b+      <> foldMap fromClause c+      <> foldMap whereClause d+      <> foldMap groupClause e+      <> foldMap havingClause f+      <> foldMap windowClause g+  ValuesSimpleSelect a -> valuesClause a+  TableSimpleSelect a -> relationExpr a+  BinSimpleSelect _ a _ b -> selectClause a <> selectClause b++targeting = \case+  NormalTargeting a -> hsTargetList a+  AllTargeting a -> foldMap targetList a+  DistinctTargeting a b -> foldMap exprList a <> targetList b++-- Same left-to-right leaf order as "Hasql.TH.Extraction.OutputTypeList".+hsTargetList (HsTargetList a) = foldMap hsTargetEl a++hsTargetEl = \case+  HsRecTargetEl _ a -> foldMap hsFieldTargetEl a+  HsFuncTargetEl _ a -> foldMap hsTargetEl a+  SqlTargetEl a -> targetEl a++hsFieldTargetEl (HsFieldEl _ a) = hsTargetEl a++targetList (TargetList a) = foldMap targetEl a++targetEl = \case+  AliasedExprTargetEl a _ -> aExpr a+  ImplicitlyAliasedExprTargetEl a _ -> aExpr a+  ExprTargetEl a -> aExpr a+  AsteriskTargetEl -> []++intoClause (IntoClause a) = optTempTableName a++fromClause (FromClause a) = fromList a++fromList (FromList a) = foldMap tableRef a++whereClause (WhereClause a) = aExpr a++whereOrCurrentClause = \case+  ExprWhereOrCurrentClause a -> aExpr a+  CursorWhereOrCurrentClause a -> cursorName a++groupClause (GroupClause a) = foldMap groupByItem a++havingClause (HavingClause a) = aExpr a++windowClause (WindowClause a) = foldMap windowDefinition a++valuesClause (ValuesClause a) = foldMap exprList a++optTempTableName _ = []++groupByItem = \case+  ExprGroupByItem a -> aExpr a+  EmptyGroupingSetGroupByItem -> []+  RollupGroupByItem a -> exprList a+  CubeGroupByItem a -> exprList a+  GroupingSetsGroupByItem a -> foldMap groupByItem a++windowDefinition (WindowDefinition _ a) = windowSpecification a++windowSpecification (WindowSpecification _ a b c) = foldMap exprList a <> foldMap sortClause b <> foldMap frameClause c++frameClause (FrameClause _ a _) = frameExtent a++frameExtent = \case+  SingularFrameExtent a -> frameBound a+  BetweenFrameExtent a b -> frameBound a <> frameBound b++frameBound = \case+  UnboundedPrecedingFrameBound -> []+  UnboundedFollowingFrameBound -> []+  CurrentRowFrameBound -> []+  PrecedingFrameBound a -> aExpr a+  FollowingFrameBound a -> aExpr a++sortClause (SortClause a) = foldMap sortBy a++sortBy = \case+  UsingSortBy a b c -> aExpr a <> qualAllOp b <> foldMap nullsOrder c+  AscDescSortBy a b c -> aExpr a <> foldMap ascDesc b <> foldMap nullsOrder c++-- * Table refs++tableRef = \case+  RelationExprTableRef a b c -> relationExpr a <> foldMap aliasClause b <> foldMap tablesampleClause c+  FuncTableRef a b c -> funcTable b <> foldMap funcAliasClause c+  SelectTableRef _ a _ -> selectWithParens a+  JoinTableRef a _ -> joinedTable a++relationExpr = \case+  SimpleRelationExpr a _ -> qualifiedName a+  OnlyRelationExpr a _ -> qualifiedName a++relationExprOptAlias (RelationExprOptAlias a b) = relationExpr a <> foldMap (colId . snd) b++tablesampleClause (TablesampleClause a b c) = funcName a <> exprList b <> foldMap repeatableClause c++repeatableClause = aExpr++funcTable = \case+  FuncExprFuncTable a b -> funcExprWindowless a <> optOrdinality b+  RowsFromFuncTable a b -> rowsfromList a <> optOrdinality b++rowsfromItem (RowsfromItem a b) = funcExprWindowless a <> foldMap colDefList b++rowsfromList (RowsfromList a) = foldMap rowsfromItem a++colDefList = tableFuncElementList++optOrdinality = const []++tableFuncElementList (TableFuncElementList a) = foldMap tableFuncElement a++tableFuncElement (TableFuncElement a b c) = colId a <> typename b <> foldMap collateClause c++collateClause = anyName++aliasClause = const []++funcAliasClause = \case+  AliasFuncAliasClause a -> aliasClause a+  AsFuncAliasClause a -> tableFuncElementList a+  AsColIdFuncAliasClause a b -> colId a <> tableFuncElementList b+  ColIdFuncAliasClause a b -> colId a <> tableFuncElementList b++joinedTable = \case+  InParensJoinedTable a -> joinedTable a+  CrossJoinedTable a b -> tableRef a <> tableRef b+  QualJoinedTable a _ b c -> tableRef a <> tableRef b <> joinQual c+  NaturalJoinedTable a _ b -> tableRef a <> tableRef b++joinQual = \case+  UsingJoinQual _ -> []+  OnJoinQual a -> aExpr a++exprList (ExprList a) = fmap AChildExpr (toList a)++aExpr = pure . AChildExpr++bExpr = pure . BChildExpr++cExpr = pure . CChildExpr++funcExpr = \case+  ApplicationFuncExpr a b c d -> funcApplication a <> foldMap withinGroupClause b <> foldMap filterClause c <> foldMap overClause d+  SubexprFuncExpr a -> funcExprCommonSubexpr a++funcExprWindowless = \case+  ApplicationFuncExprWindowless a -> funcApplication a+  CommonSubexprFuncExprWindowless a -> funcExprCommonSubexpr a++withinGroupClause = sortClause++filterClause a = aExpr a++overClause = \case+  WindowOverClause a -> windowSpecification a+  ColIdOverClause _ -> []++funcExprCommonSubexpr = \case+  CollationForFuncExprCommonSubexpr a -> aExpr a+  CurrentDateFuncExprCommonSubexpr -> []+  CurrentTimeFuncExprCommonSubexpr _ -> []+  CurrentTimestampFuncExprCommonSubexpr _ -> []+  LocalTimeFuncExprCommonSubexpr _ -> []+  LocalTimestampFuncExprCommonSubexpr _ -> []+  CurrentRoleFuncExprCommonSubexpr -> []+  CurrentUserFuncExprCommonSubexpr -> []+  SessionUserFuncExprCommonSubexpr -> []+  UserFuncExprCommonSubexpr -> []+  CurrentCatalogFuncExprCommonSubexpr -> []+  CurrentSchemaFuncExprCommonSubexpr -> []+  CastFuncExprCommonSubexpr a b -> aExpr a <> typename b+  ExtractFuncExprCommonSubexpr a -> foldMap extractList a+  OverlayFuncExprCommonSubexpr a -> overlayList a+  PositionFuncExprCommonSubexpr a -> foldMap positionList a+  SubstringFuncExprCommonSubexpr a -> foldMap substrList a+  TreatFuncExprCommonSubexpr a b -> aExpr a <> typename b+  TrimFuncExprCommonSubexpr a b -> foldMap trimModifier a <> trimList b+  NullIfFuncExprCommonSubexpr a b -> aExpr a <> aExpr b+  CoalesceFuncExprCommonSubexpr a -> exprList a+  GreatestFuncExprCommonSubexpr a -> exprList a+  LeastFuncExprCommonSubexpr a -> exprList a++extractList (ExtractList a b) = extractArg a <> aExpr b++extractArg _ = []++overlayList (OverlayList a b c d) = foldMap aExpr ([a, b, c] <> toList d)++positionList (PositionList a b) = bExpr a <> bExpr b++substrList = \case+  ExprSubstrList a b -> aExpr a <> substrListFromFor b+  ExprListSubstrList a -> exprList a++substrListFromFor = \case+  FromForSubstrListFromFor a b -> aExpr a <> aExpr b+  ForFromSubstrListFromFor a b -> aExpr a <> aExpr b+  FromSubstrListFromFor a -> aExpr a+  ForSubstrListFromFor a -> aExpr a++trimModifier _ = []++trimList = \case+  ExprFromExprListTrimList a b -> aExpr a <> exprList b+  FromExprListTrimList a -> exprList a+  ExprListTrimList a -> exprList a++whenClause (WhenClause a b) = aExpr a <> aExpr b++funcApplication (FuncApplication a b) = funcName a <> foldMap funcApplicationParams b++funcApplicationParams = \case+  NormalFuncApplicationParams _ a b -> foldMap funcArgExpr a <> foldMap sortClause b+  VariadicFuncApplicationParams a b c -> foldMap (foldMap funcArgExpr) a <> funcArgExpr b <> foldMap sortClause c+  StarFuncApplicationParams -> []++funcArgExpr = \case+  ExprFuncArgExpr a -> aExpr a+  ColonEqualsFuncArgExpr _ a -> aExpr a+  EqualsGreaterFuncArgExpr _ a -> aExpr a++caseExpr (CaseExpr a b c) = foldMap aExpr a <> whenClauseList b <> foldMap aExpr c++whenClauseList (WhenClauseList a) = foldMap whenClause a++arrayExpr = \case+  ExprListArrayExpr a -> exprList a+  ArrayExprListArrayExpr a -> arrayExprList a+  EmptyArrayExpr -> []++arrayExprList (ArrayExprList a) = foldMap arrayExpr a++inExpr = \case+  SelectInExpr a -> selectWithParens a+  ExprListInExpr a -> exprList a++-- * Operators++symbolicExprBinOp = \case+  MathSymbolicExprBinOp a -> mathOp a+  QualSymbolicExprBinOp a -> qualOp a++qualOp = \case+  OpQualOp a -> op a+  OperatorQualOp a -> anyOperator a++qualAllOp = \case+  AllQualAllOp a -> allOp a+  AnyQualAllOp a -> anyOperator a++verbalExprBinOp = const []++aExprReversableOp = \case+  NullAExprReversableOp -> []+  TrueAExprReversableOp -> []+  FalseAExprReversableOp -> []+  UnknownAExprReversableOp -> []+  DistinctFromAExprReversableOp a -> aExpr a+  OfAExprReversableOp a -> typeList a+  BetweenAExprReversableOp a b c -> bExpr b <> aExpr c+  BetweenSymmetricAExprReversableOp a b -> bExpr a <> aExpr b+  InAExprReversableOp a -> inExpr a+  DocumentAExprReversableOp -> []++subqueryOp = \case+  AllSubqueryOp a -> allOp a+  AnySubqueryOp a -> anyOperator a+  LikeSubqueryOp _ -> []+  IlikeSubqueryOp _ -> []++bExprIsOp = \case+  DistinctFromBExprIsOp a -> bExpr a+  OfBExprIsOp a -> typeList a+  DocumentBExprIsOp -> []++allOp = \case+  OpAllOp a -> op a+  MathAllOp a -> mathOp a++anyOperator = \case+  AllOpAnyOperator a -> allOp a+  QualifiedAnyOperator a b -> colId a <> anyOperator b++op = const []++mathOp = const []++-- * Rows++row = \case+  ExplicitRowRow a -> explicitRow a+  ImplicitRowRow a -> implicitRow a++explicitRow = \case+  EmptyExplicitRow -> []+  ExprListExplicitRow a -> exprList a++implicitRow (ImplicitRow a b) = exprList a <> aExpr b++-- * Constants++aexprConst = \case+  IAexprConst _ -> []+  FAexprConst _ -> []+  SAexprConst _ -> []+  BAexprConst _ -> []+  XAexprConst _ -> []+  FuncAexprConst a b _ -> funcName a <> foldMap funcConstArgs b+  ConstTypenameAexprConst a _ -> constTypename a+  StringIntervalAexprConst _ a -> foldMap interval a+  IntIntervalAexprConst _ _ -> []+  BoolAexprConst _ -> []+  NullAexprConst -> []++funcConstArgs (FuncConstArgs a b) = foldMap funcArgExpr a <> foldMap sortClause b++constTypename = \case+  NumericConstTypename a -> numeric a+  ConstBitConstTypename a -> constBit a+  ConstCharacterConstTypename a -> constCharacter a+  ConstDatetimeConstTypename a -> constDatetime a++numeric = \case+  IntNumeric -> []+  IntegerNumeric -> []+  SmallintNumeric -> []+  BigintNumeric -> []+  RealNumeric -> []+  FloatNumeric _ -> []+  DoublePrecisionNumeric -> []+  DecimalNumeric a -> foldMap exprList a+  DecNumeric a -> foldMap exprList a+  NumericNumeric a -> foldMap exprList a+  BooleanNumeric -> []++bit (Bit _ a) = foldMap exprList a++constBit = bit++constCharacter (ConstCharacter _ _) = []++constDatetime _ = []++interval _ = []++-- * Names++ident _ = []++colId = ident++name = colId++cursorName = name++anyName (AnyName a b) = colId a <> foldMap attrs b++columnref (Columnref a b) = colId a <> foldMap indirection b++funcName = \case+  TypeFuncName a -> typeFunctionName a+  IndirectedFuncName a b -> colId a <> indirection b++qualifiedName = \case+  SimpleQualifiedName _ -> []+  IndirectedQualifiedName _ a -> indirection a++indirection (Indirection a) = foldMap indirectionEl a++indirectionEl = \case+  AttrNameIndirectionEl _ -> []+  AllIndirectionEl -> []+  ExprIndirectionEl a -> aExpr a+  SliceIndirectionEl a b -> foldMap aExpr a <> foldMap aExpr b++-- * Types++typeList (TypeList a) = foldMap typename a++typename (Typename a b c d) =+  simpleTypename b++simpleTypename = \case+  GenericTypeSimpleTypename a -> genericType a+  NumericSimpleTypename a -> numeric a+  BitSimpleTypename a -> bit a+  CharacterSimpleTypename a -> character a+  ConstDatetimeSimpleTypename a -> constDatetime a+  ConstIntervalSimpleTypename a -> either (foldMap interval) (const []) a++arrayBounds _ = []++genericType (GenericType a b c) = typeFunctionName a <> foldMap attrs b <> foldMap typeModifiers c++typeFunctionName = ident++attrs (Attrs a) = foldMap attrName a++attrName _ = []++typeModifiers = exprList++character _ = []++subType _ = []++-- * Indexes++indexParams (IndexParams a) = foldMap indexElem a++indexElem (IndexElem a b c d e) = indexElemDef a <> foldMap anyName b <> foldMap anyName c++indexElemDef = \case+  IdIndexElemDef a -> colId a+  FuncIndexElemDef a -> funcExprWindowless a+  ExprIndexElemDef a -> aExpr a++ascDesc = const []++nullsOrder = const []
+ src/library/Hasql/TH/Extraction/Exp.hs view
@@ -0,0 +1,124 @@+module Hasql.TH.Extraction.Exp where++import qualified Hasql.Decoders as Decoders+import qualified Hasql.Encoders as Encoders+import qualified Hasql.TH.Construction.Exp as Exp+import qualified Hasql.TH.Extraction.InputTypeList as InputTypeList+import qualified Hasql.TH.Extraction.OutputHsTarget as OutputHsTarget+import qualified Hasql.TH.Extraction.OutputTypeList as OutputTypeList+import qualified Hasql.TH.Extraction.PrimitiveType as PrimitiveType+import Hasql.TH.Prelude+import Language.Haskell.TH+import qualified PostgresqlSyntax as Ast++-- |+-- The SQL text the statement is compiled to: the AST with the Haskell targets+-- erased, rendered at 'mempty' settings so that the nullability markers are+-- dropped too. The placeholders have already been renumbered densely by+-- "PostgresqlSyntax.Lowering" before the AST reaches here.+sql :: Ast.PreparableStmt -> Exp+sql = Exp.text . Ast.toText mempty . Ast.eraseHaskellTargets++undecodedStatement :: (Exp -> Exp) -> Ast.PreparableStmt -> Ast.InputParams -> Either Text Exp+undecodedStatement decoderProj ast renamedParams =+  do+    encoder <- paramsEncoder ast renamedParams+    rowDecoder' <- rowDecoder ast+    return (Exp.statement (sql ast) encoder (decoderProj rowDecoder'))++foldStatement :: Ast.PreparableStmt -> Ast.InputParams -> Either Text Exp+foldStatement ast renamedParams =+  do+    encoder <- paramsEncoder ast renamedParams+    rowDecoder' <- rowDecoder ast+    return (Exp.foldStatement (sql ast) encoder rowDecoder')++paramsEncoder :: Ast.PreparableStmt -> Ast.InputParams -> Either Text Exp+paramsEncoder a renamedParams = do+  b <- InputTypeList.preparableStmt a+  c <- traverse paramEncoder b+  return (maybe (Exp.contrazip c) (flip Exp.lmapExp (Exp.contrazip c)) (Exp.mkParamsMapping renamedParams))++rowDecoder :: Ast.PreparableStmt -> Either Text Exp+rowDecoder a = do+  b <- OutputTypeList.preparableStmt a+  c <- traverse columnDecoder b+  exps <- OutputHsTarget.preparableStmt a+  -- When every top-level target is a bare SQL column the mapping lambda would+  -- be the identity, so it is skipped and the emitted code stays identical to+  -- what upstream emits for a statement using no extension.+  if null exps || all (\case VarE _ -> True; _ -> False) exps+    then return (Exp.cozip c)+    else return (Exp.fmapExp (Exp.mkMapping (length b) exps) (Exp.cozip c))++paramEncoder :: Ast.Typename -> Either Text Exp+paramEncoder =+  byTypename+    (\a b -> valueEncoder a & fmap (Exp.unidimensionalParamEncoder b))+    (\a b c d -> valueEncoder a & fmap (Exp.multidimensionalParamEncoder b c d))++columnDecoder :: Ast.Typename -> Either Text Exp+columnDecoder =+  byTypename+    (\a b -> valueDecoder a & fmap (Exp.unidimensionalColumnDecoder b))+    (\a b c d -> valueDecoder a & fmap (Exp.multidimensionalColumnDecoder b c d))++byTypename :: (PrimitiveType.PrimitiveType -> Bool -> Either Text Exp) -> (PrimitiveType.PrimitiveType -> Bool -> Int -> Bool -> Either Text Exp) -> Ast.Typename -> Either Text Exp+byTypename unidimensional multidimensional (Ast.Typename a b c d) =+  if a+    then Left "SETOF is not supported"+    else do+      e <- PrimitiveType.simpleTypename b+      case d of+        Nothing -> unidimensional e c+        Just (f, g) -> case f of+          Ast.BoundsTypenameArrayDimensions (Ast.ArrayBounds h) -> multidimensional e c (length h) g+          Ast.ExplicitTypenameArrayDimensions _ -> multidimensional e c 1 g++valueEncoder :: PrimitiveType.PrimitiveType -> Either Text Exp+valueEncoder =+  Right . VarE . \case+    PrimitiveType.BoolPrimitiveType -> 'Encoders.bool+    PrimitiveType.Int2PrimitiveType -> 'Encoders.int2+    PrimitiveType.Int4PrimitiveType -> 'Encoders.int4+    PrimitiveType.Int8PrimitiveType -> 'Encoders.int8+    PrimitiveType.Float4PrimitiveType -> 'Encoders.float4+    PrimitiveType.Float8PrimitiveType -> 'Encoders.float8+    PrimitiveType.NumericPrimitiveType -> 'Encoders.numeric+    PrimitiveType.CharPrimitiveType -> 'Encoders.char+    PrimitiveType.TextPrimitiveType -> 'Encoders.text+    PrimitiveType.ByteaPrimitiveType -> 'Encoders.bytea+    PrimitiveType.DatePrimitiveType -> 'Encoders.date+    PrimitiveType.TimestampPrimitiveType -> 'Encoders.timestamp+    PrimitiveType.TimestamptzPrimitiveType -> 'Encoders.timestamptz+    PrimitiveType.TimePrimitiveType -> 'Encoders.time+    PrimitiveType.TimetzPrimitiveType -> 'Encoders.timetz+    PrimitiveType.IntervalPrimitiveType -> 'Encoders.interval+    PrimitiveType.UuidPrimitiveType -> 'Encoders.uuid+    PrimitiveType.InetPrimitiveType -> 'Encoders.inet+    PrimitiveType.JsonPrimitiveType -> 'Encoders.json+    PrimitiveType.JsonbPrimitiveType -> 'Encoders.jsonb++valueDecoder :: PrimitiveType.PrimitiveType -> Either Text Exp+valueDecoder =+  Right . VarE . \case+    PrimitiveType.BoolPrimitiveType -> 'Decoders.bool+    PrimitiveType.Int2PrimitiveType -> 'Decoders.int2+    PrimitiveType.Int4PrimitiveType -> 'Decoders.int4+    PrimitiveType.Int8PrimitiveType -> 'Decoders.int8+    PrimitiveType.Float4PrimitiveType -> 'Decoders.float4+    PrimitiveType.Float8PrimitiveType -> 'Decoders.float8+    PrimitiveType.NumericPrimitiveType -> 'Decoders.numeric+    PrimitiveType.CharPrimitiveType -> 'Decoders.char+    PrimitiveType.TextPrimitiveType -> 'Decoders.text+    PrimitiveType.ByteaPrimitiveType -> 'Decoders.bytea+    PrimitiveType.DatePrimitiveType -> 'Decoders.date+    PrimitiveType.TimestampPrimitiveType -> 'Decoders.timestamp+    PrimitiveType.TimestamptzPrimitiveType -> 'Decoders.timestamptz+    PrimitiveType.TimePrimitiveType -> 'Decoders.time+    PrimitiveType.TimetzPrimitiveType -> 'Decoders.timetz+    PrimitiveType.IntervalPrimitiveType -> 'Decoders.interval+    PrimitiveType.UuidPrimitiveType -> 'Decoders.uuid+    PrimitiveType.InetPrimitiveType -> 'Decoders.inet+    PrimitiveType.JsonPrimitiveType -> 'Decoders.json+    PrimitiveType.JsonbPrimitiveType -> 'Decoders.jsonb
+ src/library/Hasql/TH/Extraction/InputTypeList.hs view
@@ -0,0 +1,53 @@+-- |+-- AST traversal extracting input types.+module Hasql.TH.Extraction.InputTypeList where++import qualified Data.IntMap.Strict as IntMap+import qualified Hasql.TH.Extraction.PlaceholderTypeMap as PlaceholderTypeMap+import Hasql.TH.Prelude+import PostgresqlSyntax++-- |+-- >>> import qualified Data.Text as Text+-- >>> import qualified PostgresqlSyntax as P+-- >>> test = either (fail . Text.unpack) (return . preparableStmt) . P.parse (P.nullabilityMarkers True)+--+-- >>> test "select $1 :: INT"+-- Right [Typename False (NumericSimpleTypename IntNumeric) False Nothing]+--+-- >>> test "select $1 :: INT, a + $2 :: INTEGER"+-- Right [Typename False (NumericSimpleTypename IntNumeric) False Nothing,Typename False (NumericSimpleTypename IntegerNumeric) False Nothing]+--+-- >>> test "select $1 :: INT4"+-- Right [Typename False (GenericTypeSimpleTypename (GenericType (UnquotedIdent "int4") Nothing Nothing)) False Nothing]+--+-- >>> test "select $1 :: text[]?"+-- Right [Typename False (GenericTypeSimpleTypename (GenericType (UnquotedIdent "text") Nothing Nothing)) False (Just (BoundsTypenameArrayDimensions (ArrayBounds (Nothing :| [])),True))]+--+-- >>> test "select $1 :: text?[]?"+-- Right [Typename False (GenericTypeSimpleTypename (GenericType (UnquotedIdent "text") Nothing Nothing)) True (Just (BoundsTypenameArrayDimensions (ArrayBounds (Nothing :| [])),True))]+--+-- >>> test "select $1"+-- Left "Placeholder $1 misses an explicit typecast"+--+-- >>> test "select $2 :: int4, $1 :: int4, $2 :: int4"+-- Right [Typename False (GenericTypeSimpleTypename (GenericType (UnquotedIdent "int4") Nothing Nothing)) False Nothing,Typename False (GenericTypeSimpleTypename (GenericType (UnquotedIdent "int4") Nothing Nothing)) False Nothing]+--+-- >>> test "select $1 :: int4, $1 :: text"+-- Left "Placeholder $1 has conflicting type annotations"+--+-- >>> test "select $2 :: int4, $2 :: text"+-- Left "Placeholder $2 has conflicting type annotations"+--+-- >>> test "select $3 :: int4, $1 :: int4"+-- Left "You've missed placeholder $2"+preparableStmt :: PreparableStmt -> Either Text [Typename]+preparableStmt = placeholderTypeMap <=< PlaceholderTypeMap.preparableStmt++placeholderTypeMap :: IntMap Typename -> Either Text [Typename]+placeholderTypeMap a = do+  zipWithM+    (\a b -> if a == b then Right () else Left ("You've missed placeholder $" <> showAsText b))+    (IntMap.keys a)+    [1 ..]+  return (IntMap.elems a)
+ src/library/Hasql/TH/Extraction/OutputHsTarget.hs view
@@ -0,0 +1,120 @@+{-# OPTIONS_GHC -Wno-unused-binds -Wno-unused-imports -Wno-name-shadowing -Wno-incomplete-patterns -Wno-unused-matches -Wno-missing-methods -Wno-unused-record-wildcards -Wno-redundant-constraints -Wno-deprecations -Wno-missing-signatures #-}++-- |+-- AST traversal extracting targetted haskell output types.+-- See 'preparableStmt'+module Hasql.TH.Extraction.OutputHsTarget where++import Control.Monad.Trans.State.Strict (StateT, evalStateT, get, put)+import qualified Data.Text+import Hasql.TH.Prelude+import Language.Haskell.TH+import PostgresqlSyntax++foldable :: (Foldable f, Monad m) => (a -> m [b]) -> f a -> m [b]+foldable fn = fmap join . traverse fn . toList++-- |+-- Return one expression per top-level target of the select list, in order,+-- with the decoded columns referred to as @fn1@, @fn2@, ... left to right.+--+-- @+-- [singletonStatement|+-- select+--     $mkUser (uid::bigint, uname::text)+--   , $defaultUser {userId = uid::bigint}+--   , uid::bigint+--  from label+--  where hid = $1::bigint+-- |]+-- @+--+-- should finally return a function to fmap over decoder like+--+-- @+-- \(fn1, fn2, fn3, fn4) -> (mkUser fn1 fn2, defaultUser { userId = fn3 }, fn4)+-- @+--+-- Now consider a more complex example with nesting+--+-- @+-- [singletonStatement|+-- select+--     $mkUser (uid::bigint, uname::text)+--   , $defaultUser {userId = $doSomethingToUid (uid::bigint) }+--   , uid::bigint+--  from label+--  where hid = $1::bigint+-- |]+-- @+--+-- should make a function+--+-- @+-- \(fn1, fn2, fn3, fn4) -> (mkUser fn1 fn2, defaultUser { userId = doSomethingToUid fn3 }, fn4)+-- @+preparableStmt = \case+  SelectPreparableStmt a -> selectStmt a+  _ -> pure []++-- * Select++selectStmt = \case+  NoParensSelectStmt a -> selectNoParens a+  WithParensSelectStmt a -> selectWithParens a++selectNoParens (SelectNoParens _ a _ _ _) = selectClause a++selectWithParens = \case+  NoParensSelectWithParens a -> selectNoParens a+  WithParensSelectWithParens a -> selectWithParens a++selectClause = \case+  SimpleSelectSelectClause a -> simpleSelect a+  WithParensSelectClause a -> selectWithParens a++simpleSelect :: SimpleSelect -> Either Text [Exp]+simpleSelect = \case+  NormalSimpleSelect a _ _ _ _ _ _ -> foldable targeting a+  _ -> pure []++targeting :: Targeting -> Either Text [Exp]+targeting = \case+  NormalTargeting (HsTargetList a) -> evalStateT (hsTargetList a) 1+  _ -> pure []++hsTargetList :: (Foldable f) => f HsTargetEl -> StateT Int (Either Text) [Exp]+hsTargetList = traverse hsTargetEl . toList++hsTargetEl :: HsTargetEl -> StateT Int (Either Text) Exp+hsTargetEl = \case+  HsRecTargetEl consName hftl ->+    let errExps = foldable hsFieldTargetEl hftl+        reifiedName = mkName (Data.Text.unpack consName)+        toUpdate =+          if isConsOrVar reifiedName+            then RecConE reifiedName+            else RecUpdE (VarE reifiedName)+     in toUpdate <$> errExps+  HsFuncTargetEl funcName htl ->+    let reifiedName = mkName (Data.Text.unpack funcName)+        toApp =+          if isConsOrVar reifiedName+            then ConE reifiedName+            else VarE reifiedName+     in go toApp <$> hsTargetList htl+  SqlTargetEl _ -> do+    i <- get+    put (i + 1)+    pure (VarE (mkName ("fn" ++ show i)))+  where+    isConsOrVar name = isUpper (head (nameBase name))+    -- No args to apply, so assume what you have is a value expression+    -- or a function with no arguments.+    go fn [] = fn+    go fn [x] = AppE fn x+    go fn xs = AppE (go fn (init xs)) (last xs)++hsFieldTargetEl :: HsFieldTargetEl -> StateT Int (Either Text) [FieldExp]+hsFieldTargetEl (HsFieldEl fn htl) =+  pure . (mkName (Data.Text.unpack fn),) <$> hsTargetEl htl
+ src/library/Hasql/TH/Extraction/OutputTypeList.hs view
@@ -0,0 +1,110 @@+{-# OPTIONS_GHC -Wno-unused-binds -Wno-unused-imports -Wno-name-shadowing -Wno-incomplete-patterns -Wno-unused-matches -Wno-missing-methods -Wno-unused-record-wildcards -Wno-redundant-constraints -Wno-deprecations -Wno-missing-signatures #-}++-- |+-- AST traversal extracting output types.+module Hasql.TH.Extraction.OutputTypeList where++import Hasql.TH.Prelude+import PostgresqlSyntax++foldable :: (Foldable f) => (a -> Either Text [Typename]) -> f a -> Either Text [Typename]+foldable fn = fmap join . traverse fn . toList++preparableStmt = \case+  SelectPreparableStmt a -> selectStmt a+  InsertPreparableStmt a -> insertStmt a+  UpdatePreparableStmt a -> updateStmt a+  DeletePreparableStmt a -> deleteStmt a+  CallPreparableStmt a -> callStmt a++-- * Call++callStmt (CallStmt a) =+  Right []++-- * Insert++insertStmt (InsertStmt a b c d e) = foldable returningClause e++returningClause (ReturningClause a) = targetList a++-- * Update++updateStmt (UpdateStmt _ _ _ _ _ a) = foldable returningClause a++-- * Delete++deleteStmt (DeleteStmt _ _ _ _ a) = foldable returningClause a++-- * Select++selectStmt = \case+  NoParensSelectStmt a -> selectNoParens a+  WithParensSelectStmt a -> selectWithParens a++selectNoParens (SelectNoParens _ a _ _ _) = selectClause a++selectWithParens = \case+  NoParensSelectWithParens a -> selectNoParens a+  WithParensSelectWithParens a -> selectWithParens a++selectClause = \case+  SimpleSelectSelectClause a -> simpleSelect a+  WithParensSelectClause a -> selectWithParens a++simpleSelect = \case+  NormalSimpleSelect a _ _ _ _ _ _ -> foldable targeting a+  ValuesSimpleSelect a -> valuesClause a+  TableSimpleSelect _ -> Left "TABLE cannot be used as a final statement, since it's impossible to specify the output types"+  BinSimpleSelect _ a _ b -> do+    c <- selectClause a+    d <- selectClause b+    if c == d+      then return c+      else Left "Merged queries produce results of incompatible types"++targeting :: Targeting -> Either Text [Typename]+targeting = \case+  NormalTargeting a -> hsTargetList a+  AllTargeting a -> foldable targetList a+  DistinctTargeting _ b -> targetList b++-- |+-- Collect the 'SqlTargetEl' leaves of a Haskell target list, depth-first and+-- left-to-right. That is the order the columns come back in, and it must stay+-- the order "Hasql.TH.Extraction.OutputHsTarget" ticks its @fn@ counter in.+hsTargetList :: HsTargetList -> Either Text [Typename]+hsTargetList (HsTargetList a) = foldable hsTargetEl a++hsTargetEl :: HsTargetEl -> Either Text [Typename]+hsTargetEl = \case+  HsRecTargetEl _ a -> foldable hsFieldTargetEl a+  HsFuncTargetEl _ a -> foldable hsTargetEl a+  SqlTargetEl a -> targetEl a++hsFieldTargetEl :: HsFieldTargetEl -> Either Text [Typename]+hsFieldTargetEl (HsFieldEl _ a) = hsTargetEl a++targetList :: TargetList -> Either Text [Typename]+targetList (TargetList a) = foldable targetEl a++targetEl = \case+  AliasedExprTargetEl a _ -> aExpr a+  ImplicitlyAliasedExprTargetEl a _ -> aExpr a+  ExprTargetEl a -> aExpr a+  AsteriskTargetEl ->+    Left+      "Target of all fields is not allowed, \+      \because it leaves the output types unspecified. \+      \You have to be specific."++valuesClause (ValuesClause a) = foldable (\(ExprList b) -> foldable aExpr b) a++aExpr = \case+  CExprAExpr a -> cExpr a+  TypecastAExpr _ a -> Right [a]+  a -> Left "Result expression is missing a typecast"++cExpr = \case+  InParensCExpr a Nothing -> aExpr a+  a -> Left "Result expression is missing a typecast"
+ src/library/Hasql/TH/Extraction/PlaceholderTypeMap.hs view
@@ -0,0 +1,58 @@+{-# OPTIONS_GHC -Wno-missing-signatures #-}++module Hasql.TH.Extraction.PlaceholderTypeMap where++import qualified Data.IntMap.Strict as IntMap+import Hasql.TH.Extraction.ChildExprList (ChildExpr (..))+import qualified Hasql.TH.Extraction.ChildExprList as ChildExprList+import Hasql.TH.Prelude hiding (union)+import PostgresqlSyntax++preparableStmt :: PreparableStmt -> Either Text (IntMap Typename)+preparableStmt = childExprList . ChildExprList.preparableStmt++childExprList :: [ChildExpr] -> Either Text (IntMap Typename)+childExprList = foldM union IntMap.empty <=< traverse childExpr++union :: IntMap Typename -> IntMap Typename -> Either Text (IntMap Typename)+union a b = IntMap.mergeWithKey merge (fmap Right) (fmap Right) a b & sequence+  where+    merge index a b =+      if a == b+        then Just (Right a)+        else Just (Left ("Placeholder $" <> (fromString . show) index <> " has conflicting type annotations"))++childExpr :: ChildExpr -> Either Text (IntMap Typename)+childExpr = \case+  AChildExpr a -> aExpr a+  BChildExpr a -> bExpr a+  CChildExpr a -> cExpr a++aExpr = \case+  CExprAExpr a -> cExpr a+  TypecastAExpr a b -> castedAExpr b a+  a -> childExprList (ChildExprList.aChildExpr a)++bExpr = \case+  CExprBExpr a -> cExpr a+  TypecastBExpr a b -> castedBExpr b a+  a -> childExprList (ChildExprList.bChildExpr a)++cExpr = \case+  ParamCExpr a _ -> Left ("Placeholder $" <> (fromString . show) a <> " misses an explicit typecast")+  a -> childExprList (ChildExprList.cChildExpr a)++castedAExpr a = \case+  CExprAExpr b -> castedCExpr a b+  TypecastAExpr b c -> castedAExpr c b+  b -> aExpr b++castedBExpr a = \case+  CExprBExpr b -> castedCExpr a b+  TypecastBExpr b c -> castedBExpr c b+  b -> bExpr b++castedCExpr a = \case+  ParamCExpr b _ -> Right (IntMap.singleton b a)+  InParensCExpr b _ -> castedAExpr a b+  b -> cExpr b
+ src/library/Hasql/TH/Extraction/PrimitiveType.hs view
@@ -0,0 +1,102 @@+{-# OPTIONS_GHC -Wno-unused-binds -Wno-unused-imports -Wno-name-shadowing -Wno-incomplete-patterns -Wno-unused-matches -Wno-missing-methods -Wno-unused-record-wildcards -Wno-redundant-constraints -Wno-deprecations -Wno-missing-signatures #-}++module Hasql.TH.Extraction.PrimitiveType where++import Hasql.TH.Prelude hiding (bit, fromList, sortBy)+import PostgresqlSyntax++data PrimitiveType+  = BoolPrimitiveType+  | Int2PrimitiveType+  | Int4PrimitiveType+  | Int8PrimitiveType+  | Float4PrimitiveType+  | Float8PrimitiveType+  | NumericPrimitiveType+  | CharPrimitiveType+  | TextPrimitiveType+  | ByteaPrimitiveType+  | DatePrimitiveType+  | TimestampPrimitiveType+  | TimestamptzPrimitiveType+  | TimePrimitiveType+  | TimetzPrimitiveType+  | IntervalPrimitiveType+  | UuidPrimitiveType+  | InetPrimitiveType+  | JsonPrimitiveType+  | JsonbPrimitiveType++simpleTypename = \case+  GenericTypeSimpleTypename a -> genericType a+  NumericSimpleTypename a -> numeric a+  BitSimpleTypename a -> bit a+  CharacterSimpleTypename a -> character a+  ConstDatetimeSimpleTypename a -> constDatetime a+  ConstIntervalSimpleTypename a -> Right IntervalPrimitiveType++genericType (GenericType a b c) = case b of+  Just _ -> Left "Type attributes are not supported"+  Nothing -> case c of+    Just _ -> Left "Type modifiers are not supported"+    Nothing -> ident a++numeric = \case+  IntNumeric -> Right Int4PrimitiveType+  IntegerNumeric -> Right Int4PrimitiveType+  SmallintNumeric -> Right Int2PrimitiveType+  BigintNumeric -> Right Int8PrimitiveType+  RealNumeric -> Right Float4PrimitiveType+  FloatNumeric a -> case a of+    Just _ -> Left "Modifier on FLOAT is not supported"+    Nothing -> Right Float4PrimitiveType+  DoublePrecisionNumeric -> Right Float8PrimitiveType+  DecimalNumeric a -> case a of+    Just _ -> Left "Modifiers on DECIMAL are not supported"+    Nothing -> Right NumericPrimitiveType+  DecNumeric a -> case a of+    Just _ -> Left "Modifiers on DEC are not supported"+    Nothing -> Right NumericPrimitiveType+  NumericNumeric a -> case a of+    Just _ -> Left "Modifiers on NUMERIC are not supported"+    Nothing -> Right NumericPrimitiveType+  BooleanNumeric -> Right BoolPrimitiveType++bit _ = Left "Bit codec is not supported"++character _ = Right CharPrimitiveType++constDatetime = \case+  TimestampConstDatetime _ a -> if tz a then Right TimestamptzPrimitiveType else Right TimestampPrimitiveType+  TimeConstDatetime _ a -> if tz a then Right TimetzPrimitiveType else Right TimePrimitiveType+  where+    tz = \case+      Just (Timezone a) -> a+      Nothing -> False++ident = \case+  QuotedIdent a -> name a+  UnquotedIdent a -> name a++name = \case+  "bool" -> Right BoolPrimitiveType+  "int2" -> Right Int2PrimitiveType+  "int4" -> Right Int4PrimitiveType+  "int8" -> Right Int8PrimitiveType+  "float4" -> Right Float4PrimitiveType+  "float8" -> Right Float8PrimitiveType+  "numeric" -> Right NumericPrimitiveType+  "char" -> Right CharPrimitiveType+  "text" -> Right TextPrimitiveType+  "bytea" -> Right ByteaPrimitiveType+  "date" -> Right DatePrimitiveType+  "timestamp" -> Right TimestampPrimitiveType+  "timestamptz" -> Right TimestamptzPrimitiveType+  "time" -> Right TimePrimitiveType+  "timetz" -> Right TimetzPrimitiveType+  "interval" -> Right IntervalPrimitiveType+  "uuid" -> Right UuidPrimitiveType+  "inet" -> Right InetPrimitiveType+  "json" -> Right JsonPrimitiveType+  "jsonb" -> Right JsonbPrimitiveType+  name -> Left ("No codec exists for type: " <> name)
+ src/library/Hasql/TH/Prelude.hs view
@@ -0,0 +1,95 @@+module Hasql.TH.Prelude+  ( module Exports,+    showAsText,+    suffixRec,+  )+where++import Control.Applicative as Exports+import Control.Arrow as Exports hiding (first, second)+import Control.Category as Exports+import Control.Concurrent as Exports+import Control.Exception as Exports+import Control.Foldl as Exports (Fold (..))+import Control.Monad as Exports hiding (fail, forM, forM_, mapM, mapM_, msum, sequence, sequence_)+import Control.Monad.Fail as Exports+import Control.Monad.Fix as Exports hiding (fix)+import Control.Monad.IO.Class as Exports+import Control.Monad.ST as Exports+import Data.Bifunctor as Exports+import Data.Bits as Exports+import Data.Bool as Exports+import Data.Char as Exports+import Data.Coerce as Exports+import Data.Complex as Exports+import Data.Data as Exports+import Data.Dynamic as Exports+import Data.Either as Exports+import Data.Fixed as Exports+import Data.Foldable as Exports+import Data.Function as Exports hiding (id, (.))+import Data.Functor as Exports hiding (unzip)+import Data.Functor.Contravariant as Exports+import Data.Functor.Contravariant.Divisible as Exports+import Data.Functor.Identity as Exports+import Data.IORef as Exports+import Data.Int as Exports+import Data.IntMap.Strict as Exports (IntMap)+import Data.IntSet as Exports (IntSet)+import Data.Ix as Exports+import Data.List as Exports hiding (all, and, any, concat, concatMap, elem, find, foldl, foldl', foldl1, foldr, foldr1, isSubsequenceOf, mapAccumL, mapAccumR, maximum, maximumBy, minimum, minimumBy, notElem, or, product, sortOn, sum, uncons)+import Data.List.NonEmpty as Exports (NonEmpty (..))+import Data.Map.Strict as Exports (Map)+import Data.Maybe as Exports+import Data.Monoid as Exports hiding (First (..), Last (..), (<>))+import Data.Ord as Exports+import Data.Proxy as Exports+import Data.Ratio as Exports+import Data.STRef as Exports+import Data.Semigroup as Exports+import Data.Sequence as Exports (Seq)+import Data.Set as Exports (Set)+import Data.String as Exports+import Data.Text as Exports (Text)+import Data.Traversable as Exports+import Data.Tuple as Exports+import Data.UUID as Exports (UUID)+import Data.Unique as Exports+import Data.Vector as Exports (Vector)+import Data.Version as Exports+import Data.Void as Exports+import Data.Word as Exports+import Debug.Trace as Exports+import Foreign.ForeignPtr as Exports+import Foreign.Ptr as Exports+import Foreign.StablePtr as Exports+import Foreign.Storable as Exports hiding (alignment, sizeOf)+import GHC.Conc as Exports hiding (orElse, threadWaitRead, threadWaitReadSTM, threadWaitWrite, threadWaitWriteSTM, withMVar)+import GHC.Exts as Exports (IsList (Item, fromList), groupWith, inline, lazy, sortWith)+import GHC.Generics as Exports (Generic, Generic1)+import GHC.IO.Exception as Exports+import Hasql.Statement as Exports (Statement)+import Numeric as Exports+import Prelude as Exports hiding (all, and, any, concat, concatMap, elem, fail, foldl, foldl1, foldr, foldr1, id, mapM, mapM_, maximum, minimum, notElem, or, product, sequence, sequence_, sum, (.))+import System.Environment as Exports+import System.Exit as Exports+import System.IO as Exports+import System.IO.Error as Exports+import System.IO.Unsafe as Exports+import System.Mem as Exports+import System.Mem.StableName as Exports+import System.Timeout as Exports+import Text.Printf as Exports (hPrintf, printf)+import Text.Read as Exports (Read (..), readEither, readMaybe)+import Unsafe.Coerce as Exports++showAsText :: (Show a) => a -> Text+showAsText = show >>> fromString++-- |+-- Compose a monad, which attempts to extend a value, based on the following input.+-- It does that recursively until the suffix alternative fails.+suffixRec :: (Monad m, Alternative m) => m a -> (a -> m a) -> m a+suffixRec base suffix = do+  _base <- base+  suffixRec (suffix _base) suffix <|> pure _base