B7      !"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmn o p q r s t u v w x y z { | } ~   None !"*+03457>CFKLNU2Return constructor name3"Return count of constructor fields4'Get field names from record constructor2345234523452345None !"*+03457>CFKLNU6Derive !' instance. i.e. you have type like that udata Entity = Entity { eField :: Text , eField2 :: Int , efield3 :: Bool } then 6; 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 fields7derives  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 ] 67676767None !"*+03457>CFKLNU8CFunction to transform constructor name into its PG enum conterpart.9derives " and  # instances for a sum-type enum like !data Entity = Red | Green | Blue JTakes constructor w/o arguments and apply callback function. Ejects with * if called with wrong type of constructor.89?mapping function from haskell constructor name to PG enum labeltype to derive instances forshared helper functionconstructor name*function to transform the constructor name\callback function from: 1. haskell constructor name and 2. PG enum option (ByteString)constructor to decompose899889None !"*+03457>CFKLNU:7Builder wich can be effectively concatenated. Requires + inside for string quoting implemented in libpq=<Special constructor to perform old-style query interpolation?*Things which always can be transformed to :ATyped synonym of BCPerforms 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"C8Shorthand function to convert identifier name to builder)runSqlBuilder c $ mkIdent "simple\"ident""\"simple\"\"ident\""$Note correct string quoting made by libpqD5Shorthand function to convert single value to builder(runSqlBuilder c $ mkValue "some ' value""'some '' value'"Note correct string quotingE Lift pure bytestring builder to ::;<=>?@ABCDEF :;<=>?@ABCDEF :;<?@=>ABCDEF:;<=>?@ABCDEFNone !"*+03457>CFKLNU G+Internal type. Result of parsing sql stringHPart of raw sqlI Sql commentJSequence of spacesK&String with haskell expression inside #{..}L&String with haskell expression inside ^{..}M@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 ropePBuild % expression from rowQ"Removes sequential occurencies of H` constructors. Also removes commentaries and squash sequences of spaces to single space symbolRBuild expression of type  SqlBuilder" from SQL query with interpolationS,Embed sql template and perform interpolation @let name = "name" foo = "bar" query = $(sqlExpEmbed "sqlfoobar.sql") -- using foo and bar inside T Just like S0 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  widgetFileGHIJKLMNOExpression of type %PQRExpression of type  SqlBuilderS file pathExpression of type  SqlBuilderTGHIJKLMNOPQRSTMGHIJKLONQPRST GHIJKLMNOPQRSTNone !"*+03457>CFKLNU U}Dot-separated field name. Each element in nested list will be properly quoted and separated by dot. It also have instance of ? 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'"Wtype to put and get from db inet and cidrG typed postgresql fields. This should be in postgresql-simple in fact.Z&Reader of connection. Has instance of ^G. So if you have a connection you can run queries in this monad using gZ. Or you can use this transformer to run sequence of queries using same connection with h.]BEmpty typeclass signing monad in which transaction is safe. i.e. Z^ have this instance, but some other monad giving connection from e.g. connection pool is not.^Instances of this typeclass can acquire connection and pass it to computation. It can be reader of pool of connections or just reader of connectiona0generate list of pairs (field name, field value)baMarked 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 eSingle field to UtextFN "hello" FN ["hello"]textFN "user.name"FN ["user.name"]FNote that it does not split string to parts by point like instance of  doesf=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' "hIf your monad have instance of ^= 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 function4UVWXYZ[\]^_`abcdefBuilder to intercalate withghUVWXYZ[\]^_`abcdefgh^_]Z[\ghWXYUVebcdf`a+UVWXYZ[\]^_`abcdefghNone !"*+03457>CFKLNUiEntity with it's idjvAuxiliary typeclass for data types which can map to rows of some table. This typeclass is used inside functions like pgSelectEntities to generate queries.kId type for this entitylTable name of this entitymField names without id and created?. The order of field names must match with order of fields in ToRow and FromRow instances of this type.ijklmijklmjklmiijklm None !"*+03457>CFKLNUnOptions for deriving jp!Type name to table name converterq%Record field to column name converterrTypeclasses to derive for IdsBase type for IdtDerives instance for jZ 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:  is from package  inflections herenopqrstnopqrstnopqrstnopqrst None !"*+03457>CFKLNUuCalls sequently 6 7 t. 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 u6789GHIJKLMNOPQRSTnopqrstuuu None !"*+03457>CFKLNU v-Generates comma separated list of field namesOrunSqlBuilder con $ buildFields ["u" <> "name", "u" <> "phone", "e" <> "email"]2"\"u\".\"name\", \"u\".\"phone\", \"e\".\"email\""w 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%'"x%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')"yBuild 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\""zSame as y! 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\""{'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\""|;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 "}OConvert 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 "~ Generates  INSERT INTO query for any instance of j 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 ~8 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)" vw table namefields to update conditionx table name*list of pairs (name, value) to insert intoy%modify list of fields. Applied secondZmodify each field name, e.g. prepend each field with prefix, like ("t"<>). Applied firstz{build fields part from proxy|}~ vwxyz{|}~ yz{|~}vwx vwxyz{|}~ None !"*+03457>CFKLNUNExecute all queries inside one transaction. Rollback transaction on exceptionsSame 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 b . 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 ` instanced value. Requires  while k 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 performedEntity 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 rowNone !"*+03457>CFKLNU  !"#$%&'()*+,-./016789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstu3 "!%$#('&*)10/.-,+      !"#"$"%"&"'"(")"*"+",",-./0/1-23 45657575859595:5:5;5<5<5=5=5>5>?@ABCDEFGGHIIJKLMNOPQRSTUVWXYZ[\]^_``aabccdefghijklmnopqrstu v v w x y z { | } ~   postg_AP4GyY2OwVrEddXugXyZ6pDatabase.PostgreSQL.Query#Database.PostgreSQL.Query.TH.Common Database.PostgreSQL.Query.TH.Row!Database.PostgreSQL.Query.TH.Enum$Database.PostgreSQL.Query.SqlBuilder#Database.PostgreSQL.Query.TH.SqlExpDatabase.PostgreSQL.Query.Types Database.PostgreSQL.Query.Entity#Database.PostgreSQL.Query.TH.EntityDatabase.PostgreSQL.Query.TH"Database.PostgreSQL.Query.Internal#Database.PostgreSQL.Query.Functionspostg_ABGs5p1J8FbEwi6uvHaiV6Database.PostgreSQL.LibPQOidpostg_CF6Yc3lhQvaIphAvFcqxJD"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:.ValuescNamecArgs cFieldNameslookupVNameErr deriveFromRow deriveToRow InflectorFunc derivePgEnum SqlBuildersqlBuildQp ToSqlBuilder toSqlBuilderemptyB runSqlBuildermkIdentmkValuesqlBuilderPuresqlBuilderFromFieldRopeRLitRCommentRSpacesRIntRPastesqlExp parseRope ropeParserbuildQ squashRopesqlQExp sqlExpEmbed sqlExpFileFNInetText unInetTextPgMonadT unPgMonadTTransactionSafe HasPostgreswithPGConnection ToMarkedRow toMarkedRow MarkedRowMRunMRtextFN mrToBuilder runPgMonadTlaunchPGEntEntityEntityId tableName fieldNames EntityOptions eoTableName eoColumnNameseoDeriveClasseseoIdType deriveEntityderiveEverything buildFields updateTable insertInto entityFieldsentityFieldsId selectEntityselectEntitiesBy entityToMR insertEntityinsertManyEntitiespgWithTransactionpgWithSavepointpgWithTransactionModepgWithTransactionModeRetrypgWithTransactionSerializablepgQuery pgExecutepgQueryEntitiespgInsertEntitypgSelectEntitiespgSelectJustEntitiespgSelectEntitiesBy pgGetEntity pgGetEntityBypgInsertManyEntitiesIdpgInsertManyEntitiespgDeleteEntitypgUpdateEntity pgSelectCount pgRepsertRowsqlQQwithEnumConstructorbaseGHC.Errerror makeToField makeFromFieldmakeFromFieldGuardmakeToFieldClauseGHC.Basemempty$fMonoidSqlBuilder$fToSqlBuilderText$fToSqlBuilderText0$fToSqlBuilder[]$fToSqlBuilderByteString$fToSqlBuilderByteString0$fToSqlBuilderBuilder$fToSqlBuilderSqlBuilder$fIsStringSqlBuilder$fToSqlBuilderQp buildBuilder Data.StringIsString$fFromFieldInetText$fTransactionSafePgMonadT$fHasPostgresPgMonadT$fMonadHReaderPgMonadT$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$fLiftFNinfle_7EdyykrHppL7LqDQuYb91yText.Inflections toUnderscore$fDefaultEntityOptions&Database.PostgreSQL.Simple.TransactionwithTransactionModewithTransactionModeRetrywithTransactionSerializable Serializableghc-prim GHC.TypesTrue Data.ProxyProxyFalse