UNPKG

@cubicweb/rql-generator

Version:

Helpers to build RQL queries

63 lines 2.85 kB
import { RQLQuery, getRawRelationType, } from "@cubicweb/client"; import { getEntitySchema } from "./utils/schema.js"; import { generateSetRelationByEidsRQL } from "./update.js"; import { getAttributesUpdateClause } from "./utils/rql.js"; import { splitEntityData } from "./utils/entitydata.js"; /** * Generates a RQL query to insert a new entity with the given initial data. * * Adding relations in the INSERT query only works if a relation is marked as "inlined". * To work around this issue we instead generate one query for each relation after the initial insert. * * @remarks Unknown attributes/relations used as keys in the `entityData` param will be ignored. * If no valid attribute/relation is supplied in the data, the query will insert the entity without data. * * @example * Creating a new BlogEntry with a title and content: * * ```typescript * generateCreateEntityRQL( * SCHEMA, * "BlogEntry", * { * title: "My First Post", * content: "My content" * } * ) * ``` * produces: * * ``` * INSERT BlogEntry X: X title %(title)s, X content %(content)s * ``` * * @param schema The instance schema * @param entityType The type of the entity to create * @param entityData An object with each attribute/relation type as key and their values as value. Object relations must have the reverse prefix. See [@cubicweb/client:getReverseRelationType](https://cubicweb.pages.logilab.fr/cubicwebjs/client/functions/getReverseRelationType.html) * @returns RQL queries needed to insert a new entity with the given initial data. The first query of the returned array produces a {ResultSet}. This ResultSet contains the eid of the created entity at position (0, 0). * * @category Creating entities */ export const generateCreateEntityRQL = (schema, entityType, entityData = {}) => { const entitySchema = getEntitySchema(schema, entityType); const queries = []; const { attributes, subjects, objects } = splitEntityData(entitySchema, entityData); const { attributesUpdates, params } = getAttributesUpdateClause(entitySchema, attributes); let requestStr = `INSERT ${entitySchema.type} X`; if (attributesUpdates !== "") { requestStr = `INSERT ${entitySchema.type} X: ${attributesUpdates}`; } const createQuery = new RQLQuery(requestStr, params); const eidRef = createQuery.cellRef(0, 0); queries.push(createQuery); Object.entries(subjects).forEach(([k, v]) => { const q = generateSetRelationByEidsRQL([eidRef], k, Array.isArray(v) ? v : [v]); queries.push(...q); }); Object.entries(objects).forEach(([k, v]) => { const q = generateSetRelationByEidsRQL(Array.isArray(v) ? v : [v], getRawRelationType(k), [eidRef]); queries.push(...q); }); return { queries, eidRef }; }; //# sourceMappingURL=create.js.map