2
0
mirror of https://github.com/frappe/books.git synced 2024-12-23 19:39:07 +00:00
books/backend/database/core.ts

911 lines
24 KiB
TypeScript
Raw Normal View History

2022-03-23 06:16:13 +00:00
import {
CannotCommitError,
DatabaseError,
DuplicateEntryError,
LinkValidationError,
NotFoundError,
ValueError,
} from 'fyo/utils/errors';
import { knex, Knex } from 'knex';
import {
Field,
FieldTypeEnum,
RawValue,
Schema,
SchemaMap,
TargetField,
} from '../../schemas/types';
2022-03-31 07:33:58 +00:00
import { getRandomString, getValueMapFromList } from '../../utils';
import { DatabaseBase, GetAllOptions, QueryFilter } from '../../utils/db/types';
2022-03-31 07:18:32 +00:00
import { getDefaultMetaFieldValueMap, sqliteTypeMap, SYSTEM } from '../helpers';
import {
ColumnDiff,
FieldValueMap,
GetQueryBuilderOptions,
SingleValue,
} from './types';
2022-03-28 10:01:29 +00:00
/**
* # DatabaseCore
* This is the ORM, the DatabaseCore interface (function signatures) should be
* replicated by the frontend demuxes and all the backend muxes.
*
* ## Db Core Call Sequence
2022-03-28 10:01:29 +00:00
*
* 1. Init core: `const db = new DatabaseCore(dbPath)`.
* 2. Connect db: `db.connect()`. This will allow for raw queries to be executed.
* 3. Set schemas: `db.setSchemaMap(schemaMap)`. This will allow for ORM functions to be executed.
2022-03-28 10:01:29 +00:00
* 4. Migrate: `await db.migrate()`. This will create absent tables and update the tables' shape.
* 5. ORM function execution: `db.get(...)`, `db.insert(...)`, etc.
* 6. Close connection: `await db.close()`.
*
* Note: Meta values: created, modified, createdBy, modifiedBy are set by DatabaseCore
* only for schemas that are SingleValue. Else they have to be passed by the caller in
* the `fieldValueMap`.
2022-03-28 10:01:29 +00:00
*/
2022-03-31 07:18:32 +00:00
export default class DatabaseCore extends DatabaseBase {
2022-03-25 10:12:39 +00:00
knex?: Knex;
2022-03-23 06:16:13 +00:00
typeMap = sqliteTypeMap;
dbPath: string;
schemaMap: SchemaMap = {};
connectionParams: Knex.Config;
2022-03-23 06:16:13 +00:00
constructor(dbPath?: string) {
2022-03-31 07:18:32 +00:00
super();
this.dbPath = dbPath ?? ':memory:';
2022-03-23 06:16:13 +00:00
this.connectionParams = {
client: 'sqlite3',
connection: {
filename: this.dbPath,
},
pool: {
2022-03-25 10:12:39 +00:00
afterCreate(conn: { run: (query: string) => void }, done: () => void) {
2022-03-23 06:16:13 +00:00
conn.run('PRAGMA foreign_keys=ON');
done();
},
},
useNullAsDefault: true,
asyncStackTraces: process.env.NODE_ENV === 'development',
};
}
static async getCountryCode(dbPath: string): Promise<string> {
let countryCode = 'in';
const db = new DatabaseCore(dbPath);
db.connect();
let query: { value: string }[] = [];
try {
query = await db.knex!('SingleValue').where({
fieldname: 'countryCode',
parent: 'SystemSettings',
});
} catch {
// Database not inialized and no countryCode passed
}
if (query.length > 0) {
countryCode = query[0].value as string;
}
await db.close();
return countryCode;
}
setSchemaMap(schemaMap: SchemaMap) {
this.schemaMap = schemaMap;
}
2022-03-23 06:16:13 +00:00
connect() {
this.knex = knex(this.connectionParams);
this.knex.on('query-error', (error) => {
error.type = this.#getError(error);
2022-03-23 06:16:13 +00:00
});
}
2022-03-28 10:01:29 +00:00
async close() {
await this.knex!.destroy();
2022-03-23 06:16:13 +00:00
}
async commit() {
try {
2022-03-28 10:01:29 +00:00
await this.knex!.raw('commit');
} catch (err) {
2022-03-25 10:12:39 +00:00
const type = this.#getError(err as Error);
if (type !== CannotCommitError) {
throw err;
}
}
}
async migrate() {
for (const schemaName in this.schemaMap) {
const schema = this.schemaMap[schemaName] as Schema;
if (schema.isSingle) {
continue;
}
if (await this.#tableExists(schemaName)) {
await this.#alterTable(schemaName);
} else {
await this.#createTable(schemaName);
}
}
await this.commit();
await this.#initializeSingles();
}
async exists(schemaName: string, name?: string): Promise<boolean> {
const schema = this.schemaMap[schemaName] as Schema;
if (schema.isSingle) {
return this.#singleExists(schemaName);
}
let row = [];
try {
2022-03-25 10:12:39 +00:00
const qb = this.knex!(schemaName);
if (name !== undefined) {
qb.where({ name });
}
row = await qb.limit(1);
} catch (err) {
if (this.#getError(err as Error) !== NotFoundError) {
throw err;
}
}
return row.length > 0;
}
2022-03-31 07:18:32 +00:00
async insert(
schemaName: string,
fieldValueMap: FieldValueMap
): Promise<FieldValueMap> {
// insert parent
if (this.schemaMap[schemaName]!.isSingle) {
await this.#updateSingleValues(schemaName, fieldValueMap);
} else {
await this.#insertOne(schemaName, fieldValueMap);
}
// insert children
await this.#insertOrUpdateChildren(schemaName, fieldValueMap, false);
return fieldValueMap;
}
async get(
schemaName: string,
name: string = '',
fields?: string | string[]
): Promise<FieldValueMap> {
const schema = this.schemaMap[schemaName] as Schema;
if (!schema.isSingle && !name) {
throw new ValueError('name is mandatory');
}
/**
* If schema is single return all the values
* of the single type schema, in this case field
* is ignored.
*/
let fieldValueMap: FieldValueMap = {};
if (schema.isSingle) {
return await this.#getSingle(schemaName);
}
if (typeof fields === 'string') {
fields = [fields];
}
if (fields === undefined) {
fields = schema.fields.map((f) => f.fieldname);
}
/**
* Separate table fields and non table fields
*/
const allTableFields: TargetField[] = this.#getTableFields(schemaName);
const allTableFieldNames: string[] = allTableFields.map((f) => f.fieldname);
const tableFields: TargetField[] = allTableFields.filter((f) =>
fields!.includes(f.fieldname)
);
const nonTableFieldNames: string[] = fields.filter(
(f) => !allTableFieldNames.includes(f)
);
/**
* If schema is not single then return specific fields
* if child fields are selected, all child fields are returned.
*/
if (nonTableFieldNames.length) {
fieldValueMap =
(await this.#getOne(schemaName, name, nonTableFieldNames)) ?? {};
}
if (tableFields.length) {
await this.#loadChildren(fieldValueMap, tableFields);
}
return fieldValueMap;
}
async getAll(
schemaName: string,
options: GetAllOptions = {}
): Promise<FieldValueMap[]> {
const schema = this.schemaMap[schemaName] as Schema;
const hasCreated = !!schema.fields.find((f) => f.fieldname === 'created');
const {
fields = ['name', ...(schema.keywordFields ?? [])],
filters,
offset,
limit,
groupBy,
orderBy = hasCreated ? 'created' : undefined,
order = 'desc',
} = options;
return (await this.#getQueryBuilder(
schemaName,
typeof fields === 'string' ? [fields] : fields,
filters ?? {},
{
offset,
limit,
groupBy,
orderBy,
order,
}
)) as FieldValueMap[];
}
async getSingleValues(
...fieldnames: ({ fieldname: string; parent?: string } | string)[]
): Promise<SingleValue<RawValue>> {
const fieldnameList = fieldnames.map((fieldname) => {
if (typeof fieldname === 'string') {
return { fieldname };
}
return fieldname;
});
2022-03-25 10:12:39 +00:00
let builder = this.knex!('SingleValue');
builder = builder.where(fieldnameList[0]);
fieldnameList.slice(1).forEach(({ fieldname, parent }) => {
if (typeof parent === 'undefined') {
builder = builder.orWhere({ fieldname });
} else {
builder = builder.orWhere({ fieldname, parent });
}
});
let values: { fieldname: string; parent: string; value: RawValue }[] = [];
try {
values = await builder.select('fieldname', 'value', 'parent');
} catch (err) {
if (this.#getError(err as Error) === NotFoundError) {
return [];
}
throw err;
}
return values;
}
async rename(schemaName: string, oldName: string, newName: string) {
/**
* Rename is expensive mostly won't allow it.
* TODO: rename all links
* TODO: rename in childtables
*/
2022-03-25 10:12:39 +00:00
await this.knex!(schemaName)
.update({ name: newName })
.where('name', oldName);
await this.commit();
}
async update(schemaName: string, fieldValueMap: FieldValueMap) {
// update parent
if (this.schemaMap[schemaName]!.isSingle) {
await this.#updateSingleValues(schemaName, fieldValueMap);
} else {
await this.#updateOne(schemaName, fieldValueMap);
}
// insert or update children
await this.#insertOrUpdateChildren(schemaName, fieldValueMap, true);
}
async delete(schemaName: string, name: string) {
const schema = this.schemaMap[schemaName] as Schema;
if (schema.isSingle) {
await this.#deleteSingle(schemaName, name);
return;
}
await this.#deleteOne(schemaName, name);
// delete children
const tableFields = this.#getTableFields(schemaName);
for (const field of tableFields) {
await this.#deleteChildren(field.target, name);
}
}
async #tableExists(schemaName: string) {
2022-03-25 10:12:39 +00:00
return await this.knex!.schema.hasTable(schemaName);
2022-03-23 06:16:13 +00:00
}
async #singleExists(singleSchemaName: string) {
2022-03-25 10:12:39 +00:00
const res = await this.knex!('SingleValue')
.count('parent as count')
.where('parent', singleSchemaName)
.first();
2022-03-25 10:12:39 +00:00
return (res?.count ?? 0) > 0;
2022-03-23 06:16:13 +00:00
}
async #removeColumns(schemaName: string, targetColumns: string[]) {
// TODO: Implement this for sqlite
}
2022-03-23 06:16:13 +00:00
#getError(err: Error) {
let errorType = DatabaseError;
if (err.message.includes('SQLITE_ERROR: no such table')) {
errorType = NotFoundError;
}
if (err.message.includes('FOREIGN KEY')) {
errorType = LinkValidationError;
}
if (err.message.includes('SQLITE_ERROR: cannot commit')) {
errorType = CannotCommitError;
}
if (err.message.includes('SQLITE_CONSTRAINT: UNIQUE constraint failed:')) {
errorType = DuplicateEntryError;
}
return errorType;
}
2022-03-23 06:16:13 +00:00
async prestigeTheTable(schemaName: string, tableRows: FieldValueMap[]) {
const max = 200;
2022-03-23 06:16:13 +00:00
// Alter table hacx for sqlite in case of schema change.
const tempName = `__${schemaName}`;
2022-03-25 10:12:39 +00:00
await this.knex!.schema.dropTableIfExists(tempName);
2022-03-25 10:12:39 +00:00
await this.knex!.raw('PRAGMA foreign_keys=OFF');
await this.#createTable(schemaName, tempName);
if (tableRows.length > 200) {
const fi = Math.floor(tableRows.length / max);
for (let i = 0; i <= fi; i++) {
const rowSlice = tableRows.slice(i * max, i + 1 * max);
if (rowSlice.length === 0) {
break;
2022-03-23 06:16:13 +00:00
}
2022-03-25 10:12:39 +00:00
await this.knex!.batchInsert(tempName, rowSlice);
}
} else {
2022-03-25 10:12:39 +00:00
await this.knex!.batchInsert(tempName, tableRows);
}
2022-03-25 10:12:39 +00:00
await this.knex!.schema.dropTable(schemaName);
await this.knex!.schema.renameTable(tempName, schemaName);
await this.knex!.raw('PRAGMA foreign_keys=ON');
2022-03-23 06:16:13 +00:00
}
async #getTableColumns(schemaName: string): Promise<string[]> {
2022-03-28 10:01:29 +00:00
const info: FieldValueMap[] = await this.knex!.raw(
2022-03-25 10:12:39 +00:00
`PRAGMA table_info(${schemaName})`
);
return info.map((d) => d.name as string);
}
2022-03-23 06:16:13 +00:00
async #getForeignKeys(schemaName: string): Promise<string[]> {
2022-03-28 10:01:29 +00:00
const foreignKeyList: FieldValueMap[] = await this.knex!.raw(
`PRAGMA foreign_key_list(${schemaName})`
);
2022-03-25 10:12:39 +00:00
return foreignKeyList.map((d) => d.from as string);
}
2022-03-23 06:16:13 +00:00
#getQueryBuilder(
schemaName: string,
fields: string[],
filters: QueryFilter,
options: GetQueryBuilderOptions
): Knex.QueryBuilder {
2022-03-25 10:12:39 +00:00
const builder = this.knex!.select(fields).from(schemaName);
this.#applyFiltersToBuilder(builder, filters);
if (options.orderBy) {
builder.orderBy(options.orderBy, options.order);
2022-03-23 06:16:13 +00:00
}
if (options.groupBy) {
builder.groupBy(options.groupBy);
2022-03-23 06:16:13 +00:00
}
if (options.offset) {
builder.offset(options.offset);
2022-03-23 06:16:13 +00:00
}
if (options.limit) {
builder.limit(options.limit);
}
return builder;
}
#applyFiltersToBuilder(builder: Knex.QueryBuilder, filters: QueryFilter) {
// {"status": "Open"} => `status = "Open"`
// {"status": "Open", "name": ["like", "apple%"]}
// => `status="Open" and name like "apple%"
// {"date": [">=", "2017-09-09", "<=", "2017-11-01"]}
// => `date >= 2017-09-09 and date <= 2017-11-01`
const filtersArray = [];
for (const field in filters) {
const value = filters[field];
2022-04-14 06:43:58 +00:00
let operator: string | number = '=';
let comparisonValue = value as string | number | (string | number)[];
if (Array.isArray(value)) {
2022-04-14 06:43:58 +00:00
operator = value[0] as string;
comparisonValue = value[1] as string | number | (string | number)[];
operator = operator.toLowerCase();
if (operator === 'includes') {
operator = 'like';
}
2022-04-14 06:43:58 +00:00
if (
operator === 'like' &&
!(comparisonValue as (string | number)[]).includes('%')
) {
comparisonValue = `%${comparisonValue}%`;
}
}
filtersArray.push([field, operator, comparisonValue]);
if (Array.isArray(value) && value.length > 2) {
// multiple conditions
const operator = value[2];
const comparisonValue = value[3];
filtersArray.push([field, operator, comparisonValue]);
}
2022-03-23 06:16:13 +00:00
}
filtersArray.map((filter) => {
2022-04-14 06:43:58 +00:00
const field = filter[0] as string;
const operator = filter[1];
const comparisonValue = filter[2];
if (operator === '=') {
2022-04-14 06:43:58 +00:00
builder.where(field, comparisonValue);
} else {
2022-04-14 06:43:58 +00:00
builder.where(field, operator as string, comparisonValue as string);
}
});
2022-03-23 06:16:13 +00:00
}
async #getColumnDiff(schemaName: string): Promise<ColumnDiff> {
const tableColumns = await this.#getTableColumns(schemaName);
const validFields = this.schemaMap[schemaName]!.fields;
const diff: ColumnDiff = { added: [], removed: [] };
2022-03-23 06:16:13 +00:00
for (const field of validFields) {
2022-03-25 10:12:39 +00:00
const hasDbType = this.typeMap.hasOwnProperty(field.fieldtype);
if (!tableColumns.includes(field.fieldname) && hasDbType) {
2022-03-23 06:16:13 +00:00
diff.added.push(field);
}
}
const validFieldNames = validFields.map((field) => field.fieldname);
for (const column of tableColumns) {
if (!validFieldNames.includes(column)) {
diff.removed.push(column);
}
}
return diff;
}
2022-03-25 10:12:39 +00:00
async #getNewForeignKeys(schemaName: string): Promise<Field[]> {
const foreignKeys = await this.#getForeignKeys(schemaName);
const newForeignKeys: Field[] = [];
const schema = this.schemaMap[schemaName] as Schema;
for (const field of schema.fields) {
2022-03-23 06:16:13 +00:00
if (
field.fieldtype === 'Link' &&
!foreignKeys.includes(field.fieldname)
) {
newForeignKeys.push(field);
}
}
return newForeignKeys;
}
#buildColumnForTable(table: Knex.AlterTableBuilder, field: Field) {
if (field.fieldtype === FieldTypeEnum.Table) {
// In case columnType is "Table"
// childTable links are handled using the childTable's "parent" field
return;
2022-03-23 06:16:13 +00:00
}
const columnType = this.typeMap[field.fieldtype];
if (!columnType) {
2022-03-23 06:16:13 +00:00
return;
}
2022-03-25 10:12:39 +00:00
const column = table[columnType](
field.fieldname
) as Knex.SqlLiteColumnBuilder;
// primary key
if (field.fieldname === 'name') {
column.primary();
}
// iefault value
if (field.default !== undefined) {
column.defaultTo(field.default);
}
// required
2022-03-28 10:01:29 +00:00
if (field.required) {
column.notNullable();
}
// link
2022-03-28 10:01:29 +00:00
if (
field.fieldtype === FieldTypeEnum.Link &&
(field as TargetField).target
) {
const targetSchemaName = (field as TargetField).target as string;
const schema = this.schemaMap[targetSchemaName] as Schema;
table
.foreign(field.fieldname)
.references('name')
.inTable(schema.name)
.onUpdate('CASCADE')
.onDelete('RESTRICT');
}
2022-03-23 06:16:13 +00:00
}
async #alterTable(schemaName: string) {
// get columns
const diff: ColumnDiff = await this.#getColumnDiff(schemaName);
const newForeignKeys: Field[] = await this.#getNewForeignKeys(schemaName);
2022-03-25 10:12:39 +00:00
return this.knex!.schema.table(schemaName, (table) => {
if (diff.added.length) {
for (const field of diff.added) {
this.#buildColumnForTable(table, field);
}
2022-03-25 10:12:39 +00:00
}
2022-03-25 10:12:39 +00:00
if (diff.removed.length) {
this.#removeColumns(schemaName, diff.removed);
}
}).then(() => {
if (newForeignKeys.length) {
return this.#addForeignKeys(schemaName, newForeignKeys);
}
});
2022-03-23 06:16:13 +00:00
}
async #createTable(schemaName: string, tableName?: string) {
tableName ??= schemaName;
const fields = this.schemaMap[schemaName]!.fields;
return await this.#runCreateTableQuery(tableName, fields);
}
#runCreateTableQuery(schemaName: string, fields: Field[]) {
2022-03-25 10:12:39 +00:00
return this.knex!.schema.createTable(schemaName, (table) => {
for (const field of fields) {
this.#buildColumnForTable(table, field);
}
2022-03-23 06:16:13 +00:00
});
}
async #getNonExtantSingleValues(singleSchemaName: string) {
const existingFields = (
2022-03-25 10:12:39 +00:00
await this.knex!('SingleValue')
.where({ parent: singleSchemaName })
.select('fieldname')
).map(({ fieldname }) => fieldname);
2022-03-23 06:16:13 +00:00
return this.schemaMap[singleSchemaName]!.fields.map(
({ fieldname, default: value }) => ({
fieldname,
value: value as RawValue | undefined,
})
).filter(
({ fieldname, value }) =>
!existingFields.includes(fieldname) && value !== undefined
);
2022-03-23 06:16:13 +00:00
}
async #deleteOne(schemaName: string, name: string) {
return await this.knex!(schemaName).where('name', name).delete();
}
async #deleteSingle(schemaName: string, fieldname: string) {
return await this.knex!('SingleValue')
.where({ parent: schemaName, fieldname })
.delete();
2022-03-23 06:16:13 +00:00
}
#deleteChildren(schemaName: string, parentName: string) {
2022-03-25 10:12:39 +00:00
return this.knex!(schemaName).where('parent', parentName).delete();
}
#runDeleteOtherChildren(
field: TargetField,
parentName: string,
added: string[]
) {
2022-03-23 06:16:13 +00:00
// delete other children
2022-03-25 10:12:39 +00:00
return this.knex!(field.target)
.where('parent', parentName)
2022-03-23 06:16:13 +00:00
.andWhere('name', 'not in', added)
.delete();
}
#prepareChild(
parentSchemaName: string,
parentName: string,
child: FieldValueMap,
field: Field,
idx: number
) {
2022-03-23 06:16:13 +00:00
if (!child.name) {
child.name = getRandomString();
}
child.parent = parentName;
child.parentSchemaName = parentSchemaName;
child.parentFieldname = field.fieldname;
2022-03-23 06:16:13 +00:00
child.idx = idx;
}
async #addForeignKeys(schemaName: string, newForeignKeys: Field[]) {
2022-03-28 10:01:29 +00:00
await this.knex!.raw('PRAGMA foreign_keys=OFF');
await this.knex!.raw('BEGIN TRANSACTION');
2022-03-23 06:16:13 +00:00
const tempName = 'TEMP' + schemaName;
2022-03-23 06:16:13 +00:00
// create temp table
await this.#createTable(schemaName, tempName);
2022-03-23 06:16:13 +00:00
try {
// copy from old to new table
2022-03-25 10:12:39 +00:00
await this.knex!(tempName).insert(this.knex!.select().from(schemaName));
} catch (err) {
2022-03-28 10:01:29 +00:00
await this.knex!.raw('ROLLBACK');
await this.knex!.raw('PRAGMA foreign_keys=ON');
2022-03-23 06:16:13 +00:00
2022-03-25 10:12:39 +00:00
const rows = await this.knex!.select().from(schemaName);
await this.prestigeTheTable(schemaName, rows);
return;
2022-03-23 06:16:13 +00:00
}
// drop old table
2022-03-25 10:12:39 +00:00
await this.knex!.schema.dropTable(schemaName);
2022-03-23 06:16:13 +00:00
// rename new table
2022-03-25 10:12:39 +00:00
await this.knex!.schema.renameTable(tempName, schemaName);
2022-03-23 06:16:13 +00:00
2022-03-28 10:01:29 +00:00
await this.knex!.raw('COMMIT');
await this.knex!.raw('PRAGMA foreign_keys=ON');
2022-03-23 06:16:13 +00:00
}
async #loadChildren(
fieldValueMap: FieldValueMap,
tableFields: TargetField[]
) {
for (const field of tableFields) {
fieldValueMap[field.fieldname] = await this.getAll(field.target, {
fields: ['*'],
filters: { parent: fieldValueMap.name as string },
orderBy: 'idx',
order: 'asc',
});
}
2022-03-23 06:16:13 +00:00
}
async #getOne(schemaName: string, name: string, fields: string[]) {
2022-03-25 10:12:39 +00:00
const fieldValueMap: FieldValueMap = await this.knex!.select(fields)
.from(schemaName)
.where('name', name)
.first();
return fieldValueMap;
}
2022-03-23 06:16:13 +00:00
async #getSingle(schemaName: string): Promise<FieldValueMap> {
const values = await this.getAll('SingleValue', {
fields: ['fieldname', 'value'],
filters: { parent: schemaName },
orderBy: 'fieldname',
order: 'asc',
});
2022-03-23 06:16:13 +00:00
return getValueMapFromList(values, 'fieldname', 'value') as FieldValueMap;
}
2022-03-23 06:16:13 +00:00
#insertOne(schemaName: string, fieldValueMap: FieldValueMap) {
if (!fieldValueMap.name) {
fieldValueMap.name = getRandomString();
}
// Non Table Fields
const fields = this.schemaMap[schemaName]!.fields.filter(
(f) => f.fieldtype !== FieldTypeEnum.Table
);
const validMap: FieldValueMap = {};
for (const { fieldname } of fields) {
validMap[fieldname] = fieldValueMap[fieldname];
}
return this.knex!(schemaName).insert(validMap);
2022-03-23 06:16:13 +00:00
}
async #updateSingleValues(
singleSchemaName: string,
fieldValueMap: FieldValueMap
) {
const fields = this.schemaMap[singleSchemaName]!.fields;
for (const field of fields) {
const value = fieldValueMap[field.fieldname] as RawValue | undefined;
if (value === undefined) {
continue;
}
await this.#updateSingleValue(singleSchemaName, field.fieldname, value);
}
2022-03-23 06:16:13 +00:00
}
async #updateSingleValue(
singleSchemaName: string,
fieldname: string,
value: RawValue
) {
const names: { name: string }[] = await this.knex!('SingleValue')
.select('name')
.where({
parent: singleSchemaName,
fieldname,
});
const name = names?.[0]?.name as string | undefined;
if (name === undefined) {
this.#insertSingleValue(singleSchemaName, fieldname, value);
} else {
return await this.knex!('SingleValue').where({ name }).update({
value,
modifiedBy: SYSTEM,
modified: new Date().toISOString(),
});
}
}
async #insertSingleValue(
singleSchemaName: string,
fieldname: string,
value: RawValue
) {
const updateMap = getDefaultMetaFieldValueMap();
const fieldValueMap: FieldValueMap = Object.assign({}, updateMap, {
parent: singleSchemaName,
fieldname,
value,
name: getRandomString(),
});
return await this.knex!('SingleValue').insert(fieldValueMap);
2022-03-23 06:16:13 +00:00
}
async #initializeSingles() {
const singleSchemaNames = Object.keys(this.schemaMap).filter(
(n) => this.schemaMap[n]!.isSingle
);
2022-03-23 06:16:13 +00:00
for (const schemaName of singleSchemaNames) {
if (await this.#singleExists(schemaName)) {
await this.#updateNonExtantSingleValues(schemaName);
continue;
}
2022-03-23 06:16:13 +00:00
const fields = this.schemaMap[schemaName]!.fields;
if (fields.every((f) => f.default === undefined)) {
continue;
}
2022-03-23 06:16:13 +00:00
const defaultValues: FieldValueMap = fields.reduce((acc, f) => {
if (f.default !== undefined) {
acc[f.fieldname] = f.default;
2022-03-23 06:16:13 +00:00
}
return acc;
2022-03-25 10:12:39 +00:00
}, {} as FieldValueMap);
await this.#updateSingleValues(schemaName, defaultValues);
2022-03-23 06:16:13 +00:00
}
}
2022-03-23 06:16:13 +00:00
async #updateNonExtantSingleValues(schemaName: string) {
const singleValues = await this.#getNonExtantSingleValues(schemaName);
for (const sv of singleValues) {
2022-03-25 10:12:39 +00:00
await this.#updateSingleValue(schemaName, sv.fieldname, sv.value!);
}
2022-03-23 06:16:13 +00:00
}
async #updateOne(schemaName: string, fieldValueMap: FieldValueMap) {
const updateMap = { ...fieldValueMap };
delete updateMap.name;
const schema = this.schemaMap[schemaName] as Schema;
for (const { fieldname, fieldtype } of schema.fields) {
if (fieldtype !== FieldTypeEnum.Table) {
continue;
}
delete updateMap[fieldname];
}
if (Object.keys(updateMap).length === 0) {
return;
}
2022-03-25 10:12:39 +00:00
return await this.knex!(schemaName)
.where('name', fieldValueMap.name as string)
.update(updateMap);
2022-03-23 06:16:13 +00:00
}
async #insertOrUpdateChildren(
schemaName: string,
fieldValueMap: FieldValueMap,
isUpdate: boolean
2022-03-23 06:16:13 +00:00
) {
const tableFields = this.#getTableFields(schemaName);
2022-03-23 06:16:13 +00:00
const parentName = fieldValueMap.name as string;
for (const field of tableFields) {
const added: string[] = [];
const tableFieldValue = (fieldValueMap[field.fieldname] ??
[]) as FieldValueMap[];
for (const child of tableFieldValue) {
this.#prepareChild(schemaName, parentName, child, field, added.length);
if (
isUpdate &&
(await this.exists(field.target, child.name as string))
) {
await this.#updateOne(field.target, child);
} else {
await this.#insertOne(field.target, child);
}
2022-03-23 06:16:13 +00:00
added.push(child.name as string);
}
2022-03-23 06:16:13 +00:00
if (isUpdate) {
await this.#runDeleteOtherChildren(field, parentName, added);
}
2022-03-23 06:16:13 +00:00
}
}
2022-03-23 06:16:13 +00:00
#getTableFields(schemaName: string): TargetField[] {
return this.schemaMap[schemaName]!.fields.filter(
(f) => f.fieldtype === FieldTypeEnum.Table
) as TargetField[];
}
2022-03-23 06:16:13 +00:00
}