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 | 139x 139x 588x 15x 573x 5x 568x 157x 411x 436x 13x 423x 436x 3x 420x 1x 419x 411x 8x 1x 402x 419x 3x 416x 6x 410x 1x 409x | import type { DataType } from './abstract-data-type.ts';
import { WallClock } from './wall-clock.ts';
const NUMERIC = new Set(['INTEGER', 'SMALLINT', 'TINYINT', 'MEDIUMINT', 'FLOAT', 'REAL', 'DOUBLE']);
const wallClock = new WallClock();
/**
* Converts single composite fields between JavaScript values and field text.
*
* @internal
*/
export class CompositeFields {
/**
* Converts field text read from a record into the field's value.
*
* @param field - Field type.
* @param text - Field text, or `null` for NULL.
* @returns The value.
*/
fromText(field: DataType, text: string | null): unknown {
if (text === null) {
return null;
}
if (field.parse !== undefined) {
return field.parse(text);
}
if (NUMERIC.has(field.key)) {
return Number(text);
}
return this.#byKey(field.key, text);
}
/**
* Converts a field value into field text.
*
* @param field - Field type.
* @param value - Value; `null` / `undefined` are NULL.
* @returns Field text, or `null` for NULL.
* @throws Error for array values (not supported inside composites).
*/
toText(field: DataType, value: unknown): string | null {
if (value === null || value === undefined) {
return null;
}
const converted = field.serialize === undefined ? value : field.serialize(value);
if (field.isJson === true) {
return JSON.stringify(value);
}
if (Array.isArray(converted)) {
throw new Error('Composite fields do not support array values');
}
return this.#text(field, converted);
}
#byKey(key: string, text: string): unknown {
switch (key) {
case 'BOOLEAN':
return text === 't';
case 'DATE':
return new Date(text);
case 'BLOB':
return Buffer.from(text.slice(2), 'hex');
default:
return key === 'JSON' || key === 'JSONB' ? JSON.parse(text) : text;
}
}
#text(field: DataType, value: unknown): string {
if (value instanceof Date) {
return field.key === 'TIMESTAMP' ? wallClock.format(value) : value.toISOString();
}
if (typeof value === 'boolean') {
return value ? 't' : 'f';
}
if (Buffer.isBuffer(value)) {
return `\\x${value.toString('hex')}`;
}
return typeof value === 'object' ? JSON.stringify(value) : String(value);
}
}
|