diff --git a/README.md b/README.md index fc8aeae61..9c7034730 100644 --- a/README.md +++ b/README.md @@ -127,7 +127,11 @@ Inspect the structure and data quality, then add [business definitions](https:// const schema = await ava.schema(); const profile = await ava.profile({ metrics: ['row_count', 'null_count'] }); await ava.semantic(undefined, () => ({ - description: 'Use the sales column for amounts after discounts and order_date for monthly comparisons.', + models: [{ + name: 'sales', + description: 'Use sales for amounts after discounts and order_date for monthly comparisons.', + datasets: [{ name: 'orders', source: 'data' }], + }], })); ``` diff --git a/README.zh-CN.md b/README.zh-CN.md index ab792ac49..6d9e7fafd 100644 --- a/README.zh-CN.md +++ b/README.zh-CN.md @@ -127,7 +127,11 @@ await ava.source({ type: 'csv-file', options: { path: './sales.csv' } }); const schema = await ava.schema(); const profile = await ava.profile({ metrics: ['row_count', 'null_count'] }); await ava.semantic(undefined, () => ({ - description: 'sales 字段表示折后销售额,月度比较使用 order_date 字段。', + models: [{ + name: 'sales', + description: 'sales 表示折后销售额,按月比较时使用 order_date。', + datasets: [{ name: 'orders', source: 'data' }], + }], })); ``` diff --git a/__tests__/ava.test.ts b/__tests__/ava.test.ts index 27b7f16d6..639ba70c1 100644 --- a/__tests__/ava.test.ts +++ b/__tests__/ava.test.ts @@ -530,6 +530,10 @@ describe('AVA metadata setters', () => { ], }; + function semanticDescription(description: string): Semantic { + return { models: [{ name: 'sales', description, datasets: [{ name: 'values', source: 'data' }] }] }; + } + afterEach(() => vi.restoreAllMocks()); it.each(['duckdb', 'javascript'])( @@ -540,26 +544,28 @@ describe('AVA metadata setters', () => { await ava.source(source); const discover = vi.spyOn(ava.engine!, 'schema'); expect(await ava.semantic()).toEqual({}); - const definitions: Semantic = { - description: 'Sales definitions', - properties: { currency: 'USD' }, + const definitions = { models: [ { - ...schema.models[0], - properties: { description: 'Values' }, - columns: [{ name: 'value', type: 'number', properties: { unit: 'USD' } }], + name: 'sales', + description: 'Sales definitions', + datasets: [ + { + name: 'values', + source: 'data', + fields: [ + { + name: 'value', + expression: { sql: 'value' }, + description: 'Values in USD', + }, + ], + metrics: [{ name: 'total', expression: { sql: 'SUM(value)' } }], + }, + ], }, ], - relationships: [], - views: [{ name: 'positive_values', statement: 'SELECT * FROM data WHERE value > 0' }], - cubes: [ - { - name: 'values', - baseObject: 'data', - measures: [{ name: 'total', expression: 'SUM(value)', type: 'DOUBLE' }], - }, - ], - }; + } satisfies Semantic; const expected = structuredClone(definitions); const options = {}; const setter = vi.fn(() => definitions); @@ -573,8 +579,8 @@ describe('AVA metadata setters', () => { { type: 'semanticstart', data: {} }, { type: 'semanticend', data: {} }, ]); - definitions.description = 'changed'; - definitions.models[0].columns[0].properties.unit = 'changed'; + definitions.models[0].description = 'changed'; + definitions.models[0].datasets[0].fields[0].description = 'changed'; expect(await ava.semantic()).toEqual(expected); expect(onSemantic).toHaveBeenCalledTimes(2); @@ -589,11 +595,11 @@ describe('AVA metadata setters', () => { await ava.translate('Total'); const context = getDSL.mock.calls[0][1]; const snapshot = structuredClone(context); - expect(context).toMatchObject(expected); + expect(context.semantic).toEqual(expected); expect(context.models[0].metrics).toEqual({ row_count: 2 }); expect(context.models[0].columns[0]).toMatchObject({ metrics: { mean: 3 }, - properties: { logicalType: 'numeric', unit: 'USD' }, + logicalType: 'numeric', }); expect( (await ava.analyze('Total', { includeSummary: false, strategy: { type: 'direct', maxRetries: 0 } })).data @@ -608,7 +614,7 @@ describe('AVA metadata setters', () => { await ava.semantic(undefined, () => ({})); await ava.translate('Total'); - expect(getDSL.mock.calls.at(-1)[1]).not.toHaveProperty('cubes'); + expect(getDSL.mock.calls.at(-1)[1]).not.toHaveProperty('semantic'); expect(getDSL.mock.calls[0][1]).toEqual(snapshot); } finally { await ava.dispose(); @@ -620,7 +626,7 @@ describe('AVA metadata setters', () => { const ava = new AVA({ llm, engine: { type: 'javascript' } }); try { await ava.source(source); - const setter = vi.fn(() => ({ description: 'Original' })); + const setter = vi.fn(() => semanticDescription('Original')); await ava.semantic(undefined, setter); expect(setter).toHaveBeenCalledExactlyOnceWith({}); const onEnd = vi.fn(); @@ -634,9 +640,44 @@ describe('AVA metadata setters', () => { await expect( ava.semantic(undefined, () => ({ cubes: [{ name: 'invalid', measures: [] }] } as never)) ).rejects.toThrow(); + await expect( + ava.semantic(undefined, () => ({ + models: [ + { + name: 'sales', + datasets: [ + { + name: 'orders', + source: 'data', + fields: [{ name: 'id', expression: { sql: 'id' } }], + primary_key: ['unknown'], + unique_keys: [['id', 'id']], + }, + ], + relationships: [ + { + name: 'order_customer', + from: 'orders', + to: 'customers', + from_columns: ['id', 'customer_id'], + to_columns: ['id'], + }, + ], + }, + ], + })) + ).rejects.toMatchObject({ + issues: expect.arrayContaining([ + expect.objectContaining({ path: ['models', 0, 'datasets', 0, 'primary_key', 0] }), + expect.objectContaining({ path: ['models', 0, 'datasets', 0, 'unique_keys', 0, 1] }), + expect.objectContaining({ path: ['models', 0, 'relationships', 0, 'to_columns'] }), + expect.objectContaining({ path: ['models', 0, 'relationships', 0, 'from_columns', 1] }), + expect.objectContaining({ path: ['models', 0, 'relationships', 0, 'to'] }), + ]), + }); expect(onEnd.mock.calls[0][0].data.error.message).toBe(error.message); expect(onEnd.mock.calls[1][0].data.error.name).toBe('ZodError'); - expect(await ava.semantic()).toEqual({ description: 'Original' }); + expect(await ava.semantic()).toEqual(semanticDescription('Original')); } finally { await ava.dispose(); } @@ -805,7 +846,7 @@ describe('AVA metadata setters', () => { await ava.source(source); await ava.schema(undefined, () => schema); await ava.profile(undefined, () => profile); - await ava.semantic(undefined, () => ({ description: 'Previous source' })); + await ava.semantic(undefined, () => semanticDescription('Previous source')); await ava.source(source); expect(await ava.semantic()).toEqual({}); const discover = vi.spyOn(ava.engine!, 'schema'); @@ -816,13 +857,13 @@ describe('AVA metadata setters', () => { expect(getDSL).toHaveBeenLastCalledWith('Rows', schema); await ava.schema(undefined, () => schema); await ava.profile(undefined, () => profile); - await ava.semantic(undefined, () => ({ description: 'Failed source' })); + await ava.semantic(undefined, () => semanticDescription('Failed source')); await expect(ava.source({ type: 'parquet', options: { path: 'unsupported.parquet' } })).rejects.toThrow(); expect(ava.engine).toBeNull(); await expect(ava.schema()).rejects.toThrow('No data loaded'); await ava.source(source); expect(await ava.semantic()).toEqual({}); - await ava.semantic(undefined, () => ({ description: 'Disposed source' })); + await ava.semantic(undefined, () => semanticDescription('Disposed source')); } finally { await ava.dispose(); } diff --git a/__tests__/cli-session.test.ts b/__tests__/cli-session.test.ts index 5ef4e6008..53cb60d8d 100644 --- a/__tests__/cli-session.test.ts +++ b/__tests__/cli-session.test.ts @@ -9,7 +9,7 @@ import { buildDataModel } from '../src/util/data-model'; import { startupSchema, requestSchema } from '../src/cli/session/protocol'; import { sessionDirectory } from '../src/cli/session/transport'; -import type { DataSourceConfig, EngineConfig, Schema } from '../src/types'; +import type { DataSourceConfig, EngineConfig, Schema, Semantic } from '../src/types'; vi.mock('child_process', async (importOriginal) => ({ ...(await importOriginal()), @@ -265,7 +265,9 @@ describe('dataset engine and language', () => { ], }; await datasets.createDataset([source], llm, 'javascript'); - const semantic = { description: 'Sales are in USD.', properties: { confirmedBy: 'user' } }; + const semantic = { + models: [{ name: 'sales', description: 'Sales are in USD.', datasets: [{ name: 'orders', source: 'data' }] }], + } satisfies Semantic; expect(await datasets.withDataset((ava) => ava.semantic())).toEqual({}); await datasets.withDataset((ava) => ava.semantic(undefined, () => semantic)); expect(await datasets.describeDataset(schema)).toMatchObject(schema); diff --git a/__tests__/cli.test.ts b/__tests__/cli.test.ts index ac123bb3e..230d451bf 100644 --- a/__tests__/cli.test.ts +++ b/__tests__/cli.test.ts @@ -93,6 +93,12 @@ describe('help and validation', () => { }); describe('metadata input', () => { + const semantic = { + models: [ + { name: 'sales', description: 'Revenue excludes refunds.', datasets: [{ name: 'orders', source: 'data' }] }, + ], + }; + describe.each(['schema', 'profile', 'semantic'])('%s from stdin', (kind) => { const args = [kind, datasetId, '--file', '-']; @@ -102,7 +108,7 @@ describe('metadata input', () => { } it('imports valid metadata', async () => { - const value = kind === 'semantic' ? { description: 'Revenue excludes refunds.' } : { models: [] }; + const value = kind === 'semantic' ? semantic : { models: [] }; mockStdin(JSON.stringify(value)); const output = await execute(args); @@ -138,7 +144,7 @@ describe('metadata input', () => { it.each(['schema', 'profile', 'semantic'])('sets %s from a plain file path', async (kind) => { const directory = await mkdtemp(join(tmpdir(), 'ava-cli-test-')); try { - const value = kind === 'semantic' ? { description: 'Revenue excludes refunds.' } : { models: [] }; + const value = kind === 'semantic' ? semantic : { models: [] }; const file = join(directory, 'metadata.json'); await writeFile(file, JSON.stringify(value)); await execute([kind, datasetId, '--file', file]); diff --git a/__tests__/contracts.test.ts b/__tests__/contracts.test.ts index 1a673b207..fa4f78662 100644 --- a/__tests__/contracts.test.ts +++ b/__tests__/contracts.test.ts @@ -179,7 +179,8 @@ describe('source-to-chart contract flow', () => { } expect(contracts.schemaOutputSchema.parse({ models: [] })).toEqual({ models: [] }); expect(contracts.profileOutputSchema.parse({ models: [] })).toEqual({ models: [] }); - expect(contracts.semanticOutputSchema.parse({ description: 'Sales' })).toEqual({ description: 'Sales' }); + const semantic = { models: [{ name: 'sales', datasets: [{ name: 'orders', source: 'data' }] }] }; + expect(contracts.semanticOutputSchema.parse(semantic)).toEqual(semantic); }); it('loads, queries and renders real SQL results through the public contracts', async () => { diff --git a/__tests__/query/clickhouse-sql.test.ts b/__tests__/query/clickhouse-sql.test.ts index ea1599cea..5a8568a3e 100644 --- a/__tests__/query/clickhouse-sql.test.ts +++ b/__tests__/query/clickhouse-sql.test.ts @@ -57,9 +57,13 @@ describe('ClickHouse SQL generation', () => { it('extracts SQL and preserves usage and model context', async () => { const sql = "SELECT '```' AS value"; const usage = { inputTokens: 10, outputTokens: 5, totalTokens: 15 }; - vi.mocked(generateText).mockResolvedValue({ text: `\`\`\`sql\n${sql}\n\`\`\``, usage, finishReason: 'stop' } as never); + vi.mocked(generateText).mockResolvedValue({ + text: `\`\`\`sql\n${sql}\n\`\`\``, + usage, + finishReason: 'stop', + } as never); const result = await new ClickHouseSQLDialect({ model: 'test', maxRetries: 0 }).getDSL('count orders', { - models: [{ name: 'orders', columns: [], metrics: { row_count: 42 } }], + models: [{ name: 'orders', tableReference: { table: 'orders' }, columns: [], metrics: { row_count: 42 } }], }); expect(result).toEqual({ dsl: sql, usage }); expect(generateText).toHaveBeenCalledWith( diff --git a/__tests__/query/duckdb-sql.test.ts b/__tests__/query/duckdb-sql.test.ts index 316b2b06d..d8a939bae 100644 --- a/__tests__/query/duckdb-sql.test.ts +++ b/__tests__/query/duckdb-sql.test.ts @@ -114,9 +114,13 @@ describe('DuckDB SQL generation', () => { it('extracts SQL and preserves usage and model context', async () => { const sql = "SELECT '```' AS value"; const usage = { inputTokens: 10, outputTokens: 5, totalTokens: 15 }; - vi.mocked(generateText).mockResolvedValue({ text: `\`\`\`sql\n${sql}\n\`\`\``, usage, finishReason: 'stop' } as never); + vi.mocked(generateText).mockResolvedValue({ + text: `\`\`\`sql\n${sql}\n\`\`\``, + usage, + finishReason: 'stop', + } as never); const result = await new DuckDBSQLDialect({ model: 'test', maxRetries: 0 }).getDSL('count orders', { - models: [{ name: 'orders', columns: [], metrics: { row_count: 42 } }], + models: [{ name: 'orders', tableReference: { table: 'orders' }, columns: [], metrics: { row_count: 42 } }], }); expect(result).toEqual({ dsl: sql, usage }); expect(generateText).toHaveBeenCalledWith( diff --git a/__tests__/query/interpreters.test.ts b/__tests__/query/interpreters.test.ts index 47a8c70ef..c02f12caf 100644 --- a/__tests__/query/interpreters.test.ts +++ b/__tests__/query/interpreters.test.ts @@ -16,10 +16,7 @@ describe.each([ create: () => new JavaScriptDialect({ model: 'test', maxRetries: 0 }), fence: 'js', code: "const result = '```';", - sources: [ - '// 中文😀\nconst result = `value: ${data[0]?.value ?? 0}`;', - 'const result =', - ], + sources: ['// 中文😀\nconst result = `value: ${data[0]?.value ?? 0}`;', 'const result ='], invalid: ['', ' \n\t'], notExecuted: "throw new Error('must not execute');", }, @@ -49,9 +46,13 @@ describe.each([ it('extracts code and preserves rules, context and usage', async () => { const usage = { inputTokens: 10, outputTokens: 5, totalTokens: 15 }; - vi.mocked(generateText).mockResolvedValue({ text: `\`\`\`${fence}\n${code}\n\`\`\``, finishReason: 'stop', usage } as never); + vi.mocked(generateText).mockResolvedValue({ + text: `\`\`\`${fence}\n${code}\n\`\`\``, + finishReason: 'stop', + usage, + } as never); const result = await dialect.getDSL('count orders', { - models: [{ name: 'orders', columns: [], metrics: { row_count: 42 } }], + models: [{ name: 'orders', tableReference: { table: 'orders' }, columns: [], metrics: { row_count: 42 } }], }); expect(result).toEqual({ dsl: code, usage }); expect(generateText).toHaveBeenCalledWith(expect.objectContaining({ maxRetries: 0 })); @@ -63,7 +64,10 @@ describe.each([ { finishReason: 'length', empty: false, error: 'did not complete' }, { finishReason: 'stop', empty: true, error: 'empty code' }, ])('rejects unusable generation: $error', async ({ finishReason, empty, error }) => { - vi.mocked(generateText).mockResolvedValue({ text: empty ? `\`\`\`${fence}\n\n\`\`\`` : code, finishReason } as never); + vi.mocked(generateText).mockResolvedValue({ + text: empty ? `\`\`\`${fence}\n\n\`\`\`` : code, + finishReason, + } as never); await expect(dialect.getDSL('one', { models: [] })).rejects.toThrow(error); }); @@ -93,7 +97,8 @@ describe.skipIf(process.env.AVA_PYTHON_LOCAL_TEST !== '1')('Python official comp const dialect = new PythonDialect({ model: 'unused' }); it('preserves source without executing code or resolving data bindings', async () => { - const code = "# 中文😀\ndef total(frame):\n return frame['value'].sum()\nresult = total(df)\nraise RuntimeError('must not execute')\n"; + const code = + "# 中文😀\ndef total(frame):\n return frame['value'].sum()\nresult = total(df)\nraise RuntimeError('must not execute')\n"; await expect(dialect.validateDSL(code)).resolves.toBe(code); }); diff --git a/__tests__/query/postgresql.test.ts b/__tests__/query/postgresql.test.ts index ded4095ed..10cfa84db 100644 --- a/__tests__/query/postgresql.test.ts +++ b/__tests__/query/postgresql.test.ts @@ -45,12 +45,9 @@ describe('PostgreSQL validation', () => { await expect(dialect.validateDSL(`;;${sql}; ; -- tail`)).resolves.toBe(sql); }); - it.each(['SELECT (', 'SELECT 1\0; DELETE FROM orders'])( - 'rejects invalid or truncated input: %s', - async (sql) => { - await expect(dialect.validateDSL(sql)).rejects.toThrow(); - } - ); + it.each(['SELECT (', 'SELECT 1\0; DELETE FROM orders'])('rejects invalid or truncated input: %s', async (sql) => { + await expect(dialect.validateDSL(sql)).rejects.toThrow(); + }); it.each([ '', @@ -69,9 +66,13 @@ describe('PostgreSQL generation', () => { it('extracts SQL and preserves usage and model context', async () => { const sql = "SELECT '```' AS value"; const usage = { inputTokens: 10, outputTokens: 5, totalTokens: 15 }; - vi.mocked(generateText).mockResolvedValue({ text: `\`\`\`sql\n${sql}\n\`\`\``, usage, finishReason: 'stop' } as never); + vi.mocked(generateText).mockResolvedValue({ + text: `\`\`\`sql\n${sql}\n\`\`\``, + usage, + finishReason: 'stop', + } as never); const result = await new PostgreSQLDialect({ model: 'test', maxRetries: 0 }).getDSL('count orders', { - models: [{ name: 'orders', columns: [], metrics: { row_count: 42 } }], + models: [{ name: 'orders', tableReference: { table: 'orders' }, columns: [], metrics: { row_count: 42 } }], }); expect(result).toEqual({ dsl: sql, usage }); expect(generateText).toHaveBeenCalledWith( diff --git a/__tests__/query/tsql.test.ts b/__tests__/query/tsql.test.ts index 7cf9fcf7c..644f0cfaf 100644 --- a/__tests__/query/tsql.test.ts +++ b/__tests__/query/tsql.test.ts @@ -61,9 +61,13 @@ describe('T-SQL generation', () => { it('extracts SQL and preserves usage and model context', async () => { const sql = "SELECT N'```' AS value"; const usage = { inputTokens: 10, outputTokens: 5, totalTokens: 15 }; - vi.mocked(generateText).mockResolvedValue({ text: `\`\`\`tsql\n${sql}\n\`\`\``, usage, finishReason: 'stop' } as never); + vi.mocked(generateText).mockResolvedValue({ + text: `\`\`\`tsql\n${sql}\n\`\`\``, + usage, + finishReason: 'stop', + } as never); const result = await new TSQLDialect({ model: 'test', maxRetries: 0 }).getDSL('count orders', { - models: [{ name: 'orders', columns: [], metrics: { row_count: 42 } }], + models: [{ name: 'orders', tableReference: { table: 'orders' }, columns: [], metrics: { row_count: 42 } }], }); expect(result).toEqual({ dsl: sql, usage }); expect(generateText).toHaveBeenCalledWith( diff --git a/__tests__/util/__snapshots__/data-model.test.ts.snap b/__tests__/util/__snapshots__/data-model.test.ts.snap index c900da43f..cb1122053 100644 --- a/__tests__/util/__snapshots__/data-model.test.ts.snap +++ b/__tests__/util/__snapshots__/data-model.test.ts.snap @@ -1,151 +1,36 @@ // Vitest Snapshot v1, https://vitest.dev/guide/snapshot.html -exports[`stringifyDataModel > describes cube members and drill-down paths without nesting their definitions in JSON 1`] = ` +exports[`stringifyDataModel > includes physical structure, profiling observations, and separately scoped semantic definitions 1`] = ` "# Data Model -## Cubes - -### Cube: revenue - -| Attribute | Value | -| --- | --- | -| baseObject | orders | - -Properties: - -| Attribute | Value | -| --- | --- | -| description | Sales reporting | - -#### Measures - -- total (DOUBLE) - -| Attribute | Value | -| --- | --- | -| expression | SUM(amount - refund) | -| description | Net revenue | - -Properties: - -| Attribute | Value | -| --- | --- | -| unit | USD | - -#### Dimensions - -- region (VARCHAR) - -| Attribute | Value | -| --- | --- | -| expression | region | - -#### Time dimensions - -- month (DATE) - -| Attribute | Value | -| --- | --- | -| expression | DATE_TRUNC('month', ordered_at) | - -#### Hierarchies - -- calendar: year → month - -### Cube: counts - -| Attribute | Value | -| --- | --- | -| baseObject | orders | - -#### Measures - -- count (BIGINT) - -| Attribute | Value | -| --- | --- | -| expression | COUNT(*) |" -`; - -exports[`stringifyDataModel > renders model sources, constraints, columns and metadata as Markdown tables 1`] = ` -"# Data Model - -## Properties - -| Attribute | Value | -| --- | --- | -| description | Sales data | - ## Models ### Model: orders | Attribute | Value | | --- | --- | -| tableReference | {"schema":"public","table":"raw_orders"} | -| primaryKey | ["id","customer_id"] | -| uniqueKeys | ["id"] | - -Properties: - -| Attribute | Value | -| --- | --- | -| description | Confirmed orders | +| tableReference | {"catalog":"sales","schema":"public","table":"raw_orders"} | +| primaryKey | id | Metrics: | Attribute | Value | | --- | --- | -| row_count | 0 | +| row_count | 42 | #### Columns -- id (INTEGER) NOT NULL - -| Attribute | Value | -| --- | --- | -| notNull | true | - -- amount (DOUBLE) [calculated: price * quantity] - -| Attribute | Value | -| --- | --- | -| notNull | false | -| isCalculated | true | -| expression | price * quantity | - -Properties: +- amount (DOUBLE) NOT NULL | Attribute | Value | | --- | --- | -| unit | USD | +| logicalType | numeric | Metrics: | Attribute | Value | | --- | --- | -| min | null | -| max | 0 | -| top_values | [] | - -- customer (customers) [relationship: order_customer] - -| Attribute | Value | -| --- | --- | -| relationship | order_customer | -| expression | null | - -### Model: customers - -| Attribute | Value | -| --- | --- | -| baseObject | raw_customers | - -### Model: recent_orders - -| Attribute | Value | -| --- | --- | -| refSql | SELECT * FROM orders
WHERE id > 0 | +| min | 0 | ## Relationships @@ -157,21 +42,29 @@ orders → customers (MANY_TO_ONE) | --- | --- | | models | ["orders","customers"] | | joinType | MANY_TO_ONE | -| condition | orders.customer_id = customers.id | -| custom | false | +| condition | orders.id = customers.id | -Properties: +## Views + +### View: recent | Attribute | Value | | --- | --- | -| description | Buyer | +| statement | SELECT * FROM orders WHERE id > 0 | -## Views +## Semantic Models + +### Semantic Model: sales + +| Attribute | Value | +| --- | --- | +| description | Sales definitions | +| datasets | [{"name":"orders","source":"sales.public.raw_orders","fields":[{"name":"amount","expression":{"sql":"amount"},"datatype":"Decimal"}],"metrics":[{"name":"total","expression":{"sql":"SUM(amount)"}}]}] | +| metrics | [{"name":"gross","expression":{"sql":"AGG(orders.total)"}}] | -### View: all_orders +### Semantic Model: support | Attribute | Value | | --- | --- | -| statement | SELECT * FROM orders | -| custom | {"enabled":true} |" +| datasets | [{"name":"orders","source":"SELECT order_id FROM tickets"}] |" `; diff --git a/__tests__/util/data-model.test.ts b/__tests__/util/data-model.test.ts index b3cf51b60..866a0fddd 100644 --- a/__tests__/util/data-model.test.ts +++ b/__tests__/util/data-model.test.ts @@ -6,390 +6,148 @@ import { semanticOutputSchema, profileOutputSchema } from '../../src/contracts'; import type { DataModel, Profile, Schema, Semantic } from '../../src/types'; -describe('stringifyDataModel', () => { - it('renders model sources, constraints, columns and metadata as Markdown tables', () => { - const input: DataModel = { - properties: { description: 'Sales data' }, - models: [ +const semantic = { + models: [ + { + name: 'sales', + description: 'Sales definitions', + datasets: [ { name: 'orders', - tableReference: { schema: 'public', table: 'raw_orders' }, - primaryKey: ['id', 'customer_id'], - uniqueKeys: ['id'], - metrics: { row_count: 0 }, - properties: { description: 'Confirmed orders' }, - columns: [ - { name: 'id', type: 'INTEGER', notNull: true }, - { - name: 'amount', - type: 'DOUBLE', - notNull: false, - isCalculated: true, - expression: 'price * quantity', - metrics: { min: null, max: 0, top_values: [] }, - properties: { unit: 'USD' }, - }, - { name: 'customer', type: 'customers', relationship: 'order_customer', expression: null }, - ], - }, - { name: 'customers', baseObject: 'raw_customers' }, - { name: 'recent_orders', refSql: 'SELECT * FROM orders\nWHERE id > 0' }, - ], - relationships: [ - { - name: 'order_customer', - models: ['orders', 'customers'], - joinType: 'MANY_TO_ONE', - condition: 'orders.customer_id = customers.id', - properties: { description: 'Buyer' }, - custom: false, + source: 'sales.public.raw_orders', + fields: [{ name: 'amount', expression: { sql: 'amount' }, datatype: 'Decimal' }], + metrics: [{ name: 'total', expression: { sql: 'SUM(amount)' } }], }, ], - views: [{ name: 'all_orders', statement: 'SELECT * FROM orders', custom: { enabled: true } }], - }; - const original = structuredClone(input); - const result = stringifyDataModel(input); - - expect(result).toMatchSnapshot(); - expect(input).toEqual(original); - }); - - it('accepts empty and partial descriptions without inventing metadata', () => { - expect(stringifyDataModel({})).toBe('# Data Model'); - expect(stringifyDataModel({ properties: {}, models: [], relationships: [], views: [], cubes: [] })).toBe( - '# Data Model' - ); - expect(stringifyDataModel({ models: [{ name: 'data', baseObject: 'source' }] })).toBe( - '# Data Model\n\n## Models\n\n### Model: data\n\n| Attribute | Value |\n| --- | --- |\n| baseObject | source |' - ); - }); - - it('escapes Markdown, HTML, pipes and line breaks in headings and table cells', () => { - const result = stringifyDataModel({ - properties: { 'a|b': '