romeerez / orchid-orm

Orchid ORM
https://orchid-orm.netlify.app/
MIT License
493 stars 14 forks source link

Adding `EXCLUDE` checks with GiST #419

Open mordechaim opened 3 days ago

mordechaim commented 3 days ago

I'm dealing with time ranges; with some research I discovered a special type of checks to ensure time ranges between rows don't overlap, using the btree_gist Postgres extension and this syntax:

ADD CONSTRAINT "overlap_exclude"
EXLUDE USING GIST (
    "room_id" with =,
    tstzrange("start", "end") with &&
)

I did not find Orchid to support this notation, I created a manual migration, but now I can't run any new generations (seemingly some validation finds a discrepancy with existing checks). I get this error:

error: relation "orchidtmpview10" does not exist
    at [redacted]\node_modules\pg\lib\client.js:535:17
    at process.processTicksAndRejections (node:internal/process/task_queues:105:5)
    at async performQuery$1 ([redacted]\node_modules\pqb\src\adapter.ts:188:12)
    at async <anonymous> ([redacted]\node_modules\orchid-orm\src\migrations\generate\generators\generators.utils.ts:51:13)
    at async Promise.all (index 9)
    at async compareSqlExpressions ([redacted]\questboard\node_modules\orchid-orm\src\migrations\generate\generators\generators.utils.ts:25:5)
    at async Promise.all (index 1)
    at async processTables ([redacted]\node_modules\orchid-orm\src\migrations\generate\generators\tables.generator.ts:131:3)
    at async composeMigration ([redacted]\node_modules\orchid-orm\src\migrations\generate\composeMigration.ts:52:9)
    at async generate ([redacted]\node_modules\orchid-orm\src\migrations\generate\generate.ts:113:21) {
  length: 113,
  severity: 'ERROR',
  code: '42P01',
  hint: undefined,
  position: undefined,
  internalPosition: undefined,
  internalQuery: undefined,
  where: undefined,
  schema: undefined,
  table: undefined,
  column: undefined,
  dataType: undefined,
  constraint: undefined,
  file: 'namespace.c',
  line: '434',
  routine: 'RangeVarGetRelidExtended'
}

GiST also allow adding range indexes for faster querying, like

CREATE INDEX ON table USING GIST (
    tstzrange("start", "end")
)

Which would be nice to support.

mordechaim commented 3 days ago

Perhaps supporting t.constraint() with raw SQL in the same fashion as t.check() would be the most flexible.

And for index, adding support for raw SQL index.