Merge branch 'main' of https://github.com/Abeautifulsnow/dbx into feat/ai-agent-loop-phase1
This commit is contained in:
commit
84a9fd6a0f
34 files changed
+953
-31
No files matched your search
Generated
+2
-2
@@ -1841,7 +1841,7 @@ dependencies = [
|
|||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "dbx"
|
name = "dbx"
|
||||||
version = "0.5.31"
|
version = "0.5.32"
|
||||||
dependencies = [
|
dependencies = [
|
||||||
"anyhow",
|
"anyhow",
|
||||||
"base64 0.22.1",
|
"base64 0.22.1",
|
||||||
@@ -1935,7 +1935,7 @@ dependencies = [
|
|||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "dbx-web"
|
name = "dbx-web"
|
||||||
version = "0.5.31"
|
version = "0.5.32"
|
||||||
dependencies = [
|
dependencies = [
|
||||||
"aes-gcm 0.10.3",
|
"aes-gcm 0.10.3",
|
||||||
"argon2",
|
"argon2",
|
||||||
|
|||||||
@@ -21,12 +21,24 @@ import { useToast } from "@/composables/useToast";
|
|||||||
import { type SqlHighlighter, createShikiSqlHighlighter } from "@/lib/sqlHighlighter";
|
import { type SqlHighlighter, createShikiSqlHighlighter } from "@/lib/sqlHighlighter";
|
||||||
import { copyToClipboard } from "@/lib/clipboard";
|
import { copyToClipboard } from "@/lib/clipboard";
|
||||||
import { queryTimeoutSecsForConnection } from "@/lib/queryTimeout";
|
import { queryTimeoutSecsForConnection } from "@/lib/queryTimeout";
|
||||||
import { type EditableStructureColumn, type EditableStructureIndex } from "@/lib/tableStructureEditorSql";
|
import { type EditableStructureColumn, type EditableStructureForeignKey, type EditableStructureIndex, type EditableStructureTrigger } from "@/lib/tableStructureEditorSql";
|
||||||
import { getTableMetadataCapabilities } from "@/lib/tableMetadataCapabilities";
|
import { getTableMetadataCapabilities } from "@/lib/tableMetadataCapabilities";
|
||||||
import { getTableStructureCapabilities } from "@/lib/tableStructureCapabilities";
|
import { getTableStructureCapabilities } from "@/lib/tableStructureCapabilities";
|
||||||
import { connectionObjectTreeQuerySchema, effectiveDatabaseTypeForConnection } from "@/lib/jdbcDialect";
|
import { connectionObjectTreeQuerySchema, effectiveDatabaseTypeForConnection } from "@/lib/jdbcDialect";
|
||||||
import { buildStructureTargetLabel, combineDataTypeForDatabase, createColumnDrafts, createIndexDrafts, generateIndexName, generateUniqueIndexName, getDataTypeOptions, getDefaultLengthForType, splitDataType, toColumnNames } from "@/lib/tableStructureEditorState";
|
import {
|
||||||
import type { ForeignKeyInfo, TriggerInfo } from "@/types/database";
|
buildStructureTargetLabel,
|
||||||
|
combineDataTypeForDatabase,
|
||||||
|
createColumnDrafts,
|
||||||
|
createForeignKeyDrafts,
|
||||||
|
createIndexDrafts,
|
||||||
|
createTriggerDrafts,
|
||||||
|
generateIndexName,
|
||||||
|
generateUniqueIndexName,
|
||||||
|
getDataTypeOptions,
|
||||||
|
getDefaultLengthForType,
|
||||||
|
splitDataType,
|
||||||
|
toColumnNames,
|
||||||
|
} from "@/lib/tableStructureEditorState";
|
||||||
import * as api from "@/lib/api";
|
import * as api from "@/lib/api";
|
||||||
|
|
||||||
const { t } = useI18n();
|
const { t } = useI18n();
|
||||||
@@ -90,8 +102,8 @@ const columns = ref<EditableStructureColumn[]>([]);
|
|||||||
const indexes = ref<EditableStructureIndex[]>([]);
|
const indexes = ref<EditableStructureIndex[]>([]);
|
||||||
const pendingStatements = ref<string[]>([]);
|
const pendingStatements = ref<string[]>([]);
|
||||||
const warnings = ref<string[]>([]);
|
const warnings = ref<string[]>([]);
|
||||||
const foreignKeys = ref<ForeignKeyInfo[]>([]);
|
const foreignKeys = ref<EditableStructureForeignKey[]>([]);
|
||||||
const triggers = ref<TriggerInfo[]>([]);
|
const triggers = ref<EditableStructureTrigger[]>([]);
|
||||||
|
|
||||||
function isPlainModShortcut(event: KeyboardEvent, key: string): boolean {
|
function isPlainModShortcut(event: KeyboardEvent, key: string): boolean {
|
||||||
if (event.isComposing || event.altKey || event.shiftKey) return false;
|
if (event.isComposing || event.altKey || event.shiftKey) return false;
|
||||||
@@ -307,6 +319,9 @@ const colLabels = computed(() => {
|
|||||||
return labels;
|
return labels;
|
||||||
});
|
});
|
||||||
const indexColLabels = computed(() => [t("structureEditor.indexName"), t("structureEditor.indexColumns"), t("structureEditor.unique"), t("structureEditor.indexType"), t("structureEditor.includedColumns"), t("structureEditor.filter"), t("structureEditor.comment"), t("structureEditor.actions")]);
|
const indexColLabels = computed(() => [t("structureEditor.indexName"), t("structureEditor.indexColumns"), t("structureEditor.unique"), t("structureEditor.indexType"), t("structureEditor.includedColumns"), t("structureEditor.filter"), t("structureEditor.comment"), t("structureEditor.actions")]);
|
||||||
|
const foreignKeyActionOptions = ["", "CASCADE", "SET NULL", "RESTRICT", "NO ACTION"];
|
||||||
|
const triggerTimingOptions = ["BEFORE", "AFTER"];
|
||||||
|
const triggerEventOptions = ["INSERT", "UPDATE", "DELETE"];
|
||||||
const metadataSchema = computed(() => connectionObjectTreeQuerySchema(connection.value, props.database, props.schema));
|
const metadataSchema = computed(() => connectionObjectTreeQuerySchema(connection.value, props.database, props.schema));
|
||||||
const refreshVersion = computed(() => (props.connectionId && props.tableName ? queryStore.tableStructureRefreshVersion(props.connectionId, props.database, props.schema, props.tableName) : 0));
|
const refreshVersion = computed(() => (props.connectionId && props.tableName ? queryStore.tableStructureRefreshVersion(props.connectionId, props.database, props.schema, props.tableName) : 0));
|
||||||
const isCreateMode = computed(() => !props.tableName);
|
const isCreateMode = computed(() => !props.tableName);
|
||||||
@@ -327,6 +342,8 @@ async function refreshSqlPreview() {
|
|||||||
tableName: isCreateMode.value ? newTableName.value : props.tableName || "",
|
tableName: isCreateMode.value ? newTableName.value : props.tableName || "",
|
||||||
columns: columns.value,
|
columns: columns.value,
|
||||||
indexes: indexes.value,
|
indexes: indexes.value,
|
||||||
|
foreignKeys: foreignKeys.value,
|
||||||
|
triggers: triggers.value,
|
||||||
tableComment: tableComment.value,
|
tableComment: tableComment.value,
|
||||||
originalTableComment: isCreateMode.value ? undefined : originalTableComment.value,
|
originalTableComment: isCreateMode.value ? undefined : originalTableComment.value,
|
||||||
};
|
};
|
||||||
@@ -379,8 +396,8 @@ async function loadStructure(silent = false) {
|
|||||||
]);
|
]);
|
||||||
columns.value = createColumnDrafts(nextColumns, databaseType.value);
|
columns.value = createColumnDrafts(nextColumns, databaseType.value);
|
||||||
indexes.value = createIndexDrafts(nextIndexes);
|
indexes.value = createIndexDrafts(nextIndexes);
|
||||||
foreignKeys.value = nextForeignKeys;
|
foreignKeys.value = createForeignKeyDrafts(nextForeignKeys);
|
||||||
triggers.value = nextTriggers;
|
triggers.value = createTriggerDrafts(nextTriggers);
|
||||||
try {
|
try {
|
||||||
const tables = await api.listTables(props.connectionId, props.database, metadataSchema.value);
|
const tables = await api.listTables(props.connectionId, props.database, metadataSchema.value);
|
||||||
const table = tables.find((t) => t.name.toLowerCase() === props.tableName!.toLowerCase() && t.table_type !== "VIEW");
|
const table = tables.find((t) => t.name.toLowerCase() === props.tableName!.toLowerCase() && t.table_type !== "VIEW");
|
||||||
@@ -583,6 +600,80 @@ function canDropIndex(index: EditableStructureIndex): boolean {
|
|||||||
return !!index.original && !index.isPrimary && structureCapabilities.value.dropIndex;
|
return !!index.original && !index.isPrimary && structureCapabilities.value.dropIndex;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
const canEditMysqlForeignKeys = computed(() => structureDialect.value === "mysql");
|
||||||
|
const canEditMysqlTriggers = computed(() => structureDialect.value === "mysql");
|
||||||
|
|
||||||
|
function generatedForeignKeyName(column = ""): string {
|
||||||
|
const table = structureIndexTableName() || "table";
|
||||||
|
const suffix = column || "column";
|
||||||
|
const base = `fk_${table}_${suffix}`
|
||||||
|
.replace(/[^a-zA-Z0-9_]+/g, "_")
|
||||||
|
.replace(/_+/g, "_")
|
||||||
|
.replace(/^_+|_+$/g, "");
|
||||||
|
const taken = new Set(foreignKeys.value.map((item) => item.name.trim().toLowerCase()).filter(Boolean));
|
||||||
|
if (!taken.has(base.toLowerCase())) return base;
|
||||||
|
for (let counter = 2; counter < 10_000; counter++) {
|
||||||
|
const candidate = `${base}_${counter}`;
|
||||||
|
if (!taken.has(candidate.toLowerCase())) return candidate;
|
||||||
|
}
|
||||||
|
return base;
|
||||||
|
}
|
||||||
|
|
||||||
|
function addForeignKey() {
|
||||||
|
if (!canEditMysqlForeignKeys.value) return;
|
||||||
|
activeTab.value = "foreignKeys";
|
||||||
|
foreignKeys.value.push({
|
||||||
|
id: `new:${uuid()}`,
|
||||||
|
name: generatedForeignKeyName(),
|
||||||
|
column: "",
|
||||||
|
refSchema: "",
|
||||||
|
refTable: "",
|
||||||
|
refColumn: "",
|
||||||
|
onUpdate: "",
|
||||||
|
onDelete: "",
|
||||||
|
markedForDrop: false,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
function removeNewForeignKey(foreignKey: EditableStructureForeignKey) {
|
||||||
|
foreignKeys.value = foreignKeys.value.filter((item) => item.id !== foreignKey.id);
|
||||||
|
}
|
||||||
|
|
||||||
|
function toggleDropForeignKey(foreignKey: EditableStructureForeignKey) {
|
||||||
|
if (!foreignKey.original) return;
|
||||||
|
foreignKey.markedForDrop = !foreignKey.markedForDrop;
|
||||||
|
}
|
||||||
|
|
||||||
|
function canEditForeignKeyDraft(foreignKey: EditableStructureForeignKey): boolean {
|
||||||
|
return canEditMysqlForeignKeys.value && !foreignKey.markedForDrop;
|
||||||
|
}
|
||||||
|
|
||||||
|
function addTrigger() {
|
||||||
|
if (!canEditMysqlTriggers.value) return;
|
||||||
|
activeTab.value = "triggers";
|
||||||
|
triggers.value.push({
|
||||||
|
id: `new:${uuid()}`,
|
||||||
|
name: "",
|
||||||
|
timing: "BEFORE",
|
||||||
|
event: "INSERT",
|
||||||
|
statement: "BEGIN\n \nEND",
|
||||||
|
markedForDrop: false,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
function removeNewTrigger(trigger: EditableStructureTrigger) {
|
||||||
|
triggers.value = triggers.value.filter((item) => item.id !== trigger.id);
|
||||||
|
}
|
||||||
|
|
||||||
|
function toggleDropTrigger(trigger: EditableStructureTrigger) {
|
||||||
|
if (!trigger.original) return;
|
||||||
|
trigger.markedForDrop = !trigger.markedForDrop;
|
||||||
|
}
|
||||||
|
|
||||||
|
function canEditTriggerDraft(trigger: EditableStructureTrigger): boolean {
|
||||||
|
return canEditMysqlTriggers.value && !trigger.markedForDrop;
|
||||||
|
}
|
||||||
|
|
||||||
function primarySqlOperation(sql: string): string {
|
function primarySqlOperation(sql: string): string {
|
||||||
const statement = sql
|
const statement = sql
|
||||||
.split(";")
|
.split(";")
|
||||||
@@ -657,6 +748,14 @@ function addItemForActiveTab(): boolean {
|
|||||||
addIndex();
|
addIndex();
|
||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
|
if (activeTab.value === "foreignKeys" && canEditMysqlForeignKeys.value) {
|
||||||
|
addForeignKey();
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
if (activeTab.value === "triggers" && canEditMysqlTriggers.value) {
|
||||||
|
addTrigger();
|
||||||
|
return true;
|
||||||
|
}
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -721,7 +820,7 @@ watch(tableMetadataCapabilities, (capabilities) => {
|
|||||||
});
|
});
|
||||||
|
|
||||||
watch(
|
watch(
|
||||||
[isCreateMode, databaseType, () => props.schema, () => props.tableName, newTableName, tableComment, columns, indexes],
|
[isCreateMode, databaseType, () => props.schema, () => props.tableName, newTableName, tableComment, columns, indexes, foreignKeys, triggers],
|
||||||
() => {
|
() => {
|
||||||
void refreshSqlPreview();
|
void refreshSqlPreview();
|
||||||
},
|
},
|
||||||
@@ -812,6 +911,14 @@ watch(activeTab, (tab) => {
|
|||||||
<Plus :class="structureIconClass" />
|
<Plus :class="structureIconClass" />
|
||||||
{{ t("structureEditor.addIndex") }}
|
{{ t("structureEditor.addIndex") }}
|
||||||
</Button>
|
</Button>
|
||||||
|
<Button v-if="activeTab === 'foreignKeys'" size="sm" :class="structureToolbarButtonClass" :disabled="!canEditMysqlForeignKeys" @click="addForeignKey">
|
||||||
|
<Plus :class="structureIconClass" />
|
||||||
|
{{ t("structureEditor.addForeignKey") }}
|
||||||
|
</Button>
|
||||||
|
<Button v-if="activeTab === 'triggers'" size="sm" :class="structureToolbarButtonClass" :disabled="!canEditMysqlTriggers" @click="addTrigger">
|
||||||
|
<Plus :class="structureIconClass" />
|
||||||
|
{{ t("structureEditor.addTrigger") }}
|
||||||
|
</Button>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
@@ -1138,9 +1245,43 @@ watch(activeTab, (tab) => {
|
|||||||
{{ t("structureEditor.emptyReadonly") }}
|
{{ t("structureEditor.emptyReadonly") }}
|
||||||
</div>
|
</div>
|
||||||
<div v-else class="space-y-1.5">
|
<div v-else class="space-y-1.5">
|
||||||
<div v-for="fk in foreignKeys" :key="fk.name" class="rounded-md border px-[var(--structure-cell-px)] py-[var(--structure-header-py)] text-[length:var(--structure-font-size)]">
|
<div v-for="fk in foreignKeys" :key="fk.id" class="rounded-md border px-[var(--structure-cell-px)] py-[var(--structure-header-py)] text-[length:var(--structure-font-size)]" :class="fk.markedForDrop ? 'bg-destructive/5 opacity-60' : ''">
|
||||||
<div class="font-medium">{{ fk.name }}</div>
|
<div class="grid grid-cols-[minmax(110px,1fr)_minmax(110px,1fr)_minmax(110px,1fr)_minmax(90px,0.8fr)_minmax(90px,0.8fr)_auto] gap-1.5">
|
||||||
<div class="mt-1 font-mono text-muted-foreground">{{ fk.column }} -> {{ fk.ref_table }}.{{ fk.ref_column }}</div>
|
<Input v-model="fk.name" :class="structureControlClass" :placeholder="t('structureEditor.foreignKeyName')" :disabled="!canEditForeignKeyDraft(fk)" />
|
||||||
|
<Input v-model="fk.column" :class="structureControlClass" :placeholder="t('structureEditor.columnName')" :disabled="!canEditForeignKeyDraft(fk)" />
|
||||||
|
<Input v-model="fk.refTable" :class="structureControlClass" :placeholder="t('structureEditor.referencedTable')" :disabled="!canEditForeignKeyDraft(fk)" />
|
||||||
|
<Input v-model="fk.refColumn" :class="structureControlClass" :placeholder="t('structureEditor.referencedColumn')" :disabled="!canEditForeignKeyDraft(fk)" />
|
||||||
|
<Input v-model="fk.refSchema" :class="structureControlClass" :placeholder="t('structureEditor.referencedSchema')" :disabled="!canEditForeignKeyDraft(fk)" />
|
||||||
|
<div class="flex items-center justify-end gap-1">
|
||||||
|
<Button v-if="fk.original" variant="ghost" size="sm" :class="structureToolbarButtonClass" @click="toggleDropForeignKey(fk)">
|
||||||
|
<Trash2 :class="structureIconClass" />
|
||||||
|
{{ fk.markedForDrop ? t("structureEditor.restore") : t("structureEditor.drop") }}
|
||||||
|
</Button>
|
||||||
|
<Button v-else variant="ghost" size="sm" :class="structureToolbarButtonClass" @click="removeNewForeignKey(fk)">
|
||||||
|
<X :class="structureIconClass" />
|
||||||
|
{{ t("structureEditor.remove") }}
|
||||||
|
</Button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<div class="mt-1.5 grid grid-cols-[minmax(110px,0.5fr)_minmax(110px,0.5fr)_1fr] gap-1.5">
|
||||||
|
<Select :model-value="fk.onDelete || '__default'" :disabled="!canEditForeignKeyDraft(fk)" @update:model-value="(v: any) => (fk.onDelete = String(v === '__default' ? '' : (v ?? '')))">
|
||||||
|
<SelectTrigger class="h-[var(--structure-control-height)] rounded-md px-[var(--structure-control-px)] text-[length:var(--structure-font-size)]">
|
||||||
|
<SelectValue :placeholder="t('structureEditor.onDelete')" />
|
||||||
|
</SelectTrigger>
|
||||||
|
<SelectContent>
|
||||||
|
<SelectItem v-for="action in foreignKeyActionOptions" :key="`delete-${action || 'default'}`" :value="action || '__default'">{{ action || t("structureEditor.defaultAction") }}</SelectItem>
|
||||||
|
</SelectContent>
|
||||||
|
</Select>
|
||||||
|
<Select :model-value="fk.onUpdate || '__default'" :disabled="!canEditForeignKeyDraft(fk)" @update:model-value="(v: any) => (fk.onUpdate = String(v === '__default' ? '' : (v ?? '')))">
|
||||||
|
<SelectTrigger class="h-[var(--structure-control-height)] rounded-md px-[var(--structure-control-px)] text-[length:var(--structure-font-size)]">
|
||||||
|
<SelectValue :placeholder="t('structureEditor.onUpdate')" />
|
||||||
|
</SelectTrigger>
|
||||||
|
<SelectContent>
|
||||||
|
<SelectItem v-for="action in foreignKeyActionOptions" :key="`update-${action || 'default'}`" :value="action || '__default'">{{ action || t("structureEditor.defaultAction") }}</SelectItem>
|
||||||
|
</SelectContent>
|
||||||
|
</Select>
|
||||||
|
<div class="truncate font-mono text-muted-foreground">{{ fk.column }} -> {{ fk.refSchema ? `${fk.refSchema}.` : "" }}{{ fk.refTable }}.{{ fk.refColumn }}</div>
|
||||||
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</TabsContent>
|
</TabsContent>
|
||||||
@@ -1150,9 +1291,42 @@ watch(activeTab, (tab) => {
|
|||||||
{{ t("structureEditor.emptyReadonly") }}
|
{{ t("structureEditor.emptyReadonly") }}
|
||||||
</div>
|
</div>
|
||||||
<div v-else class="space-y-1.5">
|
<div v-else class="space-y-1.5">
|
||||||
<div v-for="trigger in triggers" :key="trigger.name" class="rounded-md border px-[var(--structure-cell-px)] py-[var(--structure-header-py)] text-[length:var(--structure-font-size)]">
|
<div v-for="trigger in triggers" :key="trigger.id" class="rounded-md border px-[var(--structure-cell-px)] py-[var(--structure-header-py)] text-[length:var(--structure-font-size)]" :class="trigger.markedForDrop ? 'bg-destructive/5 opacity-60' : ''">
|
||||||
<div class="font-medium">{{ trigger.name }}</div>
|
<div class="grid grid-cols-[minmax(140px,1fr)_110px_110px_auto] gap-1.5">
|
||||||
<div class="mt-1 font-mono text-muted-foreground">{{ trigger.timing }} {{ trigger.event }}</div>
|
<Input v-model="trigger.name" :class="structureControlClass" :placeholder="t('structureEditor.triggerName')" :disabled="!canEditTriggerDraft(trigger)" />
|
||||||
|
<Select v-model="trigger.timing" :disabled="!canEditTriggerDraft(trigger)">
|
||||||
|
<SelectTrigger class="h-[var(--structure-control-height)] rounded-md px-[var(--structure-control-px)] text-[length:var(--structure-font-size)]">
|
||||||
|
<SelectValue />
|
||||||
|
</SelectTrigger>
|
||||||
|
<SelectContent>
|
||||||
|
<SelectItem v-for="timing in triggerTimingOptions" :key="timing" :value="timing">{{ timing }}</SelectItem>
|
||||||
|
</SelectContent>
|
||||||
|
</Select>
|
||||||
|
<Select v-model="trigger.event" :disabled="!canEditTriggerDraft(trigger)">
|
||||||
|
<SelectTrigger class="h-[var(--structure-control-height)] rounded-md px-[var(--structure-control-px)] text-[length:var(--structure-font-size)]">
|
||||||
|
<SelectValue />
|
||||||
|
</SelectTrigger>
|
||||||
|
<SelectContent>
|
||||||
|
<SelectItem v-for="event in triggerEventOptions" :key="event" :value="event">{{ event }}</SelectItem>
|
||||||
|
</SelectContent>
|
||||||
|
</Select>
|
||||||
|
<div class="flex items-center justify-end gap-1">
|
||||||
|
<Button v-if="trigger.original" variant="ghost" size="sm" :class="structureToolbarButtonClass" @click="toggleDropTrigger(trigger)">
|
||||||
|
<Trash2 :class="structureIconClass" />
|
||||||
|
{{ trigger.markedForDrop ? t("structureEditor.restore") : t("structureEditor.drop") }}
|
||||||
|
</Button>
|
||||||
|
<Button v-else variant="ghost" size="sm" :class="structureToolbarButtonClass" @click="removeNewTrigger(trigger)">
|
||||||
|
<X :class="structureIconClass" />
|
||||||
|
{{ t("structureEditor.remove") }}
|
||||||
|
</Button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<textarea
|
||||||
|
v-model="trigger.statement"
|
||||||
|
class="mt-1.5 min-h-28 w-full resize-y rounded-md border bg-background px-[var(--structure-control-px)] py-[var(--structure-cell-py)] font-mono text-[length:var(--structure-font-size)] leading-5 outline-none focus-visible:ring-2 focus-visible:ring-ring/40 disabled:cursor-not-allowed disabled:opacity-50"
|
||||||
|
:placeholder="t('structureEditor.triggerStatement')"
|
||||||
|
:disabled="!canEditTriggerDraft(trigger)"
|
||||||
|
/>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</TabsContent>
|
</TabsContent>
|
||||||
|
|||||||
@@ -1291,6 +1291,8 @@
|
|||||||
ddl: "DDL",
|
ddl: "DDL",
|
||||||
addColumn: "Add Column",
|
addColumn: "Add Column",
|
||||||
addIndex: "Add Index",
|
addIndex: "Add Index",
|
||||||
|
addForeignKey: "Add Foreign Key",
|
||||||
|
addTrigger: "Add Trigger",
|
||||||
columnName: "Column",
|
columnName: "Column",
|
||||||
dataType: "Type",
|
dataType: "Type",
|
||||||
typePlaceholder: "Select or type...",
|
typePlaceholder: "Select or type...",
|
||||||
@@ -1313,6 +1315,15 @@
|
|||||||
includedColumns: "Included",
|
includedColumns: "Included",
|
||||||
includedColumnsPlaceholder: "Select columns...",
|
includedColumnsPlaceholder: "Select columns...",
|
||||||
filter: "Filter",
|
filter: "Filter",
|
||||||
|
foreignKeyName: "Foreign key",
|
||||||
|
referencedSchema: "Ref schema",
|
||||||
|
referencedTable: "Ref table",
|
||||||
|
referencedColumn: "Ref column",
|
||||||
|
onDelete: "On delete",
|
||||||
|
onUpdate: "On update",
|
||||||
|
defaultAction: "Default",
|
||||||
|
triggerName: "Trigger",
|
||||||
|
triggerStatement: "Trigger statement",
|
||||||
primary: "Primary",
|
primary: "Primary",
|
||||||
drop: "Drop",
|
drop: "Drop",
|
||||||
restore: "Restore",
|
restore: "Restore",
|
||||||
|
|||||||
@@ -1200,6 +1200,8 @@
|
|||||||
ddl: "DDL",
|
ddl: "DDL",
|
||||||
addColumn: "Adicionar coluna",
|
addColumn: "Adicionar coluna",
|
||||||
addIndex: "Adicionar índice",
|
addIndex: "Adicionar índice",
|
||||||
|
addForeignKey: "Adicionar chave estrangeira",
|
||||||
|
addTrigger: "Adicionar trigger",
|
||||||
columnName: "Coluna",
|
columnName: "Coluna",
|
||||||
dataType: "Tipo",
|
dataType: "Tipo",
|
||||||
typePlaceholder: "Selecione ou digite...",
|
typePlaceholder: "Selecione ou digite...",
|
||||||
@@ -1222,6 +1224,15 @@
|
|||||||
includedColumns: "Incluídas",
|
includedColumns: "Incluídas",
|
||||||
includedColumnsPlaceholder: "Selecione as colunas...",
|
includedColumnsPlaceholder: "Selecione as colunas...",
|
||||||
filter: "Filtro",
|
filter: "Filtro",
|
||||||
|
foreignKeyName: "Chave estrangeira",
|
||||||
|
referencedSchema: "Schema ref.",
|
||||||
|
referencedTable: "Tabela ref.",
|
||||||
|
referencedColumn: "Coluna ref.",
|
||||||
|
onDelete: "Ao excluir",
|
||||||
|
onUpdate: "Ao atualizar",
|
||||||
|
defaultAction: "Padrão",
|
||||||
|
triggerName: "Trigger",
|
||||||
|
triggerStatement: "Comando do trigger",
|
||||||
primary: "Primária",
|
primary: "Primária",
|
||||||
drop: "Remover",
|
drop: "Remover",
|
||||||
restore: "Restaurar",
|
restore: "Restaurar",
|
||||||
|
|||||||
@@ -1290,6 +1290,8 @@
|
|||||||
ddl: "DDL",
|
ddl: "DDL",
|
||||||
addColumn: "新增字段",
|
addColumn: "新增字段",
|
||||||
addIndex: "新增索引",
|
addIndex: "新增索引",
|
||||||
|
addForeignKey: "新增外键",
|
||||||
|
addTrigger: "新增触发器",
|
||||||
columnName: "字段名",
|
columnName: "字段名",
|
||||||
dataType: "类型",
|
dataType: "类型",
|
||||||
length: "长度",
|
length: "长度",
|
||||||
@@ -1312,6 +1314,15 @@
|
|||||||
includedColumns: "包含列",
|
includedColumns: "包含列",
|
||||||
includedColumnsPlaceholder: "选择列...",
|
includedColumnsPlaceholder: "选择列...",
|
||||||
filter: "过滤条件",
|
filter: "过滤条件",
|
||||||
|
foreignKeyName: "外键名",
|
||||||
|
referencedSchema: "引用库",
|
||||||
|
referencedTable: "引用表",
|
||||||
|
referencedColumn: "引用字段",
|
||||||
|
onDelete: "删除时",
|
||||||
|
onUpdate: "更新时",
|
||||||
|
defaultAction: "默认",
|
||||||
|
triggerName: "触发器名",
|
||||||
|
triggerStatement: "触发语句",
|
||||||
primary: "主键",
|
primary: "主键",
|
||||||
drop: "删除",
|
drop: "删除",
|
||||||
restore: "恢复",
|
restore: "恢复",
|
||||||
|
|||||||
@@ -1179,6 +1179,8 @@
|
|||||||
ddl: "DDL",
|
ddl: "DDL",
|
||||||
addColumn: "新增欄位",
|
addColumn: "新增欄位",
|
||||||
addIndex: "新增索引",
|
addIndex: "新增索引",
|
||||||
|
addForeignKey: "新增外鍵",
|
||||||
|
addTrigger: "新增觸發器",
|
||||||
columnName: "欄位",
|
columnName: "欄位",
|
||||||
dataType: "類型",
|
dataType: "類型",
|
||||||
length: "長度",
|
length: "長度",
|
||||||
@@ -1201,6 +1203,15 @@
|
|||||||
includedColumns: "包含",
|
includedColumns: "包含",
|
||||||
includedColumnsPlaceholder: "選擇欄位……",
|
includedColumnsPlaceholder: "選擇欄位……",
|
||||||
filter: "過濾條件",
|
filter: "過濾條件",
|
||||||
|
foreignKeyName: "外鍵名稱",
|
||||||
|
referencedSchema: "引用資料庫",
|
||||||
|
referencedTable: "引用資料表",
|
||||||
|
referencedColumn: "引用欄位",
|
||||||
|
onDelete: "刪除時",
|
||||||
|
onUpdate: "更新時",
|
||||||
|
defaultAction: "預設",
|
||||||
|
triggerName: "觸發器名稱",
|
||||||
|
triggerStatement: "觸發語句",
|
||||||
primary: "主鍵",
|
primary: "主鍵",
|
||||||
drop: "刪除",
|
drop: "刪除",
|
||||||
restore: "復原",
|
restore: "復原",
|
||||||
|
|||||||
@@ -1,4 +1,4 @@
|
|||||||
import type { ColumnInfo, DatabaseType, IndexInfo } from "../types/database.ts";
|
import type { ColumnInfo, DatabaseType, ForeignKeyInfo, IndexInfo, TriggerInfo } from "../types/database.ts";
|
||||||
|
|
||||||
export interface ColumnIdentity {
|
export interface ColumnIdentity {
|
||||||
generation?: "BY DEFAULT" | "ALWAYS";
|
generation?: "BY DEFAULT" | "ALWAYS";
|
||||||
@@ -41,12 +41,37 @@ export interface EditableStructureIndex {
|
|||||||
markedForDrop: boolean;
|
markedForDrop: boolean;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
export interface EditableStructureForeignKey {
|
||||||
|
id: string;
|
||||||
|
name: string;
|
||||||
|
column: string;
|
||||||
|
refSchema: string;
|
||||||
|
refTable: string;
|
||||||
|
refColumn: string;
|
||||||
|
onUpdate: string;
|
||||||
|
onDelete: string;
|
||||||
|
original?: ForeignKeyInfo;
|
||||||
|
markedForDrop: boolean;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface EditableStructureTrigger {
|
||||||
|
id: string;
|
||||||
|
name: string;
|
||||||
|
timing: string;
|
||||||
|
event: string;
|
||||||
|
statement: string;
|
||||||
|
original?: TriggerInfo;
|
||||||
|
markedForDrop: boolean;
|
||||||
|
}
|
||||||
|
|
||||||
export interface BuildTableStructureChangeSqlOptions {
|
export interface BuildTableStructureChangeSqlOptions {
|
||||||
databaseType?: DatabaseType;
|
databaseType?: DatabaseType;
|
||||||
schema?: string;
|
schema?: string;
|
||||||
tableName: string;
|
tableName: string;
|
||||||
columns: EditableStructureColumn[];
|
columns: EditableStructureColumn[];
|
||||||
indexes: EditableStructureIndex[];
|
indexes: EditableStructureIndex[];
|
||||||
|
foreignKeys?: EditableStructureForeignKey[];
|
||||||
|
triggers?: EditableStructureTrigger[];
|
||||||
tableComment?: string;
|
tableComment?: string;
|
||||||
originalTableComment?: string;
|
originalTableComment?: string;
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,5 +1,5 @@
|
|||||||
import type { ColumnInfo, DatabaseType, IndexInfo } from "../types/database.ts";
|
import type { ColumnInfo, DatabaseType, ForeignKeyInfo, IndexInfo, TriggerInfo } from "../types/database.ts";
|
||||||
import type { ColumnExtra, EditableStructureColumn, EditableStructureIndex } from "./tableStructureEditorSql.ts";
|
import type { ColumnExtra, EditableStructureColumn, EditableStructureForeignKey, EditableStructureIndex, EditableStructureTrigger } from "./tableStructureEditorSql.ts";
|
||||||
|
|
||||||
export const DATA_TYPE_OPTIONS: Record<string, string[]> = {
|
export const DATA_TYPE_OPTIONS: Record<string, string[]> = {
|
||||||
mysql: [
|
mysql: [
|
||||||
@@ -370,6 +370,47 @@ export function createIndexDrafts(indexes: IndexInfo[]): EditableStructureIndex[
|
|||||||
}));
|
}));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
export function createForeignKeyDrafts(foreignKeys: ForeignKeyInfo[]): EditableStructureForeignKey[] {
|
||||||
|
const groups = new Map<string, ForeignKeyInfo[]>();
|
||||||
|
for (const foreignKey of foreignKeys) {
|
||||||
|
const key = [foreignKey.name, foreignKey.ref_schema ?? "", foreignKey.ref_table, foreignKey.on_update ?? "", foreignKey.on_delete ?? ""].join("\u0000");
|
||||||
|
groups.set(key, [...(groups.get(key) ?? []), foreignKey]);
|
||||||
|
}
|
||||||
|
|
||||||
|
return [...groups.values()].map((group, index) => {
|
||||||
|
const first = group[0]!;
|
||||||
|
const original = {
|
||||||
|
...first,
|
||||||
|
column: group.map((foreignKey) => foreignKey.column).join(", "),
|
||||||
|
ref_column: group.map((foreignKey) => foreignKey.ref_column).join(", "),
|
||||||
|
};
|
||||||
|
return {
|
||||||
|
id: `existing:${first.name}:${index}`,
|
||||||
|
name: first.name,
|
||||||
|
column: original.column,
|
||||||
|
refSchema: first.ref_schema ?? "",
|
||||||
|
refTable: first.ref_table,
|
||||||
|
refColumn: original.ref_column,
|
||||||
|
onUpdate: first.on_update ?? "",
|
||||||
|
onDelete: first.on_delete ?? "",
|
||||||
|
original,
|
||||||
|
markedForDrop: false,
|
||||||
|
};
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
export function createTriggerDrafts(triggers: TriggerInfo[]): EditableStructureTrigger[] {
|
||||||
|
return triggers.map((trigger) => ({
|
||||||
|
id: `existing:${trigger.name}`,
|
||||||
|
name: trigger.name,
|
||||||
|
timing: trigger.timing,
|
||||||
|
event: trigger.event,
|
||||||
|
statement: trigger.statement ?? "",
|
||||||
|
original: trigger,
|
||||||
|
markedForDrop: false,
|
||||||
|
}));
|
||||||
|
}
|
||||||
|
|
||||||
export function toColumnNames(columns: string[]): string {
|
export function toColumnNames(columns: string[]): string {
|
||||||
return columns.join(", ");
|
return columns.join(", ");
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -259,12 +259,15 @@ export interface ForeignKeyInfo {
|
|||||||
ref_schema?: string | null;
|
ref_schema?: string | null;
|
||||||
ref_table: string;
|
ref_table: string;
|
||||||
ref_column: string;
|
ref_column: string;
|
||||||
|
on_update?: string | null;
|
||||||
|
on_delete?: string | null;
|
||||||
}
|
}
|
||||||
|
|
||||||
export interface TriggerInfo {
|
export interface TriggerInfo {
|
||||||
name: string;
|
name: string;
|
||||||
event: string;
|
event: string;
|
||||||
timing: string;
|
timing: string;
|
||||||
|
statement?: string | null;
|
||||||
}
|
}
|
||||||
|
|
||||||
export interface QueryResult {
|
export interface QueryResult {
|
||||||
|
|||||||
@@ -324,7 +324,10 @@ impl AppState {
|
|||||||
|
|
||||||
let conns = self.connections.read().await;
|
let conns = self.connections.read().await;
|
||||||
if conns.contains_key(&pool_key) {
|
if conns.contains_key(&pool_key) {
|
||||||
return Ok(pool_key);
|
drop(conns);
|
||||||
|
if !self.remove_stale_connection_pool(&pool_key).await {
|
||||||
|
return Ok(pool_key);
|
||||||
|
}
|
||||||
} else {
|
} else {
|
||||||
drop(conns);
|
drop(conns);
|
||||||
}
|
}
|
||||||
@@ -675,6 +678,49 @@ impl AppState {
|
|||||||
Ok(("127.0.0.1".to_string(), local_port))
|
Ok(("127.0.0.1".to_string(), local_port))
|
||||||
}
|
}
|
||||||
|
|
||||||
|
async fn remove_stale_connection_pool(&self, pool_key: &str) -> bool {
|
||||||
|
let stale = {
|
||||||
|
let connections = self.connections.read().await;
|
||||||
|
let Some(pool) = connections.get(pool_key) else {
|
||||||
|
return false;
|
||||||
|
};
|
||||||
|
match pool {
|
||||||
|
PoolKind::SqlServer(client) => {
|
||||||
|
let client = client.clone();
|
||||||
|
drop(connections);
|
||||||
|
let mut client = client.lock().await;
|
||||||
|
match db::sqlserver::test_connection(&mut client).await {
|
||||||
|
Ok(()) => false,
|
||||||
|
Err(err) => {
|
||||||
|
log::warn!("SQL Server connection pool '{pool_key}' is stale: {err}");
|
||||||
|
true
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
PoolKind::Redis(redis) => match db::redis_driver::test_connection(redis).await {
|
||||||
|
Ok(()) => false,
|
||||||
|
Err(err) => {
|
||||||
|
log::warn!("Redis connection pool '{pool_key}' is stale: {err}");
|
||||||
|
true
|
||||||
|
}
|
||||||
|
},
|
||||||
|
_ => false,
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
if !stale {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
let removed = self.connections.write().await.remove(pool_key);
|
||||||
|
if let Some(pool) = removed {
|
||||||
|
close_pool_kind(pool).await;
|
||||||
|
true
|
||||||
|
} else {
|
||||||
|
false
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
pub async fn reconnect_pool(&self, connection_id: &str, database: Option<&str>) -> Result<String, String> {
|
pub async fn reconnect_pool(&self, connection_id: &str, database: Option<&str>) -> Result<String, String> {
|
||||||
self.reconnect_pool_for_session(connection_id, database, None).await
|
self.reconnect_pool_for_session(connection_id, database, None).await
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1717,8 +1717,13 @@ pub async fn list_indexes(pool: &MySqlPool, database: &str, table: &str) -> Resu
|
|||||||
pub async fn list_foreign_keys(pool: &MySqlPool, database: &str, table: &str) -> Result<Vec<ForeignKeyInfo>, String> {
|
pub async fn list_foreign_keys(pool: &MySqlPool, database: &str, table: &str) -> Result<Vec<ForeignKeyInfo>, String> {
|
||||||
let sql = format!(
|
let sql = format!(
|
||||||
"SELECT kcu.CONSTRAINT_NAME, kcu.COLUMN_NAME, \
|
"SELECT kcu.CONSTRAINT_NAME, kcu.COLUMN_NAME, \
|
||||||
kcu.REFERENCED_TABLE_SCHEMA, kcu.REFERENCED_TABLE_NAME, kcu.REFERENCED_COLUMN_NAME \
|
kcu.REFERENCED_TABLE_SCHEMA, kcu.REFERENCED_TABLE_NAME, kcu.REFERENCED_COLUMN_NAME, \
|
||||||
|
rc.UPDATE_RULE, rc.DELETE_RULE \
|
||||||
FROM information_schema.KEY_COLUMN_USAGE kcu \
|
FROM information_schema.KEY_COLUMN_USAGE kcu \
|
||||||
|
LEFT JOIN information_schema.REFERENTIAL_CONSTRAINTS rc \
|
||||||
|
ON rc.CONSTRAINT_SCHEMA = kcu.CONSTRAINT_SCHEMA \
|
||||||
|
AND rc.CONSTRAINT_NAME = kcu.CONSTRAINT_NAME \
|
||||||
|
AND rc.TABLE_NAME = kcu.TABLE_NAME \
|
||||||
WHERE kcu.TABLE_SCHEMA = {} AND kcu.TABLE_NAME = {} \
|
WHERE kcu.TABLE_SCHEMA = {} AND kcu.TABLE_NAME = {} \
|
||||||
AND kcu.REFERENCED_TABLE_NAME IS NOT NULL \
|
AND kcu.REFERENCED_TABLE_NAME IS NOT NULL \
|
||||||
ORDER BY kcu.CONSTRAINT_NAME, kcu.ORDINAL_POSITION",
|
ORDER BY kcu.CONSTRAINT_NAME, kcu.ORDINAL_POSITION",
|
||||||
@@ -1737,13 +1742,15 @@ pub async fn list_foreign_keys(pool: &MySqlPool, database: &str, table: &str) ->
|
|||||||
ref_schema: Some(get_str_by_name(row, "REFERENCED_TABLE_SCHEMA")),
|
ref_schema: Some(get_str_by_name(row, "REFERENCED_TABLE_SCHEMA")),
|
||||||
ref_table: get_str_by_name(row, "REFERENCED_TABLE_NAME"),
|
ref_table: get_str_by_name(row, "REFERENCED_TABLE_NAME"),
|
||||||
ref_column: get_str_by_name(row, "REFERENCED_COLUMN_NAME"),
|
ref_column: get_str_by_name(row, "REFERENCED_COLUMN_NAME"),
|
||||||
|
on_update: Some(get_str_by_name(row, "UPDATE_RULE")).filter(|value| !value.is_empty()),
|
||||||
|
on_delete: Some(get_str_by_name(row, "DELETE_RULE")).filter(|value| !value.is_empty()),
|
||||||
})
|
})
|
||||||
.collect())
|
.collect())
|
||||||
}
|
}
|
||||||
|
|
||||||
pub async fn list_triggers(pool: &MySqlPool, database: &str, table: &str) -> Result<Vec<TriggerInfo>, String> {
|
pub async fn list_triggers(pool: &MySqlPool, database: &str, table: &str) -> Result<Vec<TriggerInfo>, String> {
|
||||||
let sql = format!(
|
let sql = format!(
|
||||||
"SELECT TRIGGER_NAME, EVENT_MANIPULATION, ACTION_TIMING \
|
"SELECT TRIGGER_NAME, EVENT_MANIPULATION, ACTION_TIMING, ACTION_STATEMENT \
|
||||||
FROM information_schema.TRIGGERS \
|
FROM information_schema.TRIGGERS \
|
||||||
WHERE TRIGGER_SCHEMA = {} AND EVENT_OBJECT_TABLE = {} \
|
WHERE TRIGGER_SCHEMA = {} AND EVENT_OBJECT_TABLE = {} \
|
||||||
ORDER BY TRIGGER_NAME",
|
ORDER BY TRIGGER_NAME",
|
||||||
@@ -1760,6 +1767,7 @@ pub async fn list_triggers(pool: &MySqlPool, database: &str, table: &str) -> Res
|
|||||||
name: get_str_by_name(row, "TRIGGER_NAME"),
|
name: get_str_by_name(row, "TRIGGER_NAME"),
|
||||||
event: get_str_by_name(row, "EVENT_MANIPULATION"),
|
event: get_str_by_name(row, "EVENT_MANIPULATION"),
|
||||||
timing: get_str_by_name(row, "ACTION_TIMING"),
|
timing: get_str_by_name(row, "ACTION_TIMING"),
|
||||||
|
statement: Some(get_str_by_name(row, "ACTION_STATEMENT")).filter(|value| !value.is_empty()),
|
||||||
})
|
})
|
||||||
.collect())
|
.collect())
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -237,6 +237,8 @@ pub async fn list_foreign_keys(
|
|||||||
ref_schema: Some(get_str(row, 2)),
|
ref_schema: Some(get_str(row, 2)),
|
||||||
ref_table: get_str(row, 3),
|
ref_table: get_str(row, 3),
|
||||||
ref_column: get_str(row, 4),
|
ref_column: get_str(row, 4),
|
||||||
|
on_update: None,
|
||||||
|
on_delete: None,
|
||||||
})
|
})
|
||||||
.collect())
|
.collect())
|
||||||
}
|
}
|
||||||
@@ -265,7 +267,7 @@ pub async fn list_triggers(pool: &mysql_async::Pool, schema: &str, table: &str)
|
|||||||
} else {
|
} else {
|
||||||
"INSTEAD OF"
|
"INSTEAD OF"
|
||||||
};
|
};
|
||||||
TriggerInfo { name: get_str(row, 0), event: get_str(row, 1), timing: timing.to_string() }
|
TriggerInfo { name: get_str(row, 0), event: get_str(row, 1), timing: timing.to_string(), statement: None }
|
||||||
})
|
})
|
||||||
.collect())
|
.collect())
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1803,6 +1803,8 @@ pub async fn list_foreign_keys(pool: &Pool, schema: &str, table: &str) -> Result
|
|||||||
ref_schema: Some(row.get::<_, String>(2)),
|
ref_schema: Some(row.get::<_, String>(2)),
|
||||||
ref_table: row.get::<_, String>(3),
|
ref_table: row.get::<_, String>(3),
|
||||||
ref_column: row.get::<_, String>(4),
|
ref_column: row.get::<_, String>(4),
|
||||||
|
on_update: None,
|
||||||
|
on_delete: None,
|
||||||
})
|
})
|
||||||
.collect())
|
.collect())
|
||||||
}
|
}
|
||||||
@@ -1826,6 +1828,7 @@ pub async fn list_triggers(pool: &Pool, schema: &str, table: &str) -> Result<Vec
|
|||||||
name: row.get::<_, String>(0),
|
name: row.get::<_, String>(0),
|
||||||
event: row.get::<_, String>(1),
|
event: row.get::<_, String>(1),
|
||||||
timing: row.get::<_, String>(2),
|
timing: row.get::<_, String>(2),
|
||||||
|
statement: None,
|
||||||
})
|
})
|
||||||
.collect())
|
.collect())
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -237,6 +237,30 @@ pub async fn connect_cluster(config: &ConnectionConfig) -> Result<RedisClusterPo
|
|||||||
Err(last_error.unwrap_or_else(|| "Redis cluster connection failed".to_string()))
|
Err(last_error.unwrap_or_else(|| "Redis cluster connection failed".to_string()))
|
||||||
}
|
}
|
||||||
|
|
||||||
|
pub async fn test_connection(connection: &RedisConnection) -> Result<(), String> {
|
||||||
|
match connection {
|
||||||
|
RedisConnection::Direct(con) => {
|
||||||
|
let mut con = con.lock().await;
|
||||||
|
redis_ping(&mut *con, "Redis").await
|
||||||
|
}
|
||||||
|
RedisConnection::Cluster(cluster) => {
|
||||||
|
let mut con = cluster.connection.lock().await;
|
||||||
|
redis_ping(&mut *con, "Redis cluster").await
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn redis_ping<C>(con: &mut C, label: &str) -> Result<(), String>
|
||||||
|
where
|
||||||
|
C: ConnectionLike + Send + Sync + Unpin,
|
||||||
|
{
|
||||||
|
tokio::time::timeout(super::connection_timeout(), redis::cmd("PING").query_async::<String>(con))
|
||||||
|
.await
|
||||||
|
.map_err(|_| format!("{label} ping timed out ({}s)", super::CONNECTION_TIMEOUT_SECS))?
|
||||||
|
.map(|_| ())
|
||||||
|
.map_err(|e| format!("{label} ping failed: {e}"))
|
||||||
|
}
|
||||||
|
|
||||||
fn redis_sentinel_nodes(config: &ConnectionConfig) -> Result<Vec<ConnectionInfo>, String> {
|
fn redis_sentinel_nodes(config: &ConnectionConfig) -> Result<Vec<ConnectionInfo>, String> {
|
||||||
let raw_nodes = config.redis_sentinel_nodes.trim();
|
let raw_nodes = config.redis_sentinel_nodes.trim();
|
||||||
let endpoints: Vec<String> = if raw_nodes.is_empty() {
|
let endpoints: Vec<String> = if raw_nodes.is_empty() {
|
||||||
|
|||||||
@@ -198,6 +198,8 @@ pub async fn list_foreign_keys(
|
|||||||
ref_schema: None,
|
ref_schema: None,
|
||||||
ref_table: value_by_column(&result.columns, &row, "table").unwrap_or_default(),
|
ref_table: value_by_column(&result.columns, &row, "table").unwrap_or_default(),
|
||||||
ref_column: value_by_column(&result.columns, &row, "to").unwrap_or_default(),
|
ref_column: value_by_column(&result.columns, &row, "to").unwrap_or_default(),
|
||||||
|
on_update: None,
|
||||||
|
on_delete: None,
|
||||||
})
|
})
|
||||||
.collect())
|
.collect())
|
||||||
}
|
}
|
||||||
@@ -234,6 +236,7 @@ pub async fn list_triggers(client: &RqliteClient, _schema: &str, table: &str) ->
|
|||||||
name: value_as_string(row.first()).unwrap_or_default(),
|
name: value_as_string(row.first()).unwrap_or_default(),
|
||||||
event: event.to_string(),
|
event: event.to_string(),
|
||||||
timing: timing.to_string(),
|
timing: timing.to_string(),
|
||||||
|
statement: value_as_string(row.get(1)),
|
||||||
}
|
}
|
||||||
})
|
})
|
||||||
.collect())
|
.collect())
|
||||||
|
|||||||
@@ -455,6 +455,8 @@ pub async fn list_foreign_keys(pool: &SqliteHandle, _schema: &str, table: &str)
|
|||||||
ref_schema: None,
|
ref_schema: None,
|
||||||
ref_table: row.get("table")?,
|
ref_table: row.get("table")?,
|
||||||
ref_column: row.get("to")?,
|
ref_column: row.get("to")?,
|
||||||
|
on_update: None,
|
||||||
|
on_delete: None,
|
||||||
})
|
})
|
||||||
})
|
})
|
||||||
.map_err(|e| e.to_string())?;
|
.map_err(|e| e.to_string())?;
|
||||||
@@ -476,7 +478,7 @@ pub async fn list_triggers(pool: &SqliteHandle, _schema: &str, table: &str) -> R
|
|||||||
let rows = stmt
|
let rows = stmt
|
||||||
.query_map([table], |row| {
|
.query_map([table], |row| {
|
||||||
let sql_text: Option<String> = row.get("sql")?;
|
let sql_text: Option<String> = row.get("sql")?;
|
||||||
let upper = sql_text.unwrap_or_default().to_uppercase();
|
let upper = sql_text.clone().unwrap_or_default().to_uppercase();
|
||||||
let timing = if upper.contains("BEFORE") {
|
let timing = if upper.contains("BEFORE") {
|
||||||
"BEFORE"
|
"BEFORE"
|
||||||
} else if upper.contains("AFTER") {
|
} else if upper.contains("AFTER") {
|
||||||
@@ -491,7 +493,12 @@ pub async fn list_triggers(pool: &SqliteHandle, _schema: &str, table: &str) -> R
|
|||||||
} else {
|
} else {
|
||||||
"DELETE"
|
"DELETE"
|
||||||
};
|
};
|
||||||
Ok(TriggerInfo { name: row.get("name")?, event: event.to_string(), timing: timing.to_string() })
|
Ok(TriggerInfo {
|
||||||
|
name: row.get("name")?,
|
||||||
|
event: event.to_string(),
|
||||||
|
timing: timing.to_string(),
|
||||||
|
statement: sql_text,
|
||||||
|
})
|
||||||
})
|
})
|
||||||
.map_err(|e| e.to_string())?;
|
.map_err(|e| e.to_string())?;
|
||||||
rows.collect::<Result<Vec<_>, _>>().map_err(|e| e.to_string())
|
rows.collect::<Result<Vec<_>, _>>().map_err(|e| e.to_string())
|
||||||
|
|||||||
@@ -601,6 +601,12 @@ pub async fn list_databases(client: &mut SqlServerClient) -> Result<Vec<Database
|
|||||||
Ok(rows.iter().map(|row| DatabaseInfo { name: row.get::<&str, _>(0).unwrap_or("").to_string() }).collect())
|
Ok(rows.iter().map(|row| DatabaseInfo { name: row.get::<&str, _>(0).unwrap_or("").to_string() }).collect())
|
||||||
}
|
}
|
||||||
|
|
||||||
|
pub async fn test_connection(client: &mut SqlServerClient) -> Result<(), String> {
|
||||||
|
let stream = client.simple_query("SELECT 1").await.map_err(|e| e.to_string())?;
|
||||||
|
let _ = stream.into_first_result().await.map_err(|e| e.to_string())?;
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
pub async fn list_schemas(client: &mut SqlServerClient) -> Result<Vec<String>, String> {
|
pub async fn list_schemas(client: &mut SqlServerClient) -> Result<Vec<String>, String> {
|
||||||
let stream = client
|
let stream = client
|
||||||
.query(
|
.query(
|
||||||
@@ -891,6 +897,8 @@ pub async fn list_foreign_keys(
|
|||||||
ref_schema: Some(row.get::<&str, _>(2).unwrap_or("").to_string()),
|
ref_schema: Some(row.get::<&str, _>(2).unwrap_or("").to_string()),
|
||||||
ref_table: row.get::<&str, _>(3).unwrap_or("").to_string(),
|
ref_table: row.get::<&str, _>(3).unwrap_or("").to_string(),
|
||||||
ref_column: row.get::<&str, _>(4).unwrap_or("").to_string(),
|
ref_column: row.get::<&str, _>(4).unwrap_or("").to_string(),
|
||||||
|
on_update: None,
|
||||||
|
on_delete: None,
|
||||||
})
|
})
|
||||||
.collect())
|
.collect())
|
||||||
}
|
}
|
||||||
@@ -940,6 +948,7 @@ pub async fn list_triggers(
|
|||||||
name: row.get::<&str, _>(0).unwrap_or("").to_string(),
|
name: row.get::<&str, _>(0).unwrap_or("").to_string(),
|
||||||
event: row.get::<&str, _>(1).unwrap_or("").to_string(),
|
event: row.get::<&str, _>(1).unwrap_or("").to_string(),
|
||||||
timing: row.get::<&str, _>(2).unwrap_or("AFTER").to_string(),
|
timing: row.get::<&str, _>(2).unwrap_or("AFTER").to_string(),
|
||||||
|
statement: None,
|
||||||
})
|
})
|
||||||
.collect())
|
.collect())
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -237,6 +237,8 @@ pub async fn list_foreign_keys(
|
|||||||
ref_schema: None,
|
ref_schema: None,
|
||||||
ref_table: value_by_column(&result.columns, &row, "table").unwrap_or_default(),
|
ref_table: value_by_column(&result.columns, &row, "table").unwrap_or_default(),
|
||||||
ref_column: value_by_column(&result.columns, &row, "to").unwrap_or_default(),
|
ref_column: value_by_column(&result.columns, &row, "to").unwrap_or_default(),
|
||||||
|
on_update: None,
|
||||||
|
on_delete: None,
|
||||||
})
|
})
|
||||||
.collect())
|
.collect())
|
||||||
}
|
}
|
||||||
@@ -273,6 +275,7 @@ pub async fn list_triggers(client: &TursoClient, _schema: &str, table: &str) ->
|
|||||||
name: value_as_string(row.first()).unwrap_or_default(),
|
name: value_as_string(row.first()).unwrap_or_default(),
|
||||||
event: event.to_string(),
|
event: event.to_string(),
|
||||||
timing: timing.to_string(),
|
timing: timing.to_string(),
|
||||||
|
statement: value_as_string(row.get(1)),
|
||||||
}
|
}
|
||||||
})
|
})
|
||||||
.collect())
|
.collect())
|
||||||
|
|||||||
@@ -3,10 +3,15 @@ use crate::db::redis_driver::{
|
|||||||
self, RedisCommandResult, RedisConnection, RedisDatabaseInfo, RedisScanResult, RedisValue,
|
self, RedisCommandResult, RedisConnection, RedisDatabaseInfo, RedisScanResult, RedisValue,
|
||||||
};
|
};
|
||||||
|
|
||||||
|
async fn ensure_redis_pool(state: &AppState, connection_id: &str) -> Result<(), String> {
|
||||||
|
state.get_or_create_pool(connection_id, None).await.map(|_| ())
|
||||||
|
}
|
||||||
|
|
||||||
pub async fn redis_list_databases_core(
|
pub async fn redis_list_databases_core(
|
||||||
state: &AppState,
|
state: &AppState,
|
||||||
connection_id: &str,
|
connection_id: &str,
|
||||||
) -> Result<Vec<RedisDatabaseInfo>, String> {
|
) -> Result<Vec<RedisDatabaseInfo>, String> {
|
||||||
|
ensure_redis_pool(state, connection_id).await?;
|
||||||
let connections = state.connections.read().await;
|
let connections = state.connections.read().await;
|
||||||
let pool = connections.get(connection_id).ok_or("Connection not found")?;
|
let pool = connections.get(connection_id).ok_or("Connection not found")?;
|
||||||
match pool {
|
match pool {
|
||||||
@@ -29,6 +34,7 @@ pub async fn redis_scan_keys_core(
|
|||||||
pattern: &str,
|
pattern: &str,
|
||||||
count: usize,
|
count: usize,
|
||||||
) -> Result<RedisScanResult, String> {
|
) -> Result<RedisScanResult, String> {
|
||||||
|
ensure_redis_pool(state, connection_id).await?;
|
||||||
let connections = state.connections.read().await;
|
let connections = state.connections.read().await;
|
||||||
let pool = connections.get(connection_id).ok_or("Connection not found")?;
|
let pool = connections.get(connection_id).ok_or("Connection not found")?;
|
||||||
match pool {
|
match pool {
|
||||||
@@ -57,6 +63,7 @@ pub async fn redis_scan_values_core(
|
|||||||
include_key_matches: bool,
|
include_key_matches: bool,
|
||||||
count: usize,
|
count: usize,
|
||||||
) -> Result<RedisScanResult, String> {
|
) -> Result<RedisScanResult, String> {
|
||||||
|
ensure_redis_pool(state, connection_id).await?;
|
||||||
let connections = state.connections.read().await;
|
let connections = state.connections.read().await;
|
||||||
let pool = connections.get(connection_id).ok_or("Connection not found")?;
|
let pool = connections.get(connection_id).ok_or("Connection not found")?;
|
||||||
match pool {
|
match pool {
|
||||||
@@ -86,6 +93,7 @@ pub async fn redis_get_value_in_db_core(
|
|||||||
db: u32,
|
db: u32,
|
||||||
key_raw: &str,
|
key_raw: &str,
|
||||||
) -> Result<RedisValue, String> {
|
) -> Result<RedisValue, String> {
|
||||||
|
ensure_redis_pool(state, connection_id).await?;
|
||||||
let connections = state.connections.read().await;
|
let connections = state.connections.read().await;
|
||||||
let pool = connections.get(connection_id).ok_or("Connection not found")?;
|
let pool = connections.get(connection_id).ok_or("Connection not found")?;
|
||||||
match pool {
|
match pool {
|
||||||
@@ -126,6 +134,7 @@ pub async fn redis_set_string_in_db_core(
|
|||||||
value: &str,
|
value: &str,
|
||||||
ttl: Option<i64>,
|
ttl: Option<i64>,
|
||||||
) -> Result<(), String> {
|
) -> Result<(), String> {
|
||||||
|
ensure_redis_pool(state, connection_id).await?;
|
||||||
let connections = state.connections.read().await;
|
let connections = state.connections.read().await;
|
||||||
let pool = connections.get(connection_id).ok_or("Connection not found")?;
|
let pool = connections.get(connection_id).ok_or("Connection not found")?;
|
||||||
match pool {
|
match pool {
|
||||||
@@ -158,6 +167,7 @@ pub async fn redis_delete_key_in_db_core(
|
|||||||
db: u32,
|
db: u32,
|
||||||
key_raw: &str,
|
key_raw: &str,
|
||||||
) -> Result<(), String> {
|
) -> Result<(), String> {
|
||||||
|
ensure_redis_pool(state, connection_id).await?;
|
||||||
let connections = state.connections.read().await;
|
let connections = state.connections.read().await;
|
||||||
let pool = connections.get(connection_id).ok_or("Connection not found")?;
|
let pool = connections.get(connection_id).ok_or("Connection not found")?;
|
||||||
match pool {
|
match pool {
|
||||||
@@ -200,6 +210,7 @@ pub async fn redis_hash_set_in_db_core(
|
|||||||
value: &str,
|
value: &str,
|
||||||
ttl: Option<i64>,
|
ttl: Option<i64>,
|
||||||
) -> Result<(), String> {
|
) -> Result<(), String> {
|
||||||
|
ensure_redis_pool(state, connection_id).await?;
|
||||||
let connections = state.connections.read().await;
|
let connections = state.connections.read().await;
|
||||||
match connections.get(connection_id).ok_or("Not found")? {
|
match connections.get(connection_id).ok_or("Not found")? {
|
||||||
PoolKind::Redis(redis) => {
|
PoolKind::Redis(redis) => {
|
||||||
@@ -232,6 +243,7 @@ pub async fn redis_hash_del_in_db_core(
|
|||||||
key_raw: &str,
|
key_raw: &str,
|
||||||
field: &str,
|
field: &str,
|
||||||
) -> Result<(), String> {
|
) -> Result<(), String> {
|
||||||
|
ensure_redis_pool(state, connection_id).await?;
|
||||||
let connections = state.connections.read().await;
|
let connections = state.connections.read().await;
|
||||||
match connections.get(connection_id).ok_or("Not found")? {
|
match connections.get(connection_id).ok_or("Not found")? {
|
||||||
PoolKind::Redis(redis) => {
|
PoolKind::Redis(redis) => {
|
||||||
@@ -271,6 +283,7 @@ pub async fn redis_list_push_in_db_core(
|
|||||||
value: &str,
|
value: &str,
|
||||||
ttl: Option<i64>,
|
ttl: Option<i64>,
|
||||||
) -> Result<(), String> {
|
) -> Result<(), String> {
|
||||||
|
ensure_redis_pool(state, connection_id).await?;
|
||||||
let connections = state.connections.read().await;
|
let connections = state.connections.read().await;
|
||||||
match connections.get(connection_id).ok_or("Not found")? {
|
match connections.get(connection_id).ok_or("Not found")? {
|
||||||
PoolKind::Redis(redis) => {
|
PoolKind::Redis(redis) => {
|
||||||
@@ -300,6 +313,7 @@ pub async fn redis_list_set_in_db_core(
|
|||||||
index: i64,
|
index: i64,
|
||||||
value: &str,
|
value: &str,
|
||||||
) -> Result<(), String> {
|
) -> Result<(), String> {
|
||||||
|
ensure_redis_pool(state, connection_id).await?;
|
||||||
let connections = state.connections.read().await;
|
let connections = state.connections.read().await;
|
||||||
match connections.get(connection_id).ok_or("Not found")? {
|
match connections.get(connection_id).ok_or("Not found")? {
|
||||||
PoolKind::Redis(redis) => {
|
PoolKind::Redis(redis) => {
|
||||||
@@ -337,6 +351,7 @@ pub async fn redis_list_remove_in_db_core(
|
|||||||
key_raw: &str,
|
key_raw: &str,
|
||||||
index: i64,
|
index: i64,
|
||||||
) -> Result<(), String> {
|
) -> Result<(), String> {
|
||||||
|
ensure_redis_pool(state, connection_id).await?;
|
||||||
let connections = state.connections.read().await;
|
let connections = state.connections.read().await;
|
||||||
match connections.get(connection_id).ok_or("Not found")? {
|
match connections.get(connection_id).ok_or("Not found")? {
|
||||||
PoolKind::Redis(redis) => {
|
PoolKind::Redis(redis) => {
|
||||||
@@ -376,6 +391,7 @@ pub async fn redis_set_add_in_db_core(
|
|||||||
member: &str,
|
member: &str,
|
||||||
ttl: Option<i64>,
|
ttl: Option<i64>,
|
||||||
) -> Result<(), String> {
|
) -> Result<(), String> {
|
||||||
|
ensure_redis_pool(state, connection_id).await?;
|
||||||
let connections = state.connections.read().await;
|
let connections = state.connections.read().await;
|
||||||
match connections.get(connection_id).ok_or("Not found")? {
|
match connections.get(connection_id).ok_or("Not found")? {
|
||||||
PoolKind::Redis(redis) => {
|
PoolKind::Redis(redis) => {
|
||||||
@@ -413,6 +429,7 @@ pub async fn redis_set_remove_in_db_core(
|
|||||||
key_raw: &str,
|
key_raw: &str,
|
||||||
member: &str,
|
member: &str,
|
||||||
) -> Result<(), String> {
|
) -> Result<(), String> {
|
||||||
|
ensure_redis_pool(state, connection_id).await?;
|
||||||
let connections = state.connections.read().await;
|
let connections = state.connections.read().await;
|
||||||
match connections.get(connection_id).ok_or("Not found")? {
|
match connections.get(connection_id).ok_or("Not found")? {
|
||||||
PoolKind::Redis(redis) => {
|
PoolKind::Redis(redis) => {
|
||||||
@@ -443,6 +460,7 @@ pub async fn redis_zadd_in_db_core(
|
|||||||
score: f64,
|
score: f64,
|
||||||
ttl: Option<i64>,
|
ttl: Option<i64>,
|
||||||
) -> Result<(), String> {
|
) -> Result<(), String> {
|
||||||
|
ensure_redis_pool(state, connection_id).await?;
|
||||||
let connections = state.connections.read().await;
|
let connections = state.connections.read().await;
|
||||||
match connections.get(connection_id).ok_or("Not found")? {
|
match connections.get(connection_id).ok_or("Not found")? {
|
||||||
PoolKind::Redis(redis) => {
|
PoolKind::Redis(redis) => {
|
||||||
@@ -471,6 +489,7 @@ pub async fn redis_zrem_in_db_core(
|
|||||||
key_raw: &str,
|
key_raw: &str,
|
||||||
member: &str,
|
member: &str,
|
||||||
) -> Result<(), String> {
|
) -> Result<(), String> {
|
||||||
|
ensure_redis_pool(state, connection_id).await?;
|
||||||
let connections = state.connections.read().await;
|
let connections = state.connections.read().await;
|
||||||
match connections.get(connection_id).ok_or("Not found")? {
|
match connections.get(connection_id).ok_or("Not found")? {
|
||||||
PoolKind::Redis(redis) => {
|
PoolKind::Redis(redis) => {
|
||||||
@@ -501,6 +520,7 @@ pub async fn redis_stream_add_in_db_core(
|
|||||||
fields: Vec<(String, String)>,
|
fields: Vec<(String, String)>,
|
||||||
ttl: Option<i64>,
|
ttl: Option<i64>,
|
||||||
) -> Result<(), String> {
|
) -> Result<(), String> {
|
||||||
|
ensure_redis_pool(state, connection_id).await?;
|
||||||
let connections = state.connections.read().await;
|
let connections = state.connections.read().await;
|
||||||
match connections.get(connection_id).ok_or("Not found")? {
|
match connections.get(connection_id).ok_or("Not found")? {
|
||||||
PoolKind::Redis(redis) => {
|
PoolKind::Redis(redis) => {
|
||||||
@@ -530,6 +550,7 @@ pub async fn redis_json_set_in_db_core(
|
|||||||
value: &str,
|
value: &str,
|
||||||
ttl: Option<i64>,
|
ttl: Option<i64>,
|
||||||
) -> Result<(), String> {
|
) -> Result<(), String> {
|
||||||
|
ensure_redis_pool(state, connection_id).await?;
|
||||||
let connections = state.connections.read().await;
|
let connections = state.connections.read().await;
|
||||||
match connections.get(connection_id).ok_or("Not found")? {
|
match connections.get(connection_id).ok_or("Not found")? {
|
||||||
PoolKind::Redis(redis) => {
|
PoolKind::Redis(redis) => {
|
||||||
@@ -556,6 +577,7 @@ pub async fn redis_check_json_module_in_db_core(
|
|||||||
connection_id: &str,
|
connection_id: &str,
|
||||||
db: u32,
|
db: u32,
|
||||||
) -> Result<bool, String> {
|
) -> Result<bool, String> {
|
||||||
|
ensure_redis_pool(state, connection_id).await?;
|
||||||
let connections = state.connections.read().await;
|
let connections = state.connections.read().await;
|
||||||
match connections.get(connection_id).ok_or("Not found")? {
|
match connections.get(connection_id).ok_or("Not found")? {
|
||||||
PoolKind::Redis(redis) => match redis {
|
PoolKind::Redis(redis) => match redis {
|
||||||
@@ -581,6 +603,7 @@ pub async fn redis_set_ttl_in_db_core(
|
|||||||
key_raw: &str,
|
key_raw: &str,
|
||||||
ttl: i64,
|
ttl: i64,
|
||||||
) -> Result<(), String> {
|
) -> Result<(), String> {
|
||||||
|
ensure_redis_pool(state, connection_id).await?;
|
||||||
let connections = state.connections.read().await;
|
let connections = state.connections.read().await;
|
||||||
match connections.get(connection_id).ok_or("Not found")? {
|
match connections.get(connection_id).ok_or("Not found")? {
|
||||||
PoolKind::Redis(redis) => {
|
PoolKind::Redis(redis) => {
|
||||||
@@ -608,6 +631,7 @@ pub async fn redis_delete_keys_in_db_core(
|
|||||||
db: u32,
|
db: u32,
|
||||||
key_raws: &[String],
|
key_raws: &[String],
|
||||||
) -> Result<u64, String> {
|
) -> Result<u64, String> {
|
||||||
|
ensure_redis_pool(state, connection_id).await?;
|
||||||
let connections = state.connections.read().await;
|
let connections = state.connections.read().await;
|
||||||
match connections.get(connection_id).ok_or("Not found")? {
|
match connections.get(connection_id).ok_or("Not found")? {
|
||||||
PoolKind::Redis(redis) => {
|
PoolKind::Redis(redis) => {
|
||||||
@@ -636,6 +660,7 @@ pub async fn redis_delete_keys_in_db_core(
|
|||||||
}
|
}
|
||||||
|
|
||||||
pub async fn redis_flush_db_core(state: &AppState, connection_id: &str, db: u32) -> Result<(), String> {
|
pub async fn redis_flush_db_core(state: &AppState, connection_id: &str, db: u32) -> Result<(), String> {
|
||||||
|
ensure_redis_pool(state, connection_id).await?;
|
||||||
let connections = state.connections.read().await;
|
let connections = state.connections.read().await;
|
||||||
match connections.get(connection_id).ok_or("Not found")? {
|
match connections.get(connection_id).ok_or("Not found")? {
|
||||||
PoolKind::Redis(redis) => match redis {
|
PoolKind::Redis(redis) => match redis {
|
||||||
@@ -660,6 +685,7 @@ pub async fn redis_execute_command_core(
|
|||||||
command: &str,
|
command: &str,
|
||||||
skip_safety_check: bool,
|
skip_safety_check: bool,
|
||||||
) -> Result<RedisCommandResult, String> {
|
) -> Result<RedisCommandResult, String> {
|
||||||
|
ensure_redis_pool(state, connection_id).await?;
|
||||||
let connections = state.connections.read().await;
|
let connections = state.connections.read().await;
|
||||||
match connections.get(connection_id).ok_or("Not found")? {
|
match connections.get(connection_id).ok_or("Not found")? {
|
||||||
PoolKind::Redis(redis) => match redis {
|
PoolKind::Redis(redis) => match redis {
|
||||||
@@ -692,6 +718,7 @@ pub async fn redis_load_more_in_db_core(
|
|||||||
cursor: u64,
|
cursor: u64,
|
||||||
count: usize,
|
count: usize,
|
||||||
) -> Result<redis_driver::RedisValue, String> {
|
) -> Result<redis_driver::RedisValue, String> {
|
||||||
|
ensure_redis_pool(state, connection_id).await?;
|
||||||
let connections = state.connections.read().await;
|
let connections = state.connections.read().await;
|
||||||
match connections.get(connection_id).ok_or("Not found")? {
|
match connections.get(connection_id).ok_or("Not found")? {
|
||||||
PoolKind::Redis(redis) => {
|
PoolKind::Redis(redis) => {
|
||||||
|
|||||||
@@ -884,6 +884,8 @@ mod tests {
|
|||||||
ref_schema: overrides.ref_schema,
|
ref_schema: overrides.ref_schema,
|
||||||
ref_table: if overrides.ref_table.is_empty() { "users".to_string() } else { overrides.ref_table },
|
ref_table: if overrides.ref_table.is_empty() { "users".to_string() } else { overrides.ref_table },
|
||||||
ref_column: if overrides.ref_column.is_empty() { "id".to_string() } else { overrides.ref_column },
|
ref_column: if overrides.ref_column.is_empty() { "id".to_string() } else { overrides.ref_column },
|
||||||
|
on_update: None,
|
||||||
|
on_delete: None,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -942,6 +944,8 @@ mod tests {
|
|||||||
ref_schema: None,
|
ref_schema: None,
|
||||||
ref_table: String::new(),
|
ref_table: String::new(),
|
||||||
ref_column: String::new(),
|
ref_column: String::new(),
|
||||||
|
on_update: None,
|
||||||
|
on_delete: None,
|
||||||
}),
|
}),
|
||||||
foreign_key(ForeignKeyInfo {
|
foreign_key(ForeignKeyInfo {
|
||||||
name: "orders_account_id_fk".to_string(),
|
name: "orders_account_id_fk".to_string(),
|
||||||
@@ -949,6 +953,8 @@ mod tests {
|
|||||||
ref_schema: None,
|
ref_schema: None,
|
||||||
ref_table: "accounts".to_string(),
|
ref_table: "accounts".to_string(),
|
||||||
ref_column: String::new(),
|
ref_column: String::new(),
|
||||||
|
on_update: None,
|
||||||
|
on_delete: None,
|
||||||
}),
|
}),
|
||||||
],
|
],
|
||||||
&[
|
&[
|
||||||
@@ -958,6 +964,8 @@ mod tests {
|
|||||||
ref_schema: None,
|
ref_schema: None,
|
||||||
ref_table: "members".to_string(),
|
ref_table: "members".to_string(),
|
||||||
ref_column: String::new(),
|
ref_column: String::new(),
|
||||||
|
on_update: None,
|
||||||
|
on_delete: None,
|
||||||
}),
|
}),
|
||||||
foreign_key(ForeignKeyInfo {
|
foreign_key(ForeignKeyInfo {
|
||||||
name: "orders_region_id_fk".to_string(),
|
name: "orders_region_id_fk".to_string(),
|
||||||
@@ -965,6 +973,8 @@ mod tests {
|
|||||||
ref_schema: None,
|
ref_schema: None,
|
||||||
ref_table: "regions".to_string(),
|
ref_table: "regions".to_string(),
|
||||||
ref_column: String::new(),
|
ref_column: String::new(),
|
||||||
|
on_update: None,
|
||||||
|
on_delete: None,
|
||||||
}),
|
}),
|
||||||
],
|
],
|
||||||
);
|
);
|
||||||
@@ -1012,6 +1022,8 @@ mod tests {
|
|||||||
ref_schema: None,
|
ref_schema: None,
|
||||||
ref_table: "users".to_string(),
|
ref_table: "users".to_string(),
|
||||||
ref_column: String::new(),
|
ref_column: String::new(),
|
||||||
|
on_update: None,
|
||||||
|
on_delete: None,
|
||||||
})),
|
})),
|
||||||
target: None,
|
target: None,
|
||||||
changes: Vec::new(),
|
changes: Vec::new(),
|
||||||
|
|||||||
@@ -4,7 +4,9 @@ mod columns;
|
|||||||
mod comments;
|
mod comments;
|
||||||
mod create_table;
|
mod create_table;
|
||||||
mod dialect;
|
mod dialect;
|
||||||
|
mod foreign_keys;
|
||||||
mod indexes;
|
mod indexes;
|
||||||
|
mod triggers;
|
||||||
mod types;
|
mod types;
|
||||||
mod util;
|
mod util;
|
||||||
mod validation;
|
mod validation;
|
||||||
@@ -18,13 +20,17 @@ pub use types::*;
|
|||||||
|
|
||||||
use columns::build_column_sql;
|
use columns::build_column_sql;
|
||||||
use comments::build_table_comment_sql;
|
use comments::build_table_comment_sql;
|
||||||
|
use foreign_keys::build_foreign_key_sql;
|
||||||
use indexes::build_index_sql;
|
use indexes::build_index_sql;
|
||||||
|
use triggers::build_trigger_sql;
|
||||||
use validation::validate_draft;
|
use validation::validate_draft;
|
||||||
|
|
||||||
pub fn build_table_structure_change_sql(options: TableStructureSqlOptions) -> TableStructureSqlResult {
|
pub fn build_table_structure_change_sql(options: TableStructureSqlOptions) -> TableStructureSqlResult {
|
||||||
let mut warnings = validate_draft(&options);
|
let mut warnings = validate_draft(&options);
|
||||||
let mut statements = build_column_sql(&options, &mut warnings);
|
let mut statements = build_column_sql(&options, &mut warnings);
|
||||||
statements.extend(build_index_sql(&options, &mut warnings));
|
statements.extend(build_index_sql(&options, &mut warnings));
|
||||||
|
statements.extend(build_foreign_key_sql(&options, &mut warnings));
|
||||||
|
statements.extend(build_trigger_sql(&options, &mut warnings));
|
||||||
statements.extend(build_table_comment_sql(&options, &mut warnings));
|
statements.extend(build_table_comment_sql(&options, &mut warnings));
|
||||||
TableStructureSqlResult { statements, warnings }
|
TableStructureSqlResult { statements, warnings }
|
||||||
}
|
}
|
||||||
@@ -1,7 +1,9 @@
|
|||||||
use super::column_format::{column_data_type, column_extra_clause};
|
use super::column_format::{column_data_type, column_extra_clause};
|
||||||
use super::comments::{build_sqlserver_column_comment_sql, build_sqlserver_table_comment_sql};
|
use super::comments::{build_sqlserver_column_comment_sql, build_sqlserver_table_comment_sql};
|
||||||
use super::dialect::{capabilities_for, database_label, StructureDialect};
|
use super::dialect::{capabilities_for, database_label, StructureDialect};
|
||||||
|
use super::foreign_keys::build_foreign_key_sql;
|
||||||
use super::indexes::build_create_index_statements;
|
use super::indexes::build_create_index_statements;
|
||||||
|
use super::triggers::build_trigger_sql;
|
||||||
use super::types::{TableStructureSqlOptions, TableStructureSqlResult};
|
use super::types::{TableStructureSqlOptions, TableStructureSqlResult};
|
||||||
use super::util::{clean, format_default_for_sql, normalize_default, qualified_table, quote_ident, quote_string};
|
use super::util::{clean, format_default_for_sql, normalize_default, qualified_table, quote_ident, quote_string};
|
||||||
use super::validation::validate_columns;
|
use super::validation::validate_columns;
|
||||||
@@ -136,5 +138,8 @@ pub fn build_create_table_sql(options: TableStructureSqlOptions) -> TableStructu
|
|||||||
));
|
));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
statements.extend(build_foreign_key_sql(&options, &mut warnings));
|
||||||
|
statements.extend(build_trigger_sql(&options, &mut warnings));
|
||||||
|
|
||||||
TableStructureSqlResult { statements, warnings }
|
TableStructureSqlResult { statements, warnings }
|
||||||
}
|
}
|
||||||
@@ -0,0 +1,124 @@
|
|||||||
|
use super::dialect::{database_label, StructureDialect};
|
||||||
|
use super::types::{EditableStructureForeignKey, ForeignKeyInfo, TableStructureSqlOptions};
|
||||||
|
use super::util::{clean, qualified_table, quote_ident};
|
||||||
|
|
||||||
|
pub(super) fn build_foreign_key_sql(options: &TableStructureSqlOptions, warnings: &mut Vec<String>) -> Vec<String> {
|
||||||
|
if options.foreign_keys.is_empty() {
|
||||||
|
return Vec::new();
|
||||||
|
}
|
||||||
|
|
||||||
|
let database_label = database_label(options.database_type);
|
||||||
|
if super::dialect::capabilities_for(options.database_type).dialect != StructureDialect::Mysql {
|
||||||
|
warnings.push(format!("Editing foreign keys is not supported for {database_label} from this editor."));
|
||||||
|
return Vec::new();
|
||||||
|
}
|
||||||
|
|
||||||
|
let table = qualified_table(StructureDialect::Mysql, options.schema.as_deref(), &options.table_name);
|
||||||
|
let mut statements = Vec::new();
|
||||||
|
|
||||||
|
for foreign_key in &options.foreign_keys {
|
||||||
|
if foreign_key.marked_for_drop {
|
||||||
|
if let Some(original) = &foreign_key.original {
|
||||||
|
statements.push(drop_foreign_key_sql(&table, &original.name));
|
||||||
|
}
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
if let Some(original) = &foreign_key.original {
|
||||||
|
if !has_foreign_key_change(foreign_key, original) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
statements.push(drop_foreign_key_sql(&table, &original.name));
|
||||||
|
}
|
||||||
|
|
||||||
|
if let Some(sql) = create_foreign_key_sql(&table, foreign_key, warnings) {
|
||||||
|
statements.push(sql);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
statements
|
||||||
|
}
|
||||||
|
|
||||||
|
fn has_foreign_key_change(foreign_key: &EditableStructureForeignKey, original: &ForeignKeyInfo) -> bool {
|
||||||
|
clean(&foreign_key.name) != clean(&original.name)
|
||||||
|
|| clean(&foreign_key.column) != clean(&original.column)
|
||||||
|
|| clean(&foreign_key.ref_schema) != clean(original.ref_schema.as_deref().unwrap_or(""))
|
||||||
|
|| clean(&foreign_key.ref_table) != clean(&original.ref_table)
|
||||||
|
|| clean(&foreign_key.ref_column) != clean(&original.ref_column)
|
||||||
|
|| normalize_action(&foreign_key.on_update) != normalize_action(original.on_update.as_deref().unwrap_or(""))
|
||||||
|
|| normalize_action(&foreign_key.on_delete) != normalize_action(original.on_delete.as_deref().unwrap_or(""))
|
||||||
|
}
|
||||||
|
|
||||||
|
fn drop_foreign_key_sql(table: &str, name: &str) -> String {
|
||||||
|
format!("ALTER TABLE {table} DROP FOREIGN KEY {};", quote_ident(StructureDialect::Mysql, name))
|
||||||
|
}
|
||||||
|
|
||||||
|
fn create_foreign_key_sql(
|
||||||
|
table: &str,
|
||||||
|
foreign_key: &EditableStructureForeignKey,
|
||||||
|
warnings: &mut Vec<String>,
|
||||||
|
) -> Option<String> {
|
||||||
|
let name = clean(&foreign_key.name);
|
||||||
|
let columns = identifier_list(&foreign_key.column);
|
||||||
|
let ref_table = clean(&foreign_key.ref_table);
|
||||||
|
let ref_columns = identifier_list(&foreign_key.ref_column);
|
||||||
|
if name.is_empty() || columns.is_empty() || ref_table.is_empty() || ref_columns.is_empty() {
|
||||||
|
warnings.push("Foreign key name, column, referenced table, and referenced column are required.".to_string());
|
||||||
|
return None;
|
||||||
|
}
|
||||||
|
if columns.len() != ref_columns.len() {
|
||||||
|
warnings.push(format!("Foreign key \"{name}\" must have the same number of local and referenced columns."));
|
||||||
|
return None;
|
||||||
|
}
|
||||||
|
|
||||||
|
let ref_target = if clean(&foreign_key.ref_schema).is_empty() {
|
||||||
|
quote_ident(StructureDialect::Mysql, &ref_table)
|
||||||
|
} else {
|
||||||
|
format!(
|
||||||
|
"{}.{}",
|
||||||
|
quote_ident(StructureDialect::Mysql, &foreign_key.ref_schema),
|
||||||
|
quote_ident(StructureDialect::Mysql, &ref_table)
|
||||||
|
)
|
||||||
|
};
|
||||||
|
|
||||||
|
let mut sql = format!(
|
||||||
|
"ALTER TABLE {table} ADD CONSTRAINT {} FOREIGN KEY ({}) REFERENCES {ref_target} ({}",
|
||||||
|
quote_ident(StructureDialect::Mysql, &name),
|
||||||
|
columns.iter().map(|column| quote_ident(StructureDialect::Mysql, column)).collect::<Vec<_>>().join(", "),
|
||||||
|
ref_columns.iter().map(|column| quote_ident(StructureDialect::Mysql, column)).collect::<Vec<_>>().join(", ")
|
||||||
|
);
|
||||||
|
sql.push(')');
|
||||||
|
|
||||||
|
if let Some(action) = action_clause("ON DELETE", &foreign_key.on_delete, warnings) {
|
||||||
|
sql.push(' ');
|
||||||
|
sql.push_str(&action);
|
||||||
|
}
|
||||||
|
if let Some(action) = action_clause("ON UPDATE", &foreign_key.on_update, warnings) {
|
||||||
|
sql.push(' ');
|
||||||
|
sql.push_str(&action);
|
||||||
|
}
|
||||||
|
sql.push(';');
|
||||||
|
Some(sql)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn action_clause(prefix: &str, value: &str, warnings: &mut Vec<String>) -> Option<String> {
|
||||||
|
let action = normalize_action(value);
|
||||||
|
if action.is_empty() {
|
||||||
|
return None;
|
||||||
|
}
|
||||||
|
match action.as_str() {
|
||||||
|
"CASCADE" | "SET NULL" | "RESTRICT" | "NO ACTION" => Some(format!("{prefix} {action}")),
|
||||||
|
_ => {
|
||||||
|
warnings.push(format!("Unsupported foreign key action \"{}\".", clean(value)));
|
||||||
|
None
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn normalize_action(value: &str) -> String {
|
||||||
|
clean(value).split_whitespace().collect::<Vec<_>>().join(" ").to_ascii_uppercase()
|
||||||
|
}
|
||||||
|
|
||||||
|
fn identifier_list(value: &str) -> Vec<String> {
|
||||||
|
value.split(',').map(clean).filter(|value| !value.is_empty()).collect()
|
||||||
|
}
|
||||||
@@ -33,6 +33,33 @@ fn index(name: &str, columns: &[&str]) -> EditableStructureIndex {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
fn foreign_key(name: &str, column: &str, ref_table: &str, ref_column: &str) -> EditableStructureForeignKey {
|
||||||
|
EditableStructureForeignKey {
|
||||||
|
id: name.to_string(),
|
||||||
|
name: name.to_string(),
|
||||||
|
column: column.to_string(),
|
||||||
|
ref_schema: String::new(),
|
||||||
|
ref_table: ref_table.to_string(),
|
||||||
|
ref_column: ref_column.to_string(),
|
||||||
|
on_update: String::new(),
|
||||||
|
on_delete: String::new(),
|
||||||
|
original: None,
|
||||||
|
marked_for_drop: false,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn trigger(name: &str, timing: &str, event: &str, statement: &str) -> EditableStructureTrigger {
|
||||||
|
EditableStructureTrigger {
|
||||||
|
id: name.to_string(),
|
||||||
|
name: name.to_string(),
|
||||||
|
timing: timing.to_string(),
|
||||||
|
event: event.to_string(),
|
||||||
|
statement: statement.to_string(),
|
||||||
|
original: None,
|
||||||
|
marked_for_drop: false,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn builds_mysql_column_and_index_changes() {
|
fn builds_mysql_column_and_index_changes() {
|
||||||
let mut renamed = column("display_name");
|
let mut renamed = column("display_name");
|
||||||
@@ -72,6 +99,8 @@ fn builds_mysql_column_and_index_changes() {
|
|||||||
table_name: "users".to_string(),
|
table_name: "users".to_string(),
|
||||||
columns: vec![renamed, email],
|
columns: vec![renamed, email],
|
||||||
indexes: vec![old_index, email_index],
|
indexes: vec![old_index, email_index],
|
||||||
|
foreign_keys: Vec::new(),
|
||||||
|
triggers: Vec::new(),
|
||||||
table_comment: None,
|
table_comment: None,
|
||||||
original_table_comment: None,
|
original_table_comment: None,
|
||||||
});
|
});
|
||||||
@@ -100,6 +129,8 @@ fn mysql_add_timestamp_column_drops_invalid_precision() {
|
|||||||
table_name: "users".to_string(),
|
table_name: "users".to_string(),
|
||||||
columns: vec![created_at],
|
columns: vec![created_at],
|
||||||
indexes: Vec::new(),
|
indexes: Vec::new(),
|
||||||
|
foreign_keys: Vec::new(),
|
||||||
|
triggers: Vec::new(),
|
||||||
table_comment: None,
|
table_comment: None,
|
||||||
original_table_comment: None,
|
original_table_comment: None,
|
||||||
});
|
});
|
||||||
@@ -123,6 +154,8 @@ fn mysql_add_timestamp_column_preserves_valid_precision() {
|
|||||||
table_name: "users".to_string(),
|
table_name: "users".to_string(),
|
||||||
columns: vec![created_at],
|
columns: vec![created_at],
|
||||||
indexes: Vec::new(),
|
indexes: Vec::new(),
|
||||||
|
foreign_keys: Vec::new(),
|
||||||
|
triggers: Vec::new(),
|
||||||
table_comment: None,
|
table_comment: None,
|
||||||
original_table_comment: None,
|
original_table_comment: None,
|
||||||
});
|
});
|
||||||
@@ -153,6 +186,8 @@ fn builds_postgres_create_table_with_comments_and_index() {
|
|||||||
table_name: "users".to_string(),
|
table_name: "users".to_string(),
|
||||||
columns: vec![id, name],
|
columns: vec![id, name],
|
||||||
indexes: vec![idx],
|
indexes: vec![idx],
|
||||||
|
foreign_keys: Vec::new(),
|
||||||
|
triggers: Vec::new(),
|
||||||
table_comment: None,
|
table_comment: None,
|
||||||
original_table_comment: None,
|
original_table_comment: None,
|
||||||
});
|
});
|
||||||
@@ -189,6 +224,8 @@ fn warns_for_sqlite_unsafe_column_changes() {
|
|||||||
table_name: "users".to_string(),
|
table_name: "users".to_string(),
|
||||||
columns: vec![col],
|
columns: vec![col],
|
||||||
indexes: Vec::new(),
|
indexes: Vec::new(),
|
||||||
|
foreign_keys: Vec::new(),
|
||||||
|
triggers: Vec::new(),
|
||||||
table_comment: None,
|
table_comment: None,
|
||||||
original_table_comment: None,
|
original_table_comment: None,
|
||||||
});
|
});
|
||||||
@@ -214,6 +251,8 @@ fn builds_rqlite_changes_with_sqlite_dialect() {
|
|||||||
table_name: "users".to_string(),
|
table_name: "users".to_string(),
|
||||||
columns: vec![email],
|
columns: vec![email],
|
||||||
indexes: vec![email_index],
|
indexes: vec![email_index],
|
||||||
|
foreign_keys: Vec::new(),
|
||||||
|
triggers: Vec::new(),
|
||||||
table_comment: None,
|
table_comment: None,
|
||||||
original_table_comment: None,
|
original_table_comment: None,
|
||||||
});
|
});
|
||||||
@@ -277,6 +316,8 @@ fn builds_mysql_column_reorder_statements() {
|
|||||||
table_name: "users".to_string(),
|
table_name: "users".to_string(),
|
||||||
columns: vec![id, email, name],
|
columns: vec![id, email, name],
|
||||||
indexes: Vec::new(),
|
indexes: Vec::new(),
|
||||||
|
foreign_keys: Vec::new(),
|
||||||
|
triggers: Vec::new(),
|
||||||
table_comment: None,
|
table_comment: None,
|
||||||
original_table_comment: None,
|
original_table_comment: None,
|
||||||
});
|
});
|
||||||
@@ -303,6 +344,8 @@ fn builds_sql_server_quoted_column_and_index_statements() {
|
|||||||
table_name: "users".to_string(),
|
table_name: "users".to_string(),
|
||||||
columns: vec![email],
|
columns: vec![email],
|
||||||
indexes: vec![index("idx_users_email", &["email"])],
|
indexes: vec![index("idx_users_email", &["email"])],
|
||||||
|
foreign_keys: Vec::new(),
|
||||||
|
triggers: Vec::new(),
|
||||||
table_comment: None,
|
table_comment: None,
|
||||||
original_table_comment: None,
|
original_table_comment: None,
|
||||||
});
|
});
|
||||||
@@ -333,6 +376,8 @@ fn builds_duckdb_create_table_statements() {
|
|||||||
table_name: "events".to_string(),
|
table_name: "events".to_string(),
|
||||||
columns: vec![name, created_at],
|
columns: vec![name, created_at],
|
||||||
indexes: vec![index("idx_events_name", &["name"])],
|
indexes: vec![index("idx_events_name", &["name"])],
|
||||||
|
foreign_keys: Vec::new(),
|
||||||
|
triggers: Vec::new(),
|
||||||
table_comment: None,
|
table_comment: None,
|
||||||
original_table_comment: None,
|
original_table_comment: None,
|
||||||
});
|
});
|
||||||
@@ -373,6 +418,8 @@ fn builds_clickhouse_nullable_comment_and_reorder_statements() {
|
|||||||
table_name: "events".to_string(),
|
table_name: "events".to_string(),
|
||||||
columns: vec![source, status],
|
columns: vec![source, status],
|
||||||
indexes: Vec::new(),
|
indexes: Vec::new(),
|
||||||
|
foreign_keys: Vec::new(),
|
||||||
|
triggers: Vec::new(),
|
||||||
table_comment: None,
|
table_comment: None,
|
||||||
original_table_comment: None,
|
original_table_comment: None,
|
||||||
});
|
});
|
||||||
@@ -414,6 +461,8 @@ fn builds_h2_schema_qualified_existing_column_statements() {
|
|||||||
table_name: "USERS".to_string(),
|
table_name: "USERS".to_string(),
|
||||||
columns: vec![name],
|
columns: vec![name],
|
||||||
indexes: vec![index("IDX_USERS_DISPLAY_NAME", &["DISPLAY_NAME"])],
|
indexes: vec![index("IDX_USERS_DISPLAY_NAME", &["DISPLAY_NAME"])],
|
||||||
|
foreign_keys: Vec::new(),
|
||||||
|
triggers: Vec::new(),
|
||||||
table_comment: None,
|
table_comment: None,
|
||||||
original_table_comment: None,
|
original_table_comment: None,
|
||||||
});
|
});
|
||||||
@@ -454,6 +503,8 @@ fn builds_postgres_alter_table_add_primary_key() {
|
|||||||
table_name: "users".to_string(),
|
table_name: "users".to_string(),
|
||||||
columns: vec![id],
|
columns: vec![id],
|
||||||
indexes: Vec::new(),
|
indexes: Vec::new(),
|
||||||
|
foreign_keys: Vec::new(),
|
||||||
|
triggers: Vec::new(),
|
||||||
table_comment: None,
|
table_comment: None,
|
||||||
original_table_comment: None,
|
original_table_comment: None,
|
||||||
});
|
});
|
||||||
@@ -484,6 +535,8 @@ fn builds_postgres_alter_table_drop_primary_key() {
|
|||||||
table_name: "users".to_string(),
|
table_name: "users".to_string(),
|
||||||
columns: vec![id],
|
columns: vec![id],
|
||||||
indexes: Vec::new(),
|
indexes: Vec::new(),
|
||||||
|
foreign_keys: Vec::new(),
|
||||||
|
triggers: Vec::new(),
|
||||||
table_comment: None,
|
table_comment: None,
|
||||||
original_table_comment: None,
|
original_table_comment: None,
|
||||||
});
|
});
|
||||||
@@ -530,6 +583,8 @@ fn builds_mysql_alter_table_change_primary_key() {
|
|||||||
table_name: "users".to_string(),
|
table_name: "users".to_string(),
|
||||||
columns: vec![old_pk, new_pk],
|
columns: vec![old_pk, new_pk],
|
||||||
indexes: Vec::new(),
|
indexes: Vec::new(),
|
||||||
|
foreign_keys: Vec::new(),
|
||||||
|
triggers: Vec::new(),
|
||||||
table_comment: None,
|
table_comment: None,
|
||||||
original_table_comment: None,
|
original_table_comment: None,
|
||||||
});
|
});
|
||||||
@@ -563,6 +618,8 @@ fn builds_no_statements_when_primary_key_unchanged() {
|
|||||||
table_name: "users".to_string(),
|
table_name: "users".to_string(),
|
||||||
columns: vec![id],
|
columns: vec![id],
|
||||||
indexes: Vec::new(),
|
indexes: Vec::new(),
|
||||||
|
foreign_keys: Vec::new(),
|
||||||
|
triggers: Vec::new(),
|
||||||
table_comment: None,
|
table_comment: None,
|
||||||
original_table_comment: None,
|
original_table_comment: None,
|
||||||
});
|
});
|
||||||
@@ -593,6 +650,8 @@ fn warns_sqlite_cannot_alter_primary_key() {
|
|||||||
table_name: "users".to_string(),
|
table_name: "users".to_string(),
|
||||||
columns: vec![id],
|
columns: vec![id],
|
||||||
indexes: Vec::new(),
|
indexes: Vec::new(),
|
||||||
|
foreign_keys: Vec::new(),
|
||||||
|
triggers: Vec::new(),
|
||||||
table_comment: None,
|
table_comment: None,
|
||||||
original_table_comment: None,
|
original_table_comment: None,
|
||||||
});
|
});
|
||||||
@@ -616,6 +675,8 @@ fn mysql_create_table_with_auto_increment() {
|
|||||||
table_name: "users".to_string(),
|
table_name: "users".to_string(),
|
||||||
columns: vec![col],
|
columns: vec![col],
|
||||||
indexes: Vec::new(),
|
indexes: Vec::new(),
|
||||||
|
foreign_keys: Vec::new(),
|
||||||
|
triggers: Vec::new(),
|
||||||
table_comment: None,
|
table_comment: None,
|
||||||
original_table_comment: None,
|
original_table_comment: None,
|
||||||
});
|
});
|
||||||
@@ -639,6 +700,8 @@ fn mysql_create_table_with_on_update_current_timestamp() {
|
|||||||
table_name: "users".to_string(),
|
table_name: "users".to_string(),
|
||||||
columns: vec![col],
|
columns: vec![col],
|
||||||
indexes: Vec::new(),
|
indexes: Vec::new(),
|
||||||
|
foreign_keys: Vec::new(),
|
||||||
|
triggers: Vec::new(),
|
||||||
table_comment: None,
|
table_comment: None,
|
||||||
original_table_comment: None,
|
original_table_comment: None,
|
||||||
});
|
});
|
||||||
@@ -664,6 +727,8 @@ fn postgres_create_table_with_identity() {
|
|||||||
table_name: "users".to_string(),
|
table_name: "users".to_string(),
|
||||||
columns: vec![col],
|
columns: vec![col],
|
||||||
indexes: Vec::new(),
|
indexes: Vec::new(),
|
||||||
|
foreign_keys: Vec::new(),
|
||||||
|
triggers: Vec::new(),
|
||||||
table_comment: None,
|
table_comment: None,
|
||||||
original_table_comment: None,
|
original_table_comment: None,
|
||||||
});
|
});
|
||||||
@@ -689,6 +754,8 @@ fn sqlserver_create_table_with_identity() {
|
|||||||
table_name: "users".to_string(),
|
table_name: "users".to_string(),
|
||||||
columns: vec![col],
|
columns: vec![col],
|
||||||
indexes: Vec::new(),
|
indexes: Vec::new(),
|
||||||
|
foreign_keys: Vec::new(),
|
||||||
|
triggers: Vec::new(),
|
||||||
table_comment: None,
|
table_comment: None,
|
||||||
original_table_comment: None,
|
original_table_comment: None,
|
||||||
});
|
});
|
||||||
@@ -709,6 +776,8 @@ fn mysql_quotes_datetime_literal_default() {
|
|||||||
table_name: "events".to_string(),
|
table_name: "events".to_string(),
|
||||||
columns: vec![col],
|
columns: vec![col],
|
||||||
indexes: Vec::new(),
|
indexes: Vec::new(),
|
||||||
|
foreign_keys: Vec::new(),
|
||||||
|
triggers: Vec::new(),
|
||||||
table_comment: None,
|
table_comment: None,
|
||||||
original_table_comment: None,
|
original_table_comment: None,
|
||||||
});
|
});
|
||||||
@@ -729,6 +798,8 @@ fn mysql_does_not_quote_current_timestamp() {
|
|||||||
table_name: "events".to_string(),
|
table_name: "events".to_string(),
|
||||||
columns: vec![col],
|
columns: vec![col],
|
||||||
indexes: Vec::new(),
|
indexes: Vec::new(),
|
||||||
|
foreign_keys: Vec::new(),
|
||||||
|
triggers: Vec::new(),
|
||||||
table_comment: None,
|
table_comment: None,
|
||||||
original_table_comment: None,
|
original_table_comment: None,
|
||||||
});
|
});
|
||||||
@@ -750,6 +821,8 @@ fn mysql_does_not_quote_temporal_function_with_parens() {
|
|||||||
table_name: "events".to_string(),
|
table_name: "events".to_string(),
|
||||||
columns: vec![col],
|
columns: vec![col],
|
||||||
indexes: Vec::new(),
|
indexes: Vec::new(),
|
||||||
|
foreign_keys: Vec::new(),
|
||||||
|
triggers: Vec::new(),
|
||||||
table_comment: None,
|
table_comment: None,
|
||||||
original_table_comment: None,
|
original_table_comment: None,
|
||||||
});
|
});
|
||||||
@@ -770,6 +843,8 @@ fn mysql_date_literal_default_is_quoted() {
|
|||||||
table_name: "users".to_string(),
|
table_name: "users".to_string(),
|
||||||
columns: vec![col],
|
columns: vec![col],
|
||||||
indexes: Vec::new(),
|
indexes: Vec::new(),
|
||||||
|
foreign_keys: Vec::new(),
|
||||||
|
triggers: Vec::new(),
|
||||||
table_comment: None,
|
table_comment: None,
|
||||||
original_table_comment: None,
|
original_table_comment: None,
|
||||||
});
|
});
|
||||||
@@ -790,6 +865,8 @@ fn mysql_time_literal_default_is_quoted() {
|
|||||||
table_name: "shifts".to_string(),
|
table_name: "shifts".to_string(),
|
||||||
columns: vec![col],
|
columns: vec![col],
|
||||||
indexes: Vec::new(),
|
indexes: Vec::new(),
|
||||||
|
foreign_keys: Vec::new(),
|
||||||
|
triggers: Vec::new(),
|
||||||
table_comment: None,
|
table_comment: None,
|
||||||
original_table_comment: None,
|
original_table_comment: None,
|
||||||
});
|
});
|
||||||
@@ -810,6 +887,8 @@ fn non_temporal_types_are_not_quoted() {
|
|||||||
table_name: "games".to_string(),
|
table_name: "games".to_string(),
|
||||||
columns: vec![col],
|
columns: vec![col],
|
||||||
indexes: Vec::new(),
|
indexes: Vec::new(),
|
||||||
|
foreign_keys: Vec::new(),
|
||||||
|
triggers: Vec::new(),
|
||||||
table_comment: None,
|
table_comment: None,
|
||||||
original_table_comment: None,
|
original_table_comment: None,
|
||||||
});
|
});
|
||||||
@@ -868,3 +947,109 @@ fn mysql_single_column_alter_quotes_datetime_literal() {
|
|||||||
|
|
||||||
assert!(result.statements.iter().any(|s| s.contains("DEFAULT '2024-01-01 00:00:00'")));
|
assert!(result.statements.iter().any(|s| s.contains("DEFAULT '2024-01-01 00:00:00'")));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn builds_mysql_foreign_key_changes() {
|
||||||
|
let mut existing = foreign_key("fk_orders_users", "user_id", "users", "id");
|
||||||
|
existing.on_delete = "CASCADE".to_string();
|
||||||
|
existing.original = Some(ForeignKeyInfo {
|
||||||
|
name: "fk_orders_users_old".to_string(),
|
||||||
|
column: "customer_id".to_string(),
|
||||||
|
ref_schema: None,
|
||||||
|
ref_table: "customers".to_string(),
|
||||||
|
ref_column: "id".to_string(),
|
||||||
|
on_update: None,
|
||||||
|
on_delete: Some("RESTRICT".to_string()),
|
||||||
|
});
|
||||||
|
|
||||||
|
let mut dropped = foreign_key("fk_orders_accounts", "account_id", "accounts", "id");
|
||||||
|
dropped.marked_for_drop = true;
|
||||||
|
dropped.original = Some(ForeignKeyInfo {
|
||||||
|
name: "fk_orders_accounts".to_string(),
|
||||||
|
column: "account_id".to_string(),
|
||||||
|
ref_schema: None,
|
||||||
|
ref_table: "accounts".to_string(),
|
||||||
|
ref_column: "id".to_string(),
|
||||||
|
on_update: None,
|
||||||
|
on_delete: None,
|
||||||
|
});
|
||||||
|
|
||||||
|
let result = build_table_structure_change_sql(TableStructureSqlOptions {
|
||||||
|
database_type: Some(DatabaseType::Mysql),
|
||||||
|
schema: None,
|
||||||
|
table_name: "orders".to_string(),
|
||||||
|
columns: Vec::new(),
|
||||||
|
indexes: Vec::new(),
|
||||||
|
foreign_keys: vec![existing, dropped],
|
||||||
|
triggers: Vec::new(),
|
||||||
|
table_comment: None,
|
||||||
|
original_table_comment: None,
|
||||||
|
});
|
||||||
|
|
||||||
|
assert_eq!(result.warnings, Vec::<String>::new());
|
||||||
|
assert_eq!(
|
||||||
|
result.statements,
|
||||||
|
vec![
|
||||||
|
"ALTER TABLE `orders` DROP FOREIGN KEY `fk_orders_users_old`;",
|
||||||
|
"ALTER TABLE `orders` ADD CONSTRAINT `fk_orders_users` FOREIGN KEY (`user_id`) REFERENCES `users` (`id`) ON DELETE CASCADE;",
|
||||||
|
"ALTER TABLE `orders` DROP FOREIGN KEY `fk_orders_accounts`;",
|
||||||
|
]
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn builds_mysql_composite_foreign_key() {
|
||||||
|
let composite = foreign_key("fk_order_items_product", "tenant_id, product_id", "products", "tenant_id, id");
|
||||||
|
|
||||||
|
let result = build_table_structure_change_sql(TableStructureSqlOptions {
|
||||||
|
database_type: Some(DatabaseType::Mysql),
|
||||||
|
schema: None,
|
||||||
|
table_name: "order_items".to_string(),
|
||||||
|
columns: Vec::new(),
|
||||||
|
indexes: Vec::new(),
|
||||||
|
foreign_keys: vec![composite],
|
||||||
|
triggers: Vec::new(),
|
||||||
|
table_comment: None,
|
||||||
|
original_table_comment: None,
|
||||||
|
});
|
||||||
|
|
||||||
|
assert_eq!(result.warnings, Vec::<String>::new());
|
||||||
|
assert_eq!(
|
||||||
|
result.statements,
|
||||||
|
vec![
|
||||||
|
"ALTER TABLE `order_items` ADD CONSTRAINT `fk_order_items_product` FOREIGN KEY (`tenant_id`, `product_id`) REFERENCES `products` (`tenant_id`, `id`);",
|
||||||
|
]
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn builds_mysql_trigger_changes() {
|
||||||
|
let mut existing = trigger("orders_bu", "BEFORE", "UPDATE", "BEGIN\n SET NEW.updated_at = NOW();\nEND");
|
||||||
|
existing.original = Some(TriggerInfo {
|
||||||
|
name: "orders_bu".to_string(),
|
||||||
|
event: "UPDATE".to_string(),
|
||||||
|
timing: "BEFORE".to_string(),
|
||||||
|
statement: Some("SET NEW.updated_at = CURRENT_TIMESTAMP".to_string()),
|
||||||
|
});
|
||||||
|
|
||||||
|
let result = build_table_structure_change_sql(TableStructureSqlOptions {
|
||||||
|
database_type: Some(DatabaseType::Mysql),
|
||||||
|
schema: None,
|
||||||
|
table_name: "orders".to_string(),
|
||||||
|
columns: Vec::new(),
|
||||||
|
indexes: Vec::new(),
|
||||||
|
foreign_keys: Vec::new(),
|
||||||
|
triggers: vec![existing],
|
||||||
|
table_comment: None,
|
||||||
|
original_table_comment: None,
|
||||||
|
});
|
||||||
|
|
||||||
|
assert_eq!(result.warnings, Vec::<String>::new());
|
||||||
|
assert_eq!(
|
||||||
|
result.statements,
|
||||||
|
vec![
|
||||||
|
"DROP TRIGGER `orders_bu`;",
|
||||||
|
"CREATE TRIGGER `orders_bu` BEFORE UPDATE ON `orders` FOR EACH ROW\nBEGIN\n SET NEW.updated_at = NOW();\nEND;",
|
||||||
|
]
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -0,0 +1,94 @@
|
|||||||
|
use super::dialect::{database_label, StructureDialect};
|
||||||
|
use super::types::{EditableStructureTrigger, TableStructureSqlOptions, TriggerInfo};
|
||||||
|
use super::util::{clean, qualified_table, quote_ident};
|
||||||
|
|
||||||
|
pub(super) fn build_trigger_sql(options: &TableStructureSqlOptions, warnings: &mut Vec<String>) -> Vec<String> {
|
||||||
|
if options.triggers.is_empty() {
|
||||||
|
return Vec::new();
|
||||||
|
}
|
||||||
|
|
||||||
|
let database_label = database_label(options.database_type);
|
||||||
|
if super::dialect::capabilities_for(options.database_type).dialect != StructureDialect::Mysql {
|
||||||
|
warnings.push(format!("Editing triggers is not supported for {database_label} from this editor."));
|
||||||
|
return Vec::new();
|
||||||
|
}
|
||||||
|
|
||||||
|
let table = qualified_table(StructureDialect::Mysql, options.schema.as_deref(), &options.table_name);
|
||||||
|
let mut statements = Vec::new();
|
||||||
|
|
||||||
|
for trigger in &options.triggers {
|
||||||
|
if trigger.marked_for_drop {
|
||||||
|
if let Some(original) = &trigger.original {
|
||||||
|
statements.push(drop_trigger_sql(options.schema.as_deref(), &original.name));
|
||||||
|
}
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
if let Some(original) = &trigger.original {
|
||||||
|
if !has_trigger_change(trigger, original) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
statements.push(drop_trigger_sql(options.schema.as_deref(), &original.name));
|
||||||
|
}
|
||||||
|
|
||||||
|
if let Some(sql) = create_trigger_sql(&table, trigger, warnings) {
|
||||||
|
statements.push(sql);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
statements
|
||||||
|
}
|
||||||
|
|
||||||
|
fn has_trigger_change(trigger: &EditableStructureTrigger, original: &TriggerInfo) -> bool {
|
||||||
|
clean(&trigger.name) != clean(&original.name)
|
||||||
|
|| normalize_keyword(&trigger.timing) != normalize_keyword(&original.timing)
|
||||||
|
|| normalize_keyword(&trigger.event) != normalize_keyword(&original.event)
|
||||||
|
|| normalize_statement(&trigger.statement) != normalize_statement(original.statement.as_deref().unwrap_or(""))
|
||||||
|
}
|
||||||
|
|
||||||
|
fn drop_trigger_sql(schema: Option<&str>, name: &str) -> String {
|
||||||
|
let qualified_name = if schema.is_some_and(|schema| !schema.trim().is_empty()) {
|
||||||
|
format!(
|
||||||
|
"{}.{}",
|
||||||
|
quote_ident(StructureDialect::Mysql, schema.unwrap()),
|
||||||
|
quote_ident(StructureDialect::Mysql, name)
|
||||||
|
)
|
||||||
|
} else {
|
||||||
|
quote_ident(StructureDialect::Mysql, name)
|
||||||
|
};
|
||||||
|
format!("DROP TRIGGER {qualified_name};")
|
||||||
|
}
|
||||||
|
|
||||||
|
fn create_trigger_sql(table: &str, trigger: &EditableStructureTrigger, warnings: &mut Vec<String>) -> Option<String> {
|
||||||
|
let name = clean(&trigger.name);
|
||||||
|
let timing = normalize_keyword(&trigger.timing);
|
||||||
|
let event = normalize_keyword(&trigger.event);
|
||||||
|
let statement = clean(&trigger.statement);
|
||||||
|
|
||||||
|
if name.is_empty() || timing.is_empty() || event.is_empty() || statement.is_empty() {
|
||||||
|
warnings.push("Trigger name, timing, event, and statement are required.".to_string());
|
||||||
|
return None;
|
||||||
|
}
|
||||||
|
if !matches!(timing.as_str(), "BEFORE" | "AFTER") {
|
||||||
|
warnings.push(format!("Unsupported trigger timing \"{}\".", clean(&trigger.timing)));
|
||||||
|
return None;
|
||||||
|
}
|
||||||
|
if !matches!(event.as_str(), "INSERT" | "UPDATE" | "DELETE") {
|
||||||
|
warnings.push(format!("Unsupported trigger event \"{}\".", clean(&trigger.event)));
|
||||||
|
return None;
|
||||||
|
}
|
||||||
|
|
||||||
|
Some(format!(
|
||||||
|
"CREATE TRIGGER {} {timing} {event} ON {table} FOR EACH ROW\n{};",
|
||||||
|
quote_ident(StructureDialect::Mysql, &name),
|
||||||
|
statement.trim_end_matches(';').trim_end()
|
||||||
|
))
|
||||||
|
}
|
||||||
|
|
||||||
|
fn normalize_keyword(value: &str) -> String {
|
||||||
|
clean(value).to_ascii_uppercase()
|
||||||
|
}
|
||||||
|
|
||||||
|
fn normalize_statement(value: &str) -> String {
|
||||||
|
clean(value).trim_end_matches(';').trim().to_string()
|
||||||
|
}
|
||||||
@@ -105,6 +105,69 @@ pub struct IndexInfo {
|
|||||||
pub comment: Option<String>,
|
pub comment: Option<String>,
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
|
||||||
|
#[serde(rename_all = "camelCase")]
|
||||||
|
pub struct EditableStructureForeignKey {
|
||||||
|
pub id: String,
|
||||||
|
pub name: String,
|
||||||
|
#[serde(default)]
|
||||||
|
pub column: String,
|
||||||
|
#[serde(default)]
|
||||||
|
pub ref_schema: String,
|
||||||
|
#[serde(default)]
|
||||||
|
pub ref_table: String,
|
||||||
|
#[serde(default)]
|
||||||
|
pub ref_column: String,
|
||||||
|
#[serde(default)]
|
||||||
|
pub on_update: String,
|
||||||
|
#[serde(default)]
|
||||||
|
pub on_delete: String,
|
||||||
|
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||||
|
pub original: Option<ForeignKeyInfo>,
|
||||||
|
#[serde(default)]
|
||||||
|
pub marked_for_drop: bool,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
|
||||||
|
pub struct ForeignKeyInfo {
|
||||||
|
pub name: String,
|
||||||
|
pub column: String,
|
||||||
|
#[serde(default)]
|
||||||
|
pub ref_schema: Option<String>,
|
||||||
|
pub ref_table: String,
|
||||||
|
pub ref_column: String,
|
||||||
|
#[serde(default)]
|
||||||
|
pub on_update: Option<String>,
|
||||||
|
#[serde(default)]
|
||||||
|
pub on_delete: Option<String>,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
|
||||||
|
#[serde(rename_all = "camelCase")]
|
||||||
|
pub struct EditableStructureTrigger {
|
||||||
|
pub id: String,
|
||||||
|
pub name: String,
|
||||||
|
#[serde(default)]
|
||||||
|
pub timing: String,
|
||||||
|
#[serde(default)]
|
||||||
|
pub event: String,
|
||||||
|
#[serde(default)]
|
||||||
|
pub statement: String,
|
||||||
|
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||||
|
pub original: Option<TriggerInfo>,
|
||||||
|
#[serde(default)]
|
||||||
|
pub marked_for_drop: bool,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
|
||||||
|
pub struct TriggerInfo {
|
||||||
|
pub name: String,
|
||||||
|
pub event: String,
|
||||||
|
pub timing: String,
|
||||||
|
#[serde(default)]
|
||||||
|
pub statement: Option<String>,
|
||||||
|
}
|
||||||
|
|
||||||
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
|
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
|
||||||
#[serde(rename_all = "camelCase")]
|
#[serde(rename_all = "camelCase")]
|
||||||
pub struct TableStructureSqlOptions {
|
pub struct TableStructureSqlOptions {
|
||||||
@@ -117,6 +180,10 @@ pub struct TableStructureSqlOptions {
|
|||||||
pub columns: Vec<EditableStructureColumn>,
|
pub columns: Vec<EditableStructureColumn>,
|
||||||
#[serde(default)]
|
#[serde(default)]
|
||||||
pub indexes: Vec<EditableStructureIndex>,
|
pub indexes: Vec<EditableStructureIndex>,
|
||||||
|
#[serde(default)]
|
||||||
|
pub foreign_keys: Vec<EditableStructureForeignKey>,
|
||||||
|
#[serde(default)]
|
||||||
|
pub triggers: Vec<EditableStructureTrigger>,
|
||||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||||
pub table_comment: Option<String>,
|
pub table_comment: Option<String>,
|
||||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||||
|
|||||||
@@ -3545,6 +3545,8 @@ mod tests {
|
|||||||
ref_schema: None,
|
ref_schema: None,
|
||||||
ref_table: "users".to_string(),
|
ref_table: "users".to_string(),
|
||||||
ref_column: "id".to_string(),
|
ref_column: "id".to_string(),
|
||||||
|
on_update: None,
|
||||||
|
on_delete: None,
|
||||||
},
|
},
|
||||||
db::ForeignKeyInfo {
|
db::ForeignKeyInfo {
|
||||||
name: "orders_user_id_fkey".to_string(),
|
name: "orders_user_id_fkey".to_string(),
|
||||||
@@ -3552,6 +3554,8 @@ mod tests {
|
|||||||
ref_schema: None,
|
ref_schema: None,
|
||||||
ref_table: "users".to_string(),
|
ref_table: "users".to_string(),
|
||||||
ref_column: "tenant_id".to_string(),
|
ref_column: "tenant_id".to_string(),
|
||||||
|
on_update: None,
|
||||||
|
on_delete: None,
|
||||||
},
|
},
|
||||||
];
|
];
|
||||||
|
|
||||||
|
|||||||
@@ -102,6 +102,10 @@ pub struct ForeignKeyInfo {
|
|||||||
pub ref_schema: Option<String>,
|
pub ref_schema: Option<String>,
|
||||||
pub ref_table: String,
|
pub ref_table: String,
|
||||||
pub ref_column: String,
|
pub ref_column: String,
|
||||||
|
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||||
|
pub on_update: Option<String>,
|
||||||
|
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||||
|
pub on_delete: Option<String>,
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||||
@@ -109,4 +113,6 @@ pub struct TriggerInfo {
|
|||||||
pub name: String,
|
pub name: String,
|
||||||
pub event: String,
|
pub event: String,
|
||||||
pub timing: String,
|
pub timing: String,
|
||||||
|
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||||
|
pub statement: Option<String>,
|
||||||
}
|
}
|
||||||
@@ -1,6 +1,6 @@
|
|||||||
[package]
|
[package]
|
||||||
name = "dbx-web"
|
name = "dbx-web"
|
||||||
version = "0.5.31"
|
version = "0.5.32"
|
||||||
edition = "2021"
|
edition = "2021"
|
||||||
license = "Apache-2.0"
|
license = "Apache-2.0"
|
||||||
|
|
||||||
|
|||||||
+1
-1
@@ -1,6 +1,6 @@
|
|||||||
{
|
{
|
||||||
"name": "dbx",
|
"name": "dbx",
|
||||||
"version": "0.5.31",
|
"version": "0.5.32",
|
||||||
"private": true,
|
"private": true,
|
||||||
"license": "Apache-2.0",
|
"license": "Apache-2.0",
|
||||||
"type": "module",
|
"type": "module",
|
||||||
|
|||||||
@@ -1,7 +1,7 @@
|
|||||||
{
|
{
|
||||||
"id": "jdbc",
|
"id": "jdbc",
|
||||||
"name": "DBX JDBC Plugin",
|
"name": "DBX JDBC Plugin",
|
||||||
"version": "0.1.11",
|
"version": "0.1.12",
|
||||||
"protocol_version": 1,
|
"protocol_version": 1,
|
||||||
"description": "Adds optional JDBC driver support to DBX.",
|
"description": "Adds optional JDBC driver support to DBX.",
|
||||||
"executable": "bin/dbx-jdbc-plugin",
|
"executable": "bin/dbx-jdbc-plugin",
|
||||||
|
|||||||
@@ -4,7 +4,7 @@
|
|||||||
<modelVersion>4.0.0</modelVersion>
|
<modelVersion>4.0.0</modelVersion>
|
||||||
<groupId>app.dbx</groupId>
|
<groupId>app.dbx</groupId>
|
||||||
<artifactId>dbx-jdbc-plugin</artifactId>
|
<artifactId>dbx-jdbc-plugin</artifactId>
|
||||||
<version>0.1.11</version>
|
<version>0.1.12</version>
|
||||||
|
|
||||||
<properties>
|
<properties>
|
||||||
<maven.compiler.source>17</maven.compiler.source>
|
<maven.compiler.source>17</maven.compiler.source>
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
[package]
|
[package]
|
||||||
name = "dbx"
|
name = "dbx"
|
||||||
version = "0.5.31"
|
version = "0.5.32"
|
||||||
description = "Open-source database management tool"
|
description = "Open-source database management tool"
|
||||||
authors = ["skyler"]
|
authors = ["skyler"]
|
||||||
license = "Apache-2.0"
|
license = "Apache-2.0"
|
||||||
|
|||||||
@@ -1,7 +1,7 @@
|
|||||||
{
|
{
|
||||||
"$schema": "https://schema.tauri.app/config/2",
|
"$schema": "https://schema.tauri.app/config/2",
|
||||||
"productName": "DBX",
|
"productName": "DBX",
|
||||||
"version": "0.5.31",
|
"version": "0.5.32",
|
||||||
"identifier": "com.dbx.app",
|
"identifier": "com.dbx.app",
|
||||||
"build": {
|
"build": {
|
||||||
"frontendDist": "../dist",
|
"frontendDist": "../dist",
|
||||||
|
|||||||
Reference in new issue
Block a user