Module

Data.Postgres.Query.Builder

Package
purescript-postgresql
Repository
cakekindel/purescript-postgresql

#QueryBuilderT Source

type QueryBuilderT :: (Type -> Type) -> Type -> Typetype QueryBuilderT m a = StateT Query m a

Monad for building parameterized queries without managing positional parameters directly

For example, given the table CREATE TABLE foo (id INT NOT NULL PRIMARY KEY, bar TEXT NOT NULL)

updateFoo :: Int -> String -> Effect Query
updateFoo id newBar =
  build do
    idP <- param id
    newBarP <- param newBar
    pure $
      [ "update foo"
      , "set bar = " <> newBarP
      , "where id = " <> idP
      ]

updateFoo 1 "test" will yield:

{ text: "update foo\nset bar = $2\nwhere id = $1"
, values: ["test", 1]
}

#QueryBuilder Source

#lastParamString Source

lastParamString :: forall m. Monad m => QueryBuilderT m String

Yields a SQL string referencing the last parameter in the parameter list

Examples:

  • if no parameters have been appended this will yield "$0" (invalid)
  • if 1 parameter has been appended this will yield "$1"
  • if 5 parameters have been appended this will yield "$5"

#appendParam Source

appendParam :: forall m a. MonadEffect m => Rep a => a -> QueryBuilderT m Unit

Append a serializable SQL value to the parameter list

#putText Source

putText :: forall m. Monad m => String -> QueryBuilderT m Unit

Replace the builder's query string with a new value

#param Source

param :: forall m a. MonadEffect m => Rep a => a -> QueryBuilderT m String

Adds a parameter to the query

This accepts any value Representable in SQL, and yields the SQL string for the new parameter.

do
  p1 <- param 1     -- "$1"
  p2 <- param "foo" -- "$2"
  p3 <- param true  -- "$3"
  pure unit

#build Source

build :: QueryBuilder String -> Effect Query

Accepts a QueryBuilder monad that yields the built query string and yields the finished Query.

build $ pure "select 1"
-- Query {text: "select 1", values: [], name: Nothing}

 

build do
  foo <- param "foo"
  pure $ "select " <> foo
-- Query {text: "select $1", values: ["foo"], name: Nothing}

#build' Source

build' :: forall m a. MonadEffect m => QueryBuilderT m a -> m (a /\ Query)

Executes a QueryBuilderT