4*S      !"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|}~None !"*+03457>CFKLNU27Builder wich can be effectively concatenated. Requires + inside for string quoting implemented in libpq5<Special constructor to perform old-style query interpolation7*Things which always can be transformed to 29Typed synonym of :CPerforms parameters interpolation and return ready to execute query let val = 10let name = "field"TrunSqlBuilder c $ "SELECT * FROM tbl WHERE " <> mkIdent name <> " = " <> mkValue val("SELECT * FROM tbl WHERE \"field\" = 10";8Shorthand function to convert identifier name to builder)runSqlBuilder c $ mkIdent "simple\"ident""\"simple\"\"ident\""$Note correct string quoting made by libpq<5Shorthand function to convert single value to builder(runSqlBuilder c $ mkValue "some ' value""'some '' value'"Note correct string quoting= Lift pure bytestring builder to 223456789:;<=> 23456789:;<=> 23478569:;<=>23456789:;<=>None !"*+03457>CFKLNU ?+Internal type. Result of parsing sql string@Part of raw sqlA Sql commentBSequence of spacesC&String with haskell expression inside #{..}D&String with haskell expression inside ^{..}E@Maybe the main feature of all library. Quasiquoter which builds  SqlBuilder from string query. Removes line comments and block comments (even nested) and sequences of spaces. Correctly works handles string literals and quoted identifiers. Here is examples of usagelet name = "name"let val = "some 'value'"JrunSqlBuilder c [sqlExp|SELECT * FROM tbl WHERE ^{mkIdent name} = #{val}|]5"SELECT * FROM tbl WHERE \"name\" = 'some ''value'''"And more comples example:let name = Just "name"let size = Just 10"let active = Nothing :: Maybe Boollet condlist = catMaybes [ fmap (\a -> [sqlExp|name = #{a}|]) name, fmap (\a -> [sqlExp|size = #{a}|]) size, fmap (\a -> [sqlExp|active = #{a}|]) active]nlet cond = if L.null condlist then mempty else [sqlExp| WHERE ^{mconcat $ L.intersperse " AND " $ condlist} |]ErunSqlBuilder c [sqlExp|SELECT * FROM tbl ^{cond} -- line comment|]8"SELECT * FROM tbl WHERE name = 'name' AND size = 10 "Build builder from ropeHBuild % expression from rowI"Removes sequential occurencies of @` constructors. Also removes commentaries and squash sequences of spaces to single space symbolJBuild expression of type  SqlBuilder" from SQL query with interpolationK,Embed sql template and perform interpolation @let name = "name" foo = "bar" query = $(sqlExpEmbed "sqlfoobar.sql") -- using foo and bar inside L Just like K0 but uses pattern instead of file name. So, code $let query = $(sqlExpFile "foo/bar") is just the same as let query = $(sqlExpEmbed "sqlfoo bar.sql") "This function inspired by Yesod's  widgetFile?@ABCDEFGExpression of type %HIJExpression of type  SqlBuilderK file pathExpression of type  SqlBuilderL?@ABCDEFGHIJKLE?@ABCDGFIHJKL ?@ABCDEFGHIJKLNone !"*+03457>CFKLNU M}Dot-separated field name. Each element in nested list will be properly quoted and separated by dot. It also have instance of 7 and  so you can:let a = "hello" :: FNa FN ["hello"]let b = "user.name" :: FNbFN ["user","name"]let n = "u.name" :: FN runSqlBuilder c $ toSqlBuilder n"\"u\".\"name\""("user" <> "name") :: FNFN ["user","name"]let a = "name" :: FNlet b = "email" :: FNErunSqlBuilder c [sqlExp|^{"u" <> a} = 'name', ^{"e" <> b} = 'email'|]4"\"u\".\"name\" = 'name', \"e\".\"email\" = 'email'"Otype to put and get from db inet and cidrG typed postgresql fields. This should be in postgresql-simple in fact.R&Reader of connection. Has instance of VG. So if you have a connection you can run queries in this monad using _Z. Or you can use this transformer to run sequence of queries using same connection with `.UBEmpty typeclass signing monad in which transaction is safe. i.e. R^ have this instance, but some other monad giving connection from e.g. connection pool is not.VInstances of this typeclass can acquire connection and pass it to computation. It can be reader of pool of connections or just reader of connectionY0generate list of pairs (field name, field value)ZaMarked row is list of pairs of field name and some sql expression. Used to generate queries like: name = name AND size = 10 AND length = 20 or UPDATE tbl SET name = name, size = 10, lenght = 20 ]Single field to MtextFN "hello" FN ["hello"]textFN "user.name"FN ["user.name"]FNote that it does not split string to parts by point like instance of  does^=Turns marked row to query intercalating it with other buildererunSqlBuilder c $ mrToBuilder "AND" $ MR [("name", mkValue "petr"), ("email", mkValue "foo@bar.com")]3" \"name\" = 'petr' AND \"email\" = 'foo@bar.com' "`If your monad have instance of V= you maybe dont need this function, unless your instance use  withPGPool which acquires connection from pool for each query. If you want to run sequence of queries using same connection you need this function3MNOPQRSTUVWXYZ[\]^Builder to intercalate with_`MNOPQRSTUVWXYZ[\]^_`VWURST_`OPQMN]Z[\^XY*MNOPQRSTUVWXYZ[\]^_`None !"*+03457>CFKLNUaEntity with it's idbvAuxiliary typeclass for data types which can map to rows of some table. This typeclass is used inside functions like pgSelectEntities to generate queries.cId type for this entitydTable name of this entityeField names without id and created?. The order of field names must match with order of fields in ToRow and FromRow instances of this type.abcdeabcdebcdeaabcdeNone !"*+03457>CFKLNU fOptions for deriving bh!Type name to table name converteri%Record field to column name converterjTypeclasses to derive for IdkBase type for IdReturn constructor name"Return count of constructor fields'Get field names from record constructorlDerive !' instance. i.e. you have type like that udata Entity = Entity { eField :: Text , eField2 :: Int , efield3 :: Bool } then l; will generate this instance: instance FromRow Entity where {instance FromRow Entity where fromRow = Entity <$> field <*> field <*> field FDatatype must have just one constructor with arbitrary count of fieldsmderives  instance for datatype like udata Entity = Entity { eField :: Text , eField2 :: Int , efield3 :: Bool } "it will derive instance like that: instance ToRow Entity where toRow (Entity e1 e2 e3) = [ toField e1 , toField e2 , toField e3 ] nDerives instance for bZ using type name and field names. Also generates type synonim for ID. E.g. code like this: data Agent = Agent { aName :: !Text , aAttributes :: !HStoreMap , aLongWeirdName :: !Int } deriving (Ord, Eq, Show) $(deriveEntity def { eoIdType = ''Id , eoTableName = toUnderscore , eoColumnNames = toUnderscore . drop 1 , eoDeriveClasses = [''Show, ''Read, ''Ord, ''Eq , ''FromField, ''ToField, ''PathPiece] } ''Agent ) Will generate code like this: 1instance Database.PostgreSQL.Query.Entity Agent where newtype EntityId Agent = AgentId {getAgentId :: Id} deriving (Show, Read, Ord, Eq, FromField, ToField, PathPiece) tableName _ = "agent" fieldNames _ = ["name", "attributes", "long_weird_name"] type AgentId = EntityId Agent 0So, you dont need to write it by hands any more.NOTE:  toUnderscore is from package  inflections hereoCalls sequently l m n. E.g. code like this: data Agent = Agent { aName :: !Text , aAttributes :: !HStoreMap , aLongWeirdName :: !Int } deriving (Ord, Eq, Show) $(deriveEverything def { eoIdType = ''Id , eoTableName = toUnderscore , eoColumnNames = toUnderscore . drop 1 , eoDeriveClasses = [''Show, ''Read, ''Ord, ''Eq , ''FromField, ''ToField, ''PathPiece] } ''Agent ) will generate that: instance ToRow Agent where toRow (Agent a_aE3w a_aE3x a_aE3y) = [toField a_aE3w, toField a_aE3x, toField a_aE3y] instance FromRow Agent where fromRow = Agent  $2 Database.PostgreSQL.Simple.FromRow.field  *2 Database.PostgreSQL.Simple.FromRow.field  *[ Database.PostgreSQL.Simple.FromRow.field instance Database.PostgreSQL.Query.Entity Agent where newtype EntityId Agent = AgentId {getAgentId :: Id} deriving (Show, Read, Ord, Eq, FromField, ToField, PathPiece) tableName _ = "agent" fieldNames _ = ["name", "attributes", "long_weird_name"] type AgentId = EntityId Agent fghijklmnop File pathqsql file patternEKLfghijklmnopqlmnofghijkpqEKL fghijklmnopqNone !"*+03457>CFKLNU r-Generates comma separated list of field namesOrunSqlBuilder con $ buildFields ["u" <> "name", "u" <> "phone", "e" <> "email"]2"\"u\".\"name\", \"u\".\"phone\", \"e\".\"email\""s generates UPDATE querylet name = "%vip%"wrunSqlBuilder con $ updateTable "ships" (MR [("size", mkValue 15)]) [sqlExp|WHERE size > 15 AND name NOT LIKE #{name}|]P"UPDATE \"ships\" SET \"size\" = 15 WHERE size > 15 AND name NOT LIKE '%vip%'"t%Generate INSERT INTO query for entityerunSqlBuilder con $ insertInto "foo" $ MR [("name", mkValue "vovka"), ("hobby", mkValue "president")]I"INSERT INTO \"foo\" (\"name\", \"hobby\") VALUES ('vovka', 'president')"uBuild entity fields.data Foo = Foo { fName :: Text, fSize :: Int }tinstance Entity Foo where {newtype EntityId Foo = FooId Int ; fieldNames _ = ["name", "size"] ; tableName _ = "foo"};runSqlBuilder con $ entityFields id id (Proxy :: Proxy Foo)"\"name\", \"size\""@runSqlBuilder con $ entityFields ("id":) id (Proxy :: Proxy Foo)"\"id\", \"name\", \"size\""XrunSqlBuilder con $ entityFields (\l -> ("id":l) ++ ["created"]) id (Proxy :: Proxy Foo))"\"id\", \"name\", \"size\", \"created\""@runSqlBuilder con $ entityFields id ("f"<>) (Proxy :: Proxy Foo) "\"f\".\"name\", \"f\".\"size\""GrunSqlBuilder con $ entityFields ("f.id":) ("f"<>) (Proxy :: Proxy Foo)."\"f\".\"id\", \"f\".\"name\", \"f\".\"size\""vSame as u! but prefixes list of names with id3 field. This is shorthand function for often usage..data Foo = Foo { fName :: Text, fSize :: Int }tinstance Entity Foo where {newtype EntityId Foo = FooId Int ; fieldNames _ = ["name", "size"] ; tableName _ = "foo"}:runSqlBuilder con $ entityFieldsId id (Proxy :: Proxy Foo)"\"id\", \"name\", \"size\""?runSqlBuilder con $ entityFieldsId ("f"<>) (Proxy :: Proxy Foo)."\"f\".\"id\", \"f\".\"name\", \"f\".\"size\""w'Generate SELECT query string for entity.data Foo = Foo { fName :: Text, fSize :: Int }tinstance Entity Foo where {newtype EntityId Foo = FooId Int ; fieldNames _ = ["name", "size"] ; tableName _ = "foo"}IrunSqlBuilder con $ selectEntity (entityFieldsId id) (Proxy :: Proxy Foo)0"SELECT \"id\", \"name\", \"size\" FROM \"foo\""NrunSqlBuilder con $ selectEntity (entityFieldsId ("f"<>)) (Proxy :: Proxy Foo)B"SELECT \"f\".\"id\", \"f\".\"name\", \"f\".\"size\" FROM \"foo\""JrunSqlBuilder con $ selectEntity (entityFields id id) (Proxy :: Proxy Foo)("SELECT \"name\", \"size\" FROM \"foo\""x;Generates SELECT FROM WHERE query with most used conditions.data Foo = Foo { fName :: Text, fSize :: Int }tinstance Entity Foo where {newtype EntityId Foo = FooId Int ; fieldNames _ = ["name", "size"] ; tableName _ = "foo"}DrunSqlBuilder con $ selectEntitiesBy id (Proxy :: Proxy Foo) $ MR []("SELECT \"name\", \"size\" FROM \"foo\""_runSqlBuilder con $ selectEntitiesBy id (Proxy :: Proxy Foo) $ MR [("name", mkValue "fooname")]E"SELECT \"name\", \"size\" FROM \"foo\" WHERE \"name\" = 'fooname' "urunSqlBuilder con $ selectEntitiesBy id (Proxy :: Proxy Foo) $ MR [("name", mkValue "fooname"), ("size", mkValue 10)]W"SELECT \"name\", \"size\" FROM \"foo\" WHERE \"name\" = 'fooname' AND \"size\" = 10 "yOConvert entity instance to marked row to perform inserts updates and same stuff.data Foo = Foo { fName :: Text, fSize :: Int }tinstance Entity Foo where {newtype EntityId Foo = FooId Int ; fieldNames _ = ["name", "size"] ; tableName _ = "foo"}Kinstance ToRow Foo where { toRow Foo{..} = [toField fName, toField fSize] }HrunSqlBuilder con $ mrToBuilder ", " $ entityToMR $ Foo "Enterprise" 610-" \"name\" = 'Enterprise' , \"size\" = 610 "z Generates  INSERT INTO query for any instance of b and .data Foo = Foo { fName :: Text, fSize :: Int }tinstance Entity Foo where {newtype EntityId Foo = FooId Int ; fieldNames _ = ["name", "size"] ; tableName _ = "foo"}Kinstance ToRow Foo where { toRow Foo{..} = [toField fName, toField fSize] }7runSqlBuilder con $ insertEntity $ Foo "Enterprise" 910E"INSERT INTO \"foo\" (\"name\", \"size\") VALUES ('Enterprise', 910)"{Same as z8 but generates query to insert many queries at same time.data Foo = Foo { fName :: Text, fSize :: Int }tinstance Entity Foo where {newtype EntityId Foo = FooId Int ; fieldNames _ = ["name", "size"] ; tableName _ = "foo"}Kinstance ToRow Foo where { toRow Foo{..} = [toField fName, toField fSize] }mrunSqlBuilder con $ insertManyEntities $ NL.fromList [Foo "meter" 1, Foo "table" 2, Foo "earth" 151930000000]_"INSERT INTO \"foo\" (\"name\",\"size\") VALUES ('meter',1),('table',2),('earth',151930000000)" rs table namefields to update conditiont table name*list of pairs (name, value) to insert intou%modify list of fields. Applied secondZmodify each field name, e.g. prepend each field with prefix, like ("t"<>). Applied firstvwbuild fields part from proxyxyz{ rstuvwxyz{ uvwxz{yrst rstuvwxyz{None !"*+03457>CFKLNU|NExecute all queries inside one transaction. Rollback transaction on exceptions}Same as |& but executes queries inside savepoint~ Wrapper for L: Execute an action inside a SQL transaction with a given transaction mode. Wrapper for : Like ~D, but also takes a custom callback to determine if a transaction should be retried if an SqlError occurs. If the callback returns True, then the transaction will be retried. If the callback returns False, or an exception other than an SqlError occurs then the transaction will be rolled back and the exception rethrown. Wrapper for !: Execute an action inside of a  transaction. If a serialization failure occurs, roll back the transaction and try again. Be warned that this may execute the IO action multiple times.A Serializable transaction creates the illusion that your program has exclusive access to the database. This means that, even in a concurrent setting, you can perform queries in sequence without having to worry about what might happen between one statement and the next.Execute query generated by  SqlBuilder. Typical use case: mlet userName = "Vovka Erohin" :: Text pgQuery [sqlExp| SELECT id, name FROM users WHERE name = #{userName}|] Or jlet userName = "Vovka Erohin" :: Text pgQuery $ Qp "SELECT id, name FROM users WHERE name = ?" [userName] uWhich is almost the same. In both cases proper value escaping is performed so you stay protected from sql injections.9Execute arbitrary query and return count of affected rows@Executes arbitrary query and parses it as entities and their ids$Insert new entity and return it's id)Select entities as pairs of (id, entity). %handler :: Handler [Ent a] handler = do now <- liftIO getCurrentTime let back = addUTCTime (days (-7)) now pgSelectEntities id [sqlExp|WHERE created BETWEEN #{now} AND #{back} ORDER BY created|] handler2 :: Text -> Handler [Ent Foo] handler2 fvalue = do pgSelectEntities ("t"<>) [sqlExp|AS t INNER JOIN table2 AS t2 ON t.t2_id = t2.id WHERE t.field = #{fvalue} ORDER BY t2.field2|] -- Here the query will be: SELECT ... FROM tbl AS t INNER JOIN ... Same as  but do not select id)Select entities by condition formed from Z . Usefull function when you knowSelect entity by id qgetUser :: EntityId User -> Handler User getUser uid = do pgGetEntity uid >>= maybe notFound return $Get entity by some fields constraint getUser :: UserName -> Handler User getUser name = do pgGetEntityBy (MR [("name", mkValue name), ("active", mkValue True)]) >>= maybe notFound return The query here will be like CpgQuery [sqlExp|SELECT id, name, phone ... FROM users WHERE name = {name} AND active =  {True}|] Same as S but insert many entities at one action. Returns list of id's of inserted entities8Insert many entities without returning list of id like  doesDelete entity. MrmUser :: EntityId User -> Handler () rmUser uid = do pgDeleteEntity uid Return  if row was actually deleted.Update entity using X instanced value. Requires  while c is not a data type. fixUser :: Text -> EntityId User -> Handler () fixUser username uid = do pgGetEntity uid >>= maybe notFound run where run user = pgUpdateEntity uid $ MR [("active", mkValue True) ("name", mkValue username)] Returns $ if record was actually updated and @ if there was not row with such id (or was more than 1, in fact))Select count of entities with given query activeUsers :: Handler Integer activeUsers = do pgSelectCount (Proxy :: Proxy User) [sqlExp|WHERE active = #{True}|] Perform repsert of the same row, first trying "update where" then "insert" with concatenated fields. Which means that if you run VpgRepsertRow "emails" (MR [("user_id", mkValue uid)]) (MR [("email", mkValue email)]) Then firstly will be performed UPDATE "emails" SET email =  'foo@bar.com' WHERE "user_id" = 1234 4And if no one row is affected (which is returned by ), then 8INSERT INTO "emails" ("user_id", "email") VALUES (1234,  'foo@bar.com') will be performed|}~Entity fields name modifier, e.g. ("tablename"<>). Each field of entity will be processed by this modifier before pasting to the querypart of query just after SELECT .. FROM table.*uniq constrained list of fields and values Table namewhere condition update row|}~|}~|}~None !"*+03457>CFKLNU|  !"#$%&'()*+,-./0123456789:;<=>EKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmnopq|}~3 "!%$#('&*)10/.-,+                        ! " # $ % & ' ( ( )* +, +- ). / 0 12 13 13 14 15 15 16 16 17 18 18 19 19 1: 1:;;<==>?@ABCDEFGHIJKLMNOPQRSTTUUVWWXYZ[\]^_`abcdefghijjklmnopqrstuvwxyz{|}~ postg_1o1u0VrHgjv37G4jT3Xm57Database.PostgreSQL.Query$Database.PostgreSQL.Query.SqlBuilder#Database.PostgreSQL.Query.TH.SqlExpDatabase.PostgreSQL.Query.Types Database.PostgreSQL.Query.EntityDatabase.PostgreSQL.Query.TH"Database.PostgreSQL.Query.Internal#Database.PostgreSQL.Query.Functionspostg_ABGs5p1J8FbEwi6uvHaiV6Database.PostgreSQL.LibPQOidpostg_DXnmvwB5nnw4cfMxwmQxcQ"Database.PostgreSQL.Simple.FromRowfromRow0Database.PostgreSQL.Simple.HStore.ImplementationparseHStoreListhstoretoHStoreToHStore HStoreBuilder toHStoreText ToHStoreText HStoreTextfromHStoreList HStoreList fromHStoreMap HStoreMap$Database.PostgreSQL.Simple.FromField fromField#Database.PostgreSQL.Simple.InternalconnectPostgreSQLconnectdefaultConnectInfo ConnectionconnectDatabaseconnectPassword connectUser connectPort connectHost ConnectInfo"Database.PostgreSQL.Simple.ToFieldtoField Database.PostgreSQL.Simple.ToRowtoRowToRowToFieldFromRow FromField Database.PostgreSQL.Simple.Types fromQueryQueryfromOnlyOnlyIn fromPGArrayPGArray:.Values SqlBuildersqlBuildQp ToSqlBuilder toSqlBuilderemptyB runSqlBuildermkIdentmkValuesqlBuilderPuresqlBuilderFromFieldRopeRLitRCommentRSpacesRIntRPastesqlExp parseRope ropeParserbuildQ squashRopesqlQExp sqlExpEmbed sqlExpFileFNInetText unInetTextPgMonadT unPgMonadTTransactionSafe HasPostgreswithPGConnection ToMarkedRow toMarkedRow MarkedRowMRunMRtextFN mrToBuilder runPgMonadTlaunchPGEntEntityEntityId tableName fieldNames EntityOptions eoTableName eoColumnNameseoDeriveClasseseoIdType deriveFromRow deriveToRow deriveEntityderiveEverythingembedSqlsqlFile buildFields updateTable insertInto entityFieldsentityFieldsId selectEntityselectEntitiesBy entityToMR insertEntityinsertManyEntitiespgWithTransactionpgWithSavepointpgWithTransactionModepgWithTransactionModeRetrypgWithTransactionSerializablepgQuery pgExecutepgQueryEntitiespgInsertEntitypgSelectEntitiespgSelectJustEntitiespgSelectEntitiesBy pgGetEntity pgGetEntityBypgInsertManyEntitiesIdpgInsertManyEntitiespgDeleteEntitypgUpdateEntity pgSelectCount pgRepsertRowsqlQQbaseGHC.Basemempty$fMonoidSqlBuilder$fToSqlBuilderText$fToSqlBuilderText0$fToSqlBuilder[]$fToSqlBuilderByteString$fToSqlBuilderByteString0$fToSqlBuilderBuilder$fToSqlBuilderSqlBuilder$fIsStringSqlBuilder$fToSqlBuilderQp buildBuilder Data.StringIsString$fFromFieldInetText$fTransactionSafePgMonadT$fHasPostgresPgMonadT$fMonadReaderrPgMonadT$fMonadTransControlPgMonadT$fMonadBaseControlbPgMonadT$fTransactionSafeWriterT$fTransactionSafeWriterT0$fTransactionSafeContT$fTransactionSafeStateT$fTransactionSafeStateT0$fTransactionSafeReaderT$fTransactionSafeMaybeT$fTransactionSafeIdentityT$fTransactionSafeExceptT$fTransactionSafeEitherT$fHasPostgresHReaderT$fHasPostgresWriterT$fHasPostgresWriterT0$fHasPostgresContT$fHasPostgresStateT$fHasPostgresStateT0$fHasPostgresReaderT$fHasPostgresMaybeT$fHasPostgresIdentityT$fHasPostgresExceptT$fHasPostgresEitherT$fToMarkedRowMarkedRow $fIsStringFN$fToSqlBuilderFN$fLiftFNcNamecArgs cFieldNameslookupVNameErr$fDefaultEntityOptions&Database.PostgreSQL.Simple.TransactionwithTransactionModewithTransactionModeRetrywithTransactionSerializable Serializableghc-prim GHC.TypesTrue Data.ProxyProxyFalse