feat(spanner): add Google Cloud Spanner support

This commit is contained in:
Frost authored and GitHub committed 2026-08-20 16:33:09 +08:00
1 parent 2cc8d78e64
commit f494f90c30
74 files changed
+2920 -53

No files matched your search

@@ -43,6 +43,10 @@ describe("connectionAttemptTimeout", () => {
expect(connectionAttemptTimeoutMs({ db_type: "zookeeper", connect_timeout_secs: 5, transport_layers: [] })).toBe(AGENT_DRIVER_MIN_CONNECT_TIMEOUT_SECS * 1000 + CONNECTION_ATTEMPT_TIMEOUT_BUFFER_MS);
});
it("uses the startup floor for Cloud Spanner agent connections", () => {
expect(connectionAttemptTimeoutMs({ db_type: "spanner", connect_timeout_secs: 5, transport_layers: [] })).toBe(AGENT_DRIVER_MIN_CONNECT_TIMEOUT_SECS * 1000 + CONNECTION_ATTEMPT_TIMEOUT_BUFFER_MS);
});
it("uses a 30s Access agent startup floor", () => {
expect(connectionAttemptTimeoutMs({ db_type: "access", connect_timeout_secs: 5, transport_layers: [] })).toBe(ACCESS_AGENT_MIN_CONNECT_TIMEOUT_SECS * 1000 + CONNECTION_ATTEMPT_TIMEOUT_BUFFER_MS);
});
@@ -0,0 +1,69 @@
import { readFileSync } from "node:fs";
import { describe, expect, it } from "vitest";
const dialogSource = readFileSync(new URL("../../../components/connection/ConnectionDialog.vue", import.meta.url), "utf8");
const fieldsSource = readFileSync(new URL("../../../components/connection/SpannerConnectionFields.vue", import.meta.url), "utf8");
describe("Cloud Spanner connection dialog", () => {
it("registers the bundled agent profile in the SQL category", () => {
expect(dialogSource).toContain('spanner: { type: "spanner", port: 443, user: "", label: "Cloud Spanner", icon: "spanner" }');
expect(dialogSource).toContain('{ value: "spanner", label: "Cloud Spanner" }');
expect(dialogSource).toContain('spanner: "spanner",');
// Cloud Spanner is an OLTP relational database, so it belongs to the SQL
// category rather than the analytics one.
const sqlCategory = dialogSource.match(/key: "sql",\s*\n\s*titleKey: "connection\.databaseCategorySql",\s*\n\s*optionValues: \[([\s\S]*?)\]/)?.[1] ?? "";
const analyticsCategory = dialogSource.match(/key: "analytics",[\s\S]*?optionValues: \[([\s\S]*?)\]/)?.[1] ?? "";
expect(sqlCategory).toContain('"spanner"');
expect(analyticsCategory).not.toContain('"spanner"');
});
it("does not expose external JDBC driver configuration because the driver is bundled", () => {
const nativeAgentDriverSupport = dialogSource.match(/function supportsNativeAgentJdbcDriverConfigType\(dbType: DatabaseType\): boolean \{([\s\S]*?)\}/)?.[1] ?? "";
const jdbcBackedDatabaseTypes = dialogSource.match(/const jdbcBackedDatabaseTypes = new Set<DatabaseType>\(\[([\s\S]*?)\]\);/)?.[1] ?? "";
expect(nativeAgentDriverSupport).toContain('dbType === "bigquery"');
expect(nativeAgentDriverSupport).not.toContain('dbType === "spanner"');
expect(jdbcBackedDatabaseTypes).not.toContain('"spanner"');
});
it("collects the resource path through dedicated fields instead of host and credentials", () => {
expect(dialogSource).toContain('import SpannerConnectionFields from "@/components/connection/SpannerConnectionFields.vue";');
expect(dialogSource).toContain('<SpannerConnectionFields v-model:database="form.database" @change="resetTestState" />');
// User, password, and the generic database row are hidden for Spanner.
// These pin the whole v-if because the rows are shared, so adding another
// database that opts out of one of them means updating the string here too.
expect(dialogSource).toContain("<div v-if=\"form.db_type !== 'meilisearch' && form.db_type !== 'spanner'\" class=\"grid grid-cols-4 items-center gap-4\">");
expect(dialogSource).toContain('<div v-if="form.db_type !== \'spanner\'" class="grid grid-cols-4 items-center gap-4">');
expect(dialogSource).toContain("<div v-if=\"form.db_type !== 'hbase' && form.db_type !== 'meilisearch' && form.db_type !== 'spanner'\" class=\"grid grid-cols-4 items-center gap-4\">");
// Switching to the Spanner profile clears host and credentials.
expect(dialogSource).toContain('if (profile.type === "spanner") {');
// Save/Test gating and submit-time normalization.
expect(dialogSource).toContain("if (isSpannerConnection(form.value)) return hasSpannerResourcePath(form.value);");
expect(dialogSource).toContain("normalizeSpannerConnection(config);");
expect(dialogSource).toContain('throw new Error(t("connection.spannerFieldsRequired"));');
});
it("stays inside the generic branch so the agent install hint and URL params remain available", () => {
const spannerBlockStart = dialogSource.indexOf("<!-- Cloud Spanner: project/instance/database resource path instead of user/password/database -->");
const genericBranchStart = dialogSource.indexOf("<!-- MySQL / PostgreSQL: host, port, user, password, database -->");
const urlParamsRow = dialogSource.indexOf('v-if="supportsGenericUrlParams"');
const agentInstallHint = dialogSource.indexOf('v-if="shouldShowAgentDriverInstallHint"');
expect(genericBranchStart).toBeGreaterThan(0);
expect(spannerBlockStart).toBeGreaterThan(genericBranchStart);
expect(urlParamsRow).toBeGreaterThan(spannerBlockStart);
expect(agentInstallHint).toBeGreaterThan(spannerBlockStart);
expect(dialogSource).toContain("'credentials=/path/key.json;autocommit=true'");
});
it("offers both the structured editor and the raw resource path editor", () => {
expect(fieldsSource).toContain('const database = defineModel<string | undefined>("database");');
expect(fieldsSource).toContain("data-spanner-resource-fields");
expect(fieldsSource).toContain('t("connection.spannerProject")');
expect(fieldsSource).toContain('t("connection.spannerInstance")');
expect(fieldsSource).toContain('t("connection.spannerDatabase")');
expect(fieldsSource).toContain('t("connection.spannerResourcePathMode")');
expect(fieldsSource).toContain('emit("change")');
});
});
@@ -0,0 +1,109 @@
import { describe, expect, it } from "vitest";
import {
encodeSpannerResourcePath,
spannerSchemaDisplayName,
formatSpannerResourcePath,
hasSpannerResourcePath,
isSpannerConnection,
normalizeSpannerConnection,
parseSpannerResourcePath,
spannerDisplayDatabase,
spannerResourceParts,
withSpannerResourcePart,
} from "@/lib/connection/spannerResourcePath";
const RESOURCE_PATH = "projects/p1/instances/i1/databases/db1";
describe("spannerResourcePath", () => {
it("detects Cloud Spanner connections", () => {
expect(isSpannerConnection({ db_type: "spanner" })).toBe(true);
expect(isSpannerConnection({ db_type: "bigquery" })).toBe(false);
});
it("parses a standard resource path", () => {
expect(parseSpannerResourcePath(RESOURCE_PATH)).toEqual({ project: "p1", instance: "i1", database: "db1" });
});
it("tolerates surrounding whitespace, leading and trailing slashes, and keyword casing", () => {
expect(parseSpannerResourcePath(" /projects/p1/instances/i1/databases/db1/ ")).toEqual({ project: "p1", instance: "i1", database: "db1" });
expect(parseSpannerResourcePath("Projects/p1/Instances/i1/Databases/db1")).toEqual({ project: "p1", instance: "i1", database: "db1" });
});
it("rejects paths that are not exactly project/instance/database", () => {
expect(parseSpannerResourcePath("projects/p1/databases/db1")).toBeUndefined();
expect(parseSpannerResourcePath("projects/p1/instances/i1/databases/db1/backups/b1")).toBeUndefined();
expect(parseSpannerResourcePath("projects/p1/instances//databases/db1")).toBeUndefined();
expect(parseSpannerResourcePath(undefined)).toBeUndefined();
expect(parseSpannerResourcePath("")).toBeUndefined();
});
it("reads partial paths so a half-filled form keeps the segments already typed", () => {
expect(spannerResourceParts("projects/p1/instances//databases/")).toEqual({ project: "p1", instance: "", database: "" });
expect(spannerResourceParts("jdbc:cloudspanner:/whatever")).toEqual({ project: "", instance: "", database: "" });
});
it("formats the three segments into a resource path", () => {
expect(formatSpannerResourcePath({ project: "p1", instance: "i1", database: "db1" })).toBe(RESOURCE_PATH);
});
it("keeps partially filled paths instead of discarding typed segments", () => {
expect(formatSpannerResourcePath({ project: "p1", instance: "", database: "db1" })).toBe("projects/p1/instances//databases/db1");
expect(formatSpannerResourcePath({ project: "", instance: "", database: "" })).toBe("");
});
it("keeps only the last segment when a whole path is pasted into one field", () => {
expect(formatSpannerResourcePath({ project: "projects/p1", instance: "i1", database: "db1" })).toBe(RESOURCE_PATH);
});
it("round-trips a canonical path", () => {
expect(formatSpannerResourcePath(parseSpannerResourcePath(RESOURCE_PATH)!)).toBe(RESOURCE_PATH);
});
it("replaces a single segment and adopts a pasted full path", () => {
expect(withSpannerResourcePart(RESOURCE_PATH, "database", "db2")).toBe("projects/p1/instances/i1/databases/db2");
expect(withSpannerResourcePart(undefined, "project", "p1")).toBe("projects/p1/instances//databases/");
expect(withSpannerResourcePart("projects/px/instances/ix/databases/dx", "project", RESOURCE_PATH)).toBe(RESOURCE_PATH);
});
it("requires all three segments before the connection target counts as complete", () => {
expect(hasSpannerResourcePath({ database: RESOURCE_PATH })).toBe(true);
expect(hasSpannerResourcePath({ database: undefined })).toBe(false);
expect(hasSpannerResourcePath({ database: "projects/p1/instances//databases/db1" })).toBe(false);
});
it("normalizes credentials and port while preserving host and url params", () => {
const config = { host: " ", port: 0, username: "root", password: "secret", database: ` /${RESOURCE_PATH}/ `, url_params: "credentials=/path/key.json" };
normalizeSpannerConnection(config);
expect(config).toEqual({ host: "", port: 443, username: "", password: "", database: RESOURCE_PATH, url_params: "credentials=/path/key.json" });
});
it("keeps an emulator host and port untouched", () => {
const config = { host: "localhost", port: 9010, username: "", password: "", database: RESOURCE_PATH };
normalizeSpannerConnection(config);
expect(config.host).toBe("localhost");
expect(config.port).toBe(9010);
});
it("shows the database ID rather than the whole resource path", () => {
expect(spannerDisplayDatabase(RESOURCE_PATH)).toBe("db1");
expect(spannerDisplayDatabase("some-other-path")).toBe("some-other-path");
expect(spannerDisplayDatabase(undefined)).toBe("");
});
it("gives GoogleSQL's nameless default schema something to render", () => {
// The empty string is the literal name of the GoogleSQL user schema, so the sidebar would
// otherwise show a blank node beside any named schema. Display only: routing still uses "".
expect(spannerSchemaDisplayName("")).toBe("(default)");
expect(spannerSchemaDisplayName("public")).toBe("public");
expect(spannerSchemaDisplayName("sales")).toBe("sales");
});
it("keeps the resource path separators when encoding it for display", () => {
// The connection tooltip used to run the whole value through
// encodeURIComponent, rendering every separator as %2F and making the URL
// unreadable. Separators are structure here, so only the segments escape.
expect(encodeSpannerResourcePath(RESOURCE_PATH)).toBe(RESOURCE_PATH);
expect(encodeSpannerResourcePath("projects/p 1/instances/i/databases/d")).toBe("projects/p%201/instances/i/databases/d");
expect(encodeSpannerResourcePath("")).toBe("");
});
});
@@ -0,0 +1,52 @@
import { readFileSync } from "node:fs";
import { describe, expect, it } from "vitest";
/**
* Admin SQL (drop / empty / truncate / clone / copy) is built in Rust from the database type alone,
* which cannot describe a database whose quote character depends on the connection. Cloud Spanner is
* the case that forces the connection-reported quote to be threaded through: GoogleSQL quotes with
* backticks, its PostgreSQL dialect quotes with double quotes, and the dialect is fixed when the
* database is created. Emitting the static answer produces admin SQL that is a syntax error for
* every PostgreSQL-dialect Spanner database.
*
* These assertions pin the call sites rather than the generated SQL, because the plumbing is what
* regressed: the backend already knew how to honour a reported quote (`data_grid_sql.rs` carries the
* same field) and the builders simply were not given one.
*/
const mutationRuntimeSource = readFileSync(new URL("../../../composables/useSidebarTableMutationRuntime.ts", import.meta.url), "utf8");
const treeRuntimeSource = readFileSync(new URL("../../../components/sidebar/SidebarTreeRuntimeHost.vue", import.meta.url), "utf8");
const objectBrowserSource = readFileSync(new URL("../../../components/objects/ObjectBrowser.vue", import.meta.url), "utf8");
const adminSqlSource = readFileSync(new URL("../../database/dbAdminSql.ts", import.meta.url), "utf8");
describe("admin SQL carries the connection identifier quote", () => {
it("declares the field on every option type whose SQL qualifies an object name", () => {
for (const type of ["DropObjectSqlOptions", "TableAdminSqlOptions", "DuplicateTableStructureSqlOptions", "CopyTableDataSqlOptions"]) {
const body = adminSqlSource.match(new RegExp(`export interface ${type} \\{([\\s\\S]*?)\\n\\}`))?.[1] ?? "";
expect(body, `${type} must accept identifierQuote`).toContain("identifierQuote?: string;");
}
});
it("threads the quote through drop, empty and truncate from the sidebar", () => {
// Both factories: one reads the active node, the other an explicit node during multi-select.
expect(mutationRuntimeSource).toMatch(/tableName: activeNode\.value\.label,[\s\S]*?identifierQuote: connectionStore\.connectionIdentifierQuote\?\.\(activeNode\.value\.connectionId\)/);
expect(mutationRuntimeSource).toMatch(/tableName: node\.label,\s*identifierQuote: connectionStore\.connectionIdentifierQuote\?\.\(node\.connectionId\)/);
});
it("threads the quote through dropping a view or routine", () => {
expect(treeRuntimeSource).toMatch(/signature: node\.signature,[\s\S]*?identifierQuote: connectionStore\.connectionIdentifierQuote\?\.\(node\.connectionId\)/);
expect(objectBrowserSource).toMatch(/buildDropObjectSql\(\{[\s\S]*?identifierQuote: connectionStore\.connectionIdentifierQuote\?\.\(props\.connection\.id\)/);
});
it("threads the quote through clone and cross-database paste", () => {
expect(treeRuntimeSource).toMatch(/buildDuplicateTableStructurePlan\(\{[\s\S]*?identifierQuote: connectionStore\.connectionIdentifierQuote\?\.\(node\.connectionId\)/);
expect(treeRuntimeSource).toMatch(/buildDuplicateTableStructurePlan\(\{[\s\S]*?identifierQuote: connectionStore\.connectionIdentifierQuote\?\.\(entry\.connectionId\)/);
expect(objectBrowserSource).toMatch(/buildSharedDuplicateTableStructurePlan\(\{[\s\S]*?identifierQuote: connectionStore\.connectionIdentifierQuote\?\.\(props\.connection\.id\)/);
// The plan helper must forward it to the SQL builder rather than swallowing it.
expect(adminSqlSource).toMatch(/buildDuplicateTableStructureSql\(\{[\s\S]*?identifierQuote: options\.identifierQuote/);
});
it("threads the quote through copying table data", () => {
expect(treeRuntimeSource).toMatch(/buildCopyTableDataSql\(\{[\s\S]*?identifierQuote: connectionStore\.connectionIdentifierQuote\?\.\(entry\.connectionId\)/);
expect(objectBrowserSource).toMatch(/buildCopyTableDataSql\(\{[\s\S]*?identifierQuote: connectionStore\.connectionIdentifierQuote\?\.\(props\.connection\.id\)/);
});
});
@@ -15,12 +15,34 @@ import {
supportsTableVacuum,
supportsTransaction,
usesConnectionOnlyQueryTarget,
usesTreeSchemaMode,
schemaNodeHasLoadableName,
} from "@/lib/database/databaseFeatureSupport";
describe("schema awareness", () => {
it("keeps SQLite database aliases separate from schema-capable databases", () => {
expect(isSchemaAware("sqlite")).toBe(false);
});
it("puts Cloud Spanner in both schema sets because they gate different surfaces", () => {
// Spanner 2024+ has named schemas and they are queryable, so both have to be true. The two sets
// are not interchangeable: SCHEMA_AWARE_TYPES reaches the schema pickers in dialogs, while
// TREE_SCHEMA_TYPES is what makes a database node load schemas instead of tables. With only the
// former, `sales` showed up in the schema-diff dropdown but was unreachable in the object tree.
expect(isSchemaAware("spanner")).toBe(true);
expect(usesTreeSchemaMode("spanner")).toBe(true);
});
it("treats Cloud Spanner's blank schema as a loadable node name", () => {
// The GoogleSQL default schema node carries "", so a truthiness check would render an
// expandable node that never loads its tables. Other types keep the truthiness test, which is
// what filters the undefined schema on nodes that have no schema level at all.
expect(schemaNodeHasLoadableName("spanner", "")).toBe(true);
expect(schemaNodeHasLoadableName("spanner", "sales")).toBe(true);
expect(schemaNodeHasLoadableName("spanner", undefined)).toBe(false);
expect(schemaNodeHasLoadableName("postgres", "")).toBe(false);
expect(schemaNodeHasLoadableName("postgres", "public")).toBe(true);
});
});
describe("connection database browser", () => {
@@ -0,0 +1,42 @@
import { describe, expect, it } from "vitest";
import { buildDatabaseTreeNodes } from "@/lib/database/databaseTree";
import { spannerDisplayDatabase } from "@/lib/connection/spannerResourcePath";
import type { DatabaseInfo } from "@/types/database";
const SPANNER_PATH = "projects/test-project/instances/test-instance/databases/gsqldb";
function databases(...names: string[]): DatabaseInfo[] {
return names.map((name) => ({ name }) as DatabaseInfo);
}
describe("buildDatabaseTreeNodes", () => {
it("labels nodes with the reported name when no displayLabel is given", () => {
const [node] = buildDatabaseTreeNodes("conn-1", databases("analytics"));
expect(node.label).toBe("analytics");
expect(node.database).toBe("analytics");
expect(node.id).toBe("conn-1:analytics");
});
it("shortens the Cloud Spanner label but keeps the resource path as the node identity", () => {
const [node] = buildDatabaseTreeNodes("conn-1", databases(SPANNER_PATH), { displayLabel: spannerDisplayDatabase });
// Visible text is the database id only — a 60-char resource path would be
// truncated to `projects/test-proj…` in a narrow sidebar.
expect(node.label).toBe("gsqldb");
// Identity must stay the full path: it round-trips to the agent as
// ConnectParams.database, and the short name would break URL building.
expect(node.database).toBe(SPANNER_PATH);
expect(node.id).toBe(`conn-1:${SPANNER_PATH}`);
});
it("falls back to the reported name when displayLabel yields nothing", () => {
const [node] = buildDatabaseTreeNodes("conn-1", databases("analytics"), { displayLabel: () => "" });
expect(node.label).toBe("analytics");
});
it("leaves every other database type untouched when a displayLabel is absent", () => {
const nodes = buildDatabaseTreeNodes("conn-1", databases("beta", "alpha"));
expect(nodes.map((node) => node.label)).toEqual(["alpha", "beta"]);
});
});
@@ -425,6 +425,25 @@ describe("buildDuplicateTableStructurePlan", () => {
expect(plan).toEqual({ sql: 'CREATE TABLE "copy" (LIKE "source" INCLUDING ALL);', sourceColumns: undefined, executeAsScript: false });
});
it("forwards the connection identifier quote so dual-dialect clones stay executable", async () => {
// Cloud Spanner's PostgreSQL dialect quotes with double quotes while GoogleSQL uses backticks,
// and only the connected agent knows which. Dropping the quote here would make the backend fall
// back to the static per-type mapping and emit a syntax error for one of the two dialects.
apiMock.buildDuplicateTableStructureSql.mockResolvedValue('CREATE TABLE "copy" AS SELECT * FROM "source" WHERE false;');
await buildDuplicateTableStructurePlan({
connectionId: "spanner-1",
database: "projects/p/instances/i/databases/d",
databaseType: "spanner",
schema: "public",
sourceName: "source",
targetName: "copy",
identifierQuote: '"',
});
expect(apiMock.buildDuplicateTableStructureSql).toHaveBeenCalledWith(expect.objectContaining({ identifierQuote: '"' }));
});
it("keeps Oracle cloning available when optional table comment loading fails", async () => {
const warning = vi.spyOn(console, "warn").mockImplementation(() => {});
const columns = [{ name: "ID", data_type: "NUMBER", is_nullable: false, column_default: null, is_primary_key: true }];
@@ -1,7 +1,9 @@
import { describe, expect, it } from "vitest";
import type { ConnectionConfig } from "@/types/database";
import { databaseObjectTreeNodeSchema } from "@/lib/database/databaseFeatureSupport";
import {
GAUSSDB_M_JDBC_DRIVER_CLASS,
connectionDatabaseMetadataSchema,
connectionObjectTreeNodeSchema,
connectionObjectTreeQuerySchema,
connectionQueryExecutionSchema,
@@ -17,6 +19,7 @@ import {
gaussdbIdentifierQuoteStyle,
gaussdbTargetServerType,
inferJdbcDialect,
metadataSchemaForConnection,
setGaussdbConnectionMode,
setGaussdbCountQueryDop,
setGaussdbIdentifierQuoteStyle,
@@ -112,6 +115,10 @@ describe("jdbc dialect inference", () => {
expect(connectionShouldLoadIdentifierQuote({ db_type: "gaussdb" })).toBe(true);
expect(connectionShouldLoadIdentifierQuote({ db_type: "gbase", driver_profile: "gbase8s" })).toBe(true);
expect(connectionShouldLoadIdentifierQuote({ db_type: "gbase", driver_profile: "gbase8a" })).toBe(false);
// Cloud Spanner reports a backtick for GoogleSQL and a double quote for the
// PostgreSQL dialect; both are only known from the connection.
expect(connectionShouldLoadIdentifierQuote({ db_type: "spanner" })).toBe(true);
expect(connectionShouldLoadIdentifierQuote({ db_type: "bigquery" })).toBe(false);
expect(
connectionShouldLoadIdentifierQuote({
db_type: "jdbc",
@@ -311,4 +318,47 @@ describe("object tree node schema", () => {
expect(connectionObjectTreeQuerySchema({ db_type: "informix" }, "prulife", "xtdpcky")).toBe("xtdpcky");
expect(connectionObjectTreeNodeSchema({ db_type: "informix" }, "prulife", "xtdpcky")).toBe("xtdpcky");
});
it("never sends the Cloud Spanner resource path as a metadata schema", () => {
const connection = { db_type: "spanner" as const };
const resourcePath = "projects/p/instances/i/databases/db";
// GoogleSQL's default schema is the empty string, which must survive the
// `schema || database` default: sending the resource path matches no objects.
expect(connectionObjectTreeQuerySchema(connection, resourcePath, "")).toBe("");
expect(connectionObjectTreeQuerySchema(connection, resourcePath)).toBe("");
expect(metadataSchemaForConnection(connection, resourcePath, "")).toBe("");
// PostgreSQL-dialect databases and named schemas pass through unchanged.
expect(connectionObjectTreeQuerySchema(connection, resourcePath, "public")).toBe("public");
expect(connectionObjectTreeQuerySchema(connection, resourcePath, "analytics")).toBe("analytics");
expect(metadataSchemaForConnection(connection, resourcePath, "analytics")).toBe("analytics");
// The tree node resolves to GoogleSQL's blank default schema rather than to the resource
// path, so the path can never reach qualifiedTableName as a qualifier. It is the empty
// string and not undefined because Spanner does have a schema level: "" is the literal
// name of the GoogleSQL user schema.
expect(connectionObjectTreeNodeSchema(connection, resourcePath)).toBe("");
expect(connectionObjectTreeNodeSchema(connection, resourcePath, "")).toBe("");
expect(connectionObjectTreeNodeSchema(connection, resourcePath, "sales")).toBe("sales");
expect(connectionObjectTreeNodeSchema(connection, resourcePath, resourcePath)).toBe("");
// Named schemas (Spanner 2024+) reach the tree unchanged now that Spanner is schema-aware.
expect(connectionObjectTreeQuerySchema(connection, resourcePath, "sales")).toBe("sales");
expect(databaseObjectTreeNodeSchema("spanner", resourcePath, "sales")).toBe("sales");
expect(databaseObjectTreeNodeSchema("spanner", resourcePath, "")).toBe("");
expect(databaseObjectTreeNodeSchema("spanner", resourcePath)).toBe("");
// Callers that collapsed `node.schema || node.database` before calling in (the sidebar
// SQL template and DDL paths) hand over the resource path as the schema.
expect(connectionObjectTreeQuerySchema(connection, resourcePath, resourcePath)).toBe("");
expect(metadataSchemaForConnection(connection, resourcePath, resourcePath)).toBe("");
});
it("keeps the database-as-schema fallback for flat engines and blanks it for Cloud Spanner", () => {
// Editor completion paths send the database name as the metadata schema when a
// connection has no schema level; only Spanner must send a blank schema instead.
expect(connectionDatabaseMetadataSchema({ db_type: "mysql" }, "shop")).toBe("shop");
expect(connectionDatabaseMetadataSchema({ db_type: "hbase" }, "shop")).toBe("shop");
expect(connectionDatabaseMetadataSchema({ db_type: "mysql" }, "shop", "other")).toBe("other");
expect(connectionDatabaseMetadataSchema({ db_type: "spanner" }, "projects/p/instances/i/databases/db")).toBe("");
expect(connectionDatabaseMetadataSchema({ db_type: "spanner" }, "projects/p/instances/i/databases/db", "")).toBe("");
expect(connectionDatabaseMetadataSchema({ db_type: "spanner" }, "projects/p/instances/i/databases/db", "public")).toBe("public");
});
});
@@ -59,6 +59,42 @@ describe("quoteTableIdentifier", () => {
expect(quoteTableIdentifier("bigquery", "a`b")).toBe("`a\\`b`");
});
it("backtick-quotes Cloud Spanner GoogleSQL identifiers by default", () => {
expect(quoteTableIdentifier("spanner", "order")).toBe("`order`");
expect(quoteTableIdentifier("spanner", "a`b")).toBe("`a\\`b`");
});
it("uses the connection-reported quote for Cloud Spanner table-data identifiers", () => {
// GoogleSQL dialect: the agent reports a backtick.
expect(quoteTableDataIdentifier("spanner", "order", "`")).toBe("`order`");
// PostgreSQL dialect: the agent reports a double quote.
expect(quoteTableDataIdentifier("spanner", "MixedCase", '"')).toBe('"MixedCase"');
});
it("keeps Cloud Spanner GoogleSQL names single-segment and qualifies PostgreSQL-dialect names", () => {
// GoogleSQL user schema is the empty string; a two-part name would be a syntax error.
expect(qualifiedTableName({ databaseType: "spanner", schema: "", tableName: "singers", identifierQuote: "`" })).toBe("`singers`");
expect(qualifiedTableName({ databaseType: "spanner", schema: "public", tableName: "singers", identifierQuote: '"' })).toBe('"public"."singers"');
// No reported quote: fall back to the GoogleSQL default.
expect(qualifiedTableName({ databaseType: "spanner", tableName: "singers" })).toBe("`singers`");
});
it("never qualifies a Cloud Spanner table with the resource path", () => {
// The sidebar SQL template path collapses `node.schema || node.database`, and for Spanner the
// database is the resource path, which is not a schema and is not valid inside a table name.
const resourcePath = "projects/p/instances/i/databases/db";
expect(qualifiedTableName({ databaseType: "spanner", schema: resourcePath, database: resourcePath, tableName: "singers", identifierQuote: "`" })).toBe("`singers`");
expect(qualifiedTableName({ databaseType: "spanner", schema: resourcePath, database: resourcePath, tableName: "singers", identifierQuote: '"' })).toBe('"singers"');
expect(qualifiedTableName({ databaseType: "spanner", schema: resourcePath, tableName: "singers" })).toBe("`singers`");
});
it("keeps the Cloud Spanner schema qualifier even before the connection quote loads", () => {
// The quote is fetched asynchronously after connect and can be missing, so the
// branch is unconditional: a named schema must never lose its qualifier.
expect(qualifiedTableName({ databaseType: "spanner", schema: "analytics", tableName: "singers" })).toBe("`analytics`.`singers`");
expect(qualifiedTableName({ databaseType: "spanner", schema: " ", tableName: "singers" })).toBe("`singers`");
});
it("bracket-quotes sqlserver identifiers", () => {
expect(quoteTableIdentifier("sqlserver", "orders")).toBe("[orders]");
});
@@ -81,6 +81,7 @@ describe("AGENT_DRIVER_CATEGORY_MAP integrity", () => {
"informix",
"iris",
"oracle",
"spanner",
"sqlserver-legacy",
// analytics
"bigquery",
@@ -40,6 +40,7 @@ const DRIVER_STARTUP_FLOOR_TYPES = new Set<DatabaseType>([
"neo4j",
"cassandra",
"bigquery",
"spanner",
"kylin",
"ignite",
"ignite3",
@@ -1,6 +1,7 @@
import type { ConnectionConfig, DatabaseType } from "@/types/database";
import { GAUSSDB_M_JDBC_DRIVER_PROFILE } from "@/lib/database/jdbcDialect";
import { parseGaussdbHosts, serializeGaussdbHosts } from "@/lib/connection/gaussdbHosts";
import { spannerDisplayDatabase } from "@/lib/connection/spannerResourcePath";
type ConnectionPresentationConfig = Pick<ConnectionConfig, "db_type" | "driver_profile" | "driver_label" | "host" | "port" | "database">;
type ConnectionNamePresentationConfig = ConnectionPresentationConfig & Pick<ConnectionConfig, "name">;
@@ -20,6 +21,9 @@ export function connectionDriverLabel(connection?: Pick<ConnectionConfig, "db_ty
export function connectionEndpointLabel(connection?: ConnectionPresentationConfig): string {
if (!connection) return "";
if (connection.db_type === "cloudflare-d1") return [connection.host, connection.database].filter(Boolean).join("/");
// Cloud Spanner stores the whole resource path in `database`; only the trailing
// database ID is short enough for a subtitle, and the host is empty on Google Cloud.
if (connection.db_type === "spanner") return connection.host ? `${connection.host}:${connection.port}` : spannerDisplayDatabase(connection.database);
if (LOCAL_DATABASE_TYPES.has(connection.db_type) || (connection.db_type === "h2" && connection.port === 0)) {
return connection.host || connection.database || "local";
}
@@ -80,6 +84,10 @@ function redactSingleHost(host: string): string {
export function connectionRedactedEndpointLabel(connection?: ConnectionPresentationConfig): string {
if (!connection) return "";
if (connection.db_type === "cloudflare-d1") return `${REDACTED_HOST_SEGMENT}/${REDACTED_HOST_SEGMENT}`;
// The Spanner endpoint label already drops project and instance, so it carries
// no more than any other database name; without this branch the fallback below
// would print the full `projects/.../databases/...` path.
if (connection.db_type === "spanner") return connection.host ? `${redactConnectionHost(connection.host)}:${REDACTED_PORT}` : spannerDisplayDatabase(connection.database);
if (LOCAL_DATABASE_TYPES.has(connection.db_type) || (connection.db_type === "h2" && connection.port === 0)) {
return connectionEndpointLabel(connection);
}
@@ -242,6 +250,9 @@ export function connectionUrlPlaceholder(dbType: DatabaseType): string {
case "bigquery":
return "bigquery://https://www.googleapis.com/bigquery/v2:443/project-id";
case "spanner":
return "spanner:///projects/{project}/instances/{instance}/databases/{database}";
case "iris":
return "iris://user:password@host:port/namespace";
@@ -55,6 +55,7 @@ export const AGENT_DRIVER_CATEGORY_MAP: Readonly<Record<string, DriverCategoryKe
rocketmq: "mq",
saphana: "analytics",
snowflake: "analytics",
spanner: "sql",
spark: "analytics",
"sqlserver-legacy": "sql",
sundb: "domestic",
@@ -0,0 +1,133 @@
import type { ConnectionConfig } from "@/types/database";
/**
* Cloud Spanner has no host/port identity: a database is addressed by the
* resource path `projects/{project}/instances/{instance}/databases/{database}`.
* DBX stores that whole path in `ConnectionConfig.database` and lets the
* connection dialog edit it either as three IDs or as the raw path.
*
* Partial paths (`projects/p/instances//databases/`) are intentionally
* representable so that typing one field at a time never discards the fields
* already filled in; `hasSpannerResourcePath` is what gates Save/Test.
*/
export interface SpannerResourceParts {
project: string;
instance: string;
database: string;
}
export const SPANNER_DEFAULT_PORT = 443;
const EMPTY_PARTS: SpannerResourceParts = { project: "", instance: "", database: "" };
// Keywords are matched case-insensitively; segments are captured verbatim.
// The trailing segment is optional so a path whose database ID is still empty
// (`projects/p/instances/i/databases/`, trailing slash trimmed) still parses.
const SPANNER_RESOURCE_PATH_RE = /^projects\/([^/]*)\/instances\/([^/]*)\/databases(?:\/([^/]*))?$/i;
type MutableSpannerConfig = Pick<ConnectionConfig, "host" | "port" | "username" | "password" | "database">;
export function isSpannerConnection(config: Pick<ConnectionConfig, "db_type">): boolean {
return config.db_type === "spanner";
}
function normalizeResourcePath(path: string | undefined): string {
return (path ?? "").trim().replace(/^\/+/, "").replace(/\/+$/, "");
}
/**
* Lenient read: returns whatever segments the value carries, with empty strings
* for the missing ones. Anything that is not shaped like a Spanner resource path
* yields all-empty parts, which is what keeps the raw-path editor authoritative.
*/
export function spannerResourceParts(path: string | undefined): SpannerResourceParts {
const match = SPANNER_RESOURCE_PATH_RE.exec(normalizeResourcePath(path));
if (!match) return { ...EMPTY_PARTS };
return { project: match[1] ?? "", instance: match[2] ?? "", database: match[3] ?? "" };
}
/** Strict read: only a complete three-segment path parses. */
export function parseSpannerResourcePath(path: string | undefined): SpannerResourceParts | undefined {
const parts = spannerResourceParts(path);
return parts.project && parts.instance && parts.database ? parts : undefined;
}
/**
* Each field holds a single ID. When a value contains slashes (typically a whole
* resource path pasted into one box) only the last segment is kept, so
* `projects/p1` becomes `p1` instead of `projects/projects/p1/...`.
*/
function normalizeSegment(value: string): string {
const trimmed = value.trim();
if (!trimmed.includes("/")) return trimmed;
const segments = trimmed
.split("/")
.map((segment) => segment.trim())
.filter(Boolean);
return segments.length ? segments[segments.length - 1]! : "";
}
export function formatSpannerResourcePath(parts: SpannerResourceParts): string {
const project = normalizeSegment(parts.project);
const instance = normalizeSegment(parts.instance);
const database = normalizeSegment(parts.database);
if (!project && !instance && !database) return "";
return `projects/${project}/instances/${instance}/databases/${database}`;
}
/**
* Replaces one segment of the stored path. A full resource path pasted into any
* of the three fields replaces all three segments at once.
*/
export function withSpannerResourcePart(database: string | undefined, key: keyof SpannerResourceParts, value: string): string {
const pasted = parseSpannerResourcePath(value);
if (pasted) return formatSpannerResourcePath(pasted);
return formatSpannerResourcePath({ ...spannerResourceParts(database), [key]: value });
}
export function hasSpannerResourcePath(config: Pick<ConnectionConfig, "database">): boolean {
return !!parseSpannerResourcePath(config.database);
}
/**
* Submit-time normalization. Unlike Cloudflare D1 this must not clear
* `url_params` (Spanner passes `credentials=`, `autoConfigEmulator=` through it)
* and must not touch `host` (empty means Google Cloud, `localhost` means the
* local emulator).
*/
export function normalizeSpannerConnection(config: MutableSpannerConfig): void {
const parts = parseSpannerResourcePath(config.database);
config.database = (parts ? formatSpannerResourcePath(parts) : normalizeResourcePath(config.database)) || undefined;
config.host = config.host.trim();
config.username = "";
config.password = "";
if (!Number.isInteger(config.port) || config.port <= 0) config.port = SPANNER_DEFAULT_PORT;
}
/** Sidebar/subtitle label: the database ID, not the whole resource path. */
export function spannerDisplayDatabase(database: string | undefined): string {
return parseSpannerResourcePath(database)?.database ?? (database ?? "").trim();
}
/**
* GoogleSQL's user schema is literally the empty string, so the sidebar would otherwise render a
* nameless node next to any named schema. Mirrors `xuguSchemaDisplayName`: a display-only label
* that never replaces the real schema key used for routing.
*/
export const SPANNER_DEFAULT_SCHEMA_LABEL = "(default)";
export function spannerSchemaDisplayName(schema: string): string {
return schema === "" ? SPANNER_DEFAULT_SCHEMA_LABEL : schema;
}
/**
* Percent-encode a Spanner resource path for display, keeping the `/` separators
* intact — they are structure, not data. Mirrors `encode_spanner_resource_path`
* in crates/dbx-core/src/models/connection.rs.
*
* Every other database type keeps whole-value encoding, where a slash inside a
* database name really is data and should be escaped.
*/
export function encodeSpannerResourcePath(database: string): string {
return database.split("/").map(encodeURIComponent).join("/");
}
@@ -2,6 +2,9 @@ import type { DatabaseType } from "@/types/database";
export const SCHEMA_AWARE_TYPES = new Set<DatabaseType>([
"postgres",
// Cloud Spanner supports named schemas; GoogleSQL's default schema is the empty string, which
// `spannerObjectTreeSchema` keeps intact through the `schema || database` fallbacks.
"spanner",
"sqlserver",
"oracle",
"redshift",
@@ -55,6 +58,12 @@ export const FETCH_FIRST_TYPES = new Set<DatabaseType>(["oracle", "dameng"]);
export const TREE_SCHEMA_TYPES = new Set<DatabaseType>([
"postgres",
// Cloud Spanner needs the schema level for the same reason it is in SCHEMA_AWARE_TYPES: named
// schemas exist and are queryable, so the tree has to expose them. Membership here is what makes
// a database node load schemas instead of tables; SCHEMA_AWARE_TYPES alone only reaches the
// schema pickers in dialogs. The sites gated on `database === ""` stay unreachable because a
// Spanner database is always the resource path.
"spanner",
"redshift",
"sqlserver",
"db2",
@@ -64,8 +64,33 @@ export function databaseObjectTreeQuerySchema(dbType: DatabaseType | undefined,
return schema || database;
}
/**
* Cloud Spanner is the one schema-aware type whose default schema is the empty string: that is the
* literal name of GoogleSQL's user schema, and the agent forwards it to the driver verbatim. Every
* `schema || database` fallback therefore has to be bypassed, because `database` holds a resource
* path (`projects/…/databases/db`) that is never a schema name and matches no metadata.
*
* Named schemas (Spanner 2024+) pass through unchanged. Callers that already collapsed
* `schema || node.database` are normalized back to the blank schema, which is safe because a Spanner
* schema identifier is letters, digits and underscores and can never contain the path separator.
*/
export function spannerObjectTreeSchema(schema?: string): string {
return schema && !schema.includes("/") ? schema : "";
}
/**
* Whether a schema tree node carries a name its children can be loaded for. Cloud Spanner is the one
* type where the empty string is a real schema name (GoogleSQL's user schema), so a plain truthiness
* check would leave that node expandable but permanently empty. Every other type keeps the
* truthiness test, which also filters the undefined schema on nodes that have no schema level.
*/
export function schemaNodeHasLoadableName(dbType: DatabaseType | undefined, schema?: string): boolean {
return dbType === "spanner" ? schema != null : !!schema;
}
export function databaseObjectTreeNodeSchema(dbType: DatabaseType | undefined, database: string, schema?: string): string | undefined {
if (usesDatabaseObjectTreeMode(dbType)) return undefined;
if (dbType === "spanner") return spannerObjectTreeSchema(schema);
if (schema) return schema;
return isSchemaAware(dbType) ? database : undefined;
}
@@ -75,6 +75,7 @@ export const DATABASE_NAMESPACE_CREATION_MATRIX = {
neo4j: { deferred: "database creation depends on edition/admin privileges" },
cassandra: { deferred: "keyspace creation requires replication options" },
bigquery: { deferred: "dataset creation needs project/location options" },
spanner: { deferred: "database creation requires the Cloud Spanner Admin API" },
kylin: { deferred: "project/model lifecycle is not SQL database creation" },
ignite: { deferred: "schema lifecycle is managed through cluster/cache configuration" },
ignite3: { deferred: "schema lifecycle is managed through cluster configuration" },
@@ -77,6 +77,9 @@ const DATABASE_TYPE_OBJECTS = new Map<DatabaseType, SidebarObjectKind[]>([
["prestosql", TABLE_VIEW_OBJECTS],
["cassandra", TABLE_VIEW_OBJECTS],
["bigquery", TABLE_VIEW_OBJECTS],
// Cloud Spanner has no triggers, routines, sequences, or synonyms; without an
// explicit entry the sidebar would fall back to ROUTINE_OBJECTS.
["spanner", TABLE_VIEW_OBJECTS],
["kylin", TABLE_VIEW_OBJECTS],
["ignite", TABLE_VIEW_OBJECTS],
["ignite3", TABLE_VIEW_OBJECTS],
@@ -75,6 +75,7 @@ export const DATABASE_PROPERTY_EDITING_MATRIX = {
neo4j: { deferred: "database properties depend on edition/admin privileges" },
cassandra: { deferred: "keyspace properties require replication option handling" },
bigquery: { deferred: "dataset properties need project/location-specific handling" },
spanner: { deferred: "database/schema properties are Cloud Spanner Admin API operations" },
kylin: { deferred: "project/model lifecycle is not SQL database property editing" },
ignite: { deferred: "schema properties need product-specific handling" },
ignite3: { deferred: "schema properties need product-specific handling" },
@@ -84,6 +84,7 @@ const NAVICAT_STYLE_TABLE_DATA_TYPES = new Set<DatabaseType>([
"db2",
"informix",
"bigquery",
"spanner",
"sundb",
"oscar",
"databend",
+10 -2
View File
@@ -19,14 +19,22 @@ export function sortSidebarDatabases(databases: readonly DatabaseInfo[]): Databa
return [...databases].sort((left, right) => sidebarNameCollator.compare(left.name, right.name));
}
export function buildDatabaseTreeNodes(connectionId: string, databases: DatabaseInfo[], options: { includeDefaultWhenEmpty?: boolean } = {}): TreeNode[] {
export function buildDatabaseTreeNodes(
connectionId: string,
databases: DatabaseInfo[],
// `displayLabel` only rewrites the visible text. `id` and `database` keep the
// backend-reported name because that value round-trips to the agent — Cloud
// Spanner reports the full `projects/../instances/../databases/..` resource
// path and would break URL building if the shortened label were sent back.
options: { includeDefaultWhenEmpty?: boolean; displayLabel?: (name: string) => string } = {},
): TreeNode[] {
const nodes = sortSidebarDatabases(databases).flatMap((db) => {
const name = db.name;
if (!name.trim()) return [];
return [
{
id: `${connectionId}:${name}`,
label: name,
label: options.displayLabel?.(name) || name,
type: "database" as const,
connectionId,
database: name,
@@ -9,6 +9,10 @@ export interface DropObjectSqlOptions {
schema?: string | null;
name: string;
signature?: string | null;
/** Quote character reported by the connected server, for types whose quote is not fixed by the
* database type alone (Cloud Spanner's two dialects differ). Mirrors `identifierQuote` on the
* table-data SQL options. */
identifierQuote?: string;
}
export interface TableAdminSqlOptions {
@@ -16,6 +20,10 @@ export interface TableAdminSqlOptions {
schema?: string | null;
tableName: string;
cascade?: boolean;
/** Quote character reported by the connected server, for types whose quote is not fixed by the
* database type alone (Cloud Spanner's two dialects differ). Mirrors `identifierQuote` on the
* table-data SQL options. */
identifierQuote?: string;
}
export interface VacuumTableSqlOptions {
@@ -75,6 +83,10 @@ export interface DuplicateTableStructureSqlOptions {
targetName: string;
tableComment?: string | null;
columnComments?: Array<{ name: string; comment: string }>;
/** Quote character reported by the connected server, for types whose quote is not fixed by the
* database type alone (Cloud Spanner's two dialects differ). Mirrors `identifierQuote` on the
* table-data SQL options. */
identifierQuote?: string;
}
export interface DuplicateTableStructurePlanOptions extends DuplicateTableStructureSqlOptions {
@@ -259,6 +271,7 @@ export async function buildDuplicateTableStructurePlan(options: DuplicateTableSt
targetName: options.targetName,
tableComment: options.tableComment,
columnComments: [],
identifierQuote: options.identifierQuote,
});
return { sql, sourceColumns: options.sourceColumns, executeAsScript: duplicateTableStructureRequiresScript(sql) };
}
@@ -272,6 +285,10 @@ export interface CopyTableDataSqlOptions {
postgresOverridingSystemValue?: boolean;
sqlserverIdentityInsert?: boolean;
normalizeNewTargetName?: boolean;
/** Quote character reported by the connected server, for types whose quote is not fixed by the
* database type alone (Cloud Spanner's two dialects differ). Mirrors `identifierQuote` on the
* table-data SQL options. */
identifierQuote?: string;
}
export function buildDropObjectSql(options: DropObjectSqlOptions): Promise<string> {
+23 -2
View File
@@ -1,5 +1,5 @@
import type { ConnectionConfig, DatabaseType } from "@/types/database";
import { isSchemaAware, usesDatabaseObjectTreeMode, usesTreeSchemaMode } from "@/lib/database/databaseFeatureSupport";
import { isSchemaAware, spannerObjectTreeSchema, usesDatabaseObjectTreeMode, usesTreeSchemaMode } from "@/lib/database/databaseFeatureSupport";
import type { CodeMirrorSqlDialectName } from "@/lib/editor/codemirrorSqlDialect";
type JdbcDialectConnection = Partial<Pick<ConnectionConfig, "db_type" | "driver_profile" | "driver_label" | "connection_string" | "url_params" | "jdbc_driver_class" | "jdbc_driver_paths" | "database_info" | "external_config">>;
@@ -81,6 +81,12 @@ export function connectionShouldLoadIdentifierQuote(connection: JdbcDialectConne
if (!connection) return false;
if (connection.db_type === "gbase" && isGbase8sProfile(connection.driver_profile)) return true;
if (connection.db_type === "kingbase") return true;
// Cloud Spanner is dual-dialect: the agent reports a backtick for GoogleSQL and
// a double quote for PostgreSQL-dialect databases. The backend counts Spanner
// unconditionally in `uses_connection_identifier_quote`, so the UI must fetch
// the reported quote or every locally built statement would use the GoogleSQL
// default against a PostgreSQL-dialect database.
if (connection.db_type === "spanner") return true;
if (gaussdbIdentifierQuoteStyle(connection) !== "auto") return false;
if (connection.db_type === "gaussdb") return true;
if (connection.db_type !== "jdbc") return false;
@@ -207,10 +213,24 @@ export function connectionQueryExecutionSchema(connection: JdbcDialectConnection
export function connectionObjectTreeQuerySchema(connection: JdbcDialectConnection | undefined, database: string, schema?: string): string {
if (connection?.db_type === "jdbc" && inferJdbcDialect(connection) === "databend") return schema || database;
if (connectionUsesDatabaseObjectTreeMode(connection)) return "";
if (effectiveDatabaseTypeForConnection(connection) === "informix") return schema || "";
const type = effectiveDatabaseTypeForConnection(connection);
if (type === "informix") return schema || "";
if (type === "spanner") return spannerObjectTreeSchema(schema);
return schema || database;
}
/**
* Metadata schema for query paths that treat the database name as the schema when a
* connection exposes no schema level (MySQL, HBase, and the other flat engines).
* Cloud Spanner is the exception: its database is a resource path, so the blank
* GoogleSQL schema has to be sent instead of the path. Behavior for every other
* database type is exactly `schema || database`.
*/
export function connectionDatabaseMetadataSchema(connection: JdbcDialectConnection | undefined, database: string, schema?: string): string {
if (schema) return schema;
return effectiveDatabaseTypeForConnection(connection) === "spanner" ? "" : database;
}
export function metadataSchemaForConnection(connection: JdbcDialectConnection | undefined, database: string, schema?: string): string {
const type = effectiveDatabaseTypeForConnection(connection);
if (type === "sqlserver") return schema || "dbo";
@@ -223,6 +243,7 @@ export function connectionObjectTreeNodeSchema(connection: JdbcDialectConnection
const type = effectiveDatabaseTypeForConnection(connection);
if (type === "informix") return schema || undefined;
if (type === "sqlite") return schema || database;
if (type === "spanner") return spannerObjectTreeSchema(schema);
if (!type) return schema;
return isSchemaAware(type) ? schema || database : undefined;
}
+21 -1
View File
@@ -33,6 +33,9 @@ export function quoteTableIdentifier(databaseType: DatabaseType | undefined, nam
// (DatabaseMetaData.getIdentifierQuoteString()) — pass through unquoted.
if (databaseType === "jdbc") return name;
if (databaseType === "bigquery") return `\`${name.replace(/`/g, "\\`")}\``;
// Cloud Spanner defaults to the GoogleSQL dialect (backticks). PostgreSQL-dialect
// databases report `"` on connect and take the quoteTableDataIdentifier path.
if (databaseType === "spanner") return `\`${name.replace(/`/g, "\\`")}\``;
if (
databaseType === "mysql" ||
databaseType === "clickhouse" ||
@@ -55,7 +58,7 @@ export function quoteTableIdentifier(databaseType: DatabaseType | undefined, nam
export function quoteTableDataIdentifier(databaseType: DatabaseType | undefined, name: string, identifierQuote?: string): string {
if ((databaseType === "gaussdb" || databaseType === "opengauss" || databaseType === "postgres") && identifierQuote != null) return quoteGaussDbJdbcIdentifier(name, identifierQuote);
if ((databaseType === "kingbase" || databaseType === "informix") && identifierQuote != null) {
if ((databaseType === "kingbase" || databaseType === "informix" || databaseType === "spanner") && identifierQuote != null) {
if (!identifierQuote) return name;
return `${identifierQuote}${name.replaceAll(identifierQuote, identifierQuote + identifierQuote)}${identifierQuote}`;
}
@@ -100,6 +103,23 @@ export function qualifiedTableName(options: Pick<BuildTableSelectSqlOptions, "da
}
return quotedTable;
}
// Cloud Spanner mirrors `uses_connection_identifier_quote` on the backend, which
// counts Spanner unconditionally: the branch must not be gated on a reported
// quote, otherwise a connection whose quote has not loaded yet would fall through
// to the SCHEMA_AWARE_TYPES path and silently drop the schema qualifier. A blank
// schema (GoogleSQL's default) drops the dot separator with it, because
// `` `s`.`t` `` with an empty `s` is a Spanner syntax error; a missing quote falls
// back to the GoogleSQL backtick default, exactly like `identifiers.rs`.
if (databaseType === "spanner") {
const quotedTable = quoteTableDataIdentifier(databaseType, tableName, identifierQuote);
// `database` holds the resource path `projects/{p}/instances/{i}/databases/{d}`, and callers
// that treat the database as the schema (the sidebar SQL templates collapse
// `node.schema || node.database`) would otherwise emit `` `projects/…`.`singers` ``. A Spanner
// schema name is letters, digits and underscores, so the path separator identifies it.
const trimmedSchema = schema?.trim();
const schemaQualifier = trimmedSchema && !trimmedSchema.includes("/") ? trimmedSchema : undefined;
return schemaQualifier ? `${quoteTableDataIdentifier(databaseType, schemaQualifier, identifierQuote)}.${quotedTable}` : quotedTable;
}
if (databaseType === "informix" && identifierQuote != null) {
const quotedTable = quoteTableDataIdentifier(databaseType, tableName, identifierQuote);
const trimmedSchema = schema?.trim();