Database diagrams editor that allows you to visualize and design your DB with a single query.
TypeScript databasedbdb-migrationeditorerdmariadbmssqlmysqlpostgresqlreactreact-flowschema-migrationssqlsqlitetypescriptvisualizationxyflow
feat: add check constraint support (#1046)
Jonathan Fishner6879e19fa575
diff --git a/src/context/chartdb-context/chartdb-context.tsx b/src/context/chartdb-context/chartdb-context.tsxindex c8450528..c94a030f 100644--- a/src/context/chartdb-context/chartdb-context.tsx+++ b/src/context/chartdb-context/chartdb-context.tsx@@ -4,6 +4,7 @@ import { emptyFn } from '@/lib/utils';import { DatabaseType } from '@/lib/domain/database-type';import type { DBField } from '@/lib/domain/db-field';import type { DBIndex } from '@/lib/domain/db-index';+import type { DBCheckConstraint } from '@/lib/domain/db-check-constraint';import type { DBRelationship } from '@/lib/domain/db-relationship';import type { Diagram } from '@/lib/domain/diagram';import type { DatabaseEdition } from '@/lib/domain/database-edition';@@ -174,6 +175,25 @@ export interface ChartDBContext {options?: { updateHistory: boolean }) => Promise<void>;+ // Check constraint operations+ createCheckConstraint: (tableId: string) => Promise<DBCheckConstraint>;+ addCheckConstraint: (+ tableId: string,+ constraint: DBCheckConstraint,+ options?: { updateHistory: boolean }+ ) => Promise<void>;+ removeCheckConstraint: (+ tableId: string,+ constraintId: string,+ options?: { updateHistory: boolean }+ ) => Promise<void>;+ updateCheckConstraint: (+ tableId: string,+ constraintId: string,+ constraint: Partial<DBCheckConstraint>,+ options?: { updateHistory: boolean }+ ) => Promise<void>;+// Relationship operationscreateRelationship: (params: {sourceTableId: string;@@ -369,6 +389,12 @@ export const chartDBContext = createContext<ChartDBContext>({removeIndex: emptyFn,updateIndex: emptyFn,+ // Check constraint operations+ createCheckConstraint: emptyFn,+ addCheckConstraint: emptyFn,+ removeCheckConstraint: emptyFn,+ updateCheckConstraint: emptyFn,+// Relationship operationscreateRelationship: emptyFn,addRelationship: emptyFn,diff --git a/src/context/chartdb-context/chartdb-provider.tsx b/src/context/chartdb-context/chartdb-provider.tsxindex 04d4150c..df4e9b0e 100644--- a/src/context/chartdb-context/chartdb-provider.tsx+++ b/src/context/chartdb-context/chartdb-provider.tsx@@ -10,6 +10,7 @@ import {getTableIndexesWithPrimaryKey,type DBIndex,} from '@/lib/domain/db-index';+import type { DBCheckConstraint } from '@/lib/domain/db-check-constraint';import type { DBRelationship } from '@/lib/domain/db-relationship';import { useStorage } from '@/hooks/use-storage';import { useRedoUndoStack } from '@/hooks/use-redo-undo-stack';@@ -1063,6 +1064,255 @@ export const ChartDBProvider: React.FC<[db, diagramId, setTables, addUndoAction, resetRedoStack, getIndex]);+ const createCheckConstraint: ChartDBContext['createCheckConstraint'] =+ useCallback(+ async (tableId: string) => {+ const constraint: DBCheckConstraint = {+ id: generateId(),+ expression: '',+ createdAt: Date.now(),+ };++ setTables((tables) =>+ tables.map((t) =>+ t.id === tableId+ ? {+ ...t,+ checkConstraints: [+ ...(t.checkConstraints ?? []),+ constraint,+ ],+ }+ : t+ )+ );++ const dbTable = await db.getTable({ diagramId, id: tableId });+ if (!dbTable) {+ return constraint;+ }++ const updatedAt = new Date();+ setDiagramUpdatedAt(updatedAt);+ await Promise.all([+ db.updateDiagram({+ id: diagramId,+ attributes: { updatedAt },+ }),+ db.updateTable({+ id: tableId,+ attributes: {+ ...dbTable,+ checkConstraints: [+ ...(dbTable.checkConstraints ?? []),+ constraint,+ ],+ },+ }),+ ]);++ addUndoAction({+ action: 'addCheckConstraint',+ redoData: { tableId, constraint },+ undoData: { tableId, constraintId: constraint.id },+ });+ resetRedoStack();++ return constraint;+ },+ [db, diagramId, setTables, addUndoAction, resetRedoStack]+ );++ const addCheckConstraint: ChartDBContext['addCheckConstraint'] =+ useCallback(+ async (+ tableId: string,+ constraint: DBCheckConstraint,+ options = { updateHistory: true }+ ) => {+ setTables((tables) =>+ tables.map((t) =>+ t.id === tableId+ ? {+ ...t,+ checkConstraints: [+ ...(t.checkConstraints ?? []),+ constraint,+ ],+ }+ : t+ )+ );++ const dbTable = await db.getTable({ diagramId, id: tableId });+ if (!dbTable) {+ return;+ }++ const updatedAt = new Date();+ setDiagramUpdatedAt(updatedAt);+ await Promise.all([+ db.updateDiagram({+ id: diagramId,+ attributes: { updatedAt },+ }),+ db.updateTable({+ id: tableId,+ attributes: {+ ...dbTable,+ checkConstraints: [+ ...(dbTable.checkConstraints ?? []),+ constraint,+ ],+ },+ }),+ ]);++ if (options.updateHistory) {+ addUndoAction({+ action: 'addCheckConstraint',+ redoData: { tableId, constraint },+ undoData: { tableId, constraintId: constraint.id },+ });+ resetRedoStack();+ }+ },+ [db, diagramId, setTables, addUndoAction, resetRedoStack]+ );++ const removeCheckConstraint: ChartDBContext['removeCheckConstraint'] =+ useCallback(+ async (+ tableId: string,+ constraintId: string,+ options = { updateHistory: true }+ ) => {+ const table = getTable(tableId);+ const prevConstraint = table?.checkConstraints?.find(+ (c) => c.id === constraintId+ );++ setTables((tables) =>+ tables.map((t) =>+ t.id === tableId+ ? {+ ...t,+ checkConstraints: (+ t.checkConstraints ?? []+ ).filter((c) => c.id !== constraintId),+ }+ : t+ )+ );++ const dbTable = await db.getTable({ diagramId, id: tableId });+ if (!dbTable) {+ return;+ }++ const updatedAt = new Date();+ setDiagramUpdatedAt(updatedAt);+ await Promise.all([+ db.updateDiagram({+ id: diagramId,+ attributes: { updatedAt },+ }),+ db.updateTable({+ id: tableId,+ attributes: {+ ...dbTable,+ checkConstraints: (+ dbTable.checkConstraints ?? []+ ).filter((c) => c.id !== constraintId),+ },+ }),+ ]);++ if (!!prevConstraint && options.updateHistory) {+ addUndoAction({+ action: 'removeCheckConstraint',+ redoData: { tableId, constraintId },+ undoData: { tableId, constraint: prevConstraint },+ });+ resetRedoStack();+ }+ },+ [db, diagramId, setTables, addUndoAction, resetRedoStack, getTable]+ );++ const updateCheckConstraint: ChartDBContext['updateCheckConstraint'] =+ useCallback(+ async (+ tableId: string,+ constraintId: string,+ constraint: Partial<DBCheckConstraint>,+ options = { updateHistory: true }+ ) => {+ const table = getTable(tableId);+ const prevConstraint = table?.checkConstraints?.find(+ (c) => c.id === constraintId+ );++ setTables((tables) =>+ tables.map((t) =>+ t.id === tableId+ ? {+ ...t,+ checkConstraints: (+ t.checkConstraints ?? []+ ).map((c) =>+ c.id === constraintId+ ? { ...c, ...constraint }+ : c+ ),+ }+ : t+ )+ );++ const dbTable = await db.getTable({ diagramId, id: tableId });+ if (!dbTable) {+ return;+ }++ const updatedAt = new Date();+ setDiagramUpdatedAt(updatedAt);+ await Promise.all([+ db.updateDiagram({+ id: diagramId,+ attributes: { updatedAt },+ }),+ db.updateTable({+ id: tableId,+ attributes: {+ ...dbTable,+ checkConstraints: (+ dbTable.checkConstraints ?? []+ ).map((c) =>+ c.id === constraintId+ ? { ...c, ...constraint }+ : c+ ),+ },+ }),+ ]);++ if (!!prevConstraint && options.updateHistory) {+ addUndoAction({+ action: 'updateCheckConstraint',+ redoData: { tableId, constraintId, constraint },+ undoData: {+ tableId,+ constraintId,+ constraint: prevConstraint,+ },+ });+ resetRedoStack();+ }+ },+ [db, diagramId, setTables, addUndoAction, resetRedoStack, getTable]+ );+const addRelationships: ChartDBContext['addRelationships'] = useCallback(async (relationships: DBRelationship[],@@ -1931,6 +2181,10 @@ export const ChartDBProvider: React.FC<getField,getIndex,updateIndex,+ createCheckConstraint,+ addCheckConstraint,+ removeCheckConstraint,+ updateCheckConstraint,addRelationship,addRelationships,createRelationship,diff --git a/src/context/history-context/history-provider.tsx b/src/context/history-context/history-provider.tsxindex 8c814daa..b156dd19 100644--- a/src/context/history-context/history-provider.tsx+++ b/src/context/history-context/history-provider.tsx@@ -32,6 +32,9 @@ export const HistoryProvider: React.FC<React.PropsWithChildren> = ({addIndex,removeIndex,updateIndex,+ addCheckConstraint,+ removeCheckConstraint,+ updateCheckConstraint,removeRelationships,addAreas,removeAreas,@@ -116,6 +119,30 @@ export const HistoryProvider: React.FC<React.PropsWithChildren> = ({updateHistory: false,});},+ addCheckConstraint: ({ redoData: { tableId, constraint } }) => {+ return addCheckConstraint(tableId, constraint, {+ updateHistory: false,+ });+ },+ removeCheckConstraint: ({+ redoData: { tableId, constraintId },+ }) => {+ return removeCheckConstraint(tableId, constraintId, {+ updateHistory: false,+ });+ },+ updateCheckConstraint: ({+ redoData: { tableId, constraintId, constraint },+ }) => {+ return updateCheckConstraint(+ tableId,+ constraintId,+ constraint,+ {+ updateHistory: false,+ }+ );+ },addAreas: ({ redoData: { areas } }) => {return addAreas(areas, { updateHistory: false });},@@ -162,6 +189,9 @@ export const HistoryProvider: React.FC<React.PropsWithChildren> = ({addIndex,removeIndex,updateIndex,+ addCheckConstraint,+ removeCheckConstraint,+ updateCheckConstraint,removeRelationships,addDependencies,removeDependencies,@@ -264,6 +294,28 @@ export const HistoryProvider: React.FC<React.PropsWithChildren> = ({updateHistory: false,});},+ addCheckConstraint: ({ undoData: { tableId, constraintId } }) => {+ return removeCheckConstraint(tableId, constraintId, {+ updateHistory: false,+ });+ },+ removeCheckConstraint: ({ undoData: { tableId, constraint } }) => {+ return addCheckConstraint(tableId, constraint, {+ updateHistory: false,+ });+ },+ updateCheckConstraint: ({+ undoData: { tableId, constraintId, constraint },+ }) => {+ return updateCheckConstraint(+ tableId,+ constraintId,+ constraint,+ {+ updateHistory: false,+ }+ );+ },addAreas: ({ undoData: { areaIds } }) => {return removeAreas(areaIds, { updateHistory: false });},@@ -310,6 +362,9 @@ export const HistoryProvider: React.FC<React.PropsWithChildren> = ({addIndex,removeIndex,updateIndex,+ addCheckConstraint,+ removeCheckConstraint,+ updateCheckConstraint,removeRelationships,addDependencies,removeDependencies,diff --git a/src/context/history-context/redo-undo-action.ts b/src/context/history-context/redo-undo-action.tsindex ef32f6b0..f618c845 100644--- a/src/context/history-context/redo-undo-action.ts+++ b/src/context/history-context/redo-undo-action.ts@@ -2,6 +2,7 @@ import type { DBTable } from '@/lib/domain/db-table';import type { ChartDBContext } from '../chartdb-context/chartdb-context';import type { DBField } from '@/lib/domain/db-field';import type { DBIndex } from '@/lib/domain/db-index';+import type { DBCheckConstraint } from '@/lib/domain/db-check-constraint';import type { DBRelationship } from '@/lib/domain/db-relationship';import type { DBDependency } from '@/lib/domain/db-dependency';import type { Area } from '@/lib/domain/area';@@ -90,6 +91,32 @@ type RedoUndoActionUpdateIndex = RedoUndoActionBase<{ tableId: string; indexId: string; index: Partial<DBIndex> }>;+type RedoUndoActionAddCheckConstraint = RedoUndoActionBase<+ 'addCheckConstraint',+ { tableId: string; constraint: DBCheckConstraint },+ { tableId: string; constraintId: string }+>;++type RedoUndoActionRemoveCheckConstraint = RedoUndoActionBase<+ 'removeCheckConstraint',+ { tableId: string; constraintId: string },+ { tableId: string; constraint: DBCheckConstraint }+>;++type RedoUndoActionUpdateCheckConstraint = RedoUndoActionBase<+ 'updateCheckConstraint',+ {+ tableId: string;+ constraintId: string;+ constraint: Partial<DBCheckConstraint>;+ },+ {+ tableId: string;+ constraintId: string;+ constraint: Partial<DBCheckConstraint>;+ }+>;+type RedoUndoActionAddRelationships = RedoUndoActionBase<'addRelationships',{ relationships: DBRelationship[] },@@ -192,6 +219,9 @@ export type RedoUndoAction =| RedoUndoActionAddIndex| RedoUndoActionRemoveIndex| RedoUndoActionUpdateIndex+ | RedoUndoActionAddCheckConstraint+ | RedoUndoActionRemoveCheckConstraint+ | RedoUndoActionUpdateCheckConstraint| RedoUndoActionAddRelationships| RedoUndoActionUpdateRelationship| RedoUndoActionRemoveRelationshipsdiff --git a/src/i18n/locales/ar.ts b/src/i18n/locales/ar.tsindex 2283c41a..08cdad9b 100644--- a/src/i18n/locales/ar.ts+++ b/src/i18n/locales/ar.ts@@ -136,10 +136,12 @@ export const ar: LanguageTranslation = {nullable: 'يمكن ان يكون فارغاً؟',primary_key: 'المفتاح الأساسي',indexes: 'الفهارس',+ check_constraints: 'قيود التحقق',comments: 'تعليقات',no_comments: 'لا توجد تعليقات',add_field: 'إضافة حقل',add_index: 'إضافة فهرس',+ add_check: 'إضافة تحقق',index_select_fields: 'حدد الحقول',no_types_found: 'لا يوجد أنواع',field_name: 'الإسم',@@ -165,6 +167,11 @@ export const ar: LanguageTranslation = {index_type: 'نوع الفهرس',delete_index: 'حذف الفهرس',},+ check_constraint_actions: {+ title: 'قيد التحقق',+ expression: 'التعبير',+ delete: 'حذف قيد التحقق',+ },table_actions: {title: 'إجراءات الجدول',change_schema: 'تغيير المخطط',diff --git a/src/i18n/locales/bn.ts b/src/i18n/locales/bn.tsindex 0895557e..171d0902 100644--- a/src/i18n/locales/bn.ts+++ b/src/i18n/locales/bn.ts@@ -137,10 +137,12 @@ export const bn: LanguageTranslation = {nullable: 'নালযোগ্য?',primary_key: 'প্রাথমিক কী',indexes: 'ইনডেক্স',+ check_constraints: 'চেক সীমাবদ্ধতা',comments: 'মন্তব্য',no_comments: 'কোনো মন্তব্য নেই',add_field: 'ফিল্ড যোগ করুন',add_index: 'ইনডেক্স যোগ করুন',+ add_check: 'চেক যোগ করুন',index_select_fields: 'ফিল্ড নির্বাচন করুন',no_types_found: 'কোনো ধরন পাওয়া যায়নি',field_name: 'নাম',@@ -167,6 +169,11 @@ export const bn: LanguageTranslation = {index_type: 'ইনডেক্স ধরন',delete_index: 'ইনডেক্স মুছুন',},+ check_constraint_actions: {+ title: 'চেক সীমাবদ্ধতা',+ expression: 'এক্সপ্রেশন',+ delete: 'সীমাবদ্ধতা মুছুন',+ },table_actions: {title: 'টেবিল কর্ম',change_schema: 'স্কিমা পরিবর্তন করুন',diff --git a/src/i18n/locales/de.ts b/src/i18n/locales/de.tsindex 581bf22e..cb5bed24 100644--- a/src/i18n/locales/de.ts+++ b/src/i18n/locales/de.ts@@ -137,10 +137,12 @@ export const de: LanguageTranslation = {nullable: 'Nullable?',primary_key: 'Primärschlüssel',indexes: 'Indizes',+ check_constraints: 'Prüfbedingungen',comments: 'Kommentare',no_comments: 'Keine Kommentare',add_field: 'Feld hinzufügen',add_index: 'Index hinzufügen',+ add_check: 'Prüfung hinzufügen',index_select_fields: 'Felder auswählen',no_types_found: 'Keine Datentypen gefunden',field_name: 'Name',@@ -167,6 +169,11 @@ export const de: LanguageTranslation = {index_type: 'Indextyp',delete_index: 'Index löschen',},+ check_constraint_actions: {+ title: 'Prüfbedingung',+ expression: 'Ausdruck',+ delete: 'Prüfbedingung löschen',+ },table_actions: {title: 'Tabellenaktionen',change_schema: 'Schema ändern',diff --git a/src/i18n/locales/en.ts b/src/i18n/locales/en.tsindex 5af17fc2..f4fda3c7 100644--- a/src/i18n/locales/en.ts+++ b/src/i18n/locales/en.ts@@ -133,10 +133,12 @@ export const en = {nullable: 'Nullable?',primary_key: 'Primary Key',indexes: 'Indexes',+ check_constraints: 'Check Constraints',comments: 'Comments',no_comments: 'No comments',add_field: 'Add Field',add_index: 'Add Index',+ add_check: 'Add Check',index_select_fields: 'Select fields',no_types_found: 'No types found',field_name: 'Name',@@ -161,6 +163,11 @@ export const en = {index_type: 'Index Type',delete_index: 'Delete Index',},+ check_constraint_actions: {+ title: 'Check Constraint',+ expression: 'Expression',+ delete: 'Delete Check Constraint',+ },table_actions: {title: 'Table Actions',change_schema: 'Change Schema',diff --git a/src/i18n/locales/es.ts b/src/i18n/locales/es.tsindex 1cb0d878..8b8058e4 100644--- a/src/i18n/locales/es.ts+++ b/src/i18n/locales/es.ts@@ -136,10 +136,12 @@ export const es: LanguageTranslation = {nullable: '¿Opcional?',primary_key: 'Clave Primaria',indexes: 'Índices',+ check_constraints: 'Restricciones de verificación',comments: 'Comentarios',no_comments: 'Sin comentarios',add_field: 'Agregar Campo',add_index: 'Agregar Índice',+ add_check: 'Agregar verificación',index_select_fields: 'Seleccionar campos',field_name: 'Nombre',field_type: 'Tipo',@@ -166,6 +168,11 @@ export const es: LanguageTranslation = {index_type: 'Tipo de Índice',delete_index: 'Eliminar Índice',},+ check_constraint_actions: {+ title: 'Restricción de verificación',+ expression: 'Expresión',+ delete: 'Eliminar restricción',+ },table_actions: {title: 'Acciones de la Tabla',change_schema: 'Cambiar Esquema',diff --git a/src/i18n/locales/fr.ts b/src/i18n/locales/fr.tsindex 2a45b086..bd756c79 100644--- a/src/i18n/locales/fr.ts+++ b/src/i18n/locales/fr.ts@@ -134,10 +134,12 @@ export const fr: LanguageTranslation = {nullable: 'Nullable?',primary_key: 'Clé Primaire',indexes: 'Index',+ check_constraints: 'Contraintes de vérification',comments: 'Commentaires',no_comments: 'Pas de commentaires',add_field: 'Ajouter un Champ',add_index: 'Ajouter un Index',+ add_check: 'Ajouter une vérification',index_select_fields: 'Sélectionner des champs',no_types_found: 'Aucun type trouvé',field_name: 'Nom',@@ -164,6 +166,11 @@ export const fr: LanguageTranslation = {index_type: "Type d'index",delete_index: "Supprimer l'Index",},+ check_constraint_actions: {+ title: 'Contrainte de vérification',+ expression: 'Expression',+ delete: 'Supprimer la contrainte',+ },table_actions: {title: 'Actions de la Table',add_field: 'Ajouter un Champ',diff --git a/src/i18n/locales/gu.ts b/src/i18n/locales/gu.tsindex 0eca1a29..7887287a 100644--- a/src/i18n/locales/gu.ts+++ b/src/i18n/locales/gu.ts@@ -138,10 +138,12 @@ export const gu: LanguageTranslation = {nullable: 'Nullable?',primary_key: 'પ્રાથમિક કી',indexes: 'ઈન્ડેક્સ',+ check_constraints: 'ચકાસણી નિયંત્રણો',comments: 'ટિપ્પણીઓ',no_comments: 'કોઈ ટિપ્પણીઓ નથી',add_field: 'ફીલ્ડ ઉમેરો',add_index: 'ઈન્ડેક્સ ઉમેરો',+ add_check: 'ચકાસણી ઉમેરો',index_select_fields: 'ફીલ્ડ્સ પસંદ કરો',no_types_found: 'કોઈ પ્રકાર મળ્યા નથી',field_name: 'નામ',@@ -168,6 +170,11 @@ export const gu: LanguageTranslation = {index_type: 'ઇન્ડેક્સ પ્રકાર',delete_index: 'ઇન્ડેક્સ કાઢી નાખો',},+ check_constraint_actions: {+ title: 'ચકાસણી નિયંત્રણ',+ expression: 'અભિવ્યક્તિ',+ delete: 'નિયંત્રણ કાઢી નાખો',+ },table_actions: {title: 'ટેબલ ક્રિયાઓ',change_schema: 'સ્કીમા બદલો',diff --git a/src/i18n/locales/hi.ts b/src/i18n/locales/hi.tsindex 94a4d1b8..e6f18a8d 100644--- a/src/i18n/locales/hi.ts+++ b/src/i18n/locales/hi.ts@@ -137,10 +137,12 @@ export const hi: LanguageTranslation = {nullable: 'Nullable?',primary_key: 'प्राथमिक कुंजी',indexes: 'सूचकांक',+ check_constraints: 'जाँच प्रतिबंध',comments: 'टिप्पणियाँ',no_comments: 'कोई टिप्पणी नहीं',add_field: 'फ़ील्ड जोड़ें',add_index: 'सूचकांक जोड़ें',+ add_check: 'जाँच जोड़ें',index_select_fields: 'फ़ील्ड्स चुनें',no_types_found: 'कोई प्रकार नहीं मिला',field_name: 'नाम',@@ -167,6 +169,11 @@ export const hi: LanguageTranslation = {index_type: 'इंडेक्स प्रकार',delete_index: 'सूचकांक हटाएँ',},+ check_constraint_actions: {+ title: 'जाँच प्रतिबंध',+ expression: 'अभिव्यक्ति',+ delete: 'प्रतिबंध हटाएं',+ },table_actions: {title: 'तालिका क्रियाएँ',change_schema: 'स्कीमा बदलें',diff --git a/src/i18n/locales/hr.ts b/src/i18n/locales/hr.tsindex b7bb5c6c..b399afed 100644--- a/src/i18n/locales/hr.ts+++ b/src/i18n/locales/hr.ts@@ -134,10 +134,12 @@ export const hr: LanguageTranslation = {nullable: 'Može biti null?',primary_key: 'Primarni ključ',indexes: 'Indeksi',+ check_constraints: 'Provjerna ograničenja',comments: 'Komentari',no_comments: 'Nema komentara',add_field: 'Dodaj polje',add_index: 'Dodaj indeks',+ add_check: 'Dodaj provjeru',index_select_fields: 'Odaberi polja',no_types_found: 'Nema pronađenih tipova',field_name: 'Naziv',@@ -162,6 +164,11 @@ export const hr: LanguageTranslation = {index_type: 'Vrsta indeksa',delete_index: 'Izbriši indeks',},+ check_constraint_actions: {+ title: 'Provjerno ograničenje',+ expression: 'Izraz',+ delete: 'Obriši ograničenje',+ },table_actions: {title: 'Radnje nad tablicom',change_schema: 'Promijeni shemu',diff --git a/src/i18n/locales/id_ID.ts b/src/i18n/locales/id_ID.tsindex 2e5beed7..62f918fb 100644--- a/src/i18n/locales/id_ID.ts+++ b/src/i18n/locales/id_ID.ts@@ -136,10 +136,12 @@ export const id_ID: LanguageTranslation = {nullable: 'Bisa Kosong?',primary_key: 'Kunci Utama',indexes: 'Indeks',+ check_constraints: 'Batasan Pemeriksaan',comments: 'Komentar',no_comments: 'Tidak ada komentar',add_field: 'Tambah Kolom',add_index: 'Tambah Indeks',+ add_check: 'Tambah Pemeriksaan',index_select_fields: 'Pilih kolom',no_types_found: 'Tidak ada tipe yang ditemukan',field_name: 'Nama',@@ -166,6 +168,11 @@ export const id_ID: LanguageTranslation = {index_type: 'Tipe Indeks',delete_index: 'Hapus Indeks',},+ check_constraint_actions: {+ title: 'Batasan Pemeriksaan',+ expression: 'Ekspresi',+ delete: 'Hapus Batasan',+ },table_actions: {title: 'Aksi Tabel',change_schema: 'Ubah Skema',diff --git a/src/i18n/locales/ja.ts b/src/i18n/locales/ja.tsindex 50254978..274b89da 100644--- a/src/i18n/locales/ja.ts+++ b/src/i18n/locales/ja.ts@@ -139,10 +139,12 @@ export const ja: LanguageTranslation = {nullable: 'NULL可能?',primary_key: '主キー',indexes: 'インデックス',+ check_constraints: 'チェック制約',comments: 'コメント',no_comments: 'コメントがありません',add_field: 'フィールドを追加',add_index: 'インデックスを追加',+ add_check: 'チェックを追加',index_select_fields: 'フィールドを選択',no_types_found: 'タイプが見つかりません',field_name: '名前',@@ -169,6 +171,11 @@ export const ja: LanguageTranslation = {index_type: 'インデックスタイプ',delete_index: 'インデックスを削除',},+ check_constraint_actions: {+ title: 'チェック制約',+ expression: '式',+ delete: 'チェック制約を削除',+ },table_actions: {title: 'テーブル操作',change_schema: 'スキーマを変更',diff --git a/src/i18n/locales/ko_KR.ts b/src/i18n/locales/ko_KR.tsindex 104b0635..36dc6f2d 100644--- a/src/i18n/locales/ko_KR.ts+++ b/src/i18n/locales/ko_KR.ts@@ -136,10 +136,12 @@ export const ko_KR: LanguageTranslation = {nullable: 'null 여부',primary_key: '기본키',indexes: '인덱스',+ check_constraints: '체크 제약조건',comments: '주석',no_comments: '주석 없음',add_field: '필드 추가',add_index: '인덱스 추가',+ add_check: '체크 추가',index_select_fields: '필드 선택',no_types_found: '타입을 찾을 수 없습니다.',field_name: '이름',@@ -166,6 +168,11 @@ export const ko_KR: LanguageTranslation = {index_type: '인덱스 타입',delete_index: '인덱스 삭제',},+ check_constraint_actions: {+ title: '체크 제약조건',+ expression: '표현식',+ delete: '체크 제약조건 삭제',+ },table_actions: {title: '테이블 작업',change_schema: '스키마 변경',diff --git a/src/i18n/locales/mr.ts b/src/i18n/locales/mr.tsindex 194ad2ba..77fbebdb 100644--- a/src/i18n/locales/mr.ts+++ b/src/i18n/locales/mr.ts@@ -139,10 +139,12 @@ export const mr: LanguageTranslation = {nullable: 'नल करण्यायोग्य?',primary_key: 'प्राथमिक की',indexes: 'सूचकांक',+ check_constraints: 'तपासणी निर्बंध',comments: 'टिप्पण्या',no_comments: 'कोणत्याही टिप्पणी नाहीत',add_field: 'फील्ड जोडा',add_index: 'सूचकांक जोडा',+ add_check: 'तपासणी जोडा',index_select_fields: 'फील्ड निवडा',no_types_found: 'कोणतेही प्रकार सापडले नाहीत',field_name: 'नाव',@@ -169,6 +171,11 @@ export const mr: LanguageTranslation = {index_type: 'इंडेक्स प्रकार',delete_index: 'इंडेक्स हटवा',},+ check_constraint_actions: {+ title: 'तपासणी निर्बंध',+ expression: 'अभिव्यक्ती',+ delete: 'निर्बंध हटवा',+ },table_actions: {title: 'टेबल एक्शन',change_schema: 'स्कीमा बदला',diff --git a/src/i18n/locales/ne.ts b/src/i18n/locales/ne.tsindex 918eba8e..256813cd 100644--- a/src/i18n/locales/ne.ts+++ b/src/i18n/locales/ne.ts@@ -137,10 +137,12 @@ export const ne: LanguageTranslation = {nullable: 'नलेबल?',primary_key: 'प्राथमिक कुंजी',indexes: 'सूचकहरू',+ check_constraints: 'जाँच प्रतिबन्धहरू',comments: 'टिप्पणीहरू',no_comments: 'कुनै टिप्पणीहरू छैनन्',add_field: 'क्षेत्र थप्नुहोस्',add_index: 'सूचक थप्नुहोस्',+ add_check: 'जाँच थप्नुहोस्',index_select_fields: 'क्षेत्रहरू चयन गर्नुहोस्',no_types_found: 'कुनै प्रकारहरू फेला परेनन्',field_name: 'नाम',@@ -167,6 +169,11 @@ export const ne: LanguageTranslation = {index_type: 'इन्डेक्स प्रकार',delete_index: 'सूचक हटाउनुहोस्',},+ check_constraint_actions: {+ title: 'जाँच प्रतिबन्ध',+ expression: 'अभिव्यक्ति',+ delete: 'प्रतिबन्ध हटाउनुहोस्',+ },table_actions: {title: 'तालिका विशेषताहरू',change_schema: 'स्कीम परिवर्तन गर्नुहोस्',diff --git a/src/i18n/locales/pt_BR.ts b/src/i18n/locales/pt_BR.tsindex aa7b189e..7de18c30 100644--- a/src/i18n/locales/pt_BR.ts+++ b/src/i18n/locales/pt_BR.ts@@ -137,10 +137,12 @@ export const pt_BR: LanguageTranslation = {nullable: 'Permite Nulo?',primary_key: 'Chave Primária',indexes: 'Índices',+ check_constraints: 'Restrições de verificação',comments: 'Comentários',no_comments: 'Sem comentários',add_field: 'Adicionar Campo',add_index: 'Adicionar Índice',+ add_check: 'Adicionar verificação',index_select_fields: 'Selecionar campos',no_types_found: 'Nenhum tipo encontrado',field_name: 'Nome',@@ -167,6 +169,11 @@ export const pt_BR: LanguageTranslation = {index_type: 'Tipo de Índice',delete_index: 'Excluir Índice',},+ check_constraint_actions: {+ title: 'Restrição de verificação',+ expression: 'Expressão',+ delete: 'Excluir restrição',+ },table_actions: {title: 'Ações da Tabela',change_schema: 'Alterar Esquema',diff --git a/src/i18n/locales/ru.ts b/src/i18n/locales/ru.tsindex 1bb1ce07..5dadc4f6 100644--- a/src/i18n/locales/ru.ts+++ b/src/i18n/locales/ru.ts@@ -134,10 +134,12 @@ export const ru: LanguageTranslation = {nullable: 'Может быть NULL?',primary_key: 'Первичный ключ',indexes: 'Индексы',+ check_constraints: 'Проверочные ограничения',comments: 'Комментарии',no_comments: 'Нет комментария',add_field: 'Добавить поле',add_index: 'Добавить индекс',+ add_check: 'Добавить проверку',index_select_fields: 'Выберите поля',no_types_found: 'Типы не найдены',field_name: 'Имя',@@ -163,6 +165,11 @@ export const ru: LanguageTranslation = {index_type: 'Тип индекса',delete_index: 'Удалить индекс',},+ check_constraint_actions: {+ title: 'Проверочное ограничение',+ expression: 'Выражение',+ delete: 'Удалить ограничение',+ },table_actions: {title: 'Действия',change_schema: 'Изменить схему',diff --git a/src/i18n/locales/te.ts b/src/i18n/locales/te.tsindex 00a86efd..a4af8778 100644--- a/src/i18n/locales/te.ts+++ b/src/i18n/locales/te.ts@@ -137,10 +137,12 @@ export const te: LanguageTranslation = {nullable: 'నల్వాలు?',primary_key: 'ప్రాథమిక కీ',indexes: 'ఇండెక్సులు',+ check_constraints: 'తనిఖీ పరిమితులు',comments: 'వ్యాఖ్యలు',no_comments: 'వ్యాఖ్యలు లేవు',add_field: 'ఫీల్డ్ జోడించు',add_index: 'ఇండెక్స్ జోడించు',+ add_check: 'తనిఖీ జోడించు',index_select_fields: 'ఫీల్డ్స్ ఎంచుకోండి',no_types_found: 'ప్రకృతులు కనుగొనబడలేదు',field_name: 'పేరు',@@ -167,6 +169,11 @@ export const te: LanguageTranslation = {index_type: 'ఇండెక్స్ రకం',delete_index: 'ఇండెక్స్ తొలగించు',},+ check_constraint_actions: {+ title: 'తనిఖీ పరిమితి',+ expression: 'వ్యక్తీకరణ',+ delete: 'పరిమితిని తొలగించు',+ },table_actions: {title: 'పట్టిక చర్యలు',change_schema: 'స్కీమాను మార్చు',diff --git a/src/i18n/locales/tr.ts b/src/i18n/locales/tr.tsindex e7c3f760..daf03538 100644--- a/src/i18n/locales/tr.ts+++ b/src/i18n/locales/tr.ts@@ -136,10 +136,12 @@ export const tr: LanguageTranslation = {nullable: 'Boş Bırakılabilir?',primary_key: 'Birincil Anahtar',indexes: 'İndeksler',+ check_constraints: 'Kontrol Kısıtlamaları',comments: 'Yorumlar',no_comments: 'Yorum yok',add_field: 'Alan Ekle',add_index: 'İndeks Ekle',+ add_check: 'Kontrol Ekle',index_select_fields: 'Alanları Seç',no_types_found: 'Tür bulunamadı',field_name: 'Ad',@@ -166,6 +168,11 @@ export const tr: LanguageTranslation = {index_type: 'İndeks Türü',delete_index: 'İndeksi Sil',},+ check_constraint_actions: {+ title: 'Kontrol Kısıtlaması',+ expression: 'İfade',+ delete: 'Kısıtlamayı Sil',+ },table_actions: {title: 'Tablo İşlemleri',change_schema: 'Şemayı Değiştir',diff --git a/src/i18n/locales/uk.ts b/src/i18n/locales/uk.tsindex d3ab9495..cf4b48a7 100644--- a/src/i18n/locales/uk.ts+++ b/src/i18n/locales/uk.ts@@ -135,10 +135,12 @@ export const uk: LanguageTranslation = {nullable: 'Може бути Null?',primary_key: 'Первинний ключ',indexes: 'Індекси',+ check_constraints: 'Перевірочні обмеження',comments: 'Коментарі',no_comments: 'Немає коментарів',add_field: 'Додати поле',add_index: 'Додати індекс',+ add_check: 'Додати перевірку',index_select_fields: 'Виберіть поля',no_types_found: 'Типи не знайдено',field_name: 'Назва поля',@@ -165,6 +167,11 @@ export const uk: LanguageTranslation = {index_type: 'Тип індексу',delete_index: 'Видалити індекс',},+ check_constraint_actions: {+ title: 'Перевірочне обмеження',+ expression: 'Вираз',+ delete: 'Видалити обмеження',+ },table_actions: {title: 'Дії з таблицею',change_schema: 'Змінити схему',diff --git a/src/i18n/locales/vi.ts b/src/i18n/locales/vi.tsindex e632de62..80d6d3e6 100644--- a/src/i18n/locales/vi.ts+++ b/src/i18n/locales/vi.ts@@ -136,10 +136,12 @@ export const vi: LanguageTranslation = {nullable: 'Có thể NULL?',primary_key: 'Khóa chính',indexes: 'Chỉ mục',+ check_constraints: 'Ràng buộc kiểm tra',comments: 'Bình luận',no_comments: 'Không có bình luận',add_field: 'Thêm trường',add_index: 'Thêm chỉ mục',+ add_check: 'Thêm kiểm tra',index_select_fields: 'Chọn trường',no_types_found: 'Không tìm thấy',field_name: 'Tên trường',@@ -166,6 +168,11 @@ export const vi: LanguageTranslation = {index_type: 'Loại chỉ mục',delete_index: 'Xóa chỉ mục',},+ check_constraint_actions: {+ title: 'Ràng buộc kiểm tra',+ expression: 'Biểu thức',+ delete: 'Xóa ràng buộc',+ },table_actions: {title: 'Hành động',change_schema: 'Thay đổi lược đồ',diff --git a/src/i18n/locales/zh_CN.ts b/src/i18n/locales/zh_CN.tsindex d584f96e..352a2667 100644--- a/src/i18n/locales/zh_CN.ts+++ b/src/i18n/locales/zh_CN.ts@@ -133,10 +133,12 @@ export const zh_CN: LanguageTranslation = {nullable: '可为空?',primary_key: '主键',indexes: '索引',+ check_constraints: '检查约束',comments: '注释',no_comments: '空',add_field: '添加字段',add_index: '添加索引',+ add_check: '添加检查',index_select_fields: '选择字段',no_types_found: '未找到类型',field_name: '名称',@@ -163,6 +165,11 @@ export const zh_CN: LanguageTranslation = {index_type: '索引类型',delete_index: '删除索引',},+ check_constraint_actions: {+ title: '检查约束',+ expression: '表达式',+ delete: '删除检查约束',+ },table_actions: {title: '表操作',change_schema: '更改模式',diff --git a/src/i18n/locales/zh_TW.ts b/src/i18n/locales/zh_TW.tsindex 29eb9ef7..288d0741 100644--- a/src/i18n/locales/zh_TW.ts+++ b/src/i18n/locales/zh_TW.ts@@ -133,10 +133,12 @@ export const zh_TW: LanguageTranslation = {nullable: '可為 NULL?',primary_key: '主鍵',indexes: '索引',+ check_constraints: '檢查約束',comments: '註解',no_comments: '無註解',add_field: '新增欄位',add_index: '新增索引',+ add_check: '新增檢查',index_select_fields: '選擇欄位',no_types_found: '未找到類型',field_name: '名稱',@@ -163,6 +165,11 @@ export const zh_TW: LanguageTranslation = {index_type: '索引類型',delete_index: '刪除索引',},+ check_constraint_actions: {+ title: '檢查約束',+ expression: '運算式',+ delete: '刪除檢查約束',+ },table_actions: {title: '表格操作',change_schema: '變更 Schema',diff --git a/src/lib/check-constraints/__tests__/check-constraints-validator.test.ts b/src/lib/check-constraints/__tests__/check-constraints-validator.test.tsnew file mode 100644index 00000000..9d983b32--- /dev/null+++ b/src/lib/check-constraints/__tests__/check-constraints-validator.test.ts@@ -0,0 +1,522 @@+import { describe, it, expect } from 'vitest';+import {+ validateCheckConstraint,+ validateCheckConstraintWithDetails,+} from '../check-constraints-validator';++describe('Check Constraint Validator', () => {+ describe('Valid expressions', () => {+ describe('Simple comparisons', () => {+ it('should validate simple less than', () => {+ expect(validateCheckConstraint('a < b')).toBe(true);+ });++ it('should validate simple greater than', () => {+ expect(validateCheckConstraint('a > b')).toBe(true);+ });++ it('should validate simple equal', () => {+ expect(validateCheckConstraint('a = b')).toBe(true);+ });++ it('should validate less than or equal', () => {+ expect(validateCheckConstraint('a <= b')).toBe(true);+ });++ it('should validate greater than or equal', () => {+ expect(validateCheckConstraint('a >= b')).toBe(true);+ });++ it('should validate not equal (!=)', () => {+ expect(validateCheckConstraint('a != b')).toBe(true);+ });++ it('should validate not equal (<>)', () => {+ expect(validateCheckConstraint('a <> b')).toBe(true);+ });++ it('should validate comparison with number', () => {+ expect(validateCheckConstraint('price > 0')).toBe(true);+ });++ it('should validate comparison with negative number', () => {+ expect(validateCheckConstraint('balance >= -100')).toBe(true);+ });++ it('should validate comparison with decimal', () => {+ expect(validateCheckConstraint('rate < 0.05')).toBe(true);+ });+ });++ describe('Compound expressions', () => {+ it('should validate AND expression', () => {+ expect(validateCheckConstraint('a > 0 AND b < 100')).toBe(true);+ });++ it('should validate OR expression', () => {+ expect(validateCheckConstraint('a > 0 OR a < -10')).toBe(true);+ });++ it('should validate complex AND/OR', () => {+ expect(+ validateCheckConstraint('a > 0 AND b < 100 OR c = 5')+ ).toBe(true);+ });++ it('should validate range check with AND', () => {+ expect(+ validateCheckConstraint('grade >= 0 AND grade <= 100')+ ).toBe(true);+ });++ it('should validate multiple conditions', () => {+ expect(+ validateCheckConstraint('age >= 18 AND age <= 120')+ ).toBe(true);+ });+ });++ describe('BETWEEN expressions', () => {+ it('should validate BETWEEN with numbers', () => {+ expect(+ validateCheckConstraint('quantity BETWEEN 1 AND 100')+ ).toBe(true);+ });++ it('should validate BETWEEN with identifiers', () => {+ expect(+ validateCheckConstraint('value BETWEEN min_val AND max_val')+ ).toBe(true);+ });++ it('should validate danger_level BETWEEN', () => {+ expect(+ validateCheckConstraint('danger_level BETWEEN 1 AND 10')+ ).toBe(true);+ });++ it('should validate day_of_week BETWEEN', () => {+ expect(+ validateCheckConstraint('day_of_week BETWEEN 1 AND 7')+ ).toBe(true);+ });+ });++ describe('IN expressions', () => {+ it('should validate IN with strings', () => {+ expect(+ validateCheckConstraint(+ "status IN ('active', 'inactive', 'pending')"+ )+ ).toBe(true);+ });++ it('should validate IN with numbers', () => {+ expect(+ validateCheckConstraint('priority IN (1, 2, 3, 4, 5)')+ ).toBe(true);+ });++ it('should validate IN with single value', () => {+ expect(validateCheckConstraint("type IN ('default')")).toBe(+ true+ );+ });++ it('should validate complex IN expression', () => {+ expect(+ validateCheckConstraint(+ "status IN ('scheduled', 'confirmed', 'in_progress', 'completed', 'cancelled', 'no_show')"+ )+ ).toBe(true);+ });+ });++ describe('IS NULL / IS NOT NULL', () => {+ it('should validate IS NULL', () => {+ expect(validateCheckConstraint('deleted_at IS NULL')).toBe(+ true+ );+ });++ it('should validate IS NOT NULL', () => {+ expect(validateCheckConstraint('name IS NOT NULL')).toBe(true);+ });+ });++ describe('LIKE expressions', () => {+ it('should validate LIKE with pattern', () => {+ expect(validateCheckConstraint("email LIKE '%@%'")).toBe(true);+ });++ it('should validate NOT LIKE', () => {+ expect(validateCheckConstraint("code NOT LIKE 'TEST%'")).toBe(+ true+ );+ });+ });++ describe('NOT IN and NOT BETWEEN', () => {+ it('should validate NOT IN', () => {+ expect(+ validateCheckConstraint(+ "status NOT IN ('deleted', 'archived')"+ )+ ).toBe(true);+ });++ it('should validate NOT BETWEEN', () => {+ expect(+ validateCheckConstraint('value NOT BETWEEN 0 AND 10')+ ).toBe(true);+ });+ });++ describe('Function calls', () => {+ it('should validate LENGTH function', () => {+ expect(validateCheckConstraint('LENGTH(name) > 0')).toBe(true);+ });++ it('should validate UPPER function comparison', () => {+ expect(validateCheckConstraint('UPPER(code) = code')).toBe(+ true+ );+ });++ it('should validate nested function calls', () => {+ expect(+ validateCheckConstraint('TRIM(UPPER(name)) = name')+ ).toBe(true);+ });++ it('should validate ISJSON function', () => {+ expect(validateCheckConstraint('ISJSON(metadata) = 1')).toBe(+ true+ );+ });++ it('should validate YEAR function', () => {+ expect(+ validateCheckConstraint('YEAR(created_at) >= 2020')+ ).toBe(true);+ });+ });++ describe('Arithmetic expressions', () => {+ it('should validate addition', () => {+ expect(validateCheckConstraint('a + b < 100')).toBe(true);+ });++ it('should validate subtraction', () => {+ expect(+ validateCheckConstraint('end_date - start_date > 0')+ ).toBe(true);+ });++ it('should validate multiplication', () => {+ expect(+ validateCheckConstraint('quantity * price < 10000')+ ).toBe(true);+ });++ it('should validate division', () => {+ expect(validateCheckConstraint('total / count > 0')).toBe(true);+ });++ it('should validate modulo', () => {+ expect(validateCheckConstraint('id % 2 = 0')).toBe(true);+ });+ });++ describe('Parenthesized expressions', () => {+ it('should validate simple parentheses', () => {+ expect(validateCheckConstraint('(a < b)')).toBe(true);+ });++ it('should validate nested parentheses', () => {+ expect(validateCheckConstraint('((a < b) AND (c > d))')).toBe(+ true+ );+ });++ it('should validate grouped OR with AND', () => {+ expect(+ validateCheckConstraint('(a = 1 OR a = 2) AND b > 0')+ ).toBe(true);+ });+ });++ describe('Quoted identifiers', () => {+ it('should validate double-quoted identifier', () => {+ expect(validateCheckConstraint('"column name" > 0')).toBe(true);+ });++ it('should validate backtick-quoted identifier (MySQL)', () => {+ expect(validateCheckConstraint('`column name` > 0')).toBe(true);+ });++ it('should validate bracket-quoted identifier (SQL Server)', () => {+ expect(validateCheckConstraint('[price] >= 0')).toBe(true);+ });++ it('should validate SQL Server style with multiple brackets', () => {+ expect(+ validateCheckConstraint('[grade] >= 0 AND [grade] <= 100')+ ).toBe(true);+ });+ });++ describe('NOT expressions', () => {+ it('should validate NOT with parentheses', () => {+ expect(validateCheckConstraint('NOT (a = b)')).toBe(true);+ });++ it('should validate NOT with comparison', () => {+ expect(validateCheckConstraint('NOT deleted')).toBe(true);+ });+ });++ describe('Boolean literals', () => {+ it('should validate TRUE', () => {+ expect(validateCheckConstraint('is_active = TRUE')).toBe(true);+ });++ it('should validate FALSE', () => {+ expect(validateCheckConstraint('is_deleted = FALSE')).toBe(+ true+ );+ });+ });++ describe('Type casting (PostgreSQL)', () => {+ it('should validate PostgreSQL type cast', () => {+ expect(validateCheckConstraint('value::integer > 0')).toBe(+ true+ );+ });+ });++ describe('Real-world examples from codebase', () => {+ it('should validate price >= 0', () => {+ expect(validateCheckConstraint('price >= 0')).toBe(true);+ });++ it('should validate enchantment_charges >= 0', () => {+ expect(+ validateCheckConstraint('enchantment_charges >= 0')+ ).toBe(true);+ });++ it('should validate quantity > 0', () => {+ expect(validateCheckConstraint('quantity > 0')).toBe(true);+ });++ it('should validate mana_cost > 0', () => {+ expect(validateCheckConstraint('mana_cost > 0')).toBe(true);+ });++ it('should validate enchantment_level BETWEEN 0 AND 10', () => {+ expect(+ validateCheckConstraint(+ 'enchantment_level BETWEEN 0 AND 10'+ )+ ).toBe(true);+ });++ it('should validate period_end >= period_start', () => {+ expect(+ validateCheckConstraint('period_end >= period_start')+ ).toBe(true);+ });++ it('should validate total_cents >= 0', () => {+ expect(validateCheckConstraint('total_cents >= 0')).toBe(true);+ });++ it('should validate amount_cents > 0', () => {+ expect(validateCheckConstraint('amount_cents > 0')).toBe(true);+ });+ });+ });++ describe('Invalid expressions', () => {+ describe('Incomplete expressions', () => {+ it('should reject expression with missing right operand', () => {+ expect(validateCheckConstraint('a<')).toBe(false);+ });++ it('should reject expression with missing left operand', () => {+ expect(validateCheckConstraint('<b')).toBe(false);+ });++ it('should reject expression with missing operand after AND', () => {+ expect(validateCheckConstraint('a > 0 AND')).toBe(false);+ });++ it('should reject expression with missing operand after OR', () => {+ expect(validateCheckConstraint('a > 0 OR')).toBe(false);+ });++ it('should reject expression ending with operator', () => {+ expect(validateCheckConstraint('price >')).toBe(false);+ });++ it('should reject expression ending with >=', () => {+ expect(validateCheckConstraint('value >=')).toBe(false);+ });+ });++ describe('Invalid identifiers', () => {+ it('should reject identifier starting with digit', () => {+ expect(validateCheckConstraint('a < 2b')).toBe(false);+ });++ it('should reject number followed by letters without space', () => {+ expect(validateCheckConstraint('a < 123abc')).toBe(false);+ });+ });++ describe('Unbalanced parentheses', () => {+ it('should reject missing closing parenthesis', () => {+ expect(validateCheckConstraint('(a < b')).toBe(false);+ });++ it('should reject missing opening parenthesis', () => {+ expect(validateCheckConstraint('a < b)')).toBe(false);+ });++ it('should reject nested unbalanced parentheses', () => {+ expect(validateCheckConstraint('((a < b)')).toBe(false);+ });++ it('should reject function with missing closing paren', () => {+ expect(validateCheckConstraint('LENGTH(name > 0')).toBe(false);+ });+ });++ describe('Empty expressions', () => {+ it('should reject empty string', () => {+ expect(validateCheckConstraint('')).toBe(false);+ });++ it('should reject whitespace only', () => {+ expect(validateCheckConstraint(' ')).toBe(false);+ });++ it('should reject tabs and newlines only', () => {+ expect(validateCheckConstraint('\t\n')).toBe(false);+ });+ });++ describe('Invalid operator placement', () => {+ it('should reject double operators', () => {+ expect(validateCheckConstraint('a < > b')).toBe(false);+ });++ it('should reject AND at start', () => {+ expect(validateCheckConstraint('AND a > 0')).toBe(false);+ });++ it('should reject OR at start', () => {+ expect(validateCheckConstraint('OR a > 0')).toBe(false);+ });+ });++ describe('Invalid BETWEEN', () => {+ it('should reject BETWEEN without value before', () => {+ expect(validateCheckConstraint('BETWEEN 1 AND 10')).toBe(false);+ });+ });++ describe('Invalid IN', () => {+ it('should reject IN without value before', () => {+ expect(validateCheckConstraint("IN ('a', 'b')")).toBe(false);+ });+ });++ describe('Invalid IS', () => {+ it('should reject IS without value before', () => {+ expect(validateCheckConstraint('IS NULL')).toBe(false);+ });+ });+ });++ describe('validateCheckConstraintWithDetails', () => {+ it('should return error details for invalid expression', () => {+ const result = validateCheckConstraintWithDetails('a<');+ expect(result.isValid).toBe(false);+ expect(result.error).toBeDefined();+ expect(result.error).toContain('incomplete');+ });++ it('should return error details for unbalanced parentheses', () => {+ const result = validateCheckConstraintWithDetails('(a < b');+ expect(result.isValid).toBe(false);+ expect(result.error).toContain('parenthes');+ });++ it('should return error details for empty expression', () => {+ const result = validateCheckConstraintWithDetails('');+ expect(result.isValid).toBe(false);+ expect(result.error).toContain('empty');+ });++ it('should return valid result for good expression', () => {+ const result = validateCheckConstraintWithDetails('a < b');+ expect(result.isValid).toBe(true);+ expect(result.error).toBeUndefined();+ });++ it('should return position for certain errors', () => {+ const result = validateCheckConstraintWithDetails('a < b)');+ expect(result.isValid).toBe(false);+ expect(result.position).toBeDefined();+ });+ });++ describe('Edge cases', () => {+ it('should handle underscores in identifiers', () => {+ expect(validateCheckConstraint('my_column > 0')).toBe(true);+ });++ it('should handle multiple underscores', () => {+ expect(validateCheckConstraint('my__very__long__column > 0')).toBe(+ true+ );+ });++ it('should handle $ in identifier', () => {+ expect(validateCheckConstraint('col$1 > 0')).toBe(true);+ });++ it('should handle scientific notation', () => {+ expect(validateCheckConstraint('value < 1e10')).toBe(true);+ });++ it('should handle negative scientific notation', () => {+ expect(validateCheckConstraint('value > 1e-5')).toBe(true);+ });++ it('should handle string with escaped quote', () => {+ expect(validateCheckConstraint("name = 'O''Brien'")).toBe(true);+ });++ it('should handle empty parentheses in function call', () => {+ expect(validateCheckConstraint('NOW() > created_at')).toBe(true);+ });++ it('should handle comparison between two columns', () => {+ expect(validateCheckConstraint('end_date >= start_date')).toBe(+ true+ );+ });++ it('should handle just an identifier (boolean column)', () => {+ expect(validateCheckConstraint('is_valid')).toBe(true);+ });++ it('should handle NOT with identifier', () => {+ expect(validateCheckConstraint('NOT is_deleted')).toBe(true);+ });+ });+});diff --git a/src/lib/check-constraints/check-constraints-validator.ts b/src/lib/check-constraints/check-constraints-validator.tsnew file mode 100644index 00000000..f3ec796b--- /dev/null+++ b/src/lib/check-constraints/check-constraints-validator.ts@@ -0,0 +1,616 @@+/**+ * SQL Check Constraint Expression Validator+ *+ * Validates SQL check constraint expressions for syntactic correctness.+ * This is a syntax validator - it doesn't verify that column names exist.+ *+ * Valid examples:+ * - "price > 0"+ * - "age >= 18 AND age <= 120"+ * - "status IN ('active', 'inactive')"+ * - "quantity BETWEEN 1 AND 100"+ *+ * Invalid examples:+ * - "a<" (incomplete expression)+ * - "a<2b" (invalid identifier starting with digit)+ * - "(a < b" (unbalanced parentheses)+ */++// Token types for the lexer+type TokenType =+ | 'IDENTIFIER' // column names, table names+ | 'NUMBER' // numeric literals+ | 'STRING' // 'string' or "string"+ | 'OPERATOR' // comparison and arithmetic operators+ | 'LOGICAL' // AND, OR, NOT+ | 'KEYWORD' // BETWEEN, IN, IS, NULL, LIKE, TRUE, FALSE, ISNULL, etc.+ | 'LPAREN' // (+ | 'RPAREN' // )+ | 'LBRACKET' // [ (SQL Server style)+ | 'RBRACKET' // ] (SQL Server style)+ | 'COMMA' // ,+ | 'UNKNOWN'; // unrecognized token++interface Token {+ type: TokenType;+ value: string;+ position: number;+}++// SQL keywords used in check constraints+const SQL_KEYWORDS = new Set([+ 'BETWEEN',+ 'IN',+ 'IS',+ 'NULL',+ 'NOT',+ 'LIKE',+ 'ILIKE',+ 'TRUE',+ 'FALSE',+ 'UNKNOWN',+ 'ESCAPE',+ 'SIMILAR',+ 'TO',+ 'ANY',+ 'ALL',+ 'SOME',+ 'EXISTS',+ 'CASE',+ 'WHEN',+ 'THEN',+ 'ELSE',+ 'END',+ 'CAST',+ 'AS',+ 'COLLATE',+]);++// Logical operators+const LOGICAL_OPERATORS = new Set(['AND', 'OR', 'NOT']);++// Comparison operators (including multi-char)+const COMPARISON_OPERATORS = [+ '<>',+ '!=',+ '<=',+ '>=',+ '::',+ '<',+ '>',+ '=',+ '+',+ '-',+ '*',+ '/',+ '%',+ '||',+ '~',+ '!~',+ '~*',+ '!~*',+];++/**+ * Tokenizes a SQL check constraint expression+ */+function tokenize(expression: string): Token[] {+ const tokens: Token[] = [];+ let i = 0;++ while (i < expression.length) {+ // Skip whitespace+ if (/\s/.test(expression[i])) {+ i++;+ continue;+ }++ const startPos = i;++ // Single-quoted string+ if (expression[i] === "'") {+ let value = "'";+ i++;+ while (i < expression.length) {+ if (expression[i] === "'" && expression[i + 1] === "'") {+ // Escaped quote+ value += "''";+ i += 2;+ } else if (expression[i] === "'") {+ value += "'";+ i++;+ break;+ } else {+ value += expression[i];+ i++;+ }+ }+ tokens.push({ type: 'STRING', value, position: startPos });+ continue;+ }++ // Double-quoted identifier (standard SQL)+ if (expression[i] === '"') {+ let value = '"';+ i++;+ while (i < expression.length && expression[i] !== '"') {+ value += expression[i];+ i++;+ }+ if (i < expression.length) {+ value += '"';+ i++;+ }+ tokens.push({ type: 'IDENTIFIER', value, position: startPos });+ continue;+ }++ // Backtick-quoted identifier (MySQL style)+ if (expression[i] === '`') {+ let value = '`';+ i++;+ while (i < expression.length && expression[i] !== '`') {+ value += expression[i];+ i++;+ }+ if (i < expression.length) {+ value += '`';+ i++;+ }+ tokens.push({ type: 'IDENTIFIER', value, position: startPos });+ continue;+ }++ // SQL Server bracket-quoted identifier [column]+ if (expression[i] === '[') {+ let value = '[';+ i++;+ while (i < expression.length && expression[i] !== ']') {+ value += expression[i];+ i++;+ }+ if (i < expression.length) {+ value += ']';+ i++;+ }+ tokens.push({ type: 'IDENTIFIER', value, position: startPos });+ continue;+ }++ // Parentheses+ if (expression[i] === '(') {+ tokens.push({ type: 'LPAREN', value: '(', position: startPos });+ i++;+ continue;+ }+ if (expression[i] === ')') {+ tokens.push({ type: 'RPAREN', value: ')', position: startPos });+ i++;+ continue;+ }++ // Comma+ if (expression[i] === ',') {+ tokens.push({ type: 'COMMA', value: ',', position: startPos });+ i++;+ continue;+ }++ // Check for multi-character operators first+ let foundOperator = false;+ for (const op of COMPARISON_OPERATORS) {+ if (expression.substring(i, i + op.length) === op) {+ tokens.push({+ type: 'OPERATOR',+ value: op,+ position: startPos,+ });+ i += op.length;+ foundOperator = true;+ break;+ }+ }+ if (foundOperator) continue;++ // Number (including decimals and negative numbers handled by context)+ if (/[0-9]/.test(expression[i])) {+ let value = '';+ while (+ i < expression.length &&+ /[0-9.]/.test(expression[i]) &&+ !(expression[i] === '.' && value.includes('.'))+ ) {+ value += expression[i];+ i++;+ }+ // Handle scientific notation+ if (+ i < expression.length &&+ (expression[i] === 'e' || expression[i] === 'E')+ ) {+ value += expression[i];+ i++;+ if (+ i < expression.length &&+ (expression[i] === '+' || expression[i] === '-')+ ) {+ value += expression[i];+ i++;+ }+ while (i < expression.length && /[0-9]/.test(expression[i])) {+ value += expression[i];+ i++;+ }+ }+ tokens.push({ type: 'NUMBER', value, position: startPos });+ continue;+ }++ // Identifier or keyword (starts with letter or underscore)+ if (/[a-zA-Z_]/.test(expression[i])) {+ let value = '';+ while (+ i < expression.length &&+ /[a-zA-Z0-9_$]/.test(expression[i])+ ) {+ value += expression[i];+ i++;+ }+ const upperValue = value.toUpperCase();+ if (LOGICAL_OPERATORS.has(upperValue)) {+ tokens.push({+ type: 'LOGICAL',+ value: upperValue,+ position: startPos,+ });+ } else if (SQL_KEYWORDS.has(upperValue)) {+ tokens.push({+ type: 'KEYWORD',+ value: upperValue,+ position: startPos,+ });+ } else {+ tokens.push({ type: 'IDENTIFIER', value, position: startPos });+ }+ continue;+ }++ // Unknown character+ tokens.push({+ type: 'UNKNOWN',+ value: expression[i],+ position: startPos,+ });+ i++;+ }++ return tokens;+}++/**+ * Validation result with detailed error information+ */+export interface CheckConstraintValidationResult {+ isValid: boolean;+ error?: string;+ position?: number;+}++/**+ * Validates a SQL check constraint expression.+ *+ * @param expression - The check constraint expression to validate (e.g., "price > 0")+ * @returns true if the expression is syntactically valid, false otherwise+ */+export function validateCheckConstraint(expression: string): boolean {+ return validateCheckConstraintWithDetails(expression).isValid;+}++/**+ * Validates a SQL check constraint expression with detailed error information.+ *+ * @param expression - The check constraint expression to validate+ * @returns Validation result with error details if invalid+ */+export function validateCheckConstraintWithDetails(+ expression: string+): CheckConstraintValidationResult {+ // Empty or whitespace-only expressions are invalid+ if (!expression || !expression.trim()) {+ return { isValid: false, error: 'Expression cannot be empty' };+ }++ const trimmed = expression.trim();++ // Tokenize the expression+ const tokens = tokenize(trimmed);++ // Check for unknown tokens (except handling edge cases)+ for (const token of tokens) {+ if (token.type === 'UNKNOWN') {+ return {+ isValid: false,+ error: `Unexpected character '${token.value}'`,+ position: token.position,+ };+ }+ }++ // Empty token list after trimming+ if (tokens.length === 0) {+ return { isValid: false, error: 'Expression cannot be empty' };+ }++ // Check for balanced parentheses+ let parenDepth = 0;+ for (const token of tokens) {+ if (token.type === 'LPAREN') parenDepth++;+ if (token.type === 'RPAREN') parenDepth--;+ if (parenDepth < 0) {+ return {+ isValid: false,+ error: 'Unbalanced parentheses: unexpected closing parenthesis',+ position: token.position,+ };+ }+ }+ if (parenDepth !== 0) {+ return {+ isValid: false,+ error: 'Unbalanced parentheses: missing closing parenthesis',+ };+ }++ // Validate token sequence for complete expressions+ const validationResult = validateTokenSequence(tokens);+ if (!validationResult.isValid) {+ return validationResult;+ }++ return { isValid: true };+}++/**+ * Validates that the token sequence forms a valid expression.+ * Checks that operators have operands on both sides, etc.+ */+function validateTokenSequence(+ tokens: Token[]+): CheckConstraintValidationResult {+ if (tokens.length === 0) {+ return { isValid: false, error: 'Expression cannot be empty' };+ }++ // Track context for validation+ let expectingOperand = true; // Start expecting an operand+ let lastToken: Token | null = null;++ for (let i = 0; i < tokens.length; i++) {+ const token = tokens[i];++ switch (token.type) {+ case 'IDENTIFIER':+ case 'NUMBER':+ case 'STRING':+ if (!expectingOperand && lastToken?.type !== 'KEYWORD') {+ // Allow identifiers after certain keywords like IS, AS, CAST+ if (+ lastToken?.type === 'IDENTIFIER' ||+ lastToken?.type === 'NUMBER' ||+ lastToken?.type === 'STRING'+ ) {+ return {+ isValid: false,+ error: `Unexpected ${token.type.toLowerCase()} '${token.value}' - expected an operator`,+ position: token.position,+ };+ }+ }+ expectingOperand = false;+ break;++ case 'OPERATOR':+ // Unary minus/plus before numbers or identifiers is OK at start or after operator/lparen+ if (+ (token.value === '-' || token.value === '+') &&+ expectingOperand+ ) {+ // This is a unary operator, still expecting an operand+ break;+ }+ // Type cast operator :: doesn't require operand after+ if (token.value === '::') {+ if (expectingOperand) {+ return {+ isValid: false,+ error: `Operator '${token.value}' requires a value before it`,+ position: token.position,+ };+ }+ expectingOperand = true;+ break;+ }+ if (expectingOperand) {+ return {+ isValid: false,+ error: `Operator '${token.value}' requires a value before it`,+ position: token.position,+ };+ }+ expectingOperand = true;+ break;++ case 'LOGICAL':+ if (token.value === 'NOT') {+ // NOT can appear:+ // 1. Before an operand: NOT(a = b), NOT deleted+ // 2. After IS: a IS NOT NULL+ // 3. Before LIKE/IN/BETWEEN: a NOT LIKE '%x%', a NOT IN (1,2), a NOT BETWEEN 1 AND 10+ // In case 3, NOT comes after a complete operand but is valid+ // We'll allow it and keep expectingOperand = true+ expectingOperand = true;+ } else {+ // AND, OR require operands on both sides+ if (expectingOperand) {+ return {+ isValid: false,+ error: `Logical operator '${token.value}' requires a value before it`,+ position: token.position,+ };+ }+ expectingOperand = true;+ }+ break;++ case 'KEYWORD':+ // Handle special keywords+ if (+ token.value === 'NULL' ||+ token.value === 'TRUE' ||+ token.value === 'FALSE'+ ) {+ expectingOperand = false;+ } else if (token.value === 'NOT') {+ // NOT as keyword (e.g., IS NOT NULL)+ expectingOperand = true;+ } else if (+ token.value === 'IS' ||+ token.value === 'IN' ||+ token.value === 'LIKE' ||+ token.value === 'ILIKE'+ ) {+ // These keywords require a value before them, BUT+ // they can also come after NOT (e.g., "a NOT LIKE 'x'", "a NOT IN (1,2)")+ if (expectingOperand && lastToken?.value !== 'NOT') {+ return {+ isValid: false,+ error: `Keyword '${token.value}' requires a value before it`,+ position: token.position,+ };+ }+ expectingOperand = true;+ } else if (token.value === 'BETWEEN') {+ // BETWEEN requires a value before it, or can come after NOT+ if (expectingOperand && lastToken?.value !== 'NOT') {+ return {+ isValid: false,+ error: `Keyword 'BETWEEN' requires a value before it`,+ position: token.position,+ };+ }+ expectingOperand = true;+ } else if (+ token.value === 'CASE' ||+ token.value === 'CAST' ||+ token.value === 'EXISTS'+ ) {+ // These can start expressions+ expectingOperand = false;+ } else if (+ token.value === 'WHEN' ||+ token.value === 'THEN' ||+ token.value === 'ELSE' ||+ token.value === 'END'+ ) {+ // CASE-related keywords+ if (token.value === 'END') {+ expectingOperand = false;+ } else {+ expectingOperand = true;+ }+ } else if (token.value === 'AS' || token.value === 'TO') {+ // AS in CAST, TO in SIMILAR TO+ expectingOperand = true;+ } else {+ // Other keywords - generally need an operand after+ expectingOperand = true;+ }+ break;++ case 'LPAREN':+ // Parenthesis can follow an identifier (function call) or start a group+ if (+ lastToken?.type === 'IDENTIFIER' ||+ lastToken?.value === 'IN' ||+ lastToken?.value === 'EXISTS'+ ) {+ // Function call or IN list - still expecting operand+ expectingOperand = true;+ } else {+ // Grouping parenthesis+ expectingOperand = true;+ }+ break;++ case 'RPAREN':+ // After closing paren, we have a complete subexpression+ if (expectingOperand && lastToken?.type !== 'LPAREN') {+ // Empty parens () are only valid for function calls+ // But we already validated for balance, so this might be OK+ }+ expectingOperand = false;+ break;++ case 'COMMA':+ // Commas separate list items (e.g., IN (..., ...))+ if (expectingOperand) {+ return {+ isValid: false,+ error: 'Unexpected comma - expected a value',+ position: token.position,+ };+ }+ expectingOperand = true;+ break;+ }++ lastToken = token;+ }++ // At the end, we should not be expecting an operand (expression should be complete)+ if (expectingOperand && lastToken?.type !== 'RPAREN') {+ // Exception: expression ending with ) is OK+ // Find the last non-RPAREN token+ let lastNonParen: Token | undefined;+ for (let j = tokens.length - 1; j >= 0; j--) {+ if (tokens[j].type !== 'RPAREN') {+ lastNonParen = tokens[j];+ break;+ }+ }+ if (lastNonParen) {+ if (lastNonParen.type === 'OPERATOR') {+ return {+ isValid: false,+ error: `Expression incomplete - operator '${lastNonParen.value}' requires a value after it`,+ position: lastNonParen.position,+ };+ }+ if (+ lastNonParen.type === 'LOGICAL' &&+ lastNonParen.value !== 'NOT'+ ) {+ return {+ isValid: false,+ error: `Expression incomplete - '${lastNonParen.value}' requires a value after it`,+ position: lastNonParen.position,+ };+ }+ if (+ lastNonParen.type === 'KEYWORD' &&+ lastNonParen.value !== 'NULL' &&+ lastNonParen.value !== 'TRUE' &&+ lastNonParen.value !== 'FALSE' &&+ lastNonParen.value !== 'END'+ ) {+ return {+ isValid: false,+ error: `Expression incomplete - '${lastNonParen.value}' requires a value after it`,+ position: lastNonParen.position,+ };+ }+ }+ }++ return { isValid: true };+}diff --git a/src/lib/data/import-metadata/import/tables.ts b/src/lib/data/import-metadata/import/tables.tsindex 939404e2..7b346820 100644--- a/src/lib/data/import-metadata/import/tables.ts+++ b/src/lib/data/import-metadata/import/tables.ts@@ -1,4 +1,4 @@-import type { DBIndex, DBTable } from '@/lib/domain';+import type { DBCheckConstraint, DBIndex, DBTable } from '@/lib/domain';import {DatabaseType,generateTableKey,@@ -6,6 +6,7 @@ import {} from '@/lib/domain';import type { DatabaseMetadata } from '../metadata-types/database-metadata';import type { TableInfo } from '../metadata-types/table-info';+import type { CheckConstraintInfo } from '../metadata-types/check-constraint-info';import { createAggregatedIndexes } from '../metadata-types/index-info';import {decodeBase64ToUtf16LE,@@ -51,6 +52,7 @@ export const createTablesFromMetadata = ({columns,indexes,views: views,+ check_constraints: checkConstraints,} = databaseMetadata;// Pre-compute view names for faster lookup if there are views@@ -117,6 +119,21 @@ export const createTablesFromMetadata = ({primaryKeysByTable.get(key)!.push(pk);});+ // Group check constraints by table+ const checkConstraintsByTable = new Map<string, CheckConstraintInfo[]>();+ if (checkConstraints) {+ checkConstraints.forEach((cc) => {+ const key = generateTableKey({+ schemaName: cc.schema,+ tableName: cc.table,+ });+ if (!checkConstraintsByTable.has(key)) {+ checkConstraintsByTable.set(key, []);+ }+ checkConstraintsByTable.get(key)!.push(cc);+ });+ }+const result = tableInfos.map((tableInfo: TableInfo) => {const tableSchema = schemaNameToDomainSchemaName(tableInfo.schema);const tableKey = generateTableKey({@@ -204,6 +221,17 @@ export const createTablesFromMetadata = ({const isView = viewNamesSet.has(viewKey);const isMaterializedView = materializedViewNamesSet.has(viewKey);+ // Convert check constraints for this table+ const tableCheckConstraints = checkConstraintsByTable.get(tableKey);+ const dbCheckConstraints: DBCheckConstraint[] | undefined =+ tableCheckConstraints && tableCheckConstraints.length > 0+ ? tableCheckConstraints.map((cc) => ({+ id: generateId(),+ expression: cc.expression,+ createdAt: Date.now(),+ }))+ : undefined;+// Initial random positions; these will be adjusted laterreturn {id: generateId(),@@ -213,6 +241,7 @@ export const createTablesFromMetadata = ({y: Math.random() * 800, // Placeholder Yfields,indexes: dbIndexes,+ checkConstraints: dbCheckConstraints,color: isMaterializedView? materializedViewColor: isViewdiff --git a/src/lib/data/import-metadata/metadata-types/check-constraint-info.ts b/src/lib/data/import-metadata/metadata-types/check-constraint-info.tsnew file mode 100644index 00000000..6c4649a7--- /dev/null+++ b/src/lib/data/import-metadata/metadata-types/check-constraint-info.ts@@ -0,0 +1,14 @@+import { z } from 'zod';++export interface CheckConstraintInfo {+ schema: string;+ table: string;+ expression: string;+}++export const CheckConstraintInfoSchema: z.ZodType<CheckConstraintInfo> =+ z.object({+ schema: z.string(),+ table: z.string(),+ expression: z.string(),+ });diff --git a/src/lib/data/import-metadata/metadata-types/database-metadata.ts b/src/lib/data/import-metadata/metadata-types/database-metadata.tsindex e4868722..9cab57ae 100644--- a/src/lib/data/import-metadata/metadata-types/database-metadata.ts+++ b/src/lib/data/import-metadata/metadata-types/database-metadata.ts@@ -1,4 +1,8 @@import { z } from 'zod';+import {+ CheckConstraintInfoSchema,+ type CheckConstraintInfo,+} from './check-constraint-info';import { ForeignKeyInfoSchema, type ForeignKeyInfo } from './foreign-key-info';import { PrimaryKeyInfoSchema, type PrimaryKeyInfo } from './primary-key-info';import { ColumnInfoSchema, type ColumnInfo } from './column-info';@@ -17,6 +21,7 @@ export interface DatabaseMetadata {indexes: IndexInfo[];tables: TableInfo[];views: ViewInfo[];+ check_constraints?: CheckConstraintInfo[];custom_types?: DBCustomTypeInfo[];database_name: string;version: string;@@ -29,6 +34,7 @@ export const DatabaseMetadataSchema: z.ZodType<DatabaseMetadata> = z.object({indexes: z.array(IndexInfoSchema),tables: z.array(TableInfoSchema),views: z.array(ViewInfoSchema),+ check_constraints: z.array(CheckConstraintInfoSchema).optional(),custom_types: z.array(DBCustomTypeInfoSchema).optional(),database_name: z.string(),version: z.string(),diff --git a/src/lib/data/import-metadata/scripts/postgres-script.ts b/src/lib/data/import-metadata/scripts/postgres-script.tsindex e4d35e1f..6a30bce0 100644--- a/src/lib/data/import-metadata/scripts/postgres-script.ts+++ b/src/lib/data/import-metadata/scripts/postgres-script.ts@@ -356,6 +356,32 @@ cols AS (GROUP BY n.nspname, t.typname) AS comp) AS all_types+), check_constraints AS (+ SELECT array_to_string(array_agg(CONCAT('{"schema":"', replace(schema_name, '"', ''), '"',+ ',"table":"', replace(table_name, '"', ''), '"',+ ',"expression":"', replace(replace(check_expr, '"', '\\"'), E'\\n', ' '),+ '"}')), ',') AS check_constraints_metadata+ FROM (+ SELECT+ n.nspname AS schema_name,+ CASE+ WHEN position('.' in c.conrelid::regclass::text) > 0+ THEN split_part(c.conrelid::regclass::text, '.', 2)+ ELSE c.conrelid::regclass::text+ END AS table_name,+ substring(pg_get_constraintdef(c.oid) FROM 'CHECK \\((.*)\\)') AS check_expr+ FROM pg_constraint c+ JOIN pg_class cl ON cl.oid = c.conrelid+ JOIN pg_namespace n ON n.oid = cl.relnamespace+ WHERE c.contype = 'c'+ AND n.nspname NOT IN ('information_schema', 'pg_catalog')${+ databaseEdition === DatabaseEdition.POSTGRESQL_TIMESCALE+ ? timescaleFilters+ : databaseEdition === DatabaseEdition.POSTGRESQL_SUPABASE+ ? supabaseFilters+ : ''+ }+ ) AS chk)SELECT CONCAT('{ "fk_info": [', COALESCE(fk_metadata, ''),'], "pk_info": [', COALESCE(pk_metadata, ''),@@ -363,10 +389,11 @@ SELECT CONCAT('{ "fk_info": [', COALESCE(fk_metadata, ''),'], "indexes": [', COALESCE(indexes_metadata, ''),'], "tables":[', COALESCE(tbls_metadata, ''),'], "views":[', COALESCE(views_metadata, ''),+ '], "check_constraints": [', COALESCE(check_constraints_metadata, ''),'], "custom_types": [', COALESCE(custom_types_metadata, ''),'], "database_name": "', CURRENT_DATABASE(), '', '", "version": "', '','"}') AS metadata_json_to_import-FROM fk_info${databaseEdition ? '_' + databaseEdition : ''}, pk_info, cols, indexes_metadata, tbls, config, views, custom_types;+FROM fk_info${databaseEdition ? '_' + databaseEdition : ''}, pk_info, cols, indexes_metadata, tbls, config, views, check_constraints, custom_types;`;const psqlPreCommand = `# *** Remember to change! (HOST_NAME, PORT, USER_NAME, DATABASE_NAME) *** \n`;diff --git a/src/lib/data/import-metadata/scripts/sqlserver-script.ts b/src/lib/data/import-metadata/scripts/sqlserver-script.tsindex 20c20176..5edfb305 100644--- a/src/lib/data/import-metadata/scripts/sqlserver-script.ts+++ b/src/lib/data/import-metadata/scripts/sqlserver-script.ts@@ -184,6 +184,24 @@ views AS (CROSS APPLY(SELECT CONVERT(VARBINARY(MAX), m.definition) AS DefinitionBinary) AS binWHERE s.name LIKE '%'+),+check_constraints AS (+ SELECT+ JSON_QUERY(+ N'[' + STRING_AGG(+ CONVERT(nvarchar(max),+ JSON_QUERY(N'{+ "schema": "' + STRING_ESCAPE(COALESCE(REPLACE(s.name, '"', ''), ''), 'json') ++ '", "table": "' + STRING_ESCAPE(COALESCE(REPLACE(t.name, '"', ''), ''), 'json') ++ '", "expression": "' + STRING_ESCAPE(COALESCE(REPLACE(REPLACE(cc.definition, '"', '\\"'), CHAR(10), ' '), ''), 'json') ++ '"}') COLLATE DATABASE_DEFAULT+ ), N','+ ) + N']'+ ) AS all_check_constraints_json+ FROM sys.check_constraints cc+ JOIN sys.tables t ON cc.parent_object_id = t.object_id+ JOIN sys.schemas s ON t.schema_id = s.schema_id+ WHERE s.name LIKE '%')SELECT JSON_QUERY(N'{@@ -193,6 +211,7 @@ SELECT JSON_QUERY(', "indexes": ' + ISNULL((SELECT cast(all_indexes_json as nvarchar(max)) FROM indexes), N'[]') +', "tables": ' + ISNULL((SELECT cast(all_tables_json as nvarchar(max)) FROM tbls), N'[]') +', "views": ' + ISNULL((SELECT cast(all_views_json as nvarchar(max)) FROM views), N'[]') ++ ', "check_constraints": ' + ISNULL((SELECT cast(all_check_constraints_json as nvarchar(max)) FROM check_constraints), N'[]') +', "database_name": "' + STRING_ESCAPE(DB_NAME(), 'json') +'", "version": ""}'@@ -396,6 +415,26 @@ views AS (s.name LIKE '%'FOR XML PATH(''), TYPE).value('.', 'NVARCHAR(MAX)'), 1, 1, '')) + ']' AS all_views_json+),+check_constraints AS (+ SELECT+ '[' + ISNULL(+ STUFF((+ SELECT ',' ++ CONVERT(nvarchar(max),+ JSON_QUERY(N'{+ "schema": "' + STRING_ESCAPE(COALESCE(REPLACE(s.name, '"', ''), ''), 'json') ++ '", "table": "' + STRING_ESCAPE(COALESCE(REPLACE(t.name, '"', ''), ''), 'json') ++ '", "expression": "' + STRING_ESCAPE(COALESCE(REPLACE(REPLACE(cc.definition, '"', '\\"'), CHAR(10), ' '), ''), 'json') ++ '"}') COLLATE DATABASE_DEFAULT+ )+ FROM sys.check_constraints cc+ JOIN sys.tables t ON cc.parent_object_id = t.object_id+ JOIN sys.schemas s ON t.schema_id = s.schema_id+ WHERE s.name LIKE '%'+ FOR XML PATH('')+ ), 1, 1, ''), '')+ + N']' AS all_check_constraints_json)SELECT JSON_QUERY(N'{@@ -405,6 +444,7 @@ SELECT JSON_QUERY(', "indexes": ' + ISNULL((SELECT cast(all_indexes_json as nvarchar(max)) FROM indexes), N'[]') +', "tables": ' + ISNULL((SELECT cast(all_objects_json as nvarchar(max)) FROM tbls), N'[]') +', "views": ' + ISNULL((SELECT cast(all_views_json as nvarchar(max)) FROM views), N'[]') ++ ', "check_constraints": ' + ISNULL((SELECT cast(all_check_constraints_json as nvarchar(max)) FROM check_constraints), N'[]') +', "database_name": "' + DB_NAME() + '"' +', "version": ""}'diff --git a/src/lib/data/sql-export/cross-dialect/postgresql/to-mssql.ts b/src/lib/data/sql-export/cross-dialect/postgresql/to-mssql.tsindex 36a2653a..1d598a71 100644--- a/src/lib/data/sql-export/cross-dialect/postgresql/to-mssql.ts+++ b/src/lib/data/sql-export/cross-dialect/postgresql/to-mssql.ts@@ -148,10 +148,14 @@ function findCustomType(/*** Map a PostgreSQL type to SQL Server type with size/precision handling+ * @param field - The field to map+ * @param customTypes - Custom types defined in the schema+ * @param isIndexed - Whether this field is used in an index (affects MAX type handling)*/function mapPostgresTypeToMSSQL(field: DBField,- customTypes: DBCustomType[]+ customTypes: DBCustomType[],+ isIndexed: boolean = false): {typeName: string;inlineComment: string | null;@@ -159,11 +163,17 @@ function mapPostgresTypeToMSSQL(const originalType = field.type.name.toLowerCase();let inlineComment: string | null = null;+ // SQL Server has a 900-byte limit for index keys. NVARCHAR uses 2 bytes per char,+ // so 450 chars is the max for indexed NVARCHAR columns.+ const indexSafeNvarcharSize = 'NVARCHAR(450)';+// Handle array typesif (field.isArray || originalType.endsWith('[]')) {+ // Arrays used in indexes need bounded size (though this is unusual)+ const arrayType = isIndexed ? indexSafeNvarcharSize : 'NVARCHAR(MAX)';return {- typeName: 'NVARCHAR(MAX)',- inlineComment: `Was: ${field.type.name} (PostgreSQL array, stored as JSON)`,+ typeName: arrayType,+ inlineComment: `Was: ${field.type.name} (PostgreSQL array${isIndexed ? ', size limited for index' : ', stored as JSON'})`,};}@@ -177,10 +187,13 @@ function mapPostgresTypeToMSSQL(inlineComment: null, // Inline comment handled separately via getEnumValuesComment};} else if (customType.kind === 'composite') {- // Composite types become NVARCHAR(MAX) as JSON+ // Composite types become NVARCHAR(MAX) as JSON (shouldn't be indexed normally)+ const compositeType = isIndexed+ ? indexSafeNvarcharSize+ : 'NVARCHAR(MAX)';return {- typeName: 'NVARCHAR(MAX)',- inlineComment: `Was: ${field.type.name} (PostgreSQL composite type)`,+ typeName: compositeType,+ inlineComment: `Was: ${field.type.name} (PostgreSQL composite type${isIndexed ? ', size limited for index' : ''})`,};}}@@ -191,6 +204,13 @@ function mapPostgresTypeToMSSQL(let typeName = effectiveMapping.targetType;+ // If indexed and type contains (MAX), replace with bounded size for index compatibility+ // SQL Server cannot use MAX types as index keys+ if (isIndexed && typeName.includes('(MAX)')) {+ typeName = typeName.replace('(MAX)', '(450)');+ inlineComment = `Was: ${field.type.name} (size limited for index)`;+ }+// Handle size/precisionif (field.characterMaximumLength) {if (@@ -240,8 +260,8 @@ function mapPostgresTypeToMSSQL(typeName = `${typeName}(${effectiveMapping.defaultPrecision}, ${effectiveMapping.defaultScale || 0})`;}- // Set inline comment if conversion note exists- if (effectiveMapping.includeInlineComment) {+ // Set inline comment if conversion note exists (but don't override index-related comment)+ if (effectiveMapping.includeInlineComment && !inlineComment) {inlineComment = `Was: ${field.type.name}`;}@@ -362,17 +382,47 @@ export function exportPostgreSQLToMSSQL({(f) => f.primaryKey);- return `${- table.comments- ? formatMSSQLTableComment(table.comments)- : ''- }CREATE TABLE ${tableName} (\n${table.fields- .map((field: DBField) => {+ // Check if we have following constraints (for comma placement)+ const validCheckConstraints = (+ table.checkConstraints ?? []+ ).filter((c) => c.expression && c.expression.trim());+ const hasFollowingConstraints =+ primaryKeyFields.length > 0 ||+ validCheckConstraints.length > 0;++ // Compute which fields are used in indexes (for type size limiting)+ // SQL Server has a 900-byte limit for index keys+ const indexedFieldIds = new Set<string>();+ table.indexes.forEach((idx) => {+ idx.fieldIds.forEach((fieldId) => {+ indexedFieldIds.add(fieldId);+ });+ });+ // Also add primary key fields as they are indexed+ primaryKeyFields.forEach((f) => {+ indexedFieldIds.add(f.id);+ });+ // Also add unique fields as they create implicit indexes+ table.fields.forEach((f) => {+ if (f.unique) {+ indexedFieldIds.add(f.id);+ }+ });++ const fieldDefinitions = table.fields.map(+ (field: DBField, index: number, allFields: DBField[]) => {const fieldName = `[${field.name}]`;+ // Check if this field is used in an index+ const isIndexed = indexedFieldIds.has(field.id);+// Map type to SQL Serverconst { typeName, inlineComment } =- mapPostgresTypeToMSSQL(field, customTypes);+ mapPostgresTypeToMSSQL(+ field,+ customTypes,+ isIndexed+ );// Check for enum type and get valuesconst enumComment = getEnumValuesComment(@@ -407,12 +457,23 @@ export function exportPostgreSQLToMSSQL({? ` -- ${fullInlineComment}`: '';- return `${exportFieldComment(field.comments ?? '')} ${fieldName} ${typeName}${notNull}${identity}${unique}${defaultValue}${sqlInlineComment}`;- })- .join(',\n')}${+ // Determine if this field needs a trailing comma+ const isLastField = index === allFields.length - 1;+ const needsComma =+ !isLastField || hasFollowingConstraints;++ return `${exportFieldComment(field.comments ?? '')} ${fieldName} ${typeName}${notNull}${identity}${unique}${defaultValue}${needsComma ? ',' : ''}${sqlInlineComment}`;+ }+ );++ return `${+ table.comments+ ? formatMSSQLTableComment(table.comments)+ : ''+ }CREATE TABLE ${tableName} (\n${fieldDefinitions.join('\n')}${// Add PRIMARY KEY as table constraintprimaryKeyFields.length > 0- ? `,\n ${(() => {+ ? `\n ${(() => {const pkIndex = table.indexes.find((idx) => idx.isPrimaryKey);@@ -421,7 +482,19 @@ export function exportPostgreSQLToMSSQL({: '';})()}PRIMARY KEY (${primaryKeyFields.map((f) => `[${f.name}]`)- .join(', ')})`+ .join(+ ', '+ )})${validCheckConstraints.length > 0 ? ',' : ''}`+ : ''+ }${+ // Add check constraints (already computed above as validCheckConstraints)+ validCheckConstraints.length > 0+ ? validCheckConstraints+ .map(+ (constraint, index) =>+ `${index > 0 ? ',' : ''}\n CHECK (${constraint.expression})`+ )+ .join(''): ''}\n);\nGO${// Add indexes@@ -489,7 +562,7 @@ export function exportPostgreSQLToMSSQL({: '';return indexFieldNames.length > 0- ? `CREATE ${index.unique ? 'UNIQUE ' : ''}${indexTypeMapping?.targetType === 'CLUSTERED' ? 'CLUSTERED ' : 'NONCLUSTERED '}INDEX ${indexName}\nON ${tableName} (${indexFieldNames.join(', ')});${commentStr}`+ ? `CREATE ${index.unique ? 'UNIQUE ' : ''}${indexTypeMapping?.targetType === 'CLUSTERED' ? 'CLUSTERED ' : 'NONCLUSTERED '}INDEX ${indexName} ON ${tableName} (${indexFieldNames.join(', ')});${commentStr}`: '';}).filter(Boolean)diff --git a/src/lib/data/sql-export/cross-dialect/postgresql/to-mysql.ts b/src/lib/data/sql-export/cross-dialect/postgresql/to-mysql.tsindex b52a4b30..cf409f9c 100644--- a/src/lib/data/sql-export/cross-dialect/postgresql/to-mysql.ts+++ b/src/lib/data/sql-export/cross-dialect/postgresql/to-mysql.ts@@ -329,10 +329,16 @@ export function exportPostgreSQLToMySQL({(f) => f.primaryKey);- return `${- table.comments ? formatTableComment(table.comments) : ''- }\nCREATE TABLE IF NOT EXISTS ${tableName} (\n${table.fields- .map((field: DBField) => {+ // Check if we have following constraints (for comma placement)+ const validCheckConstraints = (+ table.checkConstraints ?? []+ ).filter((c) => c.expression && c.expression.trim());+ const hasFollowingConstraints =+ primaryKeyFields.length > 0 ||+ validCheckConstraints.length > 0;++ const fieldDefinitions = table.fields.map(+ (field: DBField, index: number, allFields: DBField[]) => {const fieldName = `\`${field.name}\``;// Map type to MySQL@@ -377,12 +383,21 @@ export function exportPostgreSQLToMySQL({? ` -- ${fullInlineComment}`: '';- return `${exportFieldComment(field.comments ?? '')} ${fieldName} ${typeName}${notNull}${autoIncrement}${unique}${defaultValue}${comment}${sqlInlineComment}`;- })- .join(',\n')}${+ // Determine if this field needs a trailing comma+ const isLastField = index === allFields.length - 1;+ const needsComma =+ !isLastField || hasFollowingConstraints;++ return `${exportFieldComment(field.comments ?? '')} ${fieldName} ${typeName}${notNull}${autoIncrement}${unique}${defaultValue}${comment}${needsComma ? ',' : ''}${sqlInlineComment}`;+ }+ );++ return `${+ table.comments ? formatTableComment(table.comments) : ''+ }\nCREATE TABLE IF NOT EXISTS ${tableName} (\n${fieldDefinitions.join('\n')}${// Add PRIMARY KEY as table constraintprimaryKeyFields.length > 0- ? `,\n ${(() => {+ ? `\n ${(() => {// Find PK index to get the constraint nameconst pkIndex = table.indexes.find((idx) => idx.isPrimaryKey@@ -392,7 +407,19 @@ export function exportPostgreSQLToMySQL({: '';})()}PRIMARY KEY (${primaryKeyFields.map((f) => `\`${f.name}\``)- .join(', ')})`+ .join(+ ', '+ )})${validCheckConstraints.length > 0 ? ',' : ''}`+ : ''+ }${+ // Add CHECK constraints (already computed above as validCheckConstraints)+ validCheckConstraints.length > 0+ ? validCheckConstraints+ .map(+ (constraint, index) =>+ `${index > 0 ? ',' : ''}\n CHECK (${constraint.expression})`+ )+ .join(''): ''}\n)${// MySQL supports table commentsdiff --git a/src/lib/data/sql-export/export-per-type/mssql.ts b/src/lib/data/sql-export/export-per-type/mssql.tsindex a7afc3b4..4cab4ee5 100644--- a/src/lib/data/sql-export/export-per-type/mssql.ts+++ b/src/lib/data/sql-export/export-per-type/mssql.ts@@ -132,9 +132,15 @@ export function exportMSSQL({typeName.toLowerCase() === 'varchar' ||typeName.toLowerCase() === 'nvarchar' ||typeName.toLowerCase() === 'char' ||- typeName.toLowerCase() === 'nchar'+ typeName.toLowerCase() === 'nchar' ||+ typeName.toLowerCase() === 'varbinary') {- typeWithSize = `${typeName}(${field.characterMaximumLength})`;+ // SQL Server uses -1 to represent MAX length+ const lengthSpec =+ field.characterMaximumLength === '-1'+ ? 'MAX'+ : field.characterMaximumLength;+ typeWithSize = `${typeName}(${lengthSpec})`;}}if (field.precision && field.scale) {@@ -192,6 +198,21 @@ export function exportMSSQL({.map((f) => `[${f.name}]`).join(', ')})`: ''+ }${+ // Add check constraints (filter out empty expressions)+ (() => {+ const validChecks = (+ table.checkConstraints ?? []+ ).filter((c) => c.expression && c.expression.trim());+ return validChecks.length > 0+ ? validChecks+ .map(+ (constraint) =>+ `,\n CHECK (${constraint.expression})`+ )+ .join('')+ : '';+ })()}\n);\n${(() => {const validIndexes = table.indexes.map((index) => {@@ -220,12 +241,12 @@ export function exportMSSQL({);indexFields.length = 32;return indexFields.length > 0- ? `${warningComment}CREATE ${index.unique ? 'UNIQUE ' : ''}INDEX ${indexName}\nON ${tableName} (${indexFields.join(', ')});`+ ? `${warningComment}CREATE ${index.unique ? 'UNIQUE ' : ''}INDEX ${indexName} ON ${tableName} (${indexFields.join(', ')});`: '';}return indexFields.length > 0- ? `CREATE ${index.unique ? 'UNIQUE ' : ''}INDEX ${indexName}\nON ${tableName} (${indexFields.join(', ')});`+ ? `CREATE ${index.unique ? 'UNIQUE ' : ''}INDEX ${indexName} ON ${tableName} (${indexFields.join(', ')});`: '';}).filter(Boolean)diff --git a/src/lib/data/sql-export/export-per-type/mysql.ts b/src/lib/data/sql-export/export-per-type/mysql.tsindex c5af6547..82a9547c 100644--- a/src/lib/data/sql-export/export-per-type/mysql.ts+++ b/src/lib/data/sql-export/export-per-type/mysql.ts@@ -326,6 +326,21 @@ export function exportMySQL({.map((f) => `\`${f.name}\``).join(', ')})`: ''+ }${+ // Add check constraints (filter out empty expressions)+ (() => {+ const validChecks = (+ table.checkConstraints ?? []+ ).filter((c) => c.expression && c.expression.trim());+ return validChecks.length > 0+ ? validChecks+ .map(+ (constraint) =>+ `,\n CHECK (${constraint.expression})`+ )+ .join('')+ : '';+ })()}\n)${// MySQL supports table commentstable.commentsdiff --git a/src/lib/data/sql-export/export-per-type/postgresql.ts b/src/lib/data/sql-export/export-per-type/postgresql.tsindex bf009605..15f07207 100644--- a/src/lib/data/sql-export/export-per-type/postgresql.ts+++ b/src/lib/data/sql-export/export-per-type/postgresql.ts@@ -342,6 +342,21 @@ export function exportPostgreSQL({.map((f) => `"${f.name}"`).join(', ')})`: ''+ }${+ // Add check constraints (filter out empty expressions)+ (() => {+ const validChecks = (+ table.checkConstraints ?? []+ ).filter((c) => c.expression && c.expression.trim());+ return validChecks.length > 0+ ? validChecks+ .map(+ (constraint) =>+ `,\n CHECK (${constraint.expression})`+ )+ .join('')+ : '';+ })()}\n);${// Add table commentstable.commentsdiff --git a/src/lib/data/sql-export/export-per-type/sqlite.ts b/src/lib/data/sql-export/export-per-type/sqlite.tsindex d136b69e..ad4471f2 100644--- a/src/lib/data/sql-export/export-per-type/sqlite.ts+++ b/src/lib/data/sql-export/export-per-type/sqlite.ts@@ -393,6 +393,21 @@ export function exportSQLite({.map((f) => `"${f.name}"`).join(', ')})`: ''+ }${+ // Add check constraints (filter out empty expressions)+ (() => {+ const validChecks = (+ table.checkConstraints ?? []+ ).filter((c) => c.expression && c.expression.trim());+ return validChecks.length > 0+ ? validChecks+ .map(+ (constraint) =>+ `,\n CHECK (${constraint.expression})`+ )+ .join('')+ : '';+ })()}${// Add foreign key constraintstableForeignKeys.length > 0diff --git a/src/lib/data/sql-export/export-sql-script.ts b/src/lib/data/sql-export/export-sql-script.tsindex 12c95ed9..e84f11a1 100644--- a/src/lib/data/sql-export/export-sql-script.ts+++ b/src/lib/data/sql-export/export-sql-script.ts@@ -16,6 +16,7 @@ import { escapeSQLComment } from './export-per-type/common';import {databaseTypesWithCommentSupport,supportsCustomTypes,+ supportsCheckConstraints,} from '@/lib/domain/database-capabilities';// Function to format default values with proper quoting@@ -523,10 +524,10 @@ export const exportBaseSQL = ({const pkIndex = table.indexes.find((idx) => idx.isPrimaryKey);// Only use CONSTRAINT syntax if PK index has a non-empty nameconst useNamedConstraint = !!pkIndex?.name;- if (+ const needsPKConstraint =hasCompositePrimaryKey ||- (primaryKeyFields.length === 1 && useNamedConstraint)- ) {+ (primaryKeyFields.length === 1 && useNamedConstraint);+ if (needsPKConstraint) {const pkFieldNames = primaryKeyFields.map((f) => getQuotedFieldName(f.name, isDBMLFlow)).join(', ');@@ -537,6 +538,26 @@ export const exportBaseSQL = ({}}+ // Add CHECK constraints (only for databases that support them, filter out empty)+ const dbSupportsChecks = supportsCheckConstraints(targetDatabaseType);+ const validCheckConstraints = (table.checkConstraints ?? []).filter(+ (c) => c.expression && c.expression.trim()+ );+ if (validCheckConstraints.length > 0 && dbSupportsChecks) {+ validCheckConstraints.forEach((checkConstraint, idx) => {+ // Add comma if needed (after fields or PK constraint)+ if (+ idx === 0 &&+ (table.fields.length > 0 || needsPKConstraint)+ ) {+ sqlScript += ',';+ } else if (idx > 0) {+ sqlScript += ',';+ }+ sqlScript += `\n CHECK (${checkConstraint.expression})`;+ });+ }+sqlScript += '\n);\n';// Add table comment (only for databases that support COMMENT ON syntax)diff --git a/src/lib/data/sql-import/common.ts b/src/lib/data/sql-import/common.tsindex f80241ff..e0621c83 100644--- a/src/lib/data/sql-import/common.ts+++ b/src/lib/data/sql-import/common.ts@@ -4,6 +4,7 @@ import type { DBTable } from '@/lib/domain/db-table';import type { Cardinality, DBRelationship } from '@/lib/domain/db-relationship';import type { DBField } from '@/lib/domain/db-field';import type { DBIndex } from '@/lib/domain/db-index';+import type { DBCheckConstraint } from '@/lib/domain/db-check-constraint';import {getPreferredSynonym,type DataType,@@ -35,12 +36,17 @@ export interface SQLColumn {increment?: boolean;}+export interface SQLCheckConstraint {+ expression: string;+}+export interface SQLTable {id: string;name: string;schema?: string;columns: SQLColumn[];indexes: SQLIndex[];+ checkConstraints?: SQLCheckConstraint[];comment?: string;order: number;isView?: boolean;@@ -903,6 +909,16 @@ export function convertToChartDBDiagram(}).filter((idx): idx is DBIndex => idx !== null);+ // Convert check constraints+ const checkConstraints: DBCheckConstraint[] | undefined =+ table.checkConstraints && table.checkConstraints.length > 0+ ? table.checkConstraints.map((c) => ({+ id: generateId(),+ expression: c.expression,+ createdAt: Date.now(),+ }))+ : undefined;+return {id: newId,name: table.name,@@ -910,6 +926,7 @@ export function convertToChartDBDiagram(order: index,fields,indexes,+ checkConstraints,x: col * tableSpacing,y: row * tableSpacing,color: table.isView ? viewColor : defaultTableColor,diff --git a/src/lib/data/sql-import/dialect-importers/mysql/mysql.ts b/src/lib/data/sql-import/dialect-importers/mysql/mysql.tsindex cbb79536..5d7c5475 100644--- a/src/lib/data/sql-import/dialect-importers/mysql/mysql.ts+++ b/src/lib/data/sql-import/dialect-importers/mysql/mysql.ts@@ -5,8 +5,51 @@ import type {SQLColumn,SQLIndex,SQLForeignKey,+ SQLCheckConstraint,} from '../../common';import { buildSQLFromAST } from '../../common';++/**+ * Extract CHECK constraints from CREATE TABLE statements+ */+function extractCheckConstraintsFromCreateTable(+ sql: string+): SQLCheckConstraint[] {+ const constraints: SQLCheckConstraint[] = [];++ // Extract the table body+ const tableBodyMatch = sql.match(/\(([\s\S]+)\)/);+ if (!tableBodyMatch) return constraints;++ const tableBody = tableBodyMatch[1];++ // Pattern for CHECK constraints:+ // CHECK (expression) or CONSTRAINT name CHECK (expression)+ const checkPattern = /(?:CONSTRAINT\s+(?:`[^`]+`|[^\s]+)\s+)?CHECK\s*\(/gi;+ let match;++ while ((match = checkPattern.exec(tableBody)) !== null) {+ const startIdx = match.index + match[0].length;+ let depth = 1;+ let endIdx = startIdx;++ // Find the matching closing parenthesis+ for (let i = startIdx; i < tableBody.length && depth > 0; i++) {+ if (tableBody[i] === '(') depth++;+ else if (tableBody[i] === ')') depth--;+ endIdx = i;+ }++ if (depth === 0) {+ const expression = tableBody.substring(startIdx, endIdx).trim();+ if (expression) {+ constraints.push({ expression });+ }+ }+ }++ return constraints;+}import type {ColumnDefinition,ConstraintDefinition,@@ -828,6 +871,12 @@ export async function fromMySQL(sqlContent: string): Promise<SQLParserResult> {}}+ // Extract check constraints+ const checkConstraints =+ extractCheckConstraintsFromCreateTable(+ trimmedStmt+ );+// Create and store the tabletables.push({id: tableId,@@ -835,6 +884,10 @@ export async function fromMySQL(sqlContent: string): Promise<SQLParserResult> {schema: database || undefined,columns,indexes,+ checkConstraints:+ checkConstraints.length > 0+ ? checkConstraints+ : undefined,order: tables.length,});}@@ -857,12 +910,20 @@ export async function fromMySQL(sqlContent: string): Promise<SQLParserResult> {const extractedColumns =extractColumnsFromCreateTable(trimmedStmt);if (extractedColumns.length > 0) {+ const checkConstraints =+ extractCheckConstraintsFromCreateTable(+ trimmedStmt+ );tables.push({id: tableId,name: tableName,schema: undefined,columns: extractedColumns,indexes: [],+ checkConstraints:+ checkConstraints.length > 0+ ? checkConstraints+ : undefined,order: tables.length,});}diff --git a/src/lib/data/sql-import/dialect-importers/postgresql/postgresql.ts b/src/lib/data/sql-import/dialect-importers/postgresql/postgresql.tsindex edfb459d..951e64fa 100644--- a/src/lib/data/sql-import/dialect-importers/postgresql/postgresql.ts+++ b/src/lib/data/sql-import/dialect-importers/postgresql/postgresql.ts@@ -6,6 +6,7 @@ import type {SQLIndex,SQLForeignKey,SQLEnumType,+ SQLCheckConstraint,} from '../../common';import { buildSQLFromAST } from '../../common';import { DatabaseType } from '@/lib/domain/database-type';@@ -833,6 +834,50 @@ function extractForeignKeysFromCreateTable(return relationships;}+/**+ * Extract CHECK constraints from CREATE TABLE statements+ * Handles both inline column-level and table-level CHECK constraints+ */+function extractCheckConstraintsFromCreateTable(+ sql: string+): SQLCheckConstraint[] {+ const constraints: SQLCheckConstraint[] = [];++ // Extract the table body+ const tableBodyMatch = sql.match(/\(([\s\S]+)\)/);+ if (!tableBodyMatch) return constraints;++ const tableBody = tableBodyMatch[1];++ // Pattern for table-level CHECK constraints:+ // CHECK (expression) or CONSTRAINT name CHECK (expression)+ // We need to handle nested parentheses in the expression+ const checkPattern = /(?:CONSTRAINT\s+(?:"[^"]+"|[^\s]+)\s+)?CHECK\s*\(/gi;+ let match;++ while ((match = checkPattern.exec(tableBody)) !== null) {+ const startIdx = match.index + match[0].length;+ let depth = 1;+ let endIdx = startIdx;++ // Find the matching closing parenthesis+ for (let i = startIdx; i < tableBody.length && depth > 0; i++) {+ if (tableBody[i] === '(') depth++;+ else if (tableBody[i] === ')') depth--;+ endIdx = i;+ }++ if (depth === 0) {+ const expression = tableBody.substring(startIdx, endIdx).trim();+ if (expression) {+ constraints.push({ expression });+ }+ }+ }++ return constraints;+}+/*** Parse PostgreSQL SQL with improved error handling and statement filtering*/@@ -1197,6 +1242,11 @@ export async function fromPostgres();relationships.push(...tableFKs);+ // Extract check constraints from the original SQL+ const checkConstraints = extractCheckConstraintsFromCreateTable(+ stmt.sql+ );+// Create table objectconst table: SQLTable = {id: tableId,@@ -1204,6 +1254,8 @@ export async function fromPostgres(schema: schemaName,columns,indexes,+ checkConstraints:+ checkConstraints.length > 0 ? checkConstraints : undefined,order: tables.length,};@@ -1249,6 +1301,10 @@ export async function fromPostgres();relationships.push(...fks);+ // Extract check constraints+ const checkConstraints =+ extractCheckConstraintsFromCreateTable(stmt.sql);+// Create table objectconst table: SQLTable = {id: tableId,@@ -1256,6 +1312,10 @@ export async function fromPostgres(schema: schemaName,columns,indexes: [],+ checkConstraints:+ checkConstraints.length > 0+ ? checkConstraints+ : undefined,order: tables.length,};diff --git a/src/lib/data/sql-import/dialect-importers/sqlite/sqlite.ts b/src/lib/data/sql-import/dialect-importers/sqlite/sqlite.tsindex ff967aef..fecb48a3 100644--- a/src/lib/data/sql-import/dialect-importers/sqlite/sqlite.ts+++ b/src/lib/data/sql-import/dialect-importers/sqlite/sqlite.ts@@ -5,6 +5,7 @@ import type {SQLIndex,SQLForeignKey,SQLASTNode,+ SQLCheckConstraint,} from '../../common';import type {TableReference,@@ -122,6 +123,9 @@ export async function fromSQLite(sqlContent: string): Promise<SQLParserResult> {return isValidForeignKeyRelationship(rel, tables);});+ // Extract check constraints and add to tables+ addCheckConstraintsToTables(sqlContent, tables);+return { tables, relationships: validRelationships };} catch (error) {console.error('Error parsing SQLite SQL:', error);@@ -129,6 +133,61 @@ export async function fromSQLite(sqlContent: string): Promise<SQLParserResult> {}}+/**+ * Extract check constraints from SQL and add them to existing tables+ */+function addCheckConstraintsToTables(+ sqlContent: string,+ tables: SQLTable[]+): void {+ // Find all CREATE TABLE statements and extract check constraints+ const createTableRegex =+ /CREATE\s+TABLE\s+(?:IF\s+NOT\s+EXISTS\s+)?(?:"([^"]+)"|([^\s(]+))\s*\(([\s\S]+?)\)(?:\s*;|\s*$)/gi;++ let match;+ while ((match = createTableRegex.exec(sqlContent)) !== null) {+ const tableName = match[1] || match[2];+ const tableBody = match[3];++ // Find the table in our tables array+ const table = tables.find(+ (t) => t.name.toLowerCase() === tableName.toLowerCase()+ );+ if (!table) continue;++ // Extract check constraints from this table body+ const checkPattern =+ /(?:CONSTRAINT\s+(?:"[^"]+"|[^\s]+)\s+)?CHECK\s*\(/gi;+ let checkMatch;++ const constraints: SQLCheckConstraint[] = [];++ while ((checkMatch = checkPattern.exec(tableBody)) !== null) {+ const startIdx = checkMatch.index + checkMatch[0].length;+ let depth = 1;+ let endIdx = startIdx;++ // Find the matching closing parenthesis+ for (let i = startIdx; i < tableBody.length && depth > 0; i++) {+ if (tableBody[i] === '(') depth++;+ else if (tableBody[i] === ')') depth--;+ endIdx = i;+ }++ if (depth === 0) {+ const expression = tableBody.substring(startIdx, endIdx).trim();+ if (expression) {+ constraints.push({ expression });+ }+ }+ }++ if (constraints.length > 0) {+ table.checkConstraints = constraints;+ }+ }+}+/*** Parse SQLite CREATE TABLE statements directly to preserve exact type information*/diff --git a/src/lib/data/sql-import/dialect-importers/sqlserver/sqlserver.ts b/src/lib/data/sql-import/dialect-importers/sqlserver/sqlserver.tsindex 013e098c..bd9eb85e 100644--- a/src/lib/data/sql-import/dialect-importers/sqlserver/sqlserver.ts+++ b/src/lib/data/sql-import/dialect-importers/sqlserver/sqlserver.ts@@ -6,6 +6,7 @@ import type {SQLIndex,SQLForeignKey,SQLASTNode,+ SQLCheckConstraint,} from '../../common';import type {TableReference,@@ -116,6 +117,49 @@ function extractColumnsFromView(sql: string): SQLColumn[] {return columns;}+/**+ * Extract CHECK constraints from CREATE TABLE statements+ */+function extractCheckConstraintsFromCreateTable(+ sql: string+): SQLCheckConstraint[] {+ const constraints: SQLCheckConstraint[] = [];++ // Extract the table body+ const tableBodyMatch = sql.match(/\(([\s\S]+)\)/);+ if (!tableBodyMatch) return constraints;++ const tableBody = tableBodyMatch[1];++ // Pattern for CHECK constraints:+ // CHECK (expression) or CONSTRAINT [name] CHECK (expression)+ const checkPattern =+ /(?:CONSTRAINT\s+(?:\[[^\]]+\]|[^\s]+)\s+)?CHECK\s*\(/gi;+ let match;++ while ((match = checkPattern.exec(tableBody)) !== null) {+ const startIdx = match.index + match[0].length;+ let depth = 1;+ let endIdx = startIdx;++ // Find the matching closing parenthesis+ for (let i = startIdx; i < tableBody.length && depth > 0; i++) {+ if (tableBody[i] === '(') depth++;+ else if (tableBody[i] === ')') depth--;+ endIdx = i;+ }++ if (depth === 0) {+ const expression = tableBody.substring(startIdx, endIdx).trim();+ if (expression) {+ constraints.push({ expression });+ }+ }+ }++ return constraints;+}+/*** Preprocess SQL Server script to remove or modify parts that the parser can't handle*/@@ -707,6 +751,9 @@ function parseCreateTableManually(}}+ // Extract check constraints+ const checkConstraints = extractCheckConstraintsFromCreateTable(statement);+// Add the tabletables.push({id: tableId,@@ -714,6 +761,8 @@ function parseCreateTableManually(schema: schema,columns,indexes,+ checkConstraints:+ checkConstraints.length > 0 ? checkConstraints : undefined,order: tables.length,});}diff --git a/src/lib/dbml/apply-dbml/apply-dbml.ts b/src/lib/dbml/apply-dbml/apply-dbml.tsindex d8d67005..1129f11b 100644--- a/src/lib/dbml/apply-dbml/apply-dbml.ts+++ b/src/lib/dbml/apply-dbml/apply-dbml.ts@@ -354,6 +354,7 @@ const updateTables = ({...sourceTable,fields: updatedFields,indexes: updatedIndexes,+ checkConstraints: targetTable.checkConstraints,comments: targetTable.comments,};diff --git a/src/lib/dbml/dbml-export/__tests__/dbml-export-invalid-check-constraints.test.ts b/src/lib/dbml/dbml-export/__tests__/dbml-export-invalid-check-constraints.test.tsnew file mode 100644index 00000000..d658e280--- /dev/null+++ b/src/lib/dbml/dbml-export/__tests__/dbml-export-invalid-check-constraints.test.ts@@ -0,0 +1,247 @@+import { describe, it, expect } from 'vitest';+import { generateDBMLFromDiagram } from '../dbml-export';+import { DatabaseType } from '@/lib/domain/database-type';+import type { Diagram } from '@/lib/domain/diagram';++describe('DBML Export - Invalid Check Constraints', () => {+ it('should not fail when table has invalid check constraints', () => {+ const diagram: Diagram = {+ id: 'test-diagram',+ name: 'Test',+ databaseType: DatabaseType.POSTGRESQL,+ createdAt: new Date(),+ updatedAt: new Date(),+ tables: [+ {+ id: 'table1',+ name: 'table_1',+ x: 0,+ y: 0,+ fields: [+ {+ id: 'field1',+ name: 'id',+ type: { id: 'bigint', name: 'bigint' },+ primaryKey: true,+ nullable: false,+ unique: false,+ createdAt: Date.now(),+ },+ ],+ indexes: [],+ color: 'blue',+ isView: false,+ createdAt: Date.now(),+ checkConstraints: [+ {+ id: 'check1',+ expression: 'id > 0', // Valid+ createdAt: Date.now(),+ },+ {+ id: 'check2',+ expression: '(a < b)', // Valid+ createdAt: Date.now(),+ },+ {+ id: 'check3',+ expression: '(a a)', // Invalid - no operator+ createdAt: Date.now(),+ },+ ],+ },+ ],+ relationships: [],+ };++ // Should not throw+ const result = generateDBMLFromDiagram(diagram);++ // Should not contain error message+ expect(result.error).toBeUndefined();+ expect(result.standardDbml).not.toContain('Error generating DBML');++ // Should contain the table+ expect(result.standardDbml).toContain('table_1');++ // Should contain valid check constraints+ expect(result.standardDbml).toContain('id > 0');+ expect(result.standardDbml).toContain('(a < b)');++ // Should NOT contain invalid check constraint+ expect(result.standardDbml).not.toContain('(a a)');+ });++ it('should handle table with only invalid check constraints', () => {+ const diagram: Diagram = {+ id: 'test-diagram',+ name: 'Test',+ databaseType: DatabaseType.POSTGRESQL,+ createdAt: new Date(),+ updatedAt: new Date(),+ tables: [+ {+ id: 'table1',+ name: 'products',+ x: 0,+ y: 0,+ fields: [+ {+ id: 'field1',+ name: 'price',+ type: { id: 'decimal', name: 'decimal' },+ primaryKey: false,+ nullable: false,+ unique: false,+ createdAt: Date.now(),+ },+ ],+ indexes: [],+ color: 'blue',+ isView: false,+ createdAt: Date.now(),+ checkConstraints: [+ {+ id: 'check1',+ expression: 'price >', // Invalid - incomplete+ createdAt: Date.now(),+ },+ {+ id: 'check2',+ expression: '> 0', // Invalid - no left operand+ createdAt: Date.now(),+ },+ ],+ },+ ],+ relationships: [],+ };++ // Should not throw+ const result = generateDBMLFromDiagram(diagram);++ // Should not contain error message+ expect(result.error).toBeUndefined();+ expect(result.standardDbml).not.toContain('Error generating DBML');++ // Should contain the table+ expect(result.standardDbml).toContain('products');++ // Should NOT contain a checks block (no valid constraints)+ expect(result.standardDbml).not.toContain('checks {');+ });++ it('should handle empty check constraint expressions', () => {+ const diagram: Diagram = {+ id: 'test-diagram',+ name: 'Test',+ databaseType: DatabaseType.POSTGRESQL,+ createdAt: new Date(),+ updatedAt: new Date(),+ tables: [+ {+ id: 'table1',+ name: 'users',+ x: 0,+ y: 0,+ fields: [+ {+ id: 'field1',+ name: 'age',+ type: { id: 'integer', name: 'integer' },+ primaryKey: false,+ nullable: false,+ unique: false,+ createdAt: Date.now(),+ },+ ],+ indexes: [],+ color: 'blue',+ isView: false,+ createdAt: Date.now(),+ checkConstraints: [+ {+ id: 'check1',+ expression: '', // Empty+ createdAt: Date.now(),+ },+ {+ id: 'check2',+ expression: ' ', // Whitespace only+ createdAt: Date.now(),+ },+ {+ id: 'check3',+ expression: 'age >= 0', // Valid+ createdAt: Date.now(),+ },+ ],+ },+ ],+ relationships: [],+ };++ // Should not throw+ const result = generateDBMLFromDiagram(diagram);++ // Should not contain error message+ expect(result.error).toBeUndefined();++ // Should contain valid constraint+ expect(result.standardDbml).toContain('age >= 0');+ });++ it('should handle unbalanced parentheses in check constraints', () => {+ const diagram: Diagram = {+ id: 'test-diagram',+ name: 'Test',+ databaseType: DatabaseType.POSTGRESQL,+ createdAt: new Date(),+ updatedAt: new Date(),+ tables: [+ {+ id: 'table1',+ name: 'orders',+ x: 0,+ y: 0,+ fields: [+ {+ id: 'field1',+ name: 'status',+ type: { id: 'varchar', name: 'varchar' },+ primaryKey: false,+ nullable: false,+ unique: false,+ createdAt: Date.now(),+ },+ ],+ indexes: [],+ color: 'blue',+ isView: false,+ createdAt: Date.now(),+ checkConstraints: [+ {+ id: 'check1',+ expression: "(status = 'active'", // Missing closing paren+ createdAt: Date.now(),+ },+ ],+ },+ ],+ relationships: [],+ };++ // Should not throw+ const result = generateDBMLFromDiagram(diagram);++ // Should not contain error message+ expect(result.error).toBeUndefined();+ expect(result.standardDbml).not.toContain('Error generating DBML');++ // Should contain the table+ expect(result.standardDbml).toContain('orders');++ // Should NOT contain the invalid constraint+ expect(result.standardDbml).not.toContain("(status = 'active'");+ });+});diff --git a/src/lib/dbml/dbml-export/dbml-export.ts b/src/lib/dbml/dbml-export/dbml-export.tsindex 38c48486..429d022f 100644--- a/src/lib/dbml/dbml-export/dbml-export.ts+++ b/src/lib/dbml/dbml-export/dbml-export.ts@@ -5,6 +5,7 @@ import { DatabaseType } from '@/lib/domain/database-type';import type { DBTable } from '@/lib/domain/db-table';import type { DBCustomType } from '@/lib/domain/db-custom-type';import { DBCustomTypeKind } from '@/lib/domain/db-custom-type';+import { validateCheckConstraint } from '@/lib/check-constraints/check-constraints-validator';// Use DBCustomType for generating Enum DBMLconst generateEnumsDBML = (customTypes: DBCustomType[] | undefined): string => {@@ -656,6 +657,61 @@ const restoreIncrementAttribute = (dbml: string, tables: DBTable[]): string => {return result;};+// Restore check constraints that may have been lost during DBML export+// The @dbml/core importer doesn't support check constraints natively+const restoreCheckConstraints = (dbml: string, tables: DBTable[]): string => {+ if (!tables || tables.length === 0) return dbml;++ let result = dbml;++ tables.forEach((table) => {+ // Filter out empty and invalid expressions+ const validChecks = (table.checkConstraints ?? []).filter(+ (c) =>+ c.expression &&+ c.expression.trim() &&+ validateCheckConstraint(c.expression)+ );++ if (validChecks.length === 0) {+ return;+ }++ // Build the table identifier pattern once for this table+ const tableIdentifier = table.schema+ ? `"${table.schema.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')}"\\."${table.name.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')}"`+ : `"${table.name.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')}"`;++ // Pattern to match the entire table block+ const tableBlockPattern = new RegExp(+ `(Table ${tableIdentifier} \\{)([\\s\\S]*?)(^\\})`,+ 'gm'+ );++ result = result.replace(+ tableBlockPattern,+ (match, tableStart, tableContent, tableEnd) => {+ // Check if a checks block already exists+ if (/^\s*checks\s*\{/m.test(tableContent)) {+ return match;+ }++ // Build the checks block+ const checksContent = validChecks+ .map((check) => ` \`${check.expression}\``)+ .join('\n');++ const checksBlock = `\n checks {\n${checksContent}\n }\n`;++ // Add the checks block at the end, before the closing brace+ return `${tableStart}${tableContent}${checksBlock}${tableEnd}`;+ }+ );+ });++ return result;+};+// Restore table and field notes/comments that may have been lost during DBML export// This handles databases where @dbml/core doesn't recognize the comment syntax// (e.g., MySQL's inline COMMENT syntax). For databases like PostgreSQL where@@ -998,7 +1054,7 @@ export function generateDBMLFromDiagram(diagram: Diagram): DBMLExportResult {// Sanitize field names ('from'/'to' in 'relation' table)const cleanDiagram = fixProblematicFieldNames(filteredDiagram);- // Simplified processing - just handle duplicate field names+ // Simplified processing - handle duplicate field names and filter invalid check constraintsconst processTable = (table: DBTable) => {const fieldNameCounts = new Map<string, number>();const processedFields = table.fields.map((field) => {@@ -1015,6 +1071,14 @@ export function generateDBMLFromDiagram(diagram: Diagram): DBMLExportResult {return field;});+ // Filter out empty and invalid check constraint expressions+ const validCheckConstraints = (table.checkConstraints ?? []).filter(+ (c) =>+ c.expression &&+ c.expression.trim() &&+ validateCheckConstraint(c.expression)+ );+return {...table,fields: processedFields,@@ -1026,6 +1090,10 @@ export function generateDBMLFromDiagram(diagram: Diagram): DBMLExportResult {index.name ||`idx_${Math.random().toString(36).substring(2, 8)}`,})),+ checkConstraints:+ validCheckConstraints.length > 0+ ? validCheckConstraints+ : undefined,};};@@ -1087,6 +1155,9 @@ export function generateDBMLFromDiagram(diagram: Diagram): DBMLExportResult {// Restore table and field notes/comments that may have been lost during DBML exportstandard = restoreNotes(standard, tablesWithFields);+ // Restore check constraints that may have been lost during DBML export+ standard = restoreCheckConstraints(standard, tablesWithFields);+// Prepend Enum DBML to the standard outputif (enumsDBML) {standard = enumsDBML + '\n\n' + standard;diff --git a/src/lib/dbml/dbml-import/__tests__/dbml-check-constraints-validation.test.ts b/src/lib/dbml/dbml-import/__tests__/dbml-check-constraints-validation.test.tsnew file mode 100644index 00000000..0f57ec07--- /dev/null+++ b/src/lib/dbml/dbml-import/__tests__/dbml-check-constraints-validation.test.ts@@ -0,0 +1,318 @@+import { describe, it, expect } from 'vitest';+import { preprocessDBML, importDBMLToDiagram } from '../dbml-import';+import { DBMLValidationError } from '../dbml-import-error';+import { DatabaseType } from '@/lib/domain/database-type';++describe('DBML Check Constraints Validation', () => {+ describe('preprocessDBML - table-level check constraints', () => {+ it('should accept valid check constraint expressions', () => {+ const dbml = `+Table users {+ id int [pk]+ age int++ checks {+ \`age >= 0\`+ }+}`;+ expect(() => preprocessDBML(dbml)).not.toThrow();+ const { tableChecks } = preprocessDBML(dbml);+ expect(tableChecks.get('users')).toHaveLength(1);+ expect(tableChecks.get('users')![0].expression).toBe('age >= 0');+ });++ it('should accept multiple valid check constraints', () => {+ const dbml = `+Table products {+ id int [pk]+ price decimal+ quantity int++ checks {+ \`price > 0\`+ \`quantity >= 0\`+ }+}`;+ expect(() => preprocessDBML(dbml)).not.toThrow();+ const { tableChecks } = preprocessDBML(dbml);+ expect(tableChecks.get('products')).toHaveLength(2);+ });++ it('should accept complex check constraint expressions', () => {+ const dbml = `+Table orders {+ id int [pk]+ status varchar++ checks {+ \`status IN ('pending', 'completed', 'cancelled')\`+ }+}`;+ expect(() => preprocessDBML(dbml)).not.toThrow();+ });++ it('should accept BETWEEN expressions', () => {+ const dbml = `+Table ratings {+ id int [pk]+ score int++ checks {+ \`score BETWEEN 1 AND 5\`+ }+}`;+ expect(() => preprocessDBML(dbml)).not.toThrow();+ });++ it('should reject incomplete expressions - missing right operand', () => {+ const dbml = `+Table users {+ id int [pk]+ age int++ checks {+ \`age >\`+ }+}`;+ expect(() => preprocessDBML(dbml)).toThrow(DBMLValidationError);+ try {+ preprocessDBML(dbml);+ } catch (e) {+ expect(e).toBeInstanceOf(DBMLValidationError);+ const error = e as DBMLValidationError;+ expect(error.message).toContain('Invalid check constraint');+ expect(error.message).toContain('incomplete');+ }+ });++ it('should reject unbalanced parentheses', () => {+ const dbml = `+Table users {+ id int [pk]+ status varchar++ checks {+ \`(status = 'active'\`+ }+}`;+ expect(() => preprocessDBML(dbml)).toThrow(DBMLValidationError);+ try {+ preprocessDBML(dbml);+ } catch (e) {+ expect(e).toBeInstanceOf(DBMLValidationError);+ const error = e as DBMLValidationError;+ expect(error.message).toContain('parenthes');+ }+ });++ it('should reject expressions starting with operator', () => {+ const dbml = `+Table users {+ id int [pk]+ age int++ checks {+ \`> 0\`+ }+}`;+ expect(() => preprocessDBML(dbml)).toThrow(DBMLValidationError);+ });++ it('should provide line number in error', () => {+ const dbml = `+Table users {+ id int [pk]+ age int++ checks {+ \`age >\`+ }+}`;+ try {+ preprocessDBML(dbml);+ expect.fail('Should have thrown');+ } catch (e) {+ expect(e).toBeInstanceOf(DBMLValidationError);+ const error = e as DBMLValidationError;+ expect(error.dbmlError.line).toBeGreaterThan(0);+ }+ });+ });++ describe('preprocessDBML - field-level check constraints', () => {+ it('should accept valid field-level check constraint', () => {+ const dbml = `+Table products {+ id int [pk]+ price decimal [not null, check: \`price > 0\`]+}`;+ expect(() => preprocessDBML(dbml)).not.toThrow();+ const { fieldChecks } = preprocessDBML(dbml);+ expect(fieldChecks.get('products')?.get('price')?.expression).toBe(+ 'price > 0'+ );+ });++ it('should reject invalid field-level check constraint', () => {+ const dbml = `+Table products {+ id int [pk]+ price decimal [not null, check: \`price >\`]+}`;+ expect(() => preprocessDBML(dbml)).toThrow(DBMLValidationError);+ try {+ preprocessDBML(dbml);+ } catch (e) {+ expect(e).toBeInstanceOf(DBMLValidationError);+ const error = e as DBMLValidationError;+ expect(error.message).toContain('Invalid check constraint');+ expect(error.message).toContain('price');+ }+ });+ });++ describe('importDBMLToDiagram - check constraint validation', () => {+ it('should successfully import valid check constraints', async () => {+ const dbml = `+Table users {+ id int [pk]+ age int+ status varchar++ checks {+ \`age >= 0 AND age <= 150\`+ \`status IN ('active', 'inactive')\`+ }+}`;+ const diagram = await importDBMLToDiagram(dbml, {+ databaseType: DatabaseType.POSTGRESQL,+ });++ expect(diagram.tables).toHaveLength(1);+ const table = diagram.tables![0];+ expect(table.checkConstraints).toHaveLength(2);+ expect(table.checkConstraints![0].expression).toBe(+ 'age >= 0 AND age <= 150'+ );+ expect(table.checkConstraints![1].expression).toBe(+ "status IN ('active', 'inactive')"+ );+ });++ it('should throw validation error for invalid check constraint during import', async () => {+ const dbml = `+Table users {+ id int [pk]+ age int++ checks {+ \`age <\`+ }+}`;+ await expect(+ importDBMLToDiagram(dbml, {+ databaseType: DatabaseType.POSTGRESQL,+ })+ ).rejects.toThrow(DBMLValidationError);+ });++ it('should import named check constraints', async () => {+ const dbml = `+Table products {+ id int [pk]+ price decimal++ checks {+ \`price > 0\` [name: 'positive_price']+ }+}`;+ const diagram = await importDBMLToDiagram(dbml, {+ databaseType: DatabaseType.POSTGRESQL,+ });++ const table = diagram.tables![0];+ expect(table.checkConstraints).toHaveLength(1);+ expect(table.checkConstraints![0].expression).toBe('price > 0');+ });+ });++ describe('edge cases', () => {+ it('should handle check constraints with quoted identifiers', () => {+ const dbml = `+Table users {+ id int [pk]+ "user name" varchar++ checks {+ \`"user name" IS NOT NULL\`+ }+}`;+ expect(() => preprocessDBML(dbml)).not.toThrow();+ });++ it('should handle check constraints with SQL Server bracket notation', () => {+ const dbml = `+Table users {+ id int [pk]+ age int++ checks {+ \`[age] >= 0 AND [age] <= 100\`+ }+}`;+ expect(() => preprocessDBML(dbml)).not.toThrow();+ });++ it('should handle check constraints with function calls', () => {+ const dbml = `+Table users {+ id int [pk]+ email varchar++ checks {+ \`LENGTH(email) > 0\`+ }+}`;+ expect(() => preprocessDBML(dbml)).not.toThrow();+ });++ it('should handle NOT LIKE expressions', () => {+ const dbml = `+Table users {+ id int [pk]+ code varchar++ checks {+ \`code NOT LIKE 'TEST%'\`+ }+}`;+ expect(() => preprocessDBML(dbml)).not.toThrow();+ });++ it('should handle NOT IN expressions', () => {+ const dbml = `+Table users {+ id int [pk]+ status varchar++ checks {+ \`status NOT IN ('deleted', 'banned')\`+ }+}`;+ expect(() => preprocessDBML(dbml)).not.toThrow();+ });++ it('should handle empty checks block gracefully', () => {+ const dbml = `+Table users {+ id int [pk]++ checks {+ }+}`;+ expect(() => preprocessDBML(dbml)).not.toThrow();+ const { tableChecks } = preprocessDBML(dbml);+ expect(tableChecks.has('users')).toBe(false);+ });+ });+});diff --git a/src/lib/dbml/dbml-import/dbml-import.ts b/src/lib/dbml/dbml-import/dbml-import.tsindex f31f73d7..61793981 100644--- a/src/lib/dbml/dbml-import/dbml-import.ts+++ b/src/lib/dbml/dbml-import/dbml-import.ts@@ -5,6 +5,7 @@ import type { DBTable } from '@/lib/domain/db-table';import { defaultSchemas } from '@/lib/data/default-schemas';import type { Cardinality, DBRelationship } from '@/lib/domain/db-relationship';import type { DBField } from '@/lib/domain/db-field';+import type { DBCheckConstraint } from '@/lib/domain/db-check-constraint';import type { DataTypeData } from '@/lib/data/data-types/data-types';import {findDataTypeDataById,@@ -19,20 +20,51 @@ import {DBCustomTypeKind,type DBCustomType,} from '@/lib/domain/db-custom-type';-import { validateArrayTypesForDatabase } from './dbml-import-error';+import {+ validateArrayTypesForDatabase,+ DBMLValidationError,+ getPositionFromIndex,+} from './dbml-import-error';+import { validateCheckConstraintWithDetails } from '@/lib/check-constraints/check-constraints-validator';export const defaultDBMLDiagramName = 'DBML Import';+interface FieldCheckConstraint {+ expression: string;+}++interface TableCheckConstraint {+ expression: string;+ name?: string;+}+interface PreprocessDBMLResult {content: string;arrayFields: Map<string, Set<string>>;+ fieldChecks: Map<string, Map<string, FieldCheckConstraint>>;+ tableChecks: Map<string, TableCheckConstraint[]>;}+// Helper to find matching closing brace+const findMatchingBrace = (str: string, startIndex: number): number => {+ let depth = 1;+ for (let i = startIndex; i < str.length && depth > 0; i++) {+ if (str[i] === '{') depth++;+ else if (str[i] === '}') depth--;+ if (depth === 0) return i;+ }+ return -1;+};+export const preprocessDBML = (content: string): PreprocessDBMLResult => {let processed = content;// Track array fields found during preprocessingconst arrayFields = new Map<string, Set<string>>();+ // Track field-level check constraints: Map<tableName, Map<fieldName, constraint>>+ const fieldChecks = new Map<string, Map<string, FieldCheckConstraint>>();+ // Track table-level check constraints: Map<tableName, constraints[]>+ const tableChecks = new Map<string, TableCheckConstraint[]>();// Remove TableGroup blocks (not supported by parser)processed = processed.replace(/TableGroup\s+[^{]*\{[^}]*\}/gs, '');@@ -47,22 +79,31 @@ export const preprocessDBML = (content: string): PreprocessDBMLResult => {// Note: DBML doesn't officially support array syntax, so we convert type[] to type// but track which fields should be arrays- // First, find all array field declarations and track them- const tablePattern =- /Table\s+(?:"([^"]+)"\.)?(?:"([^"]+)"|(\w+))\s*(?:\[[^\]]*\])?\s*\{([^}]+)\}/gs;- let match;+ // First, find all Table declarations and extract their bodies properly+ // Pattern matches: Table "schema"."name" { or Table name { or Table "name" {+ const tableStartPattern =+ /Table\s+(?:(?:"([^"]+)"\.)?(?:"([^"]+)"|([a-zA-Z_]\w*)))\s*(?:\[[^\]]*\])?\s*\{/g;+ let tableMatch;- while ((match = tablePattern.exec(content)) !== null) {- const schema = match[1] || '';- const tableName = match[2] || match[3];- const tableBody = match[4];+ while ((tableMatch = tableStartPattern.exec(content)) !== null) {+ const schema = tableMatch[1] || '';+ const tableName = tableMatch[2] || tableMatch[3];+ const openBraceIndex = tableMatch.index + tableMatch[0].length - 1;+ const closeBraceIndex = findMatchingBrace(content, openBraceIndex + 1);++ if (closeBraceIndex === -1) continue;++ const tableBody = content.substring(+ openBraceIndex + 1,+ closeBraceIndex+ );const fullTableName = schema ? `${schema}.${tableName}` : tableName;// Find array field declarations within this table- const fieldPattern = /"?(\w+)"?\s+(\w+(?:\([^)]+\))?)\[\]/g;+ const arrayFieldPattern = /"?(\w+)"?\s+(\w+(?:\([^)]+\))?)\[\]/g;let fieldMatch;- while ((fieldMatch = fieldPattern.exec(tableBody)) !== null) {+ while ((fieldMatch = arrayFieldPattern.exec(tableBody)) !== null) {const fieldName = fieldMatch[1];if (!arrayFields.has(fullTableName)) {@@ -70,11 +111,111 @@ export const preprocessDBML = (content: string): PreprocessDBMLResult => {}arrayFields.get(fullTableName)!.add(fieldName);}++ // Extract field-level check constraints: check: `expression`+ // Pattern matches lines like: price decimal [not null, check: `price > 0`]+ const fieldCheckPattern =+ /^\s*"?(\w+)"?\s+\w+[^\n[]*\[[^\]]*check:\s*`([^`]+)`/gm;+ let checkMatch;++ while ((checkMatch = fieldCheckPattern.exec(tableBody)) !== null) {+ const fieldName = checkMatch[1];+ const expression = checkMatch[2];++ // Validate the check constraint expression+ const validationResult =+ validateCheckConstraintWithDetails(expression);+ if (!validationResult.isValid) {+ // Calculate position in original content+ const expressionStartInTableBody =+ checkMatch.index + checkMatch[0].indexOf(expression);+ const expressionStartInContent =+ openBraceIndex + 1 + expressionStartInTableBody;+ const { line, column } = getPositionFromIndex(+ content,+ expressionStartInContent+ );+ throw new DBMLValidationError(+ `Invalid check constraint expression "${expression}" on field "${fieldName}": ${validationResult.error}`,+ line,+ column+ );+ }++ if (!fieldChecks.has(fullTableName)) {+ fieldChecks.set(fullTableName, new Map());+ }+ fieldChecks.get(fullTableName)!.set(fieldName, { expression });+ }++ // Extract table-level checks block: checks { `expression` [name: 'name'] }+ const checksBlockPattern = /checks\s*\{([^}]*)\}/gs;+ const checksBlockMatch = checksBlockPattern.exec(tableBody);++ if (checksBlockMatch) {+ const checksContent = checksBlockMatch[1];+ const checksBlockStartInTableBody = checksBlockMatch.index;++ // Parse individual check constraints within the block+ // Pattern: `expression` or `expression` [name: 'name']+ const checkItemPattern =+ /`([^`]+)`(?:\s*\[(?:[^\]]*name:\s*['"]([^'"]+)['"])?[^\]]*\])?/g;+ let checkItemMatch;++ const constraints: TableCheckConstraint[] = [];+ while (+ (checkItemMatch = checkItemPattern.exec(checksContent)) !== null+ ) {+ const expression = checkItemMatch[1];++ // Validate the check constraint expression+ const validationResult =+ validateCheckConstraintWithDetails(expression);+ if (!validationResult.isValid) {+ // Calculate position in original content+ // checksContent starts after "checks {"+ const checksBlockHeaderLength =+ checksBlockMatch[0].indexOf(checksContent);+ const expressionStartInChecksContent =+ checkItemMatch.index + 1; // +1 to skip the opening backtick+ const expressionStartInContent =+ openBraceIndex ++ 1 ++ checksBlockStartInTableBody ++ checksBlockHeaderLength ++ expressionStartInChecksContent;+ const { line, column } = getPositionFromIndex(+ content,+ expressionStartInContent+ );+ throw new DBMLValidationError(+ `Invalid check constraint expression "${expression}": ${validationResult.error}`,+ line,+ column+ );+ }++ constraints.push({+ expression,+ name: checkItemMatch[2] || undefined,+ });+ }++ if (constraints.length > 0) {+ tableChecks.set(fullTableName, constraints);+ }+ }}// Now convert array syntax for DBML parser (keep the base type, remove [])processed = processed.replace(/(\w+(?:\(\d+(?:,\s*\d+)?\))?)\[\]/g, '$1');+ // Remove check: `...` from field attributes (not supported by parser)+ processed = processed.replace(/,?\s*check:\s*`[^`]+`/g, '');++ // Remove checks { ... } blocks (not supported by parser)+ processed = processed.replace(/\s*checks\s*\{[^}]*\}/gs, '');+// Handle inline enum types without values by converting to varcharprocessed = processed.replace(/^\s*(\w+)\s+enum\s*(?:\/\/.*)?$/gm,@@ -88,7 +229,7 @@ export const preprocessDBML = (content: string): PreprocessDBMLResult => {'Table $1 {');- return { content: processed, arrayFields };+ return { content: processed, arrayFields, fieldChecks, tableChecks };};// Simple function to replace Spanish special characters@@ -256,8 +397,12 @@ export const importDBMLToDiagram = async (const parser = new Parser();// Preprocess and sanitize DBML content- const { content: preprocessedContent, arrayFields } =- preprocessDBML(dbmlContent);+ const {+ content: preprocessedContent,+ arrayFields,+ fieldChecks,+ tableChecks,+ } = preprocessDBML(dbmlContent);const sanitizedContent = sanitizeDBML(preprocessedContent);// Handle content that becomes empty after preprocessing@@ -748,6 +893,48 @@ export const importDBMLToDiagram = async (isStringEmpty(rawSchema) || rawSchema === 'public';const tableSchema = isSchemaEmpty ? defaultSchema : rawSchema;+ // Build check constraints (all as table-level)+ // Try with schema first, then without (since original DBML might not have schema)+ const rawTableSchemaForChecks = rawSchema || '';+ const fullTableNameForTableChecks = rawTableSchemaForChecks+ ? `${rawTableSchemaForChecks}.${table.name}`+ : table.name;++ const allCheckConstraints: DBCheckConstraint[] = [];++ // Convert field-level check constraints to table-level+ const fieldChecksDefs =+ fieldChecks.get(fullTableNameForTableChecks) ||+ fieldChecks.get(table.name);+ if (fieldChecksDefs) {+ fieldChecksDefs.forEach((check) => {+ allCheckConstraints.push({+ id: generateId(),+ expression: check.expression,+ createdAt: Date.now(),+ });+ });+ }++ // Add table-level check constraints+ const tableCheckConstraintsDefs =+ tableChecks.get(fullTableNameForTableChecks) ||+ tableChecks.get(table.name);+ if (tableCheckConstraintsDefs) {+ tableCheckConstraintsDefs.forEach((check) => {+ allCheckConstraints.push({+ id: generateId(),+ expression: check.expression,+ createdAt: Date.now(),+ });+ });+ }++ const checkConstraints: DBCheckConstraint[] | undefined =+ allCheckConstraints.length > 0+ ? allCheckConstraints+ : undefined;+const tableToReturn: DBTable = {id: generateId(),name: table.name.replace(/['"]/g, ''),@@ -755,6 +942,9 @@ export const importDBMLToDiagram = async (order: index,fields,indexes,+ ...(checkConstraints && checkConstraints.length > 0+ ? { checkConstraints }+ : {}),x: col * tableSpacing,y: row * tableSpacing,color: defaultTableColor,diff --git a/src/lib/domain/database-capabilities.ts b/src/lib/domain/database-capabilities.tsindex 8fad91bb..e4a20ab9 100644--- a/src/lib/domain/database-capabilities.ts+++ b/src/lib/domain/database-capabilities.ts@@ -5,6 +5,7 @@ export interface DatabaseCapabilities {supportsCustomTypes?: boolean;supportsSchemas?: boolean;supportsComments?: boolean;+ supportsCheckConstraints?: boolean;}export const DATABASE_CAPABILITIES: Record<DatabaseType, DatabaseCapabilities> =@@ -14,24 +15,34 @@ export const DATABASE_CAPABILITIES: Record<DatabaseType, DatabaseCapabilities> =supportsCustomTypes: true,supportsSchemas: true,supportsComments: true,+ supportsCheckConstraints: true,},[DatabaseType.COCKROACHDB]: {supportsArrays: true,supportsSchemas: true,supportsComments: true,+ supportsCheckConstraints: true,+ },+ [DatabaseType.MYSQL]: {+ supportsCheckConstraints: true,+ },+ [DatabaseType.MARIADB]: {+ supportsCheckConstraints: true,},- [DatabaseType.MYSQL]: {},- [DatabaseType.MARIADB]: {},[DatabaseType.SQL_SERVER]: {supportsSchemas: true,+ supportsCheckConstraints: true,+ },+ [DatabaseType.SQLITE]: {+ supportsCheckConstraints: true,},- [DatabaseType.SQLITE]: {},[DatabaseType.CLICKHOUSE]: {supportsSchemas: true,},[DatabaseType.ORACLE]: {supportsSchemas: true,supportsComments: true,+ supportsCheckConstraints: true,},[DatabaseType.GENERIC]: {},};@@ -55,3 +66,11 @@ export const databaseTypesWithCommentSupport: DatabaseType[] = Object.keys(export const supportsCustomTypes = (databaseType: DatabaseType): boolean => {return getDatabaseCapabilities(databaseType).supportsCustomTypes ?? false;};++export const supportsCheckConstraints = (+ databaseType: DatabaseType+): boolean => {+ return (+ getDatabaseCapabilities(databaseType).supportsCheckConstraints ?? false+ );+};diff --git a/src/lib/domain/db-check-constraint.ts b/src/lib/domain/db-check-constraint.tsnew file mode 100644index 00000000..826692e2--- /dev/null+++ b/src/lib/domain/db-check-constraint.ts@@ -0,0 +1,13 @@+import { z } from 'zod';++export interface DBCheckConstraint {+ id: string;+ expression: string;+ createdAt: number;+}++export const dbCheckConstraintSchema: z.ZodType<DBCheckConstraint> = z.object({+ id: z.string(),+ expression: z.string(),+ createdAt: z.number(),+});diff --git a/src/lib/domain/db-field.ts b/src/lib/domain/db-field.tsindex 3f7ef153..38736665 100644--- a/src/lib/domain/db-field.ts+++ b/src/lib/domain/db-field.ts@@ -23,6 +23,7 @@ export interface DBField {default?: string | null;collation?: string | null;comments?: string | null;+ check?: string | null;}export const dbFieldSchema: z.ZodType<DBField> = z.object({@@ -41,6 +42,7 @@ export const dbFieldSchema: z.ZodType<DBField> = z.object({default: z.string().or(z.null()).optional(),collation: z.string().or(z.null()).optional(),comments: z.string().or(z.null()).optional(),+ check: z.string().or(z.null()).optional(),});export const generateDBFieldSuffix = (diff --git a/src/lib/domain/db-table.ts b/src/lib/domain/db-table.tsindex 27ee7d50..246542cd 100644--- a/src/lib/domain/db-table.ts+++ b/src/lib/domain/db-table.ts@@ -1,6 +1,10 @@import { dbIndexSchema, type DBIndex } from './db-index';import { dbFieldSchema, type DBField } from './db-field';import type { DBRelationship } from './db-relationship';+import {+ dbCheckConstraintSchema,+ type DBCheckConstraint,+} from './db-check-constraint';import { deepCopy, findContainingArea } from '../utils';import { schemaNameToDomainSchemaName } from './db-schema';import { z } from 'zod';@@ -19,6 +23,7 @@ export interface DBTable {y: number;fields: DBField[];indexes: DBIndex[];+ checkConstraints?: DBCheckConstraint[] | null;color: string;isView: boolean;isMaterializedView?: boolean | null;@@ -38,6 +43,7 @@ export const dbTableSchema: z.ZodType<DBTable> = z.object({y: z.number(),fields: z.array(dbFieldSchema),indexes: z.array(dbIndexSchema),+ checkConstraints: z.array(dbCheckConstraintSchema).or(z.null()).optional(),color: z.string(),isView: z.boolean(),isMaterializedView: z.boolean().or(z.null()).optional(),diff --git a/src/lib/domain/diff/check-constraint-diff.ts b/src/lib/domain/diff/check-constraint-diff.tsnew file mode 100644index 00000000..683872af--- /dev/null+++ b/src/lib/domain/diff/check-constraint-diff.ts@@ -0,0 +1,78 @@+import { z } from 'zod';+import type { DBCheckConstraint } from '../db-check-constraint';++export type CheckConstraintDiffAttribute = 'expression';++export const checkConstraintDiffAttributeSchema: z.ZodType<CheckConstraintDiffAttribute> =+ z.literal('expression');++export interface CheckConstraintDiffAdded<T = DBCheckConstraint> {+ object: 'checkConstraint';+ type: 'added';+ tableId: string;+ newCheckConstraint: T;+}++export const createCheckConstraintDiffAddedSchema = <T = DBCheckConstraint>(+ checkConstraintSchema: z.ZodType<T>+): z.ZodType<CheckConstraintDiffAdded<T>> => {+ return z.object({+ object: z.literal('checkConstraint'),+ type: z.literal('added'),+ tableId: z.string(),+ newCheckConstraint: checkConstraintSchema,+ }) as z.ZodType<CheckConstraintDiffAdded<T>>;+};++export interface CheckConstraintDiffRemoved {+ object: 'checkConstraint';+ type: 'removed';+ checkConstraintId: string;+ tableId: string;+}++export const checkConstraintDiffRemovedSchema: z.ZodType<CheckConstraintDiffRemoved> =+ z.object({+ object: z.literal('checkConstraint'),+ type: z.literal('removed'),+ checkConstraintId: z.string(),+ tableId: z.string(),+ });++export interface CheckConstraintDiffChanged {+ object: 'checkConstraint';+ type: 'changed';+ checkConstraintId: string;+ newCheckConstraintId: string;+ tableId: string;+ attribute: CheckConstraintDiffAttribute;+ oldValue?: string | null;+ newValue?: string | null;+}++export const checkConstraintDiffChangedSchema: z.ZodType<CheckConstraintDiffChanged> =+ z.object({+ object: z.literal('checkConstraint'),+ type: z.literal('changed'),+ checkConstraintId: z.string(),+ newCheckConstraintId: z.string(),+ tableId: z.string(),+ attribute: checkConstraintDiffAttributeSchema,+ oldValue: z.string().nullable().optional(),+ newValue: z.string().nullable().optional(),+ });++export type CheckConstraintDiff<T = DBCheckConstraint> =+ | CheckConstraintDiffAdded<T>+ | CheckConstraintDiffRemoved+ | CheckConstraintDiffChanged;++export const createCheckConstraintDiffSchema = <T = DBCheckConstraint>(+ checkConstraintSchema: z.ZodType<T>+): z.ZodType<CheckConstraintDiff<T>> => {+ return z.union([+ createCheckConstraintDiffAddedSchema(checkConstraintSchema),+ checkConstraintDiffRemovedSchema,+ checkConstraintDiffChangedSchema,+ ]) as z.ZodType<CheckConstraintDiff<T>>;+};diff --git a/src/lib/domain/diff/diff-check/diff-check.ts b/src/lib/domain/diff/diff-check/diff-check.tsindex 6fac168f..6c3e3421 100644--- a/src/lib/domain/diff/diff-check/diff-check.ts+++ b/src/lib/domain/diff/diff-check/diff-check.ts@@ -4,6 +4,7 @@ import {defaultIndexTypeForDatabase,type DBIndex,} from '@/lib/domain/db-index';+import type { DBCheckConstraint } from '@/lib/domain/db-check-constraint';import type { DBTable } from '@/lib/domain/db-table';import type { DBRelationship } from '@/lib/domain/db-relationship';import type { Area } from '@/lib/domain/area';@@ -17,6 +18,10 @@ import type { TableDiff, TableDiffAttribute } from '../table-diff';import type { AreaDiff, AreaDiffAttribute } from '../area-diff';import type { NoteDiff, NoteDiffAttribute } from '../note-diff';import type { IndexDiff, IndexDiffAttribute } from '../index-diff';+import type {+ CheckConstraintDiff,+ CheckConstraintDiffAttribute,+} from '../check-constraint-diff';import type {RelationshipDiff,RelationshipDiffAttribute,@@ -115,6 +120,7 @@ export interface GenerateDiffOptions {includeTables?: boolean;includeFields?: boolean;includeIndexes?: boolean;+ includeCheckConstraints?: boolean;includeRelationships?: boolean;includeAreas?: boolean;includeNotes?: boolean;@@ -122,6 +128,7 @@ export interface GenerateDiffOptions {tables?: TableDiffAttribute[];fields?: FieldDiffAttribute[];indexes?: IndexDiffAttribute[];+ checkConstraints?: CheckConstraintDiffAttribute[];relationships?: RelationshipDiffAttribute[];areas?: AreaDiffAttribute[];notes?: NoteDiffAttribute[];@@ -130,6 +137,7 @@ export interface GenerateDiffOptions {changedTablesAttributes?: TableDiffAttribute[];changedFieldsAttributes?: FieldDiffAttribute[];changedIndexesAttributes?: IndexDiffAttribute[];+ changedCheckConstraintsAttributes?: CheckConstraintDiffAttribute[];changedRelationshipsAttributes?: RelationshipDiffAttribute[];changedAreasAttributes?: AreaDiffAttribute[];changedNotesAttributes?: NoteDiffAttribute[];@@ -138,6 +146,7 @@ export interface GenerateDiffOptions {tables?: TableDiff['type'][];fields?: FieldDiff['type'][];indexes?: IndexDiff['type'][];+ checkConstraints?: CheckConstraintDiff['type'][];relationships?: RelationshipDiff['type'][];areas?: AreaDiff['type'][];notes?: NoteDiff['type'][];@@ -146,6 +155,10 @@ export interface GenerateDiffOptions {table?: (table: DBTable, tables: DBTable[]) => DBTable | undefined;field?: (field: DBField, fields: DBField[]) => DBField | undefined;index?: (index: DBIndex, indexes: DBIndex[]) => DBIndex | undefined;+ checkConstraint?: (+ constraint: DBCheckConstraint,+ constraints: DBCheckConstraint[]+ ) => DBCheckConstraint | undefined;relationship?: (relationship: DBRelationship,relationships: DBRelationship[]@@ -168,6 +181,7 @@ export function generateDiff({changedTables: Map<string, boolean>;changedFields: Map<string, boolean>;changedIndexes: Map<string, boolean>;+ changedCheckConstraints: Map<string, boolean>;changedRelationships: Map<string, boolean>;changedAreas: Map<string, boolean>;changedNotes: Map<string, boolean>;@@ -178,6 +192,7 @@ export function generateDiff({includeTables: options.includeTables ?? true,includeFields: options.includeFields ?? true,includeIndexes: options.includeIndexes ?? true,+ includeCheckConstraints: options.includeCheckConstraints ?? true,includeRelationships: options.includeRelationships ?? true,includeAreas: options.includeAreas ?? false,includeNotes: options.includeNotes ?? false,@@ -191,6 +206,7 @@ export function generateDiff({const changedTables = new Map<string, boolean>();const changedFields = new Map<string, boolean>();const changedIndexes = new Map<string, boolean>();+ const changedCheckConstraints = new Map<string, boolean>();const changedRelationships = new Map<string, boolean>();const changedAreas = new Map<string, boolean>();const changedNotes = new Map<string, boolean>();@@ -200,6 +216,9 @@ export function generateDiff({const tableMatcher = mergedOptions.matchers?.table ?? defaultTableMatcher;const fieldMatcher = mergedOptions.matchers?.field ?? defaultFieldMatcher;const indexMatcher = mergedOptions.matchers?.index ?? defaultIndexMatcher;+ const checkConstraintMatcher =+ mergedOptions.matchers?.checkConstraint ??+ defaultCheckConstraintMatcher;const relationshipMatcher =mergedOptions.matchers?.relationship ?? defaultRelationshipMatcher;const areaMatcher = mergedOptions.matchers?.area ?? defaultAreaMatcher;@@ -220,7 +239,7 @@ export function generateDiff({});}- // Compare fields and indexes for matching tables+ // Compare fields, indexes, and check constraints for matching tablescompareTableContents({diagram,newDiagram,@@ -228,6 +247,7 @@ export function generateDiff({changedTables,changedFields,changedIndexes,+ changedCheckConstraints,options: mergedOptions,changedTablesAttributes:mergedOptions.changedMaps?.changedTablesAttributes,@@ -235,9 +255,12 @@ export function generateDiff({mergedOptions.changedMaps?.changedFieldsAttributes,changedIndexesAttributes:mergedOptions.changedMaps?.changedIndexesAttributes,+ changedCheckConstraintsAttributes:+ mergedOptions.changedMaps?.changedCheckConstraintsAttributes,tableMatcher,fieldMatcher,indexMatcher,+ checkConstraintMatcher,databaseType: diagram.databaseType,});@@ -292,6 +315,7 @@ export function generateDiff({changedTables,changedFields,changedIndexes,+ changedCheckConstraints,changedRelationships,changedAreas,changedNotes,@@ -539,7 +563,7 @@ function compareTables({}}-// Compare fields and indexes for matching tables+// Compare fields, indexes, and check constraints for matching tablesfunction compareTableContents({diagram,newDiagram,@@ -547,13 +571,16 @@ function compareTableContents({changedTables,changedFields,changedIndexes,+ changedCheckConstraints,options,changedTablesAttributes,changedFieldsAttributes,changedIndexesAttributes,+ changedCheckConstraintsAttributes,tableMatcher,fieldMatcher,indexMatcher,+ checkConstraintMatcher,databaseType,}: {diagram: Diagram;@@ -562,13 +589,19 @@ function compareTableContents({changedTables: Map<string, boolean>;changedFields: Map<string, boolean>;changedIndexes: Map<string, boolean>;+ changedCheckConstraints: Map<string, boolean>;options?: GenerateDiffOptions;changedTablesAttributes?: TableDiffAttribute[];changedFieldsAttributes?: FieldDiffAttribute[];changedIndexesAttributes?: IndexDiffAttribute[];+ changedCheckConstraintsAttributes?: CheckConstraintDiffAttribute[];tableMatcher: (table: DBTable, tables: DBTable[]) => DBTable | undefined;fieldMatcher: (field: DBField, fields: DBField[]) => DBField | undefined;indexMatcher: (index: DBIndex, indexes: DBIndex[]) => DBIndex | undefined;+ checkConstraintMatcher: (+ constraint: DBCheckConstraint,+ constraints: DBCheckConstraint[]+ ) => DBCheckConstraint | undefined;databaseType: DatabaseType;}) {const oldTables = diagram.tables || [];@@ -613,6 +646,23 @@ function compareTableContents({databaseType,});}++ // Compare check constraints+ if (options?.includeCheckConstraints) {+ compareCheckConstraints({+ tableId: oldTable.id,+ oldCheckConstraints: oldTable.checkConstraints ?? [],+ newCheckConstraints: newTable.checkConstraints ?? [],+ diffMap,+ changedTables,+ changedCheckConstraints,+ attributes: options?.attributes?.checkConstraints,+ changedTablesAttributes,+ changedCheckConstraintsAttributes,+ changeTypes: options?.changeTypes?.checkConstraints,+ checkConstraintMatcher,+ });+ }}}@@ -1112,6 +1162,150 @@ function compareIndexProperties({}}+// Compare check constraints between tables+function compareCheckConstraints({+ tableId,+ oldCheckConstraints,+ newCheckConstraints,+ diffMap,+ changedTables,+ changedCheckConstraints,+ attributes,+ changedTablesAttributes,+ changedCheckConstraintsAttributes,+ changeTypes,+ checkConstraintMatcher,+}: {+ tableId: string;+ oldCheckConstraints: DBCheckConstraint[];+ newCheckConstraints: DBCheckConstraint[];+ diffMap: DiffMap;+ changedTables: Map<string, boolean>;+ changedCheckConstraints: Map<string, boolean>;+ attributes?: CheckConstraintDiffAttribute[];+ changedTablesAttributes?: TableDiffAttribute[];+ changedCheckConstraintsAttributes?: CheckConstraintDiffAttribute[];+ changeTypes?: CheckConstraintDiff['type'][];+ checkConstraintMatcher: (+ constraint: DBCheckConstraint,+ constraints: DBCheckConstraint[]+ ) => DBCheckConstraint | undefined;+}) {+ // If changeTypes is empty array, don't check any changes+ if (changeTypes && changeTypes.length === 0) {+ return;+ }++ // If changeTypes is undefined, check all types+ const typesToCheck = changeTypes ?? ['added', 'removed', 'changed'];++ // For structural changes (added/removed constraints), add to changedTables unless+ // changedTablesAttributes is explicitly set to empty array+ const shouldAddToChangedTables =+ changedTablesAttributes === undefined ||+ changedTablesAttributes.length > 0;++ // Check for added check constraints+ if (typesToCheck.includes('added')) {+ for (const newConstraint of newCheckConstraints) {+ if (!checkConstraintMatcher(newConstraint, oldCheckConstraints)) {+ diffMap.set(+ getDiffMapKey({+ diffObject: 'checkConstraint',+ objectId: newConstraint.id,+ }),+ {+ object: 'checkConstraint',+ type: 'added',+ newCheckConstraint: newConstraint,+ tableId,+ }+ );+ if (shouldAddToChangedTables) {+ changedTables.set(tableId, true);+ }+ changedCheckConstraints.set(newConstraint.id, true);+ }+ }+ }++ // Check for removed check constraints+ if (typesToCheck.includes('removed')) {+ for (const oldConstraint of oldCheckConstraints) {+ if (!checkConstraintMatcher(oldConstraint, newCheckConstraints)) {+ diffMap.set(+ getDiffMapKey({+ diffObject: 'checkConstraint',+ objectId: oldConstraint.id,+ }),+ {+ object: 'checkConstraint',+ type: 'removed',+ checkConstraintId: oldConstraint.id,+ tableId,+ }+ );+ if (shouldAddToChangedTables) {+ changedTables.set(tableId, true);+ }+ changedCheckConstraints.set(oldConstraint.id, true);+ }+ }+ }++ // Check for check constraint changes (expression changes)+ if (typesToCheck.includes('changed')) {+ for (const oldConstraint of oldCheckConstraints) {+ const newConstraint = checkConstraintMatcher(+ oldConstraint,+ newCheckConstraints+ );+ if (!newConstraint) continue;++ // If attributes are specified, only check those attributes+ const attributesToCheck: CheckConstraintDiffAttribute[] =+ attributes ?? ['expression'];++ if (+ attributesToCheck.includes('expression') &&+ oldConstraint.expression !== newConstraint.expression+ ) {+ diffMap.set(+ getDiffMapKey({+ diffObject: 'checkConstraint',+ objectId: oldConstraint.id,+ attribute: 'expression',+ }),+ {+ object: 'checkConstraint',+ type: 'changed',+ checkConstraintId: oldConstraint.id,+ newCheckConstraintId: newConstraint.id,+ tableId,+ attribute: 'expression',+ oldValue: oldConstraint.expression,+ newValue: newConstraint.expression,+ }+ );++ if (+ shouldAddToChangedMap(+ 'expression',+ changedCheckConstraintsAttributes+ )+ ) {+ if (changedTablesAttributes === undefined) {+ changedTables.set(tableId, true);+ } else if (changedTablesAttributes.length > 0) {+ changedTables.set(tableId, true);+ }+ changedCheckConstraints.set(oldConstraint.id, true);+ }+ }+ }+ }+}+// Compare relationships between diagramsfunction compareRelationships({diagram,@@ -1880,6 +2074,29 @@ const defaultIndexMatcher = (return undefined;};+const defaultCheckConstraintMatcher = (+ constraint: DBCheckConstraint,+ constraints: DBCheckConstraint[]+): DBCheckConstraint | undefined => {+ // Priority 1: Match by ID+ const byId = constraints.find((c) => c.id === constraint.id);+ if (byId) {+ return byId;+ }++ // Priority 2: Match by expression (only if unique match)+ if (constraint.expression) {+ const byExpression = constraints.filter(+ (c) => c.expression === constraint.expression+ );+ if (byExpression.length === 1) {+ return byExpression[0];+ }+ }++ return undefined;+};+const defaultRelationshipMatcher = (relationship: DBRelationship,relationships: DBRelationship[]diff --git a/src/lib/domain/diff/diff.ts b/src/lib/domain/diff/diff.tsindex faab4cd7..60df14b1 100644--- a/src/lib/domain/diff/diff.ts+++ b/src/lib/domain/diff/diff.ts@@ -1,5 +1,7 @@import { z } from 'zod';+import type { CheckConstraintDiff } from './check-constraint-diff';+import { createCheckConstraintDiffSchema } from './check-constraint-diff';import type { FieldDiff } from './field-diff';import { createFieldDiffSchema } from './field-diff';import type { IndexDiff } from './index-diff';@@ -12,12 +14,21 @@ import type { AreaDiff } from './area-diff';import { createAreaDiffSchema } from './area-diff';import type { NoteDiff } from './note-diff';import { createNoteDiffSchema } from './note-diff';-import type { DBField, DBIndex, DBRelationship, DBTable, Area, Note } from '..';+import type {+ DBCheckConstraint,+ DBField,+ DBIndex,+ DBRelationship,+ DBTable,+ Area,+ Note,+} from '..';export type ChartDBDiff<TTable = DBTable,TField = DBField,TIndex = DBIndex,+ TCheckConstraint = DBCheckConstraint,TRelationship = DBRelationship,TArea = Area,TNote = Note,@@ -25,6 +36,7 @@ export type ChartDBDiff<| TableDiff<TTable>| FieldDiff<TField>| IndexDiff<TIndex>+ | CheckConstraintDiff<TCheckConstraint>| RelationshipDiff<TRelationship>| AreaDiff<TArea>| NoteDiff<TNote>;@@ -33,6 +45,7 @@ export const createChartDBDiffSchema = <TTable = DBTable,TField = DBField,TIndex = DBIndex,+ TCheckConstraint = DBCheckConstraint,TRelationship = DBRelationship,TArea = Area,TNote = Note,@@ -40,21 +53,39 @@ export const createChartDBDiffSchema = <tableSchema: z.ZodType<TTable>,fieldSchema: z.ZodType<TField>,indexSchema: z.ZodType<TIndex>,+ checkConstraintSchema: z.ZodType<TCheckConstraint>,relationshipSchema: z.ZodType<TRelationship>,areaSchema: z.ZodType<TArea>,noteSchema: z.ZodType<TNote>): z.ZodType<- ChartDBDiff<TTable, TField, TIndex, TRelationship, TArea, TNote>+ ChartDBDiff<+ TTable,+ TField,+ TIndex,+ TCheckConstraint,+ TRelationship,+ TArea,+ TNote+ >> => {return z.union([createTableDiffSchema(tableSchema),createFieldDiffSchema(fieldSchema),createIndexDiffSchema(indexSchema),+ createCheckConstraintDiffSchema(checkConstraintSchema),createRelationshipDiffSchema(relationshipSchema),createAreaDiffSchema(areaSchema),createNoteDiffSchema(noteSchema),]) as z.ZodType<- ChartDBDiff<TTable, TField, TIndex, TRelationship, TArea, TNote>+ ChartDBDiff<+ TTable,+ TField,+ TIndex,+ TCheckConstraint,+ TRelationship,+ TArea,+ TNote+ >>;};@@ -62,18 +93,28 @@ export type DiffMap<TTable = DBTable,TField = DBField,TIndex = DBIndex,+ TCheckConstraint = DBCheckConstraint,TRelationship = DBRelationship,TArea = Area,TNote = Note,> = Map<string,- ChartDBDiff<TTable, TField, TIndex, TRelationship, TArea, TNote>+ ChartDBDiff<+ TTable,+ TField,+ TIndex,+ TCheckConstraint,+ TRelationship,+ TArea,+ TNote+ >>;export type DiffObject<TTable = DBTable,TField = DBField,TIndex = DBIndex,+ TCheckConstraint = DBCheckConstraint,TRelationship = DBRelationship,TArea = Area,TNote = Note,@@ -81,6 +122,7 @@ export type DiffObject<| TableDiff<TTable>['object']| FieldDiff<TField>['object']| IndexDiff<TIndex>['object']+ | CheckConstraintDiff<TCheckConstraint>['object']| RelationshipDiff<TRelationship>['object']| AreaDiff<TArea>['object']| NoteDiff<TNote>['object'];@@ -95,23 +137,49 @@ export type DiffKind<TTable = DBTable,TField = DBField,TIndex = DBIndex,+ TCheckConstraint = DBCheckConstraint,TRelationship = DBRelationship,TArea = Area,TNote = Note,> = ExtractDiffKind<- ChartDBDiff<TTable, TField, TIndex, TRelationship, TArea, TNote>+ ChartDBDiff<+ TTable,+ TField,+ TIndex,+ TCheckConstraint,+ TRelationship,+ TArea,+ TNote+ >>;export const isDiffOfKind = <TTable = DBTable,TField = DBField,TIndex = DBIndex,+ TCheckConstraint = DBCheckConstraint,TRelationship = DBRelationship,TArea = Area,TNote = Note,>(- diff: ChartDBDiff<TTable, TField, TIndex, TRelationship, TArea, TNote>,- kind: DiffKind<TTable, TField, TIndex, TRelationship, TArea, TNote>+ diff: ChartDBDiff<+ TTable,+ TField,+ TIndex,+ TCheckConstraint,+ TRelationship,+ TArea,+ TNote+ >,+ kind: DiffKind<+ TTable,+ TField,+ TIndex,+ TCheckConstraint,+ TRelationship,+ TArea,+ TNote+ >): boolean => {if ('attribute' in kind) {return (diff --git a/src/lib/domain/index.ts b/src/lib/domain/index.tsindex 456f2e88..2b93fa9d 100644--- a/src/lib/domain/index.ts+++ b/src/lib/domain/index.ts@@ -3,6 +3,7 @@ export * from './config';export * from './database-clients';export * from './database-edition';export * from './database-type';+export * from './db-check-constraint';export * from './db-custom-type';export * from './db-dependency';export * from './db-field';diff --git a/src/pages/editor-page/side-panel/tables-section/table-list/table-list-item/table-list-item-content/table-check-constraint/table-check-constraint.tsx b/src/pages/editor-page/side-panel/tables-section/table-list/table-list-item/table-list-item-content/table-check-constraint/table-check-constraint.tsxnew file mode 100644index 00000000..073ac35e--- /dev/null+++ b/src/pages/editor-page/side-panel/tables-section/table-list/table-list-item/table-list-item-content/table-check-constraint/table-check-constraint.tsx@@ -0,0 +1,139 @@+import React, { useMemo } from 'react';+import { AlertCircle, Ellipsis, Trash2 } from 'lucide-react';+import { Button } from '@/components/button/button';+import type { DBCheckConstraint } from '@/lib/domain/db-check-constraint';+import {+ Popover,+ PopoverContent,+ PopoverTrigger,+} from '@/components/popover/popover';+import { Separator } from '@/components/separator/separator';+import { Label } from '@/components/label/label';+import { Textarea } from '@/components/textarea/textarea';+import { useTranslation } from 'react-i18next';+import { useChartDB } from '@/hooks/use-chartdb';+import { validateCheckConstraintWithDetails } from '@/lib/check-constraints/check-constraints-validator';++export interface TableCheckConstraintProps {+ constraint: DBCheckConstraint;+ updateConstraint: (attrs: Partial<DBCheckConstraint>) => void;+ removeConstraint: () => void;+}++export const TableCheckConstraint: React.FC<TableCheckConstraintProps> = ({+ constraint,+ updateConstraint,+ removeConstraint,+}) => {+ const { t } = useTranslation();+ const { readonly } = useChartDB();++ // Validate the expression and memoize the result+ const validationResult = useMemo(() => {+ // Empty expressions are allowed (user might be in the middle of typing)+ if (!constraint.expression || !constraint.expression.trim()) {+ return { isValid: true };+ }+ return validateCheckConstraintWithDetails(constraint.expression);+ }, [constraint.expression]);++ const hasError = !validationResult.isValid;++ return (+ <div className="flex flex-1 flex-row items-center justify-between gap-1 py-0.5">+ <div+ className={`flex h-8 min-w-0 flex-1 items-center gap-1.5 rounded-md border bg-slate-50 px-2.5 dark:bg-slate-900 ${+ hasError+ ? 'border-red-300 dark:border-red-700'+ : 'border-input'+ }`}+ >+ {hasError && (+ <AlertCircle className="size-3 shrink-0 text-red-500" />+ )}+ <code+ className={`min-w-0 flex-1 truncate font-mono text-xs ${+ hasError+ ? 'text-red-600 dark:text-red-400'+ : 'text-slate-700 dark:text-slate-300'+ }`}+ >+ {constraint.expression || (+ <span className="italic text-slate-400 dark:text-slate-500">+ empty+ </span>+ )}+ </code>+ </div>+ <div className="flex shrink-0">+ <Popover>+ <PopoverTrigger asChild>+ <Button+ variant="ghost"+ className="size-8 p-2 text-slate-500 hover:bg-primary-foreground hover:text-slate-700 dark:text-slate-400 dark:hover:text-slate-200"+ >+ <Ellipsis className="size-3.5" />+ </Button>+ </PopoverTrigger>+ <PopoverContent className="w-72">+ <div className="flex flex-col gap-2">+ <div className="text-sm font-semibold">+ {t(+ 'side_panel.tables_section.table.check_constraint_actions.title'+ )}+ </div>+ <Separator orientation="horizontal" />+ <div className="flex flex-col gap-2">+ <Label+ htmlFor="constraint-expression"+ className="text-subtitle"+ >+ {t(+ 'side_panel.tables_section.table.check_constraint_actions.expression'+ )}+ </Label>+ <Textarea+ id="constraint-expression"+ value={constraint.expression}+ onChange={(e) =>+ updateConstraint({+ expression: e.target.value,+ })+ }+ readOnly={readonly}+ className={`min-h-[60px] font-mono text-xs ${+ hasError+ ? 'border-red-500 focus-visible:ring-red-500'+ : ''+ }`}+ placeholder="e.g., price > 0"+ />+ {hasError && validationResult.error && (+ <div className="flex items-start gap-1.5 text-xs text-red-600 dark:text-red-400">+ <AlertCircle className="mt-0.5 size-3 shrink-0" />+ <span>{validationResult.error}</span>+ </div>+ )}+ </div>+ {!readonly ? (+ <>+ <Separator orientation="horizontal" />+ <Button+ variant="outline"+ className="flex gap-2 !text-red-700"+ onClick={removeConstraint}+ >+ <Trash2 className="size-3.5 text-red-700" />+ {t(+ 'side_panel.tables_section.table.check_constraint_actions.delete'+ )}+ </Button>+ </>+ ) : null}+ </div>+ </PopoverContent>+ </Popover>+ </div>+ </div>+ );+};diff --git a/src/pages/editor-page/side-panel/tables-section/table-list/table-list-item/table-list-item-content/table-list-item-content.tsx b/src/pages/editor-page/side-panel/tables-section/table-list/table-list-item/table-list-item-content/table-list-item-content.tsxindex a5ae96e5..2adca410 100644--- a/src/pages/editor-page/side-panel/tables-section/table-list/table-list-item/table-list-item-content/table-list-item-content.tsx+++ b/src/pages/editor-page/side-panel/tables-section/table-list/table-list-item/table-list-item-content/table-list-item-content.tsx@@ -1,5 +1,11 @@import React, { useCallback } from 'react';-import { Plus, FileType2, FileKey2, MessageCircleMore } from 'lucide-react';+import {+ Plus,+ FileType2,+ FileKey2,+ MessageCircleMore,+ ListChecks,+} from 'lucide-react';import { Button } from '@/components/button/button';import {Accordion,@@ -10,9 +16,11 @@ import {import { Separator } from '@/components/separator/separator';import type { DBTable } from '@/lib/domain/db-table';import type { DBField } from '@/lib/domain/db-field';+import type { DBCheckConstraint } from '@/lib/domain/db-check-constraint';import { useChartDB } from '@/hooks/use-chartdb';import { TableField } from './table-field/table-field';import { TableIndex } from './table-index/table-index';+import { TableCheckConstraint } from './table-check-constraint/table-check-constraint';import type { DBIndex } from '@/lib/domain/db-index';import { useTranslation } from 'react-i18next';import { Textarea } from '@/components/textarea/textarea';@@ -31,7 +39,7 @@ import {} from '@dnd-kit/sortable';import { ColorPicker } from '@/components/color-picker/color-picker';-type AccordionItemValue = 'fields' | 'indexes';+type AccordionItemValue = 'fields' | 'indexes' | 'checks';export interface TableListItemContentProps {table: DBTable;@@ -47,6 +55,9 @@ export const TableListItemContent: React.FC<TableListItemContentProps> = ({createIndex,removeIndex,updateIndex,+ createCheckConstraint,+ removeCheckConstraint,+ updateCheckConstraint,updateTable,readonly,databaseType,@@ -122,6 +133,17 @@ export const TableListItemContent: React.FC<TableListItemContentProps> = ({[createField, table.id]);+ const createCheckConstraintHandler = useCallback(+ (e: React.MouseEvent<HTMLButtonElement, MouseEvent>) => {+ e.stopPropagation();+ setSelectedItems((prev) =>+ prev.includes('checks') ? prev : [...prev, 'checks']+ );+ createCheckConstraint(table.id);+ },+ [createCheckConstraint, table.id, setSelectedItems]+ );+return (<divclassName="flex flex-col gap-1 rounded-b-md border-l-[6px] px-1"@@ -284,6 +306,80 @@ export const TableListItemContent: React.FC<TableListItemContentProps> = ({</AccordionItem>) : null}+ <AccordionItem value="checks" className="mb-2 border-y-0">+ <AccordionTrigger+ iconPosition="right"+ className="group flex flex-1 p-0 px-2 py-1 text-xs text-subtitle hover:bg-secondary"+ asChild+ >+ <div className="flex flex-1 items-center justify-between">+ <div className="flex flex-row items-center gap-1">+ <ListChecks className="size-4" />+ {t(+ 'side_panel.tables_section.table.check_constraints'+ )}+ </div>+ {!readonly ? (+ <div className="flex flex-row-reverse">+ <div className="hidden flex-row-reverse group-hover:flex">+ <Button+ variant="ghost"+ className="size-4 p-0 text-xs hover:bg-primary-foreground"+ onClick={+ createCheckConstraintHandler+ }+ >+ <Plus className="size-4 shrink-0 text-muted-foreground transition-transform duration-200" />+ </Button>+ </div>+ </div>+ ) : null}+ </div>+ </AccordionTrigger>+ <AccordionContent className="pb-0 pt-1">+ <div className="flex flex-col gap-1">+ {(table.checkConstraints ?? []).map(+ (constraint) => (+ <TableCheckConstraint+ key={constraint.id}+ constraint={constraint}+ removeConstraint={() =>+ removeCheckConstraint(+ table.id,+ constraint.id+ )+ }+ updateConstraint={(+ attrs: Partial<DBCheckConstraint>+ ) =>+ updateCheckConstraint(+ table.id,+ constraint.id,+ attrs+ )+ }+ />+ )+ )}+ </div>++ {!readonly ? (+ <div className="flex justify-start p-1">+ <Button+ variant="ghost"+ className="flex h-7 items-center gap-1 px-2 text-xs"+ onClick={createCheckConstraintHandler}+ >+ <Plus className="size-4 text-muted-foreground" />+ {t(+ 'side_panel.tables_section.table.add_check'+ )}+ </Button>+ </div>+ ) : null}+ </AccordionContent>+ </AccordionItem>+<AccordionItem value="comments" className="border-y-0"><AccordionTriggericonPosition="right"