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(postgres): add cascade table drop option

t8y2745f7f60b081
diff --git a/apps/desktop/src/components/editor/DangerConfirmDialog.vue b/apps/desktop/src/components/editor/DangerConfirmDialog.vue
index cab88ae3c9..4b18a893e0 100644
--- a/apps/desktop/src/components/editor/DangerConfirmDialog.vue
+++ b/apps/desktop/src/components/editor/DangerConfirmDialog.vue
@@ -76,6 +76,7 @@ function onConfirm() {
<div class="py-4 min-w-0">
<p class="text-sm text-muted-foreground mb-3">{{ message || t("dangerDialog.message") }}</p>
<p v-if="detailsText" class="text-xs text-muted-foreground mb-3 whitespace-pre-line">{{ detailsText }}</p>
+ <slot name="options" />
<div v-if="code" class="relative">
<Button variant="ghost" size="icon-xs" class="absolute top-1 right-1 z-10 h-6 w-6" :class="wrap ? 'text-foreground bg-accent' : 'text-muted-foreground'" :title="t('dangerDialog.wrapLines')" @click="wrap = !wrap">
<TextWrap class="h-3.5 w-3.5" />
diff --git a/apps/desktop/src/components/objects/ObjectBrowser.vue b/apps/desktop/src/components/objects/ObjectBrowser.vue
index 5d1e283dd0..b79041089b 100644
--- a/apps/desktop/src/components/objects/ObjectBrowser.vue
+++ b/apps/desktop/src/components/objects/ObjectBrowser.vue
@@ -52,7 +52,7 @@ import { isSchemaAware } from "@/lib/database/databaseCapabilities";
import { supportsSchemaDiagram, supportsTableImport, supportsTableStructureEditing, supportsTableTruncate } from "@/lib/database/databaseFeatureSupport";
import { codeMirrorSqlDialect, connectionUsesDatabaseObjectTreeMode, effectiveDatabaseTypeForConnection, tableStructureDatabaseTypeForConnection } from "@/lib/database/jdbcDialect";
import { buildTableSelectSql } from "@/lib/table/tableSelectSql";
-import { buildDropObjectSql, buildDuplicateTableStructureSql, buildCopyTableDataSql, buildEmptyTableSql, buildTruncateTableSql, type TableAdminSqlOptions } from "@/lib/database/dbAdminSql";
+import { buildDropObjectSql, buildDropTableSql, buildDuplicateTableStructureSql, buildCopyTableDataSql, buildEmptyTableSql, buildTruncateTableSql, supportsDropTableCascade, type TableAdminSqlOptions } from "@/lib/database/dbAdminSql";
import { useToast } from "@/composables/useToast";
import { buildExecutableObjectSourceStatements, buildRoutineRenameObjectSourceStatements, objectSourceSaveExecutionMode, supportsSourceBackedRoutineRename } from "@/lib/table/objectSourceEditor";
import { buildRenameObjectSql, supportsObjectRename } from "@/lib/table/objectRenameSql";
@@ -132,6 +132,8 @@ const sourceSaveError = ref("");
const error = ref("");
const showDropConfirm = ref(false);
const dropTarget = ref<ObjectBrowserRow | null>(null);
+const dropPreviewSql = ref("");
+const dropTableCascade = ref(false);
const showRenameDialog = ref(false);
const renameTarget = ref<ObjectBrowserRow | null>(null);
const renameInput = ref("");
@@ -176,6 +178,7 @@ let stopColumnResize: (() => void) | null = null;
const { addTask: addExportTask } = useExportTracker();
const needsSchema = computed(() => isSchemaAware(props.connection.db_type) && !connectionUsesDatabaseObjectTreeMode(props.connection));
+const canDropTargetCascade = computed(() => dropTarget.value?.type === "TABLE" && supportsDropTableCascade(effectiveDatabaseType.value));
const tableCount = computed(() => rows.value.filter((row) => row.type === "TABLE").length);
const viewCount = computed(() => rows.value.filter((row) => row.type === "VIEW").length);
const materializedViewCount = computed(() => rows.value.filter((row) => row.type === "MATERIALIZED_VIEW").length);
@@ -506,7 +509,10 @@ async function executeProcedureSql(sql: string) {
function requestDrop(row: ObjectBrowserRow) {
dropTarget.value = row;
+ dropPreviewSql.value = "";
+ dropTableCascade.value = false;
showDropConfirm.value = true;
+ void refreshDropPreviewSql();
}
function requestRename(row: ObjectBrowserRow) {
@@ -593,12 +599,7 @@ async function confirmDrop() {
if (!dropTarget.value) return;
const row = dropTarget.value;
try {
- const sql = await buildDropObjectSql({
- databaseType: effectiveDatabaseType.value,
- objectType: row.type,
- schema: row.schema || selectedSchema.value,
- name: row.name,
- });
+ const sql = dropPreviewSql.value || (await buildDropSqlForRow(row, { cascade: canDropTargetCascade.value && dropTableCascade.value }));
await api.executeQuery(props.connection.id, props.database, sql);
const successKey = row.type === "VIEW" ? "contextMenu.dropViewSuccess" : row.type === "PROCEDURE" ? "contextMenu.dropProcedureSuccess" : row.type === "FUNCTION" ? "contextMenu.dropFunctionSuccess" : "contextMenu.dropTableSuccess";
toast(t(successKey, { name: row.name }));
@@ -609,6 +610,34 @@ async function confirmDrop() {
toast(t("contextMenu.tableOperationFailed", { message: e?.message || String(e) }), 5000);
}
dropTarget.value = null;
+ dropPreviewSql.value = "";
+ dropTableCascade.value = false;
+}
+
+async function buildDropSqlForRow(row: ObjectBrowserRow, options?: { cascade?: boolean }): Promise<string> {
+ if (row.type === "TABLE") {
+ return buildDropTableSql(tableAdminSqlOptions(row, { cascade: options?.cascade && supportsDropTableCascade(effectiveDatabaseType.value) }));
+ }
+ return buildDropObjectSql({
+ databaseType: effectiveDatabaseType.value,
+ objectType: row.type,
+ schema: row.schema || selectedSchema.value,
+ name: row.name,
+ });
+}
+
+let dropPreviewRequestId = 0;
+
+async function refreshDropPreviewSql() {
+ const requestId = ++dropPreviewRequestId;
+ const row = dropTarget.value;
+ if (!row) {
+ dropPreviewSql.value = "";
+ return;
+ }
+ dropPreviewSql.value = "";
+ const sql = await buildDropSqlForRow(row, { cascade: canDropTargetCascade.value && dropTableCascade.value }).catch(() => "");
+ if (requestId === dropPreviewRequestId) dropPreviewSql.value = sql;
}
function dropConfirmTitle(): string {
@@ -786,12 +815,7 @@ async function refreshBatchDropPreviewSql() {
const statements: string[] = [];
const sortedRows = await fetchSortedTableRowsForDrop();
for (const row of sortedRows) {
- const sql = await buildDropObjectSql({
- databaseType: effectiveDatabaseType.value,
- objectType: "TABLE",
- schema: row.schema || selectedSchema.value,
- name: row.name,
- }).catch(() => "");
+ const sql = await buildDropTableSql(tableAdminSqlOptions(row)).catch(() => "");
if (sql) statements.push(sql);
}
batchDropPreviewSql.value = statements.join("\n");
@@ -809,12 +833,7 @@ async function confirmBatchDropTables() {
if (targets.length === 0) return;
try {
for (const row of targets) {
- const sql = await buildDropObjectSql({
- databaseType: effectiveDatabaseType.value,
- objectType: "TABLE",
- schema: row.schema || selectedSchema.value,
- name: row.name,
- });
+ const sql = await buildDropTableSql(tableAdminSqlOptions(row));
await api.executeQuery(props.connection.id, props.database, sql);
closeDroppedTableObjectTabsForRow(row);
}
@@ -1121,12 +1140,14 @@ async function confirmPasteTable() {
await connectionStore.refreshObjectListTreeNode(props.connection.id, props.database, selectedSchema.value);
}
-function tableAdminSqlOptions(row: ObjectBrowserRow): TableAdminSqlOptions {
- return {
+function tableAdminSqlOptions(row: ObjectBrowserRow, options?: { cascade?: boolean }): TableAdminSqlOptions {
+ const result: TableAdminSqlOptions = {
databaseType: effectiveDatabaseType.value,
schema: row.schema || selectedSchema.value,
tableName: row.name,
};
+ if (options?.cascade) result.cascade = true;
+ return result;
}
async function refreshTruncatePreviewSql(row: ObjectBrowserRow) {
@@ -1822,7 +1843,17 @@ function getObjectBrowserMenuItems(item: ObjectBrowserRow): ContextMenuItem[] {
</div>
</div>
- <DangerConfirmDialog v-model:open="showDropConfirm" :title="dropConfirmTitle()" :details="dropConfirmMessage()" :confirm-label="t('dangerDialog.deleteConfirm')" @confirm="confirmDrop" />
+ <DangerConfirmDialog v-model:open="showDropConfirm" :title="dropConfirmTitle()" :message="dropConfirmMessage()" :sql="dropPreviewSql" :confirm-label="t('dangerDialog.deleteConfirm')" @confirm="confirmDrop">
+ <template v-if="canDropTargetCascade" #options>
+ <label class="mb-3 flex items-start gap-2 rounded-md border bg-muted/20 px-3 py-2 text-sm">
+ <input v-model="dropTableCascade" type="checkbox" class="mt-0.5 h-3.5 w-3.5 shrink-0 accent-primary" @change="refreshDropPreviewSql()" />
+ <span class="grid gap-0.5">
+ <span class="font-medium text-foreground">{{ t("contextMenu.dropTableCascade") }}</span>
+ <span class="text-xs leading-5 text-muted-foreground">{{ t("contextMenu.dropTableCascadeHint") }}</span>
+ </span>
+ </label>
+ </template>
+ </DangerConfirmDialog>
<DangerConfirmDialog v-model:open="showBatchDropConfirm" :title="t('objects.confirmBatchDropTitle')" :message="t('objects.confirmBatchDropMessage', { count: selectedTableCount })" :sql="batchDropPreviewSql" :confirm-label="t('objects.dropSelected')" @confirm="confirmBatchDropTables" />
diff --git a/apps/desktop/src/components/sidebar/TreeItem.vue b/apps/desktop/src/components/sidebar/TreeItem.vue
index ecda4a8444..c803eb9800 100644
--- a/apps/desktop/src/components/sidebar/TreeItem.vue
+++ b/apps/desktop/src/components/sidebar/TreeItem.vue
@@ -118,6 +118,7 @@ import {
buildCopyTableDataSql,
buildEmptyTableSql,
buildTruncateTableSql,
+ supportsDropTableCascade,
supportsSchemaComment,
type DropTableChildObjectSqlOptions,
type DropObjectSqlOptions,
@@ -1714,6 +1715,7 @@ const renameObjectName = ref("");
const renameObjectError = ref("");
const renameObjectPreviewSql = ref("");
const dropTablePreviewSql = ref("");
+const dropTableCascade = ref(false);
const emptyTablePreviewSql = ref("");
const truncateTablePreviewSql = ref("");
const dropObjectPreviewSql = ref("");
@@ -2442,17 +2444,25 @@ const canEditSchemaComment = computed(() => {
return props.node.type === "schema" && !!props.node.database && !config?.read_only && supportsSchemaComment(effectiveDatabaseTypeForConnection(config));
});
-function tableAdminSqlOptions(): TableAdminSqlOptions {
- return {
+const canDropTableCascade = computed(() => props.node.type === "table" && supportsDropTableCascade(currentDatabaseType()));
+
+function tableAdminSqlOptions(options?: { cascade?: boolean }): TableAdminSqlOptions {
+ const result: TableAdminSqlOptions = {
databaseType: currentDatabaseType(),
schema: props.node.schema,
tableName: props.node.label,
};
+ if (options?.cascade) result.cascade = true;
+ return result;
+}
+
+function dropTableSqlOptions(): TableAdminSqlOptions {
+ return tableAdminSqlOptions({ cascade: canDropTableCascade.value && dropTableCascade.value });
}
async function refreshDropTablePreviewSql() {
dropTablePreviewSql.value = "";
- dropTablePreviewSql.value = await buildDropTableSql(tableAdminSqlOptions()).catch(() => "");
+ dropTablePreviewSql.value = await buildDropTableSql(dropTableSqlOptions()).catch(() => "");
}
async function refreshEmptyTablePreviewSql() {
@@ -2466,6 +2476,7 @@ async function refreshTruncateTablePreviewSql() {
}
function dropTable() {
+ dropTableCascade.value = false;
void refreshDropTablePreviewSql();
showDropTableConfirm.value = true;
}
@@ -2480,7 +2491,7 @@ async function confirmDropTable() {
if (!node.connectionId || !node.database) return;
try {
await connectionStore.ensureConnected(node.connectionId);
- const sql = dropTablePreviewSql.value || (await buildDropTableSql(tableAdminSqlOptions()));
+ const sql = dropTablePreviewSql.value || (await buildDropTableSql(dropTableSqlOptions()));
await api.executeQuery(node.connectionId, node.database, sql, node.schema);
toast(t("contextMenu.dropTableSuccess", { name: node.label }), 3000);
closeDroppedTableObjectTabsForNode(node);
@@ -5177,7 +5188,17 @@ function treeItemMenuItems(): ContextMenuItem[] {
</DialogContent>
</Dialog>
- <DangerConfirmDialog v-model:open="showDropTableConfirm" :title="t('contextMenu.confirmDropTableTitle')" :message="t('contextMenu.confirmDropTableMessage', { name: node.label })" :sql="dropTablePreviewSql" :confirm-label="t('contextMenu.dropTable')" @confirm="confirmDropTable" />
+ <DangerConfirmDialog v-model:open="showDropTableConfirm" :title="t('contextMenu.confirmDropTableTitle')" :message="t('contextMenu.confirmDropTableMessage', { name: node.label })" :sql="dropTablePreviewSql" :confirm-label="t('contextMenu.dropTable')" @confirm="confirmDropTable">
+ <template v-if="canDropTableCascade" #options>
+ <label class="mb-3 flex items-start gap-2 rounded-md border bg-muted/20 px-3 py-2 text-sm">
+ <input v-model="dropTableCascade" type="checkbox" class="mt-0.5 h-3.5 w-3.5 shrink-0 accent-primary" @change="refreshDropTablePreviewSql()" />
+ <span class="grid gap-0.5">
+ <span class="font-medium text-foreground">{{ t("contextMenu.dropTableCascade") }}</span>
+ <span class="text-xs leading-5 text-muted-foreground">{{ t("contextMenu.dropTableCascadeHint") }}</span>
+ </span>
+ </label>
+ </template>
+ </DangerConfirmDialog>
<DangerConfirmDialog v-model:open="showEmptyTableConfirm" :title="t('contextMenu.confirmEmptyTableTitle')" :message="t('contextMenu.confirmEmptyTableMessage', { name: node.label })" :sql="emptyTablePreviewSql" :confirm-label="t('contextMenu.emptyTable')" @confirm="confirmEmptyTable" />
diff --git a/apps/desktop/src/i18n/locales/en.ts b/apps/desktop/src/i18n/locales/en.ts
index 6edf7a505b..293b085a56 100644
--- a/apps/desktop/src/i18n/locales/en.ts
+++ b/apps/desktop/src/i18n/locales/en.ts
@@ -1399,6 +1399,8 @@ export default {
renameObjectSuccess: '"{oldName}" renamed to "{newName}"',
confirmDropTableTitle: "Drop Table",
confirmDropTableMessage: 'Are you sure you want to drop "{name}"? This will permanently delete the table and all its data.',
+ dropTableCascade: "Use CASCADE",
+ dropTableCascadeHint: "Also drop dependent objects such as views. Leave off to use PostgreSQL's default RESTRICT behavior.",
confirmEmptyTableTitle: "Empty Table",
confirmEmptyTableMessage: 'Are you sure you want to delete all data from "{name}"?',
confirmTruncateTableTitle: "Truncate Table",
diff --git a/apps/desktop/src/i18n/locales/es.ts b/apps/desktop/src/i18n/locales/es.ts
index 92e3c66e08..936cc6256d 100644
--- a/apps/desktop/src/i18n/locales/es.ts
+++ b/apps/desktop/src/i18n/locales/es.ts
@@ -1357,6 +1357,8 @@ export default withEnglishFallback({
renameObjectSuccess: '"{oldName}" renombrado a "{newName}"',
confirmDropTableTitle: "Eliminar tabla",
confirmDropTableMessage: '¿Estás seguro de que deseas eliminar "{name}"? Esto borrará permanentemente la tabla y todos sus datos.',
+ dropTableCascade: "Usar CASCADE",
+ dropTableCascadeHint: "También elimina objetos dependientes, como vistas. Desactívalo para usar el comportamiento RESTRICT predeterminado de PostgreSQL.",
confirmEmptyTableTitle: "Vaciar tabla",
confirmEmptyTableMessage: '¿Estás seguro de que deseas eliminar todos los datos de "{name}"?',
confirmTruncateTableTitle: "Truncar tabla",
diff --git a/apps/desktop/src/i18n/locales/it.ts b/apps/desktop/src/i18n/locales/it.ts
index af77be1ca9..69b4da48c7 100644
--- a/apps/desktop/src/i18n/locales/it.ts
+++ b/apps/desktop/src/i18n/locales/it.ts
@@ -1355,6 +1355,8 @@ export default withEnglishFallback({
renameObjectSuccess: '"{oldName}" rinominato in "{newName}"',
confirmDropTableTitle: "Elimina Tabella",
confirmDropTableMessage: 'Sei sicuro di voler eliminare (DROP) la tabella "{name}"? Questa operazione eliminerà permanentemente la tabella e tutti i suoi dati.',
+ dropTableCascade: "Usa CASCADE",
+ dropTableCascadeHint: "Elimina anche gli oggetti dipendenti, come le viste. Lascia disattivato per usare il comportamento RESTRICT predefinito di PostgreSQL.",
confirmEmptyTableTitle: "Svuota Tabella",
confirmEmptyTableMessage: 'Sei sicuro di voler eliminare tutti i dati da "{name}"?',
confirmTruncateTableTitle: "Tronca Tabella",
diff --git a/apps/desktop/src/i18n/locales/ja.ts b/apps/desktop/src/i18n/locales/ja.ts
index b1b289f502..e822922451 100644
--- a/apps/desktop/src/i18n/locales/ja.ts
+++ b/apps/desktop/src/i18n/locales/ja.ts
@@ -1353,6 +1353,8 @@ export default withEnglishFallback({
renameObjectSuccess: "「{oldName}」の名前を「{newName}」に変更しました",
confirmDropTableTitle: "テーブルを削除",
confirmDropTableMessage: "本当にテーブル「{name}」をドロップ(削除)しますか?テーブルとすべてのデータが永久に削除されます。",
+ dropTableCascade: "CASCADE を使用",
+ dropTableCascadeHint: "ビューなど、このテーブルに依存するオブジェクトも削除します。オフの場合は PostgreSQL の既定の RESTRICT を使用します。",
confirmEmptyTableTitle: "テーブルを空にする",
confirmEmptyTableMessage: "本当に「{name}」のすべてのデータを削除しますか?",
confirmTruncateTableTitle: "テーブルをトランケート",
diff --git a/apps/desktop/src/i18n/locales/pt-BR.ts b/apps/desktop/src/i18n/locales/pt-BR.ts
index 69c73a1ff8..a7e528c9a9 100644
--- a/apps/desktop/src/i18n/locales/pt-BR.ts
+++ b/apps/desktop/src/i18n/locales/pt-BR.ts
@@ -1356,6 +1356,8 @@ export default withEnglishFallback({
renameObjectSuccess: '"{oldName}" renomeado para "{newName}"',
confirmDropTableTitle: "Remover Tabela",
confirmDropTableMessage: 'Tem certeza de que deseja remover "{name}"? Isso excluirá permanentemente a tabela e todos os seus dados.',
+ dropTableCascade: "Usar CASCADE",
+ dropTableCascadeHint: "Também remove objetos dependentes, como views. Deixe desmarcado para usar o comportamento RESTRICT padrão do PostgreSQL.",
confirmEmptyTableTitle: "Esvaziar Tabela",
confirmEmptyTableMessage: 'Tem certeza de que deseja excluir todos os dados de "{name}"?',
confirmTruncateTableTitle: "Truncar Tabela",
diff --git a/apps/desktop/src/i18n/locales/zh-CN.ts b/apps/desktop/src/i18n/locales/zh-CN.ts
index 5b8273c9a7..1337ff7acd 100644
--- a/apps/desktop/src/i18n/locales/zh-CN.ts
+++ b/apps/desktop/src/i18n/locales/zh-CN.ts
@@ -1401,6 +1401,8 @@ export default withEnglishFallback({
renameObjectSuccess: "已将「{oldName}」重命名为「{newName}」",
confirmDropTableTitle: "删除表",
confirmDropTableMessage: "确定要删除「{name}」吗?这将永久删除表及其所有数据。",
+ dropTableCascade: "使用 CASCADE 强制删除",
+ dropTableCascadeHint: "同时删除依赖该表的对象(如视图)。未勾选时使用 PostgreSQL 默认的 RESTRICT。",
confirmEmptyTableTitle: "清空数据",
confirmEmptyTableMessage: "确定要删除「{name}」中的所有数据吗?",
confirmTruncateTableTitle: "截断表",
diff --git a/apps/desktop/src/i18n/locales/zh-TW.ts b/apps/desktop/src/i18n/locales/zh-TW.ts
index 39452edb2f..62958cff7c 100644
--- a/apps/desktop/src/i18n/locales/zh-TW.ts
+++ b/apps/desktop/src/i18n/locales/zh-TW.ts
@@ -1356,6 +1356,8 @@ export default withEnglishFallback({
renameObjectSuccess: "已將「{oldName}」重新命名為「{newName}」",
confirmDropTableTitle: "刪除資料表",
confirmDropTableMessage: "確定要刪除「{name}」嗎?這將永久刪除資料表及其所有資料。",
+ dropTableCascade: "使用 CASCADE 強制刪除",
+ dropTableCascadeHint: "同時刪除依賴此資料表的物件(例如檢視)。未勾選時使用 PostgreSQL 預設的 RESTRICT。",
confirmEmptyTableTitle: "清空資料",
confirmEmptyTableMessage: "確定要刪除「{name}」中的所有資料嗎?",
confirmTruncateTableTitle: "截斷資料表",
diff --git a/apps/desktop/src/lib/database/dbAdminSql.ts b/apps/desktop/src/lib/database/dbAdminSql.ts
index 150fe7e748..17689f07da 100644
--- a/apps/desktop/src/lib/database/dbAdminSql.ts
+++ b/apps/desktop/src/lib/database/dbAdminSql.ts
@@ -12,6 +12,7 @@ export interface TableAdminSqlOptions {
databaseType?: DatabaseType;
schema?: string | null;
tableName: string;
+ cascade?: boolean;
}
export type TableChildObjectType = "COLUMN" | "INDEX" | "FOREIGN_KEY" | "TRIGGER";
@@ -85,6 +86,12 @@ export function buildTruncateTableSql(options: TableAdminSqlOptions): Promise<st
return api.buildTruncateTableSql(options);
}
+const DROP_TABLE_CASCADE_DATABASE_TYPES: readonly DatabaseType[] = ["postgres", "redshift", "gaussdb", "kwdb", "kingbase", "highgo", "vastbase", "opengauss"];
+
+export function supportsDropTableCascade(databaseType?: DatabaseType): boolean {
+ return !!databaseType && DROP_TABLE_CASCADE_DATABASE_TYPES.includes(databaseType);
+}
+
export function buildDropDatabaseSql(options: DatabaseNameSqlOptions): Promise<string> {
return api.buildDropDatabaseSql(options);
}
diff --git a/crates/dbx-core/src/db_admin_sql.rs b/crates/dbx-core/src/db_admin_sql.rs
index 408b57f93e..b5bd9a43ca 100644
--- a/crates/dbx-core/src/db_admin_sql.rs
+++ b/crates/dbx-core/src/db_admin_sql.rs
@@ -88,6 +88,8 @@ pub struct TableAdminSqlOptions {
#[serde(default, skip_serializing_if = "Option::is_none")]
pub schema: Option<String>,
pub table_name: String,
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub cascade: Option<bool>,
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
@@ -322,7 +324,29 @@ pub fn build_drop_table_sql(options: TableAdminSqlOptions) -> String {
} else if matches!(options.database_type, Some(DatabaseType::InfluxDb)) {
return format!("DROP MEASUREMENT {};", table);
}
- format!("DROP TABLE {table};")
+ // CASCADE is valid for PostgreSQL-family dialects; keep default RESTRICT behavior elsewhere.
+ let cascade = if options.cascade.unwrap_or(false) && supports_drop_table_cascade(options.database_type) {
+ " CASCADE"
+ } else {
+ ""
+ };
+ format!("DROP TABLE {table}{cascade};")
+}
+
+fn supports_drop_table_cascade(database_type: Option<DatabaseType>) -> bool {
+ matches!(
+ database_type,
+ Some(
+ DatabaseType::Postgres
+ | DatabaseType::Redshift
+ | DatabaseType::Gaussdb
+ | DatabaseType::Kwdb
+ | DatabaseType::Kingbase
+ | DatabaseType::Highgo
+ | DatabaseType::Vastbase
+ | DatabaseType::OpenGauss
+ )
+ )
}
pub fn build_drop_table_child_object_sql(options: DropTableChildObjectSqlOptions) -> Result<String, String> {
@@ -1018,8 +1042,27 @@ mod tests {
database_type: Some(DatabaseType::Postgres),
schema: Some("public".to_string()),
table_name: "events".to_string(),
+ cascade: None,
};
assert_eq!(build_drop_table_sql(options.clone()), "DROP TABLE \"public\".\"events\";");
+ assert_eq!(
+ build_drop_table_sql(TableAdminSqlOptions {
+ database_type: Some(DatabaseType::Postgres),
+ schema: Some("public".to_string()),
+ table_name: "events".to_string(),
+ cascade: Some(true),
+ }),
+ "DROP TABLE \"public\".\"events\" CASCADE;"
+ );
+ assert_eq!(
+ build_drop_table_sql(TableAdminSqlOptions {
+ database_type: Some(DatabaseType::Mysql),
+ schema: None,
+ table_name: "events".to_string(),
+ cascade: Some(true),
+ }),
+ "DROP TABLE `events`;"
+ );
assert_eq!(build_empty_table_sql(options.clone()), "DELETE FROM \"public\".\"events\";");
assert_eq!(build_truncate_table_sql(options), "TRUNCATE TABLE \"public\".\"events\";");
assert_eq!(
@@ -1027,6 +1070,7 @@ mod tests {
database_type: Some(DatabaseType::ClickHouse),
schema: None,
table_name: "PresetSubjectInfo".to_string(),
+ cascade: None,
}),
"ALTER TABLE `PresetSubjectInfo` DELETE WHERE 1 = 1;"
);
@@ -1035,6 +1079,7 @@ mod tests {
database_type: Some(DatabaseType::ClickHouse),
schema: None,
table_name: "PresetSubjectInfo".to_string(),
+ cascade: None,
}),
"TRUNCATE TABLE `PresetSubjectInfo`;"
);
@@ -1043,6 +1088,7 @@ mod tests {
database_type: Some(DatabaseType::Bigquery),
schema: None,
table_name: "events".to_string(),
+ cascade: None,
}),
"DELETE FROM `events` WHERE TRUE;"
);
@@ -1051,6 +1097,7 @@ mod tests {
database_type: Some(DatabaseType::Cassandra),
schema: None,
table_name: "events".to_string(),
+ cascade: None,
}),
"TRUNCATE TABLE \"events\";"
);
@@ -1059,6 +1106,7 @@ mod tests {
database_type: Some(DatabaseType::DuckDb),
schema: None,
table_name: "events".to_string(),
+ cascade: None,
}),
"DELETE FROM \"events\";"
);
@@ -1067,6 +1115,7 @@ mod tests {
database_type: Some(DatabaseType::Iotdb),
schema: Some("root.test".to_string()),
table_name: "DCU_101".to_string(),
+ cascade: None,
}),
"DELETE TIMESERIES root.test.DCU_101.*;"
);
@@ -1075,6 +1124,7 @@ mod tests {
database_type: Some(DatabaseType::Iotdb),
schema: Some("root.test".to_string()),
table_name: "root.test.DCU_101".to_string(),
+ cascade: None,
}),
"DELETE FROM root.test.DCU_101.*;"
);
@@ -1083,6 +1133,7 @@ mod tests {
database_type: Some(DatabaseType::Iotdb),
schema: Some("root.test".to_string()),
table_name: "DCU_101".to_string(),
+ cascade: None,
}),
"DELETE FROM root.test.DCU_101.*;"
);
@@ -1092,6 +1143,7 @@ mod tests {
database_type: Some(DatabaseType::Questdb),
schema: None,
table_name: "table_sample".to_string(),
+ cascade: None,
}),
"TRUNCATE TABLE `table_sample`;"
);
@@ -1100,6 +1152,7 @@ mod tests {
database_type: Some(DatabaseType::Questdb),
schema: None,
table_name: "table_sample".to_string(),
+ cascade: None,
}),
"TRUNCATE TABLE `table_sample`;"
);