Press n or j to go to the next uncovered block, b, p or k for the previous block.
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 | 131x 131x 3020x 3020x 3020x 1521x 1521x 65x 65x 65x 65x 65x 65x 65x 2x 63x 63x 63x 5x 63x 63x 63x 63x 359x 3x 63x 63x 62x 65x 65x 3020x 3020x 3020x 3020x 3020x 65x 65x 65x 82x 65x 65x 65x 65x | import type { QueryResult } from '../connection/connection-manager.ts';
import { OptimisticLockError } from '../errors/errors.ts';
import { SqlExpression } from '../expressions/expression.ts';
import type { InstanceLifecycleServices } from './instance-lifecycle-services.ts';
import type { InstanceLifecycle } from './instance-lifecycle.ts';
import type { InstanceState } from './instance-state.ts';
import type { ModelDefinition } from './model-definition.ts';
import type { AnyModel, MutableOptions, SaveOptions, Values } from './options.ts';
import type { ModelRuntime } from './runtime.ts';
/** @internal State of one `save` call. */
export type SaveContext = Readonly<{
/** Model class. */
model: object;
/** Model definition. */
definition: ModelDefinition;
/** Runtime of the model. */
runtime: ModelRuntime;
/** Instance state. */
state: InstanceState;
/** Options passed to hooks (which may change them). */
opts: MutableOptions;
/** Options as given. */
options: SaveOptions;
/** Whether the instance is inserted. */
isNew: boolean;
/** `fields` option. */
explicitFields: readonly string[] | undefined;
}>;
/**
* SQL step of `instance.save()`: INSERT of a new instance (with nested associations) or UPDATE of
* changed attributes with optimistic locking, then the returned row is applied to the instance.
*
* @internal
*/
export class InstanceWriter {
readonly #services: InstanceLifecycleServices;
readonly #lifecycle: InstanceLifecycle;
/**
* @param services - Collaborators.
* @param lifecycle - Row application.
*/
constructor(services: InstanceLifecycleServices, lifecycle: InstanceLifecycle) {
this.#services = services;
this.#lifecycle = lifecycle;
}
/**
* Inserts a new instance, saving `belongsTo` parents before and children after it.
*
* @param instance - Instance.
* @param context - Save state.
* @param now - Timestamp of the write.
* @returns Resolves when written.
*/
async insert(instance: AnyModel, context: SaveContext, now: Date): Promise<void> {
const { nested } = this.#services;
await nested.saveBelongsTo(instance, context.state.includes, context.options);
const result = await this.#insertRow(context, this.#insertValues(instance, context, now));
this.#lifecycle.applyRow(instance, context.definition, result.rows[0]);
await nested.saveChildren(instance, context.state.includes, context.options);
}
/**
* Updates the given attributes of a loaded instance (and its version).
*
* @param instance - Instance.
* @param context - Save state.
* @param fields - Attributes to write.
* @param now - Timestamp of the write.
* @returns Resolves when written.
* @throws OptimisticLockError when the version no longer matches.
*/
async update(
instance: AnyModel,
context: SaveContext,
fields: readonly string[],
now: Date,
): Promise<void> {
const { definition } = context;
const changes = this.#changes(instance, context, fields, now);
const previous = {
...(instance.dataValues as Values),
...(instance._previousDataValues as Values),
};
const where = this.#updateWhere(definition, previous);
const set = this.#updateSet(definition, previous, changes);
const result = await this.#updateRow(context, set, where);
if (definition.version !== undefined && result.rowCount === 0) {
throw new OptimisticLockError({ modelName: definition.name, values: set, where });
}
this.#applyUpdate(instance, definition, changes, set, result.rows[0]);
}
// v6 sends no RETURNING with an instance update: the instance keeps its in-memory values (`'08:30'`,
// not the normalised `'08:30:00'`; an encrypted column that a hook decrypted stays decrypted). Only
// a column written from an expression (`fn`, `literal`) and a generated column take the value PostgreSQL computed.
#applyUpdate(
instance: AnyModel,
definition: ModelDefinition,
changes: Values,
set: Values,
row: Readonly<Record<string, unknown>> | undefined,
): void {
const values = instance.dataValues as Values;
if (definition.version !== undefined) {
values[definition.version] = set[definition.version];
}
instance.isNewRecord = false;
InstanceWriter.#keepStamp(values, definition, changes);
const computed = row === undefined ? {} : this.#services.rows.parse(definition, row);
for (const name of Object.keys(computed)) {
if (changes[name] instanceof SqlExpression || definition.attributes.get(name)?.generated) {
values[name] = computed[name];
}
}
}
// the stamped `updatedAt` is not an assigned value, so the instance takes it from the written changes
static #keepStamp(values: Values, definition: ModelDefinition, changes: Values): void {
const { updatedAt } = definition;
if (updatedAt !== undefined && changes[updatedAt] instanceof Date) {
values[updatedAt] = changes[updatedAt];
}
}
#updateRow(
{ definition, options, runtime }: SaveContext,
set: Values,
where: Values,
): Promise<QueryResult> {
const { compiler, updates, columns } = this.#services;
return runtime.execute(
compiler.compile(
updates.build(definition, columns.setItems(definition, set), where, { returning: true }),
),
options,
);
}
#insertValues(instance: AnyModel, context: SaveContext, now: Date): Values {
const rules = this.#services.values;
const silent = context.opts['silent'] === true;
return rules.pick(
rules.withTimestamps(context.definition, instance.dataValues as Values, now, true, silent),
context.explicitFields,
);
}
#insertRow({ definition, options, runtime }: SaveContext, values: Values): Promise<QueryResult> {
const { compiler, inserts } = this.#services;
return runtime.execute(
compiler.compile(
inserts.build(definition, [values], {
returning: true,
...(options.overriding === undefined ? {} : { overriding: options.overriding }),
}),
),
options,
);
}
#changes(instance: AnyModel, context: SaveContext, fields: readonly string[], now: Date): Values {
const { version } = context.definition;
const current = instance.dataValues as Values;
return this.#services.values.withTimestamps(
context.definition,
Object.fromEntries(
fields.filter((name) => name !== version).map((name) => [name, current[name]]),
),
now,
false,
context.opts['silent'] === true,
);
}
#updateWhere(definition: ModelDefinition, previous: Values): Values {
const { version } = definition;
return {
...this.#services.columns.primaryKeyWhere(definition, previous),
...(version === undefined ? {} : { [version]: previous[version] }),
};
}
#updateSet(definition: ModelDefinition, previous: Values, changes: Values): Values {
const { version } = definition;
return version === undefined
? changes
: { ...changes, [version]: Number(previous[version] ?? 0) + 1 };
}
}
|