Skip to content

Commit 13c911c

Browse files
hkaltaiclaude
andcommitted
fix: harden SQL classification for the tool CLI and MCP server
Refuses more writes that would run as reads, and blocks more ways of writing DROP DATABASE, DROP SCHEMA or TRUNCATE. - sql_explain explains one statement and refuses EXPLAIN options in its input. Some drivers run every statement after EXPLAIN, and EXPLAIN ANALYZE executes the statement. - Writes that ran as reads: Snowflake ->> statement chains; dbt Jinja anywhere in the SQL on the dbt route; Spark TRANSFORM ... USING; and functions that write or call outside systems (ClickHouse jdbc, Spark reflect/java_method, Databricks http_request/remote_query, DuckDB bigquery_execute, ducklake_*, postgres_attach/sqlite_attach, Snowflake GETNEXTVAL). Sequence advances through a quoted or commented NEXTVAL, in Oracle, Snowflake and MariaDB. - Lexing: Spark and MySQL /*+ hints holding a quote, Oracle q'...' quotes, a Spark -- comment ending in a backslash and a /* inside a comment where nesting is unknown are uncertain. ClickHouse heredocs are strings. - Hard block (best effort, now documented as such): - a write's literals are read as SQL with escapes decoded as each engine reads them; - TRUNCATE is found at statement, block and handler starts and after THEN/ELSE, including quoted, dotted and IF EXISTS targets; - DROP CATALOG, DROP NAMESPACE, DROP EXTERNAL SCHEMA and DROP PLUGGABLE DATABASE are blocked. - Columns and aliases named truncate, throw or nextval, and CASE ... THEN truncate, are reads again. - data_diff reads an empty target_warehouse as the source warehouse in both layers. The dbt dialect check follows the dbt adapter the daemon has already created. Co-Authored-By: Claude Opus 5.5 <[email protected]>
1 parent ee6add5 commit 13c911c

14 files changed

Lines changed: 427 additions & 47 deletions

File tree

‎docs/docs/usage/tool.md‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -51,7 +51,7 @@ Only the data tools are exposed. Coding tools (`bash`, `read`, `edit`, ...), `db
5151

5252
Runs are read-only by default. Reads such as `sql_execute` on a SELECT and `schema_inspect` are allowed; anything else is refused with `Permission denied: <kind>. Re-run with --allow-write to enable writes.` Tools that change local configuration (`warehouse_add`, `warehouse_remove`, `warehouse_install_driver`) also need `--allow-write`.
5353

54-
`DROP DATABASE`, `DROP SCHEMA` and `TRUNCATE` stay blocked even with `--allow-write`.
54+
`DROP DATABASE`, `DROP SCHEMA` and `TRUNCATE` are refused even with `--allow-write` when the SQL check recognises them. The check reads the SQL text, so it is best effort: a statement the warehouse builds or decodes at run time (dynamic SQL assembled by concatenation, a stored routine, an unusual literal encoding) can get past it. For a hard guarantee, connect with a database user that has no `DROP` or `TRUNCATE` privilege.
5555

5656
## Daemon
5757

‎packages/opencode/src/altimate/native/connections/dbt-adapter-type.ts‎

Lines changed: 5 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -25,13 +25,15 @@ export async function dbtProjectAdapterType(): Promise<{ project: boolean; type?
2525
try {
2626
if (existsSync(config.path())) saved = JSON.parse(readFileSync(config.path(), "utf8"))
2727
} catch {}
28-
projectRoot = saved === undefined ? config.findProjectRoot() : (saved?.projectRoot ?? null)
28+
projectRoot = saved === undefined ? config.findProjectRoot() : typeof saved?.projectRoot === "string" ? saved.projectRoot : null
2929
} catch {
3030
projectRoot = null
3131
}
3232
}
33-
// A root without dbt_project.yml is rejected by the routing, which then uses the registry default.
34-
if (!projectRoot || !existsSync(path.join(projectRoot, "dbt_project.yml"))) return { project: false, targetTypes: [] }
33+
// A root without dbt_project.yml is rejected by the routing, which then uses the registry default;
34+
// an adapter already created keeps running even if the file is removed since.
35+
if (!projectRoot || (dbtRoute.root === undefined && !existsSync(path.join(projectRoot, "dbt_project.yml"))))
36+
return { project: false, targetTypes: [] }
3537
const targetTypes = await profileTargetTypes(projectRoot)
3638
try {
3739
const { resolveDbtTargetPath } = await import("../../validators/validator-utils")

‎packages/opencode/src/altimate/tools/data-diff.ts‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -119,7 +119,7 @@ export const DataDiffTool = Tool.define("data_diff", {
119119
target: args.target,
120120
key_columns: args.key_columns,
121121
source_warehouse: args.source_warehouse,
122-
target_warehouse: args.target_warehouse,
122+
target_warehouse: args.target_warehouse || undefined, // "" is the source warehouse, as the ask resolves it
123123
extra_columns: args.extra_columns,
124124
algorithm: args.algorithm,
125125
where_clause: args.where_clause,

‎packages/opencode/src/altimate/tools/sql-classify.ts‎

Lines changed: 118 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -171,7 +171,7 @@ function otherIsReadOnly(sql: string, parsed: Array<{ category: string }>, diale
171171
// Hard-deny patterns — blocked regardless of permissions
172172
const HARD_DENY_TYPES = new Set(["DROP DATABASE", "DROP SCHEMA", "TRUNCATE", "TRUNCATE TABLE"])
173173

174-
const HARD_DENY_PATTERN = /^\s*(DROP\s+(DATABASE|SCHEMA)\b|TRUNCATE(\s+TABLE)?\b)/i
174+
const HARD_DENY_PATTERN = /^\s*(DROP\s+((EXTERNAL|PLUGGABLE)\s+)?(DATABASE|SCHEMA|CATALOG|NAMESPACE)\b|TRUNCATE(\s+TABLE)?\b)/i
175175

176176
/**
177177
* Fail closed when the parser is unavailable or rejects the input. Lexical
@@ -192,16 +192,19 @@ function classifyFallback(sql: string, dialect?: string): { queryType: "read" |
192192
// comment), so the words alone decide; the TRUNCATE() function does not count.
193193
const lexical = tokenizeSql(sql, dialect)
194194
if (!lexical.complete) {
195-
if (mentionsHardDeny(sql)) blocked = true
195+
// Escapes decoded too: dynamic SQL may run a literal such as '\x44ROP SCHEMA s'.
196+
if (mentionsHardDenyAnywhere(sql)) blocked = true
196197
} else {
197198
// Read with certainty: the statement words in code (literals, identifiers and comments masked,
198199
// so DROP/**/SCHEMA reads as DROP SCHEMA) decide too, since T-SQL runs `SELECT 1 DROP DATABASE x`
199200
// as two statements with no ; and a parser may read a literal differently from the engine.
200-
const masked = maskSql(lexical.tokens)
201-
if (CODE_HARD_DENY.test(masked)) blocked = true
202-
// Dynamic SQL (EXEC('...'), EXECUTE IMMEDIATE, PREPARE ... FROM, DO $$...$$) runs a string, so
203-
// the words in its literals count too. A statement built by concatenation is not seen.
204-
else if (DYNAMIC_SQL.test(masked) && mentionsHardDeny(sql)) blocked = true
201+
const names = namesKept(lexical.tokens)
202+
// Snowflake's ->> chains statements (elsewhere a JSON operator), and Snowflake Scripting's ASYNC (,
203+
// := ( and DEFAULT ( hold one (elsewhere DEFAULT(col) is a function).
204+
const chained =
205+
(/^snowflake$/i.test(dialect ?? "") || !isModeledDialect(dialect)) &&
206+
/(->>|\bASYNC\s*\(|:=\s*\(|\bDEFAULT\s*\()\s*TRUNCATE\b(?!\s*\()/i.test(names)
207+
if (CODE_HARD_DENY.test(names) || handlerTruncate(names) || chained) blocked = true
205208
}
206209
return { queryType: "write", blocked }
207210
}
@@ -217,26 +220,101 @@ function batchedStatement(masked: string, dialect?: string): boolean {
217220
// or clauses (USE, FETCH, OPEN, CLOSE, ENABLE, DISABLE, RENAME, THROW, ADD, MOVE, SEND, RECEIVE, END)
218221
// count only in their statement forms.
219222
const BATCH_STATEMENT = new RegExp(
220-
"\\b(INSERT|UPDATE|DELETE|MERGE|DROP|ALTER|CREATE|TRUNCATE|EXEC|EXECUTE|GRANT|REVOKE|DENY|BACKUP|RESTORE|DBCC|KILL|SHUTDOWN|BULK|WAITFOR|DECLARE|SET|INTO|" +
223+
"\\bTRUNCATE\\b(?!\\s*\\()|\\b(INSERT|UPDATE|DELETE|MERGE|DROP|ALTER|CREATE|EXEC|EXECUTE|GRANT|REVOKE|DENY|BACKUP|RESTORE|DBCC|KILL|SHUTDOWN|BULK|WAITFOR|DECLARE|SET|INTO|" +
221224
"OPENROWSET|OPENQUERY|OPENDATASOURCE|OPENXML|CHECKPOINT|RECONFIGURE|RAISERROR|GOTO|BEGIN|COMMIT|ROLLBACK|SAVE|DEALLOCATE|" +
222225
"READTEXT|UPDATETEXT|WRITETEXT|SETUSER|REVERT|PRINT)\\b" +
223-
"|\\b(ENABLE|DISABLE)\\s+TRIGGER\\b|\\bRENAME\\s+(OBJECT|DATABASE)\\b|\\bTHROW\\s*($|;|[\\d@])" +
226+
"|\\b(ENABLE|DISABLE)\\s+TRIGGER\\b|\\bRENAME\\s+(OBJECT|DATABASE)\\b|\\bTHROW\\s+[\\d@]" +
224227
// USE except OPTION (USE HINT/PLAN) and USE INDEX; FETCH except OFFSET paging (FETCH NEXT 10 ROWS ONLY).
225228
"|\\bUSE\\b(?!\\s+(HINT|PLAN|INDEX|KEY)\\b)|\\bFETCH\\b(?!\\s+(FIRST|NEXT)\\s+([\\w@().+-]+\\s+)?(PERCENT\\s+)?ROWS?\\b)" +
226229
"|\\b(OPEN|CLOSE)\\s+(GLOBAL\\s+)?[\\w@#]+\\s*(;|\\b(SELECT|WITH)\\b)|\\bADD\\s+(SENSITIVITY|SIGNATURE|COUNTER)\\b" +
227230
"|\\bMOVE\\s+CONVERSATION\\b|\\bSEND\\s+ON\\b|\\bRECEIVE\\s+(TOP\\b|\\*|\\w+\\s+FROM\\b)|\\bEND\\s+CONVERSATION\\b",
228231
"i",
229232
)
230233

231-
const CODE_HARD_DENY = /\bDROP\s+(DATABASE|SCHEMA)\b|\bTRUNCATE\b(?!\s*\()/i
232-
const DYNAMIC_SQL = /\bEXEC(UTE)?\b|(^|;)\s*(PREPARE|DO)\b/i
233-
// Sequence advances outside PostgreSQL's nextval(): NEXT VALUE FOR s (SQL Server, DB2), s.NEXTVAL
234-
// (Oracle, Snowflake).
235-
const SEQUENCE_ADVANCE = /\bNEXT\s+VALUE\s+FOR\b|\.\s*NEXTVAL\b/i
234+
/** A literal's text as an engine may run it, one string per reading: numeric escapes (\xHH, \uHHHH,
235+
* \UHHHHHHHH, octal \ooo, U&'...' \HHHH and \+HHHHHH) decoded, and a single-character escape read as a
236+
* space when it stands for whitespace (\n \r \t \f, and \v in BigQuery) and as itself otherwise;
237+
* and SQL Server's reading, where a backslash before a line break joins the two lines. */
238+
function escapeReadings(sql: string): string[] {
239+
const char = (hex: string, base = 16) => String.fromCodePoint(Math.min(parseInt(hex, base), 0x10ffff))
240+
let numeric = sql
241+
if (/U&/i.test(numeric)) numeric = numeric.replace(/\\\+([0-9a-fA-F]{6})|\\([0-9a-fA-F]{4})/g, (_, six, four) => char(six ?? four))
242+
const decode = (whitespace: RegExp) =>
243+
numeric.replace(
244+
/\\(?:x([0-9a-fA-F]{1,2})|u([0-9a-fA-F]{4})|U([0-9a-fA-F]{8})|([0-7]{1,3})|([\s\S]))/g,
245+
(_, x, u, U, octal, single) =>
246+
single !== undefined ? (whitespace.test(single) ? " " : single) : octal ? char(octal, 8) : char(x ?? u ?? U),
247+
)
248+
return [sql, sql.replace(/\\\r?\n/g, ""), decode(/^[nrtf]$/), decode(/^[nrtfv]$/)]
249+
}
250+
251+
// TRUNCATE as a statement: TRUNCATE TABLE, or TRUNCATE starting a statement or a block (BEGIN [NOT
252+
// ATOMIC], DO, LOOP, REPEAT, a handler's condition). After THEN or ELSE it must be a name and the end
253+
// of the statement, since CASE ... THEN truncate ... is a column. A column or alias named truncate is not.
254+
const CODE_HARD_DENY = new RegExp(
255+
"\\bDROP\\s+((EXTERNAL|PLUGGABLE)\\s+)?(DATABASE|SCHEMA|CATALOG|NAMESPACE)\\b|\\bTRUNCATE\\s+TABLE\\b" +
256+
// DuckDB accepts TRUNCATE after EXPLAIN (options) and PREPARE p AS ([^()] keeps the scan linear).
257+
"|(^|;|\\bPREPARE\\s+\\w+\\s+AS\\b|\\bEXPLAIN\\s*\\([^()]*\\))\\s*TRUNCATE\\b(?!\\s*\\()" +
258+
// After a block or handler word (or EXPLAIN ANALYZE), a target must follow: these words are also
259+
// column names, so `SELECT atomic truncate FROM t` is an alias.
260+
"|\\b(BEGIN|NOT\\s+ATOMIC|DO|LOOP|REPEAT|SQLEXCEPTION|SQLWARNING|FOUND|ANALYZE|ANALYSE)\\s+TRUNCATE\\s+" +
261+
"(?!(FROM|AS|WHERE|ORDER|GROUP|HAVING|UNION|LIMIT|WINDOW|INTO|JOIN|ON|AND|OR|END)\\b)[\\w\"`$\\u0080-\\uffff]" +
262+
// After THEN/ELSE: [IF EXISTS] a (dotted, quoted or IDENTIFIER(...)) name, then the statement's end.
263+
"|\\b(THEN|ELSE)\\s+TRUNCATE\\s+(IF\\s+EXISTS\\s+)?(?!END\\b)" +
264+
"(IDENTIFIER\\s*\\([^()]*\\)|[^\\s;,().]+(\\s*\\.{1,2}\\s*[^\\s;,().]+)*)(\\s+(NOWAIT|WAIT\\s+\\d+))?\\s*(;|$)",
265+
"i",
266+
)
236267

237-
/** The word DROP with DATABASE or SCHEMA anywhere after it, or TRUNCATE not directly followed by `(`
238-
* (the TRUNCATE() function; a comment before the `(` does not count, since where a comment ends is
239-
* part of what is uncertain). Only words count: quotes and comments are ignored, since how they read
268+
/** A handler's statement follows its conditions (a code, SQLSTATE '...', a name): a TRUNCATE after
269+
* HANDLER FOR within the same statement counts. One pass over the statements. */
270+
function handlerTruncate(masked: string): boolean {
271+
return masked.split(";").some((part) => {
272+
const handler = part.search(/\bHANDLER\s+FOR\b/i)
273+
return handler >= 0 && /\bTRUNCATE\b(?!\s*\()/i.test(part.slice(handler))
274+
})
275+
}
276+
277+
/** Code with literals and comments masked, and each quoted identifier as a placeholder name, so a
278+
* statement keeps its target (TRUNCATE `t`) without the identifier's text reading as code. */
279+
function namesKept(tokens: ReturnType<typeof tokenizeSql>["tokens"]): string {
280+
return tokens
281+
.map(({ kind, text }) =>
282+
kind === "code" ? text : kind === "identifier" ? ` ${"_".repeat(Math.max(text.length - 2, 1))} ` : text.replace(/[^\r\n]/g, " "),
283+
)
284+
.join("")
285+
}
286+
287+
/** Whether a write's quoted text holds a hard-denied statement. A write can run its literals as SQL:
288+
* dynamic SQL (EXEC('...'), sp_executesql N'...', EXECUTE IMMEDIATE, PREPARE ... FROM, dblink_exec),
289+
* or a function, procedure or trigger body created and called in the same call. Each literal is read
290+
* word by word with its escapes decoded, as uncertain SQL is, so nothing inside it (nested quotes,
291+
* comments) can separate the words. A statement built by concatenation is not seen, and a custom
292+
* UESCAPE character is not decoded, so it blocks. */
293+
function quotedHardDeny(tokens: ReturnType<typeof tokenizeSql>["tokens"], dialect?: string): boolean {
294+
if (/\bUESCAPE\b/i.test(maskSql(tokens))) return true
295+
// "..." is a string in Spark, Databricks and Hive, under SQL Server's QUOTED_IDENTIFIER OFF and in
296+
// MySQL without ANSI_QUOTES; other identifiers never are.
297+
const quotedStrings =
298+
/^(sqlserver|tsql|mssql|fabric|mysql|mariadb|spark|databricks|hive)$/i.test(dialect ?? "") || !isModeledDialect(dialect)
299+
return tokens.some(
300+
({ kind, text }) =>
301+
(kind === "literal" || (kind === "identifier" && quotedStrings && text[0] === '"')) &&
302+
(/\bUESCAPE\b/i.test(text) || mentionsHardDenyAnywhere(text)),
303+
)
304+
}
305+
306+
// Sequence advances outside PostgreSQL's nextval(): NEXT VALUE FOR s (SQL Server, DB2), and in Oracle,
307+
// Snowflake and MariaDB (Oracle mode) s.NEXTVAL, quoted or not (elsewhere s.nextval is a column).
308+
function advancesSequence(tokens: ReturnType<typeof tokenizeSql>["tokens"], masked: string, dialect?: string): boolean {
309+
if (/\bNEXT\s+VALUE\s+FOR\b/i.test(masked)) return true
310+
if (!/^(oracle|snowflake|mysql|mariadb)$/i.test(dialect ?? "") && isModeledDialect(dialect)) return false
311+
// Comments masked to spaces and quoted names unwrapped, so s./* c */"NEXTVAL" reads as s.NEXTVAL.
312+
return /\.\s*NEXTVAL\b/i.test(maskSql(tokens, true))
313+
}
314+
315+
/** The word DROP with DATABASE, SCHEMA, CATALOG or NAMESPACE anywhere after it, or TRUNCATE not
316+
* directly followed by `(` (the TRUNCATE() function; a comment before the `(` does not count, since
317+
* where a comment ends is part of what is uncertain). Only words count: quotes and comments are ignored, since how they read
240318
* is what is uncertain, so no comment or quote placement can separate the words. One forward pass. */
241319
function mentionsHardDeny(sql: string): boolean {
242320
let drop = false
@@ -250,7 +328,7 @@ function mentionsHardDeny(sql: string): boolean {
250328
while (j < sql.length && /\w/.test(sql[j])) j++
251329
const word = sql.slice(i, j).toUpperCase()
252330
if (word === "DROP") drop = true
253-
else if (drop && (word === "DATABASE" || word === "SCHEMA")) return true
331+
else if (drop && (word === "DATABASE" || word === "SCHEMA" || word === "CATALOG" || word === "NAMESPACE")) return true
254332
else if (word === "TRUNCATE" && !/^[ \t\r\n]*\(/.test(sql.slice(j, j + 64))) return true
255333
i = j
256334
}
@@ -349,7 +427,21 @@ export function classifyAndCheck(sql: string, dialect?: string): {
349427
blocked: boolean
350428
parseError?: string
351429
} {
352-
return classifySql(sql, dialect, 0)
430+
const result = classifySql(sql, dialect, 0)
431+
if (result.queryType === "write" && !result.blocked) {
432+
// SQL read with certainty: a write may still run the SQL in its literals. Otherwise the word scan
433+
// of the whole text already covered them.
434+
const lexical = tokenizeSql(sql, dialect)
435+
if (lexical.complete && quotedHardDeny(lexical.tokens, dialect)) return { ...result, blocked: true }
436+
}
437+
return result
438+
}
439+
440+
/** Whether DROP DATABASE/SCHEMA/CATALOG/NAMESPACE or TRUNCATE appears anywhere in the text, read word by word
441+
* with quotes and comments ignored and escapes decoded (for text another layer renders, such as dbt's
442+
* Jinja). */
443+
export function mentionsHardDenyAnywhere(sql: string): boolean {
444+
return escapeReadings(sql).some(mentionsHardDeny)
353445
}
354446

355447
function classifySql(sql: string, dialect: string | undefined, depth: number): {
@@ -385,7 +477,13 @@ function classifySql(sql: string, dialect: string | undefined, depth: number): {
385477
!functions.write &&
386478
!blocked &&
387479
!batchedStatement(masked, dialect) &&
388-
!SEQUENCE_ADVANCE.test(masked) &&
480+
// Snowflake's ->> runs the statements it chains, DML included.
481+
!(/^snowflake$/i.test(dialect ?? "") && masked.includes("->>")) &&
482+
// Spark/Hive SELECT TRANSFORM(...) USING 'cmd' runs a command on the cluster.
483+
!((/^(spark|databricks|hive)$/i.test(dialect ?? "") || !isModeledDialect(dialect)) &&
484+
/\bTRANSFORM\s*\(/i.test(masked) &&
485+
/\bUSING\b/i.test(masked)) &&
486+
!advancesSequence(lexical.tokens, masked, dialect) &&
389487
otherIsReadOnly(sql, result.statements, dialect)
390488
? "read"
391489
: "write",

‎packages/opencode/src/altimate/tools/sql-execute.ts‎

Lines changed: 23 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -9,7 +9,13 @@ import { Tool } from "../../tool/tool"
99
import { Dispatcher } from "../native"
1010
import type { SqlExecuteResult } from "../native/types"
1111
// altimate_change start - SQL write access control + fingerprinting
12-
import { classifyAndCheck, classifyMongoCommand, computeSqlFingerprint, isScratchSafeWrite } from "./sql-classify"
12+
import {
13+
classifyAndCheck,
14+
classifyMongoCommand,
15+
computeSqlFingerprint,
16+
isScratchSafeWrite,
17+
mentionsHardDenyAnywhere,
18+
} from "./sql-classify"
1319
import { statementsOf } from "./sql-tokenize"
1420

1521
const MONGO_WAREHOUSE_TYPES = new Set(["mongodb", "mongo"])
@@ -231,7 +237,12 @@ export const SqlExecuteTool = Tool.define(
231237
)
232238
}
233239
const classification = mongo ?? classifyEvery(sql, dialects)
234-
const { queryType, blocked } = classification
240+
// dbt renders Jinja before it runs SQL, wherever the Jinja sits (a comment or literal too),
241+
// so {% do run_query('...') %} runs while the query compiles and {# ... #} removes text.
242+
// A Mongo command routed to dbt is rendered too.
243+
const jinja = target?.dbt === true && /\{[{%#]/.test(sql)
244+
const queryType = jinja ? "write" : classification.queryType
245+
const blocked = classification.blocked || (jinja && mentionsHardDenyAnywhere(sql))
235246
const query = mongo?.normalized ?? sql
236247
if (blocked) {
237248
throw new Error(
@@ -671,22 +682,30 @@ function resolveStepRefs(
671682
* type and every target of the project's profile; when the profile's targets cannot be read, or one
672683
* is an adapter with no supported dialect, every supported dialect and the generic lexing count.
673684
* Read without starting dbt or loading the handlers. The registry warehouse is named for the ask. */
674-
async function defaultTarget(forceReadOnly: boolean): Promise<{ dialects: (string | undefined)[]; warehouse?: string }> {
685+
async function defaultTarget(
686+
forceReadOnly: boolean,
687+
): Promise<{ dialects: (string | undefined)[]; warehouse?: string; dbt?: boolean }> {
675688
const fallback = Registry.list().warehouses[0] // before any await, as the call resolves it now
676689
const dialectOf = (type?: string) => (type ? (Registry.canonicalType(type) ?? undefined) : undefined)
677690
const dialects: (string | undefined)[] = fallback ? [dialectOf(fallback.type)] : []
691+
let viaDbt = false
678692
if (!forceReadOnly) {
679693
const { dbtProjectAdapterType } = await import("../native/connections/dbt-adapter-type")
680694
const dbt = await dbtProjectAdapterType()
681695
if (dbt.project) {
696+
viaDbt = true
682697
const types = [dbt.type, ...dbt.targetTypes].filter((type): type is string => Boolean(type))
683698
const known = types.map(dialectOf)
684699
dialects.push(...known.filter(Boolean))
685700
// An unreadable profile, or an adapter with no supported dialect (synapse, materialize...).
686701
if (!dbt.targetTypes.length || known.includes(undefined)) dialects.push(...EVERY_DIALECT, undefined)
687702
}
688703
}
689-
return { dialects: dialects.length ? [...new Set(dialects)] : [undefined], ...(fallback && { warehouse: fallback.name }) }
704+
return {
705+
dialects: dialects.length ? [...new Set(dialects)] : [undefined],
706+
...(fallback && { warehouse: fallback.name }),
707+
...(viaDbt && { dbt: true }),
708+
}
690709
}
691710

692711
const EVERY_DIALECT = ["postgres", "redshift", "duckdb", "snowflake", "bigquery", "mysql", "sqlserver", "databricks", "clickhouse", "oracle", "trino", "sqlite"]

0 commit comments

Comments
 (0)