ktx/packages/cli/test/context/ingest/adapters/metabase/mapping.test.ts
Andrey Avtomonov 56985b7e09
test: split cli tests from source tree (#216)
* feat(cli): define full warehouse dialect contract

* test(cli): keep dialect edge tests focused

* fix(cli): stabilize dialect contract foundation

* refactor(connectors): own read-only query preparation

* refactor(connectors): resolve dialects through registry

* refactor(connectors): keep concrete dialect classes internal

* chore(workspace): enforce dialect import boundary

* refactor(cli): resolve relationship dialect at scan boundary

* refactor(cli): use dialect display parsing for entity details

* refactor(cli): use dialect display parsing for warehouse catalog

* refactor(cli): use dialect SQL in relationship workflows

* test(cli): verify solid dialect scan workflow closure

* test: split cli tests from source tree

* refactor(cli): standardize BigQuery scope listing

* feat(sqlite): implement connector scope listing

* test(connectors): cover required table listing

* feat(cli): add warehouse driver registry

* refactor(setup): route scope discovery through driver registry

* refactor(cli): route local query execution through driver registry

* refactor(historic-sql): route dialect support through driver registry

* refactor(cli): test warehouse connections through driver registry

* fix(cli): close driver registry type export gaps

* Improve setup daemon diagnostics

* refactor(setup): centralize rail-prefixed diagnostics + query-history fallback

Extract errorMessage, writePrefixedLines, and flushPrefixedBufferedCommandOutput
into clack.ts so the setup wizard, managed daemons, and embedding/agent steps
share one rail-formatted writer. setup-databases.ts also adds a
"disable query history and retry" option when the schema-context build fails
and query history is the likely culprit, surfaced via a new
failed-query-history-unavailable status.

* fix(cli): carry catalog through the picker so BigQuery/Snowflake/SQL Server scope filters match

The setup picker's KtxTableListEntry was a 2-level { schema, name }, so
qualifiedTableId always wrote db.name into enabled_tables. When BigQuery,
Snowflake, or SQL Server later ran fast ingest, their introspect step filtered
the scope set with scopedTableNames(scope, { catalog: projectId|database, db })
— catalog was non-null on the introspect side but null in the scope refs, so
every entry was rejected, the live-database adapter staged zero table files,
and detect() failed with 'Adapter "live-database" did not recognize fetched
source output'.

Align the picker boundary with the canonical 3-level KtxTableRef:

- Add catalog: string | null to KtxTableListEntry.
- BigQuery/Snowflake/SQL Server listTables populate catalog from the
  resolved projectId / database; Postgres/MySQL/ClickHouse/SQLite set null.
- qualifiedTableId emits catalog.schema.name when catalog is non-null
  (resolveEnabledTables already accepts the 3-part shape) and
  schemasFromEnabledTables now goes through parseDottedTableEntry so it
  recovers the schema correctly from both 2-part and 3-part entries.
- Export parseDottedTableEntry from enabled-tables.ts (@internal) for picker
  reuse.

Update listTables expectations in all seven connector tests and the setup /
picker test fixtures. Add a picker regression test that covers the
catalog-bearing round-trip (save + refine).

* fix(cli): allow debug telemetry under opt-out env
2026-05-26 08:49:05 +02:00

295 lines
9.8 KiB
TypeScript

import { describe, expect, it, vi } from 'vitest';
import type { MetabaseRuntimeClient } from '../../../../../src/context/ingest/adapters/metabase/client-port.js';
import {
METABASE_ENGINE_TO_CONNECTION_TYPE,
computeMetabaseMappingDrift,
computeMetabaseMappingPhysicalMismatches,
discoverMetabaseDatabases,
findBestMatch,
refreshMetabaseMapping,
validateMappingPhysicalMatch,
validateMetabaseMappings,
} from '../../../../../src/context/ingest/adapters/metabase/mapping.js';
describe('discoverMetabaseDatabases', () => {
it('filters sample databases and extracts host plus database names from Metabase details', async () => {
const client = {
getDatabases: vi.fn().mockResolvedValue([
{
id: 1,
name: 'Sample',
engine: 'postgres',
details: { host: 'sample.internal', dbname: 'sample' },
is_sample: true,
},
{
id: 2,
name: 'Analytics',
engine: 'postgres',
details: { host: 'pg.internal:5432', dbname: 'analytics' },
is_sample: false,
},
{
id: 3,
name: 'Warehouse',
engine: 'mysql',
details: { host: 'mysql.internal', db: 'warehouse' },
is_sample: false,
},
]),
} as Pick<MetabaseRuntimeClient, 'getDatabases'> as MetabaseRuntimeClient;
await expect(discoverMetabaseDatabases(client)).resolves.toEqual([
{ id: 2, name: 'Analytics', engine: 'postgres', host: 'pg.internal:5432', dbName: 'analytics' },
{ id: 3, name: 'Warehouse', engine: 'mysql', host: 'mysql.internal', dbName: 'warehouse' },
]);
});
});
describe('computeMetabaseMappingDrift', () => {
it('reports unmapped discovered databases, stale mappings, and in-sync mappings', () => {
const drift = computeMetabaseMappingDrift({
currentMappings: {
'2': 'target-postgres',
'9': 'target-stale',
},
discovered: [
{ id: 2, name: 'Analytics', engine: 'postgres', host: 'pg.internal', dbName: 'analytics' },
{ id: 3, name: 'Warehouse', engine: 'mysql', host: 'mysql.internal', dbName: 'warehouse' },
],
});
expect(drift).toEqual({
unmappedDiscovered: [
{ id: 3, name: 'Warehouse', engine: 'mysql', host: 'mysql.internal', dbName: 'warehouse' },
],
staleMappings: [{ id: '9', reason: 'database_not_found' }],
inSync: [{ id: 2, ktxConnectionId: 'target-postgres' }],
});
});
});
describe('validateMetabaseMappings', () => {
it('accepts mappings whose target connection ids exist', () => {
expect(
validateMetabaseMappings({
mappings: { '2': 'target-postgres' },
knownKtxConnectionIds: new Set(['target-postgres']),
}),
).toEqual({ ok: true });
});
it('returns one error per missing target connection id', () => {
expect(
validateMetabaseMappings({
mappings: { '2': 'missing-target', '3': 'target-mysql' },
knownKtxConnectionIds: new Set(['target-mysql']),
}),
).toEqual({
ok: false,
errors: [{ key: '2', reason: 'KTX connection missing-target does not exist' }],
});
});
});
describe('validateMappingPhysicalMatch', () => {
it('returns null when Snowflake mapping points at the same database', () => {
expect(
validateMappingPhysicalMatch(
{ metabaseEngine: 'snowflake', metabaseDbName: 'ANALYTICS', metabaseHost: null },
{ connection_type: 'SNOWFLAKE', database: 'ANALYTICS', account: 'EMOVRJS-CZ07756' },
),
).toBeNull();
});
it('returns a reason when Snowflake mapping points at a different database', () => {
const reason = validateMappingPhysicalMatch(
{ metabaseEngine: 'snowflake', metabaseDbName: 'SNAPSHOTS', metabaseHost: null },
{ connection_type: 'SNOWFLAKE', database: 'ANALYTICS', account: 'EMOVRJS-CZ07756' },
);
expect(reason).toContain('SNAPSHOTS');
expect(reason).toContain('ANALYTICS');
});
it('returns a reason when engine type mismatches', () => {
const reason = validateMappingPhysicalMatch(
{ metabaseEngine: 'snowflake', metabaseDbName: 'ANALYTICS', metabaseHost: null },
{ connection_type: 'POSTGRESQL', database: 'ANALYTICS', host: 'pg.internal' },
);
expect(reason).toContain('engine');
});
it('returns null when Postgres host and database both match after normalization', () => {
expect(
validateMappingPhysicalMatch(
{ metabaseEngine: 'postgres', metabaseDbName: 'app', metabaseHost: 'PG.INTERNAL:5432' },
{ connection_type: 'POSTGRESQL', host: 'pg.internal', database: 'APP' },
),
).toBeNull();
});
it('returns a reason when Postgres host matches but database differs', () => {
const reason = validateMappingPhysicalMatch(
{ metabaseEngine: 'postgres', metabaseDbName: 'app', metabaseHost: 'pg.internal' },
{ connection_type: 'POSTGRESQL', host: 'pg.internal', database: 'other_app' },
);
expect(reason).toContain('app');
expect(reason).toContain('other_app');
});
it('uses BigQuery dataset_id before project_id when comparing database names', () => {
expect(
validateMappingPhysicalMatch(
{ metabaseEngine: 'bigquery', metabaseDbName: 'analytics_dataset', metabaseHost: null },
{ connection_type: 'BIGQUERY', dataset_id: 'analytics_dataset', project_id: 'warehouse-project' },
),
).toBeNull();
});
it('returns null for unknown engines because KTX cannot validate them', () => {
expect(
validateMappingPhysicalMatch(
{ metabaseEngine: 'unknown-engine', metabaseDbName: 'X', metabaseHost: 'host' },
{ connection_type: 'OTHER' },
),
).toBeNull();
});
});
describe('computeMetabaseMappingPhysicalMismatches', () => {
it('returns only mismatched physical mappings', () => {
expect(
computeMetabaseMappingPhysicalMismatches([
{
mappingId: 'mapping-ok',
metabase: { metabaseEngine: 'postgres', metabaseHost: 'pg.internal', metabaseDbName: 'app' },
target: { connection_type: 'POSTGRESQL', host: 'pg.internal', database: 'app' },
},
{
mappingId: 'mapping-bad',
metabase: { metabaseEngine: 'postgres', metabaseHost: 'pg.internal', metabaseDbName: 'app' },
target: { connection_type: 'POSTGRESQL', host: 'pg.internal', database: 'other_app' },
},
]),
).toEqual([
{
mappingId: 'mapping-bad',
reason: "Metabase database 'app' does not match KTX connection database 'other_app'",
},
]);
});
});
describe('refreshMetabaseMapping', () => {
it('combines discovery drift and physical validation through a caller-provided target resolver', async () => {
const client = {
getDatabases: vi.fn().mockResolvedValue([
{
id: 2,
name: 'Analytics',
engine: 'postgres',
details: { host: 'pg.internal', dbname: 'analytics' },
is_sample: false,
},
]),
} as Pick<MetabaseRuntimeClient, 'getDatabases'> as MetabaseRuntimeClient;
await expect(
refreshMetabaseMapping({
client,
currentMappings: { '2': 'target-postgres' },
resolveKtxConnectionPhysicalInfo: vi.fn().mockResolvedValue({
connection_type: 'POSTGRESQL',
host: 'pg.internal',
database: 'wrong_database',
}),
}),
).resolves.toEqual({
drift: {
unmappedDiscovered: [],
staleMappings: [],
inSync: [{ id: 2, ktxConnectionId: 'target-postgres' }],
},
physicalMismatches: [
{
mappingId: '2',
reason: "Metabase database 'analytics' does not match KTX connection database 'wrong_database'",
},
],
});
});
});
describe('findBestMatch', () => {
const candidates = [
{
id: 'snowflake-target',
name: 'Warehouse Snowflake',
connection_type: 'SNOWFLAKE',
connection_params: { account: 'EMOVRJS-CZ07756', database: 'ANALYTICS' },
},
{
id: 'postgres-host-only',
name: 'Host Only Postgres',
connection_type: 'POSTGRESQL',
connection_params: { host: 'pg.internal', database: 'other_app' },
},
{
id: 'postgres-db-only',
name: 'Database Only Postgres',
connection_type: 'POSTGRESQL',
connection_params: { host: 'other.internal', database: 'app' },
},
{
id: 'postgres-full',
name: 'Full Postgres',
connection_type: 'POSTGRESQL',
connection_params: { host: 'pg.internal', database: 'app' },
},
];
it('chooses a host-and-database match over weaker matches', () => {
expect(
findBestMatch({ metabaseEngine: 'postgres', metabaseHost: 'pg.internal:5432', metabaseDbName: 'APP' }, candidates),
).toEqual({
connectionId: 'postgres-full',
connectionName: 'Full Postgres',
reason: 'host_and_database',
});
});
it('falls back to database-only matching when host does not match', () => {
expect(
findBestMatch(
{ metabaseEngine: 'postgres', metabaseHost: 'unknown.internal', metabaseDbName: 'app' },
candidates,
),
).toEqual({
connectionId: 'postgres-db-only',
connectionName: 'Database Only Postgres',
reason: 'database_only',
});
});
it('returns null for unsupported Metabase engines', () => {
expect(
findBestMatch({ metabaseEngine: 'unknown-engine', metabaseHost: 'pg.internal', metabaseDbName: 'app' }, candidates),
).toBeNull();
});
});
describe('METABASE_ENGINE_TO_CONNECTION_TYPE', () => {
it('keeps the server-supported Metabase engine table in KTX', () => {
expect(METABASE_ENGINE_TO_CONNECTION_TYPE).toMatchObject({
postgres: 'POSTGRESQL',
bigquery: 'BIGQUERY',
'bigquery-cloud-sdk': 'BIGQUERY',
snowflake: 'SNOWFLAKE',
sqlserver: 'SQLSERVER',
mysql: 'MYSQL',
});
});
});