feat(sqlite): support table structure changes
This commit is contained in:
1 parent
f7eec00c8e
commit
fc8d407a62
25 files changed
+2320
-50
No files matched your search
@@ -156,6 +156,7 @@ import { useQueryStore } from "@/stores/queryStore";
|
|||||||
import { useSettingsStore } from "@/stores/settingsStore";
|
import { useSettingsStore } from "@/stores/settingsStore";
|
||||||
import type { DataGridSortDirection, DataGridSortMode } from "@/lib/dataGrid/dataGridSort";
|
import type { DataGridSortDirection, DataGridSortMode } from "@/lib/dataGrid/dataGridSort";
|
||||||
import { getTableMetadataCapabilities } from "@/lib/table/tableMetadataCapabilities";
|
import { getTableMetadataCapabilities } from "@/lib/table/tableMetadataCapabilities";
|
||||||
|
import { getTableStructureCapabilities } from "@/lib/table/tableStructureCapabilities";
|
||||||
import { supportsTableStructureEditing } from "@/lib/database/databaseCapabilities";
|
import { supportsTableStructureEditing } from "@/lib/database/databaseCapabilities";
|
||||||
import { forgetDataGridConditionHistory, loadDataGridConditionHistory, rememberDataGridConditionHistory } from "@/lib/dataGrid/dataGridConditionHistory";
|
import { forgetDataGridConditionHistory, loadDataGridConditionHistory, rememberDataGridConditionHistory } from "@/lib/dataGrid/dataGridConditionHistory";
|
||||||
import { getDataGridConditionSuggestionPosition } from "@/lib/dataGrid/dataGridConditionSuggestionPosition";
|
import { getDataGridConditionSuggestionPosition } from "@/lib/dataGrid/dataGridConditionSuggestionPosition";
|
||||||
@@ -346,7 +347,9 @@ const columnTypeMap = computed(() => {
|
|||||||
}
|
}
|
||||||
return map;
|
return map;
|
||||||
});
|
});
|
||||||
const resolvedDatabaseType = computed(() => props.databaseType ?? effectiveDatabaseTypeForConnection(connectionStore.getConfig(props.connectionId ?? "")));
|
const resolvedConnectionConfig = computed(() => connectionStore.getConfig(props.connectionId ?? ""));
|
||||||
|
const resolvedDatabaseType = computed(() => props.databaseType ?? effectiveDatabaseTypeForConnection(resolvedConnectionConfig.value));
|
||||||
|
const tableStructureCapabilities = computed(() => getTableStructureCapabilities(resolvedDatabaseType.value, resolvedConnectionConfig.value?.db_type));
|
||||||
|
|
||||||
const columnCommentMap = computed(() => {
|
const columnCommentMap = computed(() => {
|
||||||
const map = new Map<string, string>();
|
const map = new Map<string, string>();
|
||||||
@@ -7467,6 +7470,7 @@ async function copyHeaderColumn() {
|
|||||||
|
|
||||||
const canCopyAlterColumnSql = computed(() => {
|
const canCopyAlterColumnSql = computed(() => {
|
||||||
if (!contextHeaderColumn.value || !props.tableMeta?.columns) return false;
|
if (!contextHeaderColumn.value || !props.tableMeta?.columns) return false;
|
||||||
|
if (tableStructureCapabilities.value.alterStrategy !== "direct") return false;
|
||||||
return props.tableMeta.columns.some((c) => c.name.toLowerCase() === contextHeaderColumn.value!.toLowerCase());
|
return props.tableMeta.columns.some((c) => c.name.toLowerCase() === contextHeaderColumn.value!.toLowerCase());
|
||||||
});
|
});
|
||||||
|
|
||||||
@@ -7825,7 +7829,7 @@ function toggleCellDetailPanelLayout() {
|
|||||||
|
|
||||||
const tableMetadataCapabilities = computed(() => getTableMetadataCapabilities(props.databaseType));
|
const tableMetadataCapabilities = computed(() => getTableMetadataCapabilities(props.databaseType));
|
||||||
const canOpenTableStructureEditor = computed(() => !!props.connectionId && !!props.database && !!props.tableMeta?.tableName && supportsTableStructureEditing(resolvedDatabaseType.value));
|
const canOpenTableStructureEditor = computed(() => !!props.connectionId && !!props.database && !!props.tableMeta?.tableName && supportsTableStructureEditing(resolvedDatabaseType.value));
|
||||||
const mongoConnectionConfig = computed(() => connectionStore.getConfig(props.connectionId ?? ""));
|
const mongoConnectionConfig = resolvedConnectionConfig;
|
||||||
const canManageMongoIndexes = computed(() => resolvedDatabaseType.value === "mongodb" && !!props.connectionId && !!props.database && !!props.tableMeta?.tableName && mongoConnectionConfig.value?.db_type === "mongodb" && mongoConnectionConfig.value?.driver_profile !== "mongodb-legacy");
|
const canManageMongoIndexes = computed(() => resolvedDatabaseType.value === "mongodb" && !!props.connectionId && !!props.database && !!props.tableMeta?.tableName && mongoConnectionConfig.value?.db_type === "mongodb" && mongoConnectionConfig.value?.driver_profile !== "mongodb-legacy");
|
||||||
const tableInfoTabs = computed(() => {
|
const tableInfoTabs = computed(() => {
|
||||||
const tabs: TableInfoTabItem[] = [];
|
const tabs: TableInfoTabItem[] = [];
|
||||||
|
|||||||
@@ -23,7 +23,7 @@ import { copyToClipboard } from "@/lib/common/clipboard";
|
|||||||
import { formatSqlForDisplay, sqlFormatDialectForDbType } from "@/lib/sql/sqlFormatter";
|
import { formatSqlForDisplay, sqlFormatDialectForDbType } from "@/lib/sql/sqlFormatter";
|
||||||
import { queryTimeoutSecsForConnection } from "@/lib/sql/queryTimeout";
|
import { queryTimeoutSecsForConnection } from "@/lib/sql/queryTimeout";
|
||||||
import { safeLocalStorageGet, safeLocalStorageSet } from "@/lib/backend/safeStorage";
|
import { safeLocalStorageGet, safeLocalStorageSet } from "@/lib/backend/safeStorage";
|
||||||
import { type EditableStructureColumn, type EditableStructureForeignKey, type EditableStructureIndex, type EditableStructureTrigger } from "@/lib/table/tableStructureEditorSql";
|
import { type BuildTableStructureChangeSqlOptions, type EditableStructureColumn, type EditableStructureForeignKey, type EditableStructureIndex, type EditableStructureTrigger } from "@/lib/table/tableStructureEditorSql";
|
||||||
import { PRESET_FIELDS_TEMPLATE_ID, createTableColumnTemplateDrafts } from "@/lib/table/tableColumnTemplates";
|
import { PRESET_FIELDS_TEMPLATE_ID, createTableColumnTemplateDrafts } from "@/lib/table/tableColumnTemplates";
|
||||||
import { getTableMetadataCapabilities, firstStructureMetadataTab, isStructureMetadataTabSupported } from "@/lib/table/tableMetadataCapabilities";
|
import { getTableMetadataCapabilities, firstStructureMetadataTab, isStructureMetadataTabSupported } from "@/lib/table/tableMetadataCapabilities";
|
||||||
import { canAddTableStructureColumn, getTableStructureCapabilities } from "@/lib/table/tableStructureCapabilities";
|
import { canAddTableStructureColumn, getTableStructureCapabilities } from "@/lib/table/tableStructureCapabilities";
|
||||||
@@ -44,6 +44,7 @@ import {
|
|||||||
getColumnEditorControls,
|
getColumnEditorControls,
|
||||||
getDataTypeOptions,
|
getDataTypeOptions,
|
||||||
getDefaultLengthForType,
|
getDefaultLengthForType,
|
||||||
|
hasExistingColumnTypeChange,
|
||||||
isDataTypeLengthDisabled,
|
isDataTypeLengthDisabled,
|
||||||
isMysqlEnumDataType,
|
isMysqlEnumDataType,
|
||||||
isMysqlCharacterDataType,
|
isMysqlCharacterDataType,
|
||||||
@@ -151,6 +152,7 @@ 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 sqliteSchemaRevision = ref<string>();
|
||||||
const foreignKeys = ref<EditableStructureForeignKey[]>([]);
|
const foreignKeys = ref<EditableStructureForeignKey[]>([]);
|
||||||
const triggers = ref<EditableStructureTrigger[]>([]);
|
const triggers = ref<EditableStructureTrigger[]>([]);
|
||||||
const secondaryMetadataLoading = computed(() => indexesLoading.value || foreignKeysLoading.value || triggersLoading.value);
|
const secondaryMetadataLoading = computed(() => indexesLoading.value || foreignKeysLoading.value || triggersLoading.value);
|
||||||
@@ -591,7 +593,7 @@ function onIndexColResize(e: MouseEvent, col: number) {
|
|||||||
|
|
||||||
const connection = computed(() => (props.connectionId ? store.getConfig(props.connectionId) : undefined));
|
const connection = computed(() => (props.connectionId ? store.getConfig(props.connectionId) : undefined));
|
||||||
const databaseType = computed(() => tableStructureDatabaseTypeForConnection(connection.value));
|
const databaseType = computed(() => tableStructureDatabaseTypeForConnection(connection.value));
|
||||||
const structureCapabilities = computed(() => getTableStructureCapabilities(databaseType.value));
|
const structureCapabilities = computed(() => getTableStructureCapabilities(databaseType.value, connection.value?.db_type));
|
||||||
const tableMetadataCapabilities = computed(() => getTableMetadataCapabilities(databaseType.value));
|
const tableMetadataCapabilities = computed(() => getTableMetadataCapabilities(databaseType.value));
|
||||||
const structureDialect = computed(() => structureCapabilities.value.dialect);
|
const structureDialect = computed(() => structureCapabilities.value.dialect);
|
||||||
const isTableCommentDisabled = computed(() => !structureCapabilities.value.comment);
|
const isTableCommentDisabled = computed(() => !structureCapabilities.value.comment);
|
||||||
@@ -790,6 +792,8 @@ 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);
|
||||||
|
const usesSqliteRebuildStrategy = computed(() => !isCreateMode.value && structureCapabilities.value.alterStrategy === "sqlite-rebuild");
|
||||||
|
const hasSqliteTypeChange = computed(() => usesSqliteRebuildStrategy.value && hasExistingColumnTypeChange(columns.value));
|
||||||
const canAddColumn = computed(() => canAddTableStructureColumn(databaseType.value, isCreateMode.value));
|
const canAddColumn = computed(() => canAddTableStructureColumn(databaseType.value, isCreateMode.value));
|
||||||
const newTableName = ref("");
|
const newTableName = ref("");
|
||||||
const tableComment = ref("");
|
const tableComment = ref("");
|
||||||
@@ -977,6 +981,7 @@ function clearSqlPreviewState() {
|
|||||||
sqlPreviewLoading.value = false;
|
sqlPreviewLoading.value = false;
|
||||||
pendingStatements.value = [];
|
pendingStatements.value = [];
|
||||||
warnings.value = [];
|
warnings.value = [];
|
||||||
|
sqliteSchemaRevision.value = undefined;
|
||||||
}
|
}
|
||||||
|
|
||||||
function dataTypeOptionsCacheKey(connectionId: string, database: string) {
|
function dataTypeOptionsCacheKey(connectionId: string, database: string) {
|
||||||
@@ -1031,49 +1036,33 @@ async function loadDynamicDataTypeOptions() {
|
|||||||
}
|
}
|
||||||
|
|
||||||
function scheduleSqlPreviewRefresh() {
|
function scheduleSqlPreviewRefresh() {
|
||||||
if (hydratingRestoredDraft || needsColumnDraftMetadataHydration()) {
|
if (sqlPreviewDebounceTimer) {
|
||||||
if (sqlPreviewDebounceTimer) {
|
clearTimeout(sqlPreviewDebounceTimer);
|
||||||
clearTimeout(sqlPreviewDebounceTimer);
|
sqlPreviewDebounceTimer = undefined;
|
||||||
sqlPreviewDebounceTimer = undefined;
|
|
||||||
}
|
|
||||||
sqlPreviewRequestId++;
|
|
||||||
deferredSqlPreviewRefresh = false;
|
|
||||||
pendingStatements.value = [];
|
|
||||||
warnings.value = [];
|
|
||||||
sqlPreviewLoading.value = true;
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
if (!hasPendingStructureChanges()) {
|
|
||||||
clearSqlPreviewState();
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
if (!isCreateMode.value && secondaryMetadataLoading.value) {
|
|
||||||
if (sqlPreviewDebounceTimer) {
|
|
||||||
clearTimeout(sqlPreviewDebounceTimer);
|
|
||||||
sqlPreviewDebounceTimer = undefined;
|
|
||||||
}
|
|
||||||
deferredSqlPreviewRefresh = true;
|
|
||||||
sqlPreviewLoading.value = true;
|
|
||||||
return;
|
|
||||||
}
|
}
|
||||||
|
sqlPreviewRequestId++;
|
||||||
deferredSqlPreviewRefresh = false;
|
deferredSqlPreviewRefresh = false;
|
||||||
if (sqlPreviewDebounceTimer) clearTimeout(sqlPreviewDebounceTimer);
|
pendingStatements.value = [];
|
||||||
|
warnings.value = [];
|
||||||
|
sqliteSchemaRevision.value = undefined;
|
||||||
|
if (!hasPendingStructureChanges()) {
|
||||||
|
sqlPreviewLoading.value = false;
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
sqlPreviewLoading.value = true;
|
||||||
|
if (hydratingRestoredDraft || needsColumnDraftMetadataHydration()) return;
|
||||||
|
if (!isCreateMode.value && secondaryMetadataLoading.value) {
|
||||||
|
deferredSqlPreviewRefresh = true;
|
||||||
|
return;
|
||||||
|
}
|
||||||
sqlPreviewDebounceTimer = setTimeout(() => {
|
sqlPreviewDebounceTimer = setTimeout(() => {
|
||||||
sqlPreviewDebounceTimer = undefined;
|
sqlPreviewDebounceTimer = undefined;
|
||||||
void refreshSqlPreview();
|
void refreshSqlPreview();
|
||||||
}, 80);
|
}, 80);
|
||||||
}
|
}
|
||||||
|
|
||||||
async function refreshSqlPreview() {
|
function structureChangeOptions(): BuildTableStructureChangeSqlOptions {
|
||||||
const requestId = ++sqlPreviewRequestId;
|
return {
|
||||||
if (!hasPendingStructureChanges()) {
|
|
||||||
pendingStatements.value = [];
|
|
||||||
warnings.value = [];
|
|
||||||
sqlPreviewLoading.value = false;
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
sqlPreviewLoading.value = true;
|
|
||||||
const options = {
|
|
||||||
databaseType: databaseType.value,
|
databaseType: databaseType.value,
|
||||||
schema: props.schema,
|
schema: props.schema,
|
||||||
tableName: isCreateMode.value ? newTableName.value : props.tableName || "",
|
tableName: isCreateMode.value ? newTableName.value : props.tableName || "",
|
||||||
@@ -1084,22 +1073,47 @@ async function refreshSqlPreview() {
|
|||||||
tableComment: tableComment.value,
|
tableComment: tableComment.value,
|
||||||
originalTableComment: isCreateMode.value ? undefined : originalTableComment.value,
|
originalTableComment: isCreateMode.value ? undefined : originalTableComment.value,
|
||||||
};
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
async function refreshSqlPreview() {
|
||||||
|
const requestId = ++sqlPreviewRequestId;
|
||||||
|
if (!hasPendingStructureChanges()) {
|
||||||
|
pendingStatements.value = [];
|
||||||
|
warnings.value = [];
|
||||||
|
sqliteSchemaRevision.value = undefined;
|
||||||
|
sqlPreviewLoading.value = false;
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
sqlPreviewLoading.value = true;
|
||||||
|
const options = structureChangeOptions();
|
||||||
try {
|
try {
|
||||||
const result = isCreateMode.value ? await api.buildCreateTableSql(options) : await api.buildTableStructureChangeSql(options);
|
const result = isCreateMode.value ? await api.buildCreateTableSql(options) : hasSqliteTypeChange.value ? await api.previewSqliteTableStructureChange(props.connectionId, props.database, options) : await api.buildTableStructureChangeSql(options);
|
||||||
if (requestId !== sqlPreviewRequestId) return;
|
if (requestId !== sqlPreviewRequestId) return;
|
||||||
pendingStatements.value = result.statements;
|
pendingStatements.value = result.statements;
|
||||||
warnings.value = result.warnings;
|
warnings.value = result.warnings;
|
||||||
|
sqliteSchemaRevision.value = "schemaRevision" in result && typeof result.schemaRevision === "string" ? result.schemaRevision : undefined;
|
||||||
} catch (e: any) {
|
} catch (e: any) {
|
||||||
if (requestId !== sqlPreviewRequestId) return;
|
if (requestId !== sqlPreviewRequestId) return;
|
||||||
pendingStatements.value = [];
|
pendingStatements.value = [];
|
||||||
warnings.value = [e?.message || String(e)];
|
warnings.value = [e?.message || String(e)];
|
||||||
|
sqliteSchemaRevision.value = undefined;
|
||||||
} finally {
|
} finally {
|
||||||
if (requestId === sqlPreviewRequestId) sqlPreviewLoading.value = false;
|
if (requestId === sqlPreviewRequestId) sqlPreviewLoading.value = false;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
const canApply = computed(
|
const canApply = computed(
|
||||||
() => !loading.value && !saving.value && !postSaveRefreshing.value && !secondaryMetadataLoading.value && !sqlPreviewLoading.value && pendingStatements.value.length > 0 && warnings.value.length === 0 && !!props.connectionId && (isCreateMode.value ? !!newTableName.value.trim() : !!props.tableName),
|
() =>
|
||||||
|
!loading.value &&
|
||||||
|
!saving.value &&
|
||||||
|
!postSaveRefreshing.value &&
|
||||||
|
!secondaryMetadataLoading.value &&
|
||||||
|
!sqlPreviewLoading.value &&
|
||||||
|
pendingStatements.value.length > 0 &&
|
||||||
|
warnings.value.length === 0 &&
|
||||||
|
(!hasSqliteTypeChange.value || !!sqliteSchemaRevision.value) &&
|
||||||
|
!!props.connectionId &&
|
||||||
|
(isCreateMode.value ? !!newTableName.value.trim() : !!props.tableName),
|
||||||
);
|
);
|
||||||
|
|
||||||
function clearDraft() {
|
function clearDraft() {
|
||||||
@@ -1120,6 +1134,7 @@ function resetState() {
|
|||||||
indexes.value = [];
|
indexes.value = [];
|
||||||
pendingStatements.value = [];
|
pendingStatements.value = [];
|
||||||
warnings.value = [];
|
warnings.value = [];
|
||||||
|
sqliteSchemaRevision.value = undefined;
|
||||||
foreignKeys.value = [];
|
foreignKeys.value = [];
|
||||||
triggers.value = [];
|
triggers.value = [];
|
||||||
ddlContent.value = "";
|
ddlContent.value = "";
|
||||||
@@ -1965,7 +1980,7 @@ async function recordStructureHistory(sql: string, start: number, success: boole
|
|||||||
success,
|
success,
|
||||||
error,
|
error,
|
||||||
activity_kind: "schema_change",
|
activity_kind: "schema_change",
|
||||||
operation: primarySqlOperation(sql),
|
operation: hasSqliteTypeChange.value ? "ALTER TABLE" : primarySqlOperation(sql),
|
||||||
target: isCreateMode.value ? newTableName.value.trim() : props.tableName,
|
target: isCreateMode.value ? newTableName.value.trim() : props.tableName,
|
||||||
affected_rows: success ? result?.affected_rows : undefined,
|
affected_rows: success ? result?.affected_rows : undefined,
|
||||||
});
|
});
|
||||||
@@ -1998,12 +2013,14 @@ async function applyChanges() {
|
|||||||
const startedAt = Date.now();
|
const startedAt = Date.now();
|
||||||
try {
|
try {
|
||||||
const connection = store.getConfig(props.connectionId);
|
const connection = store.getConfig(props.connectionId);
|
||||||
const timeoutSecs = queryTimeoutSecsForConnection(connection);
|
const result = hasSqliteTypeChange.value
|
||||||
const result = await api.executeBatch(props.connectionId, props.database, pendingStatements.value, props.schema, timeoutSecs);
|
? await api.applySqliteTableStructureChange(props.connectionId, props.database, structureChangeOptions(), sqliteSchemaRevision.value!)
|
||||||
|
: await api.executeBatch(props.connectionId, props.database, pendingStatements.value, props.schema, queryTimeoutSecsForConnection(connection));
|
||||||
await recordStructureHistory(sql, startedAt, true, result);
|
await recordStructureHistory(sql, startedAt, true, result);
|
||||||
toast(t("structureEditor.saved"), 2500);
|
toast(t("structureEditor.saved"), 2500);
|
||||||
pendingStatements.value = [];
|
pendingStatements.value = [];
|
||||||
warnings.value = [];
|
warnings.value = [];
|
||||||
|
sqliteSchemaRevision.value = undefined;
|
||||||
ddlFetched.value = false;
|
ddlFetched.value = false;
|
||||||
ddlContent.value = "";
|
ddlContent.value = "";
|
||||||
if (isCreateMode.value) {
|
if (isCreateMode.value) {
|
||||||
@@ -2194,7 +2211,7 @@ watch([() => props.connectionId, () => props.database, databaseType], () => {
|
|||||||
});
|
});
|
||||||
|
|
||||||
watch(
|
watch(
|
||||||
[isCreateMode, databaseType, () => props.schema, () => props.tableName, newTableName, tableComment, columns, indexes, foreignKeys, triggers],
|
[isCreateMode, () => props.connectionId, () => props.database, databaseType, () => props.schema, () => props.tableName, newTableName, tableComment, columns, indexes, foreignKeys, triggers],
|
||||||
() => {
|
() => {
|
||||||
scheduleSqlPreviewRefresh();
|
scheduleSqlPreviewRefresh();
|
||||||
syncDraftToParent();
|
syncDraftToParent();
|
||||||
@@ -2955,6 +2972,10 @@ watch([activeTab, ddlLoading], ([tab, loading]) => {
|
|||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
<div v-if="!sqlPreviewCollapsed" class="min-h-0 flex-1 overflow-auto p-2.5">
|
<div v-if="!sqlPreviewCollapsed" class="min-h-0 flex-1 overflow-auto p-2.5">
|
||||||
|
<div v-if="hasSqliteTypeChange" class="mb-2 flex gap-1.5 rounded-md border border-blue-300/40 bg-blue-500/10 px-[var(--structure-cell-px)] py-[var(--structure-cell-py)] text-[length:var(--structure-font-size)] text-blue-700 dark:text-blue-300">
|
||||||
|
<Info :class="[structureIconClass, 'mt-0.5 shrink-0']" />
|
||||||
|
<span>{{ t("structureEditor.sqliteRebuildNotice") }}</span>
|
||||||
|
</div>
|
||||||
<div v-if="warnings.length" class="mb-2 space-y-1">
|
<div v-if="warnings.length" class="mb-2 space-y-1">
|
||||||
<div v-for="warning in warnings" :key="warning" class="flex gap-1.5 rounded-md border border-yellow-300/40 bg-yellow-500/10 px-[var(--structure-cell-px)] py-[var(--structure-cell-py)] text-[length:var(--structure-font-size)] text-yellow-700 dark:text-yellow-300">
|
<div v-for="warning in warnings" :key="warning" class="flex gap-1.5 rounded-md border border-yellow-300/40 bg-yellow-500/10 px-[var(--structure-cell-px)] py-[var(--structure-cell-py)] text-[length:var(--structure-font-size)] text-yellow-700 dark:text-yellow-300">
|
||||||
<AlertTriangle :class="[structureIconClass, 'mt-0.5 shrink-0']" />
|
<AlertTriangle :class="[structureIconClass, 'mt-0.5 shrink-0']" />
|
||||||
|
|||||||
@@ -0,0 +1,31 @@
|
|||||||
|
import { describe, expect, it as test } from "vitest";
|
||||||
|
import en from "@/i18n/locales/en";
|
||||||
|
import es from "@/i18n/locales/es";
|
||||||
|
import it from "@/i18n/locales/it";
|
||||||
|
import ja from "@/i18n/locales/ja";
|
||||||
|
import ptBR from "@/i18n/locales/pt-BR";
|
||||||
|
import zhCN from "@/i18n/locales/zh-CN";
|
||||||
|
import zhTW from "@/i18n/locales/zh-TW";
|
||||||
|
|
||||||
|
function sqliteRebuildNotice(messages: Record<string, unknown>): string {
|
||||||
|
const structureEditor = messages.structureEditor as Record<string, unknown>;
|
||||||
|
return String(structureEditor.sqliteRebuildNotice);
|
||||||
|
}
|
||||||
|
|
||||||
|
describe("SQLite rebuild notice", () => {
|
||||||
|
test.each([
|
||||||
|
["English", en],
|
||||||
|
["Spanish", es],
|
||||||
|
["Italian", it],
|
||||||
|
["Japanese", ja],
|
||||||
|
["Brazilian Portuguese", ptBR],
|
||||||
|
["Simplified Chinese", zhCN],
|
||||||
|
["Traditional Chinese", zhTW],
|
||||||
|
])("warns about retained backup, forced CAST conversion, lossy values, and rollback in %s", (_locale, messages) => {
|
||||||
|
const notice = sqliteRebuildNotice(messages);
|
||||||
|
|
||||||
|
expect(notice.length).toBeGreaterThan(30);
|
||||||
|
expect(notice).toContain("CAST");
|
||||||
|
expect(notice).toContain("0.0");
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -1894,6 +1894,7 @@ export default {
|
|||||||
ready: "Ready",
|
ready: "Ready",
|
||||||
saved: "Table structure updated",
|
saved: "Table structure updated",
|
||||||
copySql: "Copy SQL",
|
copySql: "Copy SQL",
|
||||||
|
sqliteRebuildNotice: "SQLite retains an inert data snapshot as a backup, then rebuilds the table in one transaction and forcibly CASTs changed columns. Unrepresentable values may become 0/0.0; failures roll back.",
|
||||||
extendedProperties: "Extended",
|
extendedProperties: "Extended",
|
||||||
autoIncrement: "Auto Increment",
|
autoIncrement: "Auto Increment",
|
||||||
onUpdateCurrentTimestamp: "Auto Update Time",
|
onUpdateCurrentTimestamp: "Auto Update Time",
|
||||||
|
|||||||
@@ -1820,6 +1820,7 @@ export default withEnglishFallback({
|
|||||||
ready: "Listo",
|
ready: "Listo",
|
||||||
saved: "Estructura de tabla actualizada",
|
saved: "Estructura de tabla actualizada",
|
||||||
copySql: "Copiar SQL",
|
copySql: "Copiar SQL",
|
||||||
|
sqliteRebuildNotice: "SQLite conserva una instantánea de datos inerte como copia de seguridad, reconstruye la tabla en una sola transacción y fuerza CAST en las columnas modificadas. Los valores no representables pueden convertirse en 0/0.0; si ocurre un error, se revierte todo.",
|
||||||
extendedProperties: "Extendido",
|
extendedProperties: "Extendido",
|
||||||
autoIncrement: "Auto Incremento",
|
autoIncrement: "Auto Incremento",
|
||||||
onUpdateCurrentTimestamp: "Actualización Auto",
|
onUpdateCurrentTimestamp: "Actualización Auto",
|
||||||
|
|||||||
@@ -1818,6 +1818,7 @@ export default withEnglishFallback({
|
|||||||
ready: "Pronto",
|
ready: "Pronto",
|
||||||
saved: "Struttura tabella aggiornata",
|
saved: "Struttura tabella aggiornata",
|
||||||
copySql: "Copia SQL",
|
copySql: "Copia SQL",
|
||||||
|
sqliteRebuildNotice: "SQLite conserva uno snapshot di dati inerte come backup, ricostruisce la tabella in un'unica transazione e forza CAST sulle colonne modificate. I valori non rappresentabili possono diventare 0/0.0; in caso di errore, tutte le modifiche vengono annullate.",
|
||||||
extendedProperties: "Esteso",
|
extendedProperties: "Esteso",
|
||||||
autoIncrement: "Auto Incremento",
|
autoIncrement: "Auto Incremento",
|
||||||
onUpdateCurrentTimestamp: "Aggiorna Ora Automaticamente",
|
onUpdateCurrentTimestamp: "Aggiorna Ora Automaticamente",
|
||||||
|
|||||||
@@ -1852,6 +1852,7 @@ export default withEnglishFallback({
|
|||||||
ready: "準備完了",
|
ready: "準備完了",
|
||||||
saved: "テーブル構造を更新しました",
|
saved: "テーブル構造を更新しました",
|
||||||
copySql: "SQLをコピー",
|
copySql: "SQLをコピー",
|
||||||
|
sqliteRebuildNotice: "SQLite は制約が動作しないデータスナップショットをバックアップとして保持し、1 つのトランザクション内でテーブルを再構築して、変更された列を CAST で強制変換します。表現できない値は 0/0.0 になる場合があり、失敗時はすべてロールバックされます。",
|
||||||
extendedProperties: "拡張",
|
extendedProperties: "拡張",
|
||||||
autoIncrement: "自動採番",
|
autoIncrement: "自動採番",
|
||||||
onUpdateCurrentTimestamp: "自動更新時刻",
|
onUpdateCurrentTimestamp: "自動更新時刻",
|
||||||
|
|||||||
@@ -1819,6 +1819,7 @@ export default withEnglishFallback({
|
|||||||
ready: "Pronto",
|
ready: "Pronto",
|
||||||
saved: "Estrutura da tabela atualizada",
|
saved: "Estrutura da tabela atualizada",
|
||||||
copySql: "Copiar SQL",
|
copySql: "Copiar SQL",
|
||||||
|
sqliteRebuildNotice: "O SQLite mantém um snapshot de dados inerte como backup, reconstrói a tabela em uma única transação e força CAST nas colunas alteradas. Valores não representáveis podem se tornar 0/0.0; em caso de falha, todas as alterações são revertidas.",
|
||||||
extendedProperties: "Estendidas",
|
extendedProperties: "Estendidas",
|
||||||
autoIncrement: "Auto incremento",
|
autoIncrement: "Auto incremento",
|
||||||
onUpdateCurrentTimestamp: "Atualizar hora automaticamente",
|
onUpdateCurrentTimestamp: "Atualizar hora automaticamente",
|
||||||
|
|||||||
@@ -1893,6 +1893,7 @@ export default withEnglishFallback({
|
|||||||
ready: "可执行",
|
ready: "可执行",
|
||||||
saved: "表结构已更新",
|
saved: "表结构已更新",
|
||||||
copySql: "复制 SQL",
|
copySql: "复制 SQL",
|
||||||
|
sqliteRebuildNotice: "SQLite 会保留一张不带活动约束的数据快照作为备份表,再在同一事务内重建原表,使用 CAST 强制转换类型已修改的字段;无法表示的值可能变为 0/0.0,执行失败则整体回滚。",
|
||||||
extendedProperties: "扩展属性",
|
extendedProperties: "扩展属性",
|
||||||
autoIncrement: "自增",
|
autoIncrement: "自增",
|
||||||
onUpdateCurrentTimestamp: "自动更新时间",
|
onUpdateCurrentTimestamp: "自动更新时间",
|
||||||
|
|||||||
@@ -1723,6 +1723,7 @@ export default withEnglishFallback({
|
|||||||
ready: "可執行",
|
ready: "可執行",
|
||||||
saved: "資料表結構已更新",
|
saved: "資料表結構已更新",
|
||||||
copySql: "複製 SQL",
|
copySql: "複製 SQL",
|
||||||
|
sqliteRebuildNotice: "SQLite 會保留一張不含作用中約束的資料快照作為備份表,再於同一交易內重建原表,並使用 CAST 強制轉換已修改型別的欄位;無法表示的值可能變成 0/0.0,執行失敗則整體回復。",
|
||||||
extendedProperties: "擴充屬性",
|
extendedProperties: "擴充屬性",
|
||||||
autoIncrement: "自動遞增",
|
autoIncrement: "自動遞增",
|
||||||
onUpdateCurrentTimestamp: "自動更新時間",
|
onUpdateCurrentTimestamp: "自動更新時間",
|
||||||
|
|||||||
@@ -0,0 +1,30 @@
|
|||||||
|
import { describe, expect, it } from "vitest";
|
||||||
|
import { getTableStructureCapabilities } from "@/lib/table/tableStructureCapabilities";
|
||||||
|
|
||||||
|
describe("tableStructureCapabilities", () => {
|
||||||
|
it("uses table rebuilds only for native SQLite connections", () => {
|
||||||
|
expect(getTableStructureCapabilities("sqlite", "sqlite")).toMatchObject({
|
||||||
|
alterStrategy: "sqlite-rebuild",
|
||||||
|
alterExistingColumn: true,
|
||||||
|
alterType: true,
|
||||||
|
});
|
||||||
|
|
||||||
|
for (const [databaseType, connectionType] of [
|
||||||
|
["rqlite", "rqlite"],
|
||||||
|
["turso", "turso"],
|
||||||
|
["sqlite", "jdbc"],
|
||||||
|
["sqlite", undefined],
|
||||||
|
] as const) {
|
||||||
|
expect(getTableStructureCapabilities(databaseType, connectionType)).toMatchObject({
|
||||||
|
alterStrategy: "none",
|
||||||
|
alterExistingColumn: false,
|
||||||
|
alterType: false,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
it("marks databases with native ALTER COLUMN support as direct", () => {
|
||||||
|
expect(getTableStructureCapabilities("mysql", "mysql").alterStrategy).toBe("direct");
|
||||||
|
expect(getTableStructureCapabilities("postgres", "postgres").alterStrategy).toBe("direct");
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -3,6 +3,8 @@ import {
|
|||||||
combineDataTypeForDatabase,
|
combineDataTypeForDatabase,
|
||||||
createColumnDrafts,
|
createColumnDrafts,
|
||||||
dataTypeLengthInputValue,
|
dataTypeLengthInputValue,
|
||||||
|
getDefaultLengthForType,
|
||||||
|
hasExistingColumnTypeChange,
|
||||||
isDataTypeLengthDisabled,
|
isDataTypeLengthDisabled,
|
||||||
isMysqlCharacterDataType,
|
isMysqlCharacterDataType,
|
||||||
isMysqlEnumDataType,
|
isMysqlEnumDataType,
|
||||||
@@ -96,6 +98,40 @@ describe("tableStructureEditorState", () => {
|
|||||||
expect(combineDataTypeForDatabase("mysql", "integer", "11")).toBe("integer(11)");
|
expect(combineDataTypeForDatabase("mysql", "integer", "11")).toBe("integer(11)");
|
||||||
});
|
});
|
||||||
|
|
||||||
|
it("does not add MySQL display lengths when choosing SQLite-family types", () => {
|
||||||
|
for (const databaseType of ["sqlite", "rqlite", "turso"] as const) {
|
||||||
|
expect(getDefaultLengthForType(databaseType, "integer")).toBe("");
|
||||||
|
expect(getDefaultLengthForType(databaseType, "real")).toBe("");
|
||||||
|
expect(combineDataTypeForDatabase(databaseType, "integer", getDefaultLengthForType(databaseType, "integer"))).toBe("integer");
|
||||||
|
}
|
||||||
|
|
||||||
|
expect(getDefaultLengthForType("mysql", "integer")).toBe("11");
|
||||||
|
});
|
||||||
|
|
||||||
|
it("requires a SQLite rebuild only for a retained existing column type change", () => {
|
||||||
|
const [column] = createColumnDrafts(
|
||||||
|
[
|
||||||
|
{
|
||||||
|
name: "status",
|
||||||
|
data_type: "integer",
|
||||||
|
is_nullable: false,
|
||||||
|
column_default: null,
|
||||||
|
is_primary_key: false,
|
||||||
|
extra: null,
|
||||||
|
},
|
||||||
|
],
|
||||||
|
"sqlite",
|
||||||
|
);
|
||||||
|
|
||||||
|
expect(hasExistingColumnTypeChange([column])).toBe(false);
|
||||||
|
column.name = "state";
|
||||||
|
expect(hasExistingColumnTypeChange([column])).toBe(false);
|
||||||
|
column.dataType = "text";
|
||||||
|
expect(hasExistingColumnTypeChange([column])).toBe(true);
|
||||||
|
column.markedForDrop = true;
|
||||||
|
expect(hasExistingColumnTypeChange([column])).toBe(false);
|
||||||
|
});
|
||||||
|
|
||||||
it("strips SQL Server metadata parentheses from editable defaults", () => {
|
it("strips SQL Server metadata parentheses from editable defaults", () => {
|
||||||
const drafts = createColumnDrafts(
|
const drafts = createColumnDrafts(
|
||||||
[
|
[
|
||||||
|
|||||||
@@ -185,6 +185,8 @@ export const buildEditableObjectSource = forward("buildEditableObjectSource");
|
|||||||
export const buildRoutineRenameObjectSourceStatements = forward("buildRoutineRenameObjectSourceStatements");
|
export const buildRoutineRenameObjectSourceStatements = forward("buildRoutineRenameObjectSourceStatements");
|
||||||
export const buildViewDdlSql = forward("buildViewDdlSql");
|
export const buildViewDdlSql = forward("buildViewDdlSql");
|
||||||
export const buildTableStructureChangeSql = forward("buildTableStructureChangeSql");
|
export const buildTableStructureChangeSql = forward("buildTableStructureChangeSql");
|
||||||
|
export const previewSqliteTableStructureChange = forward("previewSqliteTableStructureChange");
|
||||||
|
export const applySqliteTableStructureChange = forward("applySqliteTableStructureChange");
|
||||||
export const buildCreateTableSql = forward("buildCreateTableSql");
|
export const buildCreateTableSql = forward("buildCreateTableSql");
|
||||||
export const buildSingleColumnAlterSql = forward("buildSingleColumnAlterSql");
|
export const buildSingleColumnAlterSql = forward("buildSingleColumnAlterSql");
|
||||||
export const analyzeEditableQueryEditability = forward("analyzeEditableQueryEditability");
|
export const analyzeEditableQueryEditability = forward("analyzeEditableQueryEditability");
|
||||||
|
|||||||
@@ -112,7 +112,7 @@ import type {
|
|||||||
DataGridSaveStatementOptions,
|
DataGridSaveStatementOptions,
|
||||||
HiveTablePropertiesSqlOptions,
|
HiveTablePropertiesSqlOptions,
|
||||||
} from "@/lib/dataGrid/dataGridSql";
|
} from "@/lib/dataGrid/dataGridSql";
|
||||||
import type { BuildTableStructureChangeSqlOptions, BuildSingleColumnAlterSqlOptions, TableStructureChangeSql } from "@/lib/table/tableStructureEditorSql";
|
import type { BuildTableStructureChangeSqlOptions, BuildSingleColumnAlterSqlOptions, SqliteTableStructureChangePreview, TableStructureChangeSql } from "@/lib/table/tableStructureEditorSql";
|
||||||
import type { BuildTableSelectSqlOptions } from "@/lib/table/tableSelectSql";
|
import type { BuildTableSelectSqlOptions } from "@/lib/table/tableSelectSql";
|
||||||
import type { DatabaseSearchSql, DatabaseSearchSqlOptions, SearchResultWhereOptions } from "@/lib/database/databaseSearch";
|
import type { DatabaseSearchSql, DatabaseSearchSqlOptions, SearchResultWhereOptions } from "@/lib/database/databaseSearch";
|
||||||
import type { BuildEditableObjectSourceSqlInput, BuildRoutineRenameObjectSourceInput } from "@/lib/table/objectSourceEditor";
|
import type { BuildEditableObjectSourceSqlInput, BuildRoutineRenameObjectSourceInput } from "@/lib/table/objectSourceEditor";
|
||||||
@@ -855,6 +855,14 @@ export async function buildTableStructureChangeSql(options: BuildTableStructureC
|
|||||||
return post("/api/query/build-table-structure-change-sql", { options });
|
return post("/api/query/build-table-structure-change-sql", { options });
|
||||||
}
|
}
|
||||||
|
|
||||||
|
export async function previewSqliteTableStructureChange(connectionId: string, database: string, options: BuildTableStructureChangeSqlOptions): Promise<SqliteTableStructureChangePreview> {
|
||||||
|
return post("/api/query/preview-sqlite-table-structure-change", { connectionId, database, options });
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function applySqliteTableStructureChange(connectionId: string, database: string, options: BuildTableStructureChangeSqlOptions, schemaRevision: string): Promise<QueryResult> {
|
||||||
|
return post("/api/query/apply-sqlite-table-structure-change", { connectionId, database, options, schemaRevision });
|
||||||
|
}
|
||||||
|
|
||||||
export async function buildCreateTableSql(options: BuildTableStructureChangeSqlOptions): Promise<TableStructureChangeSql> {
|
export async function buildCreateTableSql(options: BuildTableStructureChangeSqlOptions): Promise<TableStructureChangeSql> {
|
||||||
return post("/api/query/build-create-table-sql", { options });
|
return post("/api/query/build-create-table-sql", { options });
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -52,7 +52,7 @@ import type {
|
|||||||
} from "@/lib/dataGrid/dataGridSql";
|
} from "@/lib/dataGrid/dataGridSql";
|
||||||
import type { DataCompareFromTablesOptions, DataCompareFromTablesPreparation, DataCompareSyncPlan, DataCompareSyncPlanOptions, DataComparePreparation, DataComparePreparationOptions } from "@/lib/dataGrid/dataCompare";
|
import type { DataCompareFromTablesOptions, DataCompareFromTablesPreparation, DataCompareSyncPlan, DataCompareSyncPlanOptions, DataComparePreparation, DataComparePreparationOptions } from "@/lib/dataGrid/dataCompare";
|
||||||
import type { SchemaDiffPreparation, SchemaDiffPreparationOptions, TableDiff, FunctionDiff, SequenceDiff, RuleDiff, OwnerDiff } from "@/lib/schema/schemaDiff";
|
import type { SchemaDiffPreparation, SchemaDiffPreparationOptions, TableDiff, FunctionDiff, SequenceDiff, RuleDiff, OwnerDiff } from "@/lib/schema/schemaDiff";
|
||||||
import type { BuildTableStructureChangeSqlOptions, BuildSingleColumnAlterSqlOptions, TableStructureChangeSql } from "@/lib/table/tableStructureEditorSql";
|
import type { BuildTableStructureChangeSqlOptions, BuildSingleColumnAlterSqlOptions, SqliteTableStructureChangePreview, TableStructureChangeSql } from "@/lib/table/tableStructureEditorSql";
|
||||||
import type { BuildTableSelectSqlOptions } from "@/lib/table/tableSelectSql";
|
import type { BuildTableSelectSqlOptions } from "@/lib/table/tableSelectSql";
|
||||||
import type { DatabaseSearchSql, DatabaseSearchSqlOptions, SearchResultWhereOptions } from "@/lib/database/databaseSearch";
|
import type { DatabaseSearchSql, DatabaseSearchSqlOptions, SearchResultWhereOptions } from "@/lib/database/databaseSearch";
|
||||||
import type { BuildEditableObjectSourceSqlInput, BuildRoutineRenameObjectSourceInput } from "@/lib/table/objectSourceEditor";
|
import type { BuildEditableObjectSourceSqlInput, BuildRoutineRenameObjectSourceInput } from "@/lib/table/objectSourceEditor";
|
||||||
@@ -946,6 +946,14 @@ export async function buildTableStructureChangeSql(options: BuildTableStructureC
|
|||||||
return invoke("build_table_structure_change_sql", { options });
|
return invoke("build_table_structure_change_sql", { options });
|
||||||
}
|
}
|
||||||
|
|
||||||
|
export async function previewSqliteTableStructureChange(connectionId: string, database: string, options: BuildTableStructureChangeSqlOptions): Promise<SqliteTableStructureChangePreview> {
|
||||||
|
return invoke("preview_sqlite_table_structure_change", { connectionId, database, options });
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function applySqliteTableStructureChange(connectionId: string, database: string, options: BuildTableStructureChangeSqlOptions, schemaRevision: string): Promise<QueryResult> {
|
||||||
|
return invoke("apply_sqlite_table_structure_change", { connectionId, database, options, schemaRevision });
|
||||||
|
}
|
||||||
|
|
||||||
export async function buildCreateTableSql(options: BuildTableStructureChangeSqlOptions): Promise<TableStructureChangeSql> {
|
export async function buildCreateTableSql(options: BuildTableStructureChangeSqlOptions): Promise<TableStructureChangeSql> {
|
||||||
return invoke("build_create_table_sql", { options });
|
return invoke("build_create_table_sql", { options });
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,9 +1,11 @@
|
|||||||
import type { DatabaseType } from "@/types/database";
|
import type { DatabaseType } from "@/types/database";
|
||||||
|
|
||||||
export type TableStructureDialect = "mysql" | "postgres" | "sqlite" | "duckdb" | "sqlserver" | "oracle" | "h2" | "clickhouse" | "informix" | "influxdb" | "unsupported";
|
export type TableStructureDialect = "mysql" | "postgres" | "sqlite" | "duckdb" | "sqlserver" | "oracle" | "h2" | "clickhouse" | "informix" | "influxdb" | "unsupported";
|
||||||
|
export type TableStructureAlterStrategy = "none" | "direct" | "sqlite-rebuild";
|
||||||
|
|
||||||
export interface TableStructureCapabilities {
|
export interface TableStructureCapabilities {
|
||||||
dialect: TableStructureDialect;
|
dialect: TableStructureDialect;
|
||||||
|
alterStrategy: TableStructureAlterStrategy;
|
||||||
createTable: boolean;
|
createTable: boolean;
|
||||||
addColumn: boolean;
|
addColumn: boolean;
|
||||||
dropColumn: boolean;
|
dropColumn: boolean;
|
||||||
@@ -27,6 +29,7 @@ export interface TableStructureCapabilities {
|
|||||||
|
|
||||||
const unsupportedCapabilities: TableStructureCapabilities = {
|
const unsupportedCapabilities: TableStructureCapabilities = {
|
||||||
dialect: "unsupported",
|
dialect: "unsupported",
|
||||||
|
alterStrategy: "none",
|
||||||
createTable: false,
|
createTable: false,
|
||||||
addColumn: false,
|
addColumn: false,
|
||||||
dropColumn: false,
|
dropColumn: false,
|
||||||
@@ -49,7 +52,11 @@ const unsupportedCapabilities: TableStructureCapabilities = {
|
|||||||
};
|
};
|
||||||
|
|
||||||
function capabilities(overrides: Partial<TableStructureCapabilities>): TableStructureCapabilities {
|
function capabilities(overrides: Partial<TableStructureCapabilities>): TableStructureCapabilities {
|
||||||
return { ...unsupportedCapabilities, ...overrides };
|
const resolved = { ...unsupportedCapabilities, ...overrides };
|
||||||
|
if (overrides.alterStrategy === undefined && resolved.alterExistingColumn) {
|
||||||
|
resolved.alterStrategy = "direct";
|
||||||
|
}
|
||||||
|
return resolved;
|
||||||
}
|
}
|
||||||
|
|
||||||
const mysqlCapabilities = capabilities({
|
const mysqlCapabilities = capabilities({
|
||||||
@@ -128,6 +135,13 @@ const sqliteCapabilities = capabilities({
|
|||||||
indexFilter: true,
|
indexFilter: true,
|
||||||
});
|
});
|
||||||
|
|
||||||
|
const nativeSqliteCapabilities = capabilities({
|
||||||
|
...sqliteCapabilities,
|
||||||
|
alterStrategy: "sqlite-rebuild",
|
||||||
|
alterExistingColumn: true,
|
||||||
|
alterType: true,
|
||||||
|
});
|
||||||
|
|
||||||
const duckdbCapabilities = capabilities({
|
const duckdbCapabilities = capabilities({
|
||||||
dialect: "duckdb",
|
dialect: "duckdb",
|
||||||
createTable: true,
|
createTable: true,
|
||||||
@@ -315,7 +329,8 @@ const capabilityByType: Partial<Record<DatabaseType, TableStructureCapabilities>
|
|||||||
manticoresearch: manticoreSearchCapabilities,
|
manticoresearch: manticoreSearchCapabilities,
|
||||||
};
|
};
|
||||||
|
|
||||||
export function getTableStructureCapabilities(dbType?: DatabaseType): TableStructureCapabilities {
|
export function getTableStructureCapabilities(dbType?: DatabaseType, connectionDbType?: DatabaseType): TableStructureCapabilities {
|
||||||
|
if (dbType === "sqlite" && connectionDbType === "sqlite") return nativeSqliteCapabilities;
|
||||||
return dbType ? (capabilityByType[dbType] ?? unsupportedCapabilities) : unsupportedCapabilities;
|
return dbType ? (capabilityByType[dbType] ?? unsupportedCapabilities) : unsupportedCapabilities;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -88,6 +88,10 @@ export interface TableStructureChangeSql {
|
|||||||
warnings: string[];
|
warnings: string[];
|
||||||
}
|
}
|
||||||
|
|
||||||
|
export interface SqliteTableStructureChangePreview extends TableStructureChangeSql {
|
||||||
|
schemaRevision: string;
|
||||||
|
}
|
||||||
|
|
||||||
export interface BuildSingleColumnAlterSqlOptions {
|
export interface BuildSingleColumnAlterSqlOptions {
|
||||||
databaseType?: DatabaseType;
|
databaseType?: DatabaseType;
|
||||||
schema?: string;
|
schema?: string;
|
||||||
|
|||||||
@@ -1,6 +1,10 @@
|
|||||||
import type { ColumnInfo, DatabaseType, ForeignKeyInfo, IndexInfo, TriggerInfo } from "@/types/database.ts";
|
import type { ColumnInfo, DatabaseType, ForeignKeyInfo, IndexInfo, TriggerInfo } from "@/types/database.ts";
|
||||||
import type { ColumnExtra, EditableStructureColumn, EditableStructureForeignKey, EditableStructureIndex, EditableStructureTrigger } from "@/lib/table/tableStructureEditorSql.ts";
|
import type { ColumnExtra, EditableStructureColumn, EditableStructureForeignKey, EditableStructureIndex, EditableStructureTrigger } from "@/lib/table/tableStructureEditorSql.ts";
|
||||||
|
|
||||||
|
export function hasExistingColumnTypeChange(columns: readonly EditableStructureColumn[]): boolean {
|
||||||
|
return columns.some((column) => !!column.original && !column.markedForDrop && column.dataType !== column.original.data_type);
|
||||||
|
}
|
||||||
|
|
||||||
export const DATA_TYPE_OPTIONS: Record<string, string[]> = {
|
export const DATA_TYPE_OPTIONS: Record<string, string[]> = {
|
||||||
mysql: [
|
mysql: [
|
||||||
"tinyint",
|
"tinyint",
|
||||||
@@ -938,7 +942,9 @@ function isValidTemporalPrecision(dbType: DatabaseType | undefined, params: stri
|
|||||||
|
|
||||||
export function getDefaultLengthForType(_dbType: DatabaseType | undefined, baseType: string): string {
|
export function getDefaultLengthForType(_dbType: DatabaseType | undefined, baseType: string): string {
|
||||||
const key = baseType.trim().toLowerCase();
|
const key = baseType.trim().toLowerCase();
|
||||||
if (_dbType === "questdb") {
|
if (_dbType === "sqlite" || _dbType === "rqlite" || _dbType === "turso") {
|
||||||
|
return "";
|
||||||
|
} else if (_dbType === "questdb") {
|
||||||
return QUESTDB_TYPE_LENGTHS[key] ?? "";
|
return QUESTDB_TYPE_LENGTHS[key] ?? "";
|
||||||
} else if (_dbType === "sqlserver") {
|
} else if (_dbType === "sqlserver") {
|
||||||
return SQLSERVER_TYPE_LENGTHS[key] ?? "";
|
return SQLSERVER_TYPE_LENGTHS[key] ?? "";
|
||||||
|
|||||||
@@ -6,6 +6,7 @@ mod create_table;
|
|||||||
mod dialect;
|
mod dialect;
|
||||||
mod foreign_keys;
|
mod foreign_keys;
|
||||||
mod indexes;
|
mod indexes;
|
||||||
|
mod sqlite_rebuild;
|
||||||
mod triggers;
|
mod triggers;
|
||||||
mod types;
|
mod types;
|
||||||
mod util;
|
mod util;
|
||||||
@@ -16,6 +17,7 @@ mod tests;
|
|||||||
|
|
||||||
pub use column_alter::build_single_column_alter_sql;
|
pub use column_alter::build_single_column_alter_sql;
|
||||||
pub use create_table::build_create_table_sql;
|
pub use create_table::build_create_table_sql;
|
||||||
|
pub use sqlite_rebuild::{apply_sqlite_table_structure_change, preview_sqlite_table_structure_change};
|
||||||
pub use types::*;
|
pub use types::*;
|
||||||
|
|
||||||
use columns::build_column_sql;
|
use columns::build_column_sql;
|
||||||
|
|||||||
File diff suppressed because it is too large.
Load diff
@@ -213,6 +213,14 @@ pub struct TableStructureSqlResult {
|
|||||||
pub warnings: Vec<String>,
|
pub warnings: Vec<String>,
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
|
||||||
|
#[serde(rename_all = "camelCase")]
|
||||||
|
pub struct SqliteTableStructurePreview {
|
||||||
|
pub statements: Vec<String>,
|
||||||
|
pub warnings: Vec<String>,
|
||||||
|
pub schema_revision: String,
|
||||||
|
}
|
||||||
|
|
||||||
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
|
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
|
||||||
#[serde(rename_all = "camelCase")]
|
#[serde(rename_all = "camelCase")]
|
||||||
pub struct SingleColumnAlterSqlOptions {
|
pub struct SingleColumnAlterSqlOptions {
|
||||||
|
|||||||
@@ -352,6 +352,11 @@ async fn main() {
|
|||||||
)
|
)
|
||||||
.route("/query/build-view-ddl-sql", post(routes::query::build_view_ddl_sql))
|
.route("/query/build-view-ddl-sql", post(routes::query::build_view_ddl_sql))
|
||||||
.route("/query/build-table-structure-change-sql", post(routes::query::build_table_structure_change_sql))
|
.route("/query/build-table-structure-change-sql", post(routes::query::build_table_structure_change_sql))
|
||||||
|
.route(
|
||||||
|
"/query/preview-sqlite-table-structure-change",
|
||||||
|
post(routes::query::preview_sqlite_table_structure_change),
|
||||||
|
)
|
||||||
|
.route("/query/apply-sqlite-table-structure-change", post(routes::query::apply_sqlite_table_structure_change))
|
||||||
.route("/query/build-create-table-sql", post(routes::query::build_create_table_sql))
|
.route("/query/build-create-table-sql", post(routes::query::build_create_table_sql))
|
||||||
.route("/query/build-single-column-alter-sql", post(routes::query::build_single_column_alter_sql))
|
.route("/query/build-single-column-alter-sql", post(routes::query::build_single_column_alter_sql))
|
||||||
.route("/query/analyze-editability", post(routes::query::analyze_editable_query_editability))
|
.route("/query/analyze-editability", post(routes::query::analyze_editable_query_editability))
|
||||||
|
|||||||
@@ -211,6 +211,23 @@ pub struct BuildTableStructureSqlRequest {
|
|||||||
pub options: dbx_core::table_structure_sql::TableStructureSqlOptions,
|
pub options: dbx_core::table_structure_sql::TableStructureSqlOptions,
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[derive(Deserialize)]
|
||||||
|
#[serde(rename_all = "camelCase")]
|
||||||
|
pub struct PreviewSqliteTableStructureChangeRequest {
|
||||||
|
pub connection_id: String,
|
||||||
|
pub database: String,
|
||||||
|
pub options: dbx_core::table_structure_sql::TableStructureSqlOptions,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Deserialize)]
|
||||||
|
#[serde(rename_all = "camelCase")]
|
||||||
|
pub struct ApplySqliteTableStructureChangeRequest {
|
||||||
|
pub connection_id: String,
|
||||||
|
pub database: String,
|
||||||
|
pub options: dbx_core::table_structure_sql::TableStructureSqlOptions,
|
||||||
|
pub schema_revision: String,
|
||||||
|
}
|
||||||
|
|
||||||
#[derive(Deserialize)]
|
#[derive(Deserialize)]
|
||||||
#[serde(rename_all = "camelCase")]
|
#[serde(rename_all = "camelCase")]
|
||||||
pub struct BuildSingleColumnAlterSqlRequest {
|
pub struct BuildSingleColumnAlterSqlRequest {
|
||||||
@@ -651,6 +668,37 @@ pub async fn build_table_structure_change_sql(
|
|||||||
Json(dbx_core::table_structure_sql::build_table_structure_change_sql(req.options))
|
Json(dbx_core::table_structure_sql::build_table_structure_change_sql(req.options))
|
||||||
}
|
}
|
||||||
|
|
||||||
|
pub async fn preview_sqlite_table_structure_change(
|
||||||
|
State(state): State<Arc<WebState>>,
|
||||||
|
Json(req): Json<PreviewSqliteTableStructureChangeRequest>,
|
||||||
|
) -> Result<Json<dbx_core::table_structure_sql::SqliteTableStructurePreview>, AppError> {
|
||||||
|
dbx_core::table_structure_sql::preview_sqlite_table_structure_change(
|
||||||
|
&state.app,
|
||||||
|
&req.connection_id,
|
||||||
|
&req.database,
|
||||||
|
req.options,
|
||||||
|
)
|
||||||
|
.await
|
||||||
|
.map(Json)
|
||||||
|
.map_err(AppError)
|
||||||
|
}
|
||||||
|
|
||||||
|
pub async fn apply_sqlite_table_structure_change(
|
||||||
|
State(state): State<Arc<WebState>>,
|
||||||
|
Json(req): Json<ApplySqliteTableStructureChangeRequest>,
|
||||||
|
) -> Result<Json<dbx_core::db::QueryResult>, AppError> {
|
||||||
|
dbx_core::table_structure_sql::apply_sqlite_table_structure_change(
|
||||||
|
&state.app,
|
||||||
|
&req.connection_id,
|
||||||
|
&req.database,
|
||||||
|
req.options,
|
||||||
|
&req.schema_revision,
|
||||||
|
)
|
||||||
|
.await
|
||||||
|
.map(Json)
|
||||||
|
.map_err(AppError)
|
||||||
|
}
|
||||||
|
|
||||||
pub async fn build_create_table_sql(
|
pub async fn build_create_table_sql(
|
||||||
Json(req): Json<BuildTableStructureSqlRequest>,
|
Json(req): Json<BuildTableStructureSqlRequest>,
|
||||||
) -> Json<dbx_core::table_structure_sql::TableStructureSqlResult> {
|
) -> Json<dbx_core::table_structure_sql::TableStructureSqlResult> {
|
||||||
|
|||||||
@@ -445,6 +445,35 @@ pub fn build_table_structure_change_sql(
|
|||||||
Ok(dbx_core::table_structure_sql::build_table_structure_change_sql(options))
|
Ok(dbx_core::table_structure_sql::build_table_structure_change_sql(options))
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[tauri::command]
|
||||||
|
pub async fn preview_sqlite_table_structure_change(
|
||||||
|
state: State<'_, Arc<AppState>>,
|
||||||
|
connection_id: String,
|
||||||
|
database: String,
|
||||||
|
options: dbx_core::table_structure_sql::TableStructureSqlOptions,
|
||||||
|
) -> Result<dbx_core::table_structure_sql::SqliteTableStructurePreview, String> {
|
||||||
|
dbx_core::table_structure_sql::preview_sqlite_table_structure_change(&state, &connection_id, &database, options)
|
||||||
|
.await
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tauri::command]
|
||||||
|
pub async fn apply_sqlite_table_structure_change(
|
||||||
|
state: State<'_, Arc<AppState>>,
|
||||||
|
connection_id: String,
|
||||||
|
database: String,
|
||||||
|
options: dbx_core::table_structure_sql::TableStructureSqlOptions,
|
||||||
|
schema_revision: String,
|
||||||
|
) -> Result<db::QueryResult, String> {
|
||||||
|
dbx_core::table_structure_sql::apply_sqlite_table_structure_change(
|
||||||
|
&state,
|
||||||
|
&connection_id,
|
||||||
|
&database,
|
||||||
|
options,
|
||||||
|
&schema_revision,
|
||||||
|
)
|
||||||
|
.await
|
||||||
|
}
|
||||||
|
|
||||||
#[tauri::command]
|
#[tauri::command]
|
||||||
pub fn build_create_table_sql(
|
pub fn build_create_table_sql(
|
||||||
options: dbx_core::table_structure_sql::TableStructureSqlOptions,
|
options: dbx_core::table_structure_sql::TableStructureSqlOptions,
|
||||||
|
|||||||
@@ -905,6 +905,8 @@ pub fn run() {
|
|||||||
commands::query::build_routine_rename_object_source_statements,
|
commands::query::build_routine_rename_object_source_statements,
|
||||||
commands::query::build_view_ddl_sql,
|
commands::query::build_view_ddl_sql,
|
||||||
commands::query::build_table_structure_change_sql,
|
commands::query::build_table_structure_change_sql,
|
||||||
|
commands::query::preview_sqlite_table_structure_change,
|
||||||
|
commands::query::apply_sqlite_table_structure_change,
|
||||||
commands::query::build_create_table_sql,
|
commands::query::build_create_table_sql,
|
||||||
commands::query::build_single_column_alter_sql,
|
commands::query::build_single_column_alter_sql,
|
||||||
commands::query::analyze_editable_query_editability,
|
commands::query::analyze_editable_query_editability,
|
||||||
|
|||||||
Reference in new issue
Block a user