-- Hoogle documentation, generated by Haddock -- See Hoogle, http://www.haskell.org/hoogle/ -- | Sql interpolating quasiquote plus some kind of primitive ORM using it -- @package postgresql-query @version 1.2.1 module Database.PostgreSQL.Query.SqlBuilder -- | Builder wich can be effectively concatenated. Requires -- Connection inside for string quoting implemented in -- libpq newtype SqlBuilder SqlBuilder :: (Connection -> IO Builder) -> SqlBuilder sqlBuild :: SqlBuilder -> Connection -> IO Builder -- | Things which always can be transformed to SqlBuilder class ToSqlBuilder a toSqlBuilder :: ToSqlBuilder a => a -> SqlBuilder -- | Special constructor to perform old-style query interpolation data Qp Qp :: Query -> row -> Qp -- | Typed synonym of mempty emptyB :: SqlBuilder -- | Performs parameters interpolation and return ready to execute query -- --
-- >>> let val = 10 -- -- >>> let name = "field" -- -- >>> runSqlBuilder c $ "SELECT * FROM tbl WHERE " <> mkIdent name <> " = " <> mkValue val -- "SELECT * FROM tbl WHERE \"field\" = 10" --runSqlBuilder :: Connection -> SqlBuilder -> IO Query -- | Shorthand function to convert identifier name to builder -- --
-- >>> runSqlBuilder c $ mkIdent "simple\"ident" -- "\"simple\"\"ident\"" ---- -- Note correct string quoting made by libpq mkIdent :: Text -> SqlBuilder -- | Shorthand function to convert single value to builder -- --
-- >>> runSqlBuilder c $ mkValue "some ' value" -- "'some '' value'" ---- -- Note correct string quoting mkValue :: ToField a => a -> SqlBuilder -- | Lift pure bytestring builder to SqlBuilder sqlBuilderPure :: Builder -> SqlBuilder sqlBuilderFromField :: ToField a => Query -> a -> SqlBuilder instance Typeable SqlBuilder instance Generic SqlBuilder instance Datatype D1SqlBuilder instance Constructor C1_0SqlBuilder instance Selector S1_0_0SqlBuilder instance Monoid SqlBuilder instance ToSqlBuilder Text instance ToSqlBuilder Text instance ToSqlBuilder String instance ToSqlBuilder ByteString instance ToSqlBuilder ByteString instance ToSqlBuilder Builder instance ToSqlBuilder SqlBuilder instance IsString SqlBuilder instance ToSqlBuilder Qp module Database.PostgreSQL.Query.TH.SqlExp -- | 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 -- usage -- --
-- >>> let name = "name"
--
-- >>> let val = "some 'value'"
--
-- >>> runSqlBuilder c [sqlExp|SELECT * FROM tbl WHERE ^{mkIdent name} = #{val}|]
-- "SELECT * FROM tbl WHERE \"name\" = 'some ''value'''"
--
--
-- And more comples example:
--
--
-- >>> let name = Just "name"
--
-- >>> let size = Just 10
--
-- >>> let active = Nothing :: Maybe Bool
--
-- >>> let condlist = catMaybes [ fmap (\a -> [sqlExp|name = #{a}|]) name, fmap (\a -> [sqlExp|size = #{a}|]) size, fmap (\a -> [sqlExp|active = #{a}|]) active]
--
-- >>> let cond = if L.null condlist then mempty else [sqlExp| WHERE ^{mconcat $ L.intersperse " AND " $ condlist} |]
--
-- >>> runSqlBuilder c [sqlExp|SELECT * FROM tbl ^{cond} -- line comment|]
-- "SELECT * FROM tbl WHERE name = 'name' AND size = 10 "
--
sqlExp :: QuasiQuoter
-- | Internal type. Result of parsing sql string
data Rope
-- | Part of raw sql
RLit :: Text -> Rope
-- | Sql comment
RComment :: Text -> Rope
-- | Sequence of spaces
RSpaces :: Int -> Rope
-- | String with haskell expression inside #{..}
RInt :: Text -> Rope
-- | String with haskell expression inside ^{..}
RPaste :: Text -> Rope
ropeParser :: Parser [Rope]
parseRope :: String -> [Rope]
-- | Removes sequential occurencies of RLit constructors. Also
-- removes commentaries and squash sequences of spaces to single space
-- symbol
squashRope :: [Rope] -> [Rope]
-- | Build Query expression from row
buildQ :: [Rope] -> Q Exp
-- | Build expression of type SqlBuilder from SQL query with
-- interpolation
sqlQExp :: String -> Q Exp
-- | Embed sql template and perform interpolation
--
-- -- let name = "name" -- foo = "bar" -- query = $(sqlExpEmbed "sqlfoobar.sql") -- using foo and bar inside --sqlExpEmbed :: String -> Q Exp -- | Just like sqlExpEmbed but uses pattern instead of file name. -- So, code -- --
-- let query = $(sqlExpFile "foo/bar") ---- -- is just the same as -- --
-- let query = $(sqlExpEmbed "sqlfoobar.sql") ---- -- This function inspired by Yesod's widgetFile sqlExpFile :: String -> Q Exp instance Ord Rope instance Eq Rope instance Show Rope module Database.PostgreSQL.Query.Types -- | Instances of this typeclass can acquire connection and pass it to -- computation. It can be reader of pool of connections or just reader of -- connection class MonadBase IO m => HasPostgres m withPGConnection :: HasPostgres m => (Connection -> m a) -> m a -- | Empty typeclass signing monad in which transaction is safe. i.e. -- PgMonadT have this instance, but some other monad giving -- connection from e.g. connection pool is not. class TransactionSafe (m :: * -> *) -- | Reader of connection. Has instance of HasPostgres. So if you -- have a connection you can run queries in this monad using -- runPgMonadT. Or you can use this transformer to run sequence of -- queries using same connection with launchPG. newtype PgMonadT m a PgMonadT :: ReaderT Connection m a -> PgMonadT m a unPgMonadT :: PgMonadT m a -> ReaderT Connection m a runPgMonadT :: Connection -> PgMonadT m a -> m a -- | If your monad have instance of HasPostgres 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 function launchPG :: HasPostgres m => PgMonadT m a -> m a -- | type to put and get from db inet and cidr typed -- postgresql fields. This should be in postgresql-simple in fact. newtype InetText InetText :: Text -> InetText unInetText :: InetText -> Text -- | Dot-separated field name. Each element in nested list will be properly -- quoted and separated by dot. It also have instance of -- ToSqlBuilder and IsString so you can: -- --
-- >>> let a = "hello" :: FN -- -- >>> a -- FN ["hello"] ---- --
-- >>> let b = "user.name" :: FN -- -- >>> b -- FN ["user","name"] ---- --
-- >>> let n = "u.name" :: FN -- -- >>> runSqlBuilder c $ toSqlBuilder n -- "\"u\".\"name\"" ---- --
-- >>> ("user" <> "name") :: FN
-- FN ["user","name"]
--
--
--
-- >>> let a = "name" :: FN
--
-- >>> let b = "email" :: FN
--
-- >>> runSqlBuilder c [sqlExp|^{"u" <> a} = 'name', ^{"e" <> b} = 'email'|]
-- "\"u\".\"name\" = 'name', \"e\".\"email\" = 'email'"
--
newtype FN
FN :: [Text] -> FN
-- | Single field to FN
--
-- -- >>> textFN "hello" -- FN ["hello"] ---- --
-- >>> textFN "user.name" -- FN ["user.name"] ---- -- Note that it does not split string to parts by point like instance of -- IsString does textFN :: Text -> FN -- | Marked 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 --newtype MarkedRow MR :: [(FN, SqlBuilder)] -> MarkedRow unMR :: MarkedRow -> [(FN, SqlBuilder)] -- | Turns marked row to query intercalating it with other builder -- --
-- >>> runSqlBuilder c $ mrToBuilder "AND" $ MR [("name", mkValue "petr"), ("email", mkValue "foo@bar.com")]
-- " \"name\" = 'petr' AND \"email\" = 'foo@bar.com' "
--
mrToBuilder :: SqlBuilder -> MarkedRow -> SqlBuilder
class ToMarkedRow a
toMarkedRow :: ToMarkedRow a => a -> MarkedRow
instance Typeable InetText
instance Typeable FN
instance Typeable MarkedRow
instance IsString InetText
instance Eq InetText
instance Ord InetText
instance Read InetText
instance Show InetText
instance Monoid InetText
instance ToField InetText
instance Ord FN
instance Eq FN
instance Show FN
instance Monoid FN
instance Generic FN
instance Monoid MarkedRow
instance Generic MarkedRow
instance Functor m => Functor (PgMonadT m)
instance Applicative m => Applicative (PgMonadT m)
instance Monad m => Monad (PgMonadT m)
instance MonadWriter w m => MonadWriter w (PgMonadT m)
instance MonadState s m => MonadState s (PgMonadT m)
instance MonadError e m => MonadError e (PgMonadT m)
instance MonadTrans PgMonadT
instance Alternative m => Alternative (PgMonadT m)
instance MonadFix m => MonadFix (PgMonadT m)
instance MonadPlus m => MonadPlus (PgMonadT m)
instance MonadIO m => MonadIO (PgMonadT m)
instance MonadCont m => MonadCont (PgMonadT m)
instance MonadThrow m => MonadThrow (PgMonadT m)
instance MonadCatch m => MonadCatch (PgMonadT m)
instance MonadMask m => MonadMask (PgMonadT m)
instance MonadBase b m => MonadBase b (PgMonadT m)
instance MonadLogger m => MonadLogger (PgMonadT m)
instance Datatype D1FN
instance Constructor C1_0FN
instance Datatype D1MarkedRow
instance Constructor C1_0MarkedRow
instance Selector S1_0_0MarkedRow
instance TransactionSafe (PgMonadT m)
instance MonadBase IO m => HasPostgres (PgMonadT m)
instance MonadReader r m => MonadReader r (PgMonadT m)
instance MonadTransControl PgMonadT
instance MonadBaseControl b m => MonadBaseControl b (PgMonadT m)
instance (TransactionSafe m, Monoid w) => TransactionSafe (WriterT w m)
instance (TransactionSafe m, Monoid w) => TransactionSafe (WriterT w m)
instance TransactionSafe m => TransactionSafe (ContT r m)
instance TransactionSafe m => TransactionSafe (StateT s m)
instance TransactionSafe m => TransactionSafe (StateT s m)
instance TransactionSafe m => TransactionSafe (ReaderT r m)
instance TransactionSafe m => TransactionSafe (MaybeT m)
instance TransactionSafe m => TransactionSafe (IdentityT m)
instance TransactionSafe m => TransactionSafe (ExceptT e m)
instance TransactionSafe m => TransactionSafe (EitherT e m)
instance (HasPostgres m, Monoid w) => HasPostgres (WriterT w m)
instance (HasPostgres m, Monoid w) => HasPostgres (WriterT w m)
instance HasPostgres m => HasPostgres (ContT r m)
instance HasPostgres m => HasPostgres (StateT s m)
instance HasPostgres m => HasPostgres (StateT s m)
instance HasPostgres m => HasPostgres (ReaderT r m)
instance HasPostgres m => HasPostgres (MaybeT m)
instance HasPostgres m => HasPostgres (IdentityT m)
instance HasPostgres m => HasPostgres (ExceptT e m)
instance HasPostgres m => HasPostgres (EitherT e m)
instance ToMarkedRow MarkedRow
instance IsString FN
instance ToSqlBuilder FN
instance FromField InetText
module Database.PostgreSQL.Query.Entity
-- | Auxiliary typeclass for data types which can map to rows of some
-- table. This typeclass is used inside functions like
-- pgSelectEntities to generate queries.
class Entity a where data family EntityId a :: *
tableName :: Entity a => Proxy a -> Text
fieldNames :: Entity a => Proxy a -> [Text]
-- | Entity with it's id
type Ent a = (EntityId a, a)
instance Typeable EntityId
module Database.PostgreSQL.Query.TH
-- | Derive FromRow instance. i.e. you have type like that
--
--
-- data Entity = Entity
-- { eField :: Text
-- , eField2 :: Int
-- , efield3 :: Bool }
--
--
-- then deriveFromRow will generate this instance: instance
-- FromRow Entity where
--
-- -- instance FromRow Entity where -- fromRow = Entity -- <$> field -- <*> field -- <*> field ---- -- Datatype must have just one constructor with arbitrary count of fields deriveFromRow :: Name -> Q [Dec] -- | derives ToRow instance for datatype like -- --
-- data 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 ] --deriveToRow :: Name -> Q [Dec] -- | Derives instance for Entity 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
-- , eoDeriveClassess =
-- [''Show, ''Read, ''Ord, ''Eq
-- , ''FromField, ''ToField, ''PathPiece]
-- }
-- ''Agent )
--
--
-- Will generate code like this:
--
--
-- 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
--
--
-- So, you dont need to write it by hands any more.
--
-- NOTE: toUnderscore is from package inflections here
deriveEntity :: EntityOptions -> Name -> Q [Dec]
-- | Calls sequently deriveFromRow deriveToRow
-- deriveEntity. 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
-- , eoDeriveClassess =
-- [''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 $ Database.PostgreSQL.Simple.FromRow.field
-- * 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
--
deriveEverything :: EntityOptions -> Name -> Q [Dec]
-- | Options for deriving Entity
data EntityOptions
EntityOptions :: (String -> String) -> (String -> String) -> [Name] -> Name -> EntityOptions
-- | Type name to table name converter
eoTableName :: EntityOptions -> String -> String
-- | Record field to column name converter
eoColumnNames :: EntityOptions -> String -> String
-- | Typeclasses to derive for Id
eoDeriveClassess :: EntityOptions -> [Name]
-- | Base type for Id
eoIdType :: EntityOptions -> Name
-- | Deprecated: use sqlExpEmbed instead
embedSql :: String -> Q Exp
-- | Deprecated: use sqlExpFile instead
sqlFile :: String -> Q Exp
-- | 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
-- usage
--
--
-- >>> let name = "name"
--
-- >>> let val = "some 'value'"
--
-- >>> runSqlBuilder c [sqlExp|SELECT * FROM tbl WHERE ^{mkIdent name} = #{val}|]
-- "SELECT * FROM tbl WHERE \"name\" = 'some ''value'''"
--
--
-- And more comples example:
--
--
-- >>> let name = Just "name"
--
-- >>> let size = Just 10
--
-- >>> let active = Nothing :: Maybe Bool
--
-- >>> let condlist = catMaybes [ fmap (\a -> [sqlExp|name = #{a}|]) name, fmap (\a -> [sqlExp|size = #{a}|]) size, fmap (\a -> [sqlExp|active = #{a}|]) active]
--
-- >>> let cond = if L.null condlist then mempty else [sqlExp| WHERE ^{mconcat $ L.intersperse " AND " $ condlist} |]
--
-- >>> runSqlBuilder c [sqlExp|SELECT * FROM tbl ^{cond} -- line comment|]
-- "SELECT * FROM tbl WHERE name = 'name' AND size = 10 "
--
sqlExp :: QuasiQuoter
-- | Embed sql template and perform interpolation
--
-- -- let name = "name" -- foo = "bar" -- query = $(sqlExpEmbed "sqlfoobar.sql") -- using foo and bar inside --sqlExpEmbed :: String -> Q Exp -- | Just like sqlExpEmbed but uses pattern instead of file name. -- So, code -- --
-- let query = $(sqlExpFile "foo/bar") ---- -- is just the same as -- --
-- let query = $(sqlExpEmbed "sqlfoobar.sql") ---- -- This function inspired by Yesod's widgetFile sqlExpFile :: String -> Q Exp instance Default EntityOptions module Database.PostgreSQL.Query.Internal -- | Build entity fields -- --
-- >>> data Foo = Foo { fName :: Text, fSize :: Int }
--
-- >>> instance 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\""
--
--
--
-- >>> runSqlBuilder 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\""
--
--
--
-- >>> runSqlBuilder con $ entityFields ("f.id":) ("f"<>) (Proxy :: Proxy Foo)
-- "\"f\".\"id\", \"f\".\"name\", \"f\".\"size\""
--
entityFields :: Entity a => ([FN] -> [FN]) -> (FN -> FN) -> Proxy a -> SqlBuilder
-- | Same as entityFields but prefixes list of names with id
-- field. This is shorthand function for often usage.
--
--
-- >>> data Foo = Foo { fName :: Text, fSize :: Int }
--
-- >>> instance 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\""
--
entityFieldsId :: Entity a => (FN -> FN) -> Proxy a -> SqlBuilder
-- | Generate SELECT query string for entity
--
--
-- >>> data Foo = Foo { fName :: Text, fSize :: Int }
--
-- >>> instance Entity Foo where {newtype EntityId Foo = FooId Int ; fieldNames _ = ["name", "size"] ; tableName _ = "foo"}
--
-- >>> runSqlBuilder con $ selectEntity (entityFieldsId id) (Proxy :: Proxy Foo)
-- "SELECT \"id\", \"name\", \"size\" FROM \"foo\""
--
--
--
-- >>> runSqlBuilder con $ selectEntity (entityFieldsId ("f"<>)) (Proxy :: Proxy Foo)
-- "SELECT \"f\".\"id\", \"f\".\"name\", \"f\".\"size\" FROM \"foo\""
--
--
-- -- >>> runSqlBuilder con $ selectEntity (entityFields id id) (Proxy :: Proxy Foo) -- "SELECT \"name\", \"size\" FROM \"foo\"" --selectEntity :: Entity a => (Proxy a -> SqlBuilder) -> Proxy a -> SqlBuilder -- | Generates SELECT FROM WHERE query with most used conditions -- --
-- >>> data Foo = Foo { fName :: Text, fSize :: Int }
--
-- >>> instance Entity Foo where {newtype EntityId Foo = FooId Int ; fieldNames _ = ["name", "size"] ; tableName _ = "foo"}
--
-- >>> runSqlBuilder con $ selectEntitiesBy id (Proxy :: Proxy Foo) $ MR []
-- "SELECT \"name\", \"size\" FROM \"foo\""
--
--
--
-- >>> runSqlBuilder con $ selectEntitiesBy id (Proxy :: Proxy Foo) $ MR [("name", mkValue "fooname")]
-- "SELECT \"name\", \"size\" FROM \"foo\" WHERE \"name\" = 'fooname' "
--
--
--
-- >>> runSqlBuilder con $ selectEntitiesBy id (Proxy :: Proxy Foo) $ MR [("name", mkValue "fooname"), ("size", mkValue 10)]
-- "SELECT \"name\", \"size\" FROM \"foo\" WHERE \"name\" = 'fooname' AND \"size\" = 10 "
--
selectEntitiesBy :: (Entity a, ToMarkedRow b) => ([FN] -> [FN]) -> Proxy a -> b -> SqlBuilder
-- | Generates INSERT INTO query for any instance of Entity
-- and ToRow
--
--
-- >>> data Foo = Foo { fName :: Text, fSize :: Int }
--
-- >>> instance Entity Foo where {newtype EntityId Foo = FooId Int ; fieldNames _ = ["name", "size"] ; tableName _ = "foo"}
--
-- >>> instance ToRow Foo where { toRow Foo{..} = [toField fName, toField fSize] }
--
-- >>> runSqlBuilder con $ insertEntity $ Foo "Enterprise" 910
-- "INSERT INTO \"foo\" (\"name\", \"size\") VALUES ('Enterprise', 910)"
--
insertEntity :: (Entity a, ToRow a) => a -> SqlBuilder
-- | Same as insertEntity but generates query to insert many queries
-- at same time
--
--
-- >>> data Foo = Foo { fName :: Text, fSize :: Int }
--
-- >>> instance Entity Foo where {newtype EntityId Foo = FooId Int ; fieldNames _ = ["name", "size"] ; tableName _ = "foo"}
--
-- >>> instance ToRow Foo where { toRow Foo{..} = [toField fName, toField fSize] }
--
-- >>> runSqlBuilder 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)"
--
insertManyEntities :: (Entity a, ToRow a) => NonEmpty a -> SqlBuilder
-- | Convert entity instance to marked row to perform inserts updates and
-- same stuff
--
--
-- >>> data Foo = Foo { fName :: Text, fSize :: Int }
--
-- >>> instance Entity Foo where {newtype EntityId Foo = FooId Int ; fieldNames _ = ["name", "size"] ; tableName _ = "foo"}
--
-- >>> instance ToRow Foo where { toRow Foo{..} = [toField fName, toField fSize] }
--
-- >>> runSqlBuilder con $ mrToBuilder ", " $ entityToMR $ Foo "Enterprise" 610
-- " \"name\" = 'Enterprise' , \"size\" = 610 "
--
entityToMR :: (Entity a, ToRow a) => a -> MarkedRow
-- | Generates comma separated list of field names
--
-- -- >>> runSqlBuilder con $ buildFields ["u" <> "name", "u" <> "phone", "e" <> "email"] -- "\"u\".\"name\", \"u\".\"phone\", \"e\".\"email\"" --buildFields :: [FN] -> SqlBuilder -- | generates UPDATE query -- --
-- >>> let name = "%vip%"
--
-- >>> runSqlBuilder con $ updateTable "ships" (MR [("size", mkValue 15)]) [sqlExp|WHERE size > 15 AND name NOT LIKE #{name}|]
-- "UPDATE \"ships\" SET \"size\" = 15 WHERE size > 15 AND name NOT LIKE '%vip%'"
--
updateTable :: (ToSqlBuilder q, ToMarkedRow flds) => Text -> flds -> q -> SqlBuilder
-- | Generate INSERT INTO query for entity
--
--
-- >>> runSqlBuilder con $ insertInto "foo" $ MR [("name", mkValue "vovka"), ("hobby", mkValue "president")]
-- "INSERT INTO \"foo\" (\"name\", \"hobby\") VALUES ('vovka', 'president')"
--
insertInto :: ToMarkedRow b => Text -> b -> SqlBuilder
module Database.PostgreSQL.Query.Functions
-- | Execute query generated by SqlBuilder. Typical use case:
--
--
-- let userName = "Vovka Erohin" :: Text
-- pgQuery [sqlExp| SELECT id, name FROM users WHERE name = #{userName}|]
--
--
-- Or
--
-- -- let userName = "Vovka Erohin" :: Text -- pgQuery $ Qp "SELECT id, name FROM users WHERE name = ?" [userName] ---- -- Which is almost the same. In both cases proper value escaping is -- performed so you stay protected from sql injections. pgQuery :: (HasPostgres m, MonadLogger m, ToSqlBuilder q, FromRow r) => q -> m [r] -- | Execute arbitrary query and return count of affected rows pgExecute :: (HasPostgres m, MonadLogger m, ToSqlBuilder q) => q -> m Int64 -- | Executes arbitrary query and parses it as entities and their ids pgQueryEntities :: (ToSqlBuilder q, HasPostgres m, MonadLogger m, Entity a, FromRow a, FromField (EntityId a)) => q -> m [Ent a] -- | Execute all queries inside one transaction. Rollback transaction on -- exceptions pgWithTransaction :: (HasPostgres m, MonadBaseControl IO m, TransactionSafe m) => m a -> m a -- | Same as pgWithTransaction but executes queries inside savepoint pgWithSavepoint :: (HasPostgres m, MonadBaseControl IO m, TransactionSafe m) => m a -> m a -- | Wrapper for withTransactionMode: Execute an action inside a SQL -- transaction with a given transaction mode. pgWithTransactionMode :: (HasPostgres m, MonadBaseControl IO m, TransactionSafe m) => TransactionMode -> m a -> m a -- | Wrapper for withTransactionModeRetry: Like -- pgWithTransactionMode, 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. pgWithTransactionModeRetry :: (HasPostgres m, MonadBaseControl IO m, TransactionSafe m) => TransactionMode -> (SqlError -> Bool) -> m a -> m a -- | Wrapper for withTransactionSerializable: Execute an action -- inside of a Serializable 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. pgWithTransactionSerializable :: (HasPostgres m, MonadBaseControl IO m, TransactionSafe m) => m a -> m a -- | Insert new entity and return it's id pgInsertEntity :: (HasPostgres m, MonadLogger m, Entity a, ToRow a, FromField (EntityId a)) => a -> m (EntityId a) -- | Insert many entities without returning list of id like -- pgInsertManyEntitiesId does pgInsertManyEntities :: (Entity a, HasPostgres m, MonadLogger m, ToRow a) => [a] -> m Int64 -- | Same as pgInsertEntity but insert many entities at one action. -- Returns list of id's of inserted entities pgInsertManyEntitiesId :: (Entity a, HasPostgres m, MonadLogger m, ToRow a, FromField (EntityId a)) => [a] -> m [EntityId a] -- | 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 ...
--
pgSelectEntities :: (Functor m, HasPostgres m, MonadLogger m, Entity a, FromRow a, ToSqlBuilder q, FromField (EntityId a)) => (FN -> FN) -> q -> m [Ent a]
-- | Same as pgSelectEntities but do not select id
pgSelectJustEntities :: (Functor m, HasPostgres m, MonadLogger m, Entity a, FromRow a, ToSqlBuilder q) => (FN -> FN) -> q -> m [a]
-- | Select entities by condition formed from MarkedRow. Usefull
-- function when you know
pgSelectEntitiesBy :: (Functor m, HasPostgres m, MonadLogger m, Entity a, ToMarkedRow b, FromRow a, FromField (EntityId a)) => b -> m [Ent a]
-- | Select entity by id
--
-- -- getUser :: EntityId User -> Handler User -- getUser uid = do -- pgGetEntity uid -- >>= maybe notFound return --pgGetEntity :: (ToField (EntityId a), Entity a, HasPostgres m, MonadLogger m, FromRow a, Functor m) => EntityId a -> m (Maybe a) -- | 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
--
--
-- pgQuery [sqlExp|SELECT id, name, phone ... FROM users WHERE name = {True}|]
--
pgGetEntityBy :: (Entity a, HasPostgres m, MonadLogger m, ToMarkedRow b, FromField (EntityId a), FromRow a, Functor m) => b -> m (Maybe (Ent a))
-- | Delete entity.
--
-- -- rmUser :: EntityId User -> Handler () -- rmUser uid = do -- pgDeleteEntity uid ---- -- Return True if row was actually deleted. pgDeleteEntity :: (Entity a, HasPostgres m, MonadLogger m, ToField (EntityId a), Functor m) => EntityId a -> m Bool -- | Update entity using ToMarkedRow instanced value. Requires -- Proxy while EntityId 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 True if record was actually updated and False if
-- there was not row with such id (or was more than 1, in fact)
pgUpdateEntity :: (ToMarkedRow b, Entity a, HasPostgres m, MonadLogger m, ToField (EntityId a), Functor m, Typeable a, Typeable b) => EntityId a -> b -> m Bool
-- | Select count of entities with given query
--
--
-- activeUsers :: Handler Integer
-- activeUsers = do
-- pgSelectCount (Proxy :: Proxy User)
-- [sqlExp|WHERE active = #{True}|]
--
pgSelectCount :: (Entity a, HasPostgres m, MonadLogger m, ToSqlBuilder q) => Proxy a -> q -> m Integer
-- | Perform repsert of the same row, first trying "update where" then
-- "insert" with concatenated fields. Which means that if you run
--
--
-- pgRepsertRow "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 ---- -- And if no one row is affected (which is returned by pgExecute), -- then -- --
-- INSERT INTO "emails" ("user_id", "email") VALUES (1234, 'foo@bar.com')
--
--
-- will be performed
pgRepsertRow :: (HasPostgres m, MonadLogger m, ToMarkedRow wrow, ToMarkedRow urow) => Text -> wrow -> urow -> m ()
module Database.PostgreSQL.Query
data Connection :: *
-- | Connect with the given username to the given database. Will throw an
-- exception if it cannot connect.
connect :: ConnectInfo -> IO Connection
-- | Default information for setting up a connection.
--
-- Defaults are as follows:
--
--
-- connect defaultConnectInfo { connectHost = "db.example.com" }
--
defaultConnectInfo :: ConnectInfo
-- | Attempt to make a connection based on a libpq connection string. See
-- http://www.postgresql.org/docs/9.3/static/libpq-connect.html#LIBPQ-CONNSTRING
-- for more information. Here is an example with some of the most
-- commonly used parameters:
--
-- -- host='db.somedomain.com' port=5432 ... ---- -- This attempts to connect to db.somedomain.com:5432. Omitting -- the port will normally default to 5432. -- -- On systems that provide unix domain sockets, omitting the host -- parameter will cause libpq to attempt to connect via unix domain -- sockets. The default filesystem path to the socket is constructed from -- the port number and the DEFAULT_PGSOCKET_DIR constant defined -- in the pg_config_manual.h header file. Connecting via unix -- sockets tends to use the peer authentication method, which is -- very secure and does not require a password. -- -- On Windows and other systems without unix domain sockets, omitting the -- host will default to localhost. -- --
-- ... dbname='postgres' user='postgres' password='secret \' \\ pw' ---- -- This attempts to connect to a database named postgres with -- user postgres and password secret ' \ pw. Backslash -- characters will have to be double-quoted in literal Haskell strings, -- of course. Omitting dbname and user will both -- default to the system username that the client process is running as. -- -- Omitting password will default to an appropriate password -- found in the pgpass file, or no password at all if a matching -- line is not found. See -- http://www.postgresql.org/docs/9.3/static/libpq-pgpass.html for -- more information regarding this file. -- -- As all parameters are optional and the defaults are sensible, the -- empty connection string can be useful for development and exploratory -- use, assuming your system is set up appropriately. -- -- On Unix, such a setup would typically consist of a local postgresql -- server listening on port 5432, as well as a system user, database -- user, and database sharing a common name, with permissions granted to -- the user on the database. -- -- On Windows, in addition you will either need pg_hba.conf to -- specify the use of the trust authentication method for the -- connection, which may not be appropriate for multiuser or production -- machines, or you will need to use a pgpass file with the -- password or md5 authentication methods. -- -- See -- http://www.postgresql.org/docs/9.3/static/client-authentication.html -- for more information regarding the authentication process. -- -- SSL/TLS will typically "just work" if your postgresql server supports -- or requires it. However, note that libpq is trivially vulnerable to a -- MITM attack without setting additional SSL parameters in the -- connection string. In particular, sslmode needs to set be -- require, verify-ca, or verify-full to -- perform certificate validation. When sslmode is -- require, then you will also need to have a -- sslrootcert file, otherwise no validation of the server's -- identity will be performed. Client authentication via certificates is -- also possible via the sslcert and sslkey parameters. connectPostgreSQL :: ByteString -> IO Connection data ConnectInfo :: * ConnectInfo :: String -> Word16 -> String -> String -> String -> ConnectInfo connectHost :: ConnectInfo -> String connectPort :: ConnectInfo -> Word16 connectUser :: ConnectInfo -> String connectPassword :: ConnectInfo -> String connectDatabase :: ConnectInfo -> String -- | A type that may be used as a single parameter to a SQL query. class ToField a toField :: ToField a => a -> Action -- | A collection type that can be turned into a list of rendering -- Actions. -- -- Instances should use the toField method of the ToField -- class to perform conversion of each element of the collection. class ToRow a toRow :: ToRow a => a -> [Action] -- | A type that may be converted from a SQL type. class FromField a fromField :: FromField a => FieldParser a -- | A collection type that can be converted from a sequence of fields. -- Instances are provided for tuples up to 10 elements and lists of any -- length. -- -- Note that instances can be defined outside of postgresql-simple, which -- is often useful. For example, here's an instance for a user-defined -- pair: -- -- @data User = User { name :: String, fileQuota :: Int } -- -- instance FromRow User where fromRow = User <$> -- field <*> field @ -- -- The number of calls to field must match the number of fields -- returned in a single row of the query result. Otherwise, a -- ConversionFailed exception will be thrown. -- -- Note that field evaluates it's result to WHNF, so the caveats -- listed in mysql-simple and very early versions of postgresql-simple no -- longer apply. Instead, look at the caveats associated with -- user-defined implementations of fromField. class FromRow a fromRow :: FromRow a => RowParser a -- | A query string. This type is intended to make it difficult to -- construct a SQL query by concatenating string fragments, as that is an -- extremely common way to accidentally introduce SQL injection -- vulnerabilities into an application. -- -- This type is an instance of IsString, so the easiest way to -- construct a query is to enable the OverloadedStrings language -- extension and then simply write the query in double quotes. -- --
-- {-# LANGUAGE OverloadedStrings #-}
--
-- import Database.PostgreSQL.Simple
--
-- q :: Query
-- q = "select ?"
--
--
-- The underlying type is a ByteString, and literal Haskell
-- strings that contain Unicode characters will be correctly transformed
-- to UTF-8.
newtype Query :: *
Query :: ByteString -> Query
fromQuery :: Query -> ByteString
-- | A single-value "collection".
--
-- This is useful if you need to supply a single parameter to a SQL
-- query, or extract a single column from a SQL result.
--
-- Parameter example:
--
-- -- query c "select x from scores where x > ?" (Only (42::Int)) ---- -- Result example: -- --
-- xs <- query_ c "select id from users"
-- forM_ xs $ \(Only id) -> {- ... -}
--
newtype Only a :: * -> *
Only :: a -> Only a
fromOnly :: Only a -> a
-- | Wrap a list of values for use in an IN clause. Replaces a
-- single "?" character with a parenthesized list of rendered
-- values.
--
-- Example:
--
-- -- query c "select * from whatever where id in ?" (Only (In [3,4,5])) --newtype In a :: * -> * In :: a -> In a newtype Oid :: * Oid :: CUInt -> Oid -- | Represents a VALUES table literal, usable as an alternative -- to executeMany and returning. The main advantage is -- that you can parametrize more than just a single VALUES -- expression. For example, here's a query to insert a thing into one -- table and some attributes of that thing into another, returning the -- new id generated by the database: -- --
-- query c [sql|
-- WITH new_thing AS (
-- INSERT INTO thing (name) VALUES (?) RETURNING id
-- ), new_attributes AS (
-- INSERT INTO thing_attributes
-- SELECT new_thing.id, attrs.*
-- FROM new_thing JOIN ? attrs
-- ) SELECT * FROM new_thing
-- |] ("foo", Values [ "int4", "text" ]
-- [ ( 1 , "hello" )
-- , ( 2 , "world" ) ])
--
--
-- (Note this example uses writable common table expressions, which were
-- added in PostgreSQL 9.1)
--
-- The second parameter gets expanded into the following SQL syntax:
--
-- -- (VALUES (1::"int4",'hello'::"text"),(2,'world')) ---- -- When the list of attributes is empty, the second parameter expands to: -- --
-- (VALUES (null::"int4",null::"text") LIMIT 0) ---- -- By contrast, executeMany and returning don't issue -- the query in the empty case, and simply return 0 and -- [] respectively. This behavior is usually correct given their -- intended use cases, but would certainly be wrong in the example above. -- -- The first argument is a list of postgresql type names. Because this is -- turned into a properly quoted identifier, the type name is case -- sensitive and must be as it appears in the pg_type table. -- Thus, you must write timestamptz instead of timestamp -- with time zone, int4 instead of integer, -- _int8 instead of bigint[], etcetera. -- -- You may omit the type names, however, if you do so the list of values -- must be non-empty, and postgresql must be able to infer the types of -- the columns from the surrounding context. If the first condition is -- not met, postgresql-simple will throw an exception without issuing the -- query. In the second case, the postgres server will return an error -- which will be turned into a SqlError exception. -- -- See http://www.postgresql.org/docs/9.3/static/sql-values.html -- for more information. data Values a :: * -> * Values :: [QualifiedIdentifier] -> [a] -> Values a -- | A composite type to parse your custom data structures without having -- to define dummy newtype wrappers every time. -- --
-- instance FromRow MyData where ... ---- --
-- instance FromRow MyData2 where ... ---- -- then I can do the following for free: -- --
-- res <- query' c "..."
-- forM res $ \(MyData{..} :. MyData2{..}) -> do
-- ....
--
data (:.) h t :: * -> * -> *
(:.) :: h -> t -> (:.) h t
-- | Wrap a list for use as a PostgreSQL array.
newtype PGArray a :: * -> *
PGArray :: [a] -> PGArray a
fromPGArray :: PGArray a -> [a]
newtype HStoreList :: *
HStoreList :: [(Text, Text)] -> HStoreList
fromHStoreList :: HStoreList -> [(Text, Text)]
newtype HStoreMap :: *
HStoreMap :: Map Text Text -> HStoreMap
fromHStoreMap :: HStoreMap -> Map Text Text
class ToHStore a
toHStore :: ToHStore a => a -> HStoreBuilder
-- | Represents valid hstore syntax.
data HStoreBuilder :: *
hstore :: (ToHStoreText a, ToHStoreText b) => a -> b -> HStoreBuilder
parseHStoreList :: ByteString -> Either String HStoreList
class ToHStoreText a
toHStoreText :: ToHStoreText a => a -> HStoreText
-- | Represents escape text, ready to be the key or value to a hstore value
data HStoreText :: *
-- | Deprecated: Use sqlExp instead
sqlQQ :: QuasiQuoter