Skip to content
Draft
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
55 changes: 45 additions & 10 deletions lib/model/query/entities.js
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,8 @@
// including this file, may be copied, modified, propagated, or distributed
// except according to the terms contained in the LICENSE file.

/* eslint-disable key-spacing */

const config = require('config');
const { sql } = require('slonik');
const { Actor, Audit, Entity, Submission, Form } = require('../frames');
Expand Down Expand Up @@ -178,18 +180,51 @@ const createVersion = (dataset, partial, subDef, version, sourceId, baseVersion,

const conflictingPropJson = partial.def.conflictingProperties ? JSON.stringify(partial.def.conflictingProperties) : null;

const _unjoiner = unjoiner(Entity, Entity.Def.into('currentVersion'));

return one(sql`
with def as (${_defInsert(partial.id, false, creatorId, userAgent, partial, version, sourceId, baseVersion, conflictingPropJson)}),
upd as (update entity_defs set current=false where entity_defs."entityId" = ${partial.id} AND current IS TRUE),
entities as (update entities set "updatedAt"=clock_timestamp(), conflict=${partial.conflict ?? sql`NULL`}
where "uuid"=${partial.uuid}
returning *)
select ${_unjoiner.fields} from def as entity_defs
join entities on entity_defs."entityId" = entities.id
WITH
def AS (${_defInsert(partial.id, false, creatorId, userAgent, partial, version, sourceId, baseVersion, conflictingPropJson)}),
upd AS (UPDATE entity_defs SET current=false WHERE entity_defs."entityId" = ${partial.id} AND current IS TRUE),
entities AS (
UPDATE entities
SET "updatedAt"=clock_timestamp(), conflict=${partial.conflict ?? null}
WHERE "uuid"=${partial.uuid}
RETURNING "creatorId", "createdAt", "updatedAt"
)
SELECT entities.*
, def."id" AS "entityDefId"
FROM entities
CROSS JOIN def
`)
.then(_unjoiner);
.then(({ entityDefId, createdAt, ...entity }) =>
new Entity({
...entity,
createdAt,
id: partial.id,
uuid: partial.uuid,
datasetId: partial.datasetId,
conflict: partial.conflict,
deletedAt: null,
}, {
currentVersion: new Entity.Def({
id: entityDefId,
createdAt,
current: true,
sourceId,
creatorId,
userAgent,
root: false,
version,
baseVersion,
entityId: partial.id,
label: partial.def.label,
data: partial.def.data,
dataReceived: partial.def.dataReceived,
conflictingProperties: partial.def.conflictingProperties ?? null,
branchId: partial.def.branchId ?? null,
trunkVersion: partial.def.trunkVersion ?? null,
branchBaseVersion: partial.def.branchBaseVersion ?? null,
}),
}));
};

createVersion.audit = (updatedEntity, dataset, partial, subDef) => (log) => {
Expand Down