Skip to content

Commit 9c860e8

Browse files
committed
poc add ability to use any unique key as the external 'id'
this makes it possible to use a natural key even while also using surrogate primary keys
1 parent 037fc2c commit 9c860e8

File tree

2 files changed

+15
-2
lines changed

2 files changed

+15
-2
lines changed

packages/runtime/src/cross/utils.ts

Lines changed: 10 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -50,9 +50,17 @@ export function zip<T1, T2>(x: Enumerable<T1>, y: Enumerable<T2>): Array<[T1, T2
5050
* Gets ID fields of a model.
5151
*/
5252
export function getIdFields(modelMeta: ModelMeta, model: string, throwIfNotFound = false) {
53-
const uniqueConstraints = modelMeta.models[lowerCaseFirst(model)]?.uniqueConstraints ?? {};
53+
const metaData = modelMeta.models[lowerCaseFirst(model)] ?? {};
54+
const uniqueConstraints = metaData.uniqueConstraints ?? {};
55+
56+
let entries = Object.values(uniqueConstraints);
57+
if (metaData.attributes !== undefined) {
58+
const externalId = metaData.attributes.find((attr) => attr.name === '@@externalId');
59+
if (externalId && externalId.args[0] !== undefined) {
60+
entries = entries.filter((entry) => entry.name === externalId.args[0].value);
61+
}
62+
}
5463

55-
const entries = Object.values(uniqueConstraints);
5664
if (entries.length === 0) {
5765
if (throwIfNotFound) {
5866
throw new Error(`Model ${model} does not have any id field`);

packages/schema/src/res/stdlib.zmodel

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -738,6 +738,11 @@ attribute @@prisma.passthrough(_ text: String)
738738
*/
739739
attribute @@delegate(_ discriminator: FieldReference)
740740

741+
/**
742+
* Specifies an external identifier for the model other than a primary key
743+
*/
744+
attribute @@externalId(_ name: String)
745+
741746
/**
742747
* Used for specifying operator classes for GIN index.
743748
*/

0 commit comments

Comments
 (0)