!8ty      !"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|}~      !"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|}~      !"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|}~                                                                                              !"#$%&'()*+,-./0123456789:;<=>?@ABCD E F G H I J K L M N O P Q R S T U V W X 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 Rendering helper functions(c) Eitan Chatav, 2017eitan@morphism.tech experimentalNone,<DFQV9 squeal-postgresqlA class for rendering SQLsqueal-postgresqlParenthesize a y.squeal-postgresqlConcatenate two ys with a space between.squeal-postgresqlComma separate a list of ys.squeal-postgresqlAdd double quotes around a y.squeal-postgresqlAdd single quotes around a z$ and escape single quotes within it.squeal-postgresqlAdd single quotes around a y$ and escape single quotes within it.squeal-postgresql6Comma separate the renderings of a heterogeneous list. squeal-postgresqlComma separate the {/ renderings of a heterogeneous list, dropping |s.!squeal-postgresqlRender a promoted }."squeal-postgresql Print SQL.  !"  !"-Embedding of PostgreSQL type and alias system(c) Eitan Chatav, 2017eitan@morphism.tech experimentalNone&'+,-068;<=>?AFQSTVit#squeal-postgresqlIs a type a valid JSON type?$squeal-postgresqlIs a type a valid JSON key?%squeal-postgresqleInspect the code of an algebraic datatype and ensure it's a product, otherwise generate a type error&squeal-postgresqlCalculate the types of fields.'squeal-postgresql :kind! FieldTypeOf (Maybe Int16)#FieldTypeOf (Maybe Int16) :: PGType = 'PGint2(squeal-postgresqlCalculate the names of fields.)squeal-postgresqlCalculate the name of a field.*squeal-postgresql#Calculate the fields of a datatype.+squeal-postgresql,Calculate the names of nullary constructors.,squeal-postgresqlPCalculates the name of a nullary constructor, otherwise generates a type error.-squeal-postgresql&Calculates constructors of a datatype..squeal-postgresqlNdata Row = Row { a :: Maybe Int16, b :: Maybe LocalTime } deriving GHC.Genericinstance Generic Rowinstance HasDatatypeInfo Row:kind! FieldTypesFrom RowFieldTypesFrom Row :: [PGType]= '['PGint2, 'PGtimestamp]/squeal-postgresqlNdata Row = Row { a :: Maybe Int16, b :: Maybe LocalTime } deriving GHC.Genericinstance Generic Rowinstance HasDatatypeInfo Row:kind! FieldNamesFrom Row&FieldNamesFrom Row :: [Type.FieldName] = '["a", "b"]0squeal-postgresqlThe 0i 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 3 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)]1squeal-postgresqlThe 1A 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"]2squeal-postgresqlThe 2_ 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"]3squeal-postgresqlThe 3G type family embeds a subset of Haskell types as Postgres basic types.:kind! PG LocalTimePG LocalTime :: PGType= 'PGtimestamp4squeal-postgresqlA 4 unit type with an 6 instance6squeal-postgresql6 looks very much like the ' class. Whereas the overloaded label, ! is used for column references, 7s are used for enum terms. A 77 is called with type application like `label @"beef"`.8squeal-postgresqlUsed in  .9squeal-postgresqlFThe schema of a database consists of a list of aliased, user-defined :s.:squeal-postgresqlA :" is a user-defined type, either a ;, < or =.>squeal-postgresql Drop all ys that involve a column?squeal-postgresql Check if a y involves a column@squeal-postgresql@ is used to construct a  of a composite type.Asqueal-postgresqlA4 is used in the binary instances of composite types.Esqueal-postgresqlRename alias0 alias1 xs replaces the alias alias0 by alias1 in xs and is used in  and .Fsqueal-postgresqlAlter alias x xs& replaces the type associated with an alias in xs with the type x and is used in  and .Gsqueal-postgresql Drop alias xs" removes the type associated with alias in xs and is used in  statements and in  ALTER TABLE  statements.Hsqueal-postgresqlCreate alias x xs adds  alias ::: x to the end of xs and is used in  statements and in  ALTER TABLE .Isqueal-postgresqlI is simply promoted ~ and is used in JOINs in s.Jsqueal-postgresqlJ drops the column constraints.Ksqueal-postgresqlK9 drops the nullity constraints of its argument relations.Lsqueal-postgresqlL# is an idempotent that nullifies a rE used to nullify the left or right hand side of an outer join in a .Msqueal-postgresqlM# is an idempotent that nullifies a ~.Nsqueal-postgresqlN# is an idempotent that nullifies a .Osqueal-postgresqlO is a constraint that proves a ~ has some NOT NULL.Psqueal-postgresqlP is a constraint that proves a ~ has no NULLs.Qsqueal-postgresql&Equality constraint on the underlying  of two columns.Rsqueal-postgresqlR! is a constraint that proves two ~%s have the same length and the same s.Ssqueal-postgresqlS forgets about NULL and any column constraints.Tsqueal-postgresql<Ensure a type is a valid array type whose elements are text.Usqueal-postgresqlAEnsure a type is a valid array type with a specific element type.Vsqueal-postgresql$Ensure a type is a valid array type.squeal-postgresqlhError message helper for displaying unavailable/unknown/placeholder type variables whose kind is known.Wsqueal-postgresqlW is a constraint on  whose s have  and  functions.Xsqueal-postgresqlX is a constraint on  whose s have  and  constraints.Ysqueal-postgresqlY is a constraint on  whose  s have a  constraint.Zsqueal-postgresqlIn x xs" is a constraint that proves that x is in xs.[squeal-postgresqlElem is a promoted .\squeal-postgresql Analagous to , the constraint \ defines ]0 for a column alias qualified by a table alias.^squeal-postgresql^ extends _ to take lists of aliases and fields and infer a list of  subfields._squeal-postgresqlHas alias fields field# is a constraint that proves that fields has a field of alias ::: field , inferring field from alias and fields.`squeal-postgresqlHasUnique alias fields field# is a constraint that proves that fields is a singleton of alias ::: field.asqueal-postgresqlThe a+ class provides a type family for zipping W lists together with arbitrary lists of the same size, with an associated type family b, together with a method c$ for zipping heterogeneous lists of iTes together with a heterogeneous list of expressions into a heterogeneous list of g expressions.dsqueal-postgresqld retains the AliasesOf in a row.esqueal-postgresqlThe e$ class provides a way to scrap your  s in an  list of g expressions.gsqueal-postgresqlThe h) operator is used to name an expression. h is like a demoted version of .8Just "hello" `As` #hi :: Aliased Maybe ("hi" ::: String)As (Just "hello") Aliasisqueal-postgresqli*es are proxies for a type level string or  and have an  instance so that with -XOverloadedLabels:set -XOverloadedLabels#foobar :: Alias "foobar"Aliasksqueal-postgresqlA kf 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.lsqueal-postgresqll( is an auxiliary namespace, created by GROUP BY clauses (%), and used for typesafe aggregationmsqueal-postgresqlno aggregation permittednsqueal-postgresql8aggregation required for any column which is not groupedosqueal-postgresqlConvert a table to a relation.psqueal-postgresqlp removes table constraints.qsqueal-postgresqlq removes column constraints.rsqueal-postgresqlr is a row of ts, thought of as a product.ssqueal-postgresqlA monokinded empty t.tsqueal-postgresqlt is a row of :{0type family PersonRelation :: RelationType where PersonRelation =) '[ "name" ::: 'NotNull 'PGtext) , "age" ::: 'NotNull 'PGint4) , "dateOfBirth" ::: 'Null 'PGdate ]:}usqueal-postgresqluN 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 ]:}vsqueal-postgresqlA }+ must reference columns that either are a | or form a { constraint.wsqueal-postgresqlA monokinded empty x.xsqueal-postgresqlA x is a row of ys.ysqueal-postgresqlyD encodes various forms of data constraints of columns in a table. ys 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.~squeal-postgresql~ is a row of s.:{-type family UsersColumns :: ColumnsType where UsersColumns =- '[ "name" ::: 'NoDef :=> 'NotNull 'PGtext- , "id" ::: 'Def :=> 'NotNull 'PGint4 ]:}squeal-postgresql 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 'PGtextsqueal-postgresql 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.squeal-postgresqlDEFAULT% is available for inserts and updatessqueal-postgresqlDEFAULT' is unavailable for inserts and updatessqueal-postgresqlThe alias operator  is like a promoted version of h4, a type level pair between an alias and some type.squeal-postgresqlThe constraint operator, S is a type level pair between a "constraint" and some type, for use in pairing a  with a  to produce a  or a x and a ~ to produce a u.squeal-postgresql: 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) :: NullityTypesqueal-postgresqlNULL may be presentsqueal-postgresqlNULL is absentsqueal-postgresqlThe object identifier of a .:set -XTypeApplications oid @'PGbool16squeal-postgresql. is the promoted datakind of PostgreSQL types.import Squeal.PostgreSQL.Schema :kind 'PGbool'PGbool :: PGTypesqueal-postgresqllogical Boolean (true/false)squeal-postgresqlsigned two-byte integersqueal-postgresqlsigned four-byte integersqueal-postgresqlsigned eight-byte integersqueal-postgresql arbitrary precision numeric typesqueal-postgresql0single precision floating-point number (4 bytes)squeal-postgresql0double precision floating-point number (8 bytes)squeal-postgresqlfixed-length character stringsqueal-postgresql variable-length character stringsqueal-postgresql variable-length character stringsqueal-postgresqlbinary data ("byte array")squeal-postgresqldate and time (no time zone)squeal-postgresql"date and time, including time zonesqueal-postgresql calendar date (year, month, day)squeal-postgresqltime of day (no time zone)squeal-postgresql time of day, including time zonesqueal-postgresql time spansqueal-postgresqluniversally unique identifiersqueal-postgresqlIPv4 or IPv6 host addresssqueal-postgresqltextual JSON datasqueal-postgresqlbinary JSON data, decomposedsqueal-postgresqlvariable length arraysqueal-postgresqlfixed length arraysqueal-postgresql0an escape hatch for unsupported PostgreSQL typessqueal-postgresqlrenderAlias #jimbob "\"jimbob\""squeal-postgresqlrenderAliasString #ohmahgerd "'ohmahgerd'"squeal-postgresqlimport Generics.SOP (NP(..))!renderAliases (#jimbob :* #kandi)["\"jimbob\"","\"kandi\""]squeal-postgresql=let renderMaybe = fromString . maybe "Nothing" (const "Just")8renderAliasedAs renderMaybe (Just (3::Int) `As` #an_int)"Just AS \"an_int\""squeal-postgresqlRenders a labelsqueal-postgresqlRenders a list of labels#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxy{z|}~~tsru:;<=9y{z|}xwvijghefdabc_`^\]6745lmnkI8HGFE[ZYWXSUVTRQPONMLqpoKJ?>#$3210/.-,+*)('&%ABCD@]9 67Squeal expressions(c) Eitan Chatav, 2017eitan@morphism.tech experimentalNone+,-6;<=>?ADFKQSTV]i7גsqueal-postgresql is a demoted version of a squeal-postgresqls are used in s and  createTable commands.squeal-postgresqlA constraint for 3s that you can take averages of and the resulting .squeal-postgresqlA  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 .squeal-postgresqlA 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.squeal-postgresql takes a } using type application and a .Ylet expr = parameter @1 int4 :: Expression sch rels grp '[ 'Null 'PGint4] ('Null 'PGint4) printSQL expr ($1 :: int4)squeal-postgresqlGs 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.squeal-postgresql takes a }7 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)squeal-postgresql analagous to |printSQL null_NULLsqueal-postgresql analagous to printSQL $ notNull trueTRUEsqueal-postgresql+return the leftmost value which is not NULL/printSQL $ coalesce [null_, notNull true] falseCOALESCE(NULL, TRUE, FALSE)squeal-postgresql analagous to '( using COALESCEprintSQL $ fromNull true null_COALESCE(NULL, TRUE)squeal-postgresqlprintSQL $ null_ & isNull NULL IS NULLsqueal-postgresqlprintSQL $ null_ & isNotNullNULL IS NOT NULLsqueal-postgresql analagous to  using IS NULL$printSQL $ matchNull true not_ null_4CASE WHEN NULL IS NULL THEN TRUE ELSE (NOT NULL) ENDsqueal-postgresqlright 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))squeal-postgresql5printSQL $ array [null_, notNull false, notNull true]ARRAY[NULL, FALSE, TRUE]squeal-postgresqlA 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]glet i = row (0 `as` #real :* 1 `as` #imaginary) :: Expression '[] '[] 'Ungrouped '[] ('NotNull Complex) printSQL i ROW(0, 1)squeal-postgresqllet expr = greatest currentTimestamp [param @1] :: Expression sch rels grp '[ 'NotNull 'PGtimestamptz] ('NotNull 'PGtimestamptz) printSQL expr=GREATEST(CURRENT_TIMESTAMP, ($1 :: timestamp with time zone))squeal-postgresql)printSQL $ least currentTimestamp [null_]LEAST(CURRENT_TIMESTAMP, NULL)squeal-postgresql)printSQL $ unsafeBinaryOp "OR" true false(TRUE OR FALSE)squeal-postgresql#printSQL $ unsafeUnaryOp "NOT" true (NOT TRUE)squeal-postgresql"printSQL $ unsafeFunction "f" truef(TRUE)squeal-postgresql'Helper for defining variadic functions.squeal-postgresql:{letO expression :: Expression schema relations grouping params (nullity 'PGfloat4) expression = atan2_ pi 2in printSQL expression:}atan2(pi(), 2)squeal-postgresqlprintSQL $ true & cast int4(TRUE :: int4)squeal-postgresql&integer division, truncates the result:{letM expression :: Expression schema relations grouping params (nullity 'PGint2) expression = 5 `quot_` 2in printSQL expression:}(5 / 2)squeal-postgresqlremainder upon integer division:{letM expression :: Expression schema relations grouping params (nullity 'PGint2) expression = 5 `rem_` 2in printSQL expression:}(5 % 2)squeal-postgresql:{letO expression :: Expression schema relations grouping params (nullity 'PGfloat4) expression = trunc piin printSQL expression:} trunc(pi())squeal-postgresql:{letO expression :: Expression schema relations grouping params (nullity 'PGfloat4) expression = round_ piin printSQL expression:} round(pi())squeal-postgresql:{letO expression :: Expression schema relations grouping params (nullity 'PGfloat4) expression = ceiling_ piin printSQL expression:} ceiling(pi())squeal-postgresql printSQL trueTRUEsqueal-postgresqlprintSQL falseFALSEsqueal-postgresqlprintSQL $ not_ true (NOT TRUE)squeal-postgresqlprintSQL $ true .&& false(TRUE AND FALSE)squeal-postgresqlprintSQL $ true .|| false(TRUE OR FALSE)squeal-postgresql:{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 ENDsqueal-postgresql:{letM expression :: Expression schema relations grouping params (nullity 'PGint2)" expression = ifThenElse true 1 0in printSQL expression:} CASE WHEN TRUE THEN 1 ELSE 0 END squeal-postgresqlComparison operations like  ,  , ,  ,   and   will produce NULLs if one of their arguments is NULL.!printSQL $ notNull true .== null_ (TRUE = NULL) squeal-postgresql!printSQL $ notNull true ./= null_(TRUE <> NULL) squeal-postgresql!printSQL $ notNull true .>= null_(TRUE >= NULL) squeal-postgresql printSQL $ notNull true .< null_ (TRUE < NULL) squeal-postgresql!printSQL $ notNull true .<= null_(TRUE <= NULL)squeal-postgresql printSQL $ notNull true .> null_ (TRUE > NULL)squeal-postgresqlprintSQL currentDate CURRENT_DATEsqueal-postgresqlprintSQL currentTime CURRENT_TIMEsqueal-postgresqlprintSQL currentTimestampCURRENT_TIMESTAMPsqueal-postgresqlprintSQL localTime LOCALTIMEsqueal-postgresqlprintSQL localTimestampLOCALTIMESTAMPsqueal-postgresqlprintSQL $ lower "ARRRGGG"lower(E'ARRRGGG')squeal-postgresqlprintSQL $ upper "eeee"upper(E'eeee')squeal-postgresqlprintSQL $ charLength "four"char_length(E'four')squeal-postgresqlThe  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%')squeal-postgresql8Get JSON value (object field or array element) at a key.squeal-postgresqlAGet JSON value (object field or array element) at a key, as text.squeal-postgresql#Get JSON value at a specified path.squeal-postgresql+Get JSON value at a specified path as text.squeal-postgresqlUDoes the left JSON value contain the right JSON path/value entries at the top level?squeal-postgresql]Are the left JSON path/value entries contained at the top level within the right JSON value?squeal-postgresql?Does the string exist as a top-level key within the JSON value?squeal-postgresql6Do any of these array strings exist as top-level keys? squeal-postgresql6Do all of these array strings exist as top-level keys?!squeal-postgresqlDDelete a key or keys from a JSON object, or remove an array element.If the right operand is.. text  : Delete key3value pair or string element from left operand. Key2value pairs are matched based on their key value. text[] ~: Delete multiple key/value pairs or string elements from left operand. Key/value pairs are matched based on their key value. integer : Delete the array element with specified index (Negative integers count from the end). Throws an error if top level container is not an array."squeal-postgresqlhDelete the field or element with specified path (for JSON arrays, negative integers count from the end)#squeal-postgresqlLiteral binary JSON$squeal-postgresql Literal JSON%squeal-postgresqlReturns the value as json. Arrays and composites are converted (recursively) to arrays and objects; otherwise, if there is a cast from the type to json, the cast function will be used to perform the conversion; otherwise, a scalar value is produced. For any scalar type other than a number, a Boolean, or a null value, the text representation will be used, in such a fashion that it is a valid json value.&squeal-postgresqlReturns the value as jsonb. Arrays and composites are converted (recursively) to arrays and objects; otherwise, if there is a cast from the type to json, the cast function will be used to perform the conversion; otherwise, a scalar value is produced. For any scalar type other than a number, a Boolean, or a null value, the text representation will be used, in such a fashion that it is a valid jsonb value.'squeal-postgresqlgReturns the array as a JSON array. A PostgreSQL multidimensional array becomes a JSON array of arrays.(squeal-postgresql!Returns the row as a JSON object.)squeal-postgresqlTBuilds a possibly-heterogeneously-typed JSON array out of a variadic argument list.*squeal-postgresql]Builds a possibly-heterogeneously-typed (binary) JSON array out of a variadic argument list.+squeal-postgresqlBuilds a possibly-heterogeneously-typed JSON object out of a variadic argument list. The elements of the argument list must alternate between text and values.,squeal-postgresqlBuilds a possibly-heterogeneously-typed (binary) JSON object out of a variadic argument list. The elements of the argument list must alternate between text and values.-squeal-postgresql&Builds a JSON object out of a text array. The array must have either exactly one dimension with an even number of members, in which case they are taken as alternating key/value pairs, or two dimensions such that each inner array has exactly two elements, which are taken as a key/value pair..squeal-postgresql-Builds a binary JSON object out of a text array. The array must have either exactly one dimension with an even number of members, in which case they are taken as alternating key/value pairs, or two dimensions such that each inner array has exactly two elements, which are taken as a key/value pair./squeal-postgresqlThis is an alternate form of -k that takes two arrays; one for keys and one for values, that are zipped pairwise to create a JSON object.0squeal-postgresqlThis is an alternate form of -s that takes two arrays; one for keys and one for values, that are zipped pairwise to create a binary JSON object.1squeal-postgresql;Returns the number of elements in the outermost JSON array.2squeal-postgresqlBReturns the number of elements in the outermost binary JSON array.3squeal-postgresqlMReturns JSON value pointed to by the given path (equivalent to #> operator).4squeal-postgresqlMReturns JSON value pointed to by the given path (equivalent to #> operator).5squeal-postgresqlVReturns JSON value pointed to by the given path (equivalent to #> operator), as text.6squeal-postgresqlVReturns JSON value pointed to by the given path (equivalent to #> operator), as text.7squeal-postgresql1Returns set of keys in the outermost JSON object.8squeal-postgresql1Returns set of keys in the outermost JSON object.9squeal-postgresqlReturns the type of the outermost JSON value as a text string. Possible types are object, array, string, number, boolean, and null.:squeal-postgresqlReturns the type of the outermost binary JSON value as a text string. Possible types are object, array, string, number, boolean, and null.;squeal-postgresqllReturns its argument with all object fields that have null values omitted. Other null values are untouched.<squeal-postgresqllReturns its argument with all object fields that have null values omitted. Other null values are untouched.=squeal-postgresql . jsonbSet target path new_value create_missing2Returns target with the section designated by path replaced by new_value, or with new_value added if create_missing is true ( default is true) and the item designated by path does not exist. As with the path orientated operators, negative integers that appear in path count from the end of JSON arrays.>squeal-postgresql / jsonbInsert target path new_value insert_afterReturns target with new_value inserted. If target section designated by path is in a JSONB array, new_value will be inserted before target or after if insert_after is true (default is false). If target section designated by path is in JSONB object, new_value will be inserted only if target does not exist. As with the path orientated operators, negative integers that appear in path count from the end of JSON arrays.?squeal-postgresql+Returns its argument as indented JSON text.@squeal-postgresql*escape hatch to define aggregate functionsAsqueal-postgresql?escape hatch to define aggregate functions over distinct valuesBsqueal-postgresql:{lets expression :: Expression schema '[tab ::: '["col" ::: 'Null 'PGnumeric]] ('Grouped bys) params ('Null 'PGnumeric) expression = sum_ #colin printSQL expression:} sum("col")Csqueal-postgresql:{letw expression :: Expression schema '[tab ::: '["col" ::: nullity 'PGnumeric]] ('Grouped bys) params (nullity 'PGnumeric) expression = sumDistinct #colin printSQL expression:}sum(DISTINCT "col")Dsqueal-postgresql:{letp expression :: Expression schema '[tab ::: '["col" ::: nullity 'PGint4]] (Grouped bys) params (nullity 'PGint4) expression = bitAnd #colin printSQL expression:}bit_and("col")Esqueal-postgresql:{letp expression :: Expression schema '[tab ::: '["col" ::: nullity 'PGint4]] (Grouped bys) params (nullity 'PGint4) expression = bitOr #colin printSQL expression:} bit_or("col")Fsqueal-postgresql:{letp expression :: Expression schema '[tab ::: '["col" ::: nullity 'PGint4]] (Grouped bys) params (nullity 'PGint4)" expression = bitAndDistinct #colin printSQL expression:}bit_and(DISTINCT "col")Gsqueal-postgresql:{letp expression :: Expression schema '[tab ::: '["col" ::: nullity 'PGint4]] (Grouped bys) params (nullity 'PGint4)! expression = bitOrDistinct #colin printSQL expression:}bit_or(DISTINCT "col")Hsqueal-postgresql:{letp expression :: Expression schema '[tab ::: '["col" ::: nullity 'PGbool]] (Grouped bys) params (nullity 'PGbool) expression = boolAnd #colin printSQL expression:}bool_and("col")Isqueal-postgresql:{letp expression :: Expression schema '[tab ::: '["col" ::: nullity 'PGbool]] (Grouped bys) params (nullity 'PGbool) expression = boolOr #colin printSQL expression:}bool_or("col")Jsqueal-postgresql:{letp expression :: Expression schema '[tab ::: '["col" ::: nullity 'PGbool]] (Grouped bys) params (nullity 'PGbool)# expression = boolAndDistinct #colin printSQL expression:}bool_and(DISTINCT "col")Ksqueal-postgresql:{letp expression :: Expression schema '[tab ::: '["col" ::: nullity 'PGbool]] (Grouped bys) params (nullity 'PGbool)" expression = boolOrDistinct #colin printSQL expression:}bool_or(DISTINCT "col")Lsqueal-postgresql4A special aggregation that does not require an inputprintSQL countStarcount(*)Msqueal-postgresql:{letl expression :: Expression schema '[tab ::: '["col" ::: nullity ty]] (Grouped bys) params ('NotNull 'PGint8) expression = count #colin printSQL expression:} count("col")Nsqueal-postgresql:{letl expression :: Expression schema '[tab ::: '["col" ::: nullity ty]] (Grouped bys) params ('NotNull 'PGint8)! expression = countDistinct #colin printSQL expression:}count(DISTINCT "col")Osqueal-postgresql synonym for H:{letp expression :: Expression schema '[tab ::: '["col" ::: nullity 'PGbool]] (Grouped bys) params (nullity 'PGbool) expression = every #colin printSQL expression:} every("col")Psqueal-postgresql synonym for J:{letp expression :: Expression schema '[tab ::: '["col" ::: nullity 'PGbool]] (Grouped bys) params (nullity 'PGbool)! expression = everyDistinct #colin printSQL expression:}every(DISTINCT "col")Qsqueal-postgresqlminimum and maximum aggregationRsqueal-postgresqlminimum and maximum aggregationSsqueal-postgresqlminimum and maximum aggregationTsqueal-postgresqlminimum and maximum aggregationUsqueal-postgresqllogical Boolean (true/false)Vsqueal-postgresqlsigned two-byte integerWsqueal-postgresqlsigned two-byte integerXsqueal-postgresqlsigned four-byte integerYsqueal-postgresqlsigned four-byte integerZsqueal-postgresqlsigned four-byte integer[squeal-postgresqlsigned eight-byte integer\squeal-postgresqlsigned eight-byte integer]squeal-postgresql arbitrary precision numeric type^squeal-postgresql0single precision floating-point number (4 bytes)_squeal-postgresql0single precision floating-point number (4 bytes)`squeal-postgresql0double precision floating-point number (8 bytes)asqueal-postgresql0double precision floating-point number (8 bytes)bsqueal-postgresql variable-length character stringcsqueal-postgresqlfixed-length character stringdsqueal-postgresqlfixed-length character stringesqueal-postgresql variable-length character stringfsqueal-postgresql variable-length character stringgsqueal-postgresqlbinary data ("byte array")hsqueal-postgresqldate and time (no time zone)isqueal-postgresql"date and time, including time zonejsqueal-postgresql calendar date (year, month, day)ksqueal-postgresqltime of day (no time zone)lsqueal-postgresql time of day, including time zonemsqueal-postgresql time spannsqueal-postgresqluniversally unique identifierosqueal-postgresqlIPv4 or IPv6 host addresspsqueal-postgresqltextual JSON dataqsqueal-postgresqlbinary JSON data, decomposedrsqueal-postgresqlvariable length arrayssqueal-postgresqlfixed length array/renderTypeExpression (fixarray (Proxy @2) json) "json[2]"tsqueal-postgresql4Concatenate two jsonb values into a new jsonb value.8squeal-postgresqlwhat to averagesqueal-postgresqlwhat to averagesqueal-postgresqlparamsqueal-postgresqlNULLs may be presentsqueal-postgresqlNULL is absentsqueal-postgresqlwhat to convert NULL tosqueal-postgresql possibly NULLsqueal-postgresql possibly NULLsqueal-postgresqlwhat to convert NULL tosqueal-postgresqlfunction to perform when NULL is absentsqueal-postgresqlNULL is absentsqueal-postgresqlNULL is absentsqueal-postgresqlarray elementssqueal-postgresql1zero or more expressions for the row field valuessqueal-postgresqlneeds at least 1 argumentsqueal-postgresqlor moresqueal-postgresqlneeds at least 1 argumentsqueal-postgresqlor moresqueal-postgresqloperatorsqueal-postgresqloperatorsqueal-postgresqlfunctionsqueal-postgresqlfunctionsqueal-postgresql numeratorsqueal-postgresql denominatorsqueal-postgresqltype to cast assqueal-postgresqlvalue to convertsqueal-postgresql numeratorsqueal-postgresql denominatorsqueal-postgresql numeratorsqueal-postgresql denominatorsqueal-postgresqlfractional numbersqueal-postgresqlfractional numbersqueal-postgresqlfractional numbersqueal-postgresqlwhens and thenssqueal-postgresqlelsesqueal-postgresqlthensqueal-postgresqlelse squeal-postgresqllhssqueal-postgresqlrhs squeal-postgresqllhssqueal-postgresqlrhs squeal-postgresqllhssqueal-postgresqlrhs squeal-postgresqllhssqueal-postgresqlrhs squeal-postgresqllhssqueal-postgresqlrhssqueal-postgresqllhssqueal-postgresqlrhssqueal-postgresqlstring to lower casesqueal-postgresqlstring to upper casesqueal-postgresqlstring to measuresqueal-postgresqlstringsqueal-postgresqlpattern@squeal-postgresqlaggregate functionAsqueal-postgresqlaggregate functionBsqueal-postgresql what to sumCsqueal-postgresql what to sumDsqueal-postgresqlwhat to aggregateEsqueal-postgresqlwhat to aggregateFsqueal-postgresqlwhat to aggregateGsqueal-postgresqlwhat to aggregateHsqueal-postgresqlwhat to aggregateIsqueal-postgresqlwhat to aggregateJsqueal-postgresqlwhat to aggregateKsqueal-postgresqlwhat to aggregateMsqueal-postgresql what to countNsqueal-postgresql what to countOsqueal-postgresqlwhat to aggregatePsqueal-postgresqlwhat to aggregateQsqueal-postgresqlwhat to aggregateRsqueal-postgresqlwhat to aggregateSsqueal-postgresqlwhat to aggregateTsqueal-postgresqlwhat to aggregate#$UV      !"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrs     VU$# !"$#%&'()*+,-./0123456789:;<=>?@ABCDEHIFGJKLMNOPQSRTUVWXYZ[\]^_`abcdefghijklmnopqrs 4 4 4 4 44Squeal queries(c) Eitan Chatav, 2017eitan@morphism.tech experimentalNone&'+,-06;<=>?FKQSTV]I@squeal-postgresqls 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.squeal-postgresqlA ; is used to eliminate groups that are not of interest. An m  may only use  while a n  must use % whose conditions are combined with .squeal-postgresqlA  indicates the l of a . A  indicates m while a  indicates n. 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.squeal-postgresqls are used in group 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.squeal-postgresqlA ? can be a table name, or a derived table such as a subquery, a JOIN- construct, or complex combinations of these.squeal-postgresqlThe type of a jsonb_each_text .squeal-postgresqlThe type of a json_each_text .squeal-postgresqlThe type of a  jsonb_each .squeal-postgresqlThe type of a  json_each .squeal-postgresqlA 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.squeal-postgresqlVA table reference that can be a table name, or a derived table such as a subquery, a JOIN- construct, or complex combinations of these.squeal-postgresql)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.squeal-postgresqlThe  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.squeal-postgresql"If a table has been grouped using 0, 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).squeal-postgresqlThe . 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.squeal-postgresqlThe  is combined with  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).squeal-postgresqlThe  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.squeal-postgresqlVThe 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 = select* ((#col1 + #col2) `as` #sum :* #col1) ( 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 =* select (sum_ #col2 `as` #sum :* #col1)& ( from (table (#tab `as` #table1)) & groupBy #col1* & 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 )# ( 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")squeal-postgresqlDThe results of two queries can be combined using the set operation  . Duplicate rows are eliminated.squeal-postgresqlDThe results of two queries can be combined using the set operation 2, the disjoint union. Duplicate rows are retained.squeal-postgresqlDThe results of two queries can be combined using the set operation 2, the intersection. Duplicate rows are eliminated.squeal-postgresqlDThe results of two queries can be combined using the set operation 0, the intersection. Duplicate rows are retained.squeal-postgresqlDThe results of two queries can be combined using the set operation 4, the set difference. Duplicate rows are eliminated.squeal-postgresqlDThe results of two queries can be combined using the set operation 2, the set difference. Duplicate rows are retained.squeal-postgresqlthe  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.squeal-postgresqlvAfter the select list has been processed, the result table can be subject to the elimination of duplicate rows using .squeal-postgresqlThe simplest kind of query is = which emits all columns that the table expression produces.squeal-postgresqlA U emits all columns that the table expression produces and eliminates duplicate rows.squeal-postgresqlrWhen working with multiple tables, it can also be useful to ask for all the columns of a particular table, using .squeal-postgresqlA P asks for all the columns of a particular table, and eliminates duplicate rows.squeal-postgresql 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]Glet query = values (1 `as` #a :* "one" `as` #b) [] :: Query '[] '[] RowprintSQL query2SELECT * FROM (VALUES (1, E'one')) AS t ("a", "b")squeal-postgresqlK computes a row value or set of row values specified by value expressions.squeal-postgresql Render a squeal-postgresqlA  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 , group, , ,  and  , using the K operator to match the left-to-right sequencing of their placement in SQL.squeal-postgresqlA  is an endomorphism of (s which adds a search condition to the .squeal-postgresqlA  is a transformation of s which switches its l from m to n. Use  group Nil/ to perform a "grand total" aggregation query.squeal-postgresqlA  is an endomorphism of (s which adds a search condition to the .squeal-postgresqlAn  is an endomorphism of 1s which appends an ordering to the right of the .squeal-postgresqlA  is an endomorphism of s which adds to the .squeal-postgresqlAn  is an endomorphism of s which adds to the .squeal-postgresql@Expands the outermost JSON object into a set of key/value pairs.squeal-postgresqlGExpands the outermost binary JSON object into a set of key/value pairs.squeal-postgresql@Expands the outermost JSON object into a set of key/value pairs.squeal-postgresqlGExpands the outermost binary JSON object into a set of key/value pairs.squeal-postgresqleExpands the JSON expression to a row whose columns match the record type defined by the given table.squeal-postgresqllExpands the binary JSON expression to a row whose columns match the record type defined by the given table.squeal-postgresqlExpands the outermost array of objects in the given JSON expression to a set of rows whose columns match the record type defined by the given table.squeal-postgresqlExpands the outermost array of objects in the given binary JSON expression to a set of rows whose columns match the record type defined by the given table.squeal-postgresqlBuilds an arbitrary record from a JSON object. As with all functions returning record, the caller must explicitly define the structure of the record with an AS clause.squeal-postgresqlBuilds an arbitrary record from a binary JSON object. As with all functions returning record, the caller must explicitly define the structure of the record with an AS clause.squeal-postgresqlBuilds an arbitrary set of records from a JSON array of objects (see note below). As with all functions returning record, the caller must explicitly define the structure of the record with an AS clause.squeal-postgresqlBuilds an arbitrary set of records from a binary JSON array of objects (see note below). As with all functions returning record, the caller must explicitly define the structure of the record with an AS clause.squeal-postgresqlA real  is a table from the schema.squeal-postgresql derives a table from a .squeal-postgresql derives a table from a <.squeal-postgresqlleft & 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.squeal-postgresqlleft & innerJoin right on&. The joined table is filtered by the on condition.squeal-postgresqlleft & 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.squeal-postgresqlleft & 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.squeal-postgresqlleft & 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.squeal-postgresql Renders a .squeal-postgresql Renders a .squeal-postgresql Render a .squeal-postgresql Render a .squeal-postgresql select listsqueal-postgresqlintermediate virtual tablesqueal-postgresql select listsqueal-postgresqlintermediate virtual tablesqueal-postgresqlintermediate virtual tablesqueal-postgresqlintermediate virtual tablesqueal-postgresqlparticular virtual subtablesqueal-postgresqlintermediate virtual tablesqueal-postgresqlparticular virtual tablesqueal-postgresqlintermediate virtual tablesqueal-postgresql]When more than one row is specified, all the rows must must have the same number of elementssqueal-postgresqlone row of valuessqueal-postgresqltable referencesqueal-postgresqlfiltering conditionsqueal-postgresqlgrouped columnssqueal-postgresqlhaving conditionsqueal-postgresqlsort expressionssqueal-postgresqllimit parametersqueal-postgresqloffset parametersqueal-postgresqlrightsqueal-postgresqlleftsqueal-postgresqlrightsqueal-postgresqlon conditionsqueal-postgresqlleftsqueal-postgresqlrightsqueal-postgresqlon conditionsqueal-postgresqlleftsqueal-postgresqlrightsqueal-postgresqlon conditionsqueal-postgresqlleftsqueal-postgresqlrightsqueal-postgresqlon conditionsqueal-postgresqlleftOO!Squeal data manipulation language(c) Eitan Chatav, 2017eitan@morphism.tech experimentalNone&',-6<FKQSTV]squeal-postgresqlA > 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.squeal-postgresqlA  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."squeal-postgresql",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.&squeal-postgresqlA & 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 =< insertRow_ #tab (Set 2 `as` #col1 :* Default `as` #col2)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_ #tab> (Set (param @1) `as` #col1 :* Set (param @2) `as` #col2)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 =; insertRow #tab (Set 2 `as` #col1 :* Default `as` #col2): OnConflictDoRaise (Returning (#col1 `as` #fromOnly))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 #tab, (Set 2 `as` #col1 :* Set 4 `as` #col2), [Set 6 `as` #col1 :* Set 8 `as` #col2] (OnConflictDoUpdate- (Set 2 `as` #col1 :* Same `as` #col2) [#col1 .== #col2])- (Returning $ (#col1 + #col2) `as` #sum)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 =6 update_ #tab (Set 2 `as` #col1 :* Same `as` #col2) (#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 *)squeal-postgresql Convert a  into a &.*squeal-postgresqlInsert 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.+squeal-postgresqlInsert a single row.,squeal-postgresqlInsert multiple rows returning # and raising an error on conflicts.-squeal-postgresqlInsert a single row returning # and raising an error on conflicts..squeal-postgresql Insert a ./squeal-postgresql Insert a  returning # and raising an error on conflicts.0squeal-postgresql Render a .1squeal-postgresql Render a .2squeal-postgresqlAn 2] command changes the values of the specified columns in all rows that satisfy the condition.3squeal-postgresqlUpdate a row returning .4squeal-postgresqlDelete rows of a table.5squeal-postgresqlDelete rows returning .6squeal-postgresql6 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 = withO (deleteFrom #products (#date .< param @1) ReturningStar `as` #deleted_rows)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" *squeal-postgresqltable to insert intosqueal-postgresql row to insertsqueal-postgresqlmore rows to insertsqueal-postgresql)what to do in case of constraint conflictsqueal-postgresqlresults to return+squeal-postgresqltable to insert intosqueal-postgresql row to insertsqueal-postgresql)what to do in case of constraint conflictsqueal-postgresqlresults to return,squeal-postgresqltable to insert intosqueal-postgresql row to insertsqueal-postgresqlmore rows to insert-squeal-postgresqltable to insert intosqueal-postgresql row to insert.squeal-postgresqltable to insert intosqueal-postgresql)what to do in case of constraint conflictsqueal-postgresqlresults to return/squeal-postgresqltable to insert into2squeal-postgresqltable to updatesqueal-postgresql%modified values to replace old valuessqueal-postgresql0condition under which to perform update on a rowsqueal-postgresqlresults to return3squeal-postgresqltable to updatesqueal-postgresql%modified values to replace old valuessqueal-postgresql0condition under which to perform update on a row4squeal-postgresqltable to delete fromsqueal-postgresql%condition under which to delete a rowsqueal-postgresqlresults to return5squeal-postgresqltable to delete fromsqueal-postgresql%condition under which to delete a row6squeal-postgresqlcommon table expressions !"%$#&'()*+,-./0123456&'()"%$# !*+,-./0123456Squeal data definition language(c) Eitan Chatav, 2017eitan@morphism.tech experimentalNone&'+,-6;<=>?FKQSTV]i5=squeal-postgresql=s are used in W commands.@squeal-postgresqlAn @8 describes the alteration to perform on a single column.Csqueal-postgresqlAn C is either NULL or has DEFAULT.Dsqueal-postgresqlDS 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;Esqueal-postgresqlAn E@ describes the alteration to perform on the columns of a table.Hsqueal-postgresql Analagous to L there is also HA which is invoked when a referenced column is changed (updated).Isqueal-postgresql[if any referencing rows has not changed when the constraint is checked, an error is raisedJsqueal-postgresql#prevents update of a referenced rowKsqueal-postgresql\the updated values of the referenced column(s) should be copied into the referencing row(s)Lsqueal-postgresqlL= indicates what to do with rows that reference a deleted row.Msqueal-postgresqlWif any referencing rows still exist when the constraint is checked, an error is raisedNsqueal-postgresql%prevents deletion of a referenced rowOsqueal-postgresqlospecifies that when a referenced row is deleted, row(s) referencing it should be automatically deleted as wellPsqueal-postgresqlHA constraint synonym between types involved in a foreign key constraint.Qsqueal-postgresqlData 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. ys 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.Tsqueal-postgresqlA TA is a statement that changes the schema of the database, like a W, _, or ` command. Ts may be composed using the  operator.Wsqueal-postgresqlW adds a table to the schema.:set -XOverloadedLabels:{type Table = '[] :=>% '[ "a" ::: 'NoDef :=> 'Null 'PGint4) , "b" ::: 'NoDef :=> 'Null 'PGfloat4 ]:}:{let3 setup :: Definition '[] '["tab" ::: 'Table Table] setup = createTable #tab7 (nullable int `as` #a :* nullable real `as` #b) Nilin printSQL setup:}1CREATE TABLE "tab" ("a" int NULL, "b" real NULL);Xsqueal-postgresqlX 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. XH fixes this. Interestingly, this property makes it an idempotent in the  of Ts.*:set -XOverloadedLabels -XTypeApplications:{type Table = '[] :=>% '[ "a" ::: 'NoDef :=> 'Null 'PGint4) , "b" ::: 'NoDef :=> 'Null 'PGfloat4 ]:}'type Schema = '["tab" ::: 'Table Table]:{let# setup :: Definition Schema Schema% setup = createTableIfNotExists #tab7 (nullable int `as` #a :* nullable real `as` #b) Nilin printSQL setup:}?CREATE TABLE IF NOT EXISTS "tab" ("a" int NULL, "b" real NULL);Ysqueal-postgresqlA Y constraint is the most generic ys 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 )4 ( check (#a :* #b) (#a .> #b) `as` #inequality ):}printSQL definitioneCREATE TABLE "tab" ("a" int NOT NULL, "b" int NOT NULL, CONSTRAINT "inequality" CHECK (("a" > "b")));Zsqueal-postgresqlA Zy 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 )& ( unique (#a :* #b) `as` #uq_a_b ):}printSQL definitionWCREATE TABLE "tab" ("a" int NULL, "b" int NULL, CONSTRAINT "uq_a_b" UNIQUE ("a", "b"));[squeal-postgresqlA [ 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 )" ( primaryKey #id `as` #pk_id ):}printSQL definition^CREATE TABLE "tab" ("id" serial, "name" text NOT NULL, CONSTRAINT "pk_id" PRIMARY KEY ("id"));\squeal-postgresqlA \ 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 )* ( primaryKey #id `as` #pk_users ) >>> createTable #emails ( serial `as` #id :*+ (int & notNullable) `as` #user_id :*& (text & nullable) `as` #email )( ( primaryKey #id `as` #pk_emails :*% foreignKey #user_id #users #id; OnDeleteCascade OnUpdateCascade `as` #fk_user_id )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 :*/ (integer & nullable) `as` #employer_id )+ ( primaryKey #id `as` #employees_pk :*- foreignKey #employer_id #employees #idF OnDeleteCascade OnUpdateCascade `as` #employees_employer_fk )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);]squeal-postgresqlRender L.^squeal-postgresqlRender H._squeal-postgresql_! removes a table from the schema.:{let: definition :: Definition '["muh_table" ::: 'Table t] '[]# definition = dropTable #muh_table:}printSQL definitionDROP TABLE "muh_table";`squeal-postgresql`3 changes the definition of a table from the schema.asqueal-postgresqla- changes the name of a table from the schema.%printSQL $ alterTableRename #foo #bar"ALTER TABLE "foo" RENAME TO "bar";bsqueal-postgresqlAn b adds a table constraint.:{let definition :: DefinitionJ '["tab" ::: 'Table ('[] :=> '["col" ::: 'NoDef :=> 'NotNull 'PGint4])]g '["tab" ::: 'Table ('["positive" ::: Check '["col"]] :=> '["col" ::: 'NoDef :=> 'NotNull 'PGint4])]Q definition = alterTable #tab (addConstraint #positive (check #col (#col .> 0)))in printSQL definition:}@ALTER TABLE "tab" ADD CONSTRAINT "positive" CHECK (("col" > 0));csqueal-postgresqlA c 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";dsqueal-postgresqlA d 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";esqueal-postgresqlA e 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";fsqueal-postgresqlAn f alters a single column.gsqueal-postgresqlA g 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;hsqueal-postgresqlA h( 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;isqueal-postgresqlA i 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;jsqueal-postgresqlA j 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;ksqueal-postgresqlAn k 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;lsqueal-postgresqlCreate 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 =: createView #bc (select (#b :* #c) (from (table #abc)))in printSQL definition:}FCREATE VIEW "bc" AS SELECT "b" AS "b", "c" AS "c" FROM "abc" AS "abc";msqueal-postgresql 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";nsqueal-postgresql'Enumerated types are created using the n command, for exampleOprintSQL $ createTypeEnum #mood (label @"sad" :* label @"ok" :* label @"happy")2CREATE TYPE "mood" AS ENUM ('sad', 'ok', 'happy');osqueal-postgresqlGEnumerated 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');psqueal-postgresqlpg creates a composite type. The composite type is specified by a list of attribute names and data types.Ptype PGcomplex = 'PGcomposite '["real" ::: 'PGfloat8, "imaginary" ::: 'PGfloat8]:{let= setup :: Definition '[] '["complex" ::: 'Typedef PGcomplex]& setup = createTypeComposite #complex1 (float8 `as` #real :* float8 `as` #imaginary)in printSQL setup:}=CREATE TYPE "complex" AS ("real" float8, "imaginary" float8);qsqueal-postgresqlFComposite 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);rsqueal-postgresql 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";ssqueal-postgresqlused in W/ commands as a column constraint to note that NULL may be present in a columntsqueal-postgresqlused in W, commands as a column constraint to ensure NULL is not present in a columnusqueal-postgresqlused in W2 commands as a column constraint to give a defaultvsqueal-postgresqlgnot a true type, but merely a notational convenience for creating unique identifier columns with type wsqueal-postgresqlgnot a true type, but merely a notational convenience for creating unique identifier columns with type xsqueal-postgresqlgnot a true type, but merely a notational convenience for creating unique identifier columns with type ysqueal-postgresqlgnot a true type, but merely a notational convenience for creating unique identifier columns with type zsqueal-postgresqlgnot a true type, but merely a notational convenience for creating unique identifier columns with type {squeal-postgresqlgnot a true type, but merely a notational convenience for creating unique identifier columns with type Dsqueal-postgresql column to addsqueal-postgresqltype of the new columnWsqueal-postgresqlthe name of the table to addsqueal-postgresql%the names and datatype of each columnsqueal-postgresql(constraints that must hold for the tableXsqueal-postgresqlthe name of the table to addsqueal-postgresql%the names and datatype of each columnsqueal-postgresql(constraints that must hold for the tablesqueal-postgresqlthe name of the table to addsqueal-postgresql%the names and datatype of each columnsqueal-postgresql(constraints that must hold for the tableYsqueal-postgresql0specify the subcolumns which are getting checkedsqueal-postgresql a closed  on those subcolumnsZsqueal-postgresql9specify subcolumns which together are unique for each row[squeal-postgresql9specify the subcolumns which together form a primary key.\squeal-postgresqlcolumn or columns in the tablesqueal-postgresqlreference tablesqueal-postgresql2reference column or columns in the reference tablesqueal-postgresql$what to do when reference is deletedsqueal-postgresql$what to do when reference is updated_squeal-postgresqltable to remove`squeal-postgresqltable to altersqueal-postgresqlalteration to performasqueal-postgresqltable to renamesqueal-postgresqlwhat to rename itbsqueal-postgresqlconstraint to addcsqueal-postgresqlconstraint to dropdsqueal-postgresqlcolumn to removeesqueal-postgresqlcolumn to renamesqueal-postgresqlwhat to rename the columnfsqueal-postgresqlcolumn to altersqueal-postgresqlalteration to performgsqueal-postgresqldefault value to setlsqueal-postgresqlthe name of the view to addsqueal-postgresqlquerymsqueal-postgresqlview to removensqueal-postgresql(name of the user defined enumerated typesqueal-postgresqllabels of the enumerated typeosqueal-postgresql(name of the user defined enumerated typepsqueal-postgresql'name of the user defined composite typesqueal-postgresql&list of attribute names and data typesqsqueal-postgresql'name of the user defined composite typersqueal-postgresqlname of the user defined type@=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{@TUVWXQRSYZ[\PLMNO]HIJK^_`aEFGbcCDdef@ABghijklmnopqr=>?stuvwxyz{ Binary encoding and decoding(c) Eitan Chatav, 2017eitan@morphism.tech experimentalNone&',-3456;<=>?FSTV]i0 squeal-postgresqlA is a 1-tuple type, useful for encoding a single parameter with ! 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"}squeal-postgresqlA D constraint generically sequences the parsings of the columns of a t 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.squeal-postgresql :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"}squeal-postgresqlA  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.squeal-postgresql(: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})squeal-postgresqlA C constraint gives a parser from the binary format of a PostgreSQL  into a Haskell .squeal-postgresql0newtype Id = Id { getId :: Int16 } deriving ShowCinstance FromValue 'PGint2 Id where fromValue = fmap Id . fromValuesqueal-postgresqlA 3 constraint generically sequences the encodings of 2s of the fields of a tuple or record to a row of 's. You should not define instances of . Instead define " instances which in turn provide  instances.squeal-postgresql1type 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") :* Nilsqueal-postgresqlA  constraint lifts the  encoding of a  to a  , encoding {s to 's. You should not define instances of ", just use the provided instances.squeal-postgresql*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 Nothingsqueal-postgresqlA + constraint gives an encoding of a Haskell . into into the binary format of a PostgreSQL .squeal-postgresql#: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"PQ monad(c) Eitan Chatav, 2017eitan@morphism.tech experimentalNone,-7;<=>?AFQSTVizsqueal-postgresqlA snapshot of the state of a  computation.squeal-postgresql is an mtl style constraint, similar to )* , for using LibPQ to  runs a &# with params from a type with a  constraint. It calls # 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  and @ but provides an optimization by preparing the statement with  and then traversing a  container with 9. The temporary prepared statement is then deallocated. is a flipped  is like  but works on  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.squeal-postgresqlAn  (https://bentnib.org/paramnotions-jfp.pdfAtkey indexed monad is a   /https://ncatlab.org/nlab/show/enriched+categoryenriched category-. An indexed monad transformer transforms a  into an indexed monad. And, A is a class for indexed monad transformers that support running Ts using  7 and embedding a computation in a larger schema using  .squeal-postgresqlindexed analog of squeal-postgresqlindexed analog of  squeal-postgresqlindexed analog of  squeal-postgresqlindexed analog of flipped  squeal-postgresqlindexed analog of  squeal-postgresql.Safely embed a computation in a larger schema. squeal-postgresqlRun a T with $, we expect that libpq obeys the law Sdefine statement1 & pqThen (define statement2) = define (statement1 >>> statement2)squeal-postgresqlKWe keep track of the schema via an Atkey indexed state monad transformer, .squeal-postgresql.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!squeal-postgresql$Closes the connection to the server.squeal-postgresqlDo  and  before and after a computation.squeal-postgresqlSafely  to a smaller schema.squeal-postgresqlRun a  and keep the result and the  Connection.squeal-postgresql Execute a % and discard the result but keep the  Connection.squeal-postgresql Evaluate a  and discard the  Connection but keep the result.squeal-postgresqlHelper function in defining  instance for .squeal-postgresql5Get a row corresponding to a given row number from a <, throwing an exception if the row number is out of bounds.squeal-postgresql: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 |>, otherwise returning the row along with the next row number.squeal-postgresqlGet all rows from a .squeal-postgresql%Get the first row if possible from a .squeal-postgresqlLifts actions on results from LibPQ.squeal-postgresql8Returns the number of rows (tuples) in the query result.squeal-postgresql)Returns the result status of the command. squeal-postgresqlUReturns the error message most recently generated by an operation on the connection. squeal-postgresql*, 2 or 4squeal-postgresql and friendssqueal-postgresql and friendssqueal-postgresql*, 2, or 4 , and friendssqueal-postgresql*, 2 or 4squeal-postgresql*, 2 or 4squeal-postgresql*, 2 or 4squeal-postgresqlconninfosqueal-postgresql row numbersqueal-postgresqlresultsqueal-postgresqltotal number of rowssqueal-postgresqlresultsqueal-postgresql row numbersqueal-postgresqlresultsqueal-postgresqlresult4       4       Pooled connections(c) Eitan Chatav, 2017eitan@morphism.tech experimentalNone,-3;<=>?FQTV 7squeal-postgresqlA snapshot of the state of a 8 computation.8squeal-postgresql8 schema% should be a drop-in replacement for   schema schema.4Typical use case would be to create your pool using ;< and run anything that requires the pool connection with it.Here's a simplified example: #type Schema = '[ "tab" ::: 'Table ('[] :=> '["col" ::: 'NoDef :=> 'NotNull 'PGint2])] someQuery :: Manipulation Schema '[ 'NotNull 'PGint2] '[] someQuery = insertRow #tab (Set (param @1) `As` #col :* Nil) OnConflictDoNothing (Returning Nil) insertOne :: (MonadBaseControl IO m, MonadPQ Schema m) => m () insertOne = void $ manipulateParams someQuery . Only $ (1 :: Int16) insertOneInPool :: ByteString -> IO () insertOneInPool connectionString = do pool <- createConnectionPool connectionString 1 0.5 10 liftIO $ runPoolPQ (insertOne) pool;squeal-postgresqlCreate 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.<squeal-postgresqlHelper function in defining  instance for 8.=squeal-postgresql instance for 8.>squeal-postgresql instance for 8.?squeal-postgresql instance for 8.@squeal-postgresql instance for 8.Asqueal-postgresql instance for 8.Bsqueal-postgresql instance for 8.;squeal-postgresqlThe 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 .squeal-postgresql[The number of stripes (distinct sub-pools) to maintain. The smallest acceptable value is 1.squeal-postgresqlAmount 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.squeal-postgresqlMaximum 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.789:;<89:;7< #Squeal transaction control language(c) Eitan Chatav, 2017eitan@morphism.tech experimentalNone<]GDsqueal-postgresqlThe ED transaction property has no effect unless the transaction is also K and I. 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 Kj 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.Gsqueal-postgresqlBThe transaction access mode determines whether the transaction is H or I. H' is the default. When a transaction is I/, 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 I* that does not prevent all writes to disk.Jsqueal-postgresqlSThe SQL standard defines four levels of transaction isolation. The most strict is Kh, which is defined by the standard in a paragraph which says that any concurrent execution of a set of K; 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 N mode behaves like M. This is because it is the only sensible way to map the standard isolation levels to PostgreSQL's multiversion concurrency control architecture.Ksqueal-postgresqlDirty read is not possible. Nonrepeatable read is not possible. Phantom read is not possible. Serialization anomaly is not possible.Lsqueal-postgresqlDirty read is not possible. Nonrepeatable read is not possible. Phantom read is not possible. Serialization anomaly is possible.Msqueal-postgresql{Dirty read is not possible. Nonrepeatable read is possible. Phantom read is possible. Serialization anomaly is possible.Nsqueal-postgresql{Dirty read is not possible. Nonrepeatable read is possible. Phantom read is possible. Serialization anomaly is possible.Osqueal-postgresql>The available transaction characteristics are the transaction J, the transaction G (H or I ), and the D.Tsqueal-postgresql#Run a schema invariant computation T.Usqueal-postgresql#Run a schema invariant computation U in [.Vsqueal-postgresqlBEGIN a transaction.Wsqueal-postgresqlCOMMIT a schema invariant transaction.Xsqueal-postgresqlROLLBACK a schema invariant transaction.Ysqueal-postgresql"Run a schema changing computation Y.Zsqueal-postgresql"Run a schema changing computation Z in  DefaultMode.[squeal-postgresqlO with a K J, H G and F D.\squeal-postgresqlO with a K J, I G and E D@. This mode is well suited for long-running reports or backups.squeal-postgresql Render a O.]squeal-postgresql Render an J.^squeal-postgresql Render an G._squeal-postgresql Render a D.Tsqueal-postgresqlrun inside a transactionUsqueal-postgresqlrun inside a transactionDFEGIHJKLMNOPQRSTUVWXYZ[\]^_TUVWXYZOPQRS[\JKLMN]GIH^DFE_+Squeel export module(c) Eitan Chatav, 2017eitan@morphism.tech experimentalNone0 #$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxy{z|}~      !"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrs !"%$#&'()*+,-./0123456=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{      DFEGIHJKLMNOPQRSTUVWXYZ[\]^_ Squeal migrations(c) Eitan Chatav, 2017eitan@morphism.tech experimentalNone &',-<FST]ci hsqueal-postgresqlThe u for a Squeal migration.isqueal-postgresqlAn i) is a type-aligned list or free category.lsqueal-postgresqlA l$ should contain an inverse pair of o and p instructions and a unique n.nsqueal-postgresqlThe n of a l. Each n in a l should be unique.osqueal-postgresqlThe o instruction of a l.psqueal-postgresqlThe p instruction of a l.qsqueal-postgresqlA q step.rsqueal-postgresqlRun ls by creating the h@ if it does not exist and then in a transaction, for each each l query to see if the l( is executed. If not, then execute the l and insert its row in the h.ssqueal-postgresqlRewind ls by creating the h@ if it does not exist and then in a transaction, for each each l query to see if the l) is executed. If it is, then rewind the l and delete its row in the h.tsqueal-postgresql Creates a h if it does not already exist.usqueal-postgresql Inserts a l into the hvsqueal-postgresql Deletes a l from the hwsqueal-postgresql Selects a l from the h/, returning the time at which it was executed.rsqueal-postgresqlmigrations to runssqueal-postgresqlmigrations to rewindhijklmnopqrstuvwlmnoprsijkqhtuvwk7,-.,-/,01,234564574589:;9:<9:=9:>9:?9:@9:A9:B9:C9:D9:E9:F9:G9HIJKLJKMNOPQRSTUVWXYZ[\]^_`abcdefghijkklmnopqrstuvwxyz{|}~      !"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|}~     $ !"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTU VWXY%Z[\]^_&`ab cdefghijklmnopqrstuvwxyz{|}~                                                                                        ! !"##$%&'()*+,-.//0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXXYZ[\]^_`ab c d e f g h i j k l m n n o p q r s t u v w x y z { | } ~                        ,,,,,,,,',,0449:,9:,9:,,,,,,,,9:, 0squeal-postgresql-0.3.2.0-C1DUTRQBZ7xFTzLk0tObU0Squeal.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-5JX38dNigUk7e65oSELmomGenerics.SOP.NP:*NilNP/postgresql-libpq-0.9.4.1-HmQUg7WTong1815HjPkViUDatabase.PostgreSQL.LibPQResult SingleTuple FatalError NonfatalError BadResponseCopyBothCopyInCopyOutTuplesOk CommandOk EmptyQuery ExecStatusRow"Database.PostgreSQL.LibPQ.Internal Connection,resource-pool-0.2.3.2-3Rr84yej0EZEpb7PEm3Z9a Data.PooldestroyAllResourcesPool RenderSQL renderSQL parenthesized<+>commaSeparated doubleQuotedsingleQuotedTextsingleQuotedUtf8renderCommaSeparatedrenderCommaSeparatedMaybe renderNatprintSQLPGjson_ PGjsonKey RecordCodeOf FieldTypesOf FieldTypeOf FieldNamesOf FieldNameOfFieldsOfConstructorNamesOfConstructorNameOfConstructorsOfFieldTypesFromFieldNamesFrom CompositeFrom LabelsFromEnumFromPGPGlabel IsPGlabellabelWith SchemaType SchemumTypeTableViewTypedefDropIfConstraintsInvolveConstraintInvolvesNulls MapMaybesMaybesmaybesunMaybesRenameAlterDropCreateJoinRelationToNullityTypesRelationToRowTypeNullifyRelationsNullifyRelation NullifyType NotAllNull AllNotNull SamePGType SameTypesPGTypeOf PGtextArray PGarrayOfPGarray PGIntegral PGFloatingPGNumInElem IsQualified!HasAllHas HasUnique ZipAliasedZipAszipAs AliasesOf AliasableasAliasedAsAlias GroupedByGrouping UngroupedGroupedTableToRelationTableToColumnsColumnsToRelation RelationsType NilRelation RelationType TableTypeUniquelyNilTableConstraintsTableConstraintsTableConstraintCheckUnique PrimaryKey ForeignKey ColumnsType ColumnTypeColumnConstraintDefNoDef::::=> NullityTypeNullNotNullHasOidoidPGTypePGboolPGint2PGint4PGint8 PGnumericPGfloat4PGfloat8PGchar PGvarcharPGtextPGbytea PGtimestamp PGtimestamptzPGdatePGtimePGtimetz PGintervalPGuuidPGinetPGjsonPGjsonb PGvararray PGfixarrayPGenum PGcomposite UnsafePGType renderAliasrenderAliasString 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$fAliasablealiasexpressionNP!$fAliasablealiasexpressionAliased$fZipAliasedk::$fZipAliasedk[][]$fHaskindalias:field$fHaskindalias:field0$fHasAllk:fields:$fHasAllkind[]fields[]$fIsQualifiedtablecolumn(,)$fSamePGType(,)(,) $fMapMaybes: $fMapMaybes[]$fIsPGlabellabelNP$fIsPGlabellabelPGlabel $fEqAlias$fGenericAlias $fOrdAlias $fShowAlias $fNFDataAlias $fOrdAliased $fEqAliased $fShowAliasedPGTypedpgtypeTypeExpressionUnsafeTypeExpressionrenderTypeExpressionPGAvgavg avgDistinct Condition HasParameter parameterUnsafeExpressionrenderExpressionparamnull_notNullcoalescefromNullisNull isNotNull matchNullnullIfarraygreatestleastunsafeBinaryOp unsafeUnaryOpunsafeFunctionunsafeVariadicFunctionatan2_castquot_rem_truncround_ceiling_truefalsenot_.&&.||caseWhenThenElse ifThenElse.==./=.>=.<.<=.> currentDate currentTimecurrentTimestamp localTimelocalTimestamplowerupper charLengthlike.->.->>.#>.#>>.@>.<@.?.?|.?&.-.#-.jsonbLitjsonLittoJsontoJsonb arrayToJson rowToJsonjsonBuildArrayjsonbBuildArrayjsonBuildObjectjsonbBuildObject jsonObject jsonbObject jsonZipObjectjsonbZipObjectjsonArrayLengthjsonbArrayLengthjsonExtractPathjsonbExtractPathjsonExtractPathAsTextjsonbExtractPathAsTextjsonObjectKeysjsonbObjectKeys jsonTypeof jsonbTypeofjsonStripNullsjsonbStripNullsjsonbSet jsonbInsert jsonbPrettyunsafeAggregateunsafeAggregateDistinctsum_ sumDistinctbitAndbitOrbitAndDistinct bitOrDistinctboolAndboolOrboolAndDistinctboolOrDistinct countStarcount countDistinctevery everyDistinctmax_min_ maxDistinct minDistinctboolint2smallintint4intintegerint8bigintnumericfloat4realfloat8doublePrecisiontextchar charactervarcharcharacterVaryingbytea timestamptimestampWithTimeZonedatetimetimeWithTimeZoneintervaluuidinetjsonjsonbvararrayfixarray$fSemigroupExpression$fMonoidExpression$fSemigroupExpression0$fIsStringExpression$fFloatingExpression$fFractionalExpression$fNumExpression$fMonoidExpression0$fSemigroupExpression1$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 GroupByClauseNoGroupsGroupByBy1By2UnsafeFromClauserenderFromClause PGjsonb_each PGjson_eachTableExpression fromClause whereClause groupByClause havingClause orderByClause limitClause offsetClauseQuery UnsafeQuery renderQueryunionunionAll intersect intersectAllexcept exceptAllselectDistinct selectStarselectDistinctStar selectDotStarselectDistinctDotStarvaluesvalues_renderTableExpressionfromwhere_groupByhavingorderBylimitoffsetjsonEach jsonbEachjsonEachAsTextjsonbEachAsTextjsonPopulateRecordAsjsonbPopulateRecordAsjsonPopulateRecordSetAsjsonbPopulateRecordSetAsjsonToRecordAsjsonbToRecordAsjsonToRecordSetAsjsonbToRecordSetAstablesubqueryview crossJoin innerJoin leftOuterJoinrightOuterJoin fullOuterJoinrenderByrenderGroupByClauserenderHavingClauserenderSortExpression$fRenderSQLQuery$fIsQualifiedrelcolNP$fIsQualifiedrelcolBy$fIsLabelcolNP$fIsLabelcolBy$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 ByteString text-1.2.3.0Data.Text.InternalTextGHC.BaseMaybeNothingghc-prim GHC.TypesNat++ PlaceholderGHC.Real Fractional GHC.FloatFloatingGHC.NumNumSymbolJustmaybePGjsonb_each_textPGjson_each_text GHC.Classesmin GHC.TypeNats+CategoryrenderCreationTypeGenerics.SOP.UniverseGenericHasDatatypeInfo execParamsData.Traversabletraverseprepare Traversable execPrepared Data.FoldableFoldableFunctorMonad<*>join=<<>> Control.Monad<=<exec,monad-control-1.0.2.3-IPrpWAjYxOt1opqDMU7GN2Control.Monad.Trans.ControlMonadBaseControl0transformers-base-0.4.5.2-9baFU7phiuIKF7KTSSI06QControl.Monad.Base MonadBasetransformers-0.5.5.0Control.Monad.Trans.Class MonadTrans ApplicativerenderTransactionMode