Skip to main content

PostgresRepository

@webda/postgres


Class: PostgresRepository<T>

Defined in: postgres/src/sqlstore.ts:86

PostgreSQL-backed repository for a single model class.

Stores every object as a JSONB data column alongside a uuid primary-key column. All CRUD operations hit the pg client; the inherited MemoryRepository serialize/deserialize helpers are reused for JSON to model-instance conversion.

Extends​

  • MemoryRepository<T>

Type Parameters​

T​

T extends ModelClass

Constructors​

Constructor​

new PostgresRepository<T>(model, pks, client, table, separator?, prepare?): PostgresRepository<T>

Defined in: postgres/src/sqlstore.ts:96

Create a new PostgresRepository.

Parameters​

model​

T

the model class

pks​

string[]

primary key field names

client​

SQLClient

the pg client or pool

table​

string

the table name

separator?​

string

composite key separator

prepare?​

() => Promise<void>

awaited before every statement (e.g. to ensure the table exists)

Returns​

PostgresRepository<T>

Overrides​

MemoryRepository<T>.constructor

Properties​

[WEBDA_TEST]​

[WEBDA_TEST]: object

Defined in: models/lib/repositories/memory.d.ts:258

Test utilities - clears all stored data

clear​

clear: () => Promise<void>

Returns​

Promise<void>

Inherited from​

MemoryRepository.[WEBDA_TEST]


client​

protected readonly client: SQLClient

Defined in: postgres/src/sqlstore.ts:99

the pg client or pool


events​

protected events: Map<keyof InstanceType<T>[typeof WEBDA_EVENTS], Set<(data) => void>>

Defined in: models/lib/repositories/abstract.d.ts:22

Registered event listeners keyed by event name

Inherited from​

MemoryRepository.events


maxListeners​

protected maxListeners: number

Defined in: models/lib/repositories/abstract.d.ts:111

Max-listeners hint kept for Node EventEmitter API compatibility. Not enforced — repositories use an unbounded Set per event.

Inherited from​

MemoryRepository.maxListeners


model​

protected model: T

Defined in: models/lib/repositories/abstract.d.ts:18

Inherited from​

MemoryRepository.model


pks​

protected pks: string[]

Defined in: models/lib/repositories/abstract.d.ts:19

Inherited from​

MemoryRepository.pks


prepare?​

protected readonly optional prepare?: () => Promise<void>

Defined in: postgres/src/sqlstore.ts:102

awaited before every statement (e.g. to ensure the table exists)

Returns​

Promise<void>


separator​

protected separator: string

Defined in: models/lib/repositories/abstract.d.ts:20

Inherited from​

MemoryRepository.separator


storage​

protected storage: Map

Defined in: models/lib/repositories/memory.d.ts:35

Inherited from​

MemoryRepository.storage


table​

protected readonly table: string

Defined in: postgres/src/sqlstore.ts:100

the table name

Methods​

__clean()​

__clean(): Promise<void>

Defined in: postgres/src/sqlstore.ts:458

Delete all rows from the table (used in tests).

Returns​

Promise<void>


buildClassFilter()​

protected buildClassFilter(): string

Defined in: models/lib/repositories/memory.d.ts:161

Build the WebdaQL class-filter clause __type IN ['A', 'B', ...] covering this.model's identifier and every transitive descendant.

Returns undefined when the model carries no Metadata.

Returns​

string

the class-filter WebdaQL clause, or undefined when no Metadata

Inherited from​

MemoryRepository.buildClassFilter


buildClassFilterIdentifiers()​

protected buildClassFilterIdentifiers(): string[]

Defined in: models/lib/repositories/memory.d.ts:152

Collect the WebdaQL class-filter identifier list — this.model's identifier and every transitive descendant carried in Metadata.Subclasses.

Returns undefined when the model carries no Metadata (plain unit-test classes that didn't go through Application.setModelMetadata). In that case query() skips the prepend and returns everything in storage, preserving the pre-fix behavior for those bare classes.

Returns​

string[]

the list of identifiers to match, or undefined when no Metadata

Inherited from​

MemoryRepository.buildClassFilterIdentifiers


buildItem()​

protected buildItem(data): InstanceType<T>

Defined in: models/lib/repositories/abstract.d.ts:41

Build the model instance to create from the incoming data

Primary key fields that are undefined or null are dropped from the data so a key generated by the model constructor (e.g. UuidModel) is not overwritten. Repositories must read the storage key from the returned instance.

Parameters​

data​

Helpers<InstanceType<T>>

the incoming data

Returns​

InstanceType<T>

the model instance

Inherited from​

MemoryRepository.buildItem


checkCondition()​

protected checkCondition<K>(item, conditionField?, condition?): void

Defined in: models/lib/repositories/memory.d.ts:62

Verify an optimistic locking condition on an item

Type Parameters​

K​

K extends string

Parameters​

item​

InstanceType<T>

The item to check

conditionField?​

K

Field to validate

condition?​

any

Expected value

Returns​

void

Throws​

Error if the condition does not match

Inherited from​

MemoryRepository.checkCondition


checkItemWriteCondition()​

protected checkItemWriteCondition(item, index, itemWriteConditionField, itemWriteCondition): void

Defined in: models/lib/repositories/memory.d.ts:250

Verify a write condition on a collection item

Parameters​

item​

any[]

The array to check

index​

number

Index of the item in the array

itemWriteConditionField​

string

Field name to check on the item

itemWriteCondition​

any

Expected value for the field

Returns​

void

Throws​

Error if the condition does not match

Inherited from​

MemoryRepository.checkItemWriteCondition


create()​

create(data, _save?): Promise<any>

Defined in: postgres/src/sqlstore.ts:200

Parameters​

data​

any

_save?​

boolean = true

Returns​

Promise<any>

Overrides​

MemoryRepository.create


delete()​

delete(primaryKey, conditionField?, condition?): Promise<void>

Defined in: postgres/src/sqlstore.ts:246

Parameters​

primaryKey​

any

conditionField?​

any

condition?​

any

Returns​

Promise<void>

Overrides​

MemoryRepository.delete


deleteItemFromCollection()​

deleteItemFromCollection(primaryKey, collection, index, itemWriteConditionField?, itemWriteCondition?): Promise<void>

Defined in: postgres/src/sqlstore.ts:343

Parameters​

primaryKey​

any

collection​

any

index​

number

itemWriteConditionField?​

any

itemWriteCondition?​

any

Returns​

Promise<void>

Overrides​

MemoryRepository.deleteItemFromCollection


deserialize()​

deserialize(item): InstanceType<T>

Defined in: models/lib/repositories/memory.d.ts:116

Unserialize the object from a string

Beyond restoring the concrete type via @webda/serialize's $serializer.type typeKey, this also surfaces the storage envelope's __type stamp on the in-memory instance as a NON-ENUMERABLE property. The non-enumerable bit keeps __type invisible to JSON.stringify and Object.keys (so API responses and re-serialize cycles are byte-identical for the model's own fields), while still being readable via direct property access — which is exactly how WebdaQL's filter eval reads it (ComparisonExpression.getAttributeValue walks obj[name]).

Backward-compat: legacy rows written before the envelope-stamping was introduced won't carry __type. In that case we backfill from the repository's own model.Metadata.Identifier so they look like records of the parent class — which is exactly what query()'s prepended class filter expects (parent + descendants). Plain unit-test classes without Metadata get no stamp at all; their repos opt out of class filtering on the query side too (see query).

Parameters​

item​

string

the serialized string

Returns​

InstanceType<T>

the deserialized model instance

Inherited from​

MemoryRepository.deserialize


duplicateExpression()​

duplicateExpression(expression): Expression

Defined in: postgres/src/sqlstore.ts:376

Duplicate and translate a WebdaQL expression into SQL-friendly JSONB path expressions.

Parameters​

expression​

Expression

the WebdaQL expression

Returns​

Expression

the translated expression


emit()​

emit<K>(event, data): Promise<void>

Defined in: models/lib/repositories/abstract.d.ts:136

Emit an event to all registered listeners and await their completion.

Type Parameters​

K​

K extends string | number | symbol

Parameters​

event​

K

The event name to emit

data​

InstanceType<T>[typeof WEBDA_EVENTS][K]

The event payload

Returns​

Promise<void>

Inherited from​

MemoryRepository.emit


excludePrimaryKey()​

excludePrimaryKey(object): any

Defined in: models/lib/repositories/abstract.d.ts:65

Parameters​

object​

any

Returns​

any

Inherited from​

MemoryRepository.excludePrimaryKey


execute()​

protected execute(q, values?): Promise<{ rowCount: number; rows: any[]; }>

Defined in: postgres/src/sqlstore.ts:134

Run a statement against the client once prepare has resolved.

Parameters​

q​

string

the SQL statement

values?​

any[]

the statement parameters

Returns​

Promise<{ rowCount: number; rows: any[]; }>

the raw pg query result


exists()​

exists(primaryKey): Promise<boolean>

Defined in: postgres/src/sqlstore.ts:262

Parameters​

primaryKey​

any

Returns​

Promise<boolean>

Overrides​

MemoryRepository.exists


findModelClass()​

protected findModelClass(identifier): any

Defined in: models/lib/repositories/memory.d.ts:132

Find the class to hydrate a row typed identifier: the repository model, one of its transitive subclasses, or the repository model for one of its ancestors

Parameters​

identifier​

string

model identifier

Returns​

any

the class, this.model when it carries no Metadata, or undefined when unrelated

Inherited from​

MemoryRepository.findModelClass


fromJSON()​

protected fromJSON(data): InstanceType<T>

Defined in: postgres/src/sqlstore.ts:179

Deserialize a raw JSON object from the database into a model instance.

Parameters​

data​

any

the raw JSON object from the JSONB column

Returns​

InstanceType<T>

the model instance


fromUID()​

fromUID(uid): ModelRefWithCreate<InstanceType<T>>

Defined in: models/lib/repositories/abstract.d.ts:47

Return a ref from the uuid

Parameters​

uid​

string

the serialized primary key

Returns​

ModelRefWithCreate<InstanceType<T>>

a model reference with create capability

Inherited from​

MemoryRepository.fromUID


get()​

get(primaryKey): Promise<any>

Defined in: postgres/src/sqlstore.ts:190

Parameters​

primaryKey​

any

Returns​

Promise<any>

Overrides​

MemoryRepository.get


getMaxListeners()​

getMaxListeners(): number

Defined in: models/lib/repositories/abstract.d.ts:124

EventEmitter-compatibility shim. Returns the max-listeners hint.

Returns​

number

the current max-listeners hint

Inherited from​

MemoryRepository.getMaxListeners


getPrimaryKey()​

Call Signature​

getPrimaryKey(object, forceObject?): PrimaryKeyType<InstanceType<T>>

Defined in: models/lib/repositories/abstract.d.ts:67

Get the primary key value for an object as a scalar or string.

Parameters​
object​

any

forceObject?​

false

Returns​

PrimaryKeyType<InstanceType<T>>

Inherited from​

MemoryRepository.getPrimaryKey

Call Signature​

getPrimaryKey(object, forceObject): PrimaryKey<InstanceType<T>>

Defined in: models/lib/repositories/abstract.d.ts:69

Get the primary key value for an object as a structured key object.

Parameters​
object​

any

forceObject​

true

Returns​

PrimaryKey<InstanceType<T>>

Inherited from​

MemoryRepository.getPrimaryKey


getQueryCondition()​

getQueryCondition(writeCondition, writeConditionField, params): string

Defined in: postgres/src/sqlstore.ts:155

Build a SQL WHERE sub-expression from a write-condition.

Parameters​

writeCondition​

any

the expected value

writeConditionField​

string

the field to check

params​

any[]

the existing params array (will be extended in place)

Returns​

string

the SQL AND clause


getRootModel()​

getRootModel(): T

Defined in: models/lib/repositories/abstract.d.ts:30

Returns​

T

Inherited from​

MemoryRepository.getRootModel


getSync()​

protected getSync(primaryKey): InstanceType<T>

Defined in: models/lib/repositories/memory.d.ts:50

Synchronous read used by conditional writes to keep check-and-set atomic

Parameters​

primaryKey​

string | PK<InstanceType<T>, InstanceType<T>[typeof WEBDA_PRIMARY_KEY][number]>

key of the item

Returns​

InstanceType<T>

the deserialized item

Inherited from​

MemoryRepository.getSync


getTable()​

getTable(): string

Defined in: postgres/src/sqlstore.ts:113

Internal

The backing table name for this repository's model.

Returns​

string

the table name Not part of the @webda/models Repository interface.


getUID()​

getUID(object): string

Defined in: models/lib/repositories/abstract.d.ts:71

Parameters​

object​

any

Returns​

string

Inherited from​

MemoryRepository.getUID


hydratePlainRow()​

protected hydratePlainRow(raw): InstanceType<T>

Defined in: models/lib/repositories/memory.d.ts:140

Hydrate a plain JSON row as an instance of the repository model (or of the transitive subclass named by its __type; an ancestor type hydrates as the repository model), the same way document stores hydrate their rows; a row typed as an unrelated model is refused

Parameters​

raw​

any

the parsed row

Returns​

InstanceType<T>

the model instance

Inherited from​

MemoryRepository.hydratePlainRow


incrementAttribute()​

incrementAttribute<K, L>(primaryKey, info, _conditionField?, _condition?): Promise<void>

Defined in: models/lib/repositories/abstract.d.ts:79

Type Parameters​

K​

K extends string

L​

L extends string

Parameters​

primaryKey​

PK<InstanceType<T>, InstanceType<T>[typeof WEBDA_PRIMARY_KEY][number]>

info​

L | { property: L; value?: number; }

_conditionField?​

K

_condition?​

any

Returns​

Promise<void>

Inherited from​

MemoryRepository.incrementAttribute


incrementAttributes()​

incrementAttributes(primaryKey, info, _conditionField?, _condition?): Promise<void>

Defined in: postgres/src/sqlstore.ts:287

Parameters​

primaryKey​

any

info​

any

_conditionField?​

any

_condition?​

any

Returns​

Promise<void>

Overrides​

MemoryRepository.incrementAttributes


isPlainRow()​

protected isPlainRow(raw): boolean

Defined in: models/lib/repositories/memory.d.ts:125

Whether a stored row is a plain JSON object without a serializer envelope

Rows written by earlier versions (e.g. a v3 FileStore folder or MemoryStore persistence file) store the object itself, its type in a top-level __type.

Parameters​

raw​

any

the parsed row

Returns​

boolean

true for a plain object row

Inherited from​

MemoryRepository.isPlainRow


iterate()​

iterate(queryStr): AsyncGenerator<InstanceType<T>, any, any>

Defined in: postgres/src/sqlstore.ts:440

— iterate via paginated SQL queries

Parameters​

queryStr​

string

Returns​

AsyncGenerator<InstanceType<T>, any, any>

Overrides​

MemoryRepository.iterate


listKeysOfModel()​

protected listKeysOfModel(ids?): string[]

Defined in: models/lib/repositories/memory.d.ts:200

List the storage keys that may belong to this model

A storage shared by several models holds foreign entries whose key shape can be invalid for this repository: they are skipped from the stored envelope __type before any parsing. Entries without a readable stamp (legacy rows, corrupted payloads) are kept so any error on them still surfaces.

Parameters​

ids?​

string[]

class identifiers (model and subclasses), undefined to keep everything

Returns​

string[]

the keys to evaluate

Inherited from​

MemoryRepository.listKeysOfModel


mapExpressionAttribute()​

mapExpressionAttribute(attribute): string

Defined in: postgres/src/sqlstore.ts:144

Map an expression attribute path array to a JSONB path expression.

Parameters​

attribute​

string[]

the attribute path

Returns​

string

the JSONB path expression


off()​

off<K>(event, listener): void

Defined in: models/lib/repositories/abstract.d.ts:106

Type Parameters​

K​

K extends string | number | symbol

Parameters​

event​

K

listener​

(data) => void

Returns​

void

Inherited from​

MemoryRepository.off


on()​

on<K>(event, listener): void

Defined in: models/lib/repositories/abstract.d.ts:102

Type Parameters​

K​

K extends string | number | symbol

Parameters​

event​

K

listener​

(data) => void

Returns​

void

Inherited from​

MemoryRepository.on


once()​

once<K>(event, listener): void

Defined in: models/lib/repositories/abstract.d.ts:104

Type Parameters​

K​

K extends string | number | symbol

Parameters​

event​

K

listener​

(data) => void

Returns​

void

Inherited from​

MemoryRepository.once


parseLegacyUID()​

protected parseLegacyUID(uid): PrimaryKey<InstanceType<T>>

Defined in: models/lib/repositories/abstract.d.ts:63

Parse a uid through the model's parseLegacyUID hook

Parameters​

uid​

string

the raw storage key

Returns​

PrimaryKey<InstanceType<T>>

a key whose string form is the raw uid, or undefined when the model does not recognise it

Inherited from​

MemoryRepository.parseLegacyUID


parseUID()​

parseUID(uid, forceObject?): PrimaryKeyType<InstanceType<T>> | PrimaryKey<InstanceType<T>>

Defined in: models/lib/repositories/abstract.d.ts:57

Parse a serialized primary key

A composite key that does not split into the primary key fields is offered to the model's optional static parseLegacyUID(uid) hook (see WEBDA_LEGACY_UID): the returned key keeps the raw uid as its string form so it addresses the legacy storage entry. Without a hook, or when the hook declines, the uid is rejected.

Parameters​

uid​

string

forceObject?​

boolean

Returns​

PrimaryKeyType<InstanceType<T>> | PrimaryKey<InstanceType<T>>

Inherited from​

MemoryRepository.parseUID


patch()​

patch(primaryKey, data, conditionField?, condition?): Promise<void>

Defined in: postgres/src/sqlstore.ts:232

Parameters​

primaryKey​

any

data​

any

conditionField?​

any

condition?​

any

Returns​

Promise<void>

Overrides​

MemoryRepository.patch


query()​

query(queryStr): Promise<{ continuationToken?: string; results: InstanceType<T>[]; }>

Defined in: postgres/src/sqlstore.ts:414

— use SQL WHERE clause instead of in-memory scan

Parameters​

queryStr​

string

Returns​

Promise<{ continuationToken?: string; results: InstanceType<T>[]; }>

Overrides​

MemoryRepository.query


ref()​

ref(key): ModelRefWithCreate<InstanceType<T>>

Defined in: models/lib/repositories/abstract.d.ts:77

Parameters​

key​

PK<InstanceType<T>, InstanceType<T>[typeof WEBDA_PRIMARY_KEY][number]>

Returns​

ModelRefWithCreate<InstanceType<T>>

Inherited from​

MemoryRepository.ref


removeAttribute()​

removeAttribute(primaryKey, attribute, conditionField?, condition?): Promise<void>

Defined in: postgres/src/sqlstore.ts:269

Parameters​

primaryKey​

any

attribute​

any

conditionField?​

any

condition?​

any

Returns​

Promise<void>

Overrides​

MemoryRepository.removeAttribute


removeListener()​

removeListener<K>(event, listener): void

Defined in: models/lib/repositories/abstract.d.ts:119

EventEmitter-compatibility alias for off. Consumers that treat a repository as a Node EventEmitter (e.g. @webda/runtime EventIterator) call removeListener.

Type Parameters​

K​

K extends string | number | symbol

Parameters​

event​

K

the event name

listener​

(data) => void

the listener to remove

Returns​

void

Inherited from​

MemoryRepository.removeListener


resolvePath()​

protected resolvePath(item, path): object

Defined in: models/lib/repositories/memory.d.ts:229

Resolve the parent object and last key of a dotted path, creating intermediate objects

Parameters​

item​

any

root object

path​

string

dotted path

Returns​

object

the holder and the last key

holder​

holder: any

key​

key: string

Inherited from​

MemoryRepository.resolvePath


serialize()​

serialize(item): string

Defined in: models/lib/repositories/memory.d.ts:92

Serialize the object to a string

This method is used to allow switching between different serialization methods

The serialized payload is also stamped with a top-level __type field carrying the concrete model identifier when available (item.constructor.Metadata?.Identifier). This lets query() and external storage backends filter results by class without re-instantiating every item — important when a single underlying storage map is shared across a model and its subclasses (the common case in production where each registered model owns its own MemoryRepository pointing at the same Map).

The stamp lives on the serializer envelope (sibling of value / $serializer), not inside value. deserialize() re-surfaces it on the reconstructed instance as a non-enumerable __type property so WebdaQL's filter eval can read it without it ever leaking into JSON.stringify or Object.keys output — keeping API responses and re-serialize cycles byte-identical for the model's own fields.

Models that don't carry Metadata (plain unit-test classes that don't go through Application.setModelMetadata) simply skip the stamp; the resulting payload is byte-identical to the previous implementation.

Parameters​

item​

InstanceType<T>

to serialize

Returns​

string

serialized object

Inherited from​

MemoryRepository.serialize


setAttribute()​

setAttribute<K, L>(primaryKey, attribute, value, conditionField?, condition?): Promise<void>

Defined in: models/lib/repositories/abstract.d.ts:75

Type Parameters​

K​

K extends string

L​

L extends string

Parameters​

primaryKey​

string | PK<InstanceType<T>, InstanceType<T>[typeof WEBDA_PRIMARY_KEY][number]>

attribute​

K

value​

_PropertyPathType<InstanceType<T>, K>

conditionField?​

L

condition?​

_PropertyPathType<InstanceType<T>, L> | JSONed<_PropertyPathType<InstanceType<T>, L>>

Returns​

Promise<void>

Inherited from​

MemoryRepository.setAttribute


setMaxListeners()​

setMaxListeners(n): this

Defined in: models/lib/repositories/abstract.d.ts:130

EventEmitter-compatibility shim. Records the max-listeners hint (no enforcement).

Parameters​

n​

number

the new hint value

Returns​

this

this for chaining

Inherited from​

MemoryRepository.setMaxListeners


setupTable()​

setupTable(): Promise<void>

Defined in: postgres/src/sqlstore.ts:122

Internal

Ensure the backing table for this repository's model exists. Owns the per-model DDL previously held by PostgresStore.checkTable(). Not part of the @webda/models Repository interface.

Returns​

Promise<void>


sqlQuery()​

protected sqlQuery(q, values?): Promise<{ rowCount: number; rows: any[]; }>

Defined in: postgres/src/sqlstore.ts:167

Run a raw SQL query and return typed results.

Parameters​

q​

string

the SQL query (WHERE clause or full query)

values?​

any[] = []

the query parameters

Returns​

Promise<{ rowCount: number; rows: any[]; }>

the raw pg query result


update()​

update(data, conditionField?, condition?): Promise<void>

Defined in: postgres/src/sqlstore.ts:218

Parameters​

data​

any

conditionField?​

any

condition?​

any

Returns​

Promise<void>

Overrides​

MemoryRepository.update


upsert()​

upsert(data): Promise<InstanceType<T>>

Defined in: models/lib/repositories/abstract.d.ts:73

Parameters​

data​

Helpers<InstanceType<T>>

Returns​

Promise<InstanceType<T>>

Inherited from​

MemoryRepository.upsert


upsertItemToCollection()​

upsertItemToCollection(primaryKey, collection, item, index?, itemWriteConditionField?, itemWriteCondition?): Promise<void>

Defined in: postgres/src/sqlstore.ts:309

Parameters​

primaryKey​

any

collection​

any

item​

any

index?​

number

itemWriteConditionField?​

any

itemWriteCondition?​

any

Returns​

Promise<void>

Overrides​

MemoryRepository.upsertItemToCollection


simulateFind()​

static simulateFind<T>(query, uuids, repository): Promise<{ continuationToken?: string; results: InstanceType<T>[]; }>

Defined in: models/lib/repositories/memory.d.ts:209

Allow to simulate a find on a list of uuids It is static to be reusable by other repository like FileRepository

Type Parameters​

T​

T extends ModelClass<Storable<any, any>>

Parameters​

query​

Query

the parsed query

uuids​

any[]

the list of UIDs to search

repository​

Repository<T>

the repository to fetch objects from

Returns​

Promise<{ continuationToken?: string; results: InstanceType<T>[]; }>

the query results with optional continuation token

Inherited from​

MemoryRepository.simulateFind