Skip to content

armgit / dbx

Public Imported from GitHub
0

25 MB lightweight cross-platform database client for 100+ databases, including MySQL, PostgreSQL, SQLite, Redis, MongoDB, DuckDB, SQL Server, and Dameng. Built-in AI, MCP Server, CLI, desktop and Docker. | 轻量级跨平台数据库管理工具,支持 MySQL、PostgreSQL、SQLite、Redis、MongoDB、达梦等 100+ 数据库,提供桌面端、Docker、CLI、内置 AI 助手和 MCP。

feat(import): create table during data import

t8y27155992e0496
diff --git a/apps/desktop/src/components/import/TableImportDialog.vue b/apps/desktop/src/components/import/TableImportDialog.vue
index ceed827515..cc384afc36 100644
--- a/apps/desktop/src/components/import/TableImportDialog.vue
+++ b/apps/desktop/src/components/import/TableImportDialog.vue
@@ -27,8 +27,12 @@ const props = defineProps<{
prefillTable?: string;
}>();
+type ImportTargetMode = "existing" | "create";
+
const SKIP_VALUE = "__skip__";
const targetColumns = ref<ColumnInfo[]>([]);
+const targetMode = ref<ImportTargetMode>(props.prefillTable ? "existing" : "create");
+const newTableName = ref("");
const selectedSource = ref<string | File | null>(null);
const sourceFormat = ref<api.TableImportSourceFormat>("csv");
const preview = ref<api.TableImportPreview | null>(null);
@@ -70,6 +74,8 @@ const wizardSteps: Array<{ value: TableImportWizardStep; labelKey: string }> = [
];
const selectedConnection = computed(() => (props.prefillConnectionId ? store.getConfig(props.prefillConnectionId) : undefined));
+const hasExistingTarget = computed(() => !!props.prefillTable);
+const targetTableName = computed(() => (targetMode.value === "create" ? newTableName.value.trim() : props.prefillTable || ""));
const targetColumnNames = computed(() => targetColumns.value.map((column) => column.name));
const mappedColumns = computed<api.TableImportColumnMapping[]>(() => {
const currentPreview = preview.value;
@@ -89,11 +95,11 @@ const requiredUnmappedColumns = computed(() =>
mappedColumns.value.map((mapping) => mapping.targetColumn),
),
);
-const canImport = computed(() => !!preview.value && !!props.prefillConnectionId && !!props.prefillTable && mappingValidation.value.valid && !running.value);
+const canImport = computed(() => !!preview.value && !!props.prefillConnectionId && !!targetTableName.value && mappingValidation.value.valid && !running.value);
const canGoBack = computed(() => wizardStep.value !== "source" && wizardStep.value !== "execution" && !running.value);
const canGoNext = computed(() => {
if (wizardStep.value === "source") return !!selectedSource.value && !!sourceFormat.value;
- if (wizardStep.value === "options") return !!preview.value;
+ if (wizardStep.value === "options") return !!preview.value && !!targetTableName.value;
if (wizardStep.value === "mapping") return mappingValidation.value.valid;
return false;
});
@@ -104,7 +110,7 @@ const progressPercent = computed(() => {
});
const currentStepIndex = computed(() => wizardSteps.findIndex((step) => step.value === wizardStep.value));
const targetLabel = computed(() => {
- const pieces = [selectedConnection.value?.name, props.prefillDatabase, props.prefillSchema, props.prefillTable].filter(Boolean);
+ const pieces = [selectedConnection.value?.name, props.prefillDatabase, props.prefillSchema, targetTableName.value].filter(Boolean);
return pieces.join(" / ");
});
const selectedSourceName = computed(() => {
@@ -124,6 +130,8 @@ const terminalStatus = computed(() => progress.value?.status && ["done", "error"
function resetState() {
targetColumns.value = [];
+ targetMode.value = props.prefillTable ? "existing" : "create";
+ newTableName.value = "";
selectedSource.value = null;
sourceFormat.value = "csv";
delimiter.value = ",";
@@ -154,14 +162,24 @@ function detectFormat(name: string): api.TableImportSourceFormat {
return "csv";
}
+function suggestedTableName(name: string) {
+ const baseName = name.split(/[\\/]/).pop() || name;
+ const withoutExtension = baseName.replace(/\.[^.]+$/, "").trim();
+ return withoutExtension.replace(/[\s-]+/g, "_") || "imported_data";
+}
+
function applyAutoMapping() {
const currentPreview = preview.value;
if (!currentPreview) return;
+ if (targetMode.value === "create") {
+ columnMapping.value = Object.fromEntries(currentPreview.columns.map((source) => [source, source]));
+ return;
+ }
columnMapping.value = autoMapImportColumns(currentPreview.columns, targetColumnNames.value);
}
async function loadTargetColumns() {
- if (!props.prefillConnectionId || !props.prefillDatabase || !props.prefillTable) return;
+ if (targetMode.value !== "existing" || !props.prefillConnectionId || !props.prefillDatabase || !props.prefillTable) return;
loadingTarget.value = true;
errorMessage.value = "";
try {
@@ -211,6 +229,9 @@ function assignSelectedSource(source: string | File) {
errorMessage.value = "";
const name = typeof source === "string" ? source : source.name;
sourceFormat.value = detectFormat(name);
+ if (!newTableName.value.trim()) {
+ newTableName.value = suggestedTableName(name);
+ }
delimiter.value = sourceFormat.value === "tsv" ? "\\t" : ",";
selectedSheet.value = "";
wizardStep.value = "options";
@@ -308,7 +329,8 @@ async function goNext() {
async function startImport() {
const currentPreview = preview.value;
- if (!canImport.value || !currentPreview || !props.prefillConnectionId || !props.prefillTable) return;
+ const tableName = targetTableName.value;
+ if (!canImport.value || !currentPreview || !props.prefillConnectionId || !tableName) return;
running.value = true;
cancelling.value = false;
errorMessage.value = "";
@@ -328,13 +350,14 @@ async function startImport() {
connectionId: props.prefillConnectionId,
database: props.prefillDatabase || "",
schema: props.prefillSchema || "",
- table: props.prefillTable,
+ table: tableName,
filePath: currentPreview.filePath,
sourceRef: currentPreview.sourceRef || null,
sourceFormat: sourceFormat.value,
parseOptions: parseOptions.value,
mappings: mappedColumns.value,
- mode: importMode.value,
+ mode: targetMode.value === "create" ? "append" : importMode.value,
+ createTable: targetMode.value === "create",
batchSize: Math.max(1, Number(batchSize.value) || 500),
},
(nextProgress) => {
@@ -343,7 +366,12 @@ async function startImport() {
);
progress.value = { importId: summary.importId, status: "done", rowsImported: summary.rowsImported, totalRows: summary.totalRows };
toast(t("tableImport.success", { count: summary.rowsImported }), 2500);
- store.invalidateMetadataCache(props.prefillConnectionId, props.prefillDatabase || "", props.prefillSchema || undefined, props.prefillTable);
+ store.invalidateMetadataCache(props.prefillConnectionId, props.prefillDatabase || "", props.prefillSchema || undefined, tableName);
+ if (targetMode.value === "create") {
+ store.refreshObjectListTreeNode(props.prefillConnectionId, props.prefillDatabase || "", props.prefillSchema || undefined).catch((error) => {
+ console.warn("[DBX][table-import:refresh-created-table-failed]", error);
+ });
+ }
} catch (e: any) {
const message = String(e?.message || e);
errorMessage.value = message;
@@ -386,6 +414,15 @@ watch(
);
watch([sourceFormat, delimiter, hasHeader, trimValues, emptyStringAsNull, selectedSheet, jsonShape, previewLimit], schedulePreviewReload);
+watch(targetMode, (mode) => {
+ if (mode === "existing") {
+ void loadTargetColumns();
+ } else {
+ targetColumns.value = [];
+ importMode.value = "append";
+ applyAutoMapping();
+ }
+});
</script>
<template>
@@ -482,6 +519,29 @@ watch([sourceFormat, delimiter, hasHeader, trimValues, emptyStringAsNull, select
</div>
</div>
+ <div class="grid grid-cols-[minmax(0,1fr)_minmax(220px,320px)] gap-3 rounded-md border p-3">
+ <div class="space-y-1.5">
+ <Label class="text-xs">{{ t("tableImport.targetMode") }}</Label>
+ <div class="grid grid-cols-2 gap-2">
+ <button type="button" class="rounded-md border px-3 py-2 text-left text-xs" :class="targetMode === 'existing' ? 'border-primary bg-primary/5' : 'hover:bg-muted/30'" :disabled="!hasExistingTarget" @click="targetMode = 'existing'">
+ <div class="font-medium">{{ t("tableImport.existingTable") }}</div>
+ <div class="mt-1 truncate text-[11px] text-muted-foreground">{{ props.prefillTable || t("tableImport.noExistingTarget") }}</div>
+ </button>
+ <button type="button" class="rounded-md border px-3 py-2 text-left text-xs" :class="targetMode === 'create' ? 'border-primary bg-primary/5' : 'hover:bg-muted/30'" @click="targetMode = 'create'">
+ <div class="font-medium">{{ t("tableImport.createTable") }}</div>
+ <div class="mt-1 text-[11px] text-muted-foreground">{{ t("tableImport.createTableHint") }}</div>
+ </button>
+ </div>
+ </div>
+ <div class="space-y-1.5">
+ <Label class="text-xs">{{ t("tableImport.targetTableName") }}</Label>
+ <Input v-if="targetMode === 'create'" v-model="newTableName" class="h-8 text-xs font-mono" />
+ <div v-else class="flex h-8 items-center rounded-md border px-2 text-xs">
+ <span class="truncate">{{ props.prefillTable }}</span>
+ </div>
+ </div>
+ </div>
+
<div v-if="sourceFormat === 'csv' || sourceFormat === 'tsv' || sourceFormat === 'delimited'" class="grid grid-cols-4 gap-3 rounded-md border p-3">
<div class="space-y-1.5">
<Label class="text-xs">{{ t("tableImport.delimiter") }}</Label>
@@ -569,7 +629,8 @@ watch([sourceFormat, delimiter, hasHeader, trimValues, emptyStringAsNull, select
<div class="truncate font-mono text-xs" :title="sourceColumn">
{{ sourceColumn }}
</div>
- <Select :model-value="columnMapping[sourceColumn] || SKIP_VALUE" @update:model-value="(value: any) => updateMapping(sourceColumn, value)">
+ <Input v-if="targetMode === 'create'" :model-value="columnMapping[sourceColumn] ?? sourceColumn" class="h-7 text-xs font-mono" @update:model-value="(value: any) => updateMapping(sourceColumn, value)" />
+ <Select v-else :model-value="columnMapping[sourceColumn] || SKIP_VALUE" @update:model-value="(value: any) => updateMapping(sourceColumn, value)">
<SelectTrigger class="h-7 text-xs">
<SelectValue />
</SelectTrigger>
@@ -636,7 +697,7 @@ watch([sourceFormat, delimiter, hasHeader, trimValues, emptyStringAsNull, select
</div>
</div>
<div class="grid grid-cols-3 gap-3">
- <div class="space-y-1.5">
+ <div v-if="targetMode === 'existing'" class="space-y-1.5">
<Label class="text-xs">{{ t("tableImport.mode") }}</Label>
<Select :model-value="importMode" @update:model-value="(value: any) => (importMode = value)">
<SelectTrigger class="h-8 text-xs">
diff --git a/apps/desktop/src/components/sidebar/TreeItem.vue b/apps/desktop/src/components/sidebar/TreeItem.vue
index e8d91dad45..e17c8392c6 100644
--- a/apps/desktop/src/components/sidebar/TreeItem.vue
+++ b/apps/desktop/src/components/sidebar/TreeItem.vue
@@ -3762,12 +3762,12 @@ function openAllDatabasesExport() {
function openTableImport() {
const node = props.node;
- if (node.type !== "table" || !node.connectionId || !node.database) return;
+ if (!node.connectionId || !node.database) return;
connectionStore.tableImportSource = {
connectionId: node.connectionId,
database: node.database,
schema: node.schema,
- tableName: node.label,
+ tableName: node.type === "table" ? node.label : undefined,
};
}
@@ -3829,7 +3829,9 @@ const canOpenObjectBrowser = computed(() => {
return supportsObjectBrowserTreeNode(rawDatabaseType(), props.node.type);
});
const canOpenTableImport = computed(() => {
- return props.node.type === "table" && !isSqlServerLinkedNode(props.node) && !!props.node.database && supportsTableImport(currentDatabaseType());
+ const node = props.node;
+ const supportedNode = node.type === "table" || ((node.type === "database" || node.type === "schema" || node.type === "group-tables") && canCreateTable.value);
+ return supportedNode && !isSqlServerLinkedNode(node) && !!node.connectionId && !!node.database && supportsTableImport(currentDatabaseType());
});
const canOpenStructureEditor = computed(() => {
const editableNode = props.node.type === "table" || ((props.node.type === "column" || props.node.type === "index") && !!props.node.tableName);
@@ -4502,6 +4504,9 @@ function treeItemMenuItems(): ContextMenuItem[] {
if (canCreateTable.value) {
items.push({ label: t("contextMenu.createTable"), action: createTable, icon: Plus });
}
+ if (canOpenTableImport.value) {
+ items.push({ label: t("contextMenu.importData"), action: openTableImport, icon: Upload });
+ }
if (canCreateSchema.value) {
items.push({ label: t("contextMenu.createSchema"), action: openCreateSchemaDialog, icon: Plus });
}
@@ -4874,6 +4879,9 @@ function treeItemMenuItems(): ContextMenuItem[] {
const canLoadAllObjectGroup = node.type === "group-tables" || node.type === "group-views" || node.type === "group-materialized-views";
if (node.type === "group-tables" && canCreateTable.value) {
items.push({ label: t("contextMenu.createTable"), action: createTable, icon: Plus });
+ if (canOpenTableImport.value) {
+ items.push({ label: t("contextMenu.importData"), action: openTableImport, icon: Upload });
+ }
if (canPasteTreeClipboardToCurrentNode()) {
items.push({ label: t("contextMenu.pasteTable"), action: openPasteTableDialog, icon: Clipboard });
}
diff --git a/apps/desktop/src/composables/useDialogSources.ts b/apps/desktop/src/composables/useDialogSources.ts
index 3822b102d4..ab2068049f 100644
--- a/apps/desktop/src/composables/useDialogSources.ts
+++ b/apps/desktop/src/composables/useDialogSources.ts
@@ -142,7 +142,7 @@ export function useDialogSources() {
tableImportPrefillConnectionId.value = v.connectionId;
tableImportPrefillDatabase.value = v.database;
tableImportPrefillSchema.value = v.schema ?? "";
- tableImportPrefillTable.value = v.tableName;
+ tableImportPrefillTable.value = v.tableName ?? "";
showTableImportDialog.value = true;
connectionStore.tableImportSource = null;
}
diff --git a/apps/desktop/src/i18n/locales/en.ts b/apps/desktop/src/i18n/locales/en.ts
index 25025c41bd..78b8e298fb 100644
--- a/apps/desktop/src/i18n/locales/en.ts
+++ b/apps/desktop/src/i18n/locales/en.ts
@@ -2215,6 +2215,12 @@ export default {
noFileSelected: "No file selected",
sourceFile: "Source file",
sourceFormat: "Source format",
+ targetMode: "Target",
+ existingTable: "Existing table",
+ createTable: "Create table",
+ createTableHint: "Infer columns from the file",
+ targetTableName: "Table name",
+ noExistingTarget: "No table selected",
stepSource: "Source",
stepOptions: "Options",
stepMapping: "Mapping",
diff --git a/apps/desktop/src/i18n/locales/zh-CN.ts b/apps/desktop/src/i18n/locales/zh-CN.ts
index 39b7379e2d..b698c80f43 100644
--- a/apps/desktop/src/i18n/locales/zh-CN.ts
+++ b/apps/desktop/src/i18n/locales/zh-CN.ts
@@ -2215,6 +2215,12 @@ export default withEnglishFallback({
noFileSelected: "未选择文件",
sourceFile: "源文件",
sourceFormat: "源格式",
+ targetMode: "目标",
+ existingTable: "现有表",
+ createTable: "创建新表",
+ createTableHint: "根据文件推断字段",
+ targetTableName: "表名",
+ noExistingTarget: "未选择表",
stepSource: "来源",
stepOptions: "选项",
stepMapping: "映射",
diff --git a/apps/desktop/src/lib/backend/tauri.ts b/apps/desktop/src/lib/backend/tauri.ts
index cbbb2a5165..292a63d2b1 100644
--- a/apps/desktop/src/lib/backend/tauri.ts
+++ b/apps/desktop/src/lib/backend/tauri.ts
@@ -1964,6 +1964,7 @@ export interface TableImportRequest {
parseOptions?: TableImportParseOptions | null;
mappings: TableImportColumnMapping[];
mode: TableImportMode;
+ createTable?: boolean;
batchSize: number;
}
diff --git a/apps/desktop/src/stores/connectionStore.ts b/apps/desktop/src/stores/connectionStore.ts
index a67eb1432e..6e448f834d 100644
--- a/apps/desktop/src/stores/connectionStore.ts
+++ b/apps/desktop/src/stores/connectionStore.ts
@@ -262,7 +262,7 @@ export const useConnectionStore = defineStore("connection", () => {
connectionId: string;
database: string;
schema?: string;
- tableName: string;
+ tableName?: string;
} | null>(null);
const tableDataGenerateSource = ref<{
connectionId: string;
diff --git a/crates/dbx-core/src/table_import.rs b/crates/dbx-core/src/table_import.rs
index 680a6a6f17..49b0e65ff2 100644
--- a/crates/dbx-core/src/table_import.rs
+++ b/crates/dbx-core/src/table_import.rs
@@ -3,14 +3,18 @@ use std::fs::File;
use std::path::Path;
use calamine::{open_workbook_auto, Data, Reader};
+use chrono::{DateTime, NaiveDate, NaiveDateTime};
use serde::{Deserialize, Serialize};
use crate::connection::AppState;
use crate::models::connection::DatabaseType;
-use crate::transfer::{execute_on_pool, generate_insert_typed, get_columns_for_transfer, qualified_table};
+use crate::transfer::{
+ execute_on_pool, generate_insert_typed, get_columns_for_transfer, qualified_table, quote_identifier,
+};
pub const DEFAULT_PREVIEW_LIMIT: usize = 50;
pub const DEFAULT_BATCH_SIZE: usize = 500;
+pub const CREATE_TABLE_INFERENCE_ROWS: usize = 100;
pub const MAX_NON_STREAMING_IMPORT_BYTES: u64 = 100 * 1024 * 1024;
#[derive(Debug, Clone)]
@@ -26,6 +30,18 @@ pub struct ImportSqlBatch {
pub row_count: usize,
}
+#[derive(Debug, Clone, PartialEq, Eq)]
+pub struct ImportCreateTableColumn {
+ pub name: String,
+ pub data_type: String,
+}
+
+#[derive(Debug, Clone, PartialEq, Eq)]
+pub struct ImportCreateTablePlan {
+ pub sql: String,
+ pub columns: Vec<ImportCreateTableColumn>,
+}
+
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct TableImportColumnMapping {
@@ -131,6 +147,8 @@ pub struct TableImportRequest {
pub parse_options: TableImportParseOptions,
pub mappings: Vec<TableImportColumnMapping>,
pub mode: TableImportMode,
+ #[serde(default)]
+ pub create_table: bool,
pub batch_size: usize,
}
@@ -790,6 +808,241 @@ pub fn truncate_sql(table: &str, schema: &str, db_type: &DatabaseType) -> String
}
}
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+enum ImportInferredType {
+ Boolean,
+ Integer,
+ Decimal,
+ Date,
+ Timestamp,
+ Json,
+ Text,
+}
+
+fn merge_inferred_type(current: Option<ImportInferredType>, next: ImportInferredType) -> ImportInferredType {
+ let Some(current) = current else {
+ return next;
+ };
+ if current == next {
+ return current;
+ }
+ match (current, next) {
+ (ImportInferredType::Text, _) | (_, ImportInferredType::Text) => ImportInferredType::Text,
+ (ImportInferredType::Integer, ImportInferredType::Decimal)
+ | (ImportInferredType::Decimal, ImportInferredType::Integer) => ImportInferredType::Decimal,
+ (ImportInferredType::Date, ImportInferredType::Timestamp)
+ | (ImportInferredType::Timestamp, ImportInferredType::Date) => ImportInferredType::Timestamp,
+ _ => ImportInferredType::Text,
+ }
+}
+
+fn has_numeric_leading_zero(value: &str) -> bool {
+ let unsigned = value.trim_start_matches(['+', '-']);
+ let bytes = unsigned.as_bytes();
+ bytes.len() > 1 && bytes[0] == b'0' && bytes[1].is_ascii_digit()
+}
+
+fn is_likely_date(value: &str) -> bool {
+ ["%Y-%m-%d", "%Y/%m/%d"].iter().any(|format| NaiveDate::parse_from_str(value, format).is_ok())
+}
+
+fn is_likely_timestamp(value: &str) -> bool {
+ if DateTime::parse_from_rfc3339(value).is_ok() {
+ return true;
+ }
+ ["%Y-%m-%d %H:%M:%S%.f", "%Y-%m-%dT%H:%M:%S%.f", "%Y/%m/%d %H:%M:%S%.f", "%Y/%m/%dT%H:%M:%S%.f"]
+ .iter()
+ .any(|format| NaiveDateTime::parse_from_str(value, format).is_ok())
+}
+
+fn infer_string_type(value: &str) -> ImportInferredType {
+ let value = value.trim();
+ if value.is_empty() {
+ return ImportInferredType::Text;
+ }
+ if is_likely_timestamp(value) {
+ return ImportInferredType::Timestamp;
+ }
+ if is_likely_date(value) {
+ return ImportInferredType::Date;
+ }
+ if !has_numeric_leading_zero(value) {
+ if value.parse::<i64>().is_ok() || value.parse::<u64>().is_ok() {
+ return ImportInferredType::Integer;
+ }
+ if (value.contains('.') || value.contains('e') || value.contains('E'))
+ && value.parse::<f64>().is_ok_and(|number| number.is_finite())
+ {
+ return ImportInferredType::Decimal;
+ }
+ }
+ ImportInferredType::Text
+}
+
+fn infer_value_type(value: &serde_json::Value) -> Option<ImportInferredType> {
+ match value {
+ serde_json::Value::Null => None,
+ serde_json::Value::Bool(_) => Some(ImportInferredType::Boolean),
+ serde_json::Value::Number(number) => {
+ if number.is_i64() || number.is_u64() {
+ Some(ImportInferredType::Integer)
+ } else {
+ Some(ImportInferredType::Decimal)
+ }
+ }
+ serde_json::Value::String(value) => Some(infer_string_type(value)),
+ serde_json::Value::Array(_) | serde_json::Value::Object(_) => Some(ImportInferredType::Json),
+ }
+}
+
+fn infer_column_type(rows: &[Vec<serde_json::Value>], source_index: usize) -> ImportInferredType {
+ let mut inferred = None;
+ for row in rows {
+ let Some(value_type) = row.get(source_index).and_then(infer_value_type) else {
+ continue;
+ };
+ inferred = Some(merge_inferred_type(inferred, value_type));
+ if inferred == Some(ImportInferredType::Text) {
+ break;
+ }
+ }
+ inferred.unwrap_or(ImportInferredType::Text)
+}
+
+fn text_data_type(db_type: &DatabaseType) -> &'static str {
+ match db_type {
+ DatabaseType::SqlServer => "NVARCHAR(MAX)",
+ DatabaseType::Oracle | DatabaseType::OceanbaseOracle | DatabaseType::Dameng => "CLOB",
+ DatabaseType::ClickHouse => "String",
+ DatabaseType::Hive | DatabaseType::Trino | DatabaseType::PrestoSql | DatabaseType::Databricks => "STRING",
+ _ => "TEXT",
+ }
+}
+
+fn integer_data_type(db_type: &DatabaseType) -> &'static str {
+ match db_type {
+ DatabaseType::Sqlite | DatabaseType::Rqlite | DatabaseType::Turso => "INTEGER",
+ DatabaseType::Oracle | DatabaseType::OceanbaseOracle | DatabaseType::Dameng => "NUMBER(19)",
+ DatabaseType::ClickHouse => "Int64",
+ _ => "BIGINT",
+ }
+}
+
+fn decimal_data_type(db_type: &DatabaseType) -> &'static str {
+ match db_type {
+ DatabaseType::Postgres
+ | DatabaseType::Gaussdb
+ | DatabaseType::OpenGauss
+ | DatabaseType::Redshift
+ | DatabaseType::Kingbase
+ | DatabaseType::Highgo
+ | DatabaseType::Kwdb
+ | DatabaseType::Vastbase => "DOUBLE PRECISION",
+ DatabaseType::Sqlite | DatabaseType::Rqlite | DatabaseType::Turso => "REAL",
+ DatabaseType::Oracle | DatabaseType::OceanbaseOracle | DatabaseType::Dameng => "BINARY_DOUBLE",
+ DatabaseType::ClickHouse => "Float64",
+ _ => "DOUBLE",
+ }
+}
+
+fn boolean_data_type(db_type: &DatabaseType) -> &'static str {
+ match db_type {
+ DatabaseType::Mysql
+ | DatabaseType::Doris
+ | DatabaseType::StarRocks
+ | DatabaseType::Goldendb
+ | DatabaseType::Sundb
+ | DatabaseType::Databend => "TINYINT(1)",
+ DatabaseType::SqlServer => "BIT",
+ DatabaseType::Sqlite | DatabaseType::Rqlite | DatabaseType::Turso => "INTEGER",
+ DatabaseType::Oracle | DatabaseType::OceanbaseOracle | DatabaseType::Dameng => "NUMBER(1)",
+ DatabaseType::ClickHouse => "UInt8",
+ _ => "BOOLEAN",
+ }
+}
+
+fn date_data_type(db_type: &DatabaseType) -> &'static str {
+ match db_type {
+ DatabaseType::Sqlite | DatabaseType::Rqlite | DatabaseType::Turso => "TEXT",
+ DatabaseType::ClickHouse => "Date",
+ _ => "DATE",
+ }
+}
+
+fn timestamp_data_type(db_type: &DatabaseType) -> &'static str {
+ match db_type {
+ DatabaseType::Mysql
+ | DatabaseType::Doris
+ | DatabaseType::StarRocks
+ | DatabaseType::Goldendb
+ | DatabaseType::Sundb
+ | DatabaseType::Databend => "DATETIME",
+ DatabaseType::SqlServer => "DATETIME2",
+ DatabaseType::Sqlite | DatabaseType::Rqlite | DatabaseType::Turso => "TEXT",
+ DatabaseType::ClickHouse => "DateTime64",
+ _ => "TIMESTAMP",
+ }
+}
+
+fn json_data_type(db_type: &DatabaseType) -> &'static str {
+ match db_type {
+ DatabaseType::Postgres
+ | DatabaseType::Gaussdb
+ | DatabaseType::OpenGauss
+ | DatabaseType::Kingbase
+ | DatabaseType::Highgo
+ | DatabaseType::Kwdb
+ | DatabaseType::Vastbase => "JSONB",
+ DatabaseType::Mysql | DatabaseType::Databend => "JSON",
+ _ => text_data_type(db_type),
+ }
+}
+
+fn import_data_type(inferred_type: ImportInferredType, db_type: &DatabaseType) -> String {
+ match inferred_type {
+ ImportInferredType::Boolean => boolean_data_type(db_type),
+ ImportInferredType::Integer => integer_data_type(db_type),
+ ImportInferredType::Decimal => decimal_data_type(db_type),
+ ImportInferredType::Date => date_data_type(db_type),
+ ImportInferredType::Timestamp => timestamp_data_type(db_type),
+ ImportInferredType::Json => json_data_type(db_type),
+ ImportInferredType::Text => text_data_type(db_type),
+ }
+ .to_string()
+}
+
+pub fn build_import_create_table_plan(
+ data: &ParsedImportFile,
+ mappings: &[TableImportColumnMapping],
+ table: &str,
+ schema: &str,
+ db_type: &DatabaseType,
+) -> Result<ImportCreateTablePlan, String> {
+ if table.trim().is_empty() {
+ return Err("Target table name is required".to_string());
+ }
+ let mapped = mapping_indexes(data, mappings)?;
+ let mut columns = Vec::with_capacity(mapped.len());
+ for (source_index, target_column) in mapped {
+ let inferred_type = infer_column_type(&data.rows, source_index);
+ columns
+ .push(ImportCreateTableColumn { name: target_column, data_type: import_data_type(inferred_type, db_type) });
+ }
+ if columns.is_empty() {
+ return Err("No columns mapped for import".to_string());
+ }
+
+ let full_table = qualified_table(table.trim(), schema, db_type);
+ let column_sql = columns
+ .iter()
+ .map(|column| format!("{} {}", quote_identifier(&column.name, db_type), column.data_type))
+ .collect::<Vec<_>>()
+ .join(",\n ");
+ let engine_clause =
+ if matches!(db_type, DatabaseType::ClickHouse) { " ENGINE = MergeTree() ORDER BY tuple()" } else { "" };
+ Ok(ImportCreateTablePlan { sql: format!("CREATE TABLE {full_table} (\n {column_sql}\n){engine_clause}"), columns })
+}
+
fn import_error_message(request: &TableImportRequest, rows_imported: usize, error: impl AsRef<str>) -> String {
format!("Import into table '{}' failed after {} imported rows: {}", request.table, rows_imported, error.as_ref())
}
@@ -937,8 +1190,58 @@ where
));
}
+ let mut create_table_sample: Option<ParsedImportFile> = None;
+ let mut created_column_types: Option<Vec<(String, String)>> = None;
+ if request.create_table {
+ if matches!(request.mode, TableImportMode::Truncate) {
+ return Err(emit_import_error(
+ &mut progress_callback,
+ request,
+ 0,
+ 0,
+ "Cannot truncate a table that is being created by the import",
+ ));
+ }
+ let parsed = match parse_import_file_with_options(
+ &request.file_path,
+ Some(source_format),
+ &request.parse_options,
+ CREATE_TABLE_INFERENCE_ROWS,
+ )
+ .await
+ {
+ Ok(parsed) => parsed,
+ Err(error) => {
+ return Err(emit_import_error(&mut progress_callback, request, 0, 0, error));
+ }
+ };
+ let total_rows = parsed.total_rows;
+ let plan = match build_import_create_table_plan(
+ &parsed,
+ &request.mappings,
+ &request.table,
+ &request.schema,
+ db_type,
+ ) {
+ Ok(plan) => plan,
+ Err(error) => {
+ return Err(emit_import_error(&mut progress_callback, request, 0, total_rows, error));
+ }
+ };
+ // The table must be created before streaming rows so existing import batching
+ // can reuse the same INSERT path and database-specific value escaping.
+ if let Err(error) = execute_on_pool(state, pool_key, &plan.sql).await {
+ return Err(emit_import_error(&mut progress_callback, request, 0, total_rows, error));
+ }
+ created_column_types =
+ Some(plan.columns.iter().map(|column| (column.name.clone(), column.data_type.clone())).collect());
+ create_table_sample = Some(parsed);
+ }
+
if source_format.is_delimited() {
- let parsed =
+ let parsed = if let Some(parsed) = create_table_sample.clone() {
+ parsed
+ } else {
match parse_import_file_with_options(&request.file_path, Some(source_format), &request.parse_options, 0)
.await
{
@@ -946,7 +1249,8 @@ where
Err(error) => {
return Err(emit_import_error(&mut progress_callback, request, 0, 0, error));
}
- };
+ }
+ };
let total_rows = parsed.total_rows;
if let Err(error) = mapping_indexes_for_columns(&parsed.columns, &request.mappings) {
return Err(emit_import_error(&mut progress_callback, request, 0, total_rows, error));
@@ -960,7 +1264,7 @@ where
error: None,
});
- let target_column_types = get_columns_for_transfer(
+ let mut target_column_types = get_columns_for_transfer(
state,
pool_key,
&request.connection_id,
@@ -973,6 +1277,9 @@ where
.into_iter()
.map(|column| (column.name, column.data_type))
.collect::<Vec<_>>();
+ if target_column_types.is_empty() {
+ target_column_types = created_column_types.clone().unwrap_or_default();
+ }
if matches!(request.mode, TableImportMode::Truncate) {
let sql = truncate_sql(&request.table, &request.schema, db_type);
@@ -1154,7 +1461,7 @@ where
error: None,
});
- let target_column_types = get_columns_for_transfer(
+ let mut target_column_types = get_columns_for_transfer(
state,
pool_key,
&request.connection_id,
@@ -1167,6 +1474,9 @@ where
.into_iter()
.map(|column| (column.name, column.data_type))
.collect::<Vec<_>>();
+ if target_column_types.is_empty() {
+ target_column_types = created_column_types.clone().unwrap_or_default();
+ }
let batches = match build_import_insert_batches(
&parsed,
@@ -1350,6 +1660,90 @@ mod tests {
let _ = std::fs::remove_file(path);
}
+ #[test]
+ fn builds_create_table_plan_from_import_sample() {
+ let data = ParsedImportFile {
+ columns: vec![
+ "id".to_string(),
+ "code".to_string(),
+ "amount".to_string(),
+ "created_at".to_string(),
+ "active".to_string(),
+ "payload".to_string(),
+ ],
+ rows: vec![
+ vec![
+ serde_json::json!("1"),
+ serde_json::json!("00123"),
+ serde_json::json!("12.5"),
+ serde_json::json!("2026-07-06 12:30:45"),
+ serde_json::json!("true"),
+ serde_json::json!({ "source": "csv" }),
+ ],
+ vec![
+ serde_json::json!("2"),
+ serde_json::json!("00456"),
+ serde_json::json!("13.75"),
+ serde_json::json!("2026-07-07 08:15:00"),
+ serde_json::json!("false"),
+ serde_json::json!({ "source": "json" }),
+ ],
+ ],
+ total_rows: 2,
+ };
+ let mappings = data
+ .columns
+ .iter()
+ .map(|column| TableImportColumnMapping { source_column: column.clone(), target_column: column.clone() })
+ .collect::<Vec<_>>();
+
+ let plan =
+ build_import_create_table_plan(&data, &mappings, "orders", "public", &DatabaseType::Postgres).unwrap();
+
+ assert_eq!(
+ plan.sql,
+ "CREATE TABLE \"public\".\"orders\" (\n \"id\" BIGINT,\n \"code\" TEXT,\n \"amount\" DOUBLE PRECISION,\n \"created_at\" TIMESTAMP,\n \"active\" TEXT,\n \"payload\" JSONB\n)"
+ );
+ assert_eq!(
+ plan.columns,
+ vec![
+ ImportCreateTableColumn { name: "id".to_string(), data_type: "BIGINT".to_string() },
+ ImportCreateTableColumn { name: "code".to_string(), data_type: "TEXT".to_string() },
+ ImportCreateTableColumn { name: "amount".to_string(), data_type: "DOUBLE PRECISION".to_string() },
+ ImportCreateTableColumn { name: "created_at".to_string(), data_type: "TIMESTAMP".to_string() },
+ ImportCreateTableColumn { name: "active".to_string(), data_type: "TEXT".to_string() },
+ ImportCreateTableColumn { name: "payload".to_string(), data_type: "JSONB".to_string() },
+ ]
+ );
+ }
+
+ #[test]
+ fn create_table_plan_requires_target_table_name() {
+ let data =
+ ParsedImportFile { columns: vec!["id".to_string()], rows: vec![vec![serde_json::json!(1)]], total_rows: 1 };
+ let mappings =
+ vec![TableImportColumnMapping { source_column: "id".to_string(), target_column: "id".to_string() }];
+
+ let error = build_import_create_table_plan(&data, &mappings, " ", "", &DatabaseType::Mysql).unwrap_err();
+
+ assert_eq!(error, "Target table name is required");
+ }
+
+ #[test]
+ fn create_table_plan_uses_database_specific_text_type() {
+ let data = ParsedImportFile {
+ columns: vec!["notes".to_string()],
+ rows: vec![vec![serde_json::json!("long text")]],
+ total_rows: 1,
+ };
+ let mappings =
+ vec![TableImportColumnMapping { source_column: "notes".to_string(), target_column: "notes".to_string() }];
+
+ let plan = build_import_create_table_plan(&data, &mappings, "events", "dbo", &DatabaseType::SqlServer).unwrap();
+
+ assert_eq!(plan.sql, "CREATE TABLE [dbo].[events] (\n [notes] NVARCHAR(MAX)\n)");
+ }
+
#[test]
fn builds_import_insert_batches_from_mapped_columns() {
let mappings = vec![