fix(jdbc): expose routine parameter metadata

Closes #11045
This commit is contained in:
t8y2 committed 2026-10-04 15:59:11 +00:00
1 parent a90b00e77a
commit 320e37aa42
17 files changed
+781 -15

No files matched your search

@@ -9,7 +9,7 @@ import { copyToClipboard } from "@/lib/common/clipboard";
import { formatSqlForDisplay, type SqlFormatDialect } from "@/lib/sql/sqlFormatter"; import { formatSqlForDisplay, type SqlFormatDialect } from "@/lib/sql/sqlFormatter";
import { buildEditableObjectSource, buildExecutableObjectSourceStatements, executeObjectSourceSave, formatObjectSourceSaveError, resolveObjectSourceEditDraft } from "@/lib/table/objectSourceEditor"; import { buildEditableObjectSource, buildExecutableObjectSourceStatements, executeObjectSourceSave, formatObjectSourceSaveError, resolveObjectSourceEditDraft } from "@/lib/table/objectSourceEditor";
import { loadObjectSourceWithRoutineFallback } from "@/lib/table/objectSourceLoad"; import { loadObjectSourceWithRoutineFallback } from "@/lib/table/objectSourceLoad";
import { xuguRoutineMetadataFromDefinition, type XuguRoutineMetadata } from "@/lib/table/routineParameters"; import { jdbcRoutineMetadata, xuguRoutineMetadataFromDefinition, type RoutineMetadata } from "@/lib/table/routineParameters";
import { executeWithProductionSqlGuard } from "@/lib/database/productionExecutionGuard"; import { executeWithProductionSqlGuard } from "@/lib/database/productionExecutionGuard";
import * as api from "@/lib/backend/api"; import * as api from "@/lib/backend/api";
import QueryEditor from "@/components/editor/QueryEditor.vue"; import QueryEditor from "@/components/editor/QueryEditor.vue";
@@ -57,7 +57,7 @@ const editing = ref(false);
const sourceEditable = ref(true); const sourceEditable = ref(true);
const error = ref(""); const error = ref("");
const saveError = ref(""); const saveError = ref("");
const routineMetadata = ref<XuguRoutineMetadata | null>(null); const routineMetadata = ref<RoutineMetadata | null>(null);
/** May differ from props.objectType after PROCEDURE/FUNCTION/PACKAGE fallback resolution. */ /** May differ from props.objectType after PROCEDURE/FUNCTION/PACKAGE fallback resolution. */
const resolvedObjectType = ref<ObjectSourceKind>(props.objectType); const resolvedObjectType = ref<ObjectSourceKind>(props.objectType);
let loadSerial = 0; let loadSerial = 0;
@@ -111,7 +111,8 @@ async function loadSource(nextEditing = props.initialEditing && canEdit.value) {
}); });
if (serial !== loadSerial) return; if (serial !== loadSerial) return;
resolvedObjectType.value = resolvedType; resolvedObjectType.value = resolvedType;
routineMetadata.value = props.databaseType === "xugu" && (resolvedType === "PROCEDURE" || resolvedType === "FUNCTION") ? xuguRoutineMetadataFromDefinition(result.source) : null; const isRoutine = resolvedType === "PROCEDURE" || resolvedType === "FUNCTION";
routineMetadata.value = !isRoutine ? null : result.routine_parameters !== undefined ? jdbcRoutineMetadata(result.routine_parameters) : target.databaseType === "xugu" ? xuguRoutineMetadataFromDefinition(result.source) : null;
sourceEditable.value = editableAllowed; sourceEditable.value = editableAllowed;
const displaySource = resolvedType === "SEQUENCE" ? result.source : editable; const displaySource = resolvedType === "SEQUENCE" ? result.source : editable;
const formatted = await formatSqlForDisplay(displaySource, target.formatDialect ?? target.dialect, settingsStore.editorSettings.sqlFormatter); const formatted = await formatSqlForDisplay(displaySource, target.formatDialect ?? target.dialect, settingsStore.editorSettings.sqlFormatter);
@@ -259,6 +260,7 @@ function closeDialog() {
<div v-else class="flex min-h-0 flex-col gap-3 overflow-hidden"> <div v-else class="flex min-h-0 flex-col gap-3 overflow-hidden">
<RoutineMetadataPanel v-if="hasRoutineMetadata && routineMetadata" :parameters="routineMetadata.parameters" :return-type="routineMetadata.returnType" /> <RoutineMetadataPanel v-if="hasRoutineMetadata && routineMetadata" :parameters="routineMetadata.parameters" :return-type="routineMetadata.returnType" />
<QueryEditor <QueryEditor
v-if="content || !hasRoutineMetadata"
:key="`${props.connectionId}:${props.database}:${props.schema || ''}:${props.name}:${props.objectType}`" :key="`${props.connectionId}:${props.database}:${props.schema || ''}:${props.name}:${props.objectType}`"
:model-value="content" :model-value="content"
class="object-source-dialog-editor min-h-0 flex-1 overflow-hidden rounded border" class="object-source-dialog-editor min-h-0 flex-1 overflow-hidden rounded border"
@@ -1,18 +1,26 @@
<script setup lang="ts"> <script setup lang="ts">
import { computed } from "vue";
import { useI18n } from "vue-i18n"; import { useI18n } from "vue-i18n";
import type { RoutineParameter } from "@/lib/table/routineExecutionSql"; import type { RoutineParameter } from "@/lib/table/routineExecutionSql";
defineProps<{ const props = defineProps<{
parameters: RoutineParameter[]; parameters: RoutineParameter[];
returnType?: string; returnType?: string;
}>(); }>();
const { t } = useI18n(); const { t } = useI18n();
const showNullable = computed(() => props.parameters.some((parameter) => parameter.nullable !== undefined && parameter.nullable !== null));
function defaultLabel(parameter: RoutineParameter): string { function defaultLabel(parameter: RoutineParameter): string {
if (!parameter.hasDefault) return "-"; if (!parameter.hasDefault) return "-";
return parameter.defaultValue?.trim() || "DEFAULT"; return parameter.defaultValue?.trim() || "DEFAULT";
} }
function nullableLabel(parameter: RoutineParameter): string {
if (parameter.nullable === true) return t("structureEditor.nullable");
if (parameter.nullable === false) return t("structureEditor.notNull");
return "-";
}
</script> </script>
<template> <template>
@@ -21,17 +29,25 @@ function defaultLabel(parameter: RoutineParameter): string {
<span class="font-semibold text-muted-foreground">RETURN</span> <span class="font-semibold text-muted-foreground">RETURN</span>
<span class="font-mono">{{ returnType }}</span> <span class="font-mono">{{ returnType }}</span>
</div> </div>
<div v-if="parameters.length" class="min-w-[620px]"> <div v-if="parameters.length" :class="showNullable ? 'min-w-[720px]' : 'min-w-[620px]'">
<div class="grid grid-cols-[minmax(140px,1.2fr)_minmax(150px,1.3fr)_80px_minmax(150px,1.3fr)] border-b bg-muted px-3 py-2 text-xs font-medium text-muted-foreground"> <div class="grid border-b bg-muted px-3 py-2 text-xs font-medium text-muted-foreground" :class="showNullable ? 'grid-cols-[minmax(140px,1.2fr)_minmax(150px,1.3fr)_80px_100px_minmax(150px,1.3fr)]' : 'grid-cols-[minmax(140px,1.2fr)_minmax(150px,1.3fr)_80px_minmax(150px,1.3fr)]'">
<div>{{ t("contextMenu.parameterName") }}</div> <div>{{ t("contextMenu.parameterName") }}</div>
<div>{{ t("contextMenu.parameterType") }}</div> <div>{{ t("contextMenu.parameterType") }}</div>
<div>{{ t("contextMenu.parameterMode") }}</div> <div>{{ t("contextMenu.parameterMode") }}</div>
<div v-if="showNullable">{{ t("structureEditor.nullable") }}</div>
<div>{{ t("contextMenu.parameterDefault") }}</div> <div>{{ t("contextMenu.parameterDefault") }}</div>
</div> </div>
<div v-for="parameter in parameters" :key="`${parameter.ordinal}:${parameter.name}`" class="grid grid-cols-[minmax(140px,1.2fr)_minmax(150px,1.3fr)_80px_minmax(150px,1.3fr)] gap-2 border-b px-3 py-2 text-xs last:border-b-0" data-routine-parameter> <div
v-for="parameter in parameters"
:key="`${parameter.ordinal}:${parameter.name}`"
class="grid gap-2 border-b px-3 py-2 text-xs last:border-b-0"
:class="showNullable ? 'grid-cols-[minmax(140px,1.2fr)_minmax(150px,1.3fr)_80px_100px_minmax(150px,1.3fr)]' : 'grid-cols-[minmax(140px,1.2fr)_minmax(150px,1.3fr)_80px_minmax(150px,1.3fr)]'"
data-routine-parameter
>
<div class="truncate font-medium" :title="parameter.name">{{ parameter.name }}</div> <div class="truncate font-medium" :title="parameter.name">{{ parameter.name }}</div>
<div class="truncate font-mono text-muted-foreground" :title="parameter.dataType">{{ parameter.dataType }}</div> <div class="truncate font-mono text-muted-foreground" :title="parameter.dataType">{{ parameter.dataType }}</div>
<div class="text-muted-foreground">{{ parameter.mode }}</div> <div class="text-muted-foreground">{{ parameter.mode }}</div>
<div v-if="showNullable" class="text-muted-foreground" data-routine-nullable>{{ nullableLabel(parameter) }}</div>
<div class="truncate font-mono text-muted-foreground" :title="defaultLabel(parameter)"> <div class="truncate font-mono text-muted-foreground" :title="defaultLabel(parameter)">
{{ defaultLabel(parameter) }} {{ defaultLabel(parameter) }}
</div> </div>
@@ -0,0 +1,111 @@
// @vitest-environment happy-dom
import { createApp, defineComponent, h, type App } from "vue";
import { createPinia, setActivePinia } from "pinia";
import { createI18n } from "vue-i18n";
import { afterEach, describe, expect, it, vi } from "vitest";
import { useConnectionStore } from "@/stores/connectionStore";
import ObjectSourceDialog from "@/components/objects/ObjectSourceDialog.vue";
const mocks = vi.hoisted(() => ({
getObjectSource: vi.fn(),
buildEditableObjectSource: vi.fn(),
}));
vi.mock("@/lib/backend/api", async (importOriginal) => ({
...(await importOriginal<typeof import("@/lib/backend/api")>()),
...mocks,
}));
vi.mock("@/components/editor/QueryEditor.vue", () => ({
default: defineComponent({
name: "QueryEditorStub",
props: { modelValue: { type: String, default: "" } },
template: "<div data-query-editor-stub>{{ modelValue }}</div>",
}),
}));
const mountedApps: Array<{ app: App; host: HTMLElement }> = [];
afterEach(() => {
for (const { app, host } of mountedApps.splice(0)) {
app.unmount();
host.remove();
}
vi.restoreAllMocks();
Object.values(mocks).forEach((mock) => mock.mockReset());
});
async function mountDialog() {
const pinia = createPinia();
setActivePinia(pinia);
const connectionStore = useConnectionStore();
vi.spyOn(connectionStore, "ensureConnected").mockResolvedValue(undefined);
const host = document.createElement("div");
document.body.append(host);
const app = createApp({
render: () =>
h(ObjectSourceDialog, {
open: true,
connectionId: "jdbc-1",
database: "catalog1",
schema: "APP",
name: "calculate_total",
objectType: "FUNCTION",
databaseType: "jdbc",
dialect: "mysql",
}),
});
app.use(pinia);
app.use(createI18n({ legacy: false, locale: "en", messages: { en: {} }, missingWarn: false, fallbackWarn: false }));
app.mount(host);
mountedApps.push({ app, host });
return host;
}
describe("ObjectSourceDialog generic JDBC routine metadata", () => {
it("renders a source-less function as read-only structured metadata", async () => {
mocks.getObjectSource.mockResolvedValue({
name: "calculate_total",
object_type: "FUNCTION",
schema: "APP",
source: "",
editable: false,
routine_parameters: [
{ name: "result", mode: "OUT", jdbc_type: 12, type_name: "VARCHAR", length: 32, nullable: true, ordinal: 2 },
{ name: "RETURN", mode: "RETURN", jdbc_type: 3, type_name: "DECIMAL", precision: 12, scale: 2, ordinal: 0 },
{ name: "amount", mode: "IN", jdbc_type: 3, type_name: "DECIMAL", precision: 10, scale: 2, nullable: false, ordinal: 1 },
],
});
mocks.buildEditableObjectSource.mockResolvedValue("");
await mountDialog();
await vi.waitFor(() => expect(document.querySelectorAll("[data-routine-parameter]")).toHaveLength(2));
expect(document.querySelector("[data-routine-return-type]")?.textContent).toContain("DECIMAL(12,2)");
const rows = [...document.querySelectorAll("[data-routine-parameter]")];
expect(rows[0].textContent).toContain("amount");
expect(rows[0].textContent).toContain("DECIMAL(10,2)");
expect(rows[1].textContent).toContain("VARCHAR(32)");
expect(document.querySelector("[data-query-editor-stub]")).toBeNull();
expect(document.body.textContent).not.toContain("Object source is not supported");
expect(mocks.getObjectSource).toHaveBeenCalledTimes(1);
expect([...document.querySelectorAll("button")].some((button) => button.textContent?.trim() === "contextMenu.editView")).toBe(false);
});
it("keeps a legacy source payload without the optional field on the existing preview path", async () => {
mocks.getObjectSource.mockResolvedValue({
name: "calculate_total",
object_type: "FUNCTION",
schema: "APP",
source: "CREATE FUNCTION calculate_total() RETURNS INTEGER RETURN 1",
editable: false,
});
mocks.buildEditableObjectSource.mockResolvedValue("CREATE FUNCTION calculate_total() RETURNS INTEGER RETURN 1");
await mountDialog();
await vi.waitFor(() => expect(document.querySelector("[data-query-editor-stub]")).not.toBeNull());
expect(document.querySelector("[data-routine-metadata]")).toBeNull();
expect(document.querySelector("[data-query-editor-stub]")?.textContent).toContain("CREATE FUNCTION");
});
});
@@ -50,4 +50,22 @@ describe("RoutineMetadataPanel", () => {
expect(host.querySelector("[data-routine-return-type]")?.textContent).toContain("INTEGER"); expect(host.querySelector("[data-routine-return-type]")?.textContent).toContain("INTEGER");
expect(host.querySelectorAll("[data-routine-parameter]")).toHaveLength(0); expect(host.querySelectorAll("[data-routine-parameter]")).toHaveLength(0);
}); });
it("renders known JDBC nullability without changing legacy parameter rows", () => {
const host = document.createElement("div");
document.body.append(host);
const app = createApp(RoutineMetadataPanel, {
parameters: [
{ name: "required_id", dataType: "BIGINT", mode: "IN", ordinal: 1, nullable: false },
{ name: "optional_note", dataType: "VARCHAR(64)", mode: "OUT", ordinal: 2, nullable: true },
{ name: "unknown", dataType: "OTHER", mode: "UNKNOWN", ordinal: 3, nullable: null },
],
});
app.use(i18n);
app.mount(host);
mountedApps.push({ app, host });
const nullability = [...host.querySelectorAll("[data-routine-nullable]")].map((cell) => cell.textContent?.trim());
expect(nullability).toEqual(["Not null", "Nullable", "-"]);
});
}); });
@@ -1,5 +1,6 @@
import { describe, expect, it, vi } from "vitest"; import { describe, expect, it, vi } from "vitest";
import { loadEditableObjectSourceForEditor, loadObjectSourceWithRoutineFallback } from "@/lib/table/objectSourceLoad"; import { loadEditableObjectSourceForEditor, loadObjectSourceWithRoutineFallback } from "@/lib/table/objectSourceLoad";
import { jdbcRoutineMetadata } from "@/lib/table/routineParameters";
import type { ObjectSource } from "@/types/database"; import type { ObjectSource } from "@/types/database";
function source(text: string): ObjectSource { function source(text: string): ObjectSource {
@@ -26,6 +27,38 @@ describe("loadObjectSourceWithRoutineFallback", () => {
expect(getObjectSource).toHaveBeenCalledTimes(2); expect(getObjectSource).toHaveBeenCalledTimes(2);
expect(getObjectSource.mock.calls[1][4]).toBe("FUNCTION"); expect(getObjectSource.mock.calls[1][4]).toBe("FUNCTION");
}); });
it("keeps a source-less routine response when structured metadata is present", async () => {
const getObjectSource = vi.fn().mockResolvedValue({ ...source(""), editable: false, routine_parameters: [] });
const result = await loadObjectSourceWithRoutineFallback(getObjectSource, "c1", "catalog", "APP", "P1", "PROCEDURE");
expect(result.objectType).toBe("PROCEDURE");
expect(result.source.routine_parameters).toEqual([]);
expect(getObjectSource).toHaveBeenCalledTimes(1);
});
});
describe("jdbcRoutineMetadata", () => {
it("keeps legacy payloads optional and normalizes sorted JDBC display metadata", () => {
expect(jdbcRoutineMetadata(undefined)).toBeNull();
expect(
jdbcRoutineMetadata([
{ name: "p_note", mode: "OUT", jdbc_type: 12, type_name: "VARCHAR", length: 64, nullable: true, ordinal: 3 },
{ name: null, mode: "RETURN", jdbc_type: 3, type_name: "DECIMAL", precision: 12, scale: 3, ordinal: 0 },
{ name: "p_id", mode: "IN", jdbc_type: -5, type_name: "BIGINT", nullable: false, ordinal: 1 },
{ name: null, mode: "INOUT", jdbc_type: null, type_name: null, nullable: null, ordinal: 2 },
{ name: "p_unknown", mode: "UNKNOWN" },
]),
).toEqual({
returnType: "DECIMAL(12,3)",
parameters: [
{ name: "p_id", dataType: "BIGINT", mode: "IN", ordinal: 1, hasDefault: false, nullable: false },
{ name: "arg2", dataType: "UNKNOWN", mode: "INOUT", ordinal: 2, hasDefault: false, nullable: null },
{ name: "p_note", dataType: "VARCHAR(64)", mode: "OUT", ordinal: 3, hasDefault: false, nullable: true },
{ name: "p_unknown", dataType: "UNKNOWN", mode: "UNKNOWN", ordinal: 4, hasDefault: false, nullable: undefined },
],
});
});
}); });
describe("loadEditableObjectSourceForEditor", () => { describe("loadEditableObjectSourceForEditor", () => {
@@ -19,7 +19,7 @@ export async function loadObjectSourceWithRoutineFallback(
relationName?: string, relationName?: string,
): Promise<{ source: ObjectSource; objectType: ObjectSourceKind }> { ): Promise<{ source: ObjectSource; objectType: ObjectSourceKind }> {
const primary = await getObjectSource(connectionId, database, schema, name, objectType, signature, relationName); const primary = await getObjectSource(connectionId, database, schema, name, objectType, signature, relationName);
if (primary.source?.trim()) { if (primary.source?.trim() || primary.routine_parameters !== undefined) {
return { source: primary, objectType }; return { source: primary, objectType };
} }
@@ -28,7 +28,7 @@ export async function loadObjectSourceWithRoutineFallback(
for (const fallbackType of fallbacks) { for (const fallbackType of fallbacks) {
try { try {
const alternate = await getObjectSource(connectionId, database, schema, name, fallbackType, signature, relationName); const alternate = await getObjectSource(connectionId, database, schema, name, fallbackType, signature, relationName);
if (alternate.source?.trim()) { if (alternate.source?.trim() || alternate.routine_parameters !== undefined) {
return { source: alternate, objectType: fallbackType }; return { source: alternate, objectType: fallbackType };
} }
} catch { } catch {
@@ -17,6 +17,7 @@ export interface RoutineParameter {
ordinal: number; ordinal: number;
hasDefault?: boolean; hasDefault?: boolean;
defaultValue?: string | null; defaultValue?: string | null;
nullable?: boolean | null;
} }
export interface RoutineParameterValue extends RoutineParameter { export interface RoutineParameterValue extends RoutineParameter {
@@ -1,5 +1,5 @@
import * as api from "@/lib/backend/api"; import * as api from "@/lib/backend/api";
import type { DatabaseType, QueryResult } from "@/types/database"; import type { DatabaseType, QueryResult, RoutineParameterMetadata } from "@/types/database";
import type { RoutineParameter, RoutineParameterMode } from "@/lib/table/routineExecutionSql"; import type { RoutineParameter, RoutineParameterMode } from "@/lib/table/routineExecutionSql";
export interface LoadRoutineParametersOptions { export interface LoadRoutineParametersOptions {
@@ -142,12 +142,72 @@ ORDER BY SEQUENCE;`.trim();
return null; return null;
} }
export interface XuguRoutineMetadata { export interface RoutineMetadata {
kind?: "PROCEDURE" | "FUNCTION"; kind?: "PROCEDURE" | "FUNCTION";
parameters: RoutineParameter[]; parameters: RoutineParameter[];
returnType?: string; returnType?: string;
} }
export type XuguRoutineMetadata = RoutineMetadata;
/** Convert optional generic-JDBC wire metadata into the existing read-only panel model. */
export function jdbcRoutineMetadata(parameters: RoutineParameterMetadata[] | undefined): RoutineMetadata | null {
if (parameters === undefined) return null;
const ordered = parameters
.map((parameter, index) => ({ parameter, index }))
.sort((left, right) => routineMetadataOrdinal(left.parameter) - routineMetadataOrdinal(right.parameter) || left.index - right.index)
.map(({ parameter }) => parameter);
const returnParameter = ordered.find((parameter) => parameter.mode === "RETURN");
return {
parameters: ordered
.filter((parameter) => parameter.mode !== "RETURN")
.map((parameter, index) => ({
name: parameter.name?.trim() || `arg${positiveRoutineOrdinal(parameter.ordinal) ?? index + 1}`,
dataType: jdbcRoutineParameterType(parameter),
mode: parameter.mode,
ordinal: positiveRoutineOrdinal(parameter.ordinal) ?? index + 1,
hasDefault: false,
nullable: parameter.nullable,
})),
returnType: returnParameter ? jdbcRoutineParameterType(returnParameter) : undefined,
};
}
function routineMetadataOrdinal(parameter: RoutineParameterMetadata): number {
return typeof parameter.ordinal === "number" && Number.isFinite(parameter.ordinal) ? parameter.ordinal : Number.MAX_SAFE_INTEGER;
}
function positiveRoutineOrdinal(ordinal: number | null | undefined): number | undefined {
return typeof ordinal === "number" && Number.isFinite(ordinal) && ordinal > 0 ? ordinal : undefined;
}
function jdbcRoutineParameterType(parameter: RoutineParameterMetadata): string {
const typeName = parameter.type_name?.trim() || (typeof parameter.jdbc_type === "number" ? `JDBC ${parameter.jdbc_type}` : "UNKNOWN");
if (/\([^)]*\)\s*$/.test(typeName)) return typeName;
const jdbcType = parameter.jdbc_type;
const precision = positiveMetadataSize(parameter.precision);
const length = positiveMetadataSize(parameter.length);
const scale = typeof parameter.scale === "number" && Number.isFinite(parameter.scale) && parameter.scale >= 0 ? parameter.scale : undefined;
if (jdbcType === 2 || jdbcType === 3) {
if (precision === undefined) return typeName;
return scale === undefined ? `${typeName}(${precision})` : `${typeName}(${precision},${scale})`;
}
if (jdbcType === 92 || jdbcType === 93 || jdbcType === 2013 || jdbcType === 2014) {
return scale === undefined ? typeName : `${typeName}(${scale})`;
}
if (jdbcType === 1 || jdbcType === 12 || jdbcType === -1 || jdbcType === -15 || jdbcType === -9 || jdbcType === -16 || jdbcType === -2 || jdbcType === -3 || jdbcType === -4) {
const size = length ?? precision;
return size === undefined ? typeName : `${typeName}(${size})`;
}
return typeName;
}
function positiveMetadataSize(value: number | null | undefined): number | undefined {
return typeof value === "number" && Number.isFinite(value) && value > 0 ? value : undefined;
}
interface XuguRoutineToken { interface XuguRoutineToken {
kind: "word" | "quoted-identifier" | "string" | "symbol"; kind: "word" | "quoted-identifier" | "string" | "symbol";
text: string; text: string;
+16
View File
@@ -1024,12 +1024,28 @@ export interface ObjectStatistics {
export type ObjectSourceKind = "VIEW" | "MATERIALIZED_VIEW" | "PROCEDURE" | "FUNCTION" | "TRIGGER" | "EVENT" | "SEQUENCE" | "SYNONYM" | "JOB" | "PACKAGE" | "PACKAGE_BODY" | "TYPE" | "TYPE_BODY"; export type ObjectSourceKind = "VIEW" | "MATERIALIZED_VIEW" | "PROCEDURE" | "FUNCTION" | "TRIGGER" | "EVENT" | "SEQUENCE" | "SYNONYM" | "JOB" | "PACKAGE" | "PACKAGE_BODY" | "TYPE" | "TYPE_BODY";
export type RoutineParameterMetadataMode = "IN" | "OUT" | "INOUT" | "RETURN" | "UNKNOWN";
export interface RoutineParameterMetadata {
name?: string | null;
mode: RoutineParameterMetadataMode;
jdbc_type?: number | null;
type_name?: string | null;
precision?: number | null;
length?: number | null;
scale?: number | null;
nullable?: boolean | null;
ordinal?: number | null;
}
export interface ObjectSource { export interface ObjectSource {
name: string; name: string;
object_type: ObjectSourceKind; object_type: ObjectSourceKind;
schema?: string | null; schema?: string | null;
source: string; source: string;
editable?: boolean; editable?: boolean;
/** Optional structured metadata exposed by generic JDBC sidecars. */
routine_parameters?: RoutineParameterMetadata[];
} }
export interface MysqlEventInfo { export interface MysqlEventInfo {
+4
View File
@@ -8125,6 +8125,7 @@ async fn get_postgres_schema_object_sources_for_transfer(
schema: Some(schema.to_string()), schema: Some(schema.to_string()),
source, source,
editable: None, editable: None,
routine_parameters: None,
}); });
} }
for row in execute_on_pool(state, pool_key, &routines_sql).await?.rows { for row in execute_on_pool(state, pool_key, &routines_sql).await?.rows {
@@ -8144,6 +8145,7 @@ async fn get_postgres_schema_object_sources_for_transfer(
schema: Some(schema.to_string()), schema: Some(schema.to_string()),
source, source,
editable: None, editable: None,
routine_parameters: None,
}); });
} }
@@ -13545,6 +13547,7 @@ CREATE TABLE "Other"."prefix""Source"."NAME" ("ID" INT);"#;
schema: Some("public".into()), schema: Some("public".into()),
source: "SELECT 1".into(), source: "SELECT 1".into(),
editable: None, editable: None,
routine_parameters: None,
}, },
db::ObjectSource { db::ObjectSource {
name: "v2".into(), name: "v2".into(),
@@ -13552,6 +13555,7 @@ CREATE TABLE "Other"."prefix""Source"."NAME" ("ID" INT);"#;
schema: Some("public".into()), schema: Some("public".into()),
source: "SELECT 2".into(), source: "SELECT 2".into(),
editable: None, editable: None,
routine_parameters: None,
}, },
]; ];
let selection = let selection =
+4
View File
@@ -4480,6 +4480,7 @@ done
schema: None, schema: None,
source: "CREATE EVENT event_daily_sync ON SCHEDULE EVERY 1 DAY DO SELECT 1".to_string(), source: "CREATE EVENT event_daily_sync ON SCHEDULE EVERY 1 DAY DO SELECT 1".to_string(),
editable: None, editable: None,
routine_parameters: None,
}); });
assert_eq!(source.editable, Some(false)); assert_eq!(source.editable, Some(false));
@@ -10810,6 +10811,7 @@ async fn get_object_source_once(
schema: if schema.is_empty() { None } else { Some(schema.to_string()) }, schema: if schema.is_empty() { None } else { Some(schema.to_string()) },
source, source,
editable: None, editable: None,
routine_parameters: None,
}); });
} }
let result: db::ObjectSource = session let result: db::ObjectSource = session
@@ -10868,6 +10870,7 @@ async fn get_object_source_once(
schema: if schema.is_empty() { None } else { Some(schema.to_string()) }, schema: if schema.is_empty() { None } else { Some(schema.to_string()) },
source, source,
editable: None, editable: None,
routine_parameters: None,
}); });
} }
None => String::new(), None => String::new(),
@@ -10993,6 +10996,7 @@ async fn get_object_source_once(
schema: if schema.is_empty() { None } else { Some(schema.to_string()) }, schema: if schema.is_empty() { None } else { Some(schema.to_string()) },
source, source,
editable, editable,
routine_parameters: None,
}) })
} }
@@ -292,7 +292,14 @@ pub async fn object_source(
) )
.await?, .await?,
)?; )?;
Ok(ObjectSource { name: name.to_string(), object_type: object_type.clone(), schema: None, source, editable: None }) Ok(ObjectSource {
name: name.to_string(),
object_type: object_type.clone(),
schema: None,
source,
editable: None,
routine_parameters: None,
})
} }
pub async fn execute_query_with_max_rows( pub async fn execute_query_with_max_rows(
+8 -1
View File
@@ -286,7 +286,14 @@ pub async fn object_source(
) )
.await?, .await?,
)?; )?;
Ok(ObjectSource { name: name.to_string(), object_type: object_type.clone(), schema: None, source, editable: None }) Ok(ObjectSource {
name: name.to_string(),
object_type: object_type.clone(),
schema: None,
source,
editable: None,
routine_parameters: None,
})
} }
pub async fn execute_query(client: &RqliteClient, sql: &str) -> Result<QueryResult, String> { pub async fn execute_query(client: &RqliteClient, sql: &str) -> Result<QueryResult, String> {
+8 -1
View File
@@ -328,7 +328,14 @@ pub async fn object_source(
) )
.await?, .await?,
)?; )?;
Ok(ObjectSource { name: name.to_string(), object_type: object_type.clone(), schema: None, source, editable: None }) Ok(ObjectSource {
name: name.to_string(),
object_type: object_type.clone(),
schema: None,
source,
editable: None,
routine_parameters: None,
})
} }
pub async fn execute_query(client: &TursoClient, sql: &str) -> Result<QueryResult, String> { pub async fn execute_query(client: &TursoClient, sql: &str) -> Result<QueryResult, String> {
+75 -1
View File
@@ -222,6 +222,37 @@ pub enum ObjectSourceKind {
TypeBody, TypeBody,
} }
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
pub enum RoutineParameterMode {
In,
Out,
Inout,
Return,
Unknown,
}
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
pub struct RoutineParameterMetadata {
#[serde(default, skip_serializing_if = "Option::is_none")]
pub name: Option<String>,
pub mode: RoutineParameterMode,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub jdbc_type: Option<i32>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub type_name: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub precision: Option<i32>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub length: Option<i32>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub scale: Option<i32>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub nullable: Option<bool>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub ordinal: Option<i32>,
}
#[derive(Debug, Clone, Serialize, Deserialize)] #[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ObjectSource { pub struct ObjectSource {
pub name: String, pub name: String,
@@ -230,6 +261,8 @@ pub struct ObjectSource {
pub source: String, pub source: String,
#[serde(default, skip_serializing_if = "Option::is_none")] #[serde(default, skip_serializing_if = "Option::is_none")]
pub editable: Option<bool>, pub editable: Option<bool>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub routine_parameters: Option<Vec<RoutineParameterMetadata>>,
} }
/// Provenance for structured metadata fields that are optional in [`ColumnInfo`]. /// Provenance for structured metadata fields that are optional in [`ColumnInfo`].
@@ -1078,7 +1111,8 @@ pub struct CustomTypeDetails {
mod tests { mod tests {
use super::{ use super::{
is_opaque_aggregate_state_type, CompletionAssistantCandidate, CompletionAssistantCandidateKind, ObjectInfo, is_opaque_aggregate_state_type, CompletionAssistantCandidate, CompletionAssistantCandidateKind, ObjectInfo,
ObjectSourceKind, QueryMessage, SpatialColumn, SpatialColumnBuilder, TableInfo, ObjectSource, ObjectSourceKind, QueryMessage, RoutineParameterMode, SpatialColumn, SpatialColumnBuilder,
TableInfo,
}; };
#[test] #[test]
@@ -1277,6 +1311,46 @@ mod tests {
assert_eq!(serde_json::to_string(&kind).unwrap(), "\"JOB\""); assert_eq!(serde_json::to_string(&kind).unwrap(), "\"JOB\"");
} }
#[test]
fn object_source_accepts_legacy_payload_without_routine_parameters() {
let source: ObjectSource = serde_json::from_value(serde_json::json!({
"name": "legacy_proc",
"object_type": "PROCEDURE",
"schema": "APP",
"source": "CREATE PROCEDURE legacy_proc() BEGIN END"
}))
.unwrap();
assert!(source.routine_parameters.is_none());
assert!(serde_json::to_value(source).unwrap().get("routine_parameters").is_none());
}
#[test]
fn object_source_preserves_optional_jdbc_routine_parameters() {
let source: ObjectSource = serde_json::from_value(serde_json::json!({
"name": "calculate_total",
"object_type": "FUNCTION",
"schema": "APP",
"source": "",
"editable": false,
"routine_parameters": [{
"name": "RETURN",
"mode": "RETURN",
"jdbc_type": 3,
"type_name": "DECIMAL",
"precision": 12,
"scale": 2,
"ordinal": 0
}]
}))
.unwrap();
let parameters = source.routine_parameters.as_ref().unwrap();
assert_eq!(parameters[0].mode, RoutineParameterMode::Return);
assert_eq!(parameters[0].precision, Some(12));
assert_eq!(serde_json::to_value(source).unwrap()["routine_parameters"][0]["mode"], "RETURN");
}
#[test] #[test]
fn completion_candidate_kind_accepts_uppercase_agent_wire_values() { fn completion_candidate_kind_accepts_uppercase_agent_wire_values() {
for (wire_value, expected) in [ for (wire_value, expected) in [
@@ -4374,9 +4374,158 @@ public final class DbxJdbcPlugin {
return genericTableObjectSource(connection, database, schema, name); return genericTableObjectSource(connection, database, schema, name);
} }
String normalizedType = normalizeObjectType(objectType);
if (!isSybaseConnection(connection) && ("PROCEDURE".equals(normalizedType) || "FUNCTION".equals(normalizedType))) {
return genericRoutineObjectSource(connection, conn, database, schema, name, normalizedType);
}
throw new SQLException("Object source is not supported by this JDBC driver"); throw new SQLException("Object source is not supported by this JDBC driver");
} }
/**
* Generic JDBC does not define a routine DDL API. Return the structured
* parameter metadata that it does define and leave source empty/read-only.
* Drivers are allowed to omit or reject this optional metadata; that must
* not turn opening an already-listed routine into a fatal error.
*/
private static JsonNode genericRoutineObjectSource(
JsonNode connection,
Connection conn,
String database,
String schema,
String name,
String objectType
) {
ObjectNode item = MAPPER.createObjectNode();
item.put("name", name);
item.put("object_type", objectType);
putNullable(item, "schema", emptyToNull(schema));
item.put("source", "");
item.put("editable", false);
try {
DatabaseMetaData meta = conn.getMetaData();
JdbcDriverQuirks quirks = driverQuirks(connection);
String catalog = metadataCatalog(database, quirks);
String schemaPattern = escapeJdbcMetadataPattern(meta, resolveSchemaPattern(meta, database, schema, quirks));
String routineName = escapeJdbcMetadataPattern(meta, stripRoutineSignature(name));
ResultSet columns = "PROCEDURE".equals(objectType)
? meta.getProcedureColumns(catalog, schemaPattern, routineName, "%")
: meta.getFunctionColumns(catalog, schemaPattern, routineName, "%");
if (columns == null) {
return item;
}
try (columns) {
List<ObjectNode> parameters = new ArrayList<>();
while (columns.next()) {
parameters.add(genericRoutineParameter(columns, "PROCEDURE".equals(objectType)));
}
parameters.sort((left, right) -> {
JsonNode leftOrdinal = left.get("ordinal");
JsonNode rightOrdinal = right.get("ordinal");
int leftValue = leftOrdinal == null ? Integer.MAX_VALUE : leftOrdinal.asInt();
int rightValue = rightOrdinal == null ? Integer.MAX_VALUE : rightOrdinal.asInt();
return Integer.compare(leftValue, rightValue);
});
ArrayNode result = MAPPER.createArrayNode();
result.addAll(parameters);
item.set("routine_parameters", result);
}
} catch (SQLException | AbstractMethodError | UnsupportedOperationException ignored) {
// Parameter metadata is optional. The empty read-only source still
// lets the details dialog open when a driver does not implement it.
}
return item;
}
private static ObjectNode genericRoutineParameter(ResultSet columns, boolean procedure) {
ObjectNode parameter = MAPPER.createObjectNode();
Integer columnType = metadataInteger(columns, "COLUMN_TYPE");
String mode = routineParameterMode(columnType, procedure);
String name = metadataString(columns, "COLUMN_NAME");
if ((name == null || name.isBlank()) && "RETURN".equals(mode)) {
name = "RETURN";
}
putNullable(parameter, "name", name);
parameter.put("mode", mode);
putOptionalInt(parameter, "jdbc_type", metadataInteger(columns, "DATA_TYPE"));
putNullable(parameter, "type_name", metadataString(columns, "TYPE_NAME"));
putOptionalInt(parameter, "precision", metadataInteger(columns, "PRECISION"));
putOptionalInt(parameter, "length", metadataInteger(columns, "LENGTH"));
putOptionalInt(parameter, "scale", metadataInteger(columns, "SCALE"));
Integer nullable = metadataInteger(columns, "NULLABLE");
if (nullable != null && nullable != DatabaseMetaData.procedureNullableUnknown) {
parameter.put("nullable", nullable != DatabaseMetaData.procedureNoNulls);
}
putOptionalInt(parameter, "ordinal", metadataInteger(columns, "ORDINAL_POSITION"));
return parameter;
}
private static String routineParameterMode(Integer columnType, boolean procedure) {
if (columnType == null) {
return "UNKNOWN";
}
if (procedure) {
return switch (columnType) {
case DatabaseMetaData.procedureColumnIn -> "IN";
case DatabaseMetaData.procedureColumnInOut -> "INOUT";
case DatabaseMetaData.procedureColumnOut -> "OUT";
case DatabaseMetaData.procedureColumnReturn -> "RETURN";
default -> "UNKNOWN";
};
}
return switch (columnType) {
case DatabaseMetaData.functionColumnIn -> "IN";
case DatabaseMetaData.functionColumnInOut -> "INOUT";
case DatabaseMetaData.functionColumnOut -> "OUT";
case DatabaseMetaData.functionReturn -> "RETURN";
default -> "UNKNOWN";
};
}
private static String metadataString(ResultSet result, String column) {
try {
return result.getString(column);
} catch (SQLException | AbstractMethodError | UnsupportedOperationException ignored) {
return null;
}
}
private static Integer metadataInteger(ResultSet result, String column) {
try {
Object value = result.getObject(column);
if (value instanceof Number number) {
return number.intValue();
}
if (value instanceof String text && !text.isBlank()) {
return Integer.valueOf(text.trim());
}
} catch (SQLException | AbstractMethodError | UnsupportedOperationException | NumberFormatException ignored) {
}
return null;
}
private static String escapeJdbcMetadataPattern(DatabaseMetaData meta, String value) {
if (value == null) {
return null;
}
try {
String escape = meta.getSearchStringEscape();
if (escape == null || escape.isEmpty()) {
return value;
}
return value.replace(escape, escape + escape).replace("%", escape + "%").replace("_", escape + "_");
} catch (SQLException | AbstractMethodError | UnsupportedOperationException ignored) {
return value;
}
}
private static void putOptionalInt(ObjectNode node, String field, Integer value) {
if (value != null) {
node.put(field, value);
}
}
private static JsonNode sybaseViewObjectSource( private static JsonNode sybaseViewObjectSource(
JsonNode connection, JsonNode connection,
Connection conn, Connection conn,
@@ -4682,6 +4682,122 @@ final class DbxJdbcPluginTest {
return value == null ? "<null>" : String.valueOf(value); return value == null ? "<null>" : String.valueOf(value);
} }
private static final class RoutineColumnsDriver implements Driver {
private final String urlPrefix;
private final List<String> calls;
private final boolean unsupported;
private RoutineColumnsDriver(String urlPrefix, List<String> calls, boolean unsupported) {
this.urlPrefix = urlPrefix;
this.calls = calls;
this.unsupported = unsupported;
}
@Override
public Connection connect(String url, Properties info) {
return acceptsURL(url) ? routineColumnsConnection(calls, unsupported) : null;
}
@Override
public boolean acceptsURL(String url) {
return url != null && url.startsWith(urlPrefix);
}
@Override
public DriverPropertyInfo[] getPropertyInfo(String url, Properties info) {
return new DriverPropertyInfo[0];
}
@Override
public int getMajorVersion() {
return 1;
}
@Override
public int getMinorVersion() {
return 0;
}
@Override
public boolean jdbcCompliant() {
return false;
}
@Override
public java.util.logging.Logger getParentLogger() {
return java.util.logging.Logger.getGlobal();
}
}
private static Connection routineColumnsConnection(List<String> calls, boolean unsupported) {
DatabaseMetaData metadata = (DatabaseMetaData) Proxy.newProxyInstance(
DbxJdbcPluginTest.class.getClassLoader(),
new Class<?>[] { DatabaseMetaData.class },
(proxy, method, args) -> {
if ("getSearchStringEscape".equals(method.getName())) {
return "\\";
}
if ("getProcedureColumns".equals(method.getName())) {
calls.add("getProcedureColumns:" + metadataArgument(args[0]) + ":" + metadataArgument(args[1])
+ ":" + metadataArgument(args[2]) + ":" + metadataArgument(args[3]));
if (unsupported) {
throw new SQLFeatureNotSupportedException("routine columns unavailable");
}
return rowsResultSet(
new String[] {
"COLUMN_NAME", "COLUMN_TYPE", "DATA_TYPE", "TYPE_NAME", "LENGTH",
"NULLABLE", "SCALE", "PRECISION", "ORDINAL_POSITION"
},
new Object[][] {
{ "p_out", DatabaseMetaData.procedureColumnOut, Types.VARCHAR, "VARCHAR", 80,
DatabaseMetaData.procedureNullable, null, null, 3 },
{ null, DatabaseMetaData.procedureColumnReturn, Types.INTEGER, "INTEGER", 4,
DatabaseMetaData.procedureNullableUnknown, 0, 10, 0 },
{ "p_id", DatabaseMetaData.procedureColumnIn, Types.BIGINT, "BIGINT", 8,
DatabaseMetaData.procedureNoNulls, 0, 19, 1 },
{ null, DatabaseMetaData.procedureColumnInOut, Types.DECIMAL, "DECIMAL", 16,
DatabaseMetaData.procedureNullable, 3, 12, 2 },
{ "p_mystery", null, null, null, null, null, null, null, null }
}
);
}
if ("getFunctionColumns".equals(method.getName())) {
calls.add("getFunctionColumns:" + metadataArgument(args[0]) + ":" + metadataArgument(args[1])
+ ":" + metadataArgument(args[2]) + ":" + metadataArgument(args[3]));
if (unsupported) {
throw new SQLFeatureNotSupportedException("routine columns unavailable");
}
return rowsResultSet(
new String[] {
"COLUMN_NAME", "COLUMN_TYPE", "DATA_TYPE", "TYPE_NAME", "LENGTH",
"NULLABLE", "SCALE", "PRECISION", "ORDINAL_POSITION"
},
new Object[][] {
{ "answer", DatabaseMetaData.functionColumnOut, Types.INTEGER, "INTEGER", 4,
DatabaseMetaData.functionNullable, 0, 10, 2 },
{ null, DatabaseMetaData.functionReturn, Types.NUMERIC, "NUMERIC", 16,
DatabaseMetaData.functionNullableUnknown, 2, 15, 0 },
{ "value", DatabaseMetaData.functionColumnIn, Types.INTEGER, "INTEGER", 4,
DatabaseMetaData.functionNoNulls, 0, 10, 1 }
}
);
}
return defaultValue(method.getReturnType());
}
);
return (Connection) Proxy.newProxyInstance(
DbxJdbcPluginTest.class.getClassLoader(),
new Class<?>[] { Connection.class },
(proxy, method, args) -> switch (method.getName()) {
case "getMetaData" -> metadata;
case "isClosed" -> false;
case "isValid" -> true;
case "close", "setCatalog", "setSchema" -> null;
default -> defaultValue(method.getReturnType());
}
);
}
private static void closeAndDeregister(String connection, Driver driver) throws Exception { private static void closeAndDeregister(String connection, Driver driver) throws Exception {
try { try {
request("close", """ request("close", """
@@ -5725,6 +5841,147 @@ final class DbxJdbcPluginTest {
""".formatted(targetUrl)); """.formatted(targetUrl));
} }
@Test
void getObjectSourceReturnsSortedProcedureMetadataWithoutInventingSource() throws Exception {
List<String> calls = new ArrayList<>();
String url = "jdbc:dbx-routine-columns-procedure:";
Driver driver = new RoutineColumnsDriver(url, calls, false);
DriverManager.registerDriver(driver);
String connection = """
{ "connection_string": "%sdemo" }
""".formatted(url);
try {
JsonNode response = request("getObjectSource", """
{
"connection": %s,
"database": "catalog1",
"schema": "APP",
"name": "process_order",
"object_type": "PROCEDURE"
}
""".formatted(connection));
assertFalse(response.has("error"), response.toString());
JsonNode result = response.path("result");
assertEquals("", result.path("source").asText());
assertFalse(result.path("editable").asBoolean(true));
assertEquals(List.of("getProcedureColumns:catalog1:APP:process\\_order:%"), calls);
JsonNode parameters = result.path("routine_parameters");
assertEquals(5, parameters.size());
assertEquals("RETURN", parameters.path(0).path("name").asText());
assertEquals("RETURN", parameters.path(0).path("mode").asText());
assertEquals(0, parameters.path(0).path("ordinal").asInt());
assertFalse(parameters.path(0).has("nullable"));
assertEquals("p_id", parameters.path(1).path("name").asText());
assertEquals("IN", parameters.path(1).path("mode").asText());
assertEquals(Types.BIGINT, parameters.path(1).path("jdbc_type").asInt());
assertEquals(19, parameters.path(1).path("precision").asInt());
assertFalse(parameters.path(1).path("nullable").asBoolean(true));
assertTrue(parameters.path(2).path("name").isNull());
assertEquals("INOUT", parameters.path(2).path("mode").asText());
assertEquals(3, parameters.path(2).path("scale").asInt());
assertTrue(parameters.path(2).path("nullable").asBoolean());
assertEquals("OUT", parameters.path(3).path("mode").asText());
assertEquals(80, parameters.path(3).path("length").asInt());
assertEquals("UNKNOWN", parameters.path(4).path("mode").asText());
assertFalse(parameters.path(4).has("ordinal"));
assertFalse(parameters.path(4).has("jdbc_type"));
} finally {
closeAndDeregister(connection, driver);
}
}
@Test
void getObjectSourceUsesFunctionColumnConstants() throws Exception {
List<String> calls = new ArrayList<>();
String url = "jdbc:dbx-routine-columns-function:";
Driver driver = new RoutineColumnsDriver(url, calls, false);
DriverManager.registerDriver(driver);
String connection = """
{ "connection_string": "%sdemo" }
""".formatted(url);
try {
JsonNode response = request("getObjectSource", """
{
"connection": %s,
"database": "catalog1",
"schema": "APP",
"name": "calculate_total",
"object_type": "FUNCTION"
}
""".formatted(connection));
assertFalse(response.has("error"), response.toString());
assertEquals(List.of("getFunctionColumns:catalog1:APP:calculate\\_total:%"), calls);
JsonNode parameters = response.path("result").path("routine_parameters");
assertEquals("RETURN", parameters.path(0).path("mode").asText());
assertEquals("IN", parameters.path(1).path("mode").asText());
assertEquals("OUT", parameters.path(2).path("mode").asText());
} finally {
closeAndDeregister(connection, driver);
}
}
@Test
void getObjectSourceKeepsRoutineDetailsAvailableWhenColumnMetadataIsUnsupported() throws Exception {
List<String> calls = new ArrayList<>();
String url = "jdbc:dbx-routine-columns-unsupported:";
Driver driver = new RoutineColumnsDriver(url, calls, true);
DriverManager.registerDriver(driver);
String connection = """
{ "connection_string": "%sdemo" }
""".formatted(url);
try {
JsonNode response = request("getObjectSource", """
{
"connection": %s,
"database": "catalog1",
"schema": "APP",
"name": "legacy_proc",
"object_type": "PROCEDURE"
}
""".formatted(connection));
assertFalse(response.has("error"), response.toString());
assertEquals("", response.path("result").path("source").asText());
assertFalse(response.path("result").path("editable").asBoolean(true));
assertFalse(response.path("result").has("routine_parameters"));
assertEquals(List.of("getProcedureColumns:catalog1:APP:legacy\\_proc:%"), calls);
} finally {
closeAndDeregister(connection, driver);
}
}
@Test
void getObjectSourceKeepsSybaseRoutineBehaviorUnchanged() throws Exception {
List<String> calls = new ArrayList<>();
String url = "jdbc:sybase:Tds:sybase-routine-unsupported-test:5000";
Driver driver = new SybaseViewSourceDriver(url, calls);
DriverManager.registerDriver(driver);
String connection = """
{ "connection_string": "%s" }
""".formatted(url);
try {
JsonNode response = request("getObjectSource", """
{
"connection": %s,
"database": "appdb",
"schema": "dbo",
"name": "legacy_proc",
"object_type": "PROCEDURE"
}
""".formatted(connection));
assertEquals(
"Object source is not supported by this JDBC driver",
response.path("error").path("message").asText()
);
assertTrue(calls.isEmpty());
} finally {
closeAndDeregister(connection, driver);
}
}
@Test @Test
void getObjectSourceKeepsUnsupportedObjectTypesOnPlainJdbcDrivers() throws Exception { void getObjectSourceKeepsUnsupportedObjectTypesOnPlainJdbcDrivers() throws Exception {
JsonNode response = request("getObjectSource", """ JsonNode response = request("getObjectSource", """