#=.      !"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|}~      !"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|}~      !"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWX Y Z [ \ ] ^ _ ` a b c d e f g h i j k l m n o p q r s t u v w x y z { | } ~                                                                                          ! " # $ % & ' ( ) * + , - Rendering helper functions(c) Eitan Chatav, 2017eitan@morphism.tech experimentalNone,<DFQV0 A class for rendering SQLParenthesize a ..Concatenate two .s with a space between.Comma separate a list of .s.Add double quotes around a ..6Comma separate the renderings of a heterogeneous list.Comma separate the // renderings of a heterogeneous list, dropping 0s.Render a promoted 1.  Print SQL.   -Embedding of PostgreSQL type and alias system(c) Eitan Chatav, 2017eitan@morphism.tech experimentalNone&'+,-068;<=>?AFQSTVh£j!eInspect the code of an algebraic datatype and ensure it's a product, otherwise generate a type error"Calculate the types of fields.# :kind! FieldTypeOf (Maybe Int16)#FieldTypeOf (Maybe Int16) :: PGType = 'PGint2$Calculate the names of fields.%Calculate the name of a field.&#Calculate the fields of a datatype.',Calculate the names of nullary constructors.(PCalculates the name of a nullary constructor, otherwise generates a type error.)&Calculates constructors of a datatype.*Ndata Row = Row { a :: Maybe Int16, b :: Maybe LocalTime } deriving GHC.Genericinstance Generic Rowinstance HasDatatypeInfo Row:kind! FieldTypesFrom RowFieldTypesFrom Row :: [PGType]= '['PGint2, 'PGtimestamp]+Ndata Row = Row { a :: Maybe Int16, b :: Maybe LocalTime } deriving GHC.Genericinstance Generic Rowinstance HasDatatypeInfo Row:kind! FieldNamesFrom Row&FieldNamesFrom Row :: [Type.FieldName] = '["a", "b"],The ,i type family embeds Haskell record types as Postgres composite types, as long as the record fields are /As of Haskell types that can be embedded as basic types with the / type family.Ndata Row = Row { a :: Maybe Int16, b :: Maybe LocalTime } deriving GHC.Genericinstance Generic Rowinstance HasDatatypeInfo Row:kind! CompositeFrom RowCompositeFrom Row :: PGType7= 'PGcomposite '['("a", 'PGint2), '("b", 'PGtimestamp)]-The -A type family calculates the constructors of a Haskell enum type.:data Schwarma = Beef | Lamb | Chicken deriving GHC.Genericinstance Generic Schwarma!instance HasDatatypeInfo Schwarma:kind! LabelsFrom Schwarma-LabelsFrom Schwarma :: [Type.ConstructorName]= '["Beef", "Lamb", "Chicken"].The ._ type family embeds Haskell enum types, ADTs with nullary constructors, as Postgres enum types:data Schwarma = Beef | Lamb | Chicken deriving GHC.Genericinstance Generic Schwarma!instance HasDatatypeInfo Schwarma:kind! EnumFrom SchwarmaEnumFrom Schwarma :: PGType&= 'PGenum '["Beef", "Lamb", "Chicken"]/The /G type family embeds a subset of Haskell types as Postgres basic types.:kind! PG LocalTimePG LocalTime :: PGType= 'PGtimestamp0A 0 unit type with an 2 instance22 looks very much like the ' class. Whereas the overloaded label, ! is used for column references, 3s are used for enum terms. A 37 is called with type application like `label @"beef"`.4Used in  .5FThe schema of a database consists of a list of aliased, user-defined 6s.6A 6" is a user-defined type, either a 7, 8 or 9.: Drop all ns that involve a column; Check if a n involves a column<< is used to construct a  of a composite type.==4 is used in the binary instances of composite types.ARename alias0 alias1 xs replaces the alias alias0 by alias1 in xs and is used in  and .BAlter alias x xs& replaces the type associated with an alias in xs with the type x and is used in  and .C Drop alias xs" removes the type associated with alias in xs and is used in  statements and in  ALTER TABLE  statements.DCreate alias x xs adds  alias ::: x to the end of xs and is used in  statements and in  ALTER TABLE .EE is simply promoted 2 and is used in JOINs in s.FF# is an idempotent that nullifies a gE used to nullify the left or right hand side of an outer join in a .GG# is an idempotent that nullifies a s.HH# is an idempotent that nullifies a t.II is a constraint that proves a s has some NOT NULL.JJ is a constraint that proves a s has no NULLs.K&Equality constraint on the underlying  of two columns.LL! is a constraint that proves two s%s have the same length and the same ts.MM forgets about NULL and any column constraints.NN is a constraint on  whose s have  and  functions.OO is a constraint on  whose s have 3 and 4 constraints.PP is a constraint on  whose  s have a 5 constraint.QIn x xs" is a constraint that proves that x is in xs.RElem is a promoted .S Analagous to , the constraint S defines T0 for a column alias qualified by a table alias.UU extends V to take lists of aliases and fields and infer a list of  subfields.VHas alias fields field# is a constraint that proves that fields has a field of alias ::: field , inferring field from alias and fields.WHasUnique alias fields field# is a constraint that proves that fields is a singleton of alias ::: field.XThe X+ class provides a type family for zipping 6W lists together with arbitrary lists of the same size, with an associated type family Y, together with a method Z$ for zipping heterogeneous lists of ^Tes together with a heterogeneous list of expressions into a heterogeneous list of \ expressions.[[ retains the AliasesOf in a row.\The ]) operator is used to name an expression. ] is like a demoted version of x.8Just "hello" `As` #hi :: Aliased Maybe ("hi" ::: String)As (Just "hello") Alias^^*es are proxies for a type level string or 6 and have an  instance so that with -XOverloadedLabels:set -XOverloadedLabels#foobar :: Alias "foobar"Alias`A `f constraint indicates that a table qualified column is a member of the auxiliary namespace created by GROUP BY. clauses and thus, may be called in an output  without aggregating.aa( is an auxiliary namespace, created by GROUP BY clauses (%), and used for typesafe aggregationbno aggregation permittedc8aggregation required for any column which is not groupeddConvert a table to a relation.ee removes table constraints.ff removes column constraints.gg is a row of is, thought of as a product.hA monokinded empty i.ii is a row of z:{0type family PersonRelation :: RelationType where PersonRelation =) '[ "name" ::: 'NotNull 'PGtext) , "age" ::: 'NotNull 'PGint4) , "dateOfBirth" ::: 'Null 'PGdate ]:}jjN encodes a row of constraints on a table as well as the types of its columns.:{)type family UsersTable :: TableType where UsersTable =/ '[ "pk_users" ::: 'PrimaryKey '["id"] ] :=>1 '[ "id" ::: 'Def :=> 'NotNull 'PGint41 , "name" ::: 'NoDef :=> 'NotNull 'PGtext ]:}kA r+ must reference columns that either are a q or form a p constraint.lA monokinded empty m.mA m is a row of ns.nnD encodes various forms of data constraints of columns in a table. ns give you as much control over the data in your tables as you wish. If a user attempts to store data in a column that would violate a constraint, an error is raised. This applies even if the value came from the default value definition.ss is a row of ts.:{-type family UsersColumns :: ColumnsType where UsersColumns =- '[ "name" ::: 'NoDef :=> 'NotNull 'PGtext- , "id" ::: 'Def :=> 'NotNull 'PGint4 ]:}tt encodes the allowance of DEFAULT and NULL and the base  for a column. :set -XTypeFamilies -XTypeInTypeimport GHC.TypeLitsMtype family IdColumn :: ColumnType where IdColumn = 'Def :=> 'NotNull 'PGint4Rtype family EmailColumn :: ColumnType where EmailColumn = 'NoDef :=> 'Null 'PGtextuu encodes the availability of DEFAULTM for inserts and updates. A column can be assigned a default value. A data  | command can also request explicitly that a column be set to its default value, without having to know what that value is.vDEFAULT% is available for inserts and updateswDEFAULT' is unavailable for inserts and updatesxThe alias operator x is like a promoted version of ]4, a type level pair between an alias and some type.yThe constraint operator, yS is a type level pair between a "constraint" and some type, for use in pairing a u with a z to produce a t or a m and a s to produce a j.zz: encodes the potential presence or definite absence of a NULLB allowing operations which are sensitive to such to be well typed.:kind 'Null 'PGint4'Null 'PGint4 :: NullityType:kind 'NotNull ('PGvarchar 50)''NotNull ('PGvarchar 50) :: NullityType{NULL may be present|NULL is absent}The object identifier of a .:set -XTypeApplications oid @'PGbool16. is the promoted datakind of PostgreSQL types.import Squeal.PostgreSQL.Schema :kind 'PGbool'PGbool :: PGTypelogical Boolean (true/false)signed two-byte integersigned four-byte integersigned eight-byte integer arbitrary precision numeric type0single precision floating-point number (4 bytes)0double precision floating-point number (8 bytes)fixed-length character string variable-length character string variable-length character stringbinary data ("byte array")date and time (no time zone)"date and time, including time zone calendar date (year, month, day)time of day (no time zone) time of day, including time zone time spanuniversally unique identifierIPv4 or IPv6 host addresstextual JSON databinary JSON data, decomposedvariable length arrayfixed length array0an escape hatch for unsupported PostgreSQL typesrenderAlias #jimbob "\"jimbob\""import Generics.SOP (NP(..))(renderAliases (#jimbob :* #kandi :* Nil)["\"jimbob\"","\"kandi\""]=let renderMaybe = fromString . maybe "Nothing" (const "Just")8renderAliasedAs renderMaybe (Just (3::Int) `As` #an_int)"Just AS \"an_int\""Renders a labelRenders a list of labels!"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmnpoqrstuvwxyz{|}~}~z{|tsihgj67895yuvwnopqrmlkx^_\][XYZVWUST2301abc`E4DCBARQPNOMLKJIHGFfed;:/.-,+*)('&%$#"!=>?@<01236789=>?@STXYZ\]^_abcnopqruvwz{|}~T9 x6y7Squeal expressions(c) Eitan Chatav, 2017eitan@morphism.tech experimentalNone,-6;<=>?ADFKSTV]hsWh is a demoted version of a s are used in s and  createTable commands.A constraint for 3s that you can take averages of and the resulting .A  is a boolean valued '. While SQL allows conditions to have NULL%, Squeal instead chooses to disallow NULL%, forcing one to handle the case of NULL explicitly to produce a .A X constraint is used to indicate a value that is supplied externally to a SQL statement. !, " and #V support specifying data values separately from the SQL command string, in which case 3s are used to refer to the out-of-line data values. takes a 1 using type application and a .Ylet expr = parameter @1 int4 :: Expression sch rels grp '[ 'Null 'PGint4] ('Null 'PGint4) printSQL expr ($1 :: int4)Gs are used in a variety of contexts, such as in the target list of the $" command, as new column values in % or &, or in search s in a number of commands.The expression syntax allows the calculation of values from primitive expression using arithmetic, logical, and other operations. takes a 17 using type application and for basic types, infers a .Plet expr = param @1 :: Expression sch rels grp '[ 'Null 'PGint4] ('Null 'PGint4) printSQL expr ($1 :: int4) analagous to 0printSQL null_NULL analagous to 7printSQL $ notNull trueTRUE+return the leftmost value which is not NULL/printSQL $ coalesce [null_, notNull true] falseCOALESCE(NULL, TRUE, FALSE) analagous to '( using COALESCEprintSQL $ fromNull true null_COALESCE(NULL, TRUE)printSQL $ null_ & isNull NULL IS NULLprintSQL $ null_ & isNotNullNULL IS NOT NULL analagous to 8 using IS NULL$printSQL $ matchNull true not_ null_4CASE WHEN NULL IS NULL THEN TRUE ELSE (NOT NULL) ENDright inverse to ", if its arguments are equal then  gives NULL.#:set -XTypeApplications -XDataKindselet expr = nullIf false (param @1) :: Expression schema rels grp '[ 'NotNull 'PGbool] ('Null 'PGbool) printSQL exprNULL IF (FALSE, ($1 :: bool))5printSQL $ array [null_, notNull false, notNull true]ARRAY[NULL, FALSE, TRUE]A row constructor is an expression that builds a row value (also called a composite value) using values for its member fields.Mtype Complex = PGcomposite '["real" ::: 'PGfloat8, "imaginary" ::: 'PGfloat8]nlet i = row (0 `As` #real :* 1 `As` #imaginary :* Nil) :: Expression '[] '[] 'Ungrouped '[] ('NotNull Complex) printSQL i ROW(0, 1)let expr = greatest currentTimestamp [param @1] :: Expression sch rels grp '[ 'NotNull 'PGtimestamptz] ('NotNull 'PGtimestamptz) printSQL expr=GREATEST(CURRENT_TIMESTAMP, ($1 :: timestamp with time zone)))printSQL $ least currentTimestamp [null_]LEAST(CURRENT_TIMESTAMP, NULL))printSQL $ unsafeBinaryOp "OR" true false(TRUE OR FALSE)#printSQL $ unsafeUnaryOp "NOT" true (NOT TRUE)"printSQL $ unsafeFunction "f" truef(TRUE):{letO expression :: Expression schema relations grouping params (nullity 'PGfloat4) expression = atan2_ pi 2in printSQL expression:}atan2(pi(), 2)printSQL $ true & cast int4(TRUE :: int4)&integer division, truncates the result:{letM expression :: Expression schema relations grouping params (nullity 'PGint2) expression = 5 `quot_` 2in printSQL expression:}(5 / 2)remainder upon integer division:{letM expression :: Expression schema relations grouping params (nullity 'PGint2) expression = 5 `rem_` 2in printSQL expression:}(5 % 2):{letO expression :: Expression schema relations grouping params (nullity 'PGfloat4) expression = trunc piin printSQL expression:} trunc(pi()):{letO expression :: Expression schema relations grouping params (nullity 'PGfloat4) expression = round_ piin printSQL expression:} round(pi()):{letO expression :: Expression schema relations grouping params (nullity 'PGfloat4) expression = ceiling_ piin printSQL expression:} ceiling(pi()) printSQL trueTRUEprintSQL falseFALSEprintSQL $ not_ true (NOT TRUE)printSQL $ true .&& false(TRUE AND FALSE)printSQL $ true .|| false(TRUE OR FALSE):{letM expression :: Expression schema relations grouping params (nullity 'PGint2)9 expression = caseWhenThenElse [(true, 1), (false, 2)] 3in printSQL expression:}2CASE WHEN TRUE THEN 1 WHEN FALSE THEN 2 ELSE 3 END:{letM expression :: Expression schema relations grouping params (nullity 'PGint2)" expression = ifThenElse true 1 0in printSQL expression:} CASE WHEN TRUE THEN 1 ELSE 0 ENDComparison operations like , , , ,  and  will produce NULLs if one of their arguments is NULL.!printSQL $ notNull true .== null_ (TRUE = NULL)!printSQL $ notNull true ./= null_(TRUE <> NULL)!printSQL $ notNull true .>= null_(TRUE >= NULL) printSQL $ notNull true .< null_ (TRUE < NULL)!printSQL $ notNull true .<= null_(TRUE <= NULL) printSQL $ notNull true .> null_ (TRUE > NULL)printSQL currentDate CURRENT_DATEprintSQL currentTime CURRENT_TIMEprintSQL currentTimestampCURRENT_TIMESTAMPprintSQL localTime LOCALTIMEprintSQL localTimestampLOCALTIMESTAMPprintSQL $ lower "ARRRGGG"lower(E'ARRRGGG')printSQL $ upper "eeee"upper(E'eeee')printSQL $ charLength "four"char_length(E'four')The  expression returns true if the string matches the supplied pattern. If patterns does not contain percent signs or underscores, then the pattern only represents the string itself; in that case  acts like the equals operator. An underscore (_) in pattern stands for (matches) any single character; a percent sign (%) matches any sequence of zero or more characters.printSQL $ "abc" `like` "a%"(E'abc' LIKE E'a%')*escape hatch to define aggregate functions ?escape hatch to define aggregate functions over distinct values :{lets expression :: Expression schema '[tab ::: '["col" ::: 'Null 'PGnumeric]] ('Grouped bys) params ('Null 'PGnumeric) expression = sum_ #colin printSQL expression:} sum("col") :{letw expression :: Expression schema '[tab ::: '["col" ::: nullity 'PGnumeric]] ('Grouped bys) params (nullity 'PGnumeric) expression = sumDistinct #colin printSQL expression:}sum(DISTINCT "col") :{letp expression :: Expression schema '[tab ::: '["col" ::: nullity 'PGint4]] (Grouped bys) params (nullity 'PGint4) expression = bitAnd #colin printSQL expression:}bit_and("col") :{letp expression :: Expression schema '[tab ::: '["col" ::: nullity 'PGint4]] (Grouped bys) params (nullity 'PGint4) expression = bitOr #colin printSQL expression:} bit_or("col"):{letp expression :: Expression schema '[tab ::: '["col" ::: nullity 'PGint4]] (Grouped bys) params (nullity 'PGint4)" expression = bitAndDistinct #colin printSQL expression:}bit_and(DISTINCT "col"):{letp expression :: Expression schema '[tab ::: '["col" ::: nullity 'PGint4]] (Grouped bys) params (nullity 'PGint4)! expression = bitOrDistinct #colin printSQL expression:}bit_or(DISTINCT "col"):{letp expression :: Expression schema '[tab ::: '["col" ::: nullity 'PGbool]] (Grouped bys) params (nullity 'PGbool) expression = boolAnd #colin printSQL expression:}bool_and("col"):{letp expression :: Expression schema '[tab ::: '["col" ::: nullity 'PGbool]] (Grouped bys) params (nullity 'PGbool) expression = boolOr #colin printSQL expression:}bool_or("col"):{letp expression :: Expression schema '[tab ::: '["col" ::: nullity 'PGbool]] (Grouped bys) params (nullity 'PGbool)# expression = boolAndDistinct #colin printSQL expression:}bool_and(DISTINCT "col"):{letp expression :: Expression schema '[tab ::: '["col" ::: nullity 'PGbool]] (Grouped bys) params (nullity 'PGbool)" expression = boolOrDistinct #colin printSQL expression:}bool_or(DISTINCT "col")4A special aggregation that does not require an inputprintSQL countStarcount(*):{letl expression :: Expression schema '[tab ::: '["col" ::: nullity ty]] (Grouped bys) params ('NotNull 'PGint8) expression = count #colin printSQL expression:} count("col"):{letl expression :: Expression schema '[tab ::: '["col" ::: nullity ty]] (Grouped bys) params ('NotNull 'PGint8)! expression = countDistinct #colin printSQL expression:}count(DISTINCT "col") synonym for :{letp expression :: Expression schema '[tab ::: '["col" ::: nullity 'PGbool]] (Grouped bys) params (nullity 'PGbool) expression = every #colin printSQL expression:} every("col") synonym for :{letp expression :: Expression schema '[tab ::: '["col" ::: nullity 'PGbool]] (Grouped bys) params (nullity 'PGbool)! expression = everyDistinct #colin printSQL expression:}every(DISTINCT "col")minimum and maximum aggregationminimum and maximum aggregationminimum and maximum aggregationminimum and maximum aggregationlogical Boolean (true/false)signed two-byte integersigned two-byte integer signed four-byte integer!signed four-byte integer"signed four-byte integer#signed eight-byte integer$signed eight-byte integer% arbitrary precision numeric type&0single precision floating-point number (4 bytes)'0single precision floating-point number (4 bytes)(0double precision floating-point number (8 bytes))0double precision floating-point number (8 bytes)* variable-length character string+fixed-length character string,fixed-length character string- variable-length character string. variable-length character string/binary data ("byte array")0date and time (no time zone)1"date and time, including time zone2 calendar date (year, month, day)3time of day (no time zone)4 time of day, including time zone5 time span6universally unique identifier7IPv4 or IPv6 host address8textual JSON data9binary JSON data, decomposed:variable length array;fixed length array/renderTypeExpression (fixarray (Proxy @2) json) "json[2]"7what to averagewhat to averageparamNULLs may be presentNULL is absentwhat to convert NULL to possibly NULL possibly NULLwhat to convert NULL tofunction to perform when NULL is absentNULL is absentNULL is absentarray elements1zero or more expressions for the row field valuesneeds at least 1 argumentor moreneeds at least 1 argumentor moreoperatoroperatorfunction numerator denominatortype to cast asvalue to convert numerator denominator numerator denominatorfractional numberfractional numberfractional numberwhens and thenselsethenelselhsrhslhsrhslhsrhslhsrhslhsrhslhsrhsstring to lower casestring to upper casestring to measurestringpatternaggregate function aggregate function  what to sum  what to sum what to aggregate what to aggregatewhat to aggregatewhat to aggregatewhat to aggregatewhat to aggregatewhat to aggregatewhat to aggregate what to count what to countwhat to aggregatewhat to aggregatewhat to aggregatewhat to aggregatewhat to aggregatewhat to aggregates      !"#$%&'()*+,-./0123456789:;s      !"#$%&'()*+,-./0123456789:;444444Squeal queries(c) Eitan Chatav, 2017eitan@morphism.tech experimentalNone&',-06<FKST]O?0}}s are used by sortBy& to optionally sort the results of a . ~ or  set the sort direction of a | result column to ascending or descending. Ascending order puts smaller values first, where "smaller" is defined in terms of the ? operator. Similarly, descending order is determined with the  operator. , ,  and p options are used to determine whether nulls appear before or after non-null values in the sort ordering of a { result column.A ; is used to eliminate groups that are not of interest. An b  may only use  while a c  must use % whose conditions are combined with .A  indicates the a of a . A  indicates b while a  indicates c. NoGroups is distinguised from  Group Nil& since no aggregation can be done on NoGroups while all output s must be aggregated in  Group Nil. In general, all output s in the complement of bys must be aggregated in  Group bys.s are used in  to reference a list of columns which are then used to group together those rows in a table that have the same values in all the columns listed. By #col' will reference an unambiguous column col ; otherwise By2 (#tab ! #col)* will reference a table qualified column tab.col.A ? can be a table name, or a derived table such as a subquery, a JOIN- construct, or complex combinations of these.A 4 computes a table. The table expression contains a " that is optionally followed by a , , , ,  and s. Trivial table expressions simply refer to a table on disk, a so-called base table, but more complex expressions can be used to modify or combine base tables in various ways.VA table reference that can be a table name, or a derived table such as a subquery, a JOIN- construct, or complex combinations of these.)optional search coditions, combined with . After the processing of the ! is done, each row of the derived virtual table is checked against the search condition. If the result of the condition is true, the row is kept in the output table, otherwise it is discarded. The search condition typically references at least one column of the table generated in the P; this is not required, but otherwise the WHERE clause will be fairly useless.The  is used to group together those rows in a table that have the same values in all the columns listed. The order in which the columns are listed does not matter. The effect is to combine each set of rows having common values into one group row that represents all rows in the group. This is done to eliminate redundancy in the output and/or compute aggregates that apply to these groups."If a table has been grouped using groupBy0, but only certain groups are of interest, the  can be used, much like a ;, to eliminate groups from the result. Expressions in the w can refer both to grouped expressions and to ungrouped expressions (which necessarily involve an aggregate function).The . is for optional sorting. When more than one }u is specified, the later (right) values are used to sort rows that are equal according to the earlier (left) values.The  is combined with 9 to give a limit count if nonempty. If a limit count is given, no more than that many rows will be returned (but possibly fewer, if the query itself yields fewer rows).The  is combined with : to give an offset count if nonempty. The offset count says to skip that many rows before beginning to return rows. The rows are skipped before the limit count is applied.VThe process of retrieving or the command to retrieve data from a database is called a . The , , , ,  and & commands are used to specify queries. simple query::{ let query :: QueryG '["tab" ::: 'Table ('[] :=> '["col" ::: 'NoDef :=> 'Null 'PGint4])] '[] '["col" ::: 'Null 'PGint4]( query = selectStar (from (table #tab))in printSQL query:}SELECT * FROM "tab" AS "tab"restricted query::{let query :: Query '[ "tab" ::: 'Table ('[] :=>0 '[ "col1" ::: 'NoDef :=> 'NotNull 'PGint44 , "col2" ::: 'NoDef :=> 'NotNull 'PGint4 ])] '[]! '[ "sum" ::: 'NotNull 'PGint4$ , "col1" ::: 'NotNull 'PGint4 ] query = select1 ((#col1 + #col2) `As` #sum :* #col1 :* Nil) ( from (table #tab)! & where_ (#col1 .> #col2) & where_ (#col2 .> 0) )in printSQL query:}rSELECT ("col1" + "col2") AS "sum", "col1" AS "col1" FROM "tab" AS "tab" WHERE (("col1" > "col2") AND ("col2" > 0)) subquery::{ let query :: QueryG '["tab" ::: 'Table ('[] :=> '["col" ::: 'NoDef :=> 'Null 'PGint4])] '[] '["col" ::: 'Null 'PGint4] query = selectStarB (from (subquery (selectStar (from (table #tab)) `As` #sub)))in printSQL query:}5SELECT * FROM (SELECT * FROM "tab" AS "tab") AS "sub"limits and offsets::{ let query :: QueryG '["tab" ::: 'Table ('[] :=> '["col" ::: 'NoDef :=> 'Null 'PGint4])] '[] '["col" ::: 'Null 'PGint4] query = selectStarD (from (table #tab) & limit 100 & offset 2 & limit 50 & offset 2)in printSQL query:}.SELECT * FROM "tab" AS "tab" LIMIT 50 OFFSET 4parameterized query::{ let query :: QueryL '["tab" ::: 'Table ('[] :=> '["col" ::: 'NoDef :=> 'NotNull 'PGfloat8])] '[ 'NotNull 'PGfloat8]# '["col" ::: 'NotNull 'PGfloat8] query = selectStar3 (from (table #tab) & where_ (#col .> param @1))in printSQL query:};SELECT * FROM "tab" AS "tab" WHERE ("col" > ($1 :: float8))aggregation query::{let query :: Query '[ "tab" ::: 'Table ('[] :=>0 '[ "col1" ::: 'NoDef :=> 'NotNull 'PGint44 , "col2" ::: 'NoDef :=> 'NotNull 'PGint4 ])] '[]! '[ "sum" ::: 'NotNull 'PGint4$ , "col1" ::: 'NotNull 'PGint4 ] query =1 select (sum_ #col2 `As` #sum :* #col1 :* Nil)& ( from (table (#tab `As` #table1)) & group (By #col1 :* Nil)* & having (#col1 + sum_ #col2 .> 1) )in printSQL query:}xSELECT sum("col2") AS "sum", "col1" AS "col1" FROM "tab" AS "table1" GROUP BY "col1" HAVING (("col1" + sum("col2")) > 1) sorted query::{ let query :: QueryG '["tab" ::: 'Table ('[] :=> '["col" ::: 'NoDef :=> 'Null 'PGint4])] '[] '["col" ::: 'Null 'PGint4] query = selectStar8 (from (table #tab) & orderBy [#col & AscNullsFirst])in printSQL query:};SELECT * FROM "tab" AS "tab" ORDER BY "col" ASC NULLS FIRSTjoins::set -XFlexibleContexts:{'let query :: Query '[ "orders" ::: 'Table (- '["pk_orders" ::: PrimaryKey '["id"]M ,"fk_customers" ::: ForeignKey '["customer_id"] "customers" '["id"]O ,"fk_shippers" ::: ForeignKey '["shipper_id"] "shippers" '["id"]] :=>3 '[ "id" ::: 'NoDef :=> 'NotNull 'PGint47 , "price" ::: 'NoDef :=> 'NotNull 'PGfloat49 , "customer_id" ::: 'NoDef :=> 'NotNull 'PGint49 , "shipper_id" ::: 'NoDef :=> 'NotNull 'PGint4 ]) , "customers" ::: 'Table (5 '["pk_customers" ::: PrimaryKey '["id"]] :=>0 '[ "id" ::: 'NoDef :=> 'NotNull 'PGint42 , "name" ::: 'NoDef :=> 'NotNull 'PGtext ]) , "shippers" ::: 'Table (4 '["pk_shippers" ::: PrimaryKey '["id"]] :=>0 '[ "id" ::: 'NoDef :=> 'NotNull 'PGint42 , "name" ::: 'NoDef :=> 'NotNull 'PGtext ]) ] '[]+ '[ "order_price" ::: 'NotNull 'PGfloat4+ , "customer_name" ::: 'NotNull 'PGtext* , "shipper_name" ::: 'NotNull 'PGtext ] query = select& ( #o ! #price `As` #order_price :*' #c ! #name `As` #customer_name :*, #s ! #name `As` #shipper_name :* Nil )# ( from (table (#orders `As` #o). & innerJoin (table (#customers `As` #c))( (#o ! #customer_id .== #c ! #id)- & innerJoin (table (#shippers `As` #s))* (#o ! #shipper_id .== #s ! #id)) )in printSQL query:}SELECT "o"."price" AS "order_price", "c"."name" AS "customer_name", "s"."name" AS "shipper_name" FROM "orders" AS "o" INNER JOIN "customers" AS "c" ON ("o"."customer_id" = "c"."id") INNER JOIN "shippers" AS "s" ON ("o"."shipper_id" = "s"."id") self-join::{ let query :: QueryG '["tab" ::: 'Table ('[] :=> '["col" ::: 'NoDef :=> 'Null 'PGint4])] '[] '["col" ::: 'Null 'PGint4] query = selectDotStar #t1F (from (table (#tab `As` #t1) & crossJoin (table (#tab `As` #t2))))in printSQL query:}9SELECT "t1".* FROM "tab" AS "t1" CROSS JOIN "tab" AS "t2"set operations::{ let query :: QueryG '["tab" ::: 'Table ('[] :=> '["col" ::: 'NoDef :=> 'Null 'PGint4])] '[] '["col" ::: 'Null 'PGint4] query =" selectStar (from (table #tab)) `unionAll`" selectStar (from (table #tab))in printSQL query:}G(SELECT * FROM "tab" AS "tab") UNION ALL (SELECT * FROM "tab" AS "tab")DThe results of two queries can be combined using the set operation  . Duplicate rows are eliminated.DThe results of two queries can be combined using the set operation 2, the disjoint union. Duplicate rows are retained.DThe results of two queries can be combined using the set operation 2, the intersection. Duplicate rows are eliminated.DThe results of two queries can be combined using the set operation 0, the intersection. Duplicate rows are retained.DThe results of two queries can be combined using the set operation 4, the set difference. Duplicate rows are eliminated.DThe results of two queries can be combined using the set operation 2, the set difference. Duplicate rows are retained.the  in the  command constructs an intermediate virtual table by possibly combining tables, views, eliminating rows, grouping, etc. This table is finally passed on to processing by the select list. The select list determines which columns of the intermediate table are actually output.vAfter the select list has been processed, the result table can be subject to the elimination of duplicate rows using .The simplest kind of query is = which emits all columns that the table expression produces.A U emits all columns that the table expression produces and eliminates duplicate rows.rWhen working with multiple tables, it can also be useful to ask for all the columns of a particular table, using .A P asks for all the columns of a particular table, and eliminates duplicate rows. computes a row value or set of row values specified by value expressions. It is most commonly used to generate a constant table  within a larger command, but it can be used on its own.@type Row = '["a" ::: 'NotNull 'PGint4, "b" ::: 'NotNull 'PGtext]Nlet query = values (1 `As` #a :* "one" `As` #b :* Nil) [] :: Query '[] '[] RowprintSQL query2SELECT * FROM (VALUES (1, E'one')) AS t ("a", "b")K computes a row value or set of row values specified by value expressions. Render a A  generates a  from a table reference that can be a table name, or a derived table such as a subquery, a JOIN construct, or complex combinations of these. A  may be transformed by , , , ,  and  , using the K operator to match the left-to-right sequencing of their placement in SQL.A  is an endomorphism of (s which adds a search condition to the .A  is a transformation of s which switches its a from b to c. Use  group Nil/ to perform a "grand total" aggregation query.A  is an endomorphism of (s which adds a search condition to the .An  is an endomorphism of 1s which appends an ordering to the right of the .A  is an endomorphism of s which adds to the .An  is an endomorphism of s which adds to the .A real  is a table from the schema. derives a table from a . derives a table from a 8.left & crossJoin right2. For every possible combination of rows from left and rightc (i.e., a Cartesian product), the joined table will contain a row consisting of all columns in left followed by all columns in right. If the tables have n and m3 rows respectively, the joined table will have n * m rows.left & innerJoin right on&. The joined table is filtered by the on condition.left & leftOuterJoin right on?. First, an inner join is performed. Then, for each row in left that does not satisfy the on condition with any row in right7, a joined row is added with null values in columns of rightI. Thus, the joined table always has at least one row for each row in left.left & rightOuterJoin right on?. First, an inner join is performed. Then, for each row in right that does not satisfy the on condition with any row in left7, a joined row is added with null values in columns of leftg. This is the converse of a left join: the result table will always have a row for each row in right.left & fullOuterJoin right on?. First, an inner join is performed. Then, for each row in left that does not satisfy the on condition with any row in right7, a joined row is added with null values in columns of right. Also, for each row of right> that does not satisfy the join condition with any row in left2, a joined row with null values in the columns of left is added. Renders a . Renders a . Render a . Render a }. select listintermediate virtual table select listintermediate virtual tableintermediate virtual tableintermediate virtual tableparticular virtual subtableintermediate virtual tableparticular virtual tableintermediate virtual table]When more than one row is specified, all the rows must must have the same number of elementsone row of valuestable referencefiltering conditiongrouped columnshaving conditionsort expressionslimit parameteroffset parameterrightleftrighton conditionleftrighton conditionleftrighton conditionleftrighton conditionleftA}~A}~}~!Squeal data manipulation language(c) Eitan Chatav, 2017eitan@morphism.tech experimentalNone&',-6<FKQSTV]A > specifies an action to perform upon a constraint violation.  will raise an error. ! simply avoids inserting a row. N updates the existing row that conflicts with the row proposed for insertion.A  computes and return value(s) based on each row actually inserted, updated or deleted. This is primarily useful for obtaining values that were supplied by defaults, such as a serial sequence number. However, any expression using the table's columns is allowed. Only rows that were successfully inserted or updated or deleted will be returned. For example, if a row was locked but not updated because an = condition was not satisfied, the row will not be returned. * will return all columns in the row. Use  Returning Nil8 in the common case where no return values are desired.,s are values to insert or update in a row.  updates with the same value.  inserts or updates with the DEFAULT value.  sets a value to be an >, which can refer to existing value in the row for an update.A  is a statement which may modify data in the database, but does not alter the schema. Examples are inserts, updates and deletes. A  is also considered a % even though it does not modify data.simple insert::{ let manipulation :: Manipulation '[ "tab" ::: 'Table ('[] :=>/ '[ "col1" ::: 'NoDef :=> 'NotNull 'PGint49 , "col2" ::: 'Def :=> 'NotNull 'PGint4 ])] '[] '[] manipulation =C insertRow_ #tab (Set 2 `As` #col1 :* Default `As` #col2 :* Nil)in printSQL manipulation:}6INSERT INTO "tab" ("col1", "col2") VALUES (2, DEFAULT)parameterized insert::{ let manipulation :: Manipulation '[ "tab" ::: 'Table ('[] :=>/ '[ "col1" ::: 'NoDef :=> 'NotNull 'PGint43 , "col2" ::: 'NoDef :=> 'NotNull 'PGint4 ])]/ '[ 'NotNull 'PGint4, 'NotNull 'PGint4 ] '[] manipulation = insertRow_ #tabE (Set (param @1) `As` #col1 :* Set (param @2) `As` #col2 :* Nil)in printSQL manipulation:}FINSERT INTO "tab" ("col1", "col2") VALUES (($1 :: int4), ($2 :: int4))returning insert::{ let manipulation :: Manipulation '[ "tab" ::: 'Table ('[] :=>/ '[ "col1" ::: 'NoDef :=> 'NotNull 'PGint45 , "col2" ::: 'Def :=> 'NotNull 'PGint4 ])] '[]& '["fromOnly" ::: 'NotNull 'PGint4] manipulation =B insertRow #tab (Set 2 `As` #col1 :* Default `As` #col2 :* Nil)A OnConflictDoRaise (Returning (#col1 `As` #fromOnly :* Nil))in printSQL manipulation:}UINSERT INTO "tab" ("col1", "col2") VALUES (2, DEFAULT) RETURNING "col1" AS "fromOnly"upsert::{let manipulation :: Manipulation '[ "tab" ::: 'Table ('[] :=>/ '[ "col1" ::: 'NoDef :=> 'NotNull 'PGint43 , "col2" ::: 'NoDef :=> 'NotNull 'PGint4 ])]& '[] '[ "sum" ::: 'NotNull 'PGint4] manipulation = insertRows #tab3 (Set 2 `As` #col1 :* Set 4 `As` #col2 :* Nil)3 [Set 6 `As` #col1 :* Set 8 `As` #col2 :* Nil] (OnConflictDoUpdate4 (Set 2 `As` #col1 :* Same `As` #col2 :* Nil) [#col1 .== #col2])4 (Returning $ (#col1 + #col2) `As` #sum :* Nil)in printSQL manipulation:}INSERT INTO "tab" ("col1", "col2") VALUES (2, 4), (6, 8) ON CONFLICT DO UPDATE SET "col1" = 2 WHERE ("col1" = "col2") RETURNING ("col1" + "col2") AS "sum" query insert::{let manipulation :: Manipulation '[ "tab" ::: 'Table ('[] :=>/ '[ "col1" ::: 'NoDef :=> 'NotNull 'PGint4/ , "col2" ::: 'NoDef :=> 'NotNull 'PGint4 ])& , "other_tab" ::: 'Table ('[] :=>/ '[ "col1" ::: 'NoDef :=> 'NotNull 'PGint4/ , "col2" ::: 'NoDef :=> 'NotNull 'PGint4 ]) ] '[] '[] manipulation = insertQuery_ #tab6 (selectStar (from (table (#other_tab `As` #t))))in printSQL manipulation:}2INSERT INTO "tab" SELECT * FROM "other_tab" AS "t"update::{ let manipulation :: Manipulation '[ "tab" ::: 'Table ('[] :=>/ '[ "col1" ::: 'NoDef :=> 'NotNull 'PGint4; , "col2" ::: 'NoDef :=> 'NotNull 'PGint4 ])] '[] '[] manipulation == update_ #tab (Set 2 `As` #col1 :* Same `As` #col2 :* Nil) (#col1 ./= #col2)in printSQL manipulation:}4UPDATE "tab" SET "col1" = 2 WHERE ("col1" <> "col2")delete::{ let manipulation :: Manipulation '[ "tab" ::: 'Table ('[] :=>/ '[ "col1" ::: 'NoDef :=> 'NotNull 'PGint47 , "col2" ::: 'NoDef :=> 'NotNull 'PGint4 ])] '[]" '[ "col1" ::: 'NotNull 'PGint4$ , "col2" ::: 'NotNull 'PGint4 ]@ manipulation = deleteFrom #tab (#col1 .== #col2) ReturningStarin printSQL manipulation:}5DELETE FROM "tab" WHERE ("col1" = "col2") RETURNING * Convert a  into a .Insert multiple rows.\When a table is created, it contains no data. The first thing to do before a database can be of much use is to insert data. Data is conceptually inserted one row at a time. Of course you can also insert more than one row, but there is no way to insert less than one row. Even if you know only some column values, a complete row must be created.Insert a single row.Insert multiple rows returning # and raising an error on conflicts.Insert a single row returning # and raising an error on conflicts. Insert a . Insert a  returning # and raising an error on conflicts. Render a . Render a .An ] command changes the values of the specified columns in all rows that satisfy the condition.Update a row returning .Delete rows of a table.Delete rows returning . provides a way to write auxiliary statements for use in a larger statement. These statements, which are often referred to as Common Table Expressions or CTEs, can be thought of as defining temporary tables that exist just for one statement.otype ProductsTable = '[] :=> '["product" ::: 'NoDef :=> 'NotNull 'PGtext, "date" ::: 'Def :=> 'NotNull 'PGdate]:{let manipulation :: Manipulation '["products" ::: 'Table ProductsTable, "products_deleted" ::: 'Table ProductsTable] '[ 'NotNull 'PGdate] '[] manipulation = withV (deleteFrom #products (#date .< param @1) ReturningStar `As` #deleted_rows :* Nil)W (insertQuery_ #products_deleted (selectStar (from (view (#deleted_rows `As` #t)))))in printSQL manipulation:}WITH "deleted_rows" AS (DELETE FROM "products" WHERE ("date" < ($1 :: date)) RETURNING *) INSERT INTO "products_deleted" SELECT * FROM "deleted_rows" AS "t" table to insert into row to insertmore rows to insert)what to do in case of constraint conflictresults to returntable to insert into row to insert)what to do in case of constraint conflictresults to returntable to insert into row to insertmore rows to inserttable to insert into row to inserttable to insert into)what to do in case of constraint conflictresults to returntable to insert intotable to update%modified values to replace old values0condition under which to perform update on a rowresults to returntable to update%modified values to replace old values0condition under which to perform update on a rowtable to delete from%condition under which to delete a rowresults to returntable to delete from%condition under which to delete a rowcommon table expressionsSqueal data definition language(c) Eitan Chatav, 2017eitan@morphism.tech experimentalNone&'+,-6;<=>?FKQSTV]h5s are used in   commands.An 8 describes the alteration to perform on a single column.An  is either NULL or has DEFAULT.S adds a new column, initially filled with whatever default value is given or with NULL.:{ let definition :: DefinitionH '["tab" ::: 'Table ('[] :=> '["col1" ::: 'NoDef :=> 'Null 'PGint4])] '["tab" ::: 'Table ('[] :=>- '[ "col1" ::: 'NoDef :=> 'Null 'PGint4/ , "col2" ::: 'Def :=> 'Null 'PGtext ])]S definition = alterTable #tab (addColumn #col2 (text & nullable & default_ "foo"))in printSQL definition:}=ALTER TABLE "tab" ADD COLUMN "col2" text NULL DEFAULT E'foo';:{ let definition :: DefinitionH '["tab" ::: 'Table ('[] :=> '["col1" ::: 'NoDef :=> 'Null 'PGint4])] '["tab" ::: 'Table ('[] :=>- '[ "col1" ::: 'NoDef :=> 'Null 'PGint41 , "col2" ::: 'NoDef :=> 'Null 'PGtext ])]B definition = alterTable #tab (addColumn #col2 (text & nullable))in printSQL definition:}.ALTER TABLE "tab" ADD COLUMN "col2" text NULL;An @ describes the alteration to perform on the columns of a table. Analagous to  there is also A which is invoked when a referenced column is changed (updated).[if any referencing rows has not changed when the constraint is checked, an error is raised#prevents update of a referenced row\the updated values of the referenced column(s) should be copied into the referencing row(s)= indicates what to do with rows that reference a deleted row.Wif any referencing rows still exist when the constraint is checked, an error is raised%prevents deletion of a referenced rowospecifies that when a referenced row is deleted, row(s) referencing it should be automatically deleted as wellHA constraint synonym between types involved in a foreign key constraint.Data types are a way to limit the kind of data that can be stored in a table. For many applications, however, the constraint they provide is too coarse. For example, a column containing a product price should probably only accept positive values. But there is no standard data type that accepts only positive numbers. Another issue is that you might want to constrain column data with respect to other columns or rows. For example, in a table containing product information, there should be only one row for each product number. ns give you as much control over the data in your tables as you wish. If a user attempts to store data in a column that would violate a constraint, an error is raised. This applies even if the value came from the default value definition. A  A is a statement that changes the schema of the database, like a  , , or  command.  s may be composed using the  operator.   adds a table to the schema.:set -XOverloadedLabels:{ printSQL $U createTable #tab ((int & nullable) `As` #a :* (real & nullable) `As` #b :* Nil) Nil:}1CREATE TABLE "tab" ("a" int NULL, "b" real NULL);   creates a table if it doesn't exist, but does not add it to the schema. Instead, the schema already has the table so if the table did not yet exist, the schema was wrong.  H fixes this. Interestingly, this property makes it an idempotent in the ; of  s.*:set -XOverloadedLabels -XTypeApplications\type Table = '[] :=> '["a" ::: 'NoDef :=> 'Null 'PGint4, "b" ::: 'NoDef :=> 'Null 'PGfloat4]'type Schema = '["tab" ::: 'Table Table]:{let# setup :: Definition Schema Schemah setup = createTableIfNotExists #tab ((int & nullable) `As` #a :* (real & nullable) `As` #b :* Nil) Nilin printSQL setup:}?CREATE TABLE IF NOT EXISTS "tab" ("a" int NULL, "b" real NULL);A  constraint is the most generic ns type. It allows you to specify that the value in a certain column must satisfy a Boolean (truth-value) expression.:{type Schema = '[A "tab" ::: 'Table ('[ "inequality" ::: 'Check '["a","b"]] :=> '[( "a" ::: 'NoDef :=> 'NotNull 'PGint4,' "b" ::: 'NoDef :=> 'NotNull 'PGint4 ])]:}:{let% definition :: Definition '[] Schema definition = createTable #tab$ ( (int & notNullable) `As` #a :** (int & notNullable) `As` #b :* Nil )B ( check (#a :* #b :* Nil) (#a .> #b) `As` #inequality :* Nil ):}printSQL definitioneCREATE TABLE "tab" ("a" int NOT NULL, "b" int NOT NULL, CONSTRAINT "inequality" CHECK (("a" > "b")));A y constraint ensure that the data contained in a column, or a group of columns, is unique among all the rows in the table.:{type Schema = '[> "tab" ::: 'Table( '[ "uq_a_b" ::: 'Unique '["a","b"]] :=> '[% "a" ::: 'NoDef :=> 'Null 'PGint4,$ "b" ::: 'NoDef :=> 'Null 'PGint4 ])]:}:{let% definition :: Definition '[] Schema definition = createTable #tab! ( (int & nullable) `As` #a :*' (int & nullable) `As` #b :* Nil )4 ( unique (#a :* #b :* Nil) `As` #uq_a_b :* Nil ):}printSQL definitionWCREATE TABLE "tab" ("a" int NULL, "b" int NULL, CONSTRAINT "uq_a_b" UNIQUE ("a", "b"));A  constraint indicates that a column, or group of columns, can be used as a unique identifier for rows in the table. This requires that the values be both unique and not null.:{type Schema = '[> "tab" ::: 'Table ('[ "pk_id" ::: 'PrimaryKey '["id"]] :=> '[' "id" ::: 'Def :=> 'NotNull 'PGint4,* "name" ::: 'NoDef :=> 'NotNull 'PGtext ])]:}:{let% definition :: Definition '[] Schema definition = createTable #tab ( serial `As` #id :*. (text & notNullable) `As` #name :* Nil )) ( primaryKey #id `As` #pk_id :* Nil ):}printSQL definition^CREATE TABLE "tab" ("id" serial, "name" text NOT NULL, CONSTRAINT "pk_id" PRIMARY KEY ("id"));A  specifies that the values in a column (or a group of columns) must match the values appearing in some row of another table. We say this maintains the referential integrity between two related tables.:{ type Schema = '[ "users" ::: 'Table (2 '[ "pk_users" ::: 'PrimaryKey '["id"] ] :=>, '[ "id" ::: 'Def :=> 'NotNull 'PGint40 , "name" ::: 'NoDef :=> 'NotNull 'PGtext ]) , "emails" ::: 'Table (. '[ "pk_emails" ::: 'PrimaryKey '["id"]C , "fk_user_id" ::: 'ForeignKey '["user_id"] "users" '["id"] ] :=>, '[ "id" ::: 'Def :=> 'NotNull 'PGint43 , "user_id" ::: 'NoDef :=> 'NotNull 'PGint4. , "email" ::: 'NoDef :=> 'Null 'PGtext ]) ]:}:{let setup :: Definition '[] Schema setup = createTable #users ( serial `As` #id :*/ (text & notNullable) `As` #name :* Nil )1 ( primaryKey #id `As` #pk_users :* Nil ) >>> createTable #emails ( serial `As` #id :*+ (int & notNullable) `As` #user_id :*- (text & nullable) `As` #email :* Nil )( ( primaryKey #id `As` #pk_emails :*% foreignKey #user_id #users #idB OnDeleteCascade OnUpdateCascade `As` #fk_user_id :* Nil )in printSQL setup:}cCREATE TABLE "users" ("id" serial, "name" text NOT NULL, CONSTRAINT "pk_users" PRIMARY KEY ("id"));CREATE TABLE "emails" ("id" serial, "user_id" int NOT NULL, "email" text NULL, CONSTRAINT "pk_emails" PRIMARY KEY ("id"), CONSTRAINT "fk_user_id" FOREIGN KEY ("user_id") REFERENCES "users" ("id") ON DELETE CASCADE ON UPDATE CASCADE);A $ can even be a table self-reference.:{ type Schema = '[ "employees" ::: 'Table (9 '[ "employees_pk" ::: 'PrimaryKey '["id"]V , "employees_employer_fk" ::: 'ForeignKey '["employer_id"] "employees" '["id"] ] :=>7 '[ "id" ::: 'Def :=> 'NotNull 'PGint47 , "name" ::: 'NoDef :=> 'NotNull 'PGtext7 , "employer_id" ::: 'NoDef :=> 'Null 'PGint4 ]) ]:}:{ let setup :: Definition '[] Schema setup = createTable #employees ( serial `As` #id :*) (text & notNullable) `As` #name :*6 (integer & nullable) `As` #employer_id :* Nil )+ ( primaryKey #id `As` #employees_pk :*- foreignKey #employer_id #employees #idM OnDeleteCascade OnUpdateCascade `As` #employees_employer_fk :* Nil )in printSQL setup:} CREATE TABLE "employees" ("id" serial, "name" text NOT NULL, "employer_id" integer NULL, CONSTRAINT "employees_pk" PRIMARY KEY ("id"), CONSTRAINT "employees_employer_fk" FOREIGN KEY ("employer_id") REFERENCES "employees" ("id") ON DELETE CASCADE ON UPDATE CASCADE);Render .Render .! removes a table from the schema.:{let: definition :: Definition '["muh_table" ::: 'Table t] '[]# definition = dropTable #muh_table:}printSQL definitionDROP TABLE "muh_table";3 changes the definition of a table from the schema.- changes the name of a table from the schema.%printSQL $ alterTableRename #foo #bar"ALTER TABLE "foo" RENAME TO "bar";An  adds a table constraint.:{let definition :: DefinitionJ '["tab" ::: 'Table ('[] :=> '["col" ::: 'NoDef :=> 'NotNull 'PGint4])]g '["tab" ::: 'Table ('["positive" ::: Check '["col"]] :=> '["col" ::: 'NoDef :=> 'NotNull 'PGint4])]Z definition = alterTable #tab (addConstraint #positive (check (#col :* Nil) (#col .> 0)))in printSQL definition:}@ALTER TABLE "tab" ADD CONSTRAINT "positive" CHECK (("col" > 0));A  drops a table constraint.:{let definition :: Definitiong '["tab" ::: 'Table ('["positive" ::: Check '["col"]] :=> '["col" ::: 'NoDef :=> 'NotNull 'PGint4])]J '["tab" ::: 'Table ('[] :=> '["col" ::: 'NoDef :=> 'NotNull 'PGint4])]9 definition = alterTable #tab (dropConstraint #positive)in printSQL definition:}-ALTER TABLE "tab" DROP CONSTRAINT "positive";A  removes a column. Whatever data was in the column disappears. Table constraints involving the column are dropped, too. However, if the column is referenced by a foreign key constraint of another table, PostgreSQL will not silently drop that constraint.:{ let definition :: Definition '["tab" ::: 'Table ('[] :=>- '[ "col1" ::: 'NoDef :=> 'Null 'PGint41 , "col2" ::: 'NoDef :=> 'Null 'PGtext ])]H '["tab" ::: 'Table ('[] :=> '["col1" ::: 'NoDef :=> 'Null 'PGint4])]1 definition = alterTable #tab (dropColumn #col2)in printSQL definition:}%ALTER TABLE "tab" DROP COLUMN "col2";A  renames a column.:{let definition :: DefinitionG '["tab" ::: 'Table ('[] :=> '["foo" ::: 'NoDef :=> 'Null 'PGint4])]G '["tab" ::: 'Table ('[] :=> '["bar" ::: 'NoDef :=> 'Null 'PGint4])]7 definition = alterTable #tab (renameColumn #foo #bar)in printSQL definition:}/ALTER TABLE "tab" RENAME COLUMN "foo" TO "bar";An  alters a single column.A  sets a new default for a column. Note that this doesn't affect any existing rows in the table, it just changes the default for future insert and update commands.:{let definition :: DefinitionG '["tab" ::: 'Table ('[] :=> '["col" ::: 'NoDef :=> 'Null 'PGint4])]E '["tab" ::: 'Table ('[] :=> '["col" ::: 'Def :=> 'Null 'PGint4])]@ definition = alterTable #tab (alterColumn #col (setDefault 5))in printSQL definition:}3ALTER TABLE "tab" ALTER COLUMN "col" SET DEFAULT 5;A ( removes any default value for a column.:{let definition :: DefinitionE '["tab" ::: 'Table ('[] :=> '["col" ::: 'Def :=> 'Null 'PGint4])]G '["tab" ::: 'Table ('[] :=> '["col" ::: 'NoDef :=> 'Null 'PGint4])]= definition = alterTable #tab (alterColumn #col dropDefault)in printSQL definition:}2ALTER TABLE "tab" ALTER COLUMN "col" DROP DEFAULT;A  adds a NOT NULL constraint to a column. The constraint will be checked immediately, so the table data must satisfy the constraint before it can be added.:{let definition :: DefinitionG '["tab" ::: 'Table ('[] :=> '["col" ::: 'NoDef :=> 'Null 'PGint4])]J '["tab" ::: 'Table ('[] :=> '["col" ::: 'NoDef :=> 'NotNull 'PGint4])]< definition = alterTable #tab (alterColumn #col setNotNull)in printSQL definition:}2ALTER TABLE "tab" ALTER COLUMN "col" SET NOT NULL;A  drops a NOT NULL constraint from a column.:{let definition :: DefinitionJ '["tab" ::: 'Table ('[] :=> '["col" ::: 'NoDef :=> 'NotNull 'PGint4])]G '["tab" ::: 'Table ('[] :=> '["col" ::: 'NoDef :=> 'Null 'PGint4])]= definition = alterTable #tab (alterColumn #col dropNotNull)in printSQL definition:}3ALTER TABLE "tab" ALTER COLUMN "col" DROP NOT NULL; An   converts a column to a different data type. This will succeed only if each existing entry in the column can be converted to the new type by an implicit cast.:{ let definition :: DefinitionJ '["tab" ::: 'Table ('[] :=> '["col" ::: 'NoDef :=> 'NotNull 'PGint4])]M '["tab" ::: 'Table ('[] :=> '["col" ::: 'NoDef :=> 'NotNull 'PGnumeric])] definition =J alterTable #tab (alterColumn #col (alterType (numeric & notNullable)))in printSQL definition:};ALTER TABLE "tab" ALTER COLUMN "col" TYPE numeric NOT NULL;!Create a view.:{ let definition :: Definition '[ "abc" ::: 'Table ('[] :=> '["a" ::: 'NoDef :=> 'Null 'PGint4, "b" ::: 'NoDef :=> 'Null 'PGint4, "c" ::: 'NoDef :=> 'Null 'PGint4])] '[ "abc" ::: 'Table ('[] :=> '["a" ::: 'NoDef :=> 'Null 'PGint4, "b" ::: 'NoDef :=> 'Null 'PGint4, "c" ::: 'NoDef :=> 'Null 'PGint4])I , "bc" ::: 'View ('["b" ::: 'Null 'PGint4, "c" ::: 'Null 'PGint4])] definition =A createView #bc (select (#b :* #c :* Nil) (from (table #abc)))in printSQL definition:}FCREATE VIEW "bc" AS SELECT "b" AS "b", "c" AS "c" FROM "abc" AS "abc";" Drop a view.:{ let definition :: Definition '[ "abc" ::: 'Table ('[] :=> '["a" ::: 'NoDef :=> 'Null 'PGint4, "b" ::: 'NoDef :=> 'Null 'PGint4, "c" ::: 'NoDef :=> 'Null 'PGint4])I , "bc" ::: 'View ('["b" ::: 'Null 'PGint4, "c" ::: 'Null 'PGint4])] '[ "abc" ::: 'Table ('[] :=> '["a" ::: 'NoDef :=> 'Null 'PGint4, "b" ::: 'NoDef :=> 'Null 'PGint4, "c" ::: 'NoDef :=> 'Null 'PGint4])] definition = dropView #bcin printSQL definition:}DROP VIEW "bc";#'Enumerated types are created using the # command, for exampleVprintSQL $ createTypeEnum #mood (label @"sad" :* label @"ok" :* label @"happy" :* Nil)2CREATE TYPE "mood" AS ENUM ('sad', 'ok', 'happy');$GEnumerated types can also be generated from a Haskell type, for example:data Schwarma = Beef | Lamb | Chicken deriving GHC.Genericinstance SOP.Generic Schwarma%instance SOP.HasDatatypeInfo Schwarma1printSQL $ createTypeEnumFrom @Schwarma #schwarma;CREATE TYPE "schwarma" AS ENUM ('Beef', 'Lamb', 'Chicken');%%h creates a composite type. The composite type is specified by a list of attribute names and data types.\printSQL $ createTypeComposite #complex (float8 `As` #real :* float8 `As` #imaginary :* Nil)=CREATE TYPE "complex" AS ("real" float8, "imaginary" float8);&FComposite types can also be generated from a Haskell type, for example]data Complex = Complex {real :: Maybe Double, imaginary :: Maybe Double} deriving GHC.Genericinstance SOP.Generic Complex$instance SOP.HasDatatypeInfo Complex4printSQL $ createTypeCompositeFrom @Complex #complex=CREATE TYPE "complex" AS ("real" float8, "imaginary" float8);' Drop a type.:data Schwarma = Beef | Lamb | Chicken deriving GHC.Genericinstance SOP.Generic Schwarma%instance SOP.HasDatatypeInfo Schwarma^printSQL (dropType #schwarma :: Definition '["schwarma" ::: 'Typedef (EnumFrom Schwarma)] '[])DROP TYPE "schwarma";(used in  / commands as a column constraint to note that NULL may be present in a column)used in  , commands as a column constraint to ensure NULL is not present in a column*used in  2 commands as a column constraint to give a default+gnot a true type, but merely a notational convenience for creating unique identifier columns with type ,gnot a true type, but merely a notational convenience for creating unique identifier columns with type -gnot a true type, but merely a notational convenience for creating unique identifier columns with type .gnot a true type, but merely a notational convenience for creating unique identifier columns with type /gnot a true type, but merely a notational convenience for creating unique identifier columns with type 0gnot a true type, but merely a notational convenience for creating unique identifier columns with type  column to addtype of the new column the name of the table to add%the names and datatype of each column(constraints that must hold for the table the name of the table to add%the names and datatype of each column(constraints that must hold for the table<the name of the table to add%the names and datatype of each column(constraints that must hold for the table0specify the subcolumns which are getting checked a closed  on those subcolumns9specify subcolumns which together are unique for each row9specify the subcolumns which together form a primary key.column or columns in the tablereference table2reference column or columns in the reference table$what to do when reference is deleted$what to do when reference is updatedtable to removetable to alteralteration to performtable to renamewhat to rename itconstraint to addconstraint to dropcolumn to removecolumn to renamewhat to rename the columncolumn to alteralteration to performdefault value to set!the name of the view to addquery"view to remove#(name of the user defined enumerated typelabels of the enumerated type$(name of the user defined enumerated type%'name of the user defined composite type&list of attribute names and data types&'name of the user defined composite type'name of the user defined type@      !"#$%&'()*+,-./0@      !"#$%&'()*+,-./0   Binary encoding and decoding(c) Eitan Chatav, 2017eitan@morphism.tech experimentalNone&',-3456;<=>?FSTV]h XXA is a 1-tuple type, useful for encoding a single parameter with b! or decoding a single value with \.import Data.TextDtoParams @(Only (Maybe Text)) @'[ 'Null 'PGtext] (Only (Just "foo"))K (Just "foo") :* NilUfromRow @'["fromOnly" ::: 'Null 'PGtext] @(Only (Maybe Text)) (K (Just "bar") :* Nil)Only {fromOnly = Just "bar"}[A [D constraint generically sequences the parsings of the columns of a i into the fields of a record =N provided they have the same field names. You should not define instances of [. Instead define > and ?" instances which in turn provide [ instances.\ :set -XOverloadedStringsimport Data.Text<newtype UserId = UserId { getUserId :: Int16 } deriving ShowKinstance FromValue 'PGint2 UserId where fromValue = fmap UserId . fromValue`data UserRow = UserRow { userId :: UserId, userName :: Maybe Text } deriving (Show, GHC.Generic)instance Generic UserRow instance HasDatatypeInfo UserRowJtype User = '["userId" ::: 'NotNull 'PGint2, "userName" ::: 'Null 'PGtext]LfromRow @User @UserRow (K (Just "\NUL\SOH") :* K (Just "bloodninja") :* Nil)GUserRow {userId = UserId {getUserId = 1}, userName = Just "bloodninja"}]A ] constraint lifts the _ parser to a decoding of a (Symbol, NullityType) to a = , decoding {s to /(s. You should not define instances for ]", just use the provided instances.^(:set -XTypeOperators -XOverloadedStrings0newtype Id = Id { getId :: Int16 } deriving ShowCinstance FromValue 'PGint2 Id where fromValue = fmap Id . fromValueGfromColumnValue @("col" ::: 'NotNull 'PGint2) @Id (K (Just "\NUL\SOH"))Id {getId = 1}LfromColumnValue @("col" ::: 'Null 'PGint2) @(Maybe Id) (K (Just "\NUL\SOH"))Just (Id {getId = 1})_A _C constraint gives a parser from the binary format of a PostgreSQL  into a Haskell =.`0newtype Id = Id { getId :: Int16 } deriving ShowCinstance FromValue 'PGint2 Id where fromValue = fmap Id . fromValueaA a3 constraint generically sequences the encodings of =2s of the fields of a tuple or record to a row of t's. You should not define instances of a. Instead define >" instances which in turn provide a instances.b1type Params = '[ 'NotNull 'PGbool, 'Null 'PGint2]RtoParams @(Bool, Maybe Int16) @'[ 'NotNull 'PGbool, 'Null 'PGint2] (False, Just 0)-K (Just "\NUL") :* K (Just "\NUL\NUL") :* Nil:set -XDeriveGenericHdata Tuple = Tuple { p1 :: Bool, p2 :: Maybe Int16} deriving GHC.Genericinstance Generic Tuple.toParams @Tuple @Params (Tuple False (Just 0))-K (Just "\NUL") :* K (Just "\NUL\NUL") :* NilcA c constraint lifts the e encoding of a = to a z , encoding /s to {'s. You should not define instances of c", just use the provided instances.d*toColumnParam @Int16 @('NotNull 'PGint2) 0K (Just "\NUL\NUL")6toColumnParam @(Maybe Int16) @('Null 'PGint2) (Just 0)K (Just "\NUL\NUL")5toColumnParam @(Maybe Int16) @('Null 'PGint2) Nothing K NothingeA e+ constraint gives an encoding of a Haskell =. into into the binary format of a PostgreSQL .f#:set -XTypeApplications -XDataKindstoParam @Bool @'PGbool FalseK "\NUL"toParam @Int16 @'PGint2 0 K "\NUL\NUL"toParam @Int32 @'PGint4 0K "\NUL\NUL\NUL\NUL":set -XMultiParamTypeClasses0newtype Id = Id { getId :: Int16 } deriving Show;instance ToParam Id 'PGint2 where toParam = toParam . getIdtoParam @Id @'PGint2 (Id 1) K "\NUL\SOH"XYZ[\]^_`abcdefefcdab_`]^[\XYZ XYZ[\]^@A_`abcdBCDEefPQ monad(c) Eitan Chatav, 2017eitan@morphism.tech experimentalNone,-7;<=>?AFQSTVhGA snapshot of the state of a  computation. is an mtl style constraint, similar to )* , for using LibPQ to  runs a # with params from a type with a a constraint. It calls F# and doesn't afraid of anything. is like  for a parameter-free statement. is like  for query statements. is like  for a parameter-free statement.3 has the same type signature as a composition of G and @ but provides an optimization by preparing the statement with H and then traversing a I container with J9. The temporary prepared statement is then deallocated. is a flipped  is like  but works on K containers and returns unit. is a flipped . lets you lift actions from LibPQ- that require a connection into your monad.5To define an instance, you can minimally define only , ,  and ,. Monad transformers get a default instance.An  (https://bentnib.org/paramnotions-jfp.pdfAtkey indexed monad is a L  /https://ncatlab.org/nlab/show/enriched+categoryenriched category-. An indexed monad transformer transforms a M into an indexed monad. And, A is a class for indexed monad transformers that support running  s using 7 and embedding a computation in a larger schema using .indexed analog of Nindexed analog of Oindexed analog of Pindexed analog of flipped Qindexed analog of R.Safely embed a computation in a larger schema.Run a   with S$, we expect that libpq obeys the law Sdefine statement1 & pqThen (define statement2) = define (statement1 >>> statement2)KWe keep track of the schema via an Atkey indexed state monad transformer, ..Makes a new connection to the database server.bThis function opens a new database connection using the parameters taken from the string conninfo.The passed string can be empty to use all default parameters, or it can contain one or more parameter settings separated by whitespace. Each parameter setting is in the form keyword = value. Spaces around the equal sign are optional. To write an empty value or a value containing spaces, surround it with single quotes, e.g., keyword = 'a value'. Single quotes and backslashes within the value must be escaped with a backslash, i.e., ' and .ETo specify the schema you wish to connect with, use type application.:set -XDataKinds:set -XPolyKinds:set -XTypeOperatorsHtype Schema = '["tab" ::: '[] :=> '["col" ::: 'NoDef :=> 'Null 'PGint2]]:set -XTypeApplications:set -XOverloadedStringsEconn <- connectdb @Schema "host=localhost port=5432 dbname=exampledb"^Note that, for now, squeal doesn't offer any protection from connecting with the wrong schema!$Closes the connection to the server.Do  and  before and after a computation.Safely  to a smaller schema.Run a  and keep the result and the  Connection. Execute a % and discard the result but keep the  Connection. Evaluate a  and discard the  Connection but keep the result.Helper function in defining T instance for .5Get a row corresponding to a given row number from a <, throwing an exception if the row number is out of bounds.:Intended to be used for unfolding in streaming libraries, 8 takes a total number of rows (which can be found with  ) and a 2 and given a row number if it's too large returns 0>, otherwise returning the row along with the next row number.Get all rows from a .%Get the first row if possible from a .Lifts actions on results from LibPQ.8Returns the number of rows (tuples) in the query result.)Returns the result status of the command.UReturns the error message most recently generated by an operation on the connection. ,  or  and friends and friends, , or  , and friends,  or ,  or ,  or conninfo row numberresulttotal number of rowsresult row numberresultresult4 8  Pooled connections(c) Eitan Chatav, 2017eitan@morphism.tech experimentalNone,-3;<=>?FQTVd\ A snapshot of the state of a  computation. schema% should be a drop-in replacement for   schema schema.Create a striped pool of connections. Although the garbage collector will destroy all idle connections when the pool is garbage collected it's recommended to manually Y when you're done with the pool so that the connections are freed up as soon as possible.Helper function in defining T instance for .T instance for . instance for .U instance for .V instance for .M instance for .W instance for .The passed string can be empty to use all default parameters, or it can contain one or more parameter settings separated by whitespace. Each parameter setting is in the form keyword = value. Spaces around the equal sign are optional. To write an empty value or a value containing spaces, surround it with single quotes, e.g., keyword = 'a value'. Single quotes and backslashes within the value must be escaped with a backslash, i.e., ' and .[The number of stripes (distinct sub-pools) to maintain. The smallest acceptable value is 1.Amount of time for which an unused connection is kept open. The smallest acceptable value is 0.5 seconds. The elapsed time before destroying a connection may be a little longer than requested, as the reaper thread wakes at 1-second intervals.Maximum number of connections to keep open per stripe. The smallest acceptable value is 1. Requests for connections will block if this limit is reached on a single stripe, even if other stripes have idle connections available. #Squeal transaction control language(c) Eitan Chatav, 2017eitan@morphism.tech experimentalNone<]The D transaction property has no effect unless the transaction is also  and . When all three of these properties are selected for a transaction, the transaction may block when first acquiring its snapshot, after which it is able to run without the normal overhead of a j transaction and without any risk of contributing to or being canceled by a serialization failure. This 4 is well suited for long-running reports or backups.BThe transaction access mode determines whether the transaction is  or . ' is the default. When a transaction is /, the following SQL commands are disallowed: INSERT, UPDATE, DELETE, and  COPY FROMB if the table they would write to is not a temporary table; all CREATE, ALTER, and DROP commands; COMMENT, GRANT, REVOKE, TRUNCATE; and EXPLAIN ANALYZE and EXECUTEZ if the command they would execute is among those listed. This is a high-level notion of * that does not prevent all writes to disk.SThe SQL standard defines four levels of transaction isolation. The most strict is h, which is defined by the standard in a paragraph which says that any concurrent execution of a set of ; transactions is guaranteed to produce the same effect as running them one at a time in some order. The other three levels are defined in terms of phenomena, resulting from interaction between concurrent transactions, which must not occur at each level. The phenomena which are prohibited at various levels are: Dirty readK: A transaction reads data written by a concurrent uncommitted transaction.Nonrepeatable read: A transaction re-reads data it has previously read and finds that data has been modified by another transaction (that committed since the initial read). Phantom read: A transaction re-executes a query returning a set of rows that satisfy a search condition and finds that the set of rows satisfying the condition has changed due to another recently-committed transaction.Serialization anomaly: The result of successfully committing a group of transactions is inconsistent with all possible orderings of running those transactions one at a time.In PostgreSQL, you can request any of the four standard transaction isolation levels, but internally only three distinct isolation levels are implemented, i.e. PostgreSQL's  mode behaves like . This is because it is the only sensible way to map the standard isolation levels to PostgreSQL's multiversion concurrency control architecture.Dirty read is not possible. Nonrepeatable read is not possible. Phantom read is not possible. Serialization anomaly is not possible.Dirty read is not possible. Nonrepeatable read is not possible. Phantom read is not possible. Serialization anomaly is possible.{Dirty read is not possible. Nonrepeatable read is possible. Phantom read is possible. Serialization anomaly is possible.{Dirty read is not possible. Nonrepeatable read is possible. Phantom read is possible. Serialization anomaly is possible.>The available transaction characteristics are the transaction , the transaction  ( or  ), and the . #Run a schema invariant computation  . #Run a schema invariant computation   in . BEGIN a transaction. COMMIT a schema invariant transaction. ROLLBACK a schema invariant transaction."Run a schema changing computation ."Run a schema changing computation  in  DefaultMode. with a  ,   and  . with a  ,   and  @. This mode is well suited for long-running reports or backups.X Render a . Render an . Render an . Render a . run inside a transaction run inside a transaction          +Squeel export module(c) Eitan Chatav, 2017eitan@morphism.tech experimentalNone+ !"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmnpoqrstuvwxyz{|}~      !"#$%&'()*+,-./0123456789:;}~      !"#$%&'()*+,-./0XYZ[\]^_`abcdef      Squeal migrations(c) Eitan Chatav, 2017eitan@morphism.tech experimentalNone &',-<FST]bh The j for a Squeal migration.An ) is a type-aligned list or free category.!A !$ should contain an inverse pair of $ and % instructions and a unique #.#The # of a !. Each # in a ! should be unique.$The $ instruction of a !.%The % instruction of a !.&A & step.'Run !s by creating the @ if it does not exist and then in a transaction, for each each ! query to see if the !( is executed. If not, then execute the ! and insert its row in the .(Rewind !s by creating the @ if it does not exist and then in a transaction, for each each ! query to see if the !) is executed. If it is, then rewind the ! and delete its row in the .) Creates a  if it does not already exist.* Inserts a ! into the + Deletes a ! from the , Selects a ! from the /, returning the time at which it was executed.'migrations to run(migrations to rewind !"#$%&'()*+,!"#$%'( &)*+, !"#$% 7Y,-.,-/,01,234564574589:;9:<9:=9:>9:?9:@9:A9:B9:C9:D9:E9:F9:G9HIJKLJKMNOPQRSTUVWXYZ[\]^_`abcdefgghijklmnopqrstuvwxyz{|}~      !"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|}~$     % &  !"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxy z z { | } ~                                                                                  !#                  ! ! " # $ % & ' ( ) * + , - . / 0 1 2 3 4 5 6 7 8 9 : ; < = = > ? @ A B C D E F G HIJK,LM,LNOPQ,LR,ST,UV,WXOPY,LZ,'[O\],^_,0`aOPb4cd4ce f g h i j k9:l,mn9:o,mp9:q,rs,Lt,Lu,Lv,Lw,Lx,Ly,z{9:|}~,L 0squeal-postgresql-0.3.0.0-E9Ax8VffdgQ3ZC5pqeEIaASqueal.PostgreSQL.SchemaSqueal.PostgreSQL.DefinitionSqueal.PostgreSQL.ExpressionSqueal.PostgreSQL.PQSqueal.PostgreSQL.PoolSqueal.PostgreSQL.RenderSqueal.PostgreSQL.QuerySqueal.PostgreSQL.ManipulationSqueal.PostgreSQL.BinarySqueal.PostgreSQL.TransactionSqueal.PostgreSQL.MigrationSqueal.Postgresql.ManipulationwithSqueal.Postgresql.ExpressionrowalterTableRename renameColumn alterTable alterColumn dropTable dropColumn createTable addColumn FromClause Expressiondiv_mod_ Data.ListelemgroupSqueal.PostgreSQL.Manipulations ManipulationmanipulateParams queryParamstraversePreparedselect insertRowupdate Data.Maybe fromMaybeControl.Monad.State.Class MonadStateSqueal.PostgreSQLbaseGHC.OverloadedLabelsIsLabel fromLabelControl.Category>>> Data.Function&+generics-sop-0.3.2.0-6KSYi96kG7ZAyHbFGBJahbGenerics.SOP.NP:*NilNP/postgresql-libpq-0.9.4.1-F9x6exF7Cig8IUnzDOHpV3Database.PostgreSQL.LibPQResult SingleTuple FatalError NonfatalError BadResponseCopyBothCopyInCopyOutTuplesOk CommandOk EmptyQuery ExecStatusRow"Database.PostgreSQL.LibPQ.Internal Connection,resource-pool-0.2.3.2-3mL4NBsDPtq3vnzLVNeLLK Data.PooldestroyAllResourcesPool RenderSQL renderSQL parenthesized<+>commaSeparated doubleQuotedrenderCommaSeparatedrenderCommaSeparatedMaybe renderNatprintSQL RecordCodeOf FieldTypesOf FieldTypeOf FieldNamesOf FieldNameOfFieldsOfConstructorNamesOfConstructorNameOfConstructorsOfFieldTypesFromFieldNamesFrom CompositeFrom LabelsFromEnumFromPGPGlabel IsPGlabellabelWith SchemaType SchemumTypeTableViewTypedefDropIfConstraintsInvolveConstraintInvolvesNulls MapMaybesMaybesmaybesunMaybesRenameAlterDropCreateJoinNullifyRelationsNullifyRelation NullifyType NotAllNull AllNotNull SamePGType SameTypesPGTypeOf PGIntegral PGFloatingPGNumInElem IsQualified!HasAllHas HasUnique ZipAliasedZipAszipAs AliasesOfAliasedAsAlias GroupedByGrouping UngroupedGroupedTableToRelationTableToColumnsColumnsToRelation RelationsType NilRelation RelationType TableTypeUniquelyNilTableConstraintsTableConstraintsTableConstraintCheckUnique PrimaryKey ForeignKey ColumnsType ColumnTypeColumnConstraintDefNoDef::::=> NullityTypeNullNotNullHasOidoidPGTypePGboolPGint2PGint4PGint8 PGnumericPGfloat4PGfloat8PGchar PGvarcharPGtextPGbytea PGtimestamp PGtimestamptzPGdatePGtimePGtimetz PGintervalPGuuidPGinetPGjsonPGjsonb PGvararray PGfixarrayPGenum PGcomposite UnsafePGType renderAlias renderAliasesrenderAliasedAs renderLabel renderLabels$fHasOidPGjsonb$fHasOidPGjson$fHasOidPGinet$fHasOidPGuuid$fHasOidPGinterval$fHasOidPGtimetz$fHasOidPGtime$fHasOidPGdate$fHasOidPGtimestamptz$fHasOidPGtimestamp$fHasOidPGbytea$fHasOidPGtext$fHasOidPGvarchar$fHasOidPGchar$fHasOidPGfloat8$fHasOidPGfloat4$fHasOidPGnumeric$fHasOidPGint8$fHasOidPGint4$fHasOidPGint2$fHasOidPGbool$fGroupedBy[]relationcolumn:$fGroupedBy[]relationcolumn:0$fRenderSQLAlias$fIsLabelaliasNP$fIsLabelalias1Alias$fIsLabelalias0Aliased$fZipAliasedk::$fZipAliasedk[][]$fHaskindalias:field$fHaskindalias:field0$fHasAllk:fields:$fHasAllkind[]fields[]$fIsQualifiedtablecolumn(,)$fSamePGType(,)(,) $fMapMaybes: $fMapMaybes[]$fIsPGlabellabelPGlabel $fEqAlias$fGenericAlias $fOrdAlias $fShowAlias $fNFDataAlias $fOrdAliased $fEqAliased $fShowAliasedPGTypedpgtypeTypeExpressionUnsafeTypeExpressionrenderTypeExpressionPGAvgavg avgDistinct Condition HasParameter parameterUnsafeExpressionrenderExpressionparamnull_notNullcoalescefromNullisNull isNotNull matchNullnullIfarraygreatestleastunsafeBinaryOp unsafeUnaryOpunsafeFunctionatan2_castquot_rem_truncround_ceiling_truefalsenot_.&&.||caseWhenThenElse ifThenElse.==./=.>=.<.<=.> currentDate currentTimecurrentTimestamp localTimelocalTimestamplowerupper charLengthlikeunsafeAggregateunsafeAggregateDistinctsum_ sumDistinctbitAndbitOrbitAndDistinct bitOrDistinctboolAndboolOrboolAndDistinctboolOrDistinct countStarcount countDistinctevery everyDistinctmax_min_ maxDistinct minDistinctboolint2smallintint4intintegerint8bigintnumericfloat4realfloat8doublePrecisiontextchar charactervarcharcharacterVaryingbytea timestamptimestampWithTimeZonedatetimetimeWithTimeZoneintervaluuidinetjsonjsonbvararrayfixarray$fMonoidExpression$fSemigroupExpression$fIsStringExpression$fFloatingExpression$fFractionalExpression$fNumExpression$fMonoidExpression0$fSemigroupExpression0$fIsLabelfield(->)$fIsPGlabellabelExpression$fIsQualifiedrelationcolumnNP"$fIsQualifiedrelationcolumnAliased%$fIsQualifiedrelationcolumnExpression$fIsLabelcolumnNP$fIsLabelcolumnAliased$fIsLabelcolumnExpression$fIsQualifiedrelationcolumnNP0#$fIsQualifiedrelationcolumnAliased0&$fIsQualifiedrelationcolumnExpression0$fIsLabelcolumnNP0$fIsLabelcolumnAliased0$fIsLabelcolumnExpression0$fRenderSQLExpression!$fPGAvgPGTypePGintervalPGinterval$fPGAvgPGTypePGfloat8PGfloat8$fPGAvgPGTypePGfloat4PGfloat8$fPGAvgPGTypePGnumericPGnumeric$fPGAvgPGTypePGint8PGnumeric$fPGAvgPGTypePGint4PGnumeric$fPGAvgPGTypePGint2PGnumeric$fIsLabelaliasTypeExpression$fHasParameternschema:ty$fHasParameter1schema:ty1$fPGTypedschemaPGfixarray$fPGTypedschemaPGvararray$fPGTypedschemaPGjsonb$fPGTypedschemaPGjson$fPGTypedschemaPGuuid$fPGTypedschemaPGinterval$fPGTypedschemaPGtimetz$fPGTypedschemaPGtime$fPGTypedschemaPGdate$fPGTypedschemaPGtimestamptz$fPGTypedschemaPGtimestamp$fPGTypedschemaPGbytea$fPGTypedschemaPGvarchar$fPGTypedschemaPGchar$fPGTypedschemaPGtext$fPGTypedschemaPGfloat8$fPGTypedschemaPGfloat4$fPGTypedschemaPGnumeric$fPGTypedschemaPGint8$fPGTypedschemaPGint4$fPGTypedschemaPGint2$fPGTypedschemaPGbool$fGenericExpression$fShowExpression$fEqExpression$fOrdExpression$fNFDataExpression$fGenericTypeExpression$fShowTypeExpression$fEqTypeExpression$fOrdTypeExpression$fNFDataTypeExpressionSortExpressionAscDesc AscNullsFirst AscNullsLastDescNullsFirst DescNullsLast HavingClauseNoHavingHaving GroupByClauseNoGroupsGroupByBy2UnsafeFromClauserenderFromClauseTableExpression fromClause whereClause groupByClause havingClause orderByClause limitClause offsetClauseQuery UnsafeQuery renderQueryunionunionAll intersect intersectAllexcept exceptAllselectDistinct selectStarselectDistinctStar selectDotStarselectDistinctDotStarvaluesvalues_renderTableExpressionfromwhere_havingorderBylimitoffsettablesubqueryview crossJoin innerJoin leftOuterJoinrightOuterJoin fullOuterJoinrenderByrenderGroupByClauserenderHavingClauserenderSortExpression$fRenderSQLQuery$fGenericQuery $fShowQuery $fEqQuery $fOrdQuery $fNFDataQuery$fGenericFromClause$fShowFromClause$fEqFromClause$fOrdFromClause$fNFDataFromClause$fShowSortExpression$fOrdHavingClause$fEqHavingClause$fShowHavingClause$fOrdBy$fEqBy$fShowByConflictClauseOnConflictDoRaiseOnConflictDoNothingOnConflictDoUpdateReturningClause ReturningStar Returning ColumnValueSameDefaultSetUnsafeManipulationrenderManipulationqueryStatement insertRows insertRows_ insertRow_ insertQuery insertQuery_renderReturningClauserenderConflictClauseupdate_ deleteFrom deleteFrom_$fRenderSQLManipulation$fGenericManipulation$fShowManipulation$fEqManipulation$fOrdManipulation$fNFDataManipulationColumnTypeExpressionUnsafeColumnTypeExpressionrenderColumnTypeExpression AlterColumnUnsafeAlterColumnrenderAlterColumn AddColumn AlterTableUnsafeAlterTablerenderAlterTableOnUpdateClauseOnUpdateNoActionOnUpdateRestrictOnUpdateCascadeOnDeleteClauseOnDeleteNoActionOnDeleteRestrictOnDeleteCascade ForeignKeyedTableConstraintExpressionUnsafeTableConstraintExpressionrenderTableConstraintExpression DefinitionUnsafeDefinitionrenderDefinitioncreateTableIfNotExistscheckunique primaryKey foreignKeyrenderOnDeleteClauserenderOnUpdateClause addConstraintdropConstraint setDefault dropDefault setNotNull dropNotNull alterType createViewdropViewcreateTypeEnumcreateTypeEnumFromcreateTypeCompositecreateTypeCompositeFromdropTypenullable notNullabledefault_serial2 smallserialserial4serialserial8 bigserial$fCategory[]Definition$fRenderSQLDefinition$fNFDataOnDeleteClause$fNFDataOnUpdateClause$fAddColumn(,)$fAddColumn(,)0$fGenericDefinition$fShowDefinition$fEqDefinition$fOrdDefinition$fNFDataDefinition"$fGenericTableConstraintExpression$fShowTableConstraintExpression$fEqTableConstraintExpression$fOrdTableConstraintExpression!$fNFDataTableConstraintExpression$fGenericOnDeleteClause$fShowOnDeleteClause$fEqOnDeleteClause$fOrdOnDeleteClause$fGenericOnUpdateClause$fShowOnUpdateClause$fEqOnUpdateClause$fOrdOnUpdateClause$fGenericAlterTable$fShowAlterTable$fEqAlterTable$fOrdAlterTable$fNFDataAlterTable$fGenericAlterColumn$fShowAlterColumn$fEqAlterColumn$fOrdAlterColumn$fNFDataAlterColumn$fGenericColumnTypeExpression$fShowColumnTypeExpression$fEqColumnTypeExpression$fOrdColumnTypeExpression$fNFDataColumnTypeExpressionOnlyfromOnlyFromRowfromRowFromColumnValuefromColumnValue FromValue fromValueToParamstoParams ToColumnParam toColumnParamToParamtoParam$fToParamxPGenum$fToParamVectorPGvararray$fToParamValuePGjsonb$fToParamValuePGjson$fToParamDiffTimePGinterval$fToParamUTCTimePGtimestamptz$fToParamLocalTimePGtimestamp$fToParam(,)PGtimetz$fToParamTimeOfDayPGtime$fToParamDayPGdate$fToParamByteStringPGbytea$fToParamByteStringPGbytea0$fToParamTextPGtext$fToParamTextPGtext0$fToParamCharPGchar$fToParamNetAddrPGinet$fToParamUUIDPGuuid$fToParamScientificPGnumeric$fToParamDoublePGfloat8$fToParamFloatPGfloat4$fToParamWord64PGint8$fToParamInt64PGint8$fToParamWord32PGint4$fToParamInt32PGint4$fToParamWord16PGint2$fToParamInt16PGint2$fToParamBoolPGbool$fHasAliasedOid(,)$fToAliasedParamx(,)$fToParamxPGcomposite$fToColumnParamMaybeNull$fToColumnParamxNotNull$fToParamsxtys$fFromValuePGenumy$fFromValuePGfixarrayVector$fFromValuePGvararrayVector$fFromValuePGjsonbValue$fFromValuePGjsonValue$fFromValuePGintervalDiffTime$fFromValuePGtimestamptzUTCTime$fFromValuePGtimestampLocalTime$fFromValuePGtimetz(,)$fFromValuePGtimeTimeOfDay$fFromValuePGdateDay$fFromValuePGbyteaByteString$fFromValuePGbyteaByteString0$fFromValuePGtextText$fFromValuePGtextText0$fFromValuePGcharChar$fFromValuePGinetNetAddr$fFromValuePGuuidUUID$fFromValuePGnumericScientific$fFromValuePGfloat8Double$fFromValuePGfloat4Float$fFromValuePGint8Int64$fFromValuePGint4Int32$fFromValuePGint2Int16$fFromValuePGboolBool$fFromAliasedValue(,)y$fFromValuePGcompositey$fFromColumnValue(,)Maybe$fFromColumnValue(,)y$fFromRowresultsy$fHasDatatypeInfoOnly $fGenericOnly $fFunctorOnly$fFoldableOnly$fTraversableOnly$fEqOnly $fOrdOnly $fReadOnly $fShowOnly$fGenericOnly0PQRunMonadPQ manipulaterunQueryParamsrunQuery forPreparedtraversePrepared_ forPrepared_liftPQIndexedMonadTransPQpqAppqJoinpqBindpqThen pqAndThenpqEmbeddefinePQunPQ connectdbfinishwithConnectionlowerConnectionrunPQexecPQevalPQ pqliftWithgetRownextRowgetRowsfirstRow liftResultntuples resultStatusresultErrorMessage$fMonadBaseControlbPQ$fMonadBasebPQ $fMMonadPQ$fMonadTransPQ$fMFunctorTYPEPQ $fFunctorPQ $fMonadPQ$fApplicativePQ$fIndexedMonadTransPQPQ$fMonadPQschemaListT$fMonadPQschemaContT$fMonadPQschemaRWST$fMonadPQschemaRWST0$fMonadPQschemaExceptT$fMonadPQschemaMaybeT$fMonadPQschemaWriterT$fMonadPQschemaWriterT0$fMonadPQschemaStateT$fMonadPQschemaStateT0$fMonadPQschemaReaderT$fMonadPQschemaIdentityT$fMonadPQschemaPQ PoolPQRunPoolPQ runPoolPQcreateConnectionPoolpoolpqliftWith$fMonadBaseControlbPoolPQ$fMonadPQschemaPoolPQ$fMonadBasebPoolPQ$fMonadTransPoolPQ $fMonadPoolPQ$fApplicativePoolPQ$fFunctorPoolPQDeferrableMode Deferrable NotDeferrable AccessMode ReadWriteReadOnlyIsolationLevel SerializableRepeatableRead ReadCommittedReadUncommittedTransactionModeisolationLevel accessModedeferrableModetransactionallytransactionally_begincommitrollbacktransactionallySchematransactionallySchema_ defaultModelongRunningModerenderIsolationLevelrenderAccessModerenderDeferrableMode$fShowIsolationLevel$fEqIsolationLevel$fShowAccessMode$fEqAccessMode$fShowDeferrableMode$fEqDeferrableMode$fShowTransactionMode$fEqTransactionModeMigrationsTable AlignedListDone:>> Migrationnameupdownsingle migrateUp migrateDowncreateMigrationsinsertMigrationdeleteMigrationselectMigration$fCategorykAlignedListbytestring-0.10.8.2Data.ByteString.Internal ByteStringGHC.BaseMaybeNothingghc-prim GHC.TypesNat++GHC.Real Fractional GHC.FloatFloatingGHC.NumNumSymbolJustmaybe GHC.Classesmin GHC.TypeNats+CategoryrenderCreationTypeGenerics.SOP.UniverseGenericHasDatatypeInfoFromAliasedValuefromAliasedValueToAliasedParamtoAliasedParam HasAliasedOid aliasedOid execParamsData.Traversabletraverseprepare Traversable execPrepared Data.FoldableFoldableFunctorMonad<*>join=<<>> Control.Monad<=<exec,monad-control-1.0.2.3-2muMHtg8mYx8DwPZ9oyBonControl.Monad.Trans.ControlMonadBaseControl0transformers-base-0.4.5.2-14ebPDzvJw8768EoQRz2cGControl.Monad.Base MonadBasetransformers-0.5.2.0Control.Monad.Trans.Class MonadTrans ApplicativerenderTransactionMode