|
| 1 | +// test/validator-check/regex.test.ts |
| 2 | +import { describe, test, expect } from "bun:test"; |
| 3 | +import { MetaDataLoader, InMemoryStringSource } from "@metaobjectsdev/metadata"; |
| 4 | +import type { MetaData } from "@metaobjectsdev/metadata"; |
| 5 | +import { buildExpectedSchema } from "../../src/expected-schema.js"; |
| 6 | +import type { Dialect } from "../../src/types.js"; |
| 7 | + |
| 8 | +async function load(json: string): Promise<MetaData> { |
| 9 | + return (await new MetaDataLoader().load([new InMemoryStringSource(json)])).root; |
| 10 | +} |
| 11 | +const ENTITY = (fieldChildren: string) => JSON.stringify({ |
| 12 | + "metadata.root": { children: [{ |
| 13 | + "object.entity": { name: "User", children: [ |
| 14 | + { "field.long": { name: "id" } }, |
| 15 | + ...JSON.parse(fieldChildren), |
| 16 | + { "source.rdb": { name: "src", "@table": "users" } }, |
| 17 | + { "identity.primary": { name: "pk", "@fields": ["id"], "@generation": "increment" } }, |
| 18 | + ] }, |
| 19 | + }] }, |
| 20 | +}); |
| 21 | +function checks(root: MetaData, dialect: Dialect) { |
| 22 | + return buildExpectedSchema(root, { dialect }).tables[0]!.checks; |
| 23 | +} |
| 24 | + |
| 25 | +describe("validator.regex → CHECK", () => { |
| 26 | + test("postgres: @pattern → ~ check", async () => { |
| 27 | + const root = await load(ENTITY(`[{"field.string":{"name":"slug","children":[ |
| 28 | + {"validator.regex":{"name":"re","@pattern":"^[a-z]+$"}}]}}]`)); |
| 29 | + const c = checks(root, "postgres").find((x) => x.name === "users_slug_regex_chk"); |
| 30 | + expect(c?.expression).toBe("slug ~ '^[a-z]+$'"); |
| 31 | + }); |
| 32 | + test("single-quote in pattern is escaped", async () => { |
| 33 | + const root = await load(ENTITY(`[{"field.string":{"name":"q","children":[ |
| 34 | + {"validator.regex":{"name":"re","@pattern":"o'brien"}}]}}]`)); |
| 35 | + const c = checks(root, "postgres").find((x) => x.name === "users_q_regex_chk"); |
| 36 | + expect(c?.expression).toBe("q ~ 'o''brien'"); |
| 37 | + }); |
| 38 | + test("sqlite: regex emits NO check (no native regex)", async () => { |
| 39 | + const root = await load(ENTITY(`[{"field.string":{"name":"slug","children":[ |
| 40 | + {"validator.regex":{"name":"re","@pattern":"^[a-z]+$"}}]}}]`)); |
| 41 | + expect(checks(root, "sqlite").some((x) => x.name.includes("_regex_chk"))).toBe(false); |
| 42 | + }); |
| 43 | +}); |
0 commit comments