hasql-dynamic-statements (empty) → 0.1
raw patch · 8 files changed
+320/−0 lines, 8 filesdep +aesondep +basedep +bytestringsetup-changed
Dependencies added: aeson, base, bytestring, containers, data-default, hasql, ptr, vector
Files
- LICENSE +22/−0
- Setup.hs +2/−0
- hasql-dynamic-statements.cabal +43/−0
- library/Hasql/DynamicStatements/Prelude.hs +86/−0
- library/Hasql/DynamicStatements/Session.hs +19/−0
- library/Hasql/DynamicStatements/Snippet.hs +11/−0
- library/Hasql/DynamicStatements/Snippet/Defs.hs +73/−0
- library/Hasql/DynamicStatements/Statement.hs +64/−0
+ LICENSE view
@@ -0,0 +1,22 @@+Copyright (c) 2019, 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.
+ Setup.hs view
@@ -0,0 +1,2 @@+import Distribution.Simple+main = defaultMain
+ hasql-dynamic-statements.cabal view
@@ -0,0 +1,43 @@+name: hasql-dynamic-statements+version: 0.1+synopsis: Toolkit for constructing Hasql statements dynamically+description:+ This library introduces into the Hasql ecosystem a new abstraction named Snippet,+ which makes it trivial to construct SQL, while injecting values.+ It is intended to be used when the SQL of your statement depends on the parameters,+ that you want to pass in.+homepage: https://github.com/nikita-volkov/hasql-dynamic-statements+bug-reports: https://github.com/nikita-volkov/hasql-dynamic-statements/issues+author: Nikita Volkov <nikita.y.volkov@mail.ru>+maintainer: Nikita Volkov <nikita.y.volkov@mail.ru>+copyright: (c) 2019, Nikita Volkov+license: MIT+license-file: LICENSE+build-type: Simple+cabal-version: >=1.10++source-repository head+ type: git+ location: git://github.com/nikita-volkov/hasql-dynamic-statements.git++library+ hs-source-dirs: library+ default-extensions: BangPatterns, DeriveDataTypeable, DeriveGeneric, DeriveFunctor, DeriveTraversable, GeneralizedNewtypeDeriving, FlexibleContexts, FlexibleInstances, LambdaCase, NoImplicitPrelude, OverloadedStrings, RankNTypes, ScopedTypeVariables, StandaloneDeriving, TypeApplications, TypeFamilies+ ghc-options: -funbox-strict-fields+ default-language: Haskell2010+ exposed-modules:+ Hasql.DynamicStatements.Session+ Hasql.DynamicStatements.Snippet+ Hasql.DynamicStatements.Statement+ other-modules:+ Hasql.DynamicStatements.Prelude+ Hasql.DynamicStatements.Snippet.Defs+ build-depends:+ aeson >=1 && <2,+ base >=4.12 && <5,+ bytestring >=0.10 && <0.11,+ containers >=0.6 && <0.7,+ data-default >=0.7 && <0.8,+ hasql >=1.3.0.5 && <1.4,+ ptr >=0.16.6 && <0.17,+ vector >=0.10 && <0.13
+ library/Hasql/DynamicStatements/Prelude.hs view
@@ -0,0 +1,86 @@+module Hasql.DynamicStatements.Prelude+(+ module Exports,+)+where+++-- base+-------------------------+import Control.Applicative as Exports+import Control.Arrow as Exports+import Control.Category as Exports+import Control.Concurrent as Exports+import Control.Exception as Exports+import Control.Monad as Exports hiding (fail, mapM_, sequence_, forM_, msum, mapM, sequence, forM)+import Control.Monad.IO.Class as Exports+import Control.Monad.Fail as Exports+import Control.Monad.Fix as Exports hiding (fix)+import Control.Monad.ST 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 hiding (toList)+import Data.Function as Exports hiding (id, (.))+import Data.Functor as Exports+import Data.Functor.Contravariant as Exports+import Data.Functor.Identity as Exports+import Data.Int as Exports+import Data.IORef as Exports+import Data.Ix as Exports+import Data.List as Exports hiding (sortOn, isSubsequenceOf, uncons, concat, foldr, foldl1, maximum, minimum, product, sum, all, and, any, concatMap, elem, foldl, foldr1, notElem, or, find, maximumBy, minimumBy, mapAccumL, mapAccumR, foldl')+import Data.Maybe as Exports+import Data.Monoid as Exports hiding (Last(..), First(..), (<>))+import Data.Ord as Exports+import Data.Proxy as Exports+import Data.Ratio as Exports+import Data.Semigroup as Exports+import Data.STRef as Exports+import Data.String as Exports+import Data.Traversable as Exports+import Data.Tuple as Exports+import Data.Unique as Exports+import Data.Version 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 (sizeOf, alignment)+import GHC.Conc as Exports hiding (withMVar, threadWaitWriteSTM, threadWaitWrite, threadWaitReadSTM, threadWaitRead)+import GHC.Exts as Exports (lazy, inline, sortWith, groupWith, IsList(..))+import GHC.Generics as Exports (Generic, Generic1)+import GHC.IO.Exception as Exports+import Numeric as Exports+import Prelude as Exports hiding (fail, concat, foldr, mapM_, sequence_, foldl1, maximum, minimum, product, sum, all, and, any, concatMap, elem, foldl, foldr1, notElem, or, mapM, sequence, id, (.))+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.ParserCombinators.ReadP as Exports (ReadP, ReadS, readP_to_S, readS_to_P)+import Text.ParserCombinators.ReadPrec as Exports (ReadPrec, readPrec_to_P, readP_to_Prec, readPrec_to_S, readS_to_Prec)+import Text.Printf as Exports (printf, hPrintf)+import Text.Read as Exports (Read(..), readMaybe, readEither)+import Unsafe.Coerce as Exports++-- containers+-------------------------+import Data.Sequence as Exports (Seq)++-- bytestring+-------------------------+import Data.ByteString as Exports (ByteString)++-- data-default+-------------------------+import Data.Default as Exports
+ library/Hasql/DynamicStatements/Session.hs view
@@ -0,0 +1,19 @@+module Hasql.DynamicStatements.Session where++import Hasql.DynamicStatements.Prelude+import Hasql.Session+import qualified Hasql.DynamicStatements.Snippet.Defs as SnippetDefs+import qualified Hasql.DynamicStatements.Statement as Statement+import qualified Hasql.Decoders as Decoders+import qualified Hasql.Session as Session++{-|+Execute a dynamically parameterized statement, providing a result decoder.++This is merely a shortcut, which immediately embeds+@Hasql.DynamicStatements.Statement.'Statement.dynamicallyParameterized'@+in @Session@.+For details see the docs on that function.+-}+dynamicallyParameterizedStatement :: SnippetDefs.Snippet -> Decoders.Result result -> Session result+dynamicallyParameterizedStatement snippet decoder = Session.statement () (Statement.dynamicallyParameterized snippet decoder)
+ library/Hasql/DynamicStatements/Snippet.hs view
@@ -0,0 +1,11 @@+module Hasql.DynamicStatements.Snippet+(+ Snippet,+ param,+ nullableParam,+ encoderAndParam,+ encoderAndNullableParam,+)+where++import Hasql.DynamicStatements.Snippet.Defs
+ library/Hasql/DynamicStatements/Snippet/Defs.hs view
@@ -0,0 +1,73 @@+module Hasql.DynamicStatements.Snippet.Defs where++import Hasql.DynamicStatements.Prelude+import qualified Hasql.Encoders as Encoders+++{-|+Composable SQL snippet with parameters injected.+Abstracts over placeholders and matching of encoders.++It has an instance of `IsString`, so having the @OverloadedStrings@ extension enabled+you can use string literals to construct it from string.++Here's an example:++@+selectSubstring :: Text -> Maybe Int64 -> Maybe Int64 -> 'Snippet'+selectSubstring string from to =+ "select substring(" <> 'param' string <>+ 'foldMap' (\\ x -> " from " <> 'param' x) from <>+ 'foldMap' (\\ x -> " for " <> 'param' x) to <>+ ")"+@++Having a decoder you can lift it into 'Hasql.Statement.Statement' using+'Hasql.DynamicStatements.Statement.dynamicallyParameterized' or directly execute it in+'Hasql.Session.Session' using+'Hasql.DynamicStatements.Session.snippet'.+-}+newtype Snippet = Snippet (Seq SnippetChunk)++data SnippetChunk =+ StringSnippetChunk ByteString |+ ParamSnippetChunk (Encoders.Params ())++deriving instance Semigroup Snippet+deriving instance Monoid Snippet++instance IsString Snippet where+ fromString x = Snippet (pure (StringSnippetChunk (fromString x)))++{-|+SQL chunk in ASCII.+-}+sql :: ByteString -> Snippet+sql x = Snippet (pure (StringSnippetChunk x))++{-|+Parameter encoded using an implicitly derived encoder from the type.+-}+param :: Default (Encoders.Value param) => param -> Snippet+param = encoderAndParam def++{-|+Nullable parameter encoded using an implicitly derived encoder from the type.+-}+nullableParam :: Default (Encoders.Value param) => Maybe param -> Snippet+nullableParam = encoderAndNullableParam def++{-|+Parameter with an explicitly defined encoder.+-}+encoderAndParam :: Encoders.Value param -> param -> Snippet+encoderAndParam = paramsEncoderAndParam . Encoders.param++{-|+Nullable parameter with an explicitly defined encoder.+-}+encoderAndNullableParam :: Encoders.Value param -> Maybe param -> Snippet+encoderAndNullableParam = paramsEncoderAndParam . Encoders.nullableParam++paramsEncoderAndParam :: Encoders.Params param -> param -> Snippet+paramsEncoderAndParam encoder param = Snippet (pure (ParamSnippetChunk (param >$ encoder)))
+ library/Hasql/DynamicStatements/Statement.hs view
@@ -0,0 +1,64 @@+module Hasql.DynamicStatements.Statement where++import Hasql.DynamicStatements.Prelude+import Hasql.Statement+import qualified Hasql.DynamicStatements.Snippet.Defs as SnippetDefs+import qualified Hasql.Decoders as Decoders+import qualified Hasql.Encoders as Encoders+import qualified Ptr.Poking as Poking+import qualified Ptr.ByteString as ByteString++{-|+Construct a statement dynamically, specifying the parameters in-place+in the declaration of snippet and providing a result decoder.++The injection of the parameters is handled automatically,+generating parametric statements with binary encoders under the hood.++This is useful when the SQL of your statement depends on the parameters.+Here's an example:++@+selectSubstring :: Text -> Maybe Int64 -> Maybe Int64 -> 'Statement' () Text+selectSubstring string from to = let+ snippet =+ "select substring(" <> Snippet.'SnippetDefs.param' string <>+ foldMap (mappend " from " . Snippet.'SnippetDefs.param') from <>+ foldMap (mappend " to " . Snippet.'SnippetDefs.param') to <>+ ")"+ decoder = Decoders.'Decoders.singleRow' (Decoders.'Decoders.column' Decoders.'Decoders.text')+ in 'dynamicallyParameterized' snippet decoder+@++Without the Snippet API you would have had to implement the same functionality thus:++@+selectSubstring' :: Text -> Maybe Int64 -> Maybe Int64 -> 'Statement' () Text+selectSubstring' string from to = let+ sql = case (from, to) of+ (Just _, Just _) -> "select substring($1 from $2 to $3)"+ (Just _, Nothing) -> "select substring($1 from $2)"+ (Nothing, Just _) -> "select substring($1 to $2)"+ (Nothing, Nothing) -> "select substring($1)"+ encoder = + Encoders.'Encoders.param' (string '>$' Encoders.'Encoders.text') <>+ foldMap (\\ x -> Encoders.'Encoders.param' (x '>$' Encoders.'Encoders.int8')) from <>+ foldMap (\\ x -> Encoders.'Encoders.param' (x '>$' Encoders.'Encoders.int8')) to+ decoder = Decoders.'Decoders.singleRow' (Decoders.'Decoders.column' Decoders.'Decoders.text')+ in Statement sql encoder decoder False+@++As you can see, the Snippet API abstracts over placeholders and+matching encoder generation, thus also protecting you from all sorts of related bugs.+-}+dynamicallyParameterized :: SnippetDefs.Snippet -> Decoders.Result result -> Statement () result+dynamicallyParameterized (SnippetDefs.Snippet chunks) decoder = let+ step (!paramId, !poking, !encoder) = \ case+ SnippetDefs.StringSnippetChunk sql -> (paramId, poking <> Poking.bytes sql, encoder)+ SnippetDefs.ParamSnippetChunk paramEncoder -> let+ newParamId = paramId + 1+ newPoking = poking <> Poking.word8 36 <> Poking.asciiIntegral paramId+ newEncoder = encoder <> paramEncoder+ in (newParamId, newPoking, newEncoder)+ in case foldl' step (1, mempty, mempty) chunks of+ (_, poking, encoder) -> Statement (ByteString.poking poking) encoder decoder False