@knorm/postgres
Postgres plugin for Knorm that enables connecting to and running queries against PostgreSQL.
Installation
@knorm/postgres has a peer dependency on @knorm/knorm
Usage
Options
Option | Type | Default | Description |
---|---|---|---|
[name] | string | postgres | The name of the plugin, allows accessing the plugin instance via Knorm's plugin registry (Knorm.prototype.plugins ) |
[connection] | object | string | none | Passed directly to pg. However, connections can also be configured via environment variables |
Features
This plugin adds these postgres-specific features:
- automatically
JSON-stringify
ing alljson
andjsonb
fields before save (insert or update) - automatically validating all
string
fields withmaxLength: 255
limit
,offset
,returning
query options andilike
where option, via sql-bricks-postgres- updating multiple rows using a single query with
UPDATE FROM
, via sql-bricks-postgres - connection pooling, via pg
JSON patching
When updating json
and jsonb
fields, you may wish to only update part of the
JSON data instead of the whole object. You can partially update json fields via
the patch
option:
- set the option value to
true
to patch all the json and jsonb fields in the update data - set the option value to a string field-name to patch a single field in the update data
- set the option value to an array of field-names to patch a multiple fields in the update data
For example:
To patch multiple json
and jsonb
fields in an update:
To patch all json
and jsonb
fields contained in the update data:
note
Only basic json-patching is supported: only the first level of patching is supported. If a nested object is passed, the nested keys are replaced:
To patch nested objects, use jsonb_set instead in a raw-sql update:
Note that for plain json
fields, you have to cast to jsonb
and then cast the
result back to json
:. So assuming data
was a json
field, the update would
be: