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

@@ -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");
});
});