From 4792d820e977245b430093fcfbe60460b8a1abe8 Mon Sep 17 00:00:00 2001 From: Elliot Sabitov <> Date: Wed, 11 Dec 2024 10:07:48 -0500 Subject: [PATCH] feat: adding conditional unique indexes on nullable fields in Evse and VariableAttributes models because otherwise postgres does not treat NULLs as distinct and unique index is not enforced --- .../sequelize/model/DeviceModel/Evse.ts | 12 +++- .../model/DeviceModel/VariableAttribute.ts | 60 ++++++++++++++++++- 2 files changed, 70 insertions(+), 2 deletions(-) diff --git a/01_Data/src/layers/sequelize/model/DeviceModel/Evse.ts b/01_Data/src/layers/sequelize/model/DeviceModel/Evse.ts index 5923642b..585a9cd7 100644 --- a/01_Data/src/layers/sequelize/model/DeviceModel/Evse.ts +++ b/01_Data/src/layers/sequelize/model/DeviceModel/Evse.ts @@ -6,7 +6,17 @@ import { type CustomDataType, type EVSEType, Namespace } from '@citrineos/base'; import { AutoIncrement, Column, DataType, Model, PrimaryKey, Table } from 'sequelize-typescript'; -@Table +@Table({ + indexes: [ + { + unique: true, + fields: ['id'], + where: { + connectorId: null, + }, + }, + ], +}) export class Evse extends Model implements EVSEType { static readonly MODEL_NAME: string = Namespace.EVSEType; diff --git a/01_Data/src/layers/sequelize/model/DeviceModel/VariableAttribute.ts b/01_Data/src/layers/sequelize/model/DeviceModel/VariableAttribute.ts index c90373b2..b9b36eda 100644 --- a/01_Data/src/layers/sequelize/model/DeviceModel/VariableAttribute.ts +++ b/01_Data/src/layers/sequelize/model/DeviceModel/VariableAttribute.ts @@ -13,7 +13,64 @@ import { Boot } from '../Boot'; import { VariableStatus } from './VariableStatus'; import { ChargingStation } from '../Location'; -@Table +@Table({ + indexes: [ + { + unique: true, + fields: ['stationId'], + where: { + type: null, + variableId: null, + componentId: null, + }, + }, + { + unique: true, + fields: ['stationId', 'type'], + where: { + variableId: null, + componentId: null, + }, + }, + { + unique: true, + fields: ['stationId', 'variableId'], + where: { + type: null, + componentId: null, + }, + }, + { + unique: true, + fields: ['stationId', 'componentId'], + where: { + type: null, + variableId: null, + }, + }, + { + unique: true, + fields: ['stationId', 'type', 'variableId'], + where: { + componentId: null, + }, + }, + { + unique: true, + fields: ['stationId', 'type', 'componentId'], + where: { + variableId: null, + }, + }, + { + unique: true, + fields: ['stationId', 'variableId', 'componentId'], + where: { + type: null, + }, + }, + ], +}) export class VariableAttribute extends Model implements VariableAttributeType { static readonly MODEL_NAME: string = Namespace.VariableAttributeType; @@ -24,6 +81,7 @@ export class VariableAttribute extends Model implements VariableAttributeType { @Index @Column({ unique: 'stationId_type_variableId_componentId', + allowNull: false, }) @ForeignKey(() => ChargingStation) declare stationId: string;