diff --git a/ChangeLog.md b/ChangeLog.md
--- a/ChangeLog.md
+++ b/ChangeLog.md
@@ -1,5 +1,60 @@
 # Changelog for pg-schema
 
+## 0.9.0.0
+- Fix typos in some compile-time error messages
+- Improve Haddock
+- Remove the unused constructor `RFEmpty` of `RecField'`.
+- `PgOid` is no longer exported from `PgSchema.DML`: it is used only to read
+  the system catalogs, and its `Eq` instance treats all values as equal.
+  Use `Int` for `oid` columns.
+- `PgSchema.DML` exports the type `FldDef'` (used by `FdType` / `FdNullable`).
+- Fix: tree DML (`insertJSON`, `upsertJSON`, `updateJSON` and their `_`
+  variants) stored `Nothing` for a nullable `json` / `jsonb` column as the JSON
+  value `null` instead of SQL `NULL`. Now `Nothing` gives SQL `NULL`. A JSON `null`
+  value (e.g. `Just Aeson.Null` in a `Maybe Value` field) can't be told apart
+  from `Nothing` in the JSON sent to PostgreSQL, so it is stored as SQL `NULL`
+  too; use `insertSch` / `updateByCond` to store the JSON value `null` itself.
+- `named` (and type family `Named`): give field names once for a whole list of
+  plain rows instead of `"field" =: value` in every row.
+- `rowsOf` / `plains`: rows from / to plain values with field names and types
+  taken from the row type.
+- Aggregate fields (`Aggr` / `Aggr'`) are now type-checked against the SQL
+  result type of the aggregate function. Previously the check was not applied
+  at all.
+- `qPath` / `qPathFromHere` / `qPathToHere` with an unknown relation name now
+  report `relation "..." is not defined` with the valid relations of the table
+  (previously `qPath` reported a misleading self-reference error).
+- Fix `RETURNING` checks of `insertJSON` / `upsertJSON` / `updateJSON`
+  (`ReturningMatchesInsert` / `ReturningMatchesUpsert` / `ReturningMatchesUpdate`),
+  which were silently skipped in most cases.
+  Code that compiled only because of this may now fail to compile:
+  - `updateJSON`: child list elements must be `Maybe`;
+  - `insertJSON`: child list elements must not be `Maybe`;
+  - `upsertJSON`: a child list element must be `Maybe` iff the child in the
+    *input* row lacks mandatory columns (previously the *returning* columns
+    were used) or upsert uses `ON CONFLICT DO NOTHING` with parent FK columns
+    outside the conflict key; the root returning row must be `Maybe` if the
+    input root row lacks mandatory columns.
+- `NeedsFkKeyOnlyMaybe` matched the opposite case (a child with plain columns
+  outside the conflict key, i.e. `ON CONFLICT … DO UPDATE`, which always
+  returns the row); now it matches `ON CONFLICT DO NOTHING` as documented.
+- `upsertJSON`: a child upserted with `ON CONFLICT DO NOTHING` whose key
+  belongs to a row of another parent (parent FK outside the key) was returned
+  as an object of `null` columns (a JSON decoding error) or, when the returning
+  columns were all in the input, as if it were found under this parent; its own
+  children were still processed. Now such a child is returned as `null`
+  (`Nothing`) and its children are skipped, as for a row not found by `UPDATE`.
+- Fix: `upsertByKey` with a record whose fields all belong to the key used
+  `ON CONFLICT DO NOTHING` and returned nothing for rows that already existed.
+  Now it uses a no-op `ON CONFLICT (key) DO UPDATE`: an existing row is left
+  as is and returned, so there is one returned row per input record.
+  `upsertByKey_` uses `ON CONFLICT (key) DO NOTHING` in this case; previously
+  the conflict target was missing, so a conflict on another unique key was
+  silently ignored, and now it is an error, as for other records.
+
+## 0.8.1.1
+- aeson upper version is changed
+
 ## 0.8.1.0
 - upsertJSON: require `Maybe` on child returning when upsert uses
   `ON CONFLICT DO NOTHING` with parent FK columns outside the conflict key
diff --git a/pg-schema.cabal b/pg-schema.cabal
--- a/pg-schema.cabal
+++ b/pg-schema.cabal
@@ -1,6 +1,6 @@
 cabal-version:  3.12
 name:           pg-schema
-version:        0.8.1.0
+version:        0.9.0.0
 category:       Database
 author:         Dmitry Olshansky
 maintainer:     olshanskydr@gmail.com
@@ -16,7 +16,7 @@
 description:
     == Schema definition
 
-    Use `updateSchemaFile` function from "PgSchema.Generation" module to generate type-level definition of database schema.
+    Use @updateSchemaFile@ function from "PgSchema.Generation" module to generate type-level definition of database schema.
     You can make several schemas with any parts of your database.
 
     Usually you make executable which imports this module and run it to generate schema definition.
@@ -30,41 +30,38 @@
     With @pg-schema@ you can select or insert/upsert data into tree-like ADT in one request.
 
     === Example
-    Let's say
 
-    - we have a database with tables: "orders", "order_positions", "articles".
-    - There are articles with ids 41 and 42.
-    - We have generated `MySch` schema with `updateSchemaFile` function from "PgSchema.Generation" module.
-
-    Then we can write a function to insert an order with order positions.
-    And select orders with order positions and articles in one request using some conditions for orders and order positions that return in order.
+    Let's say we have tables @shop.ord@, @shop.ord_pos@ and @shop.article@, where @ord_pos@
+    references @ord@ and @article@. The foreign keys have the default names given by PostgreSQL:
+    @ord_pos_ord_id_fkey@ and @ord_pos_article_id_fkey@. There are articles with ids 41 and 42,
+    and we have generated the schema @MySch@ with @updateSchemaFile@ from "PgSchema.Generation".
 
-    Note that all table names, field names and foreign key constraint names are checked in compile time!
+    Then we can insert an order with its positions, and select orders with their positions and
+    articles, using conditions for orders and positions. Each operation is one request.
 
-    @
-    data Order = Order { num :: Text, createdAt :: Day, items :: [OrdPos] } deriving Generic
-    data OrdPos = OrdPos { id :: Int32, num :: Int32, article :: Article, price :: Double } deriving Generic
-    data Article = Article { id :: Int32, name :: Text } deriving Generic
-    type MyAnn tabName = 'Ann CamelToSnake MySch 5 ("dbSchema" ->> tabName)
-        ...
-    do
-      -- insert an order with order positions
-      void $ insertJSON_ (MyAnn "orders") conn
-        [ "num" =: "num1" :. "ord__ord_pos" =:
-          [ "num" =: 1 :. "articleId" =: 42 :. "price" =: 10
-          , "num" =: 2 :. "articleId" =: 41 :. "price" =: 15 ] ]
+    > type ShopAnn tabName = 'Ann RenamerId MySch 5 ("shop" ->> tabName)
+    >
+    > -- An order with its positions to insert
+    > type OrdIn = "num" := Text :. "ord_pos_ord_id_fkey" := [OrdPosIn]
+    > type OrdPosIn = "num" := Int32 :. "article_id" := Int32 :. "price" := Double
+    >
+    > -- Orders to select: with positions and their articles
+    > data Order = Order { num :: Text, created_at :: Day, ord_pos_ord_id_fkey :: [OrdPos] } deriving Generic
+    > data OrdPos = OrdPos { num :: Int32, ord_pos_article_id_fkey :: Article, price :: Double } deriving Generic
+    > data Article = Article { name :: Text } deriving Generic
+    >
+    > example :: Connection -> Day -> IO [Order]
+    > example conn someDay = do
+    >   void $ insertJSON_ (ShopAnn "ord") conn $ rowsOf @OrdIn
+    >     [ "num1" :. [ 1 :. 42 :. 10, 2 :. 41 :. 15 ] ]
+    >   fst <$> selectSch (ShopAnn "ord") conn (qRoot do
+    >     qWhere $ "created_at" >=? someDay
+    >     qOrderBy [descf "created_at", descf "num"]
+    >     qPath "ord_pos_ord_id_fkey" do
+    >       qWhere $ "price" >? (12 :: Double)
+    >       qOrderBy [ascf "num"])
 
-      -- select orders
-      (xs :: [Order]) <- selectSch (MyAnn "orders") conn $ qRoot do
-        qWhere $ "created_at" >? someDay
-          &&& pchild "ord__ord_pos" defTabParam
-            (pparent "ord_pos__article" $ "name" ~~? "%pencil%")
-        qOrderBy [descf "created_at", descf "num"]
-        qPath "ord__ord_pos" do
-          qWhere $ pparent "ord_pos__article" $ "name" ~~? "%pencil%"
-          qOrderBy [ascf "num"]
-        qLimit 20
-    @
+    Note that all table names, field names and foreign key constraint names are checked at compile time!
 
     === Structure of modules
 
@@ -169,6 +166,7 @@
     PgSchema.DML.Select
     PgSchema.DML.Select.Types
     PgSchema.DML.Update
+    PgSchema.Plain
     PgSchema.Schema
     PgSchema.Types
     PgSchema.Utils.CamelToSnake
@@ -184,7 +182,7 @@
     PackageInfo_pg_schema
   hs-source-dirs: src
   build-depends:
-      aeson >= 2.0 && < 2.3
+      aeson >= 2.0 && < 2.4
     , containers >= 0.7 && < 0.9
     , directory >= 1.3 && < 1.5
     , exceptions >= 0.9 && < 0.11
@@ -261,14 +259,20 @@
   main-is:          Main.hs
   other-modules:
     Sch
+    Tests.AggregateErrors
     Tests.Aggregates
     Tests.BaseConverts
     Tests.Conditions
     Tests.Hierarchy
     Tests.KeyedDML
     Tests.InsertJSONTransaction
+    Tests.JsonNull
+    Tests.Named
+    Tests.NamedErrors
     Tests.UpsertUniqueKey
     Tests.Path
+    Tests.PathErrors
+    Tests.ReturningErrors
     Utils
     -- Paths and PackageInfo
     Paths_pg_schema
@@ -291,7 +295,8 @@
     uuid-types,
     vector,
     -- they can be excluded by flags
-    deepseq
+    deepseq,
+    ghc-heap
     ---------------
   if flag(hashable)
     build-depends:
diff --git a/src/PgSchema/Ann.hs b/src/PgSchema/Ann.hs
--- a/src/PgSchema/Ann.hs
+++ b/src/PgSchema/Ann.hs
@@ -9,7 +9,6 @@
 import Data.Coerce
 import Data.Singletons.TH (genDefunSymbols)
 import Data.Type.Bool
-import Data.Type.Equality
 import Data.Typeable
 import Data.Text qualified as T
 import Data.Kind
@@ -30,20 +29,26 @@
 
 -- $setup
 -- >>> import PgSchema.Schema.Catalog
+-- >>> import PgSchema.Schema.Info
 -- >>> import Database.PostgreSQL.Simple
--- >>> conn <- connectPostgreSQL ""
+-- >>> import System.Environment (lookupEnv)
+-- >>> import qualified Data.ByteString.Char8 as BS
+-- >>> conn <- connectPostgreSQL . maybe "" BS.pack =<< lookupEnv "PG_CONN"
 
 -- | Type-level annotation: enforce constraints at compile time
 -- and drive demoted types used to generate correct SQL.
--- 'annRen' and 'annSch' are fixed for the whole DML-operation.
+-- 'annRen' and 'annSch' are fixed for the whole DML operation.
 -- 'annDepth' and 'annTab' are changed while traversing the structure of the ADT.
 --
 data Ann = Ann
   { annRen  :: Renamer -- ^ Renamer to convert Haskell names to database names.
   , annSch  :: Type    -- ^ Schema with tables, relations and types.
   , annDepth :: Nat
-  -- ^ Depth of the nested relations. It is mostly used to prevent cycles in types.
-  , annTab  :: NameNSK -- ^ Name of the root table.
+  -- ^ Maximal depth of the nested relations. It is decreased on each step to a
+  -- related table and is mostly used to prevent cycles in types.
+  , annTab  :: NameNSK
+  -- ^ Name of the current table: the root table of the operation, then the
+  -- related table while walking into nested relations.
   }
 
 type family AnnSch (ann :: Ann) where
@@ -65,13 +70,19 @@
 
 -- | Apply renamer to symbol.
 --
---  Like 'Data.Singletons.Apply' but specialized for 'Symbol'.
+-- Like 'Data.Singletons.Apply' but specialized for 'Symbol'.
 --
--- To make your own Renamer, typically you make
+-- To make your own renamer, declare an empty data type of kind 'Renamer',
+-- a closed type family with the renaming rules, and an instance of
+-- 'ApplyRenamer' that connects them:
 --
--- * data MyRenamer :: Renamer
--- * closed type family: `type family MyRenamerImpl (s :: Symbol) :: Symbol where ... `
--- * type instance ApplyRenamer MyRenamer s = MyRenamerImpl s
+-- > data MyRenamer :: Renamer
+-- >
+-- > type family MyRenamerImpl (s :: Symbol) :: Symbol where
+-- >   MyRenamerImpl "manager" = "users_manager_id_fkey"
+-- >   MyRenamerImpl s = CamelToSnake s
+-- >
+-- > type instance ApplyRenamer MyRenamer s = MyRenamerImpl s
 --
 type family ApplyRenamer (renamer :: Renamer) (s :: Symbol) :: Symbol
 
@@ -80,6 +91,7 @@
 
 type instance ApplyRenamer RenamerId s = s
 
+-- | Apply renamer to the name (not to the namespace) of a qualified name.
 type family ApplyRenamerNS (ren :: Renamer) (nns :: NameNSK) :: NameNSK where
   ApplyRenamerNS ren ('NameNS ns n) = 'NameNS ns (ApplyRenamer ren n)
 
@@ -188,12 +200,17 @@
     GCols ann (D1 d (C1 c flds)) = Normalize (GCols ann flds)
     GCols ann (a :*: b) = GCols ann a SP.++ GCols ann b
     GCols ann (S1 (MetaSel ('Just fld) u v w) (Rec0 t)) = Col ann fld t
-    GCols ann rep = TypeError
-      ( Text "Only Product types with fields are supported in pg-schema."
-      :$$: Text "(sum types, empty, or missing field selector are not supported)"
-      :$$: Text ""
-      :$$: Text "But I've got " :<>: ShowType rep )
+    GCols ann rep = NotProductTypeError rep
 
+-- | Error for Generic representations that are not a record with fields
+-- (shared by 'GCols' and 'PgSchema.Plain.GPlainCols').
+type NotProductTypeError :: forall k. (Type -> Type) -> k
+type NotProductTypeError rep = TypeError
+  ( Text "Only Product types with fields are supported in pg-schema."
+  :$$: Text "(sum types, empty, or missing field selector are not supported)"
+  :$$: Text ""
+  :$$: Text "But I've got " :<>: ShowType rep )
+
 --------------------------------------------------------------------------------
 -- Normalize (SymNat numbering)
 --------------------------------------------------------------------------------
@@ -239,12 +256,13 @@
    parseJSON Null = pure $ PgTag Nothing
    parseJSON v = PgTag . Just <$> parseJSONCols @ann @colsCase @cols v
 
--- >>> type AnnRel = 'Ann RenamerId PgCatalog (PGC "pg_constraint")
+-- >>> type AnnRel = 'Ann RenamerId PgCatalog 1 (PGC "pg_constraint")
 -- >>> rel = PgRelation{ constraint__namespace = PgTag "a", conname = "b", constraint__class = PgClassShort (PgTag "c") "d", constraint__fclass = PgClassShort (PgTag "e") "f", conkey = pgArr' [1,2], confkey = pgArr' [] }
 -- >>> rec = "conname" =: ("x" :: T.Text) :. "conname" =: ("z" :: T.Text) :. rel :. "conname" =: ("y" :: T.Text)
 -- >>> toJSON $ PgTag @AnnRel rec
--- >>> fromJSON (toJSON $ PgTag @AnnRel rec) == Success (PgTag @AnnRel rec)
 -- Object (fromList [("confkey",Array []),("conkey",Array [Number 1.0,Number 2.0]),("conname",String "x"),("conname___1",String "z"),("conname___2",String "b"),("conname___3",String "y"),("constraint__class",Object (fromList [("class__namespace",Object (fromList [("nspname",String "c")])),("relname",String "d")])),("constraint__fclass",Object (fromList [("class__namespace",Object (fromList [("nspname",String "e")])),("relname",String "f")])),("constraint__namespace",Object (fromList [("nspname",String "a")]))])
+--
+-- >>> fromJSON (toJSON $ PgTag @AnnRel rec) == Success (PgTag @AnnRel rec)
 -- True
 
 
@@ -256,7 +274,7 @@
 
 -- (:=)
 --------------------------------------------------------------------------------
--- NonGeneric: (:=) и (:.)
+-- NonGeneric: (:=) and (:.)
 --------------------------------------------------------------------------------
 instance ToJSONCols ann 'NonGenericCase '[] (fld := ()) where
   toPairs _ = []
@@ -517,6 +535,13 @@
   , fields  :: [FieldInfo s] }
   deriving Show
 
+-- | Term-level description of how the Haskell row type @r@ maps to the table of
+-- annotation @ann@: database names of the fields and, for relation fields, the
+-- nested descriptions of the related tables.
+--
+-- It is used to generate SQL. There is a single instance for all rows, and it
+-- reports a compile-time error if some field of @r@ does not exist in the table
+-- or has an incompatible type.
 class CRecInfo (ann :: Ann) (r :: Type) where
   getRecordInfo :: RecordInfo T.Text
 
@@ -544,8 +569,14 @@
 instance (ToStar fd, CanConvert (AnnSch ann) (AnnTab ann) fldDbName fd t) => CFldInfo ann fldDbName ('RFPlain fd) t where
   getFldInfo = RFPlain (demote @fd)
 
-instance (ToStar fd, ToStar af, ToStar b) =>
-  CFldInfo ann _fldDbName ('RFAggr fd af b) t where
+-- 'CheckAggr' is an equality: its (deferred) evidence is strict, unlike
+-- dictionaries, so a wrong aggregate type is reported even with
+-- @-fdefer-type-errors@ as soon as the field info is built.
+instance
+  ( ToStar fd, ToStar af, ToStar b
+  , CheckAggr (AnnSch ann) (AnnTab ann) fldDbName fd t ~ 'True
+  , CanConvert (AnnSch ann) (AnnTab ann) fldDbName fd t ) =>
+  CFldInfo ann fldDbName ('RFAggr fd af b) t where
   getFldInfo = RFAggr (demote @fd) (demote @af) (demote @b)
 
 instance (ToStar flds, ToStar expr) =>
@@ -598,7 +629,7 @@
   AppNotPlain rs db 'True = rs
   AppNotPlain rs db 'False = db ': rs
 
--- | All fields are plain (no RFToHere/RFFromHere)
+-- | All fields are plain (no relations: 'RFToHere', 'RFFromHere' or 'RFSelfRef').
 type AllPlain (ann :: Ann) (r :: Type) = AllPlainRS ann (NotPlainCols (Cols ann r) '[]) r
 
 type family AllPlainRS (ann :: Ann) (rs :: [Symbol]) (r :: Type) :: Constraint where
@@ -615,7 +646,7 @@
 --------------------------------------------------------------------------------
 -- Type-level RecordInfo for Ann
 --------------------------------------------------------------------------------
--- | Decrease relation-walk depth kept in 'Ann'.
+-- | Decrease relation-walk depth kept in t'Ann'.
 -- When depth is exhausted, fail with a detailed type error instead of
 -- potentially diverging in recursive type families/instances.
 type family DecDepth (ann :: Ann) :: Nat where
@@ -641,7 +672,6 @@
   :: RecField' Symbol (RecordInfo Symbol) where
   TFldInfo ann ('RFPlain fd) t = 'RFPlain fd
   TFldInfo ann ('RFAggr fd af b) t = 'RFAggr fd af b
-  TFldInfo ann ('RFEmpty s) t = 'RFEmpty s
   TFldInfo ('Ann ren sch d tab) ('RFToHere (toTab :: NameNSK) refs)
     [PgTag ('Ann ren sch d' toTab) rChild] =
     'RFToHere ('RecordInfo toTab (TRecordInfo ('Ann ren sch d' toTab) rChild)) refs
@@ -665,6 +695,9 @@
   TRecordInfoCols ann ('ColInfo sn t db fi ': cs) =
     'FieldInfo (NameSymNat sn) db (TFldInfo ann fi t) ': TRecordInfoCols ann cs
 
+-- | Type-level analogue of 'getRecordInfo': the fields of row @r@ for annotation
+-- @ann@ with their database names and kinds (plain column, aggregate, relation
+-- with the fields of the nested row).
 type family TRecordInfo (ann :: Ann) (r :: Type) :: [FieldInfo Symbol] where
   TRecordInfo ann r = TRecordInfoCols ann (Cols ann r)
 
@@ -694,8 +727,10 @@
 -- Node-level checks for Mandatory / upsert keys (CheckNodeAll* analogue)
 --------------------------------------------------------------------------------
 
--- | One-table check that all mandatory fields are present
--- rs: list of columns that are already "covered" (including those that come from Reference)
+-- | One-table check that all mandatory fields are present.
+--
+-- @rs@ is the list of columns that are already "covered" (including the
+-- columns that come from the reference to the parent).
 type family CheckAllMandatory (ann :: Ann) (rs :: [Symbol]) :: Constraint where
   CheckAllMandatory ('Ann ren sch d tab) rs =
     CheckAllMandatory' (RestMandatory sch tab rs) ('Ann ren sch d tab) rs
@@ -707,8 +742,8 @@
     :$$: Text "Table: " :<>: ShowType tab
     :$$: Text "Missing mandatory fields: " :<>: ShowType rest )
 
--- | All mandatory fields in @rs@, or a full primary key, or a full eligible
--- unique key (see 'IdentityCandidates').
+-- | All mandatory fields in @rs@, or a full primary key, or a full unique key
+-- (see 'IdentityCandidates').
 type family CheckAllMandatoryOrHasKey (ann :: Ann) (rs :: [Symbol]) :: Constraint where
   CheckAllMandatoryOrHasKey ('Ann ren sch d tab) rs = CheckAllMandatoryOrHasKey'
     (RestMandatory sch tab rs) (IdentityCandidates sch tab)
@@ -733,12 +768,12 @@
   HasAnyFullIdentity' '[] rs ks ann = ()
   HasAnyFullIdentity' (_ ': _) rs ks ann = HasAnyFullIdentity rs ks ann
 
--- | Every node must include a full primary or eligible unique key.
+-- | Every node must include a full primary or unique key (see 'IdentityCandidates').
 type family CheckHasKey (ann :: Ann) (rs :: [Symbol]) :: Constraint where
   CheckHasKey ('Ann ren sch d tab) rs =
     HasAnyFullIdentity rs (IdentityCandidates sch tab) ('Ann ren sch d tab)
 
--- | All mandatory fields and a full primary or eligible unique key (flat upsert).
+-- | All mandatory fields and a full primary or unique key (flat upsert).
 type CheckAllMandatoryAndHasKey ann rs =
   (CheckAllMandatory ann rs, CheckHasKey ann rs)
 
@@ -760,18 +795,29 @@
       , WalkLevelAnn check ('Ann ren sch d tab) xs rs )
   WalkLevelAnn check ann (_ ': xs) rs = WalkLevelAnn check ann xs rs
 
+-- | Every node of the input tree @r@ (a row or a list of rows) has all mandatory
+-- columns of its table (for 'PgSchema.DML.insertJSON').
+--
+-- @rFlds@ are columns that are known to be present at the root besides the
+-- fields of @r@ (usually @'[]@). Foreign-key columns of child rows are counted
+-- as present: they are taken from the parent row.
 type family AllMandatoryTree (ann :: Ann) (r :: Type) (rFlds :: [Symbol])
   :: Constraint where
   AllMandatoryTree ann [r] rFlds = AllMandatoryTree ann r rFlds
   AllMandatoryTree ann r rFlds =
     WalkLevelAnn CheckAllMandatorySym0 ann (TRecordInfo ann r) rFlds
 
+-- | Every node of the input tree @r@ has all mandatory columns of its table or a
+-- full primary / unique key (for 'PgSchema.DML.upsertJSON'). See
+-- 'AllMandatoryTree' for @rFlds@.
 type family AllMandatoryOrHasKeyTree (ann :: Ann) (r :: Type) (rFlds :: [Symbol])
   :: Constraint where
   AllMandatoryOrHasKeyTree ann [r] rFlds = AllMandatoryOrHasKeyTree ann r rFlds
   AllMandatoryOrHasKeyTree ann r rFlds =
     WalkLevelAnn CheckAllMandatoryOrHasKeySym0 ann (TRecordInfo ann r) rFlds
 
+-- | Every node of the input tree @r@ has a full primary / unique key of its table
+-- (for 'PgSchema.DML.updateJSON'). See 'AllMandatoryTree' for @rFlds@.
 type family AllHasKeyTree (ann :: Ann) (r :: Type) (rFlds :: [Symbol])
   :: Constraint where
   AllHasKeyTree ann [r] rFlds = AllHasKeyTree ann r rFlds
@@ -820,9 +866,6 @@
 -- Returning row optionality (Maybe) vs input mandatory coverage
 --------------------------------------------------------------------------------
 
-type family AnnChild (ann :: Ann) (childTab :: NameNSK) :: Ann where
-  AnnChild ('Ann ren sch _ _) childTab = 'Ann ren sch 0 childTab
-
 type family InnerRow (r :: Type) :: Type where
   InnerRow (Maybe r) = r
   InnerRow r = TypeError
@@ -836,7 +879,7 @@
     :$$: Text "Got: " :<>: ShowType r )
 
 -- | Flat @RETURNING@ row must not be wrapped in @Maybe@ (use @IO [Maybe r']@ on
--- 'updateByKey' for per-row absence). Nullable columns may still be @Maybe@ fields.
+-- 'PgSchema.DML.updateByKey' for per-row absence). Nullable columns may still be @Maybe@ fields.
 type family RequireBareRow (r :: Type) :: Constraint where
   RequireBareRow r = RequireBareRow' r
 
@@ -847,21 +890,6 @@
     :$$: Text "Got: " :<>: ShowType (Maybe x) )
   RequireBareRow' _ = ()
 
-type family ListElem (t :: Type) :: Type where
-  ListElem [e] = e
-  ListElem t = TypeError
-    ( Text "Expected a Haskell list type for a child branch."
-    :$$: Text "Got: " :<>: ShowType t )
-
-type family SymNatName (sn :: SymNat) :: Symbol where
-  SymNatName '(s, _) = s
-
-type family ColTypeByJsonName (name :: Symbol) (cols :: [ColInfo NameNSK]) :: Type where
-  ColTypeByJsonName name '[] = TypeError
-    ( Text "Returning field not found in output type: " :<>: ShowType name )
-  ColTypeByJsonName name ('ColInfo sn t _ _ ': xs) =
-    If (SymNatName sn == name) t (ColTypeByJsonName name xs)
-
 type family CoveredRs (ann :: Ann) (fis :: [FieldInfo Symbol]) :: [Symbol] where
   CoveredRs ann '[] = '[]
   CoveredRs ann ('FieldInfo _ db ('RFPlain _) ': xs) = db ': CoveredRs ann xs
@@ -918,135 +946,126 @@
   FkOutsideKeyB 'True fs key = FkOutsideKey fs key
 
 -- | Upsert child uses @ON CONFLICT DO NOTHING@ when JSON carries only key
--- columns while parent FK columns are injected separately.
+-- columns (no plain column outside the conflict key) while parent FK columns
+-- are injected separately.
 type family NeedsFkKeyOnlyMaybe (plain :: [Symbol]) (fk :: [Symbol])
   (key :: [Symbol]) :: Bool where
   NeedsFkKeyOnlyMaybe plain fk key = Not (Null fk)
-    && Not (Null (FilterNotIn plain key)) && FkOutsideKey fk key
+    && Null (FilterNotIn plain key) && FkOutsideKey fk key
 
-type family CheckUpsertChildListElem (path :: [Symbol]) (ann :: Ann)
-  (jsonName :: Symbol) (refs :: [RefK]) (childFIs :: [FieldInfo Symbol])
-  (elemTy :: Type) :: Constraint where
-  CheckUpsertChildListElem path ('Ann ren sch d childTab) jsonName refs childFIs
-    elemTy =
-    CheckUpsertChildElem' path sch childTab jsonName
-      (CoveredRs ('Ann ren sch d childTab) childFIs)
+-- | Which tree DML operation the returning type is checked for.
+data TreeDml = TreeInsert | TreeUpsert | TreeUpdate
+
+-- | Walk the columns of a returning row together with the input fields of the
+-- same tree node. Columns of the returning row carry the Haskell types, so for
+-- each child list @[PgTag childAnn t]@ the element row type @t@ is checked
+-- ('CheckChildElem') and the walk goes on into the columns of @t@ with the
+-- input fields of that child.
+type family CheckReturningAt (op :: TreeDml) (path :: [Symbol]) (ann :: Ann)
+  (fisIn :: [FieldInfo Symbol]) (colsOut :: [ColInfo NameNSK]) :: Constraint where
+  CheckReturningAt op path ann fisIn '[] = ()
+  CheckReturningAt op path ('Ann ren sch d tab) fisIn
+    ('ColInfo sn [PgTag childAnn t] db ('RFToHere _ refs) ': cs) =
+    ( CheckChildElem op path tab (NameSymNat sn) childAnn refs
+        (FindChildAt path db fisIn) t
+    , CheckReturningAt op (Snoc path db) childAnn (FindChildAt path db fisIn)
+        (Cols childAnn (UnMaybe t))
+    , CheckReturningAt op path ('Ann ren sch d tab) fisIn cs )
+  CheckReturningAt op path ann fisIn (_ ': cs) =
+    CheckReturningAt op path ann fisIn cs
+
+-- | Check the element type @t@ of a child list @fld@ of table @tab@:
+--
+-- * insert: always bare ('AssertNoMaybe');
+-- * update: always @Maybe@ ('AssertMustBeMaybe') - a child that is not found
+--   by its key is returned as @null@;
+-- * upsert: depends on the input fields of the child ('CheckUpsertChildElem').
+type family CheckChildElem (op :: TreeDml) (path :: [Symbol]) (tab :: NameNSK)
+  (fld :: Symbol) (childAnn :: Ann) (refs :: [RefK])
+  (childFIsIn :: [FieldInfo Symbol]) (t :: Type) :: Constraint where
+  CheckChildElem 'TreeInsert path tab fld _ _ _ t = AssertNoMaybe path tab fld t
+  CheckChildElem 'TreeUpdate path tab fld _ _ _ t = AssertMustBeMaybe path tab fld t
+  CheckChildElem 'TreeUpsert path tab fld ('Ann ren sch d childTab) refs fis t =
+    CheckUpsertChildElem path sch tab fld childTab
+      (CoveredRs ('Ann ren sch d childTab) fis)
       (RefFromNames refs)
       (PickFirstKey
-        (RefFromNames refs ++ CoveredRs ('Ann ren sch d childTab) childFIs)
+        (RefFromNames refs ++ CoveredRs ('Ann ren sch d childTab) fis)
         (IdentityCandidates sch childTab))
-      elemTy
-
-type family InnerPgTag (t :: Type) :: Type where
-  InnerPgTag (PgTag _ r) = r
-  InnerPgTag r = r
+      t
 
-type family CheckUpsertChildElem' (path :: [Symbol]) (sch :: k)
-  (tab :: NameNSK) (jsonName :: Symbol) (plainDb :: [Symbol])
-  (fkDb :: [Symbol]) (key :: [Symbol]) (elemTy :: Type) :: Constraint where
-  CheckUpsertChildElem' path sch tab jsonName plainDb fkDb key elemTy =
+-- | Upsert child element: @Maybe@ when the input child lacks mandatory columns
+-- (it is only updated by key and may be not found) or 'NeedsFkKeyOnlyMaybe';
+-- bare otherwise. @plainDb@ are plain columns of the /input/ child: they define
+-- the SQL that is generated for the child.
+type family CheckUpsertChildElem (path :: [Symbol]) (sch :: k) (tab :: NameNSK)
+  (fld :: Symbol) (childTab :: NameNSK) (plainDb :: [Symbol])
+  (fkDb :: [Symbol]) (key :: [Symbol]) (t :: Type) :: Constraint where
+  CheckUpsertChildElem path sch tab fld childTab plainDb fkDb key t =
     If (NeedsFkKeyOnlyMaybe plainDb fkDb key
-      || Not (Null (RestMandatory sch tab plainDb)))
-      (AssertMustBeMaybe path tab jsonName (InnerPgTag (ListElem elemTy)))
-      (AssertNoMaybe path tab jsonName (InnerPgTag (ListElem elemTy)))
-
-type family SkipOutField (db :: Symbol) (fis :: [FieldInfo Symbol])
-  :: [FieldInfo Symbol] where
-  SkipOutField db '[] = '[]
-  SkipOutField db ('FieldInfo _ db _ ': xs) = xs
-  SkipOutField db (_ ': xs) = SkipOutField db xs
-
-type family CheckReturningUpsertAt (path :: [Symbol]) (ann :: Ann) (rIn :: Type)
-  (rOut :: Type) (fisIn :: [FieldInfo Symbol]) (fisOut :: [FieldInfo Symbol])
-  :: Constraint where
-  CheckReturningUpsertAt path ann rIn rOut '[] '[] = ()
-  CheckReturningUpsertAt path ('Ann ren sch d tab) rIn rOut fisIn
-    ('FieldInfo jsonName db
-      ('RFToHere ('RecordInfo childTab childFIsOut) refs) ': outs) =
-    ( CheckUpsertChildListElem path ('Ann ren sch d childTab) jsonName refs
-        childFIsOut
-        (ColTypeByJsonName jsonName (Cols ('Ann ren sch d tab) rOut))
-    , CheckReturningUpsertAt (Snoc path db) (AnnChild ('Ann ren sch d tab) childTab) rIn rOut
-        (FindChildAt path db fisIn) childFIsOut
-    , CheckReturningUpsertAt path ('Ann ren sch d tab) rIn rOut fisIn (SkipOutField db outs) )
-  CheckReturningUpsertAt path ann rIn rOut
-    (_ ': ins) ('FieldInfo _ db _ ': outs) =
-    CheckReturningUpsertAt path ann rIn rOut ins (SkipOutField db outs)
-  CheckReturningUpsertAt path ann rIn rOut fisIn fisOut =
-    CheckSubtreeAt path fisIn fisOut
+      || Not (Null (RestMandatory sch childTab (fkDb ++ plainDb))))
+      (AssertMustBeMaybe path tab fld t)
+      (AssertNoMaybe path tab fld t)
 
-type family CheckReturningUpdateAt (path :: [Symbol]) (ann :: Ann) (rIn :: Type)
-  (rOut :: Type) (fisIn :: [FieldInfo Symbol]) (fisOut :: [FieldInfo Symbol])
+-- | Root row of upsert: when the input row lacks mandatory columns it is only
+-- updated by key, and a row that is not found is returned as @null@.
+type family CheckUpsertRoot (ann :: Ann) (rIn :: Type) (rOut :: Type)
   :: Constraint where
-  CheckReturningUpdateAt path ann rIn rOut '[] '[] = ()
-  CheckReturningUpdateAt path ('Ann ren sch d tab) rIn rOut fisIn
-    ('FieldInfo jsonName db ('RFToHere ('RecordInfo childTab childFIsOut) _) ': outs) =
-    ( AssertMustBeMaybe path tab jsonName
-        (ListElem (ColTypeByJsonName jsonName (Cols ('Ann ren sch d tab) rOut)))
-    , CheckReturningUpdateAt (Snoc path db) (AnnChild ('Ann ren sch d tab) childTab) rIn rOut
-        (FindChildAt path db fisIn) childFIsOut
-    , CheckReturningUpdateAt path ('Ann ren sch d tab) rIn rOut fisIn (SkipOutField db outs) )
-  CheckReturningUpdateAt path ann rIn rOut
-    (_ ': ins) ('FieldInfo _ db _ ': outs) =
-    CheckReturningUpdateAt path ann rIn rOut ins (SkipOutField db outs)
-  CheckReturningUpdateAt path ann rIn rOut fisIn fisOut =
-    CheckSubtreeAt path fisIn fisOut
+  CheckUpsertRoot ('Ann ren sch d tab) rIn rOut = CheckUpsertRoot' tab
+    (RestMandatory sch tab (CoveredRs ('Ann ren sch d tab) (TRecordInfo ('Ann ren sch d tab) rIn)))
+    rOut
 
-type family CheckReturningInsertAt (path :: [Symbol]) (ann :: Ann) (rIn :: Type)
-  (rOut :: Type) (fisIn :: [FieldInfo Symbol]) (fisOut :: [FieldInfo Symbol])
+type family CheckUpsertRoot' (tab :: NameNSK) (rest :: [Symbol]) (rOut :: Type)
   :: Constraint where
-  CheckReturningInsertAt path ann rIn rOut '[] '[] = ()
-  CheckReturningInsertAt path ('Ann ren sch d tab) rIn rOut fisIn
-    ('FieldInfo jsonName db ('RFToHere ('RecordInfo childTab childFIsOut) _) ': outs) =
-    ( AssertNoMaybe path tab jsonName
-        (ColTypeByJsonName jsonName (Cols ('Ann ren sch d tab) rOut))
-    , CheckReturningInsertAt (Snoc path db) (AnnChild ('Ann ren sch d tab) childTab) rIn rOut
-        (FindChildAt path db fisIn) childFIsOut
-    , CheckReturningInsertAt path ('Ann ren sch d tab) rIn rOut fisIn (SkipOutField db outs) )
-  CheckReturningInsertAt path ann rIn rOut
-    (_ ': ins) ('FieldInfo _ db _ ': outs) =
-    CheckReturningInsertAt path ann rIn rOut ins (SkipOutField db outs)
-  CheckReturningInsertAt path ann rIn rOut fisIn fisOut =
-    CheckSubtreeAt path fisIn fisOut
+  CheckUpsertRoot' _ '[] _ = ()
+  CheckUpsertRoot' _ _ (Maybe _) = ()
+  CheckUpsertRoot' tab rest rOut = TypeError
+    ( Text "Upsert returning row must be wrapped in Maybe:"
+    :$$: Text "the input row lacks mandatory fields " :<>: ShowType rest
+    :$$: Text "so it is only updated by key and a row that is not found is returned as null."
+    :$$: Text "Table: " :<>: ShowType tab
+    :$$: Text "Got: " :<>: ShowType rOut )
 
 -- | Checks that tree @RETURNING@ type @rOut@ matches input @rIn@ after insert:
 --
 -- * Each relation branch in @rOut@ exists in @rIn@ at the same path; plain columns
 --   in @rOut@ need not appear in @rIn@ ('CheckSubtreeAt').
--- * For every child list in @rOut@: the list element type must not be @Maybe@
---   ('AssertNoMaybe').
+-- * For every child list in @rOut@ (at any depth): the list element type must not
+--   be @Maybe@ ('AssertNoMaybe').
 type family ReturningMatchesInsert (ann :: Ann) (rIn :: Type) (rOut :: Type)
   :: Constraint where
   ReturningMatchesInsert ann rIn rOut =
     ( ReturningIsSubtree ann rIn rOut
-    , CheckReturningInsertAt '[] ann rIn rOut
-        (TRecordInfo ann rIn) (TRecordInfo ann rOut) )
+    , CheckReturningAt 'TreeInsert '[] ann (TRecordInfo ann rIn) (Cols ann rOut) )
 
 -- | Checks that tree @RETURNING@ type @rOut@ matches input @rIn@ after upsert:
 --
 -- * Same relation-subtree rules as 'ReturningMatchesInsert'.
--- * For each child list in @rOut@: if @rIn@ still lacks mandatory plain columns
---   at the child node, or upsert would use @ON CONFLICT DO NOTHING@ with parent FK
---   columns outside the conflict key ('NeedsFkKeyOnlyMaybe'), the element type must
---   be @Maybe@; otherwise it must be bare ('CheckUpsertChildListElem').
+-- * If the root input row lacks mandatory columns, @rOut@ must be @Maybe row@
+--   (the row is only updated by key and may be not found).
+-- * For each child list in @rOut@ (at any depth): if the child in @rIn@ lacks
+--   mandatory plain columns, or upsert would use @ON CONFLICT DO NOTHING@ with
+--   parent FK columns outside the conflict key ('NeedsFkKeyOnlyMaybe'), the
+--   element type must be @Maybe@; otherwise it must be bare ('CheckUpsertChildElem').
 type family ReturningMatchesUpsert (ann :: Ann) (rIn :: Type) (rOut :: Type)
   :: Constraint where
   ReturningMatchesUpsert ann rIn rOut =
-    ( ReturningIsSubtree ann rIn rOut
-    , CheckReturningUpsertAt '[] ann rIn rOut
-        (TRecordInfo ann rIn) (TRecordInfo ann rOut) )
+    ( ReturningIsSubtree ann rIn (UnMaybe rOut)
+    , CheckUpsertRoot ann rIn rOut
+    , CheckReturningAt 'TreeUpsert '[] ann (TRecordInfo ann rIn)
+        (Cols ann (UnMaybe rOut)) )
 
 -- | Checks that tree @RETURNING@ type @rOut@ matches input @rIn@ after update:
 --
--- * @rOut@ must be @Maybe row@ ('RequireMaybeRow'); checks apply to 'InnerRow rOut'.
+-- * @rOut@ must be @Maybe row@ ('RequireMaybeRow'); checks apply to @InnerRow rOut@.
 -- * Each relation branch in that row exists in @rIn@ at the same path; plain columns
 --   in the returning row need not appear in @rIn@.
--- * For every child list there: the element type must be @Maybe@
+-- * For every child list there (at any depth): the element type must be @Maybe@
 --   ('AssertMustBeMaybe').
 type family ReturningMatchesUpdate (ann :: Ann) (rIn :: Type) (rOut :: Type)
   :: Constraint where
   ReturningMatchesUpdate ann rIn rOut =
     ( RequireMaybeRow rOut
     , ReturningIsSubtree ann rIn (InnerRow rOut)
-    , CheckReturningUpdateAt '[] ann rIn (InnerRow rOut)
-        (TRecordInfo ann rIn) (TRecordInfo ann (InnerRow rOut)) )
+    , CheckReturningAt 'TreeUpdate '[] ann (TRecordInfo ann rIn)
+        (Cols ann (InnerRow rOut)) )
diff --git a/src/PgSchema/DML.hs b/src/PgSchema/DML.hs
--- a/src/PgSchema/DML.hs
+++ b/src/PgSchema/DML.hs
@@ -10,66 +10,87 @@
 -- Among @pg-schema@’s library modules, this is the one meant for ordinary application
 -- imports for database access (alongside your generated schema module).
 --
--- == TLDR; Example:
+-- == Example
 --
--- @
--- data Order = Order { num :: Text, createdAt :: Day, items :: [OrdPos] } deriving Generic
--- data OrdPos = OrdPos { id :: Int32, num :: Int32, article :: Article, price :: Double } deriving Generic
--- data Article = Article { id :: Int32, name :: Text } deriving Generic
--- type MyAnn tabName = 'Ann CamelToSnake MySch 5 ("dbSchema" ->> tabName)
---     ...
--- do
---   void $ insertJSON_ (MyAnn "orders") conn
---     [ "num" =: "num1" :. "ord__ord_pos" =:
---       [ "num" =: 1 :. "articleId" =: 42 :. "price" =: 10
---       , "num" =: 2 :. "articleId" =: 41 :. "price" =: 15 ] ]
+-- A schema module @MySch@ is generated (see "PgSchema.Generation") for tables
+-- @shop.ord@, @shop.ord_pos@ and @shop.article@, where @ord_pos@ references
+-- @ord@ and @article@. The foreign keys have the names that PostgreSQL gives
+-- them by default: @ord_pos_ord_id_fkey@ and @ord_pos_article_id_fkey@.
 --
---   (xs :: [Order]) <- selectSch (MyAnn "orders") conn $ qRoot do
---     qWhere $ "created_at" >? someDay
---       &&& pchild "ord__ord_pos" defTabParam
---         (pparent "ord_pos__article" $ "name" ~~? "%pencil%")
---     qOrderBy [descf "created_at", descf "num"]
---     qPath "ord__ord_pos" do
---       qWhere $ pparent "ord_pos__article" $ "name" ~~? "%pencil%"
---       qOrderBy [ascf "num"]
---     qLimit 20
--- @
+-- > type ShopAnn tabName = 'Ann RenamerId MySch 5 ("shop" ->> tabName)
+-- >
+-- > -- An order with its positions to insert
+-- > type OrdIn = "num" := Text :. "ord_pos_ord_id_fkey" := [OrdPosIn]
+-- > type OrdPosIn = "num" := Int32 :. "article_id" := Int32 :. "price" := Double
+-- >
+-- > -- Orders to select: with positions and their articles
+-- > data Order = Order { num :: Text, created_at :: Day, ord_pos_ord_id_fkey :: [OrdPos] } deriving Generic
+-- > data OrdPos = OrdPos { num :: Int32, ord_pos_article_id_fkey :: Article, price :: Double } deriving Generic
+-- > data Article = Article { name :: Text } deriving Generic
+-- >
+-- > example :: Connection -> Day -> IO [Order]
+-- > example conn someDay = do
+-- >   void $ insertJSON_ (ShopAnn "ord") conn $ rowsOf @OrdIn
+-- >     [ "num1" :. [ 1 :. 42 :. 10, 2 :. 41 :. 15 ] ]
+-- >   fst <$> selectSch (ShopAnn "ord") conn (qRoot do
+-- >     qWhere $ "created_at" >=? someDay
+-- >     qOrderBy [descf "created_at", descf "num"]
+-- >     qPath "ord_pos_ord_id_fkey" do
+-- >       qWhere $ "price" >? (12 :: Double)
+-- >       qOrderBy [ascf "num"])
 --
--- Here we get all orders created after `someDay` that have positions with articles like "%pencil%",
--- and return only those order items that relate to "pencil", with article info.
+-- Here we insert an order with two positions and then get the orders created on
+-- or after @someDay@, each with its positions priced above 12 and their articles.
 --
--- The preceding 'insertJSON_' call inserts one root row (here an order) and nested
--- /child/ rows (here order positions) in a single database operation, again using
--- JSON internally. Child data is carried in list fields: the field’s name (after 'Renamer') names
--- the FK constraint in the database and thus selects the child table and link;
--- each list element supplies one child row’s columns, with nested lists for further
--- children in the same way. 'insertJSON' / 'insertJSON_' require every mandatory
--- column and emit plain @INSERT@ only (duplicates fail in the database).
--- 'upsertJSON' / 'upsertJSON_' relax mandatory requirements and may @UPDATE@ or
--- @INSERT … ON CONFLICT …@ (see their Haddock).
--- 'updateJSON' / 'updateJSON_' update existing rows only (never @INSERT@).
--- Flat 'insertSch', 'upsertByKey', and 'updateByKey' use 'PlainOut' for @RETURNING@
--- (any plain columns of the table; 'RequireBareRow' forbids @Maybe@ on the whole
--- row). Tree @*JSON@ uses 'ReturningMatches{Insert,Upsert,Update}' instead.
--- 'upsertByKey' requires mandatory columns and a full key; 'updateByKey' is
--- key-only and returns @IO ([Maybe r'], Text)@.
+-- Field names are the database names here, since 'RenamerId' does not rename
+-- anything. A field of a relation is named after its foreign key.
 --
+-- Rows can be given as records ('GHC.Generics.Generic'), as rows of fields
+-- built with '(=:)' and chained with t'(:.)' (e.g. @"num" =: "num1" :. …@), or,
+-- as here, as plain values: 'rowsOf' takes field names and types from the row
+-- type, so the values need neither names nor type annotations. See also 'named'
+-- and 'plains'.
+--
+-- Conditions on related tables are made with 'pchild' and 'pparent'.
+--
+-- The 'insertJSON_' call in the example inserts one root row (here an order) and nested
+-- /child/ rows (here order positions) in a single database operation, using
+-- JSON internally. Child data is carried in list fields: the field’s name (after the
+-- 'Renamer') names the FK constraint in the database and thus selects the child table
+-- and link; each list element supplies one child row’s columns, with nested lists for
+-- further children in the same way.
+--
+-- * 'insertJSON' / 'insertJSON_' require every mandatory column and emit plain
+--   @INSERT@ only (duplicates fail in the database).
+-- * 'upsertJSON' / 'upsertJSON_' relax mandatory requirements and may @UPDATE@ or
+--   @INSERT … ON CONFLICT …@ (see 'upsertJSON').
+-- * 'updateJSON' / 'updateJSON_' update existing rows only (never @INSERT@).
+--
+-- Flat (single-table) 'insertSch', 'upsertByKey' and 'updateByKey' may return any
+-- plain columns of the table; the returning row itself must not be wrapped in
+-- 'Maybe'. Tree @*JSON@ operations check the returning type with
+-- 'ReturningMatchesInsert', 'ReturningMatchesUpsert' and 'ReturningMatchesUpdate'
+-- instead. 'upsertByKey' requires all mandatory columns and a full key;
+-- 'updateByKey' requires only a full key and returns @IO ([Maybe r'], Text)@.
+--
 -- 'selectSch' decodes each row into a Haskell type @r@ whose fields describe the
 -- root table columns and nested data for relations (multiple list-shaped children
 -- and nested parents/'Maybe' as appropriate). The type drives the generated SQL
--- shape; monadic 'QueryParam' only adds what this call needs—filters, ordering on a
+-- shape; monadic t'QueryParam' only adds what this call needs: filters, ordering on a
 -- branch, limits, and so on.
 --
--- We can use both 'GHC.Generics.Generic'-based and 'PgTag'-based ('(=:)') interfaces and mix them in any way.
---
 -- All string literals at the type level are 'GHC.TypeLits.Symbol' thanks to @RequiredTypeArguments@.
 -- Operations are safe when the live database schema matches the generated schema types.
 --
 -- The @INSERT@ and @SELECT@ shown here each run as a single, fast database round-trip (JSON inside PostgreSQL).
 --
--- We use a 'Renamer' (e.g. 'CamelToSnake') to map Haskell field names to @snake_case@ in the database.
--- In conditions and 'QueryParams', column names are the original database names.
--- It can be changed in the future.
+-- A 'Renamer' maps Haskell field names to database names. 'RenamerId' keeps
+-- them as they are; to use e.g. @createdAt@ for @created_at@ or @items@ for
+-- @ord_pos_ord_id_fkey@, declare your own renamer (see 'ApplyRenamer'). 'CamelToSnake'
+-- converts @camelCase@ to @snake_case@ and is a convenient default case for it.
+-- The renamer is applied to all names: record fields, column names in conditions
+-- and ordering, relation names in 'qPath', 'pchild' and 'pparent'. So with a
+-- renamer based on 'CamelToSnake' you can write either @"ownerId"@ or @"owner_id"@.
 --
 module PgSchema.DML
   (
@@ -83,9 +104,9 @@
   -- | Example: @"name" =? "John"@
   , (<?),(>?),(<=?),(>=?),(=?)
   -- | Null-safe equality on nullable columns (@IS NOT DISTINCT FROM@).
-  -- | Example: @"suffix" =?? (Just "a")@
+  -- Example: @"suffix" =?? (Just "a")@
   , (=??)
-  -- | Example: @"name" ~~? "%joh%"@
+  -- | @LIKE@ ('~=?') and @ILIKE@ ('~~?'). Example: @"name" ~~? "%joh%"@
   ,(~=?),(~~?)
   , (|||), (&&&), pnot, pnull, pin, pinArr
   , pparent, pchild
@@ -93,6 +114,8 @@
   -- ** Order By and Limit/Offset
   , ordf, ascf, descf, defLO, lo1
   -- ** Internals
+  -- | Types and functions that appear in the signatures above, and the building
+  -- blocks for unsafe conditions and ordering ('pUnsafeCond', 'UnsafeOrd').
   , Selectable, CRecInfo(..)
   , MonadQP, CondWithPath(..), OrdWithPath(..)
   , Cond(..), CondAnn, Cmp(..), BoolOp(..), TabParam(..), defTabParam
@@ -105,15 +128,19 @@
   --
   -- - For insert you need all mandatory fields.
   -- - For key-based update you need a full primary or unique key.
-  -- - For upsert you need all mandatory fields _and_ some key.
+  -- - For upsert you need all mandatory fields /and/ some key.
   --
   -- You can get in return any subset of the columns of the table which was affected by the operation.
-  -- For update you get `Maybe t`. It is `Nothing` if the row was not found by the key.
+  -- For key-based update each returned row is @Maybe r'@: it is 'Nothing' if the row was not found by the key.
   --
   -- All these constraints are checked at compile time.
   --
-  -- There is also operations to update or delete data by a condition.
+  -- There are also operations to update or delete data by a condition.
   --
+  -- Input rows can be records, rows of fields built with '(=:)', or plain values
+  -- made into rows with 'rowsOf' or 'named'; 'plains' gives plain values of the
+  -- returned rows.
+  --
   , insertSch, insertSch_, insertText, insertText_
   , upsertByKey, upsertByKey_, upsertByKeyText, upsertByKeyText_
   , updateByKey, updateByKey_, updateByKeyText, updateByKeyText_
@@ -130,27 +157,30 @@
   --
   -- - For insert you need all mandatory fields at every node.
   -- - For update you need a full primary or unique key at every node.
-  -- - For upsert you need all mandatory fields _or_ some key at every node.
+  -- - For upsert you need all mandatory fields /or/ some key at every node.
   --
   --     At each node:
   --
-  --     - the operation works like an insert if there is no key
-  --     - the operation works like an update if there is not all mandatory fields
-  --     - the operation works like an upsert if there is all mandatory fields and a key exists
+  --     - the operation works like an insert if there is no key;
+  --     - the operation works like an update if not all mandatory fields are present;
+  --     - the operation works like an upsert if all mandatory fields and a key are present.
   --
   -- You don't need foreign keys for children in your data (and often even keys for parents).
   -- They will be determined automatically.
   --
   -- You can get in return any subset of the columns of the tables which were affected by the operation.
-  -- All rows returned in the same order as the input tree.
+  -- All rows are returned in the same order as in the input tree.
   -- For update or some nodes of upsert (where not all mandatory fields are present),
-  -- the returning type is `Maybe t`. It is 'Nothing' if the row was not found by the key.
+  -- the returning type is @Maybe r'@. It is 'Nothing' if the row was not found by the key.
   --
   -- All these constraints are checked at compile time.
   --
   -- For all these operations you should use types that can be converted to JSON (and from JSON for returning).
   -- You don't need instances but all fields should be serializable into JSON.
-  -- I.e. you can't use 'Bytestring' for fields here.
+  -- E.g. you can't use 'Data.ByteString.ByteString' fields here.
+  --
+  -- Input trees are easy to write as plain values with 'rowsOf' (see the
+  -- example at the top of this module).
   , insertJSON, insertJSON_, upsertJSON, upsertJSON_
   , updateJSON, updateJSON_, insertJSONText, insertJSONText_
   , upsertJSONText, upsertJSONText_, updateJSONText, updateJSONText_
@@ -166,7 +196,9 @@
   -- ** Renamers
   , RenamerId, CamelToSnake, Renamer, ApplyRenamer, ApplyRenamerNS
   -- ** PgTag types
-  , type (:=), (=:), PgTag(..),
+  , type (:=), (=:), PgTag(..), named, Named,
+  -- ** Plain values of rows
+  rowsOf, rowOf, plains, plain, Plain, PlainRow,
   -- | Re-export from postgresql-simple
   (:.)(..)
   -- ** Enum
@@ -178,16 +210,21 @@
   -- ** Arrays
   , PgArr(..), pgArr', unPgArr'
   -- ** Conversion checks
-  , CanConvert, CanConvert1, TypDef'(..)
+  , CanConvert, CanConvert1, CheckAggr, TypDef'(..)
   -- ** Other types
-  , PgChar(..), PgOid(..)
+  , PgChar(..)
   , NameNS'(..), type (->>), NameNSK, (->>)
   , PathElem'(..), PathElem, PathElemK, PathKind(..)
-  , TRelDef, RelDef'(..), RdFrom, RdTo, FdType, FdNullable, CTabDef(..)
+  , TRelDef, RelDef'(..), FldDef', CTabDef(..)
+  -- | Type-level selectors (promoted record fields): 'RdFrom' and 'RdTo' give
+  -- the child and the parent table of a t'RelDef'', 'FdType' and 'FdNullable'
+  -- give the type and the nullability of a t'FldDef''.
+  , RdFrom, RdTo, FdType, FdNullable
   ) where
 
 
 import PgSchema.Ann
+import PgSchema.Plain
 import PgSchema.DML.Select as S
 import PgSchema.DML.Select.Types as S
 import PgSchema.DML.Insert as I
diff --git a/src/PgSchema/DML/Delete.hs b/src/PgSchema/DML/Delete.hs
--- a/src/PgSchema/DML/Delete.hs
+++ b/src/PgSchema/DML/Delete.hs
@@ -15,6 +15,9 @@
 
 -- | Delete records in table by condition.
 --
+-- Returns the number of deleted rows, the SQL text and the values of its
+-- placeholders.
+--
 deleteByCond :: forall ann -> SingI (AnnTab ann) => Connection -> CondAnn ann
   -> IO (Int64, (Text,[SomeToField]))
 deleteByCond ann conn cond = traceShow' (q,ps)
diff --git a/src/PgSchema/DML/Insert.hs b/src/PgSchema/DML/Insert.hs
--- a/src/PgSchema/DML/Insert.hs
+++ b/src/PgSchema/DML/Insert.hs
@@ -19,6 +19,9 @@
 -- they need not appear in the input row (e.g. @RETURNING id@ without @id@ in @r@).
 -- All mandatory fields having no defaults should be present in @r@.
 --
+-- Returns the returned rows (one per input row, in the same order) and the
+-- SQL text.
+--
 insertSch
   :: forall ann -> forall r r'. InsertReturning ann r r'
   => Connection -> [r] -> IO ([r'], Text)
@@ -29,6 +32,8 @@
     . fmap (PgTag @ann @r)
 
 -- | Insert records into a table without @RETURNING@.
+--
+-- Returns the number of inserted rows and the SQL text.
 insertSch_ :: forall ann -> forall r. (InsertNonReturning ann r) =>
   Connection -> [r] -> IO (Int64, Text)
 insertSch_ ann @r conn recs = let sql = insertText_ ann @r in do
diff --git a/src/PgSchema/DML/Insert/Types.hs b/src/PgSchema/DML/Insert/Types.hs
--- a/src/PgSchema/DML/Insert/Types.hs
+++ b/src/PgSchema/DML/Insert/Types.hs
@@ -25,7 +25,7 @@
   (PlainIn ann r, CheckAllMandatory ann (ColsDbNames (Cols ann r)))
 
 -- | Plain insert with @RETURNING@: @r'@ is any bare plain column subset of the
--- table ('PlainOut'); tree 'ReturningMatchesInsert' is for 'insertJSON' only.
+-- table ('PlainOut'); tree 'ReturningMatchesInsert' is for 'PgSchema.DML.insertJSON' only.
 type InsertReturning ann r r' =
   ( InsertNonReturning ann r, PlainOut ann r', RequireBareRow r' )
 
@@ -39,13 +39,15 @@
 
 -- | Upsert one table row by primary / unique key (@ToRow@, no JSON).
 --
--- Requires all mandatory fields and a full primary or eligible unique key so
+-- Requires all mandatory fields and a full primary or unique key so
 -- the operation is always @INSERT … ON CONFLICT …@. Use 'InsertNonReturning' or
 -- 'UpdateByKeyNonReturning' for insert-only or update-only flat writes.
 type UpsertByKeyNonReturning ann r =
   ( PlainIn ann r, HasSchema ann
   , CheckAllMandatoryAndHasKey ann (ColsDbNames (Cols ann r)) )
 
+-- | Upsert one table row by key with @RETURNING@: the constraints of
+-- 'UpsertByKeyNonReturning', and @r'@ is any bare plain column subset of the table.
 type UpsertByKeyReturning ann r r' =
   ( UpsertByKeyNonReturning ann r, PlainOut ann r', RequireBareRow r' )
 
@@ -86,7 +88,7 @@
 
 -- | Upsert tree without @RETURNING@.
 --
--- Check that all mandatory fields or a full primary / eligible unique key are
+-- Check that all mandatory fields or a full primary / unique key are
 -- present at each tree node.
 -- Reference fields in the child tables are not checked - they are inserted automatically.
 type UpsertTreeNonReturning ann r =
@@ -94,7 +96,7 @@
 
 -- | Upsert tree with @RETURNING@.
 --
--- Check that all mandatory fields or a full primary / eligible unique key are
+-- Check that all mandatory fields or a full primary / unique key are
 -- present at each tree node.
 -- Reference fields in the child tables are not checked - they are inserted automatically.
 --
diff --git a/src/PgSchema/DML/InsertJSON.hs b/src/PgSchema/DML/InsertJSON.hs
--- a/src/PgSchema/DML/InsertJSON.hs
+++ b/src/PgSchema/DML/InsertJSON.hs
@@ -40,8 +40,21 @@
 -- Uses the same SQL pipeline as 'upsertJSON', but each row is a plain @INSERT@
 -- (no @UPDATE@, no @INSERT … ON CONFLICT …@). Any duplicate primary or unique key
 -- raises a PostgreSQL error. Requires all mandatory columns at every node
--- ('InsertTreeReturning'; 'ReturningMatchesInsert' on @r'@). Flat 'insertSch'
--- uses 'PlainOut' only.
+-- ('InsertTreeReturning'; 'ReturningMatchesInsert' on @r'@).
+--
+-- /@json@ \/ @jsonb@ columns/: 'Nothing' is stored as SQL @NULL@ (as in
+-- 'PgSchema.DML.insertSch'). Rows travel to PostgreSQL as one JSON document, where
+-- 'Nothing' and a JSON @null@ value (e.g. @Just 'A.Null'@ in a
+-- @Maybe 'A.Value'@ field) are both encoded as @null@, so a JSON @null@ value
+-- is stored as SQL @NULL@ too and is read back as 'Nothing'. The same holds
+-- for 'upsertJSON' and 'updateJSON' (including the @SET@ part of an update or
+-- upsert). Use 'PgSchema.DML.insertSch' \/
+-- 'PgSchema.DML.updateByCond' if you need to store the JSON
+-- value @null@ itself.
+--
+-- Returns the returned rows (in the same order as the input rows, children in
+-- the order of the input children) and the SQL text of the temporary function
+-- (see 'insertJSONText').
 insertJSON
   :: forall ann -> forall r r'. InsertTreeReturning ann r r'
   => Connection -> [r] -> IO ([r'], Text)
@@ -49,6 +62,7 @@
 
 -- | Like 'insertJSON', but does not return rows.
 --
+-- Returns the SQL text of the temporary procedure (see 'insertJSONText_').
 insertJSON_
   :: forall ann -> forall r. InsertTreeNonReturning ann r
   => Connection -> [r] -> IO Text
@@ -57,9 +71,28 @@
 -- | Upsert a forest of rows into the root table and its /child/ tables in one
 -- round-trip, using JSON inside PostgreSQL (same pipeline as 'insertJSON').
 --
--- See Haddock on previous versions for input/output shape and per-row @INSERT@ /
--- @UPDATE@ / @UPSERT@ selection. Returning list elements use bare rows where the
--- input node has all mandatory fields, and @Maybe@ otherwise ('ReturningMatchesUpsert').
+-- The input has the same shape as for 'insertJSON': child rows are given in list
+-- fields named after the foreign keys, and their foreign-key columns are taken
+-- from the parent row automatically. Every node must have all mandatory columns
+-- or a full primary / unique key ('UpsertTreeReturning'). The operation is chosen
+-- for each node separately:
+--
+-- * not all mandatory columns are present: @UPDATE@ by key (the row may be not
+--   found; then its children are skipped);
+-- * all mandatory columns and a full key are present:
+--   @INSERT … ON CONFLICT (key) DO UPDATE@ of the other given columns, or
+--   @INSERT … ON CONFLICT DO NOTHING@ if there are no other columns (an existing
+--   row with this key is then looked up within the parent);
+-- * all mandatory columns, but no key: plain @INSERT@.
+--
+-- The key is the first fully covered one of: the primary key, unique keys over
+-- @NOT NULL@ columns, other unique keys.
+--
+-- Returning list elements must be bare rows where the node is always inserted or
+-- upserted, and @Maybe@ where the row may be not found ('ReturningMatchesUpsert').
+--
+-- 'Nothing' (and a JSON @null@ value) for a @json@ \/ @jsonb@ column is
+-- stored as SQL @NULL@; see 'insertJSON'.
 upsertJSON
   :: forall ann -> forall r r'. UpsertTreeReturning ann r r'
   => Connection -> [r] -> IO ([r'], Text)
@@ -67,6 +100,7 @@
 
 -- | Like 'upsertJSON', but does not return rows.
 --
+-- Returns the SQL text of the temporary procedure (see 'upsertJSONText_').
 upsertJSON_
   :: forall ann -> forall r. UpsertTreeNonReturning ann r
   => Connection -> [r] -> IO Text
@@ -74,7 +108,10 @@
 
 -- | Update an existing forest (never @INSERT@). Returning type @r'@ must satisfy
 -- 'ReturningMatchesUpdate' (@Maybe@ on each child list element). Flat
--- 'updateByKey' instead uses bare @r'@ and returns @IO ([Maybe r'], Text)@.
+-- 'PgSchema.DML.updateByKey' instead uses bare @r'@ and returns @IO ([Maybe r'], Text)@.
+--
+-- 'Nothing' (and a JSON @null@ value) for a @json@ \/ @jsonb@ column sets it
+-- to SQL @NULL@; see 'insertJSON'.
 updateJSON
   :: forall ann -> forall r r'. UpdateTreeReturning ann r r'
   => Connection -> [r] -> IO ([r'], Text)
@@ -82,6 +119,7 @@
 
 -- | Like 'updateJSON', but does not return rows.
 --
+-- Returns the SQL text of the temporary procedure (see 'updateJSONText_').
 updateJSON_
   :: forall ann -> forall r. UpdateTreeNonReturning ann r
   => Connection -> [r] -> IO Text
@@ -126,12 +164,23 @@
     sql = insertJSONText' mode (typDefMap @(AnnSch ann)) (tabInfoMap @(AnnSch ann))
       (getRecordInfo @ann @r) []
 
+-- | SQL text used by 'insertJSON_'.
+--
+-- The text creates a temporary PL/pgSQL procedure @pg_temp.__ins(data_0 jsonb)@
+-- that inserts the rows given as a JSON array. 'insertJSON_' runs it in a transaction
+-- (if there is none yet) and drops it afterwards.
 insertJSONText_ :: forall ann -> forall r s.
   (IsString s, Monoid s, Ord s, HasSchema ann, CRecInfo ann r) => s
 insertJSONText_ ann @r =
   insertJSONText' Insert (typDefMap @(AnnSch ann)) (tabInfoMap @(AnnSch ann))
     (getRecordInfo @ann @r) []
 
+-- | SQL text used by 'insertJSON'.
+--
+-- The text creates a temporary PL/pgSQL function @pg_temp.__ins(data_0 jsonb)@ returning @jsonb@
+-- that inserts the rows given as a JSON array. 'insertJSON' runs it in a transaction
+-- (if there is none yet) and drops it afterwards.
+-- The function returns the rows of @r'@ as a JSON array.
 insertJSONText :: forall ann -> forall r r'.
   ( HasSchema ann, CRecInfo ann r, CRecInfo ann r'
   , IsString s, Monoid s, Ord s ) => s
@@ -139,12 +188,23 @@
   insertJSONText' Insert (typDefMap @(AnnSch ann)) (tabInfoMap @(AnnSch ann))
     (getRecordInfo @ann @r) (getRecordInfo @ann @r').fields
 
+-- | SQL text used by 'upsertJSON_'.
+--
+-- The text creates a temporary PL/pgSQL procedure @pg_temp.__ins(data_0 jsonb)@
+-- that upserts the rows given as a JSON array. 'upsertJSON_' runs it in a transaction
+-- (if there is none yet) and drops it afterwards.
 upsertJSONText_ :: forall ann -> forall r s.
   (IsString s, Monoid s, Ord s, HasSchema ann, CRecInfo ann r) => s
 upsertJSONText_ ann @r =
   insertJSONText' Upsert (typDefMap @(AnnSch ann)) (tabInfoMap @(AnnSch ann))
     (getRecordInfo @ann @r) []
 
+-- | SQL text used by 'upsertJSON'.
+--
+-- The text creates a temporary PL/pgSQL function @pg_temp.__ins(data_0 jsonb)@ returning @jsonb@
+-- that upserts the rows given as a JSON array. 'upsertJSON' runs it in a transaction
+-- (if there is none yet) and drops it afterwards.
+-- The function returns the rows of @r'@ as a JSON array.
 upsertJSONText :: forall ann -> forall r r'.
   ( HasSchema ann, CRecInfo ann r, CRecInfo ann r'
   , IsString s, Monoid s, Ord s ) => s
@@ -152,12 +212,23 @@
   insertJSONText' Upsert (typDefMap @(AnnSch ann)) (tabInfoMap @(AnnSch ann))
     (getRecordInfo @ann @r) (getRecordInfo @ann @r').fields
 
+-- | SQL text used by 'updateJSON_'.
+--
+-- The text creates a temporary PL/pgSQL procedure @pg_temp.__ins(data_0 jsonb)@
+-- that updates the rows given as a JSON array. 'updateJSON_' runs it in a transaction
+-- (if there is none yet) and drops it afterwards.
 updateJSONText_ :: forall ann -> forall r s.
   (IsString s, Monoid s, Ord s, HasSchema ann, CRecInfo ann r) => s
 updateJSONText_ ann @r =
   insertJSONText' Update (typDefMap @(AnnSch ann)) (tabInfoMap @(AnnSch ann))
     (getRecordInfo @ann @r) []
 
+-- | SQL text used by 'updateJSON'.
+--
+-- The text creates a temporary PL/pgSQL function @pg_temp.__ins(data_0 jsonb)@ returning @jsonb@
+-- that updates the rows given as a JSON array. 'updateJSON' runs it in a transaction
+-- (if there is none yet) and drops it afterwards.
+-- The function returns the rows of @r'@ as a JSON array.
 updateJSONText :: forall ann -> forall r r'.
   ( HasSchema ann, CRecInfo ann r, CRecInfo ann r'
   , IsString s, Monoid s, Ord s ) => s
@@ -189,8 +260,6 @@
 
 type MonadInsert s = RWS (s, Int) ([s],[s]) Int
 
-data OP = INS | UPD | UPS deriving (Eq, Show)
-
 data Field v = Field
   { jsonName :: Text
   , dbName :: Text
@@ -228,7 +297,7 @@
       Just ti ->
         fromMaybe [] $ pickKeyNames ti (parentDbKeys <> ((.dbName) <$> iplains))
       Nothing -> []
-    (ins, op) = resolve
+    (ins, mayMiss) = resolve
       where
         jsonFld ip = case mapTypes M.!? ip.info.fdType of
           Just (TypDef "A" (Just t) _) ->
@@ -236,7 +305,12 @@
             <> " then (select coalesce(array_agg(__x)::" <> fromText (qualName t) <> "[], '{}')"
             <> " from jsonb_array_elements_text(" <> rowN <> ".value->'" <> fld <> "') __x) else null end"
           _
-            | tn == "json" || tn == "jsonb" -> "(" <> rowN <> ".value->'" <> fld <> "')"
+            -- @->@ gives the jsonb value @'null'@ for @"fld": null@ (how
+            -- 'Nothing' is encoded); turn it into SQL @NULL@. @row_N.value@
+            -- is always @jsonb@, so the comparison works for @json@ columns
+            -- too (stored via the jsonb -> json assignment cast).
+            | tn == "json" || tn == "jsonb" ->
+              "nullif(" <> rowN <> ".value->'" <> fld <> "', 'null'::jsonb)"
             | otherwise                     -> "(" <> rowN <> ".value->>'" <> fld <> "')::" <> ty
           where
             fld = fromText ip.jsonName
@@ -272,7 +346,13 @@
             <> " into " <> intercalate' ", " qretVars]
         ups0 conflictCols
           | L.null plainsOthers = case mbSetVars of
+            -- on conflict the row with this key must belong to this parent:
+            -- otherwise it is not found (@mayMiss@)
             Just xs -> ins0 <> [ "    on conflict do nothing;"]
+              <> ["  if not found then"
+                , "    perform 1 from " <> qualTabName
+                , "      " <> sWhere <> ";"
+                , "  end if;"]
               <> ["  " <> intercalate' " " xs]
             Nothing -> ins0 <> addSemiColon ([ "    on conflict do nothing"] <> rets)
               <> ["  if not found then"
@@ -287,15 +367,19 @@
               , "      do update set " <> intercalate' ", "
                   (plainsOthers <&> \(name, _) -> name <> " = EXCLUDED." <> name) ]
             <> rets
+        -- @mayMiss@: the row may be not found (@UPDATE@ by key, or
+        -- @ON CONFLICT DO NOTHING@ with the key of a row of another parent);
+        -- then its children are skipped and @null@ is returned for it.
         resolve
           | mode == Update =
-            (addSemiColon (upd0 <> rets), UPD)
+            (addSemiColon (upd0 <> rets), True)
           | mode == Insert =
-            (addSemiColon (ins0 <> rets), INS)
+            (addSemiColon (ins0 <> rets), False)
           | keyOnlyInput =
-            (addSemiColon (upd0 <> rets), UPD)
-          | not $ P.null keyNamesTxt = (ups0 keyNames, UPS)
-          | otherwise = (addSemiColon (ins0 <> rets), INS)
+            (addSemiColon (upd0 <> rets), True)
+          | not $ P.null keyNamesTxt =
+            (ups0 keyNames, L.null plainsOthers)
+          | otherwise = (addSemiColon (ins0 <> rets), False)
     endLoop = "end loop;"
     processChildren = do
       (spaces', _) <- ask
@@ -322,37 +406,25 @@
             <> "', " <> fromText qp.dbName <> sn)
           <> (arrs <&> \(jsonN, arr) -> "'" <> jsonN <> "', to_jsonb(" <> arr <> ")")
         obj = "jsonb_build_object(" <> jsonFlds <> ")"
-      in case (mode, op) of
-        (Update, UPD) ->
+      in if mayMiss
+        then
           [ spaces <> "  if " <> foundN <> " then"
           , spaces <> "    " <> arrN <> " := array_append(" <> arrN <> ", " <> obj <> ");"
           , spaces <> "  else"
           , spaces <> "    " <> arrN <> " := array_append("
             <> arrN <> ", 'null'::jsonb);"
           , spaces <> "  end if;" ]
-        (Upsert, UPD)
-          | keyOnlyInput ->
-            [ spaces <> "  if " <> foundN <> " then"
-            , spaces <> "    " <> arrN <> " := array_append(" <> arrN <> ", " <> obj <> ");"
-            , spaces <> "  else"
-            , spaces <> "    " <> arrN <> " := array_append("
-              <> arrN <> ", 'null'::jsonb);"
-            , spaces <> "  end if;" ]
-          | otherwise ->
-            [ spaces <> "  if " <> foundN <> " then"
-            , spaces <> "    " <> arrN <> " := array_append(" <> arrN <> ", " <> obj <> ");"
-            , spaces <> "  end if;" ]
-        _ ->
+        else
           [ spaces <> "  " <> arrN <> " := array_append(" <> arrN <> ", " <> obj <> ");" ]
   tell (decs, fmap (spaces <>) $ initArray <> startLoop <> ins
     <> [spaces <> "  " <> foundN <> " := found;"])
-  arrs <- case op of
-    UPD -> do
-      tell (mempty, pure $ spaces <> "  if found then")
+  arrs <- if mayMiss
+    then do
+      tell (mempty, pure $ spaces <> "  if " <> foundN <> " then")
       ch <- local (first ("    " <>)) processChildren
       tell (mempty, pure $ spaces <> "  end if;")
       pure ch
-    _ -> local (first ("  " <>)) processChildren
+    else local (first ("  " <>)) processChildren
   case mbArrN of
     Nothing -> pure ()
     Just arrN -> tell (mempty, appendReturning arrN arrs)
diff --git a/src/PgSchema/DML/KeyedWrite.hs b/src/PgSchema/DML/KeyedWrite.hs
--- a/src/PgSchema/DML/KeyedWrite.hs
+++ b/src/PgSchema/DML/KeyedWrite.hs
@@ -12,7 +12,8 @@
 import Prelude as P
 
 
--- | Runtime conflict/update targets (same order as 'InsertJSON').
+-- | Runtime conflict/update targets: the primary key, then unique keys over
+-- @NOT NULL@ columns, then other unique keys (used by "PgSchema.DML.InsertJSON").
 identityCandidatesFromTab :: TabInfo -> [[Text]]
 identityCandidatesFromTab ti =
   P.filter (not . P.null) [ti.tiDef.tdKey] <> notNullUks <> nullUks
@@ -44,13 +45,20 @@
     keyNames = fromMaybe [] $ pickKeyNames ti srcFlds
   in L.partition ((`L.elem` keyNames) . fst) plains
 
-upsertOnConflict :: [(Text, Text)] -> [Text] -> Text
-upsertOnConflict plainsOthers conflictCols =
-  case (L.null plainsOthers, conflictCols) of
-    (True, _) -> " on conflict do nothing"
-    (_, []) -> ""
-    (_, cols) ->
-      " on conflict (" <> T.intercalate ", " cols <> ")"
-        <> " do update set "
-        <> T.intercalate ", "
-          ( L.map (\(name, _) -> name <> " = EXCLUDED." <> name) plainsOthers )
+-- | @ON CONFLICT@ clause of a flat upsert with the conflict key @conflictCols@:
+-- on conflict the other columns (@plainsOthers@) are updated.
+--
+-- If there are no other columns, an existing row is left as is. Without
+-- @RETURNING@ it is @DO NOTHING@. With @RETURNING@ it is a no-op @DO UPDATE@
+-- of a key column, because @DO NOTHING@ returns nothing for an existing row.
+upsertOnConflict :: Bool -> [(Text, Text)] -> [Text] -> Text
+upsertOnConflict withReturning plainsOthers conflictCols =
+  case (conflictCols, plainsOthers) of
+    ([], _) -> ""
+    (k : _, [])
+      | withReturning -> target <> " do update set " <> k <> " = EXCLUDED." <> k
+      | otherwise -> target <> " do nothing"
+    (_, xs) -> target <> " do update set "
+      <> T.intercalate ", " (L.map (\(name, _) -> name <> " = EXCLUDED." <> name) xs)
+  where
+    target = " on conflict (" <> T.intercalate ", " conflictCols <> ")"
diff --git a/src/PgSchema/DML/Select.hs b/src/PgSchema/DML/Select.hs
--- a/src/PgSchema/DML/Select.hs
+++ b/src/PgSchema/DML/Select.hs
@@ -69,13 +69,18 @@
 -- when the foreign-key side you join from allows NULL).
 --
 -- What actually appears in the generated SQL beyond that shape is controlled by
--- the 'QueryParam': filters, which paths are traversed, ordering on a branch
+-- the t'QueryParam': filters, which paths are traversed, ordering on a branch
 -- (e.g. child rows sorted by their position number), limits, and similar options.
--- You only configure in 'QueryParam' what you need for this query—not every
+-- You only configure in t'QueryParam' what you need for this query—not every
 -- possible relation field in @r@.
 --
--- Build 'QueryParam' with the 'MonadQP' API.
+-- Build t'QueryParam' with the 'MonadQP' API.
 --
+-- To pattern match on rows of t'PgTag' fields without unwrapping every field,
+-- use 'PgSchema.DML.plains':
+--
+-- > rows <- plains @("id" := Int64 :. "name" := Text) . fst <$> selectSch (MyAnn "users") conn qpEmpty
+--
 selectSch :: forall ann -> forall r. Selectable ann r
   => Connection -> QueryParamAnn ann -> IO ([r], (Text,[SomeToField]))
 selectSch ann @r conn (selectText ann @r -> (sql,fs)) =
@@ -196,7 +201,6 @@
 -- (non-obvious for nested relation fields).
 fieldM :: MonadQuery ren sch tab m => FieldInfo Text -> m (Text, Text, Text)
 fieldM fi = case fi.fieldKind of
-  RFEmpty s -> pure ("null", s, "true")
   RFSelfRef{} -> error "Impossible: RFSelfRef should be changed to RFFromHere or RFToHere"
   RFPlain {} -> do
     n <- asks qrCurrTabNum
@@ -295,11 +299,18 @@
 runCond :: Int -> CondMonad a -> (a,[SomeToField])
 runCond n x = evalRWS x ("q", pure n) 0
 
+-- | Alias of the current table in the generated SQL (e.g. @t0@), for
+-- unsafe conditions and ordering ('pUnsafeCond', 'UnsafeOrd').
 tabPref :: CondMonad Text
 tabPref = asks \case
   (_, n :| []) -> "t" <> show' n
   (p, n :| (np : _)) -> "t" <> show' np <> p <> show' n
 
+-- | Column @fld@ qualified with the alias of the current table
+-- (e.g. @t0.name@), for unsafe conditions and ordering ('pUnsafeCond',
+-- 'UnsafeOrd'). @fld@ is a database name: the renamer is not applied.
+--
+-- > qual @"name"
 qual :: forall (fld :: Symbol). ToStar fld => CondMonad Text
 qual = tabPref <&> (<> "." <> (demote @fld))
 
diff --git a/src/PgSchema/DML/Select/Types.hs b/src/PgSchema/DML/Select/Types.hs
--- a/src/PgSchema/DML/Select/Types.hs
+++ b/src/PgSchema/DML/Select/Types.hs
@@ -34,30 +34,46 @@
 
 -- | Parameters that are used to describe @SELECT@.
 --
--- You don't need to make it directly. Use 'MonadQP' to define 'QueryParam' instead.
+-- You don't need to make it directly. Use 'MonadQP' to define t'QueryParam' instead.
 --
 data QueryParam ren sch t = QueryParam
-  { qpConds     :: ![CondWithPath ren sch t]    -- ^ `where` conditions for branches of Data-Tree
-  , qpOrds      :: ![OrdWithPath ren sch t]     -- ^ `order by` clauses
-  , qpLOs       :: ![LimOffWithPath ren sch t]  -- ^ `limit/offset` clauses
-  , qpDistinct  :: ![DistWithPath ren sch t]    -- ^ `distinct` and `distinct on` clauses
+  { qpConds     :: ![CondWithPath ren sch t]    -- ^ @WHERE@ conditions for branches of the data tree
+  , qpOrds      :: ![OrdWithPath ren sch t]     -- ^ @ORDER BY@ clauses
+  , qpLOs       :: ![LimOffWithPath ren sch t]  -- ^ @LIMIT@ / @OFFSET@ clauses
+  , qpDistinct  :: ![DistWithPath ren sch t]    -- ^ @DISTINCT@ and @DISTINCT ON@ clauses
   }
 
+-- | t'QueryParam' for the renamer, schema and root table of annotation @ann@.
+--
+-- It is the type of query parameters accepted by 'PgSchema.DML.selectSch'.
 type QueryParamAnn ann = QueryParam (AnnRen ann) (AnnSch ann) (AnnTab ann)
 
--- | Empty 'QueryParam'.
+-- | Empty t'QueryParam'.
 --
--- It means that @SELECT@ is defined only by structure of output type
+-- It means that @SELECT@ is defined only by the structure of the output type.
 qpEmpty :: forall ren sch t. QueryParam ren sch t
 qpEmpty = QueryParam [] [] [] []
 
+-- | Monad to describe t'QueryParam' for root table @t@.
+--
+-- @path@ is the path from the root table to the current table (the table that
+-- conditions, ordering, limits etc. are applied to). It is empty for the root
+-- table and is extended by 'qPath', 'qPathFromHere' and 'qPathToHere'.
+--
+-- Run it with 'qRoot':
+--
+-- > qRoot do
+-- >   qWhere $ "name" ~~? "%john%"
+-- >   qPath "tasks" do
+-- >     qOrderBy [descf "created_at"]
+-- >     qLimit 10
 type MonadQP ren sch t path
   = PathCtx ren sch t path
   => RWS (Proxy path) () (QueryParam ren sch t) ()
 
--- | Execute 'MonadQP' and get 'QueryParam'.
+-- | Execute 'MonadQP' and get t'QueryParam'.
 --
--- The table `t` defines a context and becomes the "current" table
+-- The table @t@ defines a context and becomes the "current" table.
 qRoot :: RWS (Proxy '[]) () (QueryParam ren sch t) () -> QueryParam ren sch t
 qRoot m = fst $ execRWS m Proxy qpEmpty
 
@@ -94,17 +110,18 @@
 type PathCheck pathKind p ren sch t path path' tabPath p' k =
   ( p' ~ ApplyRenamer ren p
   , tabPath ~ TabOnDPathRen ren sch t path
-  , k ~ ResolvePathKind pathKind (HasFromStep sch tabPath p') (HasToStep sch tabPath p') tabPath p'
+  , k ~ ResolvePathKind pathKind (HasFromStep sch tabPath p') (HasToStep sch tabPath p')
+      sch tabPath p p'
   , path' ~ (path ++ '[ 'PathElem p p' k ])
   , PathCtx ren sch t path'
   )
 -- | Add @WHERE@ condition for the current table.
 --
--- If several 'qWhere' exist they are composed according to the 'Monoid' instance for 'Cond', i.e. with '(&&&)'
+-- If several 'qWhere' exist they are composed according to the 'Monoid' instance for 'Cond', i.e. with '(&&&)'.
 qWhere :: forall ren sch t path. Cond ren sch (TabOnDPathRen ren sch t path) -> MonadQP ren sch t path
 qWhere c = modify \qp -> qp { qpConds = CondWithPath @path (demote @path) c : qp.qpConds }
 
--- | Add @ORDER BY@ condition for the current table
+-- | Add @ORDER BY@ condition for the current table.
 --
 -- Several 'qOrderBy' are possible and they are composed together.
 --
@@ -122,7 +139,7 @@
 qOrderBy :: forall ren sch t path. [OrdFld ren sch (TabOnDPathRen ren sch t path)] -> MonadQP ren sch t path
 qOrderBy ofs = modify \qp -> qp { qpOrds = OrdWithPath @path (demote @path) ofs : qp.qpOrds }
 
--- | Add `DISTINCT` condition for the current table.
+-- | Add @DISTINCT@ condition for the current table.
 -- It is applied only to "root" or "children" tables.
 qDistinct :: forall ren sch t path. PathEndsMany sch t path =>
   MonadQP ren sch t path
@@ -133,7 +150,7 @@
 -- It can also be applied on a parent table because that parent is joined to the current table.
 --
 -- 'qDistinctOn' automatically adds fields to the @ORDER BY@ clause (as PostgreSQL requires).
--- (That's why 'OrdDirection' is needed)
+-- (That's why 'OrdDirection' is needed.)
 -- So having
 --
 -- @
@@ -150,10 +167,10 @@
 qDistinctOn ofs =
   modify \qp -> qp { qpDistinct = DistWithPath @path (demote @path) (DistinctOn ofs) : qp.qpDistinct }
 
--- | Add `LIMIT` condition for the current table.
+-- | Add @LIMIT@ condition for the current table.
 -- It is applied only to "root" or "children" tables.
 --
--- If 'qLimit' is applied several times on the same path, only the last one is used
+-- If 'qLimit' is applied several times on the same path, only the last one is used.
 qLimit :: forall ren sch t path. PathEndsMany sch t path =>
   Natural -> MonadQP ren sch t path
 qLimit n = modify \qp -> qp { qpLOs = mk qp.qpLOs }
@@ -165,10 +182,10 @@
     upd (LimOffWithPath @p' p lo) = LimOffWithPath @p' p lo{ limit = Just n }
     new = LimOffWithPath @path (demote @path) LO { limit = Just n, offset = Nothing }
 
--- | Add `OFFSET` condition for the current table.
+-- | Add @OFFSET@ condition for the current table.
 -- It is applied only to "root" or "children" tables.
 --
--- If 'qOffset' is applied several times on the same path, only the last one is used
+-- If 'qOffset' is applied several times on the same path, only the last one is used.
 qOffset :: forall ren sch t path. PathEndsMany sch t path =>
   Natural -> MonadQP ren sch t path
 qOffset n = modify \qp -> qp { qpLOs = mk qp.qpLOs }
@@ -180,35 +197,37 @@
     upd (LimOffWithPath @p' p lo) = LimOffWithPath @p' p lo{offset = Just n}
     new = LimOffWithPath @path (demote @path) LO { offset = Just n, limit = Nothing }
 
--- | GADT to safely set `where` condition
+-- | GADT to safely set @WHERE@ condition.
 data CondWithPath ren sch t where
   CondWithPath :: forall (path :: [PathElemK]) ren sch t. PathCtx ren sch t path
     => [PathElem] -> Cond ren sch (TabOnDPathRen ren sch t path) -> CondWithPath ren sch t
 
--- | GADT to safely set `order by` clauses
+-- | GADT to safely set @ORDER BY@ clauses.
 data OrdWithPath ren sch t where
   OrdWithPath :: forall (path :: [PathElemK]) ren sch t. PathCtx ren sch t path
     => [PathElem] -> [OrdFld ren sch (TabOnDPathRen ren sch t path)] -> OrdWithPath ren sch t
 
--- | GADT to safely set `distinct/distinct on` clauses
+-- | GADT to safely set @DISTINCT@ / @DISTINCT ON@ clauses.
 data DistWithPath ren sch t where
   DistWithPath :: forall (path :: [PathElemK]) ren sch t. PathCtx ren sch t path
     => [PathElem] -> Dist ren sch (TabOnDPathRen ren sch t path) -> DistWithPath ren sch t
 
--- | GADT to safely set `limit/offset` clauses
+-- | GADT to safely set @LIMIT@ / @OFFSET@ clauses.
 data LimOffWithPath ren sch t where
   LimOffWithPath :: forall (path :: [PathElemK]) ren sch t.
     ( PathCtx ren sch t path, PathEndsMany sch t path )
     => [PathElem] -> LO -> LimOffWithPath ren sch t
 
 -- | Comparison constructors; each is paired with its corresponding operator
--- (e.g. '(:=)' with '(=?)').
+-- (e.g. v'(:=)' with '(=?)').
 data Cmp = (:=) | (:<=) | (:>=) | (:>) | (:<) | Like | ILike | NotDistinctFrom
   deriving (Show, Eq, Generic)
 
--- | Just boolean operations
+-- | Boolean operations.
 data BoolOp = And | Or deriving (Show, Eq, Generic)
 
+-- | SQL operator for the comparison, e.g. @\"<=\"@ for v'(:<=)' or
+-- @\"ilike\"@ for 'ILike'.
 showCmp :: IsString s => Cmp -> s
 showCmp = \case
   (:=)  -> "="
@@ -220,16 +239,24 @@
   ILike -> "ilike"
   NotDistinctFrom -> "is not distinct from"
 
-{- | RWS-Monad to generate condition.
-* Read: Stack of numbers of parent tables. The top is "current table"
-* Write: List of placeholder-values.
-
-    Note: SQL is generated top-down so placeholder values appear in the correct order.
+{- | RWS monad to generate condition.
 
-* State: Last number of table "in use"
+* Read: the prefix of table aliases in nested subqueries and the stack of
+  numbers of the tables (the top is the "current table"). The alias of the
+  current table is @t\<n\>@ or, in a subquery, @t\<parent\>\<prefix\>\<n\>@
+  (see 'PgSchema.DML.tabPref').
+* Write: list of placeholder values.
+  SQL is generated top-down so placeholder values appear in the correct order.
+* State: last number of table "in use".
 -}
 type CondMonad = RWS (Text, NonEmpty Int) [SomeToField] Int
 
+-- | A value of any type with 'ToField' (and 'Show' for debugging): a value for
+-- one @?@ placeholder of the generated SQL.
+--
+-- The list of these values is returned together with the SQL text by
+-- 'PgSchema.DML.selectText', 'PgSchema.DML.updateText' etc.
+-- In 'CondMonad' you add placeholder values with 'tell', e.g. in 'pUnsafeCond'.
 data SomeToField where
   SomeToField :: (ToField a, Show a) => a -> SomeToField
 
@@ -238,6 +265,8 @@
 instance ToField SomeToField where
   toField (SomeToField v) = toField v
 
+-- | Field @fld@ (a database name, after the renamer) is a plain column of table
+-- @tab@ in schema @sch@. Otherwise it is a compile-time error.
 type CDBField sch tab fld =
   (CDBField' sch tab fld (TDBFieldInfo sch tab fld), CDBFieldInfo sch tab fld)
 
@@ -251,6 +280,9 @@
 -- type CDBValue sch tab fld fd v =
 --   (CDBField sch tab fld fd, ToField v, Show v, CanConvert sch tab fld fd v)
 
+-- | Field @fld@ (a database name, after the renamer) is a plain column of table
+-- @tab@, and a value of Haskell type @v@ can be compared with it ('CanConvert'):
+-- e.g. @v@ is 'Maybe' iff the column is nullable.
 type CDBValue sch tab fld v =
   (CDBValue' sch tab fld (TDBFieldInfo sch tab fld) v, CDBFieldInfo sch tab fld
   , ToField v, Show v)
@@ -262,52 +294,55 @@
     :$$: TE.Text "Schema: " :<>: ShowType sch
     :$$: TE.Text "")
 
+-- | Field @fld@ (a database name, after the renamer) is a nullable plain column
+-- of table @tab@.
 type CDBFieldNullable sch tab fld =
   ( CDBField sch tab fld , FdNullable (GetFldDef sch tab fld) ~ 'True)
 
--- | GADT to safely set `where` condition for table `tab` based on definition of schema `sch`
+-- | GADT to safely set @WHERE@ condition for table @tab@ based on definition of schema @sch@.
 --
--- 'Cond' is 'Monoid' with conjunction ('(&&&)') as 'mappend'
+-- 'Cond' is 'Monoid' with conjunction ('(&&&)') as 'mappend'.
 --
 data Cond (ren :: Renamer) (sch::Type) (tab::NameNSK) where
   EmptyCond :: Cond ren sch tab
   -- ^ Empty Condition. Neutral for conjunction '(&&&)' and disjunction '(|||)'.
   Cmp :: forall fld v ren sch tab. CDBValue sch tab (ApplyRenamer ren fld) v => Cmp -> v -> Cond ren sch tab
-  -- ^ Comparing field value with parameter
+  -- ^ Comparing field value with parameter.
   In :: forall fld v ren sch tab. CDBValue sch tab (ApplyRenamer ren fld) v => NonEmpty v -> Cond ren sch tab
-  -- ^ Check that field value belongs to non-empty list of values
+  -- ^ Check that field value belongs to non-empty list of values.
   InArr :: forall fld v ren sch tab. CDBValue sch tab (ApplyRenamer ren fld) v => [v] -> Cond ren sch tab
   -- ^ Check that field value belongs to the list of values.
   -- If the list is empty, the condition evaluates to @false@.
   Null :: forall fld ren sch tab.
     CDBFieldNullable sch tab (ApplyRenamer ren fld) => Cond ren sch tab
-  -- ^ Check that field value is @NULL@
+  -- ^ Check that field value is @NULL@.
   Not :: Cond ren sch tab -> Cond ren sch tab
-  -- ^ Boolean @NOT@
+  -- ^ Boolean @NOT@.
   BoolOp :: BoolOp -> Cond ren sch tab -> Cond ren sch tab -> Cond ren sch tab
-  -- ^ Conjunction and disjunction
+  -- ^ Conjunction and disjunction.
   Child :: forall ren sch ref. CRelDef sch (ApplyRenamerNS ren ref)
     => TabParam ren sch (RdFrom (TRelDef sch (ApplyRenamerNS ren ref)))
     -> Cond ren sch (RdFrom (TRelDef sch (ApplyRenamerNS ren ref)))
     -> Cond ren sch (RdTo (TRelDef sch (ApplyRenamerNS ren ref)))
-  -- ^ condition @EXISTS@ in child table. 'TabParam' is used to limit
+  -- ^ Condition @EXISTS@ in child table. t'TabParam' is used to limit
   -- child dataset (usually with @ORDER BY@ and @LIMIT@) before applying
-  -- condition on child table
+  -- condition on child table.
   Parent :: forall ren sch ref . CRelDef sch (ApplyRenamerNS ren ref)
     => Cond ren sch (RdTo (TRelDef sch (ApplyRenamerNS ren ref)))
     -> Cond ren sch (RdFrom (TRelDef sch (ApplyRenamerNS ren ref)))
-  -- ^ @JOIN@ to parent rows that satisfy the nested condition
+  -- ^ Condition @EXISTS@ in parent table: the parent row satisfies the nested condition.
   UnsafeCond :: CondMonad Text -> Cond ren sch tab
-  -- ^ Unsafe condition built manually inside 'CondMonad'
+  -- ^ Unsafe condition built manually inside 'CondMonad'.
 
+-- | 'Cond' for the renamer, schema and root table of annotation @ann@
+-- (e.g. for 'PgSchema.DML.updateByCond' and 'PgSchema.DML.deleteByCond').
 type CondAnn ann = Cond (AnnRen ann) (AnnSch ann) (AnnTab ann)
 
--- Conjunction '(&&&)' is much more often operation for query conditions so
--- we use it for 'Semigroup'.
--- But note that 'EmptyCond' is also neutral for disjunction '(|||)'.
+-- | Conjunction ('(&&&)') is a much more frequent operation for query conditions,
+-- so we use it for 'Semigroup'.
+-- But note that 'EmptyCond' is also neutral for disjunction ('(|||)').
 instance Semigroup (Cond ren sch tab) where
   c1 <> c2 = c1 &&& c2
-  -- ^ Using conjunction ('(&&&)') for 'Semigroup' instance
 
 instance Monoid (Cond ren sch tab) where
   mempty = EmptyCond
@@ -315,26 +350,27 @@
 -- | Parameters for child table.
 --
 -- It is used to limit child dataset (usually with @ORDER BY@ and @LIMIT@) before applying
--- condition on child table
+-- condition on child table.
 --
 data TabParam ren sch tab = TabParam
-  { cond :: Cond ren sch tab
-  , order :: [OrdFld ren sch tab]
-  , lo :: LO }
+  { cond :: Cond ren sch tab    -- ^ Condition on child rows.
+  , order :: [OrdFld ren sch tab] -- ^ Ordering of child rows (for 'lo').
+  , lo :: LO                    -- ^ Limit and offset of child rows.
+  }
 
--- | Default empty 'TabParam': no conditions, no ordering, no limits.
+-- | Default empty t'TabParam': no conditions, no ordering, no limits.
 defTabParam :: TabParam ren sch tab
 defTabParam = TabParam mempty mempty defLO
 
--- | Check that field value is @NULL@
+-- | Check that field value is @NULL@.
 {-# INLINE pnull #-}
 pnull :: forall ren sch tab. forall name -> CDBFieldNullable sch tab (ApplyRenamer ren name) => Cond ren sch tab
 pnull name = Null @name
 
--- | True when related rows exist in the child table and satisfy the nested condition there
+-- | True when related rows exist in the child table and satisfy the nested condition there.
 --
--- 'TabParam' is used to limit child dataset (usually with @ORDER BY@ and @LIMIT@) before applying
--- condition on child table
+-- t'TabParam' is used to limit child dataset (usually with @ORDER BY@ and @LIMIT@) before applying
+-- condition on child table.
 --
 {-# INLINE pchild #-}
 pchild :: forall ren sch . forall ref -> CRelDef sch (ApplyRenamerNS ren ref)
@@ -343,23 +379,39 @@
   -> Cond ren sch (RdTo (TRelDef sch (ApplyRenamerNS ren ref)))
 pchild name = Child @ren @sch @name
 
--- | Check that condition is satisfied in parent table
+-- | Check that condition is satisfied in parent table.
 {-# INLINE pparent #-}
 pparent :: forall ren sch. forall ref -> CRelDef sch (ApplyRenamerNS ren ref)
   => Cond ren sch (RdTo (TRelDef sch (ApplyRenamerNS ren ref)))
   -> Cond ren sch (RdFrom (TRelDef sch (ApplyRenamerNS ren ref)))
 pparent name = Parent @ren @sch @name
 
--- | Boolean @NOT@
+-- | Boolean @NOT@.
 {-# INLINE pnot #-}
 pnot :: Cond ren sch tab -> Cond ren sch tab
 pnot = Not
 
+-- | Unsafe condition written as raw SQL inside 'CondMonad'.
+--
+-- Use it only for conditions that can't be expressed with the safe API.
+-- The SQL text is not checked at all: neither the names of the columns nor the
+-- types of the values.
+--
+-- * 'PgSchema.DML.tabPref' gives the alias of the current table and
+--   'PgSchema.DML.qual' gives a column
+--   qualified with it (use database names: the renamer is not applied).
+-- * Add a value for each @?@ placeholder with 'tell' (in the order of the
+--   placeholders).
+--
+-- > pUnsafeCond do
+-- >   name <- qual @"name"
+-- >   tell [SomeToField ("^jo" :: Text)]
+-- >   pure $ name <> " ~ ?"
 {-# INLINE pUnsafeCond #-}
 pUnsafeCond :: CondMonad Text -> Cond ren sch tab
 pUnsafeCond = UnsafeCond
 
--- | Check that field value belongs to non-empty list of values
+-- | Check that field value belongs to non-empty list of values.
 {-# INLINE pin #-}
 pin :: forall name -> forall ren sch tab v. CDBValue sch tab (ApplyRenamer ren name) v
   => NonEmpty v -> Cond ren sch tab
@@ -372,9 +424,9 @@
   => [v] -> Cond ren sch tab
 pinArr name = InArr @name
 
--- | Conjunction
+-- | Conjunction.
 (&&&) :: Cond ren sch tab -> Cond ren sch tab -> Cond ren sch tab
--- | Disjunction
+-- | Disjunction.
 (|||) :: Cond ren sch tab -> Cond ren sch tab -> Cond ren sch tab
 EmptyCond &&& cond = cond
 cond &&& EmptyCond = cond
@@ -393,6 +445,15 @@
 {-# INLINE (=??) #-}
 {-# INLINE (~=?) #-}
 {-# INLINE (~~?) #-}
+-- | Compare field @fld@ with a value: @\<@, @\>@, @\<=@, @\>=@ and @=@.
+--
+-- The field name is given as a required type argument and the renamer is
+-- applied to it. The value must have a compatible Haskell type ('CDBValue'):
+--
+-- > "name" =? ("John" :: Text)
+-- > "created_at" >? someDay
+--
+-- @=@ with @NULL@ is never true: use '(=??)' or 'pnull' for nullable columns.
 (<?),(>?),(<=?),(>=?),(=?)
    :: forall fld -> forall ren sch tab v. CDBValue sch tab (ApplyRenamer ren fld) v => v -> Cond ren sch tab
 x <? b  = Cmp @x (:<)  b
@@ -408,30 +469,45 @@
     )
   => v -> Cond ren sch tab
 x =?? b = Cmp @x NotDistinctFrom b
+-- | Match field @fld@ with a pattern: @LIKE@ ('~=?') and case-insensitive
+-- @ILIKE@ ('~~?').
+--
+-- > "name" ~~? ("%john%" :: Text)
 (~=?),(~~?)
   :: forall fld -> forall ren sch tab v. CDBValue sch tab (ApplyRenamer ren fld) v => v -> Cond ren sch tab
 x ~=? b  = Cmp @x Like b
 x ~~? b  = Cmp @x ILike b
 infix 4 <?, >?, <=?, >=?, =?, =??, ~=?, ~~?
 
+-- | Direction of ordering. In both directions @NULL@ values go last
+-- (@NULLS LAST@).
 data OrdDirection = Asc | Desc deriving Show
 
+-- | One item of @ORDER BY@ (or @DISTINCT ON@) for table @tab@.
+--
+-- Usually it is made with 'ascf', 'descf' or 'ordf'.
 data OrdFld ren sch tab where
   OrdFld :: forall fld ren sch tab. CDBField sch tab (ApplyRenamer ren fld) =>
     OrdDirection -> OrdFld ren sch tab
+  -- ^ Order by field @fld@ (given as a type application, the renamer is applied).
   UnsafeOrd :: CondMonad (Text, OrdDirection) -> OrdFld ren sch tab
+  -- ^ Order by an SQL expression built in 'CondMonad' (see 'pUnsafeCond').
+  -- The expression is not checked.
 
+-- | @DISTINCT@ or @DISTINCT ON@ for table @tab@. Usually it is set with
+-- 'qDistinct' or 'qDistinctOn'.
 data Dist ren sch tab where
   Distinct :: Dist ren sch tab
+  -- ^ @DISTINCT@: remove duplicate rows.
   -- | Having 'DistinctOn' we automatically add fields from 'DistinctOn'
-  -- into the begining of @ORDER BY@.
-  -- (It is "good enough" and more simple than check it on type level).
+  -- into the beginning of @ORDER BY@.
+  -- (It is "good enough" and simpler than checking it on the type level.)
   --
-  -- That's why we use 'OrdFld' who include 'OrdDirection'.
-  -- Naturally 'OrdDirection' is not used in DISTINCT ON part itself.
+  -- That's why we use t'OrdFld' which includes 'OrdDirection'.
+  -- Naturally 'OrdDirection' is not used in the @DISTINCT ON@ part itself.
   --
-  -- Beside that @DISTINCT ON@ part can include expressions like @ORDER BY@.
-  -- We can also use 'UnsafeOrd' here
+  -- Besides that, the @DISTINCT ON@ part can include expressions like @ORDER BY@.
+  -- We can also use 'UnsafeOrd' here.
   DistinctOn :: [OrdFld ren sch tab] -> Dist ren sch tab
 
 {-# INLINE ordf #-}
@@ -453,9 +529,11 @@
   => OrdFld ren sch tab
 descf fld = ordf fld Desc
 
+-- | @LIMIT@ and @OFFSET@. 'Nothing' means no limit / no offset.
 data LO = LO
-  { limit  :: Maybe Natural
-  , offset :: Maybe Natural }
+  { limit  :: Maybe Natural -- ^ @LIMIT@
+  , offset :: Maybe Natural -- ^ @OFFSET@
+  }
   deriving Show
 
 -- | No limit and no offset.
diff --git a/src/PgSchema/DML/Update.hs b/src/PgSchema/DML/Update.hs
--- a/src/PgSchema/DML/Update.hs
+++ b/src/PgSchema/DML/Update.hs
@@ -49,7 +49,12 @@
 
 -- | Update rows by primary / unique key from record fields (never inserts).
 --
+-- The key is the first fully covered one of: the primary key, unique keys over
+-- @NOT NULL@ columns, other unique keys. Key columns are compared with
+-- @IS NOT DISTINCT FROM@; all other fields of @r@ are updated.
+--
 -- Returning type @r'@ is a bare row; the result is @IO ([Maybe r'], Text)@
+-- (one element per input row, then the SQL text)
 -- with @Nothing@ when no row matched the key.
 updateByKey
   :: forall ann -> forall r r'. UpdateByKeyReturning ann r r'
@@ -64,7 +69,9 @@
         _ -> Nothing
     pure (rs, sql)
 
--- | Update rows by key without @RETURNING@.
+-- | Update rows by key without @RETURNING@ (see 'updateByKey').
+--
+-- Returns the number of updated rows and the SQL text.
 updateByKey_
   :: forall ann -> forall r. UpdateByKeyNonReturning ann r
   => Connection -> [r] -> IO (Int64, Text)
@@ -75,6 +82,8 @@
       $ fmap (updateByKeyRowParams @ann @r) recs
     pure (n, sql)
 
+-- | SQL text of 'updateByKey': update one row by key and return columns of @r'@.
+-- It has a @?@ placeholder for each field of @r@.
 updateByKeyText
   :: forall ann -> forall r r' s
   . ( CRecInfo ann r, CRecInfo ann r', IsString s, Monoid s, HasSchema ann ) => s
@@ -84,6 +93,8 @@
     ri' = getRecordInfo @ann @r'
     fs' = fromString $ T.unpack $ T.intercalate "," [fi.fieldDbName | fi <- ri'.fields]
 
+-- | SQL text of 'updateByKey_': update one row by key.
+-- It has a @?@ placeholder for each field of @r@.
 updateByKeyText_
   :: forall ann -> forall r s
   . (IsString s, Monoid s, CRecInfo ann r, HasSchema ann) => s
@@ -108,7 +119,10 @@
     <> " set " <> setClause
     <> keyWhereClause plainsKey
 
--- | Update rows matching a condition; the result type selects which columns are returned.
+-- | Update rows matching a condition: set the fields of @r@ (the same values for
+-- all rows) and return the columns of @r'@ of the updated rows.
+--
+-- The result type selects which columns are returned.
 updateByCond :: forall ann -> forall r r'.
   (UpdateReturning ann r r') => Connection -> r -> CondAnn ann -> IO [r']
 updateByCond ann @r @r' conn r (updateText ann @r @r' -> (q,ps)) =
@@ -118,6 +132,8 @@
   $ PgTag @ann @r r :. ps
 
 -- | Update records by condition without @RETURNING@.
+--
+-- Returns the number of updated rows.
 updateByCond_ :: forall ann -> forall r. UpdateNonReturning ann r =>
   Connection -> r -> CondAnn ann -> IO Int64
 updateByCond_ ann @r conn r (updateText_ ann @r -> (q, ps)) =
diff --git a/src/PgSchema/DML/UpsertByKey.hs b/src/PgSchema/DML/UpsertByKey.hs
--- a/src/PgSchema/DML/UpsertByKey.hs
+++ b/src/PgSchema/DML/UpsertByKey.hs
@@ -2,7 +2,6 @@
 module PgSchema.DML.UpsertByKey
   ( upsertByKey, upsertByKey_, upsertByKeyText, upsertByKeyText_ ) where
 
-import Data.List as L
 import Data.Maybe
 import Data.String
 import Data.Text as T
@@ -18,6 +17,24 @@
 import Prelude as P
 
 
+-- | Insert rows into one table or update them if a row with the same key exists
+-- (@INSERT … ON CONFLICT (key) DO UPDATE@).
+--
+-- @r@ must contain all mandatory columns and a full primary or unique key
+-- ('UpsertByKeyReturning'). The key is the first fully covered one of: the
+-- primary key, unique keys over @NOT NULL@ columns, other unique keys.
+-- On conflict all other fields of @r@ are updated.
+--
+-- If all fields of @r@ belong to the key, there is nothing to update: an
+-- existing row is left as is, but it is returned too (the @ON CONFLICT@ clause is
+-- a no-op @DO UPDATE@ of a key column).
+--
+-- A row with @NULL@ in a column of a unique key never conflicts (unless the
+-- constraint is @NULLS NOT DISTINCT@), so it is always inserted. The same key must not occur twice in one call
+-- (PostgreSQL can't update a row twice in one statement).
+--
+-- Returning type @r'@ may name any plain columns of the table.
+-- Returns one returned row per input row (in the same order) and the SQL text.
 upsertByKey
   :: forall ann -> forall r r'. UpsertByKeyReturning ann r r'
   => Connection -> [r] -> IO ([r'], Text)
@@ -28,6 +45,12 @@
       ( returning conn (fromString $ T.unpack sql)
       $ fmap (PgTag @ann @r) recs )
 
+-- | Like 'upsertByKey', but without @RETURNING@.
+--
+-- If all fields of @r@ belong to the key, existing rows are left as is
+-- (@ON CONFLICT (key) DO NOTHING@).
+--
+-- Returns the number of inserted or updated rows and the SQL text.
 upsertByKey_
   :: forall ann -> forall r. UpsertByKeyNonReturning ann r
   => Connection -> [r] -> IO (Int64, Text)
@@ -37,23 +60,28 @@
     . executeMany conn (fromString $ T.unpack sql)
     . fmap (PgTag @ann @r) $ recs
 
+-- | SQL text of 'upsertByKey' for one row, with a @?@ placeholder for each field of @r@.
 upsertByKeyText
   :: forall ann -> forall r r' s
   . (UpsertByKeyReturning ann r r', IsString s, Monoid s) => s
-upsertByKeyText ann @r @r' = upsertByKeyText_ ann @r <> " returning " <> fs'
+upsertByKeyText ann @r @r' =
+  fromString (T.unpack $ upsertByKeyStmt ann @r True) <> " returning " <> fs'
   where
     ri' = getRecordInfo @ann @r'
     fs' = fromText $ T.intercalate "," [fi.fieldDbName | fi <- ri'.fields]
 
+-- | SQL text of 'upsertByKey_' for one row, with a @?@ placeholder for each field of @r@.
 upsertByKeyText_
   :: forall ann -> forall r s
   . (UpsertByKeyNonReturning ann r, IsString s, Monoid s) => s
-upsertByKeyText_ ann @r = fromString $ T.unpack $ upsertByKeyStmt ann @r
+upsertByKeyText_ ann @r = fromString $ T.unpack $ upsertByKeyStmt ann @r False
 
-upsertByKeyStmt :: forall ann -> forall r. UpsertByKeyNonReturning ann r => Text
-upsertByKeyStmt ann @r
-  | L.null plainsOthers = ins <> " on conflict do nothing"
-  | otherwise = ins <> upsertOnConflict plainsOthers keyNames
+-- | @INSERT … ON CONFLICT …@ statement without @RETURNING@; the flag tells
+-- whether @RETURNING@ will be added (see 'upsertOnConflict').
+upsertByKeyStmt
+  :: forall ann -> forall r. UpsertByKeyNonReturning ann r => Bool -> Text
+upsertByKeyStmt ann @r withReturning =
+  ins <> upsertOnConflict withReturning plainsOthers keyNames
   where
     ri = getRecordInfo @ann @r
     ti = tabInfoMap @(AnnSch ann) M.! ri.tabName
diff --git a/src/PgSchema/GenDot.hs b/src/PgSchema/GenDot.hs
--- a/src/PgSchema/GenDot.hs
+++ b/src/PgSchema/GenDot.hs
@@ -16,10 +16,16 @@
 import PgSchema.Schema
 
 
+-- | Operations that change the DOT representation.
 data DotOper
   = ExcludeToTab NameNS Text
-  -- ^ Exclude relation to given table from DOT representation.
+  -- ^ Exclude relations to the given table from the DOT representation.
+  -- Instead of an arrow, the given text is added to the label of each table
+  -- that references this table (e.g. for a table referenced from everywhere).
 
+-- | DOT representation (@digraph@) of the tables and relations of schema @sch@.
+-- Tables are grouped by database schemas; relations with a nullable foreign
+-- key are green.
 genDot :: forall sch. CSchema sch
   => Bool -- ^ Whether to use qualified names
   -> [DotOper] -- ^ Operations to exclude relations from DOT representation
diff --git a/src/PgSchema/Generation.hs b/src/PgSchema/Generation.hs
--- a/src/PgSchema/Generation.hs
+++ b/src/PgSchema/Generation.hs
@@ -55,18 +55,26 @@
 
 instance Exception ExceptionSch
 
+-- | A relation that does not exist in the database as a foreign key, but is
+-- used as if it existed (e.g. a relation to a view).
+--
+-- Nothing checks the relation in the database: the columns must be correct and
+-- the data must really be consistent with it.
 data AddRelation = AddRelation
   { name  :: Text
-  -- ^ name of an additional (non-existing in the database) relation.
-  -- All additional relations will be added with the namespace "_add".
-  , from  :: NameNS
-  , to    :: NameNS
-  , cols  :: [(Text, Text)] }
+  -- ^ Name of an additional (non-existing in the database) relation.
+  -- All additional relations will be added with the namespace @_add@.
+  , from  :: NameNS -- ^ Child (referencing) table.
+  , to    :: NameNS -- ^ Parent (referenced) table.
+  , cols  :: [(Text, Text)]
+  -- ^ Pairs of columns: (column of the child table, column of the parent table).
+  }
 
+-- | What to generate.
 data GenNames = GenNames
-  { schemas :: [Text]   -- ^ generate data for all tables in these schemas
-  , tables  :: [NameNS] -- ^ generate data for these tables
-  , addRelations :: [AddRelation] -- ^ additional relations. Be careful!
+  { schemas :: [Text]   -- ^ Generate data for all tables in these schemas.
+  , tables  :: [NameNS] -- ^ Generate data for these tables.
+  , addRelations :: [AddRelation] -- ^ Additional relations. Be careful!
   }
 
 type AnnCat tn = 'Ann RenamerId PgCatalog 3 (PGC tn)
@@ -220,18 +228,22 @@
         getName t n = M.lookup (t,n) mClassAttrs
         getName2 n1 n2 = (,) <$> getName rdFrom n1 <*> getName rdTo n2
 
--- | Update (or create) the Haskell file containing the schema definition
+-- | Update (or create) the Haskell file containing the schema definition.
+--
+-- The file is rewritten only if the generated text differs from its contents;
+-- the previous version is kept as @\<file\>.bak@.
+-- Returns 'True' if the file was (re)written.
 updateSchemaFile
-  :: Bool       -- ^ verbose mode
-  -> String     -- ^ file name
+  :: Bool       -- ^ Verbose mode: also print the schema read from the database.
+  -> String     -- ^ File name.
   -> Either String ByteString
-    -- ^ name of environment variable with connection string, or
-    -- the connection string itself.
+    -- ^ 'Left': name of the environment variable with the connection string;
+    -- 'Right': the connection string itself.
     -- When this environment variable is not set or the connection string is empty,
-    -- we do nothing.
-  -> Text     -- ^ haskell module name to generate
-  -> Text     -- ^ name of generated haskell type for schema
-  -> GenNames -- ^ names of schemas in database or tables to generate
+    -- nothing is done (and 'False' is returned).
+  -> Text     -- ^ Haskell module name to generate.
+  -> Text     -- ^ Name of the generated Haskell type for the schema.
+  -> GenNames -- ^ Names of schemas in the database or of tables to generate.
   -> IO Bool
 updateSchemaFile verbose fileName ecs moduleName schName genNames = do
   getCurrentDirectory >>= print
@@ -328,7 +340,7 @@
   <> "\n    TE.:$$: TE.Text \"  Fields: " <> T.intercalate ", " fields <> ".\""
   <> "\n    TE.:$$: TE.Text \"  Foreign key constraints: " <> T.intercalate ", " rels <> ".\""
   <> "\n    TE.:$$: TE.Text \"\""
-  <> "\n    TE.:$$: TE.Text \"Your source or target type or renaimer is probably invalid.\""
+  <> "\n    TE.:$$: TE.Text \"Your source or target type or renamer is probably invalid.\""
   <> "\n    TE.:$$: TE.Text \"\""
   <> ")"
 
@@ -372,7 +384,7 @@
       "  " <> tfName <> " " <> tabStr <> " f = " <> typeErrorMsg schName tabStr fieldNames relNames <> "\n"
     tableBlocks =
       [ mconcat [ eqnLine tab fld rhs | (t, fld, rhs) <- allEntries, t == tab ]
-        <> perTableDefault tab (showType tab) (tdFlds td) ((nnsName <$> froms) <> (nnsName <$> tos))
+        <> perTableDefault tab (showType tab) (tdFlds td) (L.nub (nnsName <$> froms <> tos))
       | (tab, (td, froms, tos)) <- M.toList mtab ]
     equations = mconcat tableBlocks <> "  " <> tfName <> " t f = "
       <> typeErrorMsgFinal <> "\n"
diff --git a/src/PgSchema/Plain.hs b/src/PgSchema/Plain.hs
new file mode 100644
--- /dev/null
+++ b/src/PgSchema/Plain.hs
@@ -0,0 +1,301 @@
+{-# LANGUAGE UndecidableInstances #-}
+-- | Plain (untagged, flat) values of rows: 'rowsOf' / 'rowOf' and 'plains' / 'plain'.
+--
+-- A row is flattened the same way as for 'Database.PostgreSQL.Simple.ToRow' /
+-- 'Database.PostgreSQL.Simple.FromRow' (see the internal @Cols@):
+-- t'(:.)' and Generic records are flattened into a sequence of fields,
+-- @fld := ()@ gives no field. The structure (grouping) lives in the type only.
+--
+-- Here we have just structures: no schema is used.
+module PgSchema.Plain
+  ( Plain, PlainCols, PlainVal, PlainRow, rowsOf, plains, rowOf, plain ) where
+
+import Data.Kind
+import GHC.Generics
+import GHC.TypeLits (Symbol)
+import PgSchema.Ann (ColsCase(..), ColsCaseOf, NotProductTypeError)
+import PgSchema.Types
+import PgSchema.Utils.TF
+
+
+-- | Flat (plain) value of a row @r@: values of all fields chained with t'(:.)'
+-- from the right, without field names. A row without fields is @()@.
+--
+-- Nested rows in field values (children @[r]@, parents @r@ or @Maybe r@) are
+-- plain too.
+--
+-- >>> :kind! Plain ("a" := Int :. ("b" := Bool :. "c" := ()) :. "d" := ["e" := Char :. "f" := Char])
+-- Plain ("a" := Int :. ("b" := Bool :. "c" := ()) :. "d" := ["e" := Char :. "f" := Char]) :: *
+-- = Int :. (Bool :. [Char :. Char])
+type Plain r = Chain (PlainCols r)
+
+-- | Types of the fields of a row (like the internal @Cols@, but schema-less).
+type family PlainCols (r :: Type) :: [Type] where
+  -- an optional group of fields cannot be split into fields:
+  -- it is one value
+  PlainCols (Maybe r) = '[Maybe (Plain r)]
+  PlainCols (a :. b) = PlainCols a ++ PlainCols b
+  PlainCols ((fld :: Symbol) := ()) = '[]
+  PlainCols ((fld :: Symbol) := t) = '[PlainVal t]
+  PlainCols r = GPlainCols (Rep r)
+
+type family GPlainCols (rep :: Type -> Type) :: [Type] where
+  GPlainCols (D1 d (C1 c flds)) = GPlainCols flds
+  GPlainCols (a :*: b) = GPlainCols a ++ GPlainCols b
+  GPlainCols (S1 (MetaSel ('Just fld) u v w) (Rec0 t)) = PlainCols (fld := t)
+  GPlainCols rep = NotProductTypeError rep
+
+-- | Plain value of a field.
+--
+-- Rows built with t'(:.)' / '(:=)' (also in lists and 'Maybe') become plain.
+-- Other values are not changed. In particular, Generic records in field values
+-- are kept as is: without a schema they can't be distinguished from other
+-- types having a Generic instance (e.g. 'Data.Aeson.Value').
+type family PlainVal (t :: Type) :: Type where
+  PlainVal [t] = [PlainVal t]
+  PlainVal (Maybe t) = Maybe (PlainVal t)
+  PlainVal (a :. b) = Plain (a :. b)
+  PlainVal ((fld :: Symbol) := t) = Plain (fld := t)
+  PlainVal t = t
+
+type family Chain (ts :: [Type]) :: Type where
+  Chain '[] = ()
+  Chain '[t] = t
+  Chain (t ': ts) = t :. Chain ts
+
+--------------------------------------------------------------------------------
+-- Value level
+--------------------------------------------------------------------------------
+
+data HL (ts :: [Type]) where
+  HNil :: HL '[]
+  (:&) :: t -> HL ts -> HL (t ': ts)
+infixr 5 :&
+
+appHL :: HL xs -> HL ys -> HL (xs ++ ys)
+appHL HNil ys = ys
+appHL (x :& xs) ys = x :& appHL xs ys
+
+class ChainHL (ts :: [Type]) where
+  toChain :: HL ts -> Chain ts
+  fromChain :: Chain ts -> HL ts
+
+instance ChainHL '[] where
+  toChain _ = ()
+  fromChain _ = HNil
+
+instance ChainHL '[t] where
+  toChain (x :& _) = x
+  fromChain x = x :& HNil
+
+instance (ChainHL (t2 ': ts), Chain (t1 ': t2 ': ts) ~ (t1 :. Chain (t2 ': ts)))
+  => ChainHL (t1 ': t2 ': ts) where
+  toChain (x :& xs) = x :. toChain xs
+  fromChain (x :. xs) = x :& fromChain xs
+
+data PlainCase = PCMaybe | PCRow ColsCase
+
+type family PlainCaseOf (r :: Type) :: PlainCase where
+  PlainCaseOf (Maybe r) = 'PCMaybe
+  PlainCaseOf r = 'PCRow (ColsCaseOf r)
+
+-- | Like the internal @ToRowCols@: a row to the list of plain fields.
+class ToPlainCols (c :: PlainCase) (cols :: [Type]) r where
+  toPlainCols :: r -> HL cols
+
+-- | Like the internal @FromRowCols@: a row from the beginning of the list of
+-- plain fields (as 'Database.PostgreSQL.Simple.FromRow.RowParser' takes the
+-- beginning of the row). The rest is returned.
+class FromPlainCols (c :: PlainCase) (cols :: [Type]) r (rest :: [Type]) where
+  fromPlainCols :: HL (cols ++ rest) -> (r, HL rest)
+
+-- (:=)
+instance ToPlainCols ('PCRow 'NonGenericCase) '[] (fld := ()) where
+  toPlainCols _ = HNil
+
+instance FromPlainCols ('PCRow 'NonGenericCase) '[] (fld := ()) rest where
+  fromPlainCols xs = (PgTag (), xs)
+
+instance (CPlainVal (ValCaseOf t) t, v ~ PlainVal t)
+  => ToPlainCols ('PCRow 'NonGenericCase) '[v] (fld := t) where
+  toPlainCols (PgTag x) = toPlainVal @(ValCaseOf t) x :& HNil
+
+instance (CPlainVal (ValCaseOf t) t, v ~ PlainVal t)
+  => FromPlainCols ('PCRow 'NonGenericCase) '[v] (fld := t) rest where
+  fromPlainCols (x :& xs) = (PgTag (fromPlainVal @(ValCaseOf t) x), xs)
+
+-- (:.)
+instance
+  ( split ~ SplitAt (Length (PlainCols a)) cols
+  , colsA ~ Fst split, colsB ~ Snd split, cols ~ (colsA ++ colsB)
+  , ToPlainCols (PlainCaseOf a) colsA a, ToPlainCols (PlainCaseOf b) colsB b )
+  => ToPlainCols ('PCRow 'NonGenericCase) cols (a :. b) where
+  toPlainCols (a :. b) = appHL
+    (toPlainCols @(PlainCaseOf a) @colsA a) (toPlainCols @(PlainCaseOf b) @colsB b)
+
+instance
+  ( split ~ SplitAt (Length (PlainCols a)) cols
+  , colsA ~ Fst split, colsB ~ Snd split
+  , (cols ++ rest) ~ (colsA ++ (colsB ++ rest))
+  , FromPlainCols (PlainCaseOf a) colsA a (colsB ++ rest)
+  , FromPlainCols (PlainCaseOf b) colsB b rest )
+  => FromPlainCols ('PCRow 'NonGenericCase) cols (a :. b) rest where
+  fromPlainCols xs = (a :. b, r2)
+    where
+      (a, r1) = fromPlainCols @(PlainCaseOf a) @colsA @a @(colsB ++ rest) xs
+      (b, r2) = fromPlainCols @(PlainCaseOf b) @colsB @b @rest r1
+
+-- Maybe (optional group of fields)
+instance (PlainRow r, v ~ Maybe (Plain r))
+  => ToPlainCols 'PCMaybe '[v] (Maybe r) where
+  toPlainCols x = fmap plain x :& HNil
+
+instance (PlainRow r, v ~ Maybe (Plain r))
+  => FromPlainCols 'PCMaybe '[v] (Maybe r) rest where
+  fromPlainCols (x :& xs) = (fmap (rowOf @r) x, xs)
+
+-- Generic
+instance (Generic r, GToPlainCols cols (Rep r))
+  => ToPlainCols ('PCRow 'GenericCase) cols r where
+  toPlainCols = gToPlainCols @cols . from
+
+instance (Generic r, GFromPlainCols cols (Rep r) rest)
+  => FromPlainCols ('PCRow 'GenericCase) cols r rest where
+  fromPlainCols xs = let (x, r) = gFromPlainCols @cols @(Rep r) @rest xs in (to x, r)
+
+class GToPlainCols (cols :: [Type]) (rep :: Type -> Type) where
+  gToPlainCols :: rep x -> HL cols
+
+class GFromPlainCols (cols :: [Type]) (rep :: Type -> Type) (rest :: [Type]) where
+  gFromPlainCols :: HL (cols ++ rest) -> (rep x, HL rest)
+
+instance GToPlainCols cols flds => GToPlainCols cols (D1 d (C1 c flds)) where
+  gToPlainCols (M1 (M1 x)) = gToPlainCols @cols x
+
+instance GFromPlainCols cols flds rest
+  => GFromPlainCols cols (D1 d (C1 c flds)) rest where
+  gFromPlainCols xs = let (x, r) = gFromPlainCols @cols @flds @rest xs in (M1 (M1 x), r)
+
+instance
+  ( split ~ SplitAt (Length (GPlainCols a)) cols
+  , colsA ~ Fst split, colsB ~ Snd split, cols ~ (colsA ++ colsB)
+  , GToPlainCols colsA a, GToPlainCols colsB b )
+  => GToPlainCols cols (a :*: b) where
+  gToPlainCols (a :*: b) = appHL (gToPlainCols @colsA a) (gToPlainCols @colsB b)
+
+instance
+  ( split ~ SplitAt (Length (GPlainCols a)) cols
+  , colsA ~ Fst split, colsB ~ Snd split
+  , (cols ++ rest) ~ (colsA ++ (colsB ++ rest))
+  , GFromPlainCols colsA a (colsB ++ rest), GFromPlainCols colsB b rest )
+  => GFromPlainCols cols (a :*: b) rest where
+  gFromPlainCols xs = (a :*: b, r2)
+    where
+      (a, r1) = gFromPlainCols @colsA @a @(colsB ++ rest) xs
+      (b, r2) = gFromPlainCols @colsB @b @rest r1
+
+instance ToPlainCols ('PCRow 'NonGenericCase) cols (fld := t)
+  => GToPlainCols cols (S1 (MetaSel ('Just fld) u v w) (Rec0 t)) where
+  gToPlainCols (M1 (K1 x)) = toPlainCols @('PCRow 'NonGenericCase) (fld =: x)
+
+instance FromPlainCols ('PCRow 'NonGenericCase) cols (fld := t) rest
+  => GFromPlainCols cols (S1 (MetaSel ('Just fld) u v w) (Rec0 t)) rest where
+  gFromPlainCols xs = (M1 (K1 x), r)
+    where
+      (PgTag x, r) = fromPlainCols @('PCRow 'NonGenericCase) @cols @(fld := t) @rest xs
+
+-- Field values
+data ValCase = VCList | VCMaybe | VCRow | VCOther
+
+type family ValCaseOf (t :: Type) :: ValCase where
+  ValCaseOf [t] = 'VCList
+  ValCaseOf (Maybe t) = 'VCMaybe
+  ValCaseOf (a :. b) = 'VCRow
+  ValCaseOf ((fld :: Symbol) := t) = 'VCRow
+  ValCaseOf t = 'VCOther
+
+class CPlainVal (c :: ValCase) t where
+  toPlainVal :: t -> PlainVal t
+  fromPlainVal :: PlainVal t -> t
+
+instance (CPlainVal (ValCaseOf t) t, PlainVal [t] ~ [PlainVal t])
+  => CPlainVal 'VCList [t] where
+  toPlainVal = fmap (toPlainVal @(ValCaseOf t))
+  fromPlainVal = fmap (fromPlainVal @(ValCaseOf t))
+
+instance (CPlainVal (ValCaseOf t) t, PlainVal (Maybe t) ~ Maybe (PlainVal t))
+  => CPlainVal 'VCMaybe (Maybe t) where
+  toPlainVal = fmap (toPlainVal @(ValCaseOf t))
+  fromPlainVal = fmap (fromPlainVal @(ValCaseOf t))
+
+instance (PlainRow r, PlainVal r ~ Plain r) => CPlainVal 'VCRow r where
+  toPlainVal = plain
+  fromPlainVal = rowOf @r
+
+instance PlainVal t ~ t => CPlainVal 'VCOther t where
+  toPlainVal = id
+  fromPlainVal = id
+
+--------------------------------------------------------------------------------
+-- API
+--------------------------------------------------------------------------------
+
+-- | Row @r@ can be converted from and to its 'Plain' value.
+class
+  ( ToPlainCols (PlainCaseOf r) (PlainCols r) r
+  , FromPlainCols (PlainCaseOf r) (PlainCols r) r '[]
+  , ChainHL (PlainCols r), (PlainCols r ++ '[]) ~ PlainCols r )
+  => PlainRow r
+
+instance
+  ( ToPlainCols (PlainCaseOf r) (PlainCols r) r
+  , FromPlainCols (PlainCaseOf r) (PlainCols r) r '[]
+  , ChainHL (PlainCols r), (PlainCols r ++ '[]) ~ PlainCols r )
+  => PlainRow r
+
+-- | Make a row of type @r@ from its plain value.
+rowOf :: forall r. PlainRow r => Plain r -> r
+rowOf = fst . fromPlainCols @(PlainCaseOf r) @(PlainCols r) @r @'[] . fromChain
+
+-- | Plain value of a row. The inverse of 'rowOf'.
+plain :: forall r. PlainRow r => r -> Plain r
+plain = toChain . toPlainCols @(PlainCaseOf r) @(PlainCols r)
+
+-- | Make rows of type @r@ from plain values: field names (and field types)
+-- are taken from @r@, so values don't need names or type annotations.
+--
+-- > type Mid1 = "pos" := Int32 :. "flag" := Bool :. "sortKey" := Int32
+-- > type Root = "code" := Text :. "grp" := Int32 :. "name" := Text :. "mid1RootFk" := [Mid1]
+-- >
+-- > insertJSON_ (MyAnn "root") conn $ rowsOf @Root
+-- >   [ "r1" :. 1 :. "first" :. [10 :. True :. 1, 11 :. False :. 2]
+-- >   , "r2" :. 2 :. "second" :. [] ]
+--
+-- Rows are flattened as for 'Database.PostgreSQL.Simple.ToRow': parts joined
+-- with t'(:.)' and Generic records give their fields in order, so no
+-- parentheses are needed whatever the grouping in the type is.
+-- See 'Plain' for details.
+--
+-- The type is given with a type application (not as a required type
+-- argument), so it can be written in place: in a term position t'(:.)', @()@,
+-- @[t]@ or a record name would be taken as data constructors.
+--
+-- >>> rowsOf @("a" := Int :. ("b" := Bool :. "c" := ())) [1 :. True, 2 :. False]
+-- ["a" =: 1 :. ("b" =: True :. "c" =: ()),"a" =: 2 :. ("b" =: False :. "c" =: ())]
+rowsOf :: forall r. PlainRow r => [Plain r] -> [r]
+rowsOf = fmap (rowOf @r)
+
+-- | Plain values of rows (e.g. to pattern match on selected rows without
+-- t'PgTag'). The inverse of 'rowsOf'.
+--
+-- As for 'rowsOf', the row type can be given with a type application.
+-- For @SELECT@ or @RETURNING@ it is then the only place where the type of the
+-- result is written:
+--
+-- > rows <- plains @(Mid1 :. "mid1RootFk" := Root) . fst <$> selectSch (MyAnn "mid1") conn qpEmpty
+-- > for_ rows \(pos :. flag :. _ :. (code :. _)) -> print (pos, flag, code)
+--
+-- >>> plains ["a" =: (1 :: Int) :. "b" =: True]
+-- [1 :. True]
+plains :: forall r. PlainRow r => [r] -> [Plain r]
+plains = fmap plain
diff --git a/src/PgSchema/Schema.hs b/src/PgSchema/Schema.hs
--- a/src/PgSchema/Schema.hs
+++ b/src/PgSchema/Schema.hs
@@ -29,7 +29,9 @@
 
 -- | Description of a PostgreSQL type (category, array element, enum labels).
 data TypDef' s = TypDef
-  { typCategory :: s  -- ^ PostgreSql internal type category
+  { typCategory :: s
+  -- ^ PostgreSQL type category (@pg_type.typcategory@), e.g. @\"N\"@ (numeric),
+  -- @\"S\"@ (string), @\"A\"@ (array), @\"E\"@ (enum).
   , typElem :: Maybe (NameNS' s) -- ^ For array types: element type name; 'Nothing' for non-arrays.
   , typEnum :: [s] -- ^ Enum label names for enum types; empty list for non-enums.
   } deriving Show
@@ -61,31 +63,36 @@
 -- | Direction of one path step relative to the current table.
 data PathKind = FromHere | ToHere deriving (Show, Eq)
 
--- | One step of a 'SELECT' query path: logical branch name, DB fk name, direction.
+-- | One step of a @SELECT@ query path: logical branch name, DB fk name, direction.
 data PathElem' s = PathElem
-  { peName   :: s
-  , peDbName :: s
-  , peKind   :: PathKind
+  { peName   :: s        -- ^ Relation name as given by the user (before the renamer).
+  , peDbName :: s        -- ^ Name of the foreign-key constraint (after the renamer).
+  , peKind   :: PathKind -- ^ Direction of the step.
   } deriving (Show, Eq)
 
 -- | Field of a logical record: plain column, aggregate, or relation hop.
 data RecField' s p
-  = RFEmpty s -- ^ Placeholder / unnamed slot (depending on schema codegen).
-  | RFPlain (FldDef' s) -- ^ Ordinary column with 'FldDef''.
+  = RFPlain (FldDef' s) -- ^ Ordinary column with 'FldDef''.
   | RFAggr (FldDef' s) AggrFun Bool
-    -- ^ Aggregate field: 'FldDef'', which aggregate, and whether it is allowed outside @GROUP BY@
-    -- (when 'True': any select; when 'False': only with @GROUP BY@).
+    -- ^ Aggregate field: 'FldDef'', which aggregate, and whether the result can
+    -- be @NULL@ for a mandatory field: 'True' for 'PgSchema.DML.Aggr', 'False'
+    -- for 'PgSchema.DML.Aggr'' (used with @GROUP BY@).
   | RFUnsafe [s] s
-  -- ^ Plain field that we get as expression. E.g. @RFUnsafe ["a", "b"] "? + ?"@
-  -- means @tn.a + tn.b@ in query
+  -- ^ Plain field that we get as expression. E.g. @RFUnsafe [\"a\", \"b\"] \"? + ?\"@
+  -- means @tn.a + tn.b@ in query.
   | RFToHere p [Ref' s]
-    -- ^ Relation: navigate @p@ toward the current table (“to here”).
+    -- ^ Child relation: rows of table @p@ reference the current table
+    -- (the foreign key goes from @p@ to here). The field is a list of child rows.
   | RFFromHere p [Ref' s]
-    -- ^ Relation: navigate @p@ away from the current table (“from here”).
-  | RFSelfRef p [Ref' s] -- ^ Self-referential relation through path @p@.
+    -- ^ Parent relation: the current table references table @p@
+    -- (the foreign key goes from here to @p@). The field is one parent row
+    -- ('Maybe' if the foreign key is nullable).
+  | RFSelfRef p [Ref' s]
+    -- ^ Self-referential relation (table @p@ references itself). It is used
+    -- as 'RFToHere' for a list field and as 'RFFromHere' otherwise.
   deriving Show
 
--- | One step of a join path: source column, types, target column.
+-- | One column pair of a foreign key: source column, target column and their types.
 data Ref' s = Ref
   { fromName :: s         -- ^ Source (child) column name.
   , fromDef :: FldDef' s  -- ^ Type/nullability of @fromName@.
@@ -98,26 +105,31 @@
   , ''PathKind, ''PathElem'
   , ''RecField', ''Ref' ]
 
+-- | Type-level qualified name, usually written as @\"schema\" ->> \"name\"@.
 type NameNSK = NameNS' Symbol
 type TypDefK = TypDef' Symbol
 type FldDefK = FldDef' Symbol
 type TabDefK = TabDef' Symbol
 type RelDefK = RelDef' Symbol
+-- | Type-level kind of a field (see t'RecField'').
 type RecFieldK = RecField' Symbol
 type RefK = Ref' Symbol
 
+-- | Term-level qualified name, usually written as @\"schema\" ->> \"name\"@.
 type NameNS = NameNS' Text
 type TypDef = TypDef' Text
 type FldDef = FldDef' Text
 type TabDef = TabDef' Text
 type RelDef = RelDef' Text
+-- | Type-level step of a query path (see t'PathElem'').
 type PathElemK = PathElem' Symbol
+-- | Term-level step of a query path (see t'PathElem'').
 type PathElem = PathElem' Text
 
 mkPathStep :: Text -> Text -> PathKind -> PathElem
 mkPathStep name db kind = PathElem{peName = name, peDbName = db, peKind = kind}
 
--- | Broadcast step: 'peName' is the db/fk key from 'qPath', not a Haskell field.
+-- | Broadcast step: 'peName' is the db/fk key from 'PgSchema.DML.qPath', not a Haskell field.
 pathStepBroadcast :: PathElem -> Bool
 pathStepBroadcast s = s.peName == s.peDbName
 
@@ -147,9 +159,11 @@
 parentPathMatches p basePath piPath = pathsEqual p (basePath <> piPath)
 
 infixr 9 ->>
+-- | Qualified name: @\"public\" ->> \"users\"@ is the table @public.users@.
 (->>) :: Text -> Text -> NameNS
 (->>) = NameNS
 
+-- | Type-level qualified name: @\"public\" ->> \"users\"@ is the table @public.users@.
 type ns ->> name = 'NameNS ns name
 
 type SimpleType c = 'TypDef c 'Nothing '[]
@@ -184,10 +198,14 @@
   AppendPK '[] uks = uks
   AppendPK pk uks = pk ': uks
 
--- | Keys accepted by 'CheckAllMandatoryOrHasKey' (tree upsert) and
--- 'CheckHasKey' (flat 'updateByKey' / 'upsertByKey'): PK plus every unique
--- constraint from the schema (catalog order). Runtime key choice uses
--- 'PgSchema.DML.KeyedWrite.identityCandidatesFromTab' and its priority rules.
+-- | Keys accepted by 'PgSchema.Ann.CheckAllMandatoryOrHasKey' (tree upsert) and
+-- 'PgSchema.Ann.CheckHasKey' (flat 'PgSchema.DML.updateByKey' /
+-- 'PgSchema.DML.upsertByKey'): the primary key plus every unique constraint
+-- from the schema (catalog order), including unique constraints over nullable
+-- columns. A record \"has a key\" if it covers all columns of any of them.
+--
+-- At runtime the first covered key is used, in this order: the primary key,
+-- unique constraints over @NOT NULL@ columns, other unique constraints.
 type family IdentityCandidates sch tab :: [[Symbol]] where
   IdentityCandidates sch tab =
     AppendPK (TdKey (TTabDef sch tab)) (TdUniq (TTabDef sch tab))
@@ -209,14 +227,15 @@
   NameSymNat '(s,n) = AppendSymbol s (AppendSymbol "___" (NatToSymbol n))
 
 -- CTypDef
--- | instances will be generated by code generation
+-- | Definition of a database type. Instances are generated by schema generation.
 class
   (ToStar name, ToStar (TTypDef sch name)) => CTypDef sch (name :: NameNSK) where
 
   type TTypDef sch name :: TypDefK
 
 -- | Schema-level field kind for (sch, tab, field name).
--- Instances are generated by codegen (Gen) or defined manually (e.g. Catalog).
+-- Instances are generated by schema generation ("PgSchema.Generation") or
+-- defined manually (e.g. "PgSchema.Schema.Catalog").
 class (ToStar (TDBFieldInfo sch tab name), ToStar tab, ToStar name)
   => CDBFieldInfo sch (tab :: NameNSK) (name :: Symbol) where
     type TDBFieldInfo sch tab name :: RecFieldK NameNSK
@@ -230,16 +249,18 @@
   GetFldDef sch tab name = PlainFldDef (TDBFieldInfo sch tab name)
 
 -- CTabDef
--- | instances will be generated by code generation
+-- | Definition of a table. Instances are generated by schema generation.
 class (ToStar name, ToStar (TTabDef sch name)) => CTabDef sch (name::NameNSK) where
   type TTabDef sch name :: TabDefK
 
--- | Relation definition for relation name ref.
+-- | Relation definition for relation name @ref@.
 class
   ( ToStar (TRelDef sch ref)
   , CTabDef sch (RdFrom (TRelDef sch ref))
   , CTabDef sch (RdTo (TRelDef sch ref)) )
   => CRelDef sch (ref :: NameNSK) where
+    -- | Definition of the foreign key @ref@: child and parent tables and the
+    -- pairs of columns.
     type TRelDef sch (ref :: NameNSK) :: RelDefK
 
 getFldDef :: forall sch t n. ToStar (TDBFieldInfo sch t n) => FldDef
@@ -247,8 +268,11 @@
   RFPlain fd -> fd
   _ -> error "impossible"
 
+-- | Relations of a table. Instances are generated by schema generation.
 class CTabRels sch (tab :: NameNSK) where
+  -- | Foreign keys from table @tab@ to its parents.
   type TFrom sch tab :: [NameNSK]
+  -- | Foreign keys from children to table @tab@.
   type TTo sch tab :: [NameNSK]
 
 genDefunSymbols [''TTypDef, ''TDBFieldInfo, ''GetFldDef, ''TTabDef, ''TRelDef, ''TFrom, ''TTo]
@@ -269,7 +293,7 @@
 --
 -- This class guarantees that we can demote all the necessary information about the schema from type level to value level.
 --
--- Instances will be generated by code generation
+-- Instances are generated by schema generation.
 class
   ( ToStar (TTabs sch)
   , ToStar (TTabRelFroms sch)
@@ -334,7 +358,7 @@
 
 -- | Walk a directed @path@ from root table @t@.
 --
--- Each step is a 'PathElem' (schema walk uses 'peDbName'). Result: end table and
+-- Each step is a t'PathElem' (schema walk uses 'peDbName'). Result: end table and
 -- its cardinality ('RelOne' for a single parent step, 'RelMany' for a single child).
 type family TabOnDPath2 sch (t :: NameNSK) (path :: [PathElemK]) :: (NameNSK, RelType) where
   TabOnDPath2 sch t '[] = '(t, 'RelMany)
@@ -379,30 +403,59 @@
 type HasFromStep sch tab name = HasRelName (TFrom sch tab) name
 type HasToStep   sch tab name = HasRelName (TTo sch tab) name
 
--- | Resolve 'PathKind' for 'qPath' / 'qPathFromHere' / 'qPathToHere'.
+-- | Comma-separated names of relations (for error messages).
+type family RelNamesMsg (rels :: [NameNSK]) :: ErrorMessage where
+  RelNamesMsg '[] = TL.Text "<none>"
+  RelNamesMsg '[ 'NameNS _ n ] = TL.Text n
+  RelNamesMsg ('NameNS _ n ': rs) = TL.Text n :<>: TL.Text ", " :<>: RelNamesMsg rs
+
+-- | Note for error messages when the renamer changed the name given by user.
+type family RenamedMsg (orig :: Symbol) (name :: Symbol) :: ErrorMessage where
+  RenamedMsg name name = TL.Text ""
+  RenamedMsg orig name =
+    TL.Text " (" :<>: ShowType orig :<>: TL.Text " after applying the renamer)"
+
+-- | Resolve 'PathKind' for 'PgSchema.DML.qPath' / 'PgSchema.DML.qPathFromHere' /
+-- 'PgSchema.DML.qPathToHere'.
+--
+-- @hasFrom@ / @hasTo@: whether @name@ is in 'TFrom' / 'TTo' of @tab@
+-- (both are 'True' for a self-reference relation).
+-- @orig@ is the name as given by user, @name@ is the name after applying the renamer.
 type family ResolvePathKind
-  (pathKind :: Maybe PathKind) (hasFrom :: Bool) (hasTo :: Bool) (tab :: NameNSK)
-  (name :: Symbol)
+  (pathKind :: Maybe PathKind) (hasFrom :: Bool) (hasTo :: Bool) sch (tab :: NameNSK)
+  (orig :: Symbol) (name :: Symbol)
   :: PathKind where
-  ResolvePathKind ('Just 'FromHere) 'True _ _ _ = 'FromHere
-  ResolvePathKind ('Just 'ToHere) _ 'True _ _ = 'ToHere
-  ResolvePathKind 'Nothing 'True 'False _ _ = 'FromHere
-  ResolvePathKind 'Nothing 'False 'True _ _ = 'ToHere
-  ResolvePathKind ('Just 'FromHere) _ _ tab name = TypeError
+  ResolvePathKind _ 'False 'False sch tab orig name = TypeError
+    ( TL.Text "In schema " :<>: ShowType sch
+    :$$: TL.Text "for table " :<>: ShowType tab
+    :$$: TL.Text "relation " :<>: ShowType name :<>: RenamedMsg orig name
+      :<>: TL.Text " is not defined."
+    :$$: TL.Text ""
+    :$$: TL.Text "Valid values are:"
+    :$$: TL.Text "  Foreign key constraints to parent tables (qPathFromHere or qPath): "
+      :<>: RelNamesMsg (TFrom sch tab) :<>: TL.Text "."
+    :$$: TL.Text "  Foreign key constraints from child tables (qPathToHere or qPath): "
+      :<>: RelNamesMsg (TTo sch tab) :<>: TL.Text "."
+    :$$: TL.Text "" )
+  ResolvePathKind ('Just 'FromHere) 'True _ _ _ _ _ = 'FromHere
+  ResolvePathKind ('Just 'ToHere) _ 'True _ _ _ _ = 'ToHere
+  ResolvePathKind 'Nothing 'True 'False _ _ _ _ = 'FromHere
+  ResolvePathKind 'Nothing 'False 'True _ _ _ _ = 'ToHere
+  ResolvePathKind ('Just 'FromHere) 'False 'True _ tab _ name = TypeError
     ( TL.Text "Relation is not available in from-here direction."
     :$$: TL.Text "Use qPathToHere or qPath."
     :$$: TL.Text ""
     :$$: TL.Text "Table: " :<>: ShowType tab
     :$$: TL.Text "Relation: " :<>: ShowType name
     :$$: TL.Text "" )
-  ResolvePathKind ('Just 'ToHere) _ _ tab name = TypeError
+  ResolvePathKind ('Just 'ToHere) 'True 'False _ tab _ name = TypeError
     ( TL.Text "Relation is not available in to-here direction."
     :$$: TL.Text "Use qPathFromHere or qPath."
     :$$: TL.Text ""
     :$$: TL.Text "Table: " :<>: ShowType tab
     :$$: TL.Text "Relation: " :<>: ShowType name
     :$$: TL.Text "" )
-  ResolvePathKind 'Nothing _ _ tab name = TypeError
+  ResolvePathKind 'Nothing 'True 'True _ tab _ name = TypeError
     ( TL.Text "qPath cannot be used for self-reference relation."
     :$$: TL.Text "Use qPathFromHere or qPathToHere."
     :$$: TL.Text ""
diff --git a/src/PgSchema/Schema/Catalog.hs b/src/PgSchema/Schema/Catalog.hs
--- a/src/PgSchema/Schema/Catalog.hs
+++ b/src/PgSchema/Schema/Catalog.hs
@@ -19,10 +19,13 @@
 import GHC.TypeError qualified as TE
 import PgSchema.Utils.Internal
 
+-- | Type-level schema of the PostgreSQL system catalogs used by @pg-schema@.
 data PgCatalog
 
+-- | Name in the @pg_catalog@ schema, e.g. @PGC \"int4\"@.
 type PGC name = "pg_catalog" ->> name
 
+-- | Term-level name in the @pg_catalog@ schema, e.g. @pgc \"int4\"@.
 pgc :: Text -> NameNS
 pgc = ("pg_catalog" ->>)
 
@@ -186,7 +189,7 @@
 
 ---------- CDBFieldInfo ----------
 
--- Closed type family for PgCatalog field info
+-- | Fields of the catalog tables (see 'TDBFieldInfo').
 type family TDBFieldInfoPgCatalog (t :: NameNSK) (f :: Symbol)
   :: RecFieldK NameNSK where
   -- plain oid column for all catalog tables
diff --git a/src/PgSchema/Schema/Info.hs b/src/PgSchema/Schema/Info.hs
--- a/src/PgSchema/Schema/Info.hs
+++ b/src/PgSchema/Schema/Info.hs
@@ -27,11 +27,13 @@
   , constraint__class :: [PgConstraint] }
   deriving (Show,Eq,Generic)
 
+-- | Short table info: schema and name.
 data PgClassShort = PgClassShort
   { class__namespace :: "nspname" := Text
   , relname          :: Text }
   deriving (Show,Eq,Generic)
 
+-- | Column info.
 data PgAttribute = PgAttribute
   { attname         :: Text
   , attribute__type :: PgType
@@ -40,6 +42,7 @@
   , atthasdef       :: Bool }
   deriving (Show,Eq,Generic)
 
+-- | Constraint info (primary keys and unique constraints are used).
 data PgConstraint = PgConstraint
   { constraint__namespace :: "nspname" := Text
   , conname               :: Text
@@ -57,7 +60,7 @@
   , enum__type      :: [PgEnum] }
   deriving (Show,Eq,Generic)
 
---
+-- | Label of an enum type.
 data PgEnum = PgEnum
   { enumlabel     :: Text
   , enumsortorder :: Double }
diff --git a/src/PgSchema/Types.hs b/src/PgSchema/Types.hs
--- a/src/PgSchema/Types.hs
+++ b/src/PgSchema/Types.hs
@@ -2,7 +2,7 @@
 {-# LANGUAGE CPP #-}
 module PgSchema.Types(
   -- * PgTag types
-  type (:=), (=:), (:.)(..), PgTag(..)
+  type (:=), (=:), (:.)(..), PgTag(..), named, Named
   -- * Enum
   , PGEnum
   -- * Aggregates
@@ -12,7 +12,7 @@
   -- * Other types
   , PgChar(..), PgOid(..)
   -- * Conversion checks
-  , CanConvert, CanConvert1
+  , CanConvert, CanConvert1, CheckAggr
   -- * UnsafeCol
   , UnsafeCol(..) )
   where
@@ -45,12 +45,11 @@
 import Database.PostgreSQL.Simple.Types
 import GHC.TypeLits as TL
 import GHC.TypeError as TE
-import Data.Type.Equality (type (==))
 import GHC.Int
 import Prelude as P
 import Type.Reflection
 import PgSchema.Schema.Catalog (PGC)
-import Data.Type.Bool (Not, type (&&), type (||))
+import Data.Type.Bool (If, Not)
 import PgSchema.Schema
 import PgSchema.Utils.Internal hiding (fromText)
 import PgSchema.Utils.TF
@@ -66,10 +65,11 @@
 #endif
 
 
--- | Representation of `enum` database types.
+-- | Representation of @enum@ database types.
 --
 -- Data instances are produced by schema generation.
--- You can use these data instances in your records to @SELECT@ | @INSERT@ | @UPSERT@ data.
+-- You can use these data instances in your records to select, insert, update
+-- or upsert data.
 data family PGEnum sch (name :: NameNSK) :: Type
 
 instance
@@ -114,22 +114,38 @@
 
 -- | Representation of aggregate functions.
 --
--- E.g. @\"fld\" := Aggr AMin (Maybe Int32)@ means "minimum value of the field `fld`"
+-- E.g. @\"fld\" := Aggr AMin (Maybe Int32)@ means "minimum value of the field @fld@".
 --
--- 'Aggr' requires a 'Maybe' argument for all functions except @count@.
+-- t'Aggr' requires a 'Maybe' argument for all functions except @count@:
+-- all aggregate functions except @count@ return @NULL@ on an empty set of rows
+-- (e.g. @select min(a) from t where false@), even if the field is mandatory.
+-- Use t'Aggr'' in rows with grouping fields to avoid 'Maybe' for mandatory fields.
 --
 -- Only a small set of aggregations are supported currently: @count@, @min@, @max@, @sum@, @avg@.
+--
+-- The Haskell type is checked at compile time against the SQL result type of
+-- the aggregate ('CheckAggr'):
+--
+-- * @count@ - @int8@: 'Int64';
+-- * @min@ / @max@ - type of the field (numeric, text, bool or date fields);
+-- * @sum(int2 | int4)@ - @int8@: 'Int64', 'Scientific' or 'Rational';
+-- * @sum(int8 | numeric)@, @avg(int2 | int4 | int8 | numeric)@ - @numeric@:
+--   'Scientific' or 'Rational';
+-- * @sum(float4)@ - @float4@, @sum(float8)@ - @float8@, @avg(float4 | float8)@ - @float8@:
+--   'Double', 'Scientific' or 'Rational'.
 newtype Aggr (f :: AggrFun) t = Aggr { unAggr :: t }
   deriving stock Show
   deriving newtype (Eq, Ord, FromField, ToField, FromJSON, ToJSON)
 
--- | All aggregate functions except @count@ can return NULL.
--- But if field under aggregate is mandatory they return NULL only on empty set
--- if there is no group by clause. E.g. `select min(a) from t where false`
--- So we require Nullable for Aggr.
+-- | Like t'Aggr', but for rows that also contain non-aggregate (grouping) fields.
 --
--- 'Aggr'' is like 'Aggr' but cannot be used in SELECT without `group by`.
--- So it is mandatory if field is mandatory.
+-- For such rows @GROUP BY@ over the non-aggregate fields is generated, and every
+-- group has at least one row. So the result of the aggregate is @NULL@ only if
+-- the field is nullable: t'Aggr'' requires 'Maybe' exactly for nullable fields
+-- (and never for @count@).
+--
+-- Without grouping fields there is no @GROUP BY@, and on an empty set of rows the
+-- result is @NULL@ even for a mandatory field, so decoding fails. Use t'Aggr' there.
 newtype Aggr' (f :: AggrFun) t = Aggr' { unAggr' :: t }
   deriving stock Show
   deriving newtype (Eq, Ord, FromField, ToField, FromJSON, ToJSON)
@@ -147,14 +163,14 @@
 instance ToField PgChar where
   toField = toField . (:[]) . unPgChar
 
---
--- | 'PGArray' has no JSON instances. '[]' has JSON, but no PG instances.
+-- | t'PGArray' has no JSON instances. @[]@ has JSON, but no PostgreSQL instances.
 -- This one has both.
 --
 -- Use this type to work with arrays in database.
 --
--- All elements are 'Maybe' because PostgreSQL does not guarantee that all elements are present.
--- 'PgTag' @typeName@ 'PgArr' can be /safely/ converted to 'ToField' with type information (e.g. @val::int[]@).
+-- All elements are 'Maybe' because elements of a PostgreSQL array can be @NULL@.
+-- @PgTag typeName (PgArr a)@ has a 'ToField' instance that adds the array type
+-- to the value (e.g. @val::int[]@), so it is converted /safely/.
 -- This instance is used internally in the generation of SQL.
 --
 newtype PgArr a = PgArr { unPgArr :: [Maybe a] }
@@ -190,22 +206,27 @@
 instance FromJSON a => FromJSON (PgTag (s :: Maybe NameNSK) (PgArr a)) where
   parseJSON = fmap PgTag . parseJSON
 
--- | Make 'PgArr' from list. All elements are lifted to 'Maybe'
+-- | Make t'PgArr' from list. All elements are lifted to 'Maybe'.
 pgArr' :: [a] -> PgArr a
 pgArr' = PgArr . fmap Just
 
--- | Make list from 'PgArr'. All empty ('Nothing') elements are omitted.
+-- | Make list from t'PgArr'. All empty ('Nothing') elements are omitted.
 unPgArr' :: PgArr a -> [a]
 unPgArr' = catMaybes . unPgArr
 
--- | 'Oid' but with JSON instances
+-- | t'Oid' but with JSON instances.
+--
+-- It is used to read the system catalogs during schema generation.
+--
+-- Note that all values are equal ('Eq' ignores the OID): schemas are compared
+-- by names, not by OIDs, e.g. if some table or constraint was recreated.
 newtype PgOid = PgOid { fromPgOid :: Oid }
   deriving stock (Show, Read)
   deriving newtype (FromField, ToField)
 
+-- | All values are equal: we don't want to distinguish by OIDs but by names
+-- instead (e.g. if we recreate some table or constraint).
 instance Eq PgOid where _ == _ = True
-  -- we don't want to distinguish by OIDs but by names instead
-  -- e.g. if we recreate some table or constraint
 
 instance FromJSON PgOid where
   parseJSON = fmap (PgOid . read . ("Oid " ++)) . parseJSON
@@ -227,8 +248,12 @@
   :$$: TL.Text "Haskell Field type: " :<>: TL.ShowType t
   :$$: TL.Text "")
 
+type ErrWithHead :: forall k. Symbol -> NameNSK -> Symbol -> NameNSK -> Type -> k
 type ErrWithHead s tab fld tn t = TL.TypeError (TL.Text s :$$: ErrDesc tab fld tn t)
 
+type ErrWithHead' :: forall k. ErrorMessage -> NameNSK -> Symbol -> NameNSK -> Type -> k
+type ErrWithHead' msg tab fld tn t = TL.TypeError (msg :$$: ErrDesc tab fld tn t)
+
 type family GuardConvert (ok :: Bool) sch tab fld tn td t t' err :: Constraint where
   GuardConvert 'True  sch tab fld tn td t t' err = CanConvert1 sch tab fld tn td t'
   GuardConvert 'False sch tab fld tn td t t' err = ErrWithHead err tab fld tn t
@@ -244,80 +269,147 @@
   CanConvertMaybe sch tab fld tn nullable td (Maybe t) = GuardConvert
     nullable sch tab fld tn td (Maybe t) t "You can't use Maybe for mandatory fields"
   -- aggregates --
-  -- ACount<=>int64; AMin/AMax<=>N,S,B,D; ASum<=>N+int*->Int64|Double; AAvg<=>N+float8
-  CanConvertMaybe sch tab fld tn nullable td (Aggr ACount Int64) = ()
-  CanConvertMaybe sch tab fld tn nullable td (Aggr ACount t) =
-    ErrWithHead "You have to use Int64 for Aggr ACount fields" tab fld tn t
-  CanConvertMaybe sch tab fld tn nullable td (Aggr' ACount Int64) = ()
-  CanConvertMaybe sch tab fld tn nullable td (Aggr' ACount t) =
-    ErrWithHead "You have to use Int64 for Aggr' ACount fields" tab fld tn t
-  CanConvertMaybe sch tab fld tn nullable td (Aggr AMin t) = GuardConvert
-    (IsMaybe t && Elem' (TypCategory td) '["N","S","B","D"])
-    sch tab fld tn td (Aggr AMin t) (UnMaybe t)
-    "'Aggr AMin' is possible only for 'Maybe' values and numeric, text, bool or date fields"
-  CanConvertMaybe sch tab fld tn nullable td (Aggr' AMin t) = GuardConvert
-    (Elem' (TypCategory td) '["N","S","B","D"]) sch tab fld tn td (Aggr' AMin t) t
-      "'Aggr' AMin' is possible only for numeric, text, bool or date fields"
-  CanConvertMaybe sch tab fld tn nullable td (Aggr AMax t) = GuardConvert
-    (IsMaybe t && Elem' (TypCategory td) '["N","S","B","D"])
-    sch tab fld tn td (Aggr AMax t) (UnMaybe t)
-    "'Aggr AMax' is possible only for 'Maybe' values and numeric, text, bool or date fields"
-  CanConvertMaybe sch tab fld tn nullable td (Aggr' AMax t) = GuardConvert
-    (Elem' (TypCategory td) '["N","S","B","D"])
-    sch tab fld tn td (Aggr' AMax t) t
-    "'Aggr' AMax' is possible only for numeric, text, bool or date fields"
-  CanConvertMaybe sch tab fld tn nullable td (Aggr AAvg (Maybe Scientific)) =
-    Assert (TypCategory td == "N") (ErrWithHead
-      "'Aggr AAvg' is possible only for numeric fields"
-      tab fld tn (Aggr AAvg (Maybe Scientific)))
-  CanConvertMaybe sch tab fld tn nullable td (Aggr AAvg t) = ErrWithHead
-    "You have to use `Maybe Scientific` for `Aggr AAvg` fields"
-    tab fld tn (Aggr AAvg t)
-  CanConvertMaybe sch tab fld tn nullable td (Aggr' AAvg (Maybe Scientific)) =
-    Assert (TypCategory td == "N" && nullable) (ErrWithHead
-      "'Aggr' AAvg (Maybe Scientific)' is possible only for nullable numeric fields"
-      tab fld tn (Aggr' AAvg (Maybe Scientific)))
-  CanConvertMaybe sch tab fld tn nullable td (Aggr' AAvg Scientific) =
-    Assert (TypCategory td == "N" && Not nullable) (ErrWithHead
-      "'Aggr' AAvg Scientific' is possible only for mandatory numeric fields"
-      tab fld tn (Aggr' AAvg Scientific))
-  CanConvertMaybe sch tab fld tn nullable td (Aggr' AAvg t) = ErrWithHead
-    "You have to use `Scientific` (or `Maybe Scientific`) for `Aggr' AAvg` fields"
-    tab fld tn (Aggr' AAvg t)
-  CanConvertMaybe sch tab fld tn nullable td (Aggr ASum (Maybe Int64)) =
-    ( Assert (TypCategory td == "N" && (NnsName tn == "int2" || NnsName tn == "int4"))
-      (ErrWithHead "'Aggr ASum (Maybe Int64)' is possible only for 'int2/int4' fields"
-        tab fld tn (Aggr ASum (Maybe Int64))))
-  CanConvertMaybe sch tab fld tn nullable td (Aggr ASum (Maybe Scientific)) =
-    ( Assert (TypCategory td == "N")
-      (ErrWithHead "'Aggr ASum (Maybe Scientific)' is possible only for numeric fields"
-        tab fld tn (Aggr ASum (Maybe Scientific))))
-  CanConvertMaybe sch tab fld tn nullable td (Aggr ASum t) = ErrWithHead
-    "You have to use `Maybe Int64` (or `Maybe Scientific`) for `Aggr ASum` fields"
-    tab fld tn (Aggr ASum t)
-  CanConvertMaybe sch tab fld tn nullable td (Aggr' ASum (Maybe Int64)) =
-    ( Assert (nullable && TypCategory td == "N" && (NnsName tn == "int2" || NnsName tn == "int4"))
-      (ErrWithHead "'Aggr' ASum (Maybe Int64)' is possible only for nullable 'int2/int4' fields"
-        tab fld tn (Aggr' ASum (Maybe Int64))))
-  CanConvertMaybe sch tab fld tn nullable td (Aggr' ASum (Maybe Scientific)) =
-    ( Assert (nullable && TypCategory td == "N")
-      (ErrWithHead "'Aggr' ASum (Maybe Scientific)' is possible only for nullable numeric fields"
-        tab fld tn (Aggr' ASum (Maybe Scientific))))
-  CanConvertMaybe sch tab fld tn nullable td (Aggr' ASum Int64) =
-    ( Assert (Not nullable && TypCategory td == "N" && (NnsName tn == "int2" || NnsName tn == "int4"))
-      (ErrWithHead "'Aggr' ASum Int64' is possible only for mandatory 'int2/int4' fields"
-        tab fld tn (Aggr' ASum Int64)))
-  CanConvertMaybe sch tab fld tn nullable td (Aggr' ASum Scientific) =
-    ( Assert (Not nullable && TypCategory td == "N")
-      (ErrWithHead "'Aggr' ASum (Scientific)' is possible only for mandatory numeric fields"
-        tab fld tn (Aggr' ASum Scientific)))
-  CanConvertMaybe sch tab fld tn nullable td (Aggr' ASum t) = ErrWithHead
-    "You have to use `[Maybe] Int64` (or `[Maybe] Scientific`) for `Aggr' ASum` fields"
-    tab fld tn (Aggr' ASum t)
+  -- Shapes and SQL result types of aggregates are checked by 'CheckAggr'.
+  -- Here only values of min/max are converted (they have the type of the field).
+  CanConvertMaybe sch tab fld tn nullable td (Aggr fn t) =
+    CanConvertAggr sch tab fld fn tn td (UnMaybe t)
+  CanConvertMaybe sch tab fld tn nullable td (Aggr' fn t) =
+    CanConvertAggr sch tab fld fn tn td (UnMaybe t)
   -- end aggregates --
   CanConvertMaybe sch tab fld tn nullable td t = GuardConvert (Not nullable)
     sch tab fld tn td t t "You have to use Maybe for nullable fields"
 
+type family CanConvertAggr sch (tab::NameNSK) (fld::Symbol) (fn :: AggrFun)
+  (tn::NameNSK) (td::TypDefK) (t :: Type) :: Constraint where
+  CanConvertAggr sch tab fld 'AMin tn td t =
+    If (IsMinMaxCategory td) (CanConvert1 sch tab fld tn td t) (() :: Constraint)
+  CanConvertAggr sch tab fld 'AMax tn td t =
+    If (IsMinMaxCategory td) (CanConvert1 sch tab fld tn td t) (() :: Constraint)
+  CanConvertAggr sch tab fld fn tn td t = ()
+
+-- | Check the Haskell type @at@ of an aggregate field (e.g. @Aggr ASum (Maybe Int64)@)
+-- over the DB field @fld@ against the SQL result type of the aggregate function
+-- (see 'AggrResType'). Reduces to @'True@ or to a 'TypeError'.
+--
+-- * t'Aggr' (except @count@) requires 'Maybe': the result is NULL on an empty set.
+-- * t'Aggr'' (with @GROUP BY@) requires 'Maybe' exactly for nullable fields.
+-- * @count@ is 'Int64'.
+-- * @sum@ / @avg@ results: @int8@ - 'Int64', 'Scientific' or 'Rational';
+--   @numeric@ - 'Scientific' or 'Rational'; @float4@ / @float8@ - 'Double',
+--   'Scientific' or 'Rational'.
+-- * @min@ / @max@ have the type of the field and are converted like the field
+--   ('CanConvert1').
+type family CheckAggr sch (tab::NameNSK) (fld::Symbol) (fd :: FldDefK) (at :: Type)
+  :: Bool where
+  CheckAggr sch tab fld fd at =
+    CheckAggr' tab fld (FdType fd) (FdNullable fd) (TTypDef sch (FdType fd)) at
+
+type family CheckAggr' (tab::NameNSK) (fld::Symbol) (tn::NameNSK) (nullable :: Bool)
+  (td :: TypDefK) (at :: Type) :: Bool where
+  CheckAggr' tab fld tn nullable td (Aggr 'ACount Int64) = 'True
+  CheckAggr' tab fld tn nullable td (Aggr 'ACount t) =
+    ErrWithHead "You have to use Int64 for Aggr ACount fields" tab fld tn (Aggr 'ACount t)
+  CheckAggr' tab fld tn nullable td (Aggr' 'ACount Int64) = 'True
+  CheckAggr' tab fld tn nullable td (Aggr' 'ACount t) =
+    ErrWithHead "You have to use Int64 for Aggr' ACount fields" tab fld tn (Aggr' 'ACount t)
+  CheckAggr' tab fld tn nullable td (Aggr fn (Maybe t)) =
+    CheckAggrRes tab fld fn tn (AggrResType fn tn td) (Aggr fn (Maybe t)) t
+  CheckAggr' tab fld tn nullable td (Aggr fn t) = ErrWithHead
+    "'Aggr' (except 'Aggr ACount') requires 'Maybe': the aggregate is NULL on an empty set. Use 'Aggr'' with GROUP BY to avoid 'Maybe' for mandatory fields"
+    tab fld tn (Aggr fn t)
+  CheckAggr' tab fld tn nullable td (Aggr' fn (Maybe t)) = If nullable
+    (CheckAggrRes tab fld fn tn (AggrResType fn tn td) (Aggr' fn (Maybe t)) t)
+    (ErrWithHead "You can't use Maybe in 'Aggr'' for mandatory fields"
+      tab fld tn (Aggr' fn (Maybe t)))
+  CheckAggr' tab fld tn nullable td (Aggr' fn t) = If nullable
+    (ErrWithHead "You have to use Maybe in 'Aggr'' for nullable fields"
+      tab fld tn (Aggr' fn t))
+    (CheckAggrRes tab fld fn tn (AggrResType fn tn td) (Aggr' fn t) t)
+  CheckAggr' tab fld tn nullable td at = ErrWithHead
+    "Aggregate field must have type 'Aggr fn t' or 'Aggr' fn t'" tab fld tn at
+
+-- | SQL result type of aggregate function @fn@ over a field of type @tn@
+-- (with type definition @td@).
+-- 'Nothing' if the aggregate is not supported for the field type.
+--
+-- * @count@ -> @int8@
+-- * @min@ / @max@ -> type of the field (numeric, text, bool or date fields)
+-- * @sum(int2 | int4)@ -> @int8@, @sum(int8 | numeric)@ -> @numeric@,
+--   @sum(float4)@ -> @float4@, @sum(float8)@ -> @float8@
+-- * @avg(int2 | int4 | int8 | numeric)@ -> @numeric@, @avg(float4 | float8)@ -> @float8@
+type family AggrResType (fn :: AggrFun) (tn :: NameNSK) (td :: TypDefK)
+  :: Maybe NameNSK where
+  AggrResType 'ACount tn td = 'Just (PGC "int8")
+  AggrResType 'AMin tn td = If (IsMinMaxCategory td) ('Just tn) 'Nothing
+  AggrResType 'AMax tn td = If (IsMinMaxCategory td) ('Just tn) 'Nothing
+  AggrResType 'ASum (PGC "int2") td = 'Just (PGC "int8")
+  AggrResType 'ASum (PGC "int4") td = 'Just (PGC "int8")
+  AggrResType 'ASum (PGC "int8") td = 'Just (PGC "numeric")
+  AggrResType 'ASum (PGC "float4") td = 'Just (PGC "float4")
+  AggrResType 'ASum (PGC "float8") td = 'Just (PGC "float8")
+  AggrResType 'ASum (PGC "numeric") td = 'Just (PGC "numeric")
+  AggrResType 'AAvg (PGC "int2") td = 'Just (PGC "numeric")
+  AggrResType 'AAvg (PGC "int4") td = 'Just (PGC "numeric")
+  AggrResType 'AAvg (PGC "int8") td = 'Just (PGC "numeric")
+  AggrResType 'AAvg (PGC "numeric") td = 'Just (PGC "numeric")
+  AggrResType 'AAvg (PGC "float4") td = 'Just (PGC "float8")
+  AggrResType 'AAvg (PGC "float8") td = 'Just (PGC "float8")
+  AggrResType fn tn td = 'Nothing
+
+-- | Type categories supported by @min@ / @max@
+-- (numeric, string, boolean and date/time).
+type family IsMinMaxCategory (td :: TypDefK) :: Bool where
+  IsMinMaxCategory td = Elem' (TypCategory td) '["N","S","B","D"]
+
+type family CheckAggrRes (tab::NameNSK) (fld::Symbol) (fn :: AggrFun) (tn::NameNSK)
+  (res :: Maybe NameNSK) (at :: Type) (t :: Type) :: Bool where
+  CheckAggrRes tab fld fn tn 'Nothing at t = ErrWithHead'
+    ( TL.Text "Aggregate '" :<>: TL.Text (AggrFunName fn)
+      :<>: TL.Text "' is not supported for fields of type '"
+      :<>: TL.Text (NnsName tn) :<>: TL.Text "'" )
+    tab fld tn at
+  -- min/max have the type of the field: values are checked by 'CanConvert1'
+  CheckAggrRes tab fld 'AMin tn ('Just tn) at t = 'True
+  CheckAggrRes tab fld 'AMax tn ('Just tn) at t = 'True
+  CheckAggrRes tab fld fn tn ('Just rt) at t = If (AggrResCompatible rt t) 'True
+    ( ErrWithHead'
+      ( TL.Text "Aggregate '" :<>: TL.Text (AggrFunName fn)
+        :<>: TL.Text "' over a field of type '" :<>: TL.Text (NnsName tn)
+        :<>: TL.Text "' returns SQL type '" :<>: TL.Text (NnsName rt) :<>: TL.Text "',"
+      :$$: TL.Text "but Haskell type " :<>: TL.ShowType t
+        :<>: TL.Text " is not compatible with it."
+      :$$: TL.Text "Use " :<>: TL.Text (AggrResHint rt) :<>: TL.Text " instead." )
+      tab fld tn at )
+
+type family AggrFunName (fn :: AggrFun) :: Symbol where
+  AggrFunName 'ACount = "count"
+  AggrFunName 'AMin = "min"
+  AggrFunName 'AMax = "max"
+  AggrFunName 'ASum = "sum"
+  AggrFunName 'AAvg = "avg"
+
+-- | Haskell types for SQL result types of @count@, @sum@ and @avg@.
+type family AggrResCompatible (rt :: NameNSK) (t :: Type) :: Bool where
+  AggrResCompatible (PGC "int8") Int64 = 'True
+  AggrResCompatible (PGC "int8") Scientific = 'True
+  AggrResCompatible (PGC "int8") Rational = 'True
+  AggrResCompatible (PGC "numeric") Scientific = 'True
+  AggrResCompatible (PGC "numeric") Rational = 'True
+  AggrResCompatible (PGC "float4") Double = 'True
+  AggrResCompatible (PGC "float4") Scientific = 'True
+  AggrResCompatible (PGC "float4") Rational = 'True
+  AggrResCompatible (PGC "float8") Double = 'True
+  AggrResCompatible (PGC "float8") Scientific = 'True
+  AggrResCompatible (PGC "float8") Rational = 'True
+  AggrResCompatible rt t = 'False
+
+type family AggrResHint (rt :: NameNSK) :: Symbol where
+  AggrResHint (PGC "int8") = "Int64, Scientific or Rational"
+  AggrResHint (PGC "numeric") = "Scientific or Rational"
+  AggrResHint (PGC "float4") = "Double, Scientific or Rational"
+  AggrResHint (PGC "float8") = "Double, Scientific or Rational"
+  AggrResHint rt = "?"
+
 -- | Open mapping from a PostgreSQL type (non-nullable) to a Haskell type.
 -- Add your own equations to this family to support extra pairings.
 type family CanConvert1 sch (tab::NameNSK) (fld::Symbol) (tn::NameNSK) (td::TypDefK) t :: Constraint
@@ -381,21 +473,27 @@
 -- You can describe rows in two ways:
 --
 -- 1. Ordinary Haskell records with a 'GHC.Generics.Generic' instance.
--- 2. Symbol-labelled rows built from '(=:)' and chained with '(:.)' from
+-- 2. Symbol-labelled rows built from '(=:)' and chained with t'(:.)' from
 --    @postgresql-simple@ (re-exported from "PgSchema.DML").
 --
--- 'PgTag' is analogous to 'Data.Tagged.Tagged' from the @tagged@ package, but
+-- Lists of symbol-labelled rows can also be made from plain values without
+-- field names: with 'PgSchema.DML.rowsOf' (names and types are taken from the
+-- row type) or 'named' (names are given once for the whole list). In the other
+-- direction, 'PgSchema.DML.plains' drops the names from selected or returned rows.
+--
+-- t'PgTag' is analogous to 'Data.Tagged.Tagged' from the @tagged@ package, but
 -- carries JSON (and related) instances suited to @pg-schema@.
 --
 -- Both representations can be mixed in one row.
 --
--- Two pieces of syntax cooperate with 'PgTag':
+-- Two pieces of syntax cooperate with t'PgTag':
 --
--- * '(=:)' builds a 'PgTag' value (field name + payload).
--- @RequiredTypeArguments@ lets you avoid noisy explicit type application on the
--- field name: you write "name" =: "John" instead of @"name" =: "John".
--- * '(:=)' is the type-level spelling of the same idea (see the '(:=)' type
---   synonym below).
+-- * '(=:)' builds a t'PgTag' value (field name + payload).
+--   @RequiredTypeArguments@ lets you avoid noisy explicit type application on the
+--   field name: you write @\"name\" =: \"John\"@ instead of
+--   @(=:) \@\"name\" \"John\"@.
+-- * t'(:=)' is the type-level spelling of the same idea:
+--   @\"name\" := Text@ is the type of @\"name\" =: (\"John\" :: Text)@.
 --
 newtype PgTag s t = PgTag { unPgTag :: t }
   deriving stock (Eq, Ord, Functor, Foldable, Traversable)
@@ -463,13 +561,95 @@
 instance {-# OVERLAPPABLE #-} Read t => Read (PgTag s t) where
   readsPrec p = readParen (p > 11) readsPgTagLegacy
 
+-- | Field named @s@ with value of type @t@: the type of @s '=:' value@.
+--
+-- > type User = "name" := Text :. "email" := Maybe Text
 type s := t = PgTag s t
 infixr 5 :=
 
+-- | Field with name @a@ (given as a required type argument) and value of type @b@.
+--
+-- > "name" =: ("John" :: Text) :. "email" =: (Nothing :: Maybe Text)
+--
+-- Fields are chained into rows with t'(:.)'. To make a list of rows without
+-- repeating the field names in every row, see 'PgSchema.DML.rowsOf' and 'named'.
 (=:) :: forall b. forall a -> b -> a := b
 (=:) _ = coerce
 infixr 5 =:
 
+-- | Attach field names to a list of plain rows at once.
+--
+-- Rows are ordinary values chained with t'(:.)' (no t'PgTag' on each field);
+-- the names are given only once, for the whole list:
+--
+-- > (res, _) <- insertSch (MyAnn "projects") conn $
+-- >   named ["ownerId", "title", "status", "tags"]
+-- >     [ (1 :: Int64) :. ("pg-schema" :: Text) :. Project_status_active :. pgArr' ["db" :: Text, "haskell"]
+-- >     , 1 :. "tutorial" :. Project_status_draft :. pgArr' ["learning"] ]
+-- > print (plains @("id" := Int64) res)
+--
+-- is the same as
+--
+-- > (res, _) <- insertSch (MyAnn "projects") conn
+-- >   [ "ownerId" =: (1 :: Int64) :. "title" =: ("pg-schema" :: Text)
+-- >     :. "status" =: Project_status_active :. "tags" =: pgArr' ["db" :: Text, "haskell"]
+-- >   , "ownerId" =: 1 :. "title" =: "tutorial"
+-- >     :. "status" =: Project_status_draft :. "tags" =: pgArr' ["learning"] ]
+--
+-- The types of the values are inferred from the values here (hence the
+-- annotations). With 'PgSchema.DML.rowsOf' they are taken from a row type
+-- instead: @rowsOf \@(\"ownerId\" := Int64 :. \"title\" := Text :. …)@.
+--
+-- The n-th name is attached to the n-th field; the last name takes the whole
+-- rest of the row. The number of names must be equal to the number of fields,
+-- otherwise there is a compile-time error.
+--
+-- Values are just 'coerce'd, so 'named' costs nothing at runtime. The result
+-- has exactly the same type as rows built with '(=:)', so it can be used
+-- wherever such rows are accepted, including nested rows (a child list is just
+-- another 'named' call).
+--
+-- >>> named ["a", "b"] [1 :. "x", 2 :. ("y" :: String)] :: ["a" := Int :. "b" := String]
+-- ["a" =: 1 :. "b" =: "x","a" =: 2 :. "b" =: "y"]
+named :: forall (ns :: [Symbol]) -> forall r. Coercible [r] [Named ns r] => [r] -> [Named ns r]
+named _ = coerce
+
+-- | Type of a row with field names @ns@ attached to the fields of plain row @r@
+-- (see 'named').
+--
+-- >>> :kind! Named ["a", "b", "c"] (Int :. Bool :. Char)
+-- Named ["a", "b", "c"] (Int :. Bool :. Char) :: *
+-- = PgTag "a" Int :. (PgTag "b" Bool :. PgTag "c" Char)
+type family Named (ns :: [Symbol]) (r :: Type) :: Type where
+  Named '[] r = TE.TypeError
+    ( TE.Text "named: the list of field names is empty."
+    TE.:$$: TE.Text "  The row: " TE.:<>: TE.ShowType r )
+  Named '[n] (a :. b) = TE.TypeError
+    ( TE.Text "named: there are fewer field names than fields in the row."
+    TE.:$$: TE.Text "  The last name " TE.:<>: TE.ShowType n
+      TE.:<>: TE.Text " is given to more than one field: " TE.:<>: TE.ShowType (a :. b) )
+  Named '[n] r = PgTag n r
+  Named (n ': ns) (a :. b) = PgTag n a :. Named ns b
+  Named (n ': ns) r = TE.TypeError
+    ( TE.Text "named: there are more field names than fields in the row."
+    TE.:$$: TE.Text "  Field " TE.:<>: TE.ShowType n TE.:<>: TE.Text " gets the last field "
+      TE.:<>: TE.ShowType r
+    TE.:$$: TE.Text "  Names without fields: " TE.:<>: TE.ShowType ns )
+
+-- | Field whose value is an SQL expression over columns of the table
+-- (for @SELECT@ only).
+--
+-- @expr@ is an SQL expression where each @?@ is replaced with a column from
+-- @flds@ in order (qualified with the alias of the table; the renamer is
+-- applied to the names). E.g. the field
+--
+-- > "total" := UnsafeCol '["price", "qty"] "? * ?" Double
+--
+-- is selected as @t0.price * t0.qty@ and decoded as 'Double'.
+--
+-- It is checked at compile time that all columns exist in the table and that
+-- the number of @?@ is equal to the number of columns. The expression itself and
+-- the type of its result are /not/ checked.
 newtype UnsafeCol (flds :: [Symbol]) (expr :: Symbol) res = UnsafeCol
   { getUnsafeCol :: res }
 
@@ -481,8 +661,8 @@
 
 type family CheckExprInternal flds (m :: Maybe (Char, Symbol)) :: Constraint where
   CheckExprInternal '[] 'Nothing = ()
-  CheckExprInternal (x ': xs) 'Nothing = TypeError (TL.Text "Count of field names in the list of fields is more then count of question marks in expression." )
-  CheckExprInternal '[] ('Just '( '?', _)) = TypeError (TL.Text "Count of question marks in expression is more then count of field names in the list of fields." )
+  CheckExprInternal (x ': xs) 'Nothing = TypeError (TL.Text "Count of field names in the list of fields is more than count of question marks in expression." )
+  CheckExprInternal '[] ('Just '( '?', _)) = TypeError (TL.Text "Count of question marks in expression is more than count of field names in the list of fields." )
   CheckExprInternal (x ': xs) ('Just '( '?', s)) = CheckExprInternal xs (UnconsSymbol s)
   CheckExprInternal xs ('Just '( _, s)) = CheckExprInternal xs (UnconsSymbol s)
 
diff --git a/src/PgSchema/Utils/CamelToSnake.hs b/src/PgSchema/Utils/CamelToSnake.hs
--- a/src/PgSchema/Utils/CamelToSnake.hs
+++ b/src/PgSchema/Utils/CamelToSnake.hs
@@ -6,14 +6,17 @@
 import Data.Type.Equality
 
 
--- | Closed type family to convert CamelCase to snake_case that can be used in 'Renamer'.
+-- | Type-level function to convert @CamelCase@ to @snake_case@.
 --
--- @
+-- It is not a renamer itself, but it is convenient to use it in your renamer
+-- (see 'PgSchema.DML.ApplyRenamer'):
+--
+-- > data MyRenamer :: Renamer
+-- > type instance ApplyRenamer MyRenamer s = CamelToSnake s
+--
 -- >>> import Data.Proxy
 -- >>> symbolVal (Proxy @(CamelToSnake "TESTCamelTo_snake_Case"))
 -- "t_e_s_t_camel_to_snake__case"
---
--- @
 type CamelToSnake (s :: Symbol) = CamelToSnakeInternal (UnconsSymbol s)
 
 type family CamelToSnakeInternal (m :: Maybe (Char, Symbol)) :: Symbol where
diff --git a/src/PgSchema/Utils/Internal.hs b/src/PgSchema/Utils/Internal.hs
--- a/src/PgSchema/Utils/Internal.hs
+++ b/src/PgSchema/Utils/Internal.hs
@@ -29,6 +29,8 @@
 unlines' = intercalate' "\n"
 {-# INLINE unlines' #-}
 
+-- | Type-level value @a@ can be demoted to a term-level value
+-- (with 'Data.Singletons.demote').
 type ToStar a = (SingKind (KindOf a), SingI a)
 
 trace' :: String -> a -> a
diff --git a/src/PgSchema/Utils/ShowType.hs b/src/PgSchema/Utils/ShowType.hs
--- a/src/PgSchema/Utils/ShowType.hs
+++ b/src/PgSchema/Utils/ShowType.hs
@@ -53,7 +53,6 @@
 
 instance ShowType (RecField NameNS) where
   showType = \case
-    RFEmpty s     -> "'RFEmpty " <> showType s
     RFPlain fd    -> "'RFPlain " <> showType fd
     RFAggr fd fn b -> "'RFAggr " <> T.intercalate " " [showType fd, showType fn, showType b]
     RFUnsafe ps expr -> "'RFUnsafe " <> showType ps <> " " <> showType expr
diff --git a/src/PgSchema/Utils/TF.hs b/src/PgSchema/Utils/TF.hs
--- a/src/PgSchema/Utils/TF.hs
+++ b/src/PgSchema/Utils/TF.hs
@@ -6,10 +6,11 @@
 import GHC.TypeLits
 
 
--- | Second component of a type-level pair (replaces "Prelude.Singletons" @Snd@).
+-- | First component of a type-level pair (replaces @Fst@ from "Prelude.Singletons").
 type family Fst (xs :: (a,b)) :: a where
   Fst '(x,_) = x
 
+-- | Second component of a type-level pair (replaces @Snd@ from "Prelude.Singletons").
 type family Snd (xs :: (a, b)) :: b where
   Snd '(_, y) = y
 
@@ -46,16 +47,16 @@
 type family SplitAt (n :: Nat) (xs :: [k]) :: ([k], [k]) where
   SplitAt 0 xs             = '( '[], xs)
   SplitAt n '[]            = '( '[], '[])
-  -- Используем вспомогательный тип, чтобы "пробросить" результат рекурсии
+  -- Use a helper type family to thread the result of the recursion through
   SplitAt n (x ': xs)      = SplitAtHelper x (SplitAt (n - 1) xs)
 
--- Вспомогательный тип для конструирования результата
+-- Helper type family that builds the result
 type family SplitAtHelper (x :: k) (res :: ([k], [k])) :: ([k], [k]) where
   SplitAtHelper x '(left, right) = '(x ': left, right)
 
 -- >>> :kind! SplitAt 2 '[1,2,3,4,5]
 -- SplitAt 2 '[1,2,3,4,5] :: ([Natural], [Natural])
--- = '( '[1, 2], '[3, 4, 5])
+-- = '([1, 2], [3, 4, 5])
 
 type family Map1 (f :: a ~> b) (xs :: [a]) :: [b] where
   Map1 f '[] = '[]
diff --git a/test-gen/Main.hs b/test-gen/Main.hs
--- a/test-gen/Main.hs
+++ b/test-gen/Main.hs
@@ -100,6 +100,26 @@
         constraint nullable_uq_row_code_suffix_uq unique (code, suffix)
       );
 
+      -- All mandatory columns belong to the primary key (key-only upsert).
+      create table tag_link (
+        owner_id integer not null,
+        tag      text not null,
+        note     text,
+        constraint tag_link_pk primary key (owner_id, tag)
+      );
+
+      -- Numeric columns of different types (aggregate result types).
+      create table aggr_nums (
+        id   serial primary key,
+        grp  integer not null,
+        i2   int2 not null,
+        i4   integer,
+        i8   int8 not null,
+        n    numeric,
+        f4   float4 not null,
+        f8   float8
+      );
+
       -- Table for array types (nullable elements, no 2D arrays).
       create table arrays (
         id             serial primary key,
diff --git a/test-pgs/Main.hs b/test-pgs/Main.hs
--- a/test-pgs/Main.hs
+++ b/test-pgs/Main.hs
@@ -11,10 +11,16 @@
 import Tests.BaseConverts
 import Tests.Hierarchy
 import Tests.InsertJSONTransaction
+import Tests.JsonNull
 import Tests.UpsertUniqueKey
 import Tests.KeyedDML
 import Tests.Conditions
 import Tests.Aggregates
+import Tests.AggregateErrors
+import Tests.PathErrors
+import Tests.Named
+import Tests.NamedErrors
+import Tests.ReturningErrors
 
 prop_not_implemented :: Property
 prop_not_implemented = property $ fail "not implemented"
@@ -31,6 +37,22 @@
       , testProperty "Array of extra types" $ prop_ext_arr_converts pool
       , testProperty "InsertJSON: json/jsonb string values use -> operator" $ prop_ext_converts_json_string_via_upsertjson pool
       ]
+    , testGroup "json/jsonb Nothing is SQL NULL in tree DML"
+      [ testProperty "insertJSON/upsertJSON/updateJSON on jsonb child column" $
+          prop_json_null_tree pool
+      , testProperty "insertJSON on json and jsonb columns (vs insertSch)" $
+          prop_json_null_json_and_jsonb pool
+      ]
+    , testGroup "named (test_dml)"
+      [ testProperty "Insert rows built with named" $ prop_named_insert pool
+      , testProperty "Insert tree built with named" $ prop_named_insert_tree pool
+      , testProperty "Insert tree built with rowsOf, returning/select with plains" $ prop_rows_of_tree pool
+      , testProperty "rowsOf with Generic records" $ prop_rows_of_generic pool
+      , testProperty "named: empty list of names" prop_named_empty
+      , testProperty "named: fewer names than fields" prop_named_fewer_names
+      , testProperty "named: more names than fields" prop_named_more_names
+      , testProperty "rowsOf: not a product type" prop_rows_of_not_product
+      ]
     , testGroup "Hierarchy (test_dml)"
       [ testProperty "Insert/Upsert/Select root with children (simple FK)" $ prop_hier_insert_simple_fk pool
       , testProperty "Insert/Upsert/Select root with children (composite FK)" $ prop_hier_insert_composite_fk pool
@@ -52,6 +74,8 @@
     , testGroup "Keyed DML (test_dml)"
       [ testProperty "upsertByKey insert then key patch" $
           prop_upsert_by_key_insert_then_update pool
+      , testProperty "upsertByKey key-only record returns all rows" $
+          prop_upsert_by_key_key_only_returns_all pool
       , testProperty "upsertByKey composite unique" $
           prop_upsert_by_key_composite_unique pool
       , testProperty "upsertByKey always INSERT ON CONFLICT SQL" $
@@ -70,6 +94,16 @@
           prop_upsert_json_full_row_bare_returning pool
       , testProperty "updateJSON child key miss" $
           prop_update_json_child_maybe pool
+      , testProperty "updateJSON missing child returns null element" $
+          prop_update_json_missing_child pool
+      , testProperty "updateJSON missing grandchild returns null element" $
+          prop_update_json_missing_grandchild pool
+      , testProperty "upsertJSON key-only missing child returns null element" $
+          prop_upsert_json_key_only_missing_child pool
+      , testProperty "upsertJSON DO NOTHING child of another parent returns null element" $
+          prop_upsert_json_do_nothing_other_parent pool
+      , testProperty "upsertJSON DO NOTHING child inserted or found" $
+          prop_upsert_json_do_nothing_insert_or_found pool
       ]
     , testGroup "Upsert by unique key (test_dml)"
       [ testProperty "upsertJSON on composite unique without PK in payload" $
@@ -92,6 +126,48 @@
     , testGroup "Aggregates (test_dml)"
       [ testProperty "Aggr' on plain column is not in GROUP BY" $
           prop_selectText_aggr_plain_not_in_group_by pool
+      , testProperty "sum: Haskell types follow SQL result types" $
+          prop_aggr_sum_result_types pool
+      , testProperty "avg: Haskell types follow SQL result types" $
+          prop_aggr_avg_result_types pool
+      , testProperty "Aggr' with GROUP BY: Maybe for nullable fields only" $
+          prop_aggr_grouped_result_types pool
+      ]
+    , testGroup "Aggregate compile-time errors (deferred type errors)"
+      [ testProperty "avg(int4) as Double" prop_aggr_avg_int_double
+      , testProperty "sum(int8) as Int64" prop_aggr_sum_int8_int64
+      , testProperty "sum(int4) as Int32" prop_aggr_sum_int4_int32
+      , testProperty "avg(numeric) as Double" prop_aggr_avg_numeric_double
+      , testProperty "sum(text)" prop_aggr_sum_text
+      , testProperty "Aggr without Maybe" prop_aggr_without_maybe
+      , testProperty "Aggr' on nullable field without Maybe" prop_aggr'_nullable_without_maybe
+      , testProperty "Aggr' on mandatory field with Maybe" prop_aggr'_mandatory_with_maybe
+      ]
+    , testGroup "Path compile-time errors (deferred type errors)"
+      [ testProperty "qPath: unknown relation" prop_qpath_unknown_rel
+      , testProperty "qPath: unknown relation after renamer" prop_qpath_unknown_rel_renamed
+      , testProperty "qPath: unknown relation in nested path" prop_qpath_unknown_rel_nested
+      , testProperty "qPathFromHere: unknown relation" prop_qpath_from_here_unknown_rel
+      , testProperty "qPathToHere: unknown relation" prop_qpath_to_here_unknown_rel
+      , testProperty "qPathFromHere: relation in wrong direction" prop_qpath_from_here_wrong_dir
+      , testProperty "qPathToHere: relation in wrong direction" prop_qpath_to_here_wrong_dir
+      ]
+    , testGroup "Tree DML returning compile-time errors (deferred type errors)"
+      [ testProperty "updateJSON: bare child after plain field" prop_update_child_bare
+      , testProperty "updateJSON: bare child as first field" prop_update_child_bare_first
+      , testProperty "updateJSON: bare second child" prop_update_second_child_bare
+      , testProperty "updateJSON: bare grandchild" prop_update_grandchild_bare
+      , testProperty "updateJSON: Maybe child as first field is ok" prop_update_child_first_ok
+      , testProperty "updateJSON: Maybe on all levels is ok" prop_update_ok
+      , testProperty "insertJSON: Maybe child" prop_insert_child_maybe
+      , testProperty "insertJSON: bare child is ok" prop_insert_ok
+      , testProperty "upsertJSON: bare key-only child" prop_upsert_key_only_child_bare
+      , testProperty "upsertJSON: Maybe insert-capable child" prop_upsert_full_child_maybe
+      , testProperty "upsertJSON: bare key-only root" prop_upsert_key_only_root_bare
+      , testProperty "upsertJSON: Maybe key-only child is ok" prop_upsert_ok
+      , testProperty "upsertJSON: bare insert-capable child is ok" prop_upsert_full_ok
+      , testProperty "upsertJSON: bare ON CONFLICT DO NOTHING child" prop_upsert_do_nothing_child_bare
+      , testProperty "upsertJSON: bare ON CONFLICT DO UPDATE child is ok" prop_upsert_do_update_child_ok
       ]
     --   , testProperty "Cond: Child / Parent exists" prop_not_implemented
     --   , testProperty "Conditions by path (root vs nested path)" prop_not_implemented
diff --git a/test-pgs/Sch.hs b/test-pgs/Sch.hs
--- a/test-pgs/Sch.hs
+++ b/test-pgs/Sch.hs
@@ -1,5 +1,4 @@
 {- HLINT ignore -}
-{-# LANGUAGE CPP #-}
 {-# LANGUAGE FlexibleContexts #-}
 {-# LANGUAGE TypeFamilies #-}
 {-# LANGUAGE UndecidableInstances #-}
@@ -11,9 +10,7 @@
 -- This file is generated and can't be edited.
 
 import Control.DeepSeq
-#ifdef MK_HASHABLE
 import Data.Hashable
-#endif
 import GHC.Generics
 import GHC.TypeError qualified as TE
 import GHC.TypeLits qualified as TL
@@ -24,9 +21,7 @@
   = Color_red | Color_green | Color_blue
   deriving (Show, Read, Ord, Eq, Generic, Bounded, Enum)
 
-#ifdef MK_HASHABLE
 instance Hashable (PGEnum Sch ( "test_pgs" ->> "color" ))
-#endif
 
 instance NFData (PGEnum Sch ( "test_pgs" ->> "color" ))
 
@@ -45,10 +40,12 @@
   TTypDefSch ( "pg_catalog" ->> "date" ) = 'TypDef "D" 'Nothing '[  ]
   TTypDefSch ( "pg_catalog" ->> "float4" ) = 'TypDef "N" 'Nothing '[  ]
   TTypDefSch ( "pg_catalog" ->> "float8" ) = 'TypDef "N" 'Nothing '[  ]
+  TTypDefSch ( "pg_catalog" ->> "int2" ) = 'TypDef "N" 'Nothing '[  ]
   TTypDefSch ( "pg_catalog" ->> "int4" ) = 'TypDef "N" 'Nothing '[  ]
   TTypDefSch ( "pg_catalog" ->> "int8" ) = 'TypDef "N" 'Nothing '[  ]
   TTypDefSch ( "pg_catalog" ->> "json" ) = 'TypDef "U" 'Nothing '[  ]
   TTypDefSch ( "pg_catalog" ->> "jsonb" ) = 'TypDef "U" 'Nothing '[  ]
+  TTypDefSch ( "pg_catalog" ->> "numeric" ) = 'TypDef "N" 'Nothing '[  ]
   TTypDefSch ( "pg_catalog" ->> "text" ) = 'TypDef "S" 'Nothing '[  ]
   TTypDefSch ( "pg_catalog" ->> "time" ) = 'TypDef "D" 'Nothing '[  ]
   TTypDefSch ( "pg_catalog" ->> "timestamp" ) = 'TypDef "D" 'Nothing '[  ]
@@ -61,12 +58,13 @@
   TTypDefSch name = TE.TypeError (TE.Text "In schema " TE.:<>: TE.ShowType Sch TE.:$$: TE.Text "type " TE.:<>: TE.ShowType name TE.:<>: TE.Text " is not defined."
     TE.:$$: TE.Text ""
     TE.:$$: TE.Text "Valid values are:"
-    TE.:$$: TE.Text "  Types: pg_catalog._bool, pg_catalog._bytea, pg_catalog._date, pg_catalog._float8, pg_catalog._int4, pg_catalog._jsonb, pg_catalog._text, pg_catalog._timestamptz, pg_catalog._uuid, pg_catalog.bool, pg_catalog.bytea, pg_catalog.date, pg_catalog.float4, pg_catalog.float8, pg_catalog.int4, pg_catalog.int8, pg_catalog.json, pg_catalog.jsonb, pg_catalog.text, pg_catalog.time, pg_catalog.timestamp, pg_catalog.timestamptz, pg_catalog.uuid, public._citext, public.citext, test_pgs._color, test_pgs.color."
+    TE.:$$: TE.Text "  Types: pg_catalog._bool, pg_catalog._bytea, pg_catalog._date, pg_catalog._float8, pg_catalog._int4, pg_catalog._jsonb, pg_catalog._text, pg_catalog._timestamptz, pg_catalog._uuid, pg_catalog.bool, pg_catalog.bytea, pg_catalog.date, pg_catalog.float4, pg_catalog.float8, pg_catalog.int2, pg_catalog.int4, pg_catalog.int8, pg_catalog.json, pg_catalog.jsonb, pg_catalog.numeric, pg_catalog.text, pg_catalog.time, pg_catalog.timestamp, pg_catalog.timestamptz, pg_catalog.uuid, public._citext, public.citext, test_pgs._color, test_pgs.color."
     TE.:$$: TE.Text "")
 instance (ToStar (TTypDef Sch name), ToStar name) => CTypDef Sch name where
   type TTypDef Sch name = TTypDefSch name
 
 type family TTabDefSch (name :: NameNSK) :: TabDef' TL.Symbol where
+  TTabDefSch ( "test_pgs" ->> "aggr_nums" ) = 'TabDef '[ "id","grp","i2","i4","i8","n","f4","f8" ] '[ "id" ] '[  ]
   TTabDefSch ( "test_pgs" ->> "arrays" ) = 'TabDef '[ "id","root_id","dates_nullable","jsons" ] '[ "id" ] '[  ]
   TTabDefSch ( "test_pgs" ->> "base_arr_converts" ) = 'TabDef '[ "cboolean","cint4","cfloat8","ctimestamptz","ctext" ] '[  ] '[  ]
   TTabDefSch ( "test_pgs" ->> "base_converts" ) = 'TabDef '[ "cboolean","cint4","cfloat8","cdate","ctime","ctimestamp","ctimestamptz","ctext" ] '[  ] '[  ]
@@ -78,10 +76,11 @@
   TTabDefSch ( "test_pgs" ->> "mid2" ) = 'TabDef '[ "root_id","seq","kind","flag","priority","payload" ] '[ "root_id","seq" ] '[  ]
   TTabDefSch ( "test_pgs" ->> "nullable_uq_row" ) = 'TabDef '[ "id","code","suffix","name","note" ] '[ "id" ] '[ '[ "code","suffix" ] ]
   TTabDefSch ( "test_pgs" ->> "root" ) = 'TabDef '[ "id","code","grp","name","created_at","dim_a_id","dim_b_id" ] '[ "id" ] '[ '[ "code","grp" ] ]
+  TTabDefSch ( "test_pgs" ->> "tag_link" ) = 'TabDef '[ "owner_id","tag","note" ] '[ "owner_id","tag" ] '[  ]
   TTabDefSch name = TE.TypeError (TE.Text "In schema " TE.:<>: TE.ShowType Sch TE.:$$: TE.Text "table " TE.:<>: TE.ShowType name TE.:<>: TE.Text " is not defined."
     TE.:$$: TE.Text ""
     TE.:$$: TE.Text "Valid values are:"
-    TE.:$$: TE.Text "  Tables: test_pgs.arrays, test_pgs.base_arr_converts, test_pgs.base_converts, test_pgs.dim, test_pgs.ext_arr_converts, test_pgs.ext_converts, test_pgs.leaf, test_pgs.mid1, test_pgs.mid2, test_pgs.nullable_uq_row, test_pgs.root."
+    TE.:$$: TE.Text "  Tables: test_pgs.aggr_nums, test_pgs.arrays, test_pgs.base_arr_converts, test_pgs.base_converts, test_pgs.dim, test_pgs.ext_arr_converts, test_pgs.ext_converts, test_pgs.leaf, test_pgs.mid1, test_pgs.mid2, test_pgs.nullable_uq_row, test_pgs.root, test_pgs.tag_link."
     TE.:$$: TE.Text "")
 instance (ToStar (TTabDef Sch name), ToStar name) => CTabDef Sch name where
   type TTabDef Sch name = TTabDefSch name
@@ -105,6 +104,8 @@
   type TRelDef Sch ref = TRelDefSch ref
 
 type family TFromSch (tab :: NameNSK) :: [NameNSK] where
+  TFromSch ( "test_pgs" ->> "aggr_nums" ) = '[  ]
+
   TFromSch ( "test_pgs" ->> "arrays" ) = '[ ( "test_pgs" ->> "arrays_root_fk" ) ]
 
   TFromSch ( "test_pgs" ->> "base_arr_converts" ) = '[  ]
@@ -128,13 +129,17 @@
   TFromSch ( "test_pgs" ->> "root" ) = '[ ( "test_pgs" ->> "root_dim_a_fk" )
     ,( "test_pgs" ->> "root_dim_b_fk" ) ]
 
+  TFromSch ( "test_pgs" ->> "tag_link" ) = '[  ]
+
   TFromSch tab = TE.TypeError (TE.Text "In schema " TE.:<>: TE.ShowType Sch TE.:$$: TE.Text "TFrom for table " TE.:<>: TE.ShowType tab TE.:<>: TE.Text " is not defined."
     TE.:$$: TE.Text ""
     TE.:$$: TE.Text "Valid values are:"
-    TE.:$$: TE.Text "  Tables: test_pgs.arrays, test_pgs.base_arr_converts, test_pgs.base_converts, test_pgs.dim, test_pgs.ext_arr_converts, test_pgs.ext_converts, test_pgs.leaf, test_pgs.mid1, test_pgs.mid2, test_pgs.nullable_uq_row, test_pgs.root."
+    TE.:$$: TE.Text "  Tables: test_pgs.aggr_nums, test_pgs.arrays, test_pgs.base_arr_converts, test_pgs.base_converts, test_pgs.dim, test_pgs.ext_arr_converts, test_pgs.ext_converts, test_pgs.leaf, test_pgs.mid1, test_pgs.mid2, test_pgs.nullable_uq_row, test_pgs.root, test_pgs.tag_link."
     TE.:$$: TE.Text "")
 
 type family TToSch (tab :: NameNSK) :: [NameNSK] where
+  TToSch ( "test_pgs" ->> "aggr_nums" ) = '[  ]
+
   TToSch ( "test_pgs" ->> "arrays" ) = '[  ]
 
   TToSch ( "test_pgs" ->> "base_arr_converts" ) = '[  ]
@@ -159,16 +164,36 @@
   TToSch ( "test_pgs" ->> "root" ) = '[ ( "test_pgs" ->> "arrays_root_fk" )
     ,( "test_pgs" ->> "mid1_root_fk" ),( "test_pgs" ->> "mid2_root_fk" ) ]
 
+  TToSch ( "test_pgs" ->> "tag_link" ) = '[  ]
+
   TToSch tab = TE.TypeError (TE.Text "In schema " TE.:<>: TE.ShowType Sch TE.:$$: TE.Text "TTo for table " TE.:<>: TE.ShowType tab TE.:<>: TE.Text " is not defined."
     TE.:$$: TE.Text ""
     TE.:$$: TE.Text "Valid values are:"
-    TE.:$$: TE.Text "  Tables: test_pgs.arrays, test_pgs.base_arr_converts, test_pgs.base_converts, test_pgs.dim, test_pgs.ext_arr_converts, test_pgs.ext_converts, test_pgs.leaf, test_pgs.mid1, test_pgs.mid2, test_pgs.nullable_uq_row, test_pgs.root."
+    TE.:$$: TE.Text "  Tables: test_pgs.aggr_nums, test_pgs.arrays, test_pgs.base_arr_converts, test_pgs.base_converts, test_pgs.dim, test_pgs.ext_arr_converts, test_pgs.ext_converts, test_pgs.leaf, test_pgs.mid1, test_pgs.mid2, test_pgs.nullable_uq_row, test_pgs.root, test_pgs.tag_link."
     TE.:$$: TE.Text "")
 instance CTabRels Sch tab where
   type TFrom Sch tab = TFromSch tab
   type TTo Sch tab = TToSch tab
 
 type family TDBFieldInfoSch (t :: NameNSK) (f :: TL.Symbol) :: RecFieldK NameNSK where
+  TDBFieldInfoSch ( "test_pgs" ->> "aggr_nums" ) "f4" = 'RFPlain ('FldDef ( "pg_catalog" ->> "float4" ) 'False 'False)
+  TDBFieldInfoSch ( "test_pgs" ->> "aggr_nums" ) "f8" = 'RFPlain ('FldDef ( "pg_catalog" ->> "float8" ) 'True 'False)
+  TDBFieldInfoSch ( "test_pgs" ->> "aggr_nums" ) "grp" = 'RFPlain ('FldDef ( "pg_catalog" ->> "int4" ) 'False 'False)
+  TDBFieldInfoSch ( "test_pgs" ->> "aggr_nums" ) "i2" = 'RFPlain ('FldDef ( "pg_catalog" ->> "int2" ) 'False 'False)
+  TDBFieldInfoSch ( "test_pgs" ->> "aggr_nums" ) "i4" = 'RFPlain ('FldDef ( "pg_catalog" ->> "int4" ) 'True 'False)
+  TDBFieldInfoSch ( "test_pgs" ->> "aggr_nums" ) "i8" = 'RFPlain ('FldDef ( "pg_catalog" ->> "int8" ) 'False 'False)
+  TDBFieldInfoSch ( "test_pgs" ->> "aggr_nums" ) "id" = 'RFPlain ('FldDef ( "pg_catalog" ->> "int4" ) 'False 'True)
+  TDBFieldInfoSch ( "test_pgs" ->> "aggr_nums" ) "n" = 'RFPlain ('FldDef ( "pg_catalog" ->> "numeric" ) 'True 'False)
+  TDBFieldInfoSch ( "test_pgs" ->> "aggr_nums" ) f = TE.TypeError (TE.Text "In schema " TE.:<>: TE.ShowType Sch
+    TE.:$$: TE.Text "for table " TE.:<>: TE.ShowType ( "test_pgs" ->> "aggr_nums" )
+    TE.:$$: TE.Text "name " TE.:<>: TE.ShowType f TE.:<>: TE.Text " is not defined."
+    TE.:$$: TE.Text ""
+    TE.:$$: TE.Text "Valid values are:"
+    TE.:$$: TE.Text "  Fields: id, grp, i2, i4, i8, n, f4, f8."
+    TE.:$$: TE.Text "  Foreign key constraints: ."
+    TE.:$$: TE.Text ""
+    TE.:$$: TE.Text "Your source or target type or renamer is probably invalid."
+    TE.:$$: TE.Text "")
   TDBFieldInfoSch ( "test_pgs" ->> "arrays" ) "dates_nullable" = 'RFPlain ('FldDef ( "pg_catalog" ->> "_date" ) 'True 'False)
   TDBFieldInfoSch ( "test_pgs" ->> "arrays" ) "id" = 'RFPlain ('FldDef ( "pg_catalog" ->> "int4" ) 'False 'True)
   TDBFieldInfoSch ( "test_pgs" ->> "arrays" ) "jsons" = 'RFPlain ('FldDef ( "pg_catalog" ->> "_jsonb" ) 'True 'False)
@@ -183,7 +208,7 @@
     TE.:$$: TE.Text "  Fields: id, root_id, dates_nullable, jsons."
     TE.:$$: TE.Text "  Foreign key constraints: arrays_root_fk."
     TE.:$$: TE.Text ""
-    TE.:$$: TE.Text "Your source or target type or renaimer is probably invalid."
+    TE.:$$: TE.Text "Your source or target type or renamer is probably invalid."
     TE.:$$: TE.Text "")
   TDBFieldInfoSch ( "test_pgs" ->> "base_arr_converts" ) "cboolean" = 'RFPlain ('FldDef ( "pg_catalog" ->> "_bool" ) 'True 'False)
   TDBFieldInfoSch ( "test_pgs" ->> "base_arr_converts" ) "cfloat8" = 'RFPlain ('FldDef ( "pg_catalog" ->> "_float8" ) 'True 'False)
@@ -198,7 +223,7 @@
     TE.:$$: TE.Text "  Fields: cboolean, cint4, cfloat8, ctimestamptz, ctext."
     TE.:$$: TE.Text "  Foreign key constraints: ."
     TE.:$$: TE.Text ""
-    TE.:$$: TE.Text "Your source or target type or renaimer is probably invalid."
+    TE.:$$: TE.Text "Your source or target type or renamer is probably invalid."
     TE.:$$: TE.Text "")
   TDBFieldInfoSch ( "test_pgs" ->> "base_converts" ) "cboolean" = 'RFPlain ('FldDef ( "pg_catalog" ->> "bool" ) 'True 'False)
   TDBFieldInfoSch ( "test_pgs" ->> "base_converts" ) "cdate" = 'RFPlain ('FldDef ( "pg_catalog" ->> "date" ) 'True 'False)
@@ -216,7 +241,7 @@
     TE.:$$: TE.Text "  Fields: cboolean, cint4, cfloat8, cdate, ctime, ctimestamp, ctimestamptz, ctext."
     TE.:$$: TE.Text "  Foreign key constraints: ."
     TE.:$$: TE.Text ""
-    TE.:$$: TE.Text "Your source or target type or renaimer is probably invalid."
+    TE.:$$: TE.Text "Your source or target type or renamer is probably invalid."
     TE.:$$: TE.Text "")
   TDBFieldInfoSch ( "test_pgs" ->> "dim" ) "id" = 'RFPlain ('FldDef ( "pg_catalog" ->> "int4" ) 'False 'True)
   TDBFieldInfoSch ( "test_pgs" ->> "dim" ) "name" = 'RFPlain ('FldDef ( "pg_catalog" ->> "text" ) 'False 'False)
@@ -232,7 +257,7 @@
     TE.:$$: TE.Text "  Fields: id, name."
     TE.:$$: TE.Text "  Foreign key constraints: root_dim_a_fk, root_dim_b_fk."
     TE.:$$: TE.Text ""
-    TE.:$$: TE.Text "Your source or target type or renaimer is probably invalid."
+    TE.:$$: TE.Text "Your source or target type or renamer is probably invalid."
     TE.:$$: TE.Text "")
   TDBFieldInfoSch ( "test_pgs" ->> "ext_arr_converts" ) "cbytea" = 'RFPlain ('FldDef ( "pg_catalog" ->> "_bytea" ) 'True 'False)
   TDBFieldInfoSch ( "test_pgs" ->> "ext_arr_converts" ) "ccitext" = 'RFPlain ('FldDef ( "public" ->> "_citext" ) 'True 'False)
@@ -247,7 +272,7 @@
     TE.:$$: TE.Text "  Fields: ccitext, cbytea, cjsonb, cuuid, ccolor."
     TE.:$$: TE.Text "  Foreign key constraints: ."
     TE.:$$: TE.Text ""
-    TE.:$$: TE.Text "Your source or target type or renaimer is probably invalid."
+    TE.:$$: TE.Text "Your source or target type or renamer is probably invalid."
     TE.:$$: TE.Text "")
   TDBFieldInfoSch ( "test_pgs" ->> "ext_converts" ) "cbytea" = 'RFPlain ('FldDef ( "pg_catalog" ->> "bytea" ) 'True 'False)
   TDBFieldInfoSch ( "test_pgs" ->> "ext_converts" ) "ccitext" = 'RFPlain ('FldDef ( "public" ->> "citext" ) 'True 'False)
@@ -263,7 +288,7 @@
     TE.:$$: TE.Text "  Fields: ccitext, cbytea, cjsonb, cjson, cuuid, ccolor."
     TE.:$$: TE.Text "  Foreign key constraints: ."
     TE.:$$: TE.Text ""
-    TE.:$$: TE.Text "Your source or target type or renaimer is probably invalid."
+    TE.:$$: TE.Text "Your source or target type or renamer is probably invalid."
     TE.:$$: TE.Text "")
   TDBFieldInfoSch ( "test_pgs" ->> "leaf" ) "category" = 'RFPlain ('FldDef ( "pg_catalog" ->> "text" ) 'True 'False)
   TDBFieldInfoSch ( "test_pgs" ->> "leaf" ) "created_at" = 'RFPlain ('FldDef ( "pg_catalog" ->> "timestamptz" ) 'False 'True)
@@ -282,7 +307,7 @@
     TE.:$$: TE.Text "  Fields: root_id, seq, leaf_no, value, category, created_at."
     TE.:$$: TE.Text "  Foreign key constraints: leaf_mid2_fk."
     TE.:$$: TE.Text ""
-    TE.:$$: TE.Text "Your source or target type or renaimer is probably invalid."
+    TE.:$$: TE.Text "Your source or target type or renamer is probably invalid."
     TE.:$$: TE.Text "")
   TDBFieldInfoSch ( "test_pgs" ->> "mid1" ) "flag" = 'RFPlain ('FldDef ( "pg_catalog" ->> "bool" ) 'False 'False)
   TDBFieldInfoSch ( "test_pgs" ->> "mid1" ) "id" = 'RFPlain ('FldDef ( "pg_catalog" ->> "int4" ) 'False 'True)
@@ -300,7 +325,7 @@
     TE.:$$: TE.Text "  Fields: id, root_id, pos, flag, sort_key, payload."
     TE.:$$: TE.Text "  Foreign key constraints: mid1_root_fk."
     TE.:$$: TE.Text ""
-    TE.:$$: TE.Text "Your source or target type or renaimer is probably invalid."
+    TE.:$$: TE.Text "Your source or target type or renamer is probably invalid."
     TE.:$$: TE.Text "")
   TDBFieldInfoSch ( "test_pgs" ->> "mid2" ) "flag" = 'RFPlain ('FldDef ( "pg_catalog" ->> "bool" ) 'False 'False)
   TDBFieldInfoSch ( "test_pgs" ->> "mid2" ) "kind" = 'RFPlain ('FldDef ( "pg_catalog" ->> "text" ) 'False 'False)
@@ -321,7 +346,7 @@
     TE.:$$: TE.Text "  Fields: root_id, seq, kind, flag, priority, payload."
     TE.:$$: TE.Text "  Foreign key constraints: mid2_root_fk, leaf_mid2_fk."
     TE.:$$: TE.Text ""
-    TE.:$$: TE.Text "Your source or target type or renaimer is probably invalid."
+    TE.:$$: TE.Text "Your source or target type or renamer is probably invalid."
     TE.:$$: TE.Text "")
   TDBFieldInfoSch ( "test_pgs" ->> "nullable_uq_row" ) "code" = 'RFPlain ('FldDef ( "pg_catalog" ->> "text" ) 'False 'False)
   TDBFieldInfoSch ( "test_pgs" ->> "nullable_uq_row" ) "id" = 'RFPlain ('FldDef ( "pg_catalog" ->> "int4" ) 'False 'True)
@@ -336,7 +361,7 @@
     TE.:$$: TE.Text "  Fields: id, code, suffix, name, note."
     TE.:$$: TE.Text "  Foreign key constraints: ."
     TE.:$$: TE.Text ""
-    TE.:$$: TE.Text "Your source or target type or renaimer is probably invalid."
+    TE.:$$: TE.Text "Your source or target type or renamer is probably invalid."
     TE.:$$: TE.Text "")
   TDBFieldInfoSch ( "test_pgs" ->> "root" ) "code" = 'RFPlain ('FldDef ( "pg_catalog" ->> "text" ) 'False 'False)
   TDBFieldInfoSch ( "test_pgs" ->> "root" ) "created_at" = 'RFPlain ('FldDef ( "pg_catalog" ->> "timestamptz" ) 'False 'True)
@@ -363,8 +388,21 @@
     TE.:$$: TE.Text "  Fields: id, code, grp, name, created_at, dim_a_id, dim_b_id."
     TE.:$$: TE.Text "  Foreign key constraints: root_dim_a_fk, root_dim_b_fk, arrays_root_fk, mid1_root_fk, mid2_root_fk."
     TE.:$$: TE.Text ""
-    TE.:$$: TE.Text "Your source or target type or renaimer is probably invalid."
+    TE.:$$: TE.Text "Your source or target type or renamer is probably invalid."
     TE.:$$: TE.Text "")
+  TDBFieldInfoSch ( "test_pgs" ->> "tag_link" ) "note" = 'RFPlain ('FldDef ( "pg_catalog" ->> "text" ) 'True 'False)
+  TDBFieldInfoSch ( "test_pgs" ->> "tag_link" ) "owner_id" = 'RFPlain ('FldDef ( "pg_catalog" ->> "int4" ) 'False 'False)
+  TDBFieldInfoSch ( "test_pgs" ->> "tag_link" ) "tag" = 'RFPlain ('FldDef ( "pg_catalog" ->> "text" ) 'False 'False)
+  TDBFieldInfoSch ( "test_pgs" ->> "tag_link" ) f = TE.TypeError (TE.Text "In schema " TE.:<>: TE.ShowType Sch
+    TE.:$$: TE.Text "for table " TE.:<>: TE.ShowType ( "test_pgs" ->> "tag_link" )
+    TE.:$$: TE.Text "name " TE.:<>: TE.ShowType f TE.:<>: TE.Text " is not defined."
+    TE.:$$: TE.Text ""
+    TE.:$$: TE.Text "Valid values are:"
+    TE.:$$: TE.Text "  Fields: owner_id, tag, note."
+    TE.:$$: TE.Text "  Foreign key constraints: ."
+    TE.:$$: TE.Text ""
+    TE.:$$: TE.Text "Your source or target type or renamer is probably invalid."
+    TE.:$$: TE.Text "")
   TDBFieldInfoSch t f = TE.TypeError (TE.Text "In schema " TE.:<>: TE.ShowType Sch TE.:<>: TE.Text " the table " TE.:<>: TE.ShowType t TE.:<>: TE.Text " is not defined."
     TE.:$$: TE.Text "")
 
@@ -372,12 +410,13 @@
   type TDBFieldInfo Sch t f = TDBFieldInfoSch t f
 
 instance CSchema Sch where
-  type TTabs Sch = '[ ( "test_pgs" ->> "arrays" ),( "test_pgs" ->> "base_arr_converts" )
-    ,( "test_pgs" ->> "base_converts" )
-    ,( "test_pgs" ->> "dim" ),( "test_pgs" ->> "ext_arr_converts" )
-    ,( "test_pgs" ->> "ext_converts" ),( "test_pgs" ->> "leaf" )
-    ,( "test_pgs" ->> "mid1" ),( "test_pgs" ->> "mid2" )
-    ,( "test_pgs" ->> "nullable_uq_row" ),( "test_pgs" ->> "root" ) ]
+  type TTabs Sch = '[ ( "test_pgs" ->> "aggr_nums" )
+    ,( "test_pgs" ->> "arrays" ),( "test_pgs" ->> "base_arr_converts" )
+    ,( "test_pgs" ->> "base_converts" ),( "test_pgs" ->> "dim" )
+    ,( "test_pgs" ->> "ext_arr_converts" ),( "test_pgs" ->> "ext_converts" )
+    ,( "test_pgs" ->> "leaf" ),( "test_pgs" ->> "mid1" )
+    ,( "test_pgs" ->> "mid2" ),( "test_pgs" ->> "nullable_uq_row" )
+    ,( "test_pgs" ->> "root" ),( "test_pgs" ->> "tag_link" ) ]
 
   type TTypes Sch = '[ ( "pg_catalog" ->> "_bool" )
     ,( "pg_catalog" ->> "_bytea" ),( "pg_catalog" ->> "_date" )
@@ -386,10 +425,12 @@
     ,( "pg_catalog" ->> "_timestamptz" ),( "pg_catalog" ->> "_uuid" )
     ,( "pg_catalog" ->> "bool" ),( "pg_catalog" ->> "bytea" )
     ,( "pg_catalog" ->> "date" ),( "pg_catalog" ->> "float4" )
-    ,( "pg_catalog" ->> "float8" ),( "pg_catalog" ->> "int4" )
-    ,( "pg_catalog" ->> "int8" ),( "pg_catalog" ->> "json" )
-    ,( "pg_catalog" ->> "jsonb" ),( "pg_catalog" ->> "text" )
+    ,( "pg_catalog" ->> "float8" ),( "pg_catalog" ->> "int2" )
+    ,( "pg_catalog" ->> "int4" ),( "pg_catalog" ->> "int8" )
+    ,( "pg_catalog" ->> "json" ),( "pg_catalog" ->> "jsonb" )
+    ,( "pg_catalog" ->> "numeric" ),( "pg_catalog" ->> "text" )
     ,( "pg_catalog" ->> "time" ),( "pg_catalog" ->> "timestamp" )
     ,( "pg_catalog" ->> "timestamptz" ),( "pg_catalog" ->> "uuid" )
     ,( "public" ->> "_citext" ),( "public" ->> "citext" )
     ,( "test_pgs" ->> "_color" ),( "test_pgs" ->> "color" ) ]
+
diff --git a/test-pgs/Tests/AggregateErrors.hs b/test-pgs/Tests/AggregateErrors.hs
new file mode 100644
--- /dev/null
+++ b/test-pgs/Tests/AggregateErrors.hs
@@ -0,0 +1,95 @@
+{-# OPTIONS_GHC -fdefer-type-errors -Wno-deferred-type-errors #-}
+-- | Compile-time errors of aggregates whose Haskell type does not match
+-- the SQL result type of the aggregate function.
+--
+-- The module is compiled with @-fdefer-type-errors@, so each ill-typed
+-- definition throws 'TypeError' at runtime with the compile-time message.
+module Tests.AggregateErrors where
+
+import Control.Exception (TypeError(..), evaluate, try)
+import Data.Int
+import Data.List qualified as L
+import Data.Text qualified as T
+import Hedgehog
+import PgSchema.DML
+import Utils
+
+-- | Check that rendering the SELECT for @r@ fails with a type error
+-- containing all fragments.
+--
+-- The value is hidden behind a given equality so that the deferred error
+-- is thrown only inside 'try'.
+typeErrorWith :: [String] -> (forall u. u ~ () => Int) -> Property
+typeErrorWith fragments x = withTests 1 $ property do
+  res <- evalIO $ try @TypeError $ evaluate (x @())
+  case res of
+    Right _ -> do
+      footnote "expected a type error, but the value was evaluated"
+      failure
+    Left (TypeError msg) -> do
+      footnote msg
+      assert $ L.all (`L.isInfixOf` msg) fragments
+
+-- | @avg(int4)@ is @numeric@: 'Double' is rejected at compile time
+-- (postgresql-simple fails at runtime with @Incompatible@).
+prop_aggr_avg_int_double :: Property
+prop_aggr_avg_int_double = typeErrorWith
+  [ "Aggregate 'avg' over a field of type 'int4' returns SQL type 'numeric',"
+  , "but Haskell type Double is not compatible with it."
+  , "Use Scientific or Rational instead."
+  , "DB Field name: \"i4\"" ]
+  (T.length $ fst $ selectText (AnnSch "aggr_nums")
+    @("i4" := Aggr AAvg (Maybe Double)) qpEmpty)
+
+-- | @sum(int8)@ is @numeric@, not @int8@.
+prop_aggr_sum_int8_int64 :: Property
+prop_aggr_sum_int8_int64 = typeErrorWith
+  [ "Aggregate 'sum' over a field of type 'int8' returns SQL type 'numeric',"
+  , "but Haskell type Int64 is not compatible with it." ]
+  (T.length $ fst $ selectText (AnnSch "aggr_nums")
+    @("grp" := Int32 :. "i8" := Aggr' ASum Int64) qpEmpty)
+
+-- | @sum(int4)@ is @int8@, so 'Int32' is not enough.
+prop_aggr_sum_int4_int32 :: Property
+prop_aggr_sum_int4_int32 = typeErrorWith
+  [ "Aggregate 'sum' over a field of type 'int4' returns SQL type 'int8',"
+  , "but Haskell type Int32 is not compatible with it."
+  , "Use Int64, Scientific or Rational instead." ]
+  (T.length $ fst $ selectText (AnnSch "aggr_nums")
+    @("i4" := Aggr ASum (Maybe Int32)) qpEmpty)
+
+-- | @avg(numeric)@ is @numeric@.
+prop_aggr_avg_numeric_double :: Property
+prop_aggr_avg_numeric_double = typeErrorWith
+  [ "Aggregate 'avg' over a field of type 'numeric' returns SQL type 'numeric',"
+  , "but Haskell type Double is not compatible with it." ]
+  (T.length $ fst $ selectText (AnnSch "aggr_nums")
+    @("n" := Aggr AAvg (Maybe Double)) qpEmpty)
+
+-- | @sum@ over a text field.
+prop_aggr_sum_text :: Property
+prop_aggr_sum_text = typeErrorWith
+  [ "Aggregate 'sum' is not supported for fields of type 'text'" ]
+  (T.length $ fst $ selectText (AnnSch "root")
+    @("name" := Aggr ASum (Maybe Int64)) qpEmpty)
+
+-- | 'Aggr' (without GROUP BY) can be NULL, so it requires 'Maybe'.
+prop_aggr_without_maybe :: Property
+prop_aggr_without_maybe = typeErrorWith
+  [ "'Aggr' (except 'Aggr ACount') requires 'Maybe'" ]
+  (T.length $ fst $ selectText (AnnSch "aggr_nums")
+    @("i2" := Aggr ASum Int64) qpEmpty)
+
+-- | 'Aggr'' over a nullable field requires 'Maybe'.
+prop_aggr'_nullable_without_maybe :: Property
+prop_aggr'_nullable_without_maybe = typeErrorWith
+  [ "You have to use Maybe in 'Aggr'' for nullable fields" ]
+  (T.length $ fst $ selectText (AnnSch "aggr_nums")
+    @("grp" := Int32 :. "f8" := Aggr' AAvg Double) qpEmpty)
+
+-- | 'Aggr'' over a mandatory field must not be 'Maybe'.
+prop_aggr'_mandatory_with_maybe :: Property
+prop_aggr'_mandatory_with_maybe = typeErrorWith
+  [ "You can't use Maybe in 'Aggr'' for mandatory fields" ]
+  (T.length $ fst $ selectText (AnnSch "aggr_nums")
+    @("grp" := Int32 :. "f4" := Aggr' AMax (Maybe Double)) qpEmpty)
diff --git a/test-pgs/Tests/Aggregates.hs b/test-pgs/Tests/Aggregates.hs
--- a/test-pgs/Tests/Aggregates.hs
+++ b/test-pgs/Tests/Aggregates.hs
@@ -1,7 +1,10 @@
 {-# LANGUAGE BlockArguments #-}
 module Tests.Aggregates where
 
+import Control.Monad
+import Data.List qualified as L
 import Data.Pool as Pool
+import Data.Scientific
 import Data.Text as T
 import Database.PostgreSQL.Simple (Connection)
 import GHC.Int
@@ -25,3 +28,85 @@
     T.isInfixOf "min(t0.name)" sql === True
     T.isInfixOf "group by grp" sql === True
     T.isInfixOf ",name" sql === False
+
+
+type AggrNumsRow =
+  "grp" := Int32 :. "i2" := Int16 :. "i4" := Maybe Int32 :. "i8" := Int64
+  :. "n" := Maybe Scientific :. "f4" := Double :. "f8" := Maybe Double
+
+aggrNumsRows :: [AggrNumsRow]
+aggrNumsRows =
+  [ "grp" =: 1 :. "i2" =: 1 :. "i4" =: Just 10 :. "i8" =: 100
+    :. "n" =: Just 1.5 :. "f4" =: 0.5 :. "f8" =: Just 0.25
+  , "grp" =: 1 :. "i2" =: 2 :. "i4" =: Nothing :. "i8" =: 200
+    :. "n" =: Just 2.5 :. "f4" =: 1.5 :. "f8" =: Nothing
+  , "grp" =: 2 :. "i2" =: 3 :. "i4" =: Just 30 :. "i8" =: 300
+    :. "n" =: Nothing :. "f4" =: 4 :. "f8" =: Just 1 ]
+
+-- | Insert 'aggrNumsRows' into the empty @aggr_nums@ table and select @r@.
+selectAggrNums
+  :: forall r. Selectable (AnnSch "aggr_nums") r
+  => Pool Connection -> IO [r]
+selectAggrNums pool = withPool pool \conn -> do
+  void $ delByCond "aggr_nums" conn mempty
+  void $ insSch_ "aggr_nums" conn aggrNumsRows
+  fst <$> selSch "aggr_nums" conn qpEmpty
+
+-- | Haskell types of @sum@ follow its SQL result type:
+-- @sum(int2 | int4)@ is @int8@, @sum(int8 | numeric)@ is @numeric@,
+-- @sum(float4)@ is @float4@, @sum(float8)@ is @float8@.
+type SumsRow =
+  "cnt" := Aggr ACount Int64
+  :. "i2" := Aggr ASum (Maybe Int64)
+  :. "i4" := Aggr ASum (Maybe Int64)
+  :. "i8" := Aggr ASum (Maybe Scientific)
+  :. "n" := Aggr ASum (Maybe Rational)
+  :. "f4" := Aggr ASum (Maybe Double)
+  :. "f8" := Aggr ASum (Maybe Double)
+
+prop_aggr_sum_result_types :: Pool Connection -> Property
+prop_aggr_sum_result_types pool = withTests 1 $ property do
+  res <- evalIO $ selectAggrNums @SumsRow pool
+  res ===
+    [ "cnt" =: Aggr 3 :. "i2" =: Aggr (Just 6) :. "i4" =: Aggr (Just 40)
+      :. "i8" =: Aggr (Just 600) :. "n" =: Aggr (Just 4) :. "f4" =: Aggr (Just 6)
+      :. "f8" =: Aggr (Just 1.25) ]
+
+-- | Haskell types of @avg@ follow its SQL result type:
+-- @avg(int2 | int4 | int8 | numeric)@ is @numeric@, @avg(float4 | float8)@ is @float8@.
+type AvgsRow =
+  "i2" := Aggr AAvg (Maybe Rational)
+  :. "i4" := Aggr AAvg (Maybe Scientific)
+  :. "i8" := Aggr AAvg (Maybe Scientific)
+  :. "n" := Aggr AAvg (Maybe Scientific)
+  :. "f4" := Aggr AAvg (Maybe Double)
+  :. "f8" := Aggr AAvg (Maybe Double)
+
+prop_aggr_avg_result_types :: Pool Connection -> Property
+prop_aggr_avg_result_types pool = withTests 1 $ property do
+  res <- evalIO $ selectAggrNums @AvgsRow pool
+  res ===
+    [ "i2" =: Aggr (Just 2) :. "i4" =: Aggr (Just 20) :. "i8" =: Aggr (Just 200)
+      :. "n" =: Aggr (Just 2) :. "f4" =: Aggr (Just 2) :. "f8" =: Aggr (Just 0.625) ]
+
+-- | 'Aggr'' with GROUP BY: 'Maybe' exactly for nullable fields;
+-- @min@ / @max@ keep the field type.
+type GroupedRow =
+  "grp" := Int32
+  :. "i2" := Aggr' ASum Int64
+  :. "i4" := Aggr' ASum (Maybe Int64)
+  :. "i8" := Aggr' AAvg Scientific
+  :. "n" := Aggr' AMax (Maybe Scientific)
+  :. "f4" := Aggr' AMin Double
+  :. "f8" := Aggr' AAvg (Maybe Double)
+
+prop_aggr_grouped_result_types :: Pool Connection -> Property
+prop_aggr_grouped_result_types pool = withTests 1 $ property do
+  res <- evalIO $ selectAggrNums @GroupedRow pool
+  L.sortOn (\(PgTag g :. _) -> g) res ===
+    [ "grp" =: 1 :. "i2" =: Aggr' 3 :. "i4" =: Aggr' (Just 10)
+      :. "i8" =: Aggr' 150 :. "n" =: Aggr' (Just 2.5) :. "f4" =: Aggr' 0.5
+      :. "f8" =: Aggr' (Just 0.25)
+    , "grp" =: 2 :. "i2" =: Aggr' 3 :. "i4" =: Aggr' (Just 30)
+      :. "i8" =: Aggr' 300 :. "n" =: Aggr' Nothing :. "f4" =: Aggr' 4
+      :. "f8" =: Aggr' (Just 1) ]
diff --git a/test-pgs/Tests/Hierarchy.hs b/test-pgs/Tests/Hierarchy.hs
--- a/test-pgs/Tests/Hierarchy.hs
+++ b/test-pgs/Tests/Hierarchy.hs
@@ -62,8 +62,8 @@
   , leaf_mid2_rev_fk :: Mid2RecRev }
   deriving (Generic, Eq, Ord, Show)
   deriving anyclass GenDefault
--- >>> getRecordInfo @('Ann RenamerSch Sch (TS "leaf")) @LeafI
--- RecordInfo {tabName = NameNS {nnsNamespace = "test_pgs", nnsName = "leaf"}, fields = [FieldInfo {fieldName = "leaf_no", fieldDbName = "leaf_no", fieldKind = RFPlain (FldDef {fdType = NameNS {nnsNamespace = "pg_catalog", nnsName = "int4"}, fdNullable = False, fdHasDefault = False})},FieldInfo {fieldName = "value", fieldDbName = "value", fieldKind = RFPlain (FldDef {fdType = NameNS {nnsNamespace = "pg_catalog", nnsName = "float4"}, fdNullable = False, fdHasDefault = False})}]}
+-- >>> getRecordInfo @(AnnSch "leaf") @LeafI
+-- RecordInfo {tabName = NameNS {nnsNamespace = "test_pgs", nnsName = "leaf"}, fields = [FieldInfo {fieldName = "leafNo", fieldDbName = "leaf_no", fieldKind = RFPlain (FldDef {fdType = NameNS {nnsNamespace = "pg_catalog", nnsName = "int4"}, fdNullable = False, fdHasDefault = False})},FieldInfo {fieldName = "value", fieldDbName = "value", fieldKind = RFPlain (FldDef {fdType = NameNS {nnsNamespace = "pg_catalog", nnsName = "float4"}, fdNullable = False, fdHasDefault = False})}]}
 
 eqRoot :: RootRec -> RootRec -> Bool
 eqRoot (a1 :. b1 :. _) (a2 :. b2 :. _) = (a1, b1) == (a2, b2)
diff --git a/test-pgs/Tests/JsonNull.hs b/test-pgs/Tests/JsonNull.hs
new file mode 100644
--- /dev/null
+++ b/test-pgs/Tests/JsonNull.hs
@@ -0,0 +1,137 @@
+{-# LANGUAGE BlockArguments #-}
+{-# LANGUAGE DeriveAnyClass #-}
+-- | Tree DML ('insertJSON', 'upsertJSON', 'updateJSON') must store 'Nothing'
+-- for a nullable @json@ / @jsonb@ column as SQL @NULL@ (not the JSON value
+-- @null@), the same as flat 'insertSch'.
+module Tests.JsonNull where
+
+import Data.Aeson (FromJSON, ToJSON, Value, object, (.=))
+import Data.Aeson qualified as A
+import Data.Functor
+import Data.Int
+import Data.List qualified as L
+import Data.Pool as Pool
+import Data.Text (Text)
+import Database.PostgreSQL.Simple
+import Database.PostgreSQL.Simple.FromField (FromField(..), fromJSONField)
+import GHC.Generics (Generic)
+import Hedgehog
+import PgSchema.DML
+import Utils
+
+
+data Note = Note { note :: Text }
+  deriving (Eq, Ord, Show, Generic, FromJSON, ToJSON)
+
+-- | Needed to read a root-level @jsonb@ column into 'Note'.
+instance FromField Note where
+  fromField = fromJSONField
+
+type RootRec =
+  "code" := Text :. "grp" := Int32 :. "name" := Text :. "someEmpty" := ()
+
+-- | @mid2@: primary key @(root_id, seq)@, @payload jsonb@ nullable.
+type Mid2In =
+  "seq" := Int32 :. "kind" := Text :. "flag" := Bool :. "priority" := Int32
+    :. "payload" := Maybe Value
+
+type Mid2Patch = "seq" := Int32 :. "payload" := Maybe Value
+
+mid2 :: Int32 -> Maybe Value -> Mid2In
+mid2 s p = "seq" =: s :. "kind" =: "k" :. "flag" =: True :. "priority" =: 1
+  :. "payload" =: p
+
+noteVal :: Text -> Value
+noteVal t = object ["note" .= t]
+
+-- | @(seq, payload IS NULL)@ for all @mid2@ rows of a root, by @seq@.
+mid2Nulls :: Connection -> Int32 -> IO [(Int32, Bool)]
+mid2Nulls conn rid = query conn
+  "select seq, payload is null from test_pgs.mid2 where root_id = ? order by seq"
+  (Only rid)
+
+prop_json_null_tree :: Pool Connection -> Property
+prop_json_null_tree pool = withTests 1 $ property do
+  ( nullsIns, nullCnt, selNotes, selVals, insSql
+    , nullsUps, nullsUpd, nullsUpdNull ) <- evalIO $ withPool pool \conn -> do
+    void $ delByCond "mid2" conn mempty
+    void $ delByCond "root" conn mempty
+    let
+      root :: RootRec
+      root = "code" =: "jnull" :. "grp" =: 1 :. "name" =: "n" :. "someEmpty" =: ()
+    -- insertJSON: Nothing / object / JSON null in child rows
+    (ret :: ["id" := Int32], insSql) <- insJSON "root" conn
+      [ root :. "mid2_root_fk" =:
+        [ mid2 1 Nothing, mid2 2 (Just $ noteVal "a"), mid2 3 (Just A.Null) ] ]
+    rid <- case ret of
+      [PgTag x] -> pure x
+      _ -> fail $ "unexpected insertJSON result: " <> show ret
+    nullsIns <- mid2Nulls conn rid
+    (nulls :: ["seq" := Int32], _) <- selSch "mid2" conn
+      $ qRoot $ qWhere $ pnull "payload"
+    -- SQL NULL is read back as Nothing (FromJSON of the record is not called)
+    (selNotes :: ["seq" := Int32 :. "payload" := Maybe Note], _) <-
+      selSch "mid2" conn $ qRoot $ qOrderBy [ascf "seq"]
+    (selVals :: ["seq" := Int32 :. "payload" := Maybe Value], _) <-
+      selSch "mid2" conn $ qRoot $ qOrderBy [ascf "seq"]
+    -- upsertJSON: ON CONFLICT ... DO UPDATE SET payload = EXCLUDED.payload
+    void $ upsJSON_ "root" conn
+      [ root :. "mid2_root_fk" =:
+        [ mid2 1 (Just $ noteVal "b"), mid2 2 Nothing, mid2 3 (Just A.Null) ] ]
+    nullsUps <- mid2Nulls conn rid
+    -- updateJSON: UPDATE ... SET payload = ...
+    void $ updJSON_ "root" conn
+      [ "id" =: rid :. "mid2_root_fk" =:
+        [ "seq" =: (1 :: Int32) :. "payload" =: Nothing :: Mid2Patch
+        , "seq" =: 2 :. "payload" =: Just (noteVal "c") ] ]
+    nullsUpd <- mid2Nulls conn rid
+    -- updateJSON: an explicit JSON null value is stored as SQL NULL too
+    void $ updJSON_ "root" conn
+      [ "id" =: rid :. "mid2_root_fk" =:
+        [ "seq" =: (2 :: Int32) :. "payload" =: Just A.Null :: Mid2Patch ] ]
+    nullsUpdNull <- mid2Nulls conn rid
+    pure ( nullsIns, L.length nulls, selNotes, selVals, insSql
+      , nullsUps, nullsUpd, nullsUpdNull )
+  annotate $ show insSql
+  nullsIns === [(1, True), (2, False), (3, True)]
+  nullCnt === 2
+  selNotes ===
+    [ "seq" =: 1 :. "payload" =: Nothing
+    , "seq" =: 2 :. "payload" =: Just (Note "a")
+    , "seq" =: 3 :. "payload" =: Nothing ]
+  selVals ===
+    [ "seq" =: 1 :. "payload" =: Nothing
+    , "seq" =: 2 :. "payload" =: Just (noteVal "a")
+    , "seq" =: 3 :. "payload" =: Nothing ]
+  nullsUps === [(1, False), (2, True), (3, True)]
+  nullsUpd === [(1, True), (2, False), (3, True)]
+  nullsUpdNull === [(1, True), (2, True), (3, True)]
+
+type JsonCols = "cjsonb" := Maybe Value :. "cjson" := Maybe Value
+
+jsonCols :: Maybe Value -> JsonCols
+jsonCols v = "cjsonb" =: v :. "cjson" =: v
+
+-- | @(cjsonb IS NULL, cjson IS NULL)@ for all @ext_converts@ rows.
+extNulls :: Connection -> IO [(Bool, Bool)]
+extNulls conn = L.sort <$> query_ conn
+  "select cjsonb is null, cjson is null from test_pgs.ext_converts"
+
+-- | Both @json@ and @jsonb@ columns; flat 'insertSch' for comparison.
+prop_json_null_json_and_jsonb :: Pool Connection -> Property
+prop_json_null_json_and_jsonb pool = withTests 1 $ property do
+  (viaJSON, viaJSONSel, viaFlat) <- evalIO $ withPool pool \conn -> do
+    void $ delByCond "ext_converts" conn mempty
+    void $ insJSON_ "ext_converts" conn
+      [jsonCols Nothing, jsonCols (Just $ noteVal "a"), jsonCols (Just A.Null)]
+    viaJSON <- extNulls conn
+    (sel :: [JsonCols], _) <- selSch "ext_converts" conn qpEmpty
+    void $ delByCond "ext_converts" conn mempty
+    -- flat insert keeps an explicit JSON null value as the JSON value null
+    void $ insSch_ "ext_converts" conn [jsonCols Nothing, jsonCols (Just A.Null)]
+    viaFlat <- extNulls conn
+    pure (viaJSON, sel, viaFlat)
+  viaJSON === [(False, False), (True, True), (True, True)]
+  L.sort viaJSONSel === L.sort
+    [jsonCols Nothing, jsonCols (Just $ noteVal "a"), jsonCols Nothing]
+  viaFlat === [(False, False), (True, True)]
diff --git a/test-pgs/Tests/KeyedDML.hs b/test-pgs/Tests/KeyedDML.hs
--- a/test-pgs/Tests/KeyedDML.hs
+++ b/test-pgs/Tests/KeyedDML.hs
@@ -10,6 +10,7 @@
 import Data.Pool as Pool
 import Data.Text (Text)
 import Data.Text qualified as T
+import Data.Time (Day, fromGregorian)
 import Database.PostgreSQL.Simple (Connection)
 import Hedgehog
 import Hedgehog.Gen qualified as Gen
@@ -63,6 +64,10 @@
 
 type Mid1KeyRet = "id" := Int32 :. "flag" := Bool
 
+type TagLinkKey = "ownerId" := Int32 :. "tag" := Text
+
+type TagLinkRow = "ownerId" := Int32 :. "tag" := Text :. "note" := Maybe Text
+
 expectAbsent :: Show a => [Maybe a] -> IO ()
 expectAbsent [Nothing] = pure ()
 expectAbsent xs = fail $ "expected [Nothing], got " <> show xs
@@ -105,6 +110,32 @@
       [_ :. _ :. n] -> when (unPgTag n /= name2) $ fail "DB name not updated"
       _ -> fail "expected one row"
 
+-- | All fields of the record belong to the key: there is nothing to update, but
+-- existing rows must be returned too (and left as is).
+prop_upsert_by_key_key_only_returns_all :: Pool Connection -> Property
+prop_upsert_by_key_key_only_returns_all pool = withTests 5 $ property do
+  owner <- forAll (Gen.int32 (Range.linear 1 100000))
+  evalIO $ Pool.withResource pool \conn -> do
+    void $ delByCond "tag_link" conn ("ownerId" =? owner)
+    let
+      seed :: TagLinkRow
+      seed = "ownerId" =: owner :. "tag" =: "a" :. "note" =: Just "kept"
+      keys = rowsOf @TagLinkKey [owner :. "a", owner :. "b"]
+      expected = [owner :. ("a" :. Just "kept"), owner :. ("b" :. Nothing)]
+    void $ insSch_ "tag_link" conn [seed]
+    (ret, sql) <- upsertByKey (AnnSch "tag_link") @TagLinkKey @TagLinkRow conn keys
+    expectUpsertSql sql
+    when (plains ret /= expected) $
+      fail $ "expected all rows returned, got " <> show ret <> "\nSQL: " <> T.unpack sql
+    (n, sql_) <- upsertByKey_ (AnnSch "tag_link") conn keys
+    expectUpsertSql sql_
+    when (n /= 0) $ fail $ "expected no changed rows, got " <> show n
+    (rows :: [TagLinkRow], _) <- selSch "tag_link" conn $ qRoot do
+      qWhere $ "ownerId" =? owner
+      qOrderBy [ascf "tag"]
+    when (plains rows /= expected) $
+      fail $ "expected rows left as is, got " <> show rows
+
 prop_upsert_by_key_composite_unique :: Pool Connection -> Property
 prop_upsert_by_key_composite_unique pool = withTests 5 $ property do
   code <- forAll (Gen.text (Range.linear 3 24) Gen.alphaNum)
@@ -304,3 +335,186 @@
         :. "sortKey" =: 1 :. "payload" =: Nothing
     (ret, _) <- updateByKey (AnnSch "mid1") @Mid1KeyPatch @Mid1KeyRet conn [patch]
     expectAbsent ret
+
+type RootMid1KeyPatch = "id" := Int32 :. "mid1_root_fk" := [Mid1KeyRet]
+
+type RootMid1UpdOut =
+  Maybe ("id" := Int32 :. "mid1_root_fk" := [Maybe ("id" := Int32 :. "flag" := Bool)])
+
+-- | Insert a root with one @mid1@ child; return ids of the root and the child.
+insertRootWithMid1 :: Connection -> Text -> Int32 -> IO (Int32, Int32)
+insertRootWithMid1 conn code grp = do
+  let
+    row :: RootRec
+    row = "code" =: code :. "grp" =: grp :. "name" =: "n" :. "someEmpty" =: ()
+  res <- insertJSON (AnnSch "root") @RootWithMid1 @RootInsWithMid conn
+    [ "mid1_root_fk" =: [ "flag" =: True :. "pos" =: 1 :. "sortKey" =: 1
+        :. "payload" =: Nothing ] :. row ]
+  case res of
+    ([PgTag rid :. PgTag [PgTag mid :. _]], _) -> pure (rid, mid)
+    _ -> fail "expected one root with one mid1"
+
+-- | A child that is not found by its key comes back as @Nothing@ (JSON @null@);
+-- the returning type must have @Maybe@ on child list elements.
+prop_update_json_missing_child :: Pool Connection -> Property
+prop_update_json_missing_child pool = withTests 5 $ property do
+  code <- forAll (Gen.text (Range.linear 3 16) Gen.alphaNum)
+  grp <- forAll (Gen.int32 (Range.linear 1 5000))
+  evalIO $ Pool.withResource pool \conn -> do
+    void $ delByCond "root" conn mempty
+    (rid, mid) <- insertRootWithMid1 conn code grp
+    let
+      patch :: RootMid1KeyPatch
+      patch = "id" =: rid :. "mid1_root_fk" =:
+        [ "id" =: mid :. "flag" =: False, "id" =: (mid + 99999) :. "flag" =: False ]
+    (ret, _) <- updateJSON (AnnSch "root") @RootMid1KeyPatch @RootMid1UpdOut conn [patch]
+    case ret of
+      [Just (PgTag rid' :. PgTag [Just (PgTag mid' :. PgTag False), Nothing])]
+        | rid' == rid && mid' == mid -> pure ()
+      _ -> fail $ "expected [Just (_ :. [Just _, Nothing])], got " <> show ret
+
+type Mid2Ins =
+  "seq" := Int32 :. "kind" := Text :. "flag" := Bool :. "priority" := Int32
+    :. "leaf_mid2_fk" := ["leaf_no" := Int32 :. "value" := Double]
+
+type RootMid2LeafPatch =
+  "id" := Int32 :. "mid2_root_fk" :=
+    ["seq" := Int32 :. "leaf_mid2_fk" := ["leaf_no" := Int32 :. "value" := Double]]
+
+type RootMid2LeafUpdOut =
+  Maybe ("id" := Int32 :. "mid2_root_fk" :=
+    [Maybe ("seq" := Int32 :. "leaf_mid2_fk" :=
+      [Maybe ("leaf_no" := Int32 :. "value" := Double)])])
+
+prop_update_json_missing_grandchild :: Pool Connection -> Property
+prop_update_json_missing_grandchild pool = withTests 5 $ property do
+  code <- forAll (Gen.text (Range.linear 3 16) Gen.alphaNum)
+  grp <- forAll (Gen.int32 (Range.linear 1 5000))
+  evalIO $ Pool.withResource pool \conn -> do
+    void $ delByCond "root" conn mempty
+    let
+      row :: RootRec
+      row = "code" =: code :. "grp" =: grp :. "name" =: "n" :. "someEmpty" =: ()
+      mid2 :: Mid2Ins
+      mid2 = "seq" =: 1 :. "kind" =: "k" :. "flag" =: True :. "priority" =: 1
+        :. "leaf_mid2_fk" =: ["leaf_no" =: 1 :. "value" =: 1]
+    rid <- insertJSON (AnnSch "root") @("mid2_root_fk" := [Mid2Ins] :. RootRec)
+      @("id" := Int32) conn ["mid2_root_fk" =: [mid2] :. row] >>= \case
+        ([PgTag rid], _) -> pure rid
+        _ -> fail "expected one root"
+    let
+      patch :: RootMid2LeafPatch
+      patch = "id" =: rid :. "mid2_root_fk" =:
+        [ "seq" =: 1 :. "leaf_mid2_fk" =:
+          ["leaf_no" =: 1 :. "value" =: 2, "leaf_no" =: 2 :. "value" =: 3]
+        , "seq" =: 2 :. "leaf_mid2_fk" =: ["leaf_no" =: 1 :. "value" =: 4] ]
+    (ret, _) <- updateJSON (AnnSch "root") @RootMid2LeafPatch @RootMid2LeafUpdOut
+      conn [patch]
+    case ret of
+      [Just (_ :. PgTag
+        [ Just (PgTag 1 :. PgTag [Just (PgTag 1 :. PgTag 2), Nothing])
+        , Nothing ])] -> pure ()
+      _ -> fail $ "unexpected updateJSON result: " <> show ret
+
+-- | Key-only child in 'upsertJSON' is updated (never inserted); a missing one is
+-- returned as @Nothing@.
+prop_upsert_json_key_only_missing_child :: Pool Connection -> Property
+prop_upsert_json_key_only_missing_child pool = withTests 5 $ property do
+  code <- forAll (Gen.text (Range.linear 3 16) Gen.alphaNum)
+  grp <- forAll (Gen.int32 (Range.linear 1 5000))
+  evalIO $ Pool.withResource pool \conn -> do
+    void $ delByCond "root" conn mempty
+    (rid, mid) <- insertRootWithMid1 conn code grp
+    let
+      patch :: RootMid1KeyPatch
+      patch = "id" =: rid :. "mid1_root_fk" =:
+        [ "id" =: mid :. "flag" =: False, "id" =: (mid + 99999) :. "flag" =: False ]
+    (ret, _) <- upsertJSON (AnnSch "root") @RootMid1KeyPatch @RootMid1UpdOut conn [patch]
+    case ret of
+      [Just (PgTag rid' :. PgTag [Just (PgTag mid' :. PgTag False), Nothing])]
+        | rid' == rid && mid' == mid -> pure ()
+      _ -> fail $ "expected [Just (_ :. [Just _, Nothing])], got " <> show ret
+
+type ArrDates = "dates_nullable" := Maybe (PgArr Day)
+
+type RootArrIns = "arrays_root_fk" := [ArrDates] :. RootRec
+
+type RootArrInsOut = "id" := Int32 :. "arrays_root_fk" := ["id" := Int32]
+
+-- | Key-only patch of @arrays@ children: the parent FK @root_id@ is outside the
+-- key @id@, so the child is upserted with @ON CONFLICT DO NOTHING@.
+type RootArrKeyPatch = "id" := Int32 :. "arrays_root_fk" := ["id" := Int32]
+
+-- | Returning a column that is not in the input: it is read from the table.
+type RootArrUpsOut =
+  Maybe ("id" := Int32 :. "arrays_root_fk" := [Maybe ("id" := Int32 :. ArrDates)])
+
+-- | Returning only columns from the input.
+type RootArrUpsOutKey =
+  Maybe ("id" := Int32 :. "arrays_root_fk" := [Maybe ("id" := Int32)])
+
+-- | Insert roots A and B with one @arrays@ child each; return
+-- @(rootA, childA, rootB, childB)@.
+insertRootsWithArrays :: Connection -> Text -> IO (Int32, Int32, Int32, Int32)
+insertRootsWithArrays conn code = do
+  let
+    root :: Int32 -> Day -> RootArrIns
+    root grp d = "arrays_root_fk" =: ["dates_nullable" =: Just (pgArr' [d])]
+      :. "code" =: code :. "grp" =: grp :. "name" =: "n" :. "someEmpty" =: ()
+  res <- insertJSON (AnnSch "root") @RootArrIns @RootArrInsOut conn
+    [root 1 dayA, root 2 dayB]
+  case res of
+    ( [ PgTag ra :. PgTag [PgTag ca], PgTag rb :. PgTag [PgTag cb] ], _ ) ->
+      pure (ra, ca, rb, cb)
+    _ -> fail $ "expected two roots with one child each, got " <> show (fst res)
+
+dayA, dayB :: Day
+dayA = fromGregorian 2020 1 1
+dayB = fromGregorian 2021 2 2
+
+-- | @ON CONFLICT DO NOTHING@ child whose key belongs to another parent is not
+-- found under this parent: @Nothing@, not a row of nulls.
+prop_upsert_json_do_nothing_other_parent :: Pool Connection -> Property
+prop_upsert_json_do_nothing_other_parent pool = withTests 3 $ property do
+  code <- forAll (Gen.text (Range.linear 3 16) Gen.alphaNum)
+  evalIO $ Pool.withResource pool \conn -> do
+    void $ delByCond "root" conn mempty
+    (_, ca, rb, cb) <- insertRootsWithArrays conn code
+    let
+      patch :: RootArrKeyPatch
+      patch = "id" =: rb :. "arrays_root_fk" =: ["id" =: cb, "id" =: ca]
+    (ret, _) <- upsertJSON (AnnSch "root") @RootArrKeyPatch @RootArrUpsOut conn [patch]
+    case ret of
+      [Just (PgTag rb' :. PgTag [Just (PgTag cb' :. PgTag (Just ds)), Nothing])]
+        | rb' == rb && cb' == cb && unPgArr' ds == [dayB] -> pure ()
+      _ -> fail $ "expected [Just (_ :. [Just _, Nothing])], got " <> show ret
+    (ret', _) <- upsertJSON (AnnSch "root") @RootArrKeyPatch @RootArrUpsOutKey conn [patch]
+    case ret' of
+      [Just (_ :. PgTag [Just (PgTag cb'), Nothing])] | cb' == cb -> pure ()
+      _ -> fail $ "expected [Just (_ :. [Just _, Nothing])], got " <> show ret'
+    -- the child of root A is not moved to root B
+    (rows :: ["id" := Int32 :. "root_id" := Maybe Int32], _) <-
+      selSch "arrays" conn $ qRoot $ qWhere $ "id" =? ca
+    case rows of
+      [_ :. PgTag rootId] | rootId /= Just rb -> pure ()
+      _ -> fail $ "unexpected arrays row: " <> show rows
+
+-- | @ON CONFLICT DO NOTHING@: a new child is inserted, an existing one under
+-- this parent is returned.
+prop_upsert_json_do_nothing_insert_or_found :: Pool Connection -> Property
+prop_upsert_json_do_nothing_insert_or_found pool = withTests 3 $ property do
+  code <- forAll (Gen.text (Range.linear 3 16) Gen.alphaNum)
+  evalIO $ Pool.withResource pool \conn -> do
+    void $ delByCond "root" conn mempty
+    (_, ca, rb, cb) <- insertRootsWithArrays conn code
+    let
+      newId = max ca cb + 1000
+      patch :: RootArrKeyPatch
+      patch = "id" =: rb :. "arrays_root_fk" =: ["id" =: newId, "id" =: cb]
+    (ret, _) <- upsertJSON (AnnSch "root") @RootArrKeyPatch @RootArrUpsOut conn [patch]
+    case ret of
+      [Just (_ :. PgTag
+        [ Just (PgTag n :. PgTag Nothing)
+        , Just (PgTag cb' :. PgTag (Just ds)) ])]
+        | n == newId && cb' == cb && unPgArr' ds == [dayB] -> pure ()
+      _ -> fail $ "unexpected upsertJSON result: " <> show ret
diff --git a/test-pgs/Tests/Named.hs b/test-pgs/Tests/Named.hs
new file mode 100644
--- /dev/null
+++ b/test-pgs/Tests/Named.hs
@@ -0,0 +1,110 @@
+{-# LANGUAGE BlockArguments #-}
+{-# LANGUAGE DeriveGeneric #-}
+-- | Rows built with 'named' (names given once for the whole list)
+-- and with 'rowsOf' / 'plains' (names taken from the type).
+module Tests.Named where
+
+import Control.Monad
+import Data.CaseInsensitive
+import Data.Int
+import Data.List qualified as L
+import Data.Pool as Pool
+import Data.Text as T
+import Database.PostgreSQL.Simple
+import GHC.Generics (Generic)
+import Hedgehog as H
+import Prelude as P
+import PgSchema.DML
+import Sch
+import Utils
+
+
+type ExtRow = "ccolor" := Maybe (EnumPGS "color") :. "ccitext" := Maybe (CI Text)
+
+-- | Enum constructors, 'Nothing' etc. are used as is, without 'PgTag'.
+-- Result must be the same as for rows built with '(=:)'.
+prop_named_insert :: Pool Connection -> Property
+prop_named_insert pool = withTests 1 $ property do
+  let
+    expected :: [ExtRow]
+    expected =
+      [ "ccolor" =: Just Color_red :. "ccitext" =: Just "A"
+      , "ccolor" =: Just Color_blue :. "ccitext" =: Nothing
+      , "ccolor" =: Nothing :. "ccitext" =: Just "c" ]
+  (outIns, outSel) <- evalIO $ withPool pool \conn -> do
+    void $ delByCond "ext_converts" conn mempty
+    (outIns', _) <- insSch "ext_converts" conn $ named ["ccolor", "ccitext"]
+      [ Just (Color_red :: EnumPGS "color") :. Just ("A" :: CI Text)
+      , Just Color_blue :. Nothing
+      , Nothing :. Just "c" ]
+    (outSel', _) <- selSch "ext_converts" conn qpEmpty
+    pure (outIns', outSel')
+  outIns === expected
+  L.sort outSel === L.sort expected
+
+-- | Nested rows: a list of children is just another 'named' call.
+prop_named_insert_tree :: Pool Connection -> Property
+prop_named_insert_tree pool = withTests 1 $ property do
+  let
+    mids pos0 = named ["pos", "flag", "sortKey"]
+      [ pos0 :. True :. 1, (pos0 + 1 :: Int32) :. False :. (2 :: Int32) ]
+  (outIns, outSel) <- evalIO $ withPool pool \conn -> do
+    void $ delByCond "mid1" conn mempty
+    void $ delByCond "root" conn mempty
+    (outIns' :: ["code" := Text :. "mid1RootFk" := ["pos" := Int32]], _) <-
+      insJSON "root" conn $ named ["code", "grp", "name", "mid1RootFk"]
+        [ ("r1" :: Text) :. (1 :: Int32) :. ("first" :: Text) :. mids 10
+        , "r2" :. 2 :. "second" :. mids 20 ]
+    (outSel', _) <- selSch "root" conn qpEmpty
+    pure (outIns', outSel')
+  outIns ===
+    [ "code" =: "r1" :. "mid1RootFk" =: ["pos" =: 10, "pos" =: 11]
+    , "code" =: "r2" :. "mid1RootFk" =: ["pos" =: 20, "pos" =: 21] ]
+  L.sort outSel ===
+    [ "code" =: ("r1" :: Text) :. "grp" =: (1 :: Int32)
+      :. "mid1RootFk" =: L.sort ["pos" =: (10 :: Int32) :. "flag" =: True, "pos" =: 11 :. "flag" =: False]
+    , "code" =: "r2" :. "grp" =: 2
+      :. "mid1RootFk" =: L.sort ["pos" =: 20 :. "flag" =: True, "pos" =: 21 :. "flag" =: False] ]
+
+type RootN = "code" := Text :. "grp" := Int32 :. "name" := Text
+
+type Mid1N = "pos" := Int32 :. "flag" := Bool :. "sortKey" := Int32
+
+-- | Generic record as a part of a row: its fields are flattened.
+data RootG = RootG { code :: Text, grp :: Int32 }
+  deriving (Eq, Ord, Show, Generic)
+
+-- | 'rowsOf': names and types are taken from the type; no parentheses are
+-- needed for groups (RootN), Generic records are flattened, children are plain.
+-- 'plains': returned and selected rows (child with parent) as plain values;
+-- the type of the result is given only as @plains \@T@.
+prop_rows_of_tree :: Pool Connection -> Property
+prop_rows_of_tree pool = withTests 1 $ property do
+  (outIns, outSel) <- evalIO $ withPool pool \conn -> do
+    void $ delByCond "mid1" conn mempty
+    void $ delByCond "root" conn mempty
+    outIns' <- plains @(RootG :. "mid1RootFk" := ["pos" := Int32]) . fst
+      <$> insJSON "root" conn (rowsOf @(RootN :. "mid1RootFk" := [Mid1N])
+        [ "r1" :. 1 :. "first" :. [10 :. True :. 1, 11 :. False :. 2]
+        , "r2" :. 2 :. "second" :. [20 :. True :. 3] ])
+    outSel' <- plains @(Mid1N :. "mid1RootFk" := (RootG :. "name" := Text)) . fst
+      <$> selSch "mid1" conn qpEmpty
+    pure (outIns', outSel')
+  outIns ===
+    [ "r1" :. 1 :. [10, 11]
+    , "r2" :. 2 :. [20] ]
+  L.sort outSel ===
+    [ 10 :. True :. 1 :. ("r1" :. 1 :. "first")
+    , 11 :. False :. 2 :. ("r1" :. 1 :. "first")
+    , 20 :. True :. 3 :. ("r2" :. 2 :. "second") ]
+
+-- | 'rowsOf' with a Generic record (in the inserted and in the expected rows).
+prop_rows_of_generic :: Pool Connection -> Property
+prop_rows_of_generic pool = withTests 1 $ property do
+  outSel <- evalIO $ withPool pool \conn -> do
+    void $ delByCond "mid1" conn mempty
+    void $ delByCond "root" conn mempty
+    void $ insJSON_ "root" conn $ rowsOf @(RootG :. "name" := Text :. "mid1RootFk" := [Mid1N])
+      [ "g1" :. 1 :. "first" :. [1 :. True :. 1] ]
+    fst <$> selSch "root" conn qpEmpty
+  outSel === rowsOf @(RootG :. "mid1RootFk" := [Mid1N]) [ "g1" :. 1 :. [1 :. True :. 1] ]
diff --git a/test-pgs/Tests/NamedErrors.hs b/test-pgs/Tests/NamedErrors.hs
new file mode 100644
--- /dev/null
+++ b/test-pgs/Tests/NamedErrors.hs
@@ -0,0 +1,52 @@
+{-# OPTIONS_GHC -fdefer-type-errors -Wno-deferred-type-errors #-}
+-- | Compile-time errors of 'named' and 'rowsOf'.
+--
+-- The module is compiled with @-fdefer-type-errors@, so each ill-typed
+-- definition throws 'TypeError' at runtime with the compile-time message.
+module Tests.NamedErrors where
+
+import Control.Exception (TypeError(..), evaluate, try)
+import Data.List qualified as L
+import Hedgehog
+import PgSchema.DML
+
+-- | Check that evaluating a value fails with a type error containing all fragments.
+--
+-- The value is hidden behind a given equality: deferred coercion evidence of
+-- 'named' is strict, so without it the error is thrown as soon as the
+-- property itself is evaluated (outside 'try').
+typeErrorWith :: [String] -> (forall u. u ~ () => Int) -> Property
+typeErrorWith fragments x = withTests 1 $ property do
+  res <- evalIO $ try @TypeError $ evaluate (x @())
+  case res of
+    Right _ -> do
+      footnote "expected a type error, but the value was evaluated"
+      failure
+    Left (TypeError msg) -> do
+      footnote msg
+      assert $ L.all (`L.isInfixOf` msg) fragments
+
+prop_named_empty :: Property
+prop_named_empty = typeErrorWith
+  [ "named: the list of field names is empty.", "The row: Bool" ]
+  (L.length $ named [] [True])
+
+prop_named_fewer_names :: Property
+prop_named_fewer_names = typeErrorWith
+  [ "named: there are fewer field names than fields in the row."
+  , "The last name \"b\" is given to more than one field: Bool :. Char" ]
+  (L.length $ named ["a", "b"] [(1 :: Int) :. True :. 'c'])
+
+prop_named_more_names :: Property
+prop_named_more_names = typeErrorWith
+  [ "named: there are more field names than fields in the row."
+  , "Field \"b\" gets the last field Bool"
+  , "Names without fields: [\"c\", \"d\"]" ]
+  (L.length $ named ["a", "b", "c", "d"] [(1 :: Int) :. True])
+
+-- | The same error as for 'Generic'-based rows in DML.
+prop_rows_of_not_product :: Property
+prop_rows_of_not_product = typeErrorWith
+  [ "Only Product types with fields are supported in pg-schema."
+  , "But I've got " ]
+  (L.length $ rowsOf @Ordering [])
diff --git a/test-pgs/Tests/PathErrors.hs b/test-pgs/Tests/PathErrors.hs
new file mode 100644
--- /dev/null
+++ b/test-pgs/Tests/PathErrors.hs
@@ -0,0 +1,84 @@
+{-# OPTIONS_GHC -fdefer-type-errors -Wno-deferred-type-errors #-}
+-- | Compile-time errors of 'qPath' / 'qPathFromHere' / 'qPathToHere'.
+--
+-- The module is compiled with @-fdefer-type-errors@, so each ill-typed
+-- definition throws 'TypeError' at runtime with the compile-time message.
+-- Each path ends with 'qWhere' so that the (deferred) path evidence is
+-- used when the condition's path is evaluated.
+module Tests.PathErrors where
+
+import Control.Exception (TypeError(..), evaluate, try)
+import Data.List qualified as L
+import Hedgehog
+import PgSchema.DML
+import Utils
+
+-- | Check that evaluating paths of conditions fails with a type error
+-- containing all fragments.
+typeErrorWith :: [String] -> QueryParamAnn (AnnSch tn) -> Property
+typeErrorWith fragments qp = withTests 1 $ property do
+  res <- evalIO $ try @TypeError $ evaluate
+    $ sum [ L.length (show p) | CondWithPath p _ <- qp.qpConds ]
+  case res of
+    Right _ -> do
+      footnote "expected a type error, but the value was evaluated"
+      failure
+    Left (TypeError msg) -> do
+      footnote msg
+      assert $ L.all (`L.isInfixOf` msg) fragments
+      assert $ not ("self-reference" `L.isInfixOf` msg)
+
+relNotDefined :: String -> String -> [String]
+relNotDefined tab rel =
+  [ "for table NameNS \"test_pgs\" \"" <> tab <> "\""
+  , "relation \"" <> rel <> "\""
+  , " is not defined." ]
+
+-- | Unknown relation in 'qPath' (used to report a self-reference error).
+prop_qpath_unknown_rel :: Property
+prop_qpath_unknown_rel = typeErrorWith
+  ( relNotDefined "root" "mid1_rot_fk"
+  <> [ "root_dim_a_fk, root_dim_b_fk"
+     , "arrays_root_fk, mid1_root_fk, mid2_root_fk" ] )
+  (qRoot $ qPath "mid1_rot_fk" here :: QueryParamAnn (AnnSch "root"))
+
+-- | Unknown relation in 'qPath' after applying the renamer.
+prop_qpath_unknown_rel_renamed :: Property
+prop_qpath_unknown_rel_renamed = typeErrorWith
+  ( relNotDefined "root" "mid1_rot_fk"
+  <> [ "(\"mid1RotFk\" after applying the renamer)" ] )
+  (qRoot $ qPath "mid1RotFk" here :: QueryParamAnn (AnnSch "root"))
+
+-- | Unknown relation in a nested 'qPath'.
+prop_qpath_unknown_rel_nested :: Property
+prop_qpath_unknown_rel_nested = typeErrorWith
+  (relNotDefined "mid2" "leaf_mid_fk" <> ["mid2_root_fk", "leaf_mid2_fk"])
+  ( qRoot $ qPath "mid2_root_fk" $ qPath "leaf_mid_fk" here
+    :: QueryParamAnn (AnnSch "root") )
+
+-- | Unknown relation in 'qPathFromHere'.
+prop_qpath_from_here_unknown_rel :: Property
+prop_qpath_from_here_unknown_rel = typeErrorWith
+  (relNotDefined "mid1" "mid1_rot_fk" <> ["mid1_root_fk", "<none>"])
+  (qRoot $ qPathFromHere "mid1_rot_fk" here :: QueryParamAnn (AnnSch "mid1"))
+
+-- | Unknown relation in 'qPathToHere'.
+prop_qpath_to_here_unknown_rel :: Property
+prop_qpath_to_here_unknown_rel = typeErrorWith
+  (relNotDefined "root" "mid1_rot_fk")
+  (qRoot $ qPathToHere "mid1_rot_fk" here :: QueryParamAnn (AnnSch "root"))
+
+-- | Existing relation used in the wrong direction.
+prop_qpath_from_here_wrong_dir :: Property
+prop_qpath_from_here_wrong_dir = typeErrorWith
+  [ "Relation is not available in from-here direction.", "\"mid1_root_fk\"" ]
+  (qRoot $ qPathFromHere "mid1_root_fk" here :: QueryParamAnn (AnnSch "root"))
+
+-- | Existing relation used in the wrong direction.
+prop_qpath_to_here_wrong_dir :: Property
+prop_qpath_to_here_wrong_dir = typeErrorWith
+  [ "Relation is not available in to-here direction.", "\"mid1_root_fk\"" ]
+  (qRoot $ qPathToHere "mid1_root_fk" here :: QueryParamAnn (AnnSch "mid1"))
+
+here :: forall ren sch t path. MonadQP ren sch t path
+here = qWhere mempty
diff --git a/test-pgs/Tests/ReturningErrors.hs b/test-pgs/Tests/ReturningErrors.hs
new file mode 100644
--- /dev/null
+++ b/test-pgs/Tests/ReturningErrors.hs
@@ -0,0 +1,195 @@
+{-# OPTIONS_GHC -fdefer-type-errors -Wno-deferred-type-errors #-}
+-- | Compile-time errors of the @RETURNING@ type of 'insertJSON' / 'upsertJSON' /
+-- 'updateJSON' ('ReturningMatchesInsert', 'ReturningMatchesUpsert',
+-- 'ReturningMatchesUpdate').
+--
+-- The module is compiled with @-fdefer-type-errors@, so an unsatisfied
+-- constraint becomes a thunk that throws 'TypeError' with the compile-time
+-- message. Evidence of a 'Constraint' is lazy and is never used at runtime, so
+-- the test builds a 'Dict' of the constraint and forces all its fields
+-- ('deepForce').
+module Tests.ReturningErrors where
+
+import Control.Exception (TypeError(..), evaluate, try)
+import Data.Int (Int32)
+import Data.Kind (Constraint)
+import Data.List qualified as L
+import Data.Text (Text)
+import GHC.Exts.Heap (Box(..), GenClosure(..), getClosureData)
+import Hedgehog
+import PgSchema.DML
+import Utils
+
+data Dict (c :: Constraint) where
+  Dict :: c => Dict c
+
+-- | Force a value and (up to some depth) all its constructor fields.
+-- Dictionaries of the checked constraints are nested constraint tuples, so
+-- this reaches the deferred 'TypeError' if there is one.
+deepForce :: Int -> a -> IO ()
+deepForce 0 _ = pure ()
+deepForce n x = do
+  _ <- evaluate x
+  c <- getClosureData x
+  case c of
+    ConstrClosure{ptrArgs} -> mapM_ (\(Box y) -> deepForce (n - 1) y) ptrArgs
+    _ -> pure ()
+
+-- | Check that the constraint is not satisfied: the message of the type error
+-- contains all fragments.
+typeErrorWith :: [String] -> Dict c -> Property
+typeErrorWith fragments d = withTests 1 $ property do
+  res <- evalIO $ try @TypeError $ deepForce 100 d
+  case res of
+    Right _ -> do
+      footnote "expected a type error, but the constraint is satisfied"
+      failure
+    Left (TypeError msg) -> do
+      footnote msg
+      assert $ L.all (`L.isInfixOf` msg) fragments
+
+-- | Check that the constraint is satisfied.
+noTypeError :: Dict c -> Property
+noTypeError d = withTests 1 $ property do
+  res <- evalIO $ try @TypeError $ deepForce 100 d
+  case res of
+    Right _ -> success
+    Left (TypeError msg) -> do
+      footnote msg
+      failure
+
+type RetInsert r r' = Dict (ReturningMatchesInsert (AnnSch "root") r r')
+type RetUpsert r r' = Dict (ReturningMatchesUpsert (AnnSch "root") r r')
+type RetUpdate r r' = Dict (ReturningMatchesUpdate (AnnSch "root") r r')
+
+mustBeMaybe :: [String]
+mustBeMaybe = ["Returning must use Maybe here"]
+
+mustNotBeMaybe :: [String]
+mustNotBeMaybe = ["Returning must not use Maybe here"]
+
+-- Rows of the test schema --------------------------------------------------
+
+type RootFull = "code" := Text :. "grp" := Int32 :. "name" := Text
+
+-- | Child @mid1@ with all mandatory columns (@root_id@ comes from the parent).
+type Mid1Full = "flag" := Bool :. "pos" := Int32 :. "sortKey" := Int32
+
+-- | Child @mid1@ with primary key only (plus one plain column).
+type Mid1Key = "id" := Int32 :. "flag" := Bool
+
+type Mid1Out = "id" := Int32 :. "flag" := Bool
+
+-- | Root key + key-only @mid1@ children.
+type RootMid1Key = "id" := Int32 :. "mid1_root_fk" := [Mid1Key]
+
+-- | Root key + @mid2@ children (key only) with @leaf@ grandchildren (key only).
+type RootMid2LeafKey =
+  "id" := Int32
+    :. "mid2_root_fk" :=
+      [ "seq" := Int32 :. "kind" := Text
+        :. "leaf_mid2_fk" := ["leaf_no" := Int32 :. "category" := Maybe Text] ]
+
+-- updateJSON ---------------------------------------------------------------
+
+-- | A child list after a plain column (the reported case).
+prop_update_child_bare :: Property
+prop_update_child_bare = typeErrorWith
+  (mustBeMaybe <> ["mid1_root_fk", "Got: (\"id\" := Int32) :. (\"flag\" := Bool)"])
+  (Dict :: RetUpdate RootMid1Key
+    (Maybe ("id" := Int32 :. "mid1_root_fk" := [Mid1Out])))
+
+-- | A child list as the first field of the returning row.
+prop_update_child_bare_first :: Property
+prop_update_child_bare_first = typeErrorWith (mustBeMaybe <> ["mid1_root_fk"])
+  (Dict :: RetUpdate RootMid1Key
+    (Maybe ("mid1_root_fk" := [Mid1Out] :. "id" := Int32)))
+
+-- | A bare child list after a correct (Maybe) one.
+prop_update_second_child_bare :: Property
+prop_update_second_child_bare = typeErrorWith (mustBeMaybe <> ["mid2_root_fk"])
+  (Dict :: RetUpdate
+    ( "id" := Int32 :. "mid1_root_fk" := [Mid1Key]
+      :. "mid2_root_fk" := ["seq" := Int32 :. "kind" := Text] )
+    (Maybe ("id" := Int32 :. "mid1_root_fk" := [Maybe Mid1Out]
+      :. "mid2_root_fk" := ["seq" := Int32])))
+
+-- | A bare grandchild list under a correct (Maybe) child list.
+prop_update_grandchild_bare :: Property
+prop_update_grandchild_bare = typeErrorWith
+  (mustBeMaybe <> ["leaf_mid2_fk", "[\"mid2_root_fk\"]"])
+  (Dict :: RetUpdate RootMid2LeafKey
+    (Maybe ("id" := Int32 :. "mid2_root_fk" :=
+      [Maybe ("seq" := Int32 :. "leaf_mid2_fk" := ["leaf_no" := Int32])])))
+
+-- | Child list as the first field (the element was checked as @PgTag ann t@,
+-- which is never @Maybe@).
+prop_update_child_first_ok :: Property
+prop_update_child_first_ok = noTypeError
+  (Dict :: RetUpdate RootMid1Key
+    (Maybe ("mid1_root_fk" := [Maybe Mid1Out] :. "id" := Int32)))
+
+prop_update_ok :: Property
+prop_update_ok = noTypeError
+  (Dict :: RetUpdate RootMid2LeafKey
+    (Maybe ("id" := Int32 :. "mid2_root_fk" :=
+      [Maybe ("seq" := Int32 :. "leaf_mid2_fk" := [Maybe ("leaf_no" := Int32)])])))
+
+-- insertJSON ---------------------------------------------------------------
+
+prop_insert_child_maybe :: Property
+prop_insert_child_maybe = typeErrorWith (mustNotBeMaybe <> ["mid1_root_fk"])
+  (Dict :: RetInsert ("mid1_root_fk" := [Mid1Full] :. RootFull)
+    ("id" := Int32 :. "mid1_root_fk" := [Maybe ("id" := Int32)]))
+
+prop_insert_ok :: Property
+prop_insert_ok = noTypeError
+  (Dict :: RetInsert ("mid1_root_fk" := [Mid1Full] :. RootFull)
+    ("id" := Int32 :. "mid1_root_fk" := ["id" := Int32 :. Mid1Full]))
+
+-- upsertJSON ---------------------------------------------------------------
+
+-- | Key-only child in the input: a missing child is returned as @null@, even if
+-- the returning row selects all mandatory columns.
+prop_upsert_key_only_child_bare :: Property
+prop_upsert_key_only_child_bare = typeErrorWith (mustBeMaybe <> ["mid1_root_fk"])
+  (Dict :: RetUpsert RootMid1Key
+    (Maybe ("id" := Int32 :. "mid1_root_fk" := ["id" := Int32 :. Mid1Full])))
+
+-- | Child with all mandatory columns in the input: it is always inserted or
+-- updated, even if the returning row selects only the key.
+prop_upsert_full_child_maybe :: Property
+prop_upsert_full_child_maybe = typeErrorWith (mustNotBeMaybe <> ["mid1_root_fk"])
+  (Dict :: RetUpsert ("id" := Int32 :. "mid1_root_fk" := [Mid1Full])
+    (Maybe ("id" := Int32 :. "mid1_root_fk" := [Maybe ("id" := Int32)])))
+
+-- | Key-only root in the input: a missing root is returned as @null@.
+prop_upsert_key_only_root_bare :: Property
+prop_upsert_key_only_root_bare = typeErrorWith
+  ["Upsert returning row must be wrapped in Maybe", "\"code\""]
+  (Dict :: RetUpsert ("id" := Int32 :. "name" := Text)
+    ("id" := Int32 :. "name" := Text))
+
+prop_upsert_ok :: Property
+prop_upsert_ok = noTypeError
+  (Dict :: RetUpsert RootMid1Key
+    (Maybe ("id" := Int32 :. "mid1_root_fk" := [Maybe ("id" := Int32 :. Mid1Full)])))
+
+prop_upsert_full_ok :: Property
+prop_upsert_full_ok = noTypeError
+  (Dict :: RetUpsert ("mid1_root_fk" := [Mid1Full] :. RootFull)
+    ("id" := Int32 :. "mid1_root_fk" := ["id" := Int32]))
+
+-- | Child input has only key columns and parent FK is outside the key:
+-- @ON CONFLICT DO NOTHING@ ('NeedsFkKeyOnlyMaybe').
+prop_upsert_do_nothing_child_bare :: Property
+prop_upsert_do_nothing_child_bare = typeErrorWith (mustBeMaybe <> ["arrays_root_fk"])
+  (Dict :: RetUpsert ("id" := Int32 :. "arrays_root_fk" := ["id" := Int32])
+    (Maybe ("id" := Int32 :. "arrays_root_fk" := ["id" := Int32])))
+
+-- | Child input has plain columns outside the key: @ON CONFLICT (key) DO UPDATE@
+-- always returns the row.
+prop_upsert_do_update_child_ok :: Property
+prop_upsert_do_update_child_ok = noTypeError
+  (Dict :: RetUpsert ("id" := Int32 :. "mid1_root_fk" := ["id" := Int32 :. Mid1Full])
+    (Maybe ("id" := Int32 :. "mid1_root_fk" := ["id" := Int32])))
