mirror of
https://github.com/l0ng-ai/openidea.git
synced 2026-11-24 08:03:19 +00:00
feat(database): create and drop databases and schemas from the tree (#4201)
The Database tree gets New > Database... and New > Schema..., and Drop... on database nodes (PostgreSQL, MySQL/MariaDB schemas, SQL Server), each with a preview of the statement it runs. Creating closes the IDE's own connections to the database the server copies (the template on PostgreSQL, model on SQL Server), which both refuse to copy while it has sessions. Dropping closes the IDE's pools and sessions of that database first and runs DROP DATABASE on the data source's default database; "Close the sessions of other clients" adds WITH (FORCE) on PostgreSQL 13+ and single-user mode on SQL Server. Drop is refused for the data source's own database and read-only data sources. Both go through withConnection, so a password the data source does not save is asked for first. Closes #3189 Co-authored-by: EjaYF <9842286+EjaYF@users.noreply.github.com>
This commit is contained in:
co-authored by
EjaYF
parent
bb243909bf
commit
e689c95e93
@@ -916,6 +916,37 @@ impl DbManager {
|
||||
self.tunnels.lock().remove(id);
|
||||
}
|
||||
|
||||
/// Creates a database on the server of data source `id` by running `statement` on the data
|
||||
/// source's own database, after closing the IDE's connections to `template`, the database
|
||||
/// the server copies (PostgreSQL and SQL Server refuse to copy one that has sessions).
|
||||
pub async fn create_database(&self, id: &str, template: &str, statement: &str) -> IdeResult<()> {
|
||||
let id = split_target(id).0;
|
||||
if self.source(id)?.read_only {
|
||||
return Err(IdeError::new(ErrorKind::PermissionDenied, "the data source is read-only"));
|
||||
}
|
||||
self.disconnect(&format!("{id}:{template}")).await;
|
||||
self.pool(id).await?.execute(statement, 0, &CancellationToken::new()).await?;
|
||||
self.remember_statement(id, statement);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Drops `database` of the server of data source `id` by running `statement` on the data
|
||||
/// source's own database, after closing the IDE's connections to `database`.
|
||||
/// Refuses the database the data source connects to and read-only data sources.
|
||||
pub async fn drop_database(&self, id: &str, database: &str, statement: &str) -> IdeResult<()> {
|
||||
let id = split_target(id).0;
|
||||
if self.source(id)?.read_only {
|
||||
return Err(IdeError::new(ErrorKind::PermissionDenied, "the data source is read-only"));
|
||||
}
|
||||
if self.databases(id).await?.current == database {
|
||||
return Err(IdeError::invalid(format!("the data source connects to {database}; it cannot drop it")));
|
||||
}
|
||||
self.disconnect(&format!("{id}:{database}")).await;
|
||||
self.pool(id).await?.execute(statement, 0, &CancellationToken::new()).await?;
|
||||
self.remember_statement(id, statement);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// The databases of the server of data source `id` (PostgreSQL), the connected one first.
|
||||
pub async fn databases(&self, id: &str) -> IdeResult<Databases> {
|
||||
let id = split_target(id).0;
|
||||
|
||||
@@ -230,6 +230,44 @@ async fn opening_a_table_reads_multi_column_keys_in_order() -> IdeResult<()> {
|
||||
}
|
||||
|
||||
/// Runs `job` with the newest installed copy of its tool, the way the dialogs do.
|
||||
#[tokio::test]
|
||||
async fn drops_a_database_the_ide_holds_connections_to() -> IdeResult<()> {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let Some(db) = manager(&tmp).await else { return Ok(()) };
|
||||
let c = CancellationToken::new();
|
||||
db.execute("p", "DROP DATABASE IF EXISTS oi_drop_me", 0, &c).await?;
|
||||
db.execute("p", "CREATE DATABASE oi_drop_me TEMPLATE template0", 0, &c).await?;
|
||||
|
||||
// What the tree and a manual-commit console leave open on the database.
|
||||
db.schemas("p:oi_drop_me").await?;
|
||||
db.set_manual_commit("p:oi_drop_me", true).await?;
|
||||
db.execute("p:oi_drop_me", "SELECT 1", 1, &c).await?;
|
||||
|
||||
db.drop_database("p", "oi_drop_me", "drop database oi_drop_me").await?;
|
||||
assert!(!db.is_connected("p:oi_drop_me"));
|
||||
assert!(!db.databases("p").await?.names.iter().any(|n| n == "oi_drop_me"));
|
||||
|
||||
let current = db.databases("p").await?.current;
|
||||
let refused = db.drop_database("p", ¤t, &format!("drop database \"{current}\"")).await;
|
||||
assert!(refused.is_err());
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn creates_a_database_from_a_template_the_ide_holds_connections_to() -> IdeResult<()> {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let Some(db) = manager(&tmp).await else { return Ok(()) };
|
||||
let c = CancellationToken::new();
|
||||
db.execute("p", "DROP DATABASE IF EXISTS oi_from_template", 0, &c).await?;
|
||||
db.schemas("p:template1").await?;
|
||||
|
||||
db.create_database("p", "template1", "create database oi_from_template").await?;
|
||||
assert!(!db.is_connected("p:template1"));
|
||||
assert!(db.databases("p").await?.names.iter().any(|n| n == "oi_from_template"));
|
||||
db.execute("p", "DROP DATABASE oi_from_template", 0, &c).await?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
async fn run_tool(db: &DbManager, target: &str, job: ide_db::tools::DbToolJob) -> IdeResult<()> {
|
||||
let install = ide_db::tools::find_installs(job.tool()).into_iter().next().expect("installed");
|
||||
let mut lines = Vec::new();
|
||||
|
||||
@@ -95,3 +95,44 @@ async fn sqlserver_values_paging_transactions_and_cancellation() {
|
||||
task.await.unwrap();
|
||||
assert_eq!(pool.rows("SELECT 1", 1).await.unwrap()[0][0].as_deref(), Some("1"));
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn sqlserver_creates_from_a_held_model_and_force_drops_a_held_database() {
|
||||
let Ok(server) = std::env::var("OPENIDEA_TEST_SQLSERVER") else { return };
|
||||
let mut parts = server.splitn(4, ':');
|
||||
let (host, port, user, password) = (
|
||||
parts.next().unwrap(),
|
||||
parts.next().unwrap().parse().unwrap(),
|
||||
parts.next().unwrap(),
|
||||
parts.next().unwrap_or(""),
|
||||
);
|
||||
let source = |database: &str| DataSource {
|
||||
id: "s".into(),
|
||||
name: "sqlserver".into(),
|
||||
driver: DbDriver::SqlServer,
|
||||
host: host.into(),
|
||||
port: Some(port),
|
||||
user: user.into(),
|
||||
database: database.into(),
|
||||
ssl: DbSslMode::Disable,
|
||||
..Default::default()
|
||||
};
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let root = tmp.path().to_path_buf();
|
||||
let ssh = std::sync::Arc::new(ide_ssh::SshManager::new(root.join("ssh-passwords.json")));
|
||||
let db = ide_db::DbManager::new(root.clone(), root.join("passwords.json"), root.join("history.json"), ssh);
|
||||
db.save_sources(vec![source("master")]).await.unwrap();
|
||||
db.set_password("s", Some(password.into()), false).await.unwrap();
|
||||
let name = format!("oi_force_drop_{}", std::process::id());
|
||||
// The tree's connection to `model` would keep SQL Server from copying it.
|
||||
db.schemas("s:model").await.unwrap();
|
||||
db.create_database("s", "model", &format!("create database {name};")).await.unwrap();
|
||||
assert!(!db.is_connected("s:model"));
|
||||
|
||||
let other = Pool::connect(&source(&name), Some(password), None).await.unwrap();
|
||||
let held = Held::acquire(&other).await.unwrap();
|
||||
let force = format!("alter database {name} set single_user with rollback immediate;\ndrop database {name};");
|
||||
db.drop_database("s", &name, &force).await.unwrap();
|
||||
assert!(!db.databases("s").await.unwrap().names.contains(&name));
|
||||
drop(held);
|
||||
}
|
||||
|
||||
@@ -139,6 +139,32 @@ pub async fn db_disconnect(host: &Host, window: &str, id: String) -> IdeResult<(
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[command(trust = trusted)]
|
||||
pub async fn db_create_database(
|
||||
host: &Host,
|
||||
window: &str,
|
||||
id: String,
|
||||
template: String,
|
||||
statement: String,
|
||||
) -> IdeResult<()> {
|
||||
// Creates a database on the server of data source `id` with `statement`, copied from `template` (New › Database).
|
||||
let db = host.project(window)?.db.clone();
|
||||
db.create_database(&id, &template, &statement).await
|
||||
}
|
||||
|
||||
#[command(trust = trusted)]
|
||||
pub async fn db_drop_database(
|
||||
host: &Host,
|
||||
window: &str,
|
||||
id: String,
|
||||
database: String,
|
||||
statement: String,
|
||||
) -> IdeResult<()> {
|
||||
// Drops `database` of the server of data source `id` with `statement` (Drop… on a database node).
|
||||
let db = host.project(window)?.db.clone();
|
||||
db.drop_database(&id, &database, &statement).await
|
||||
}
|
||||
|
||||
#[command(trust = trusted)]
|
||||
pub async fn db_databases(host: &Host, window: &str, id: String) -> IdeResult<Databases> {
|
||||
// Databases of the server of data source `id` (PostgreSQL); connect to one as `<id>:<database>`.
|
||||
@@ -478,10 +504,12 @@ ide_command::domain!(
|
||||
db_connected,
|
||||
db_console_path,
|
||||
db_consoles,
|
||||
db_create_database,
|
||||
db_database_catalog,
|
||||
db_databases,
|
||||
db_ddl,
|
||||
db_disconnect,
|
||||
db_drop_database,
|
||||
db_execute,
|
||||
db_explain,
|
||||
db_finish_transaction,
|
||||
|
||||
@@ -93,10 +93,12 @@ db_connect trusted project_host bin
|
||||
db_connected trusted project_host bindings sync
|
||||
db_console_path always project_host bindings sync
|
||||
db_consoles always project_host bindings sync
|
||||
db_create_database trusted project_host bindings async
|
||||
db_database_catalog trusted project_host bindings async
|
||||
db_databases trusted project_host bindings async
|
||||
db_ddl trusted project_host bindings async
|
||||
db_disconnect trusted project_host bindings async
|
||||
db_drop_database trusted project_host bindings async
|
||||
db_dump_info trusted desktop bindings async
|
||||
db_execute trusted project_host bindings async
|
||||
db_explain trusted project_host bindings async
|
||||
|
||||
@@ -272,10 +272,12 @@ export const commands = {
|
||||
dbConsolePath: (id: string) => typedError<IpcPath, IdeError>(__TAURI_INVOKE("db_console_path", { id })),
|
||||
/** The query consoles of data source `id`; `create` adds the next one first. */
|
||||
dbConsoles: (id: string, create: boolean) => typedError<IpcPath[], IdeError>(__TAURI_INVOKE("db_consoles", { id, create })),
|
||||
dbCreateDatabase: (id: string, template: string, statement: string) => typedError<null, IdeError>(__TAURI_INVOKE("db_create_database", { id, template, statement })),
|
||||
dbDatabaseCatalog: (id: string, database: string) => typedError<DbCatalogSchema[], IdeError>(__TAURI_INVOKE("db_database_catalog", { id, database })),
|
||||
dbDatabases: (id: string) => typedError<DbDatabases, IdeError>(__TAURI_INVOKE("db_databases", { id })),
|
||||
dbDdl: (id: string, schema: string, table: string) => typedError<string, IdeError>(__TAURI_INVOKE("db_ddl", { id, schema, table })),
|
||||
dbDisconnect: (id: string) => typedError<null, IdeError>(__TAURI_INVOKE("db_disconnect", { id })),
|
||||
dbDropDatabase: (id: string, database: string, statement: string) => typedError<null, IdeError>(__TAURI_INVOKE("db_drop_database", { id, database, statement })),
|
||||
/** What made the dump at `path` and whether it creates its own database (from its first bytes). */
|
||||
dbDumpInfo: (path: string) => typedError<DbDumpInfo, IdeError>(__TAURI_INVOKE("db_dump_info", { path })),
|
||||
dbExecute: (request: RequestId, id: string, statements: SqlStatement[], skip: number, maxRows: number, schema: string | null) => typedError<DbStatementOutcome[], IdeError>(__TAURI_INVOKE("db_execute", { request, id, statements, skip, maxRows, schema })),
|
||||
|
||||
@@ -370,6 +370,9 @@
|
||||
font-size: var(--fs-small);
|
||||
color: var(--fg-muted);
|
||||
}
|
||||
.formFull {
|
||||
grid-column: 1 / -1;
|
||||
}
|
||||
.paramInput {
|
||||
font-family: var(--openidea-editor-font, var(--font-mono));
|
||||
font-weight: var(--fw-code);
|
||||
|
||||
@@ -454,7 +454,7 @@ export function DatabaseView() {
|
||||
case "source":
|
||||
return sourceIcon(n.source);
|
||||
case "database":
|
||||
return "database";
|
||||
return "db-database";
|
||||
case "schema":
|
||||
return "db-schema";
|
||||
case "folder":
|
||||
|
||||
@@ -1,34 +1,42 @@
|
||||
/**
|
||||
* Dialogs of the Database tree's object actions, after IDEA's: Rename, Confirm
|
||||
* Drop, Truncate, Modify Table / New Table (with a Preview of the SQL they
|
||||
* run), Remove Data Source, Data Source from URL, and the Quick Documentation popup.
|
||||
* Drop, Truncate, Modify Table / New Table, New Database / New Schema (with a
|
||||
* Preview of the SQL they run), Remove Data Source, Data Source from URL, and the Quick Documentation popup.
|
||||
*/
|
||||
import { useEffect, useMemo, useRef, useState } from "react";
|
||||
import { call, commands, type DbColumnInfo, type DbDriver } from "@/platform/ipc";
|
||||
import { highlightInto } from "@/editor/lsp/markdown";
|
||||
import { Button, Checkbox, Dialog, IconButton, Input, Popup, Icon, T } from "@/ui";
|
||||
import { Button, Checkbox, Dialog, IconButton, Input, Popup, Icon, Select, T, type SelectOption } from "@/ui";
|
||||
import { parseSourceUrl, sourceLabel, splitTarget } from "./model";
|
||||
import { nodeTarget, schemaObjectOf, tableOf, type DbNode } from "./nodes";
|
||||
import {
|
||||
alterTableSql,
|
||||
canAlterColumn,
|
||||
createDatabaseSql,
|
||||
createSchemaSql,
|
||||
createTableSql,
|
||||
draftOf,
|
||||
dropDatabaseSql,
|
||||
dropSql,
|
||||
ident,
|
||||
reference,
|
||||
renameSql,
|
||||
truncateSql,
|
||||
type ColumnDraft,
|
||||
templateOf,
|
||||
type CreateOptions,
|
||||
type DbObjectRef,
|
||||
} from "./objects";
|
||||
import {
|
||||
closeDialog,
|
||||
detailsKey,
|
||||
connectedTargets,
|
||||
createDatabase,
|
||||
dropDatabase,
|
||||
loadDetails,
|
||||
openSourceDialog,
|
||||
readableDdl,
|
||||
refresh,
|
||||
renameSource,
|
||||
runSql,
|
||||
sourceById,
|
||||
@@ -80,14 +88,15 @@ function objectName(o: DbObjectRef): string {
|
||||
function useRunner() {
|
||||
const [busy, setBusy] = useState(false);
|
||||
const running = useRef(false);
|
||||
const runAndClose = async (id: string, statements: string[]) => {
|
||||
if (running.current) return;
|
||||
const runAndClose = async (id: string, statements: string[]): Promise<boolean> => {
|
||||
if (running.current) return false;
|
||||
running.current = true;
|
||||
setBusy(true);
|
||||
const ok = await runSql(id, statements);
|
||||
running.current = false;
|
||||
setBusy(false);
|
||||
if (ok) closeDialog();
|
||||
return ok;
|
||||
};
|
||||
return { busy, runAndClose };
|
||||
}
|
||||
@@ -116,7 +125,7 @@ function RenameDialog({ id, object }: { id: string; object: DbObjectRef | null }
|
||||
width={480}
|
||||
buttons={[
|
||||
{ label: "Cancel", role: "cancel" },
|
||||
{ label: "Refactor", role: "default", disabled: busy || !name.trim(), onClick: submit },
|
||||
{ label: "Refactor", role: "default", disabled: busy || !name.trim(), onClick: () => void submit() },
|
||||
]}
|
||||
>
|
||||
<div className={styles.dialogBody}>
|
||||
@@ -213,6 +222,169 @@ function TruncateDialog({ id, schema, table }: { id: string; schema: string; tab
|
||||
);
|
||||
}
|
||||
|
||||
// ---- New Database / New Schema / Drop database ---------------------------------
|
||||
|
||||
const TEMPLATES: SelectOption[] = [
|
||||
{ value: "", label: "Server default" },
|
||||
...["template0", "template1"].map((name) => ({ value: name, label: name, verbatim: true })),
|
||||
];
|
||||
|
||||
/** An optional text field of the create dialogs: empty leaves it to the server. */
|
||||
function OptionField({
|
||||
id,
|
||||
label,
|
||||
value,
|
||||
onChange,
|
||||
}: {
|
||||
id: string;
|
||||
label: string;
|
||||
value: string;
|
||||
onChange: (value: string) => void;
|
||||
}) {
|
||||
return (
|
||||
<>
|
||||
<label className={styles.formLabel} htmlFor={id}>
|
||||
{tx(label)}
|
||||
</label>
|
||||
<Input id={id} placeholder="Server default" value={value} onChange={(e) => onChange(e.target.value)} />
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
/** New › Database (`database`) or New › Schema (`schema`) in target `id`. */
|
||||
function CreateDialog({ id, what }: { id: string; what: "database" | "schema" }) {
|
||||
const driver = driverOf(id);
|
||||
const [name, setName] = useState("");
|
||||
const [opts, setOpts] = useState<CreateOptions>({});
|
||||
const { busy: running, runAndClose } = useRunner();
|
||||
const [creating, setCreating] = useState(false);
|
||||
const busy = running || creating;
|
||||
const sql = (what === "database" ? createDatabaseSql : createSchemaSql)(driver, name.trim() || "<name>", opts);
|
||||
const submit = async () => {
|
||||
if (what === "schema") {
|
||||
if (await runAndClose(id, [sql])) void refresh(id);
|
||||
return;
|
||||
}
|
||||
setCreating(true);
|
||||
if (await createDatabase(id, templateOf(driver, opts), sql)) closeDialog();
|
||||
else setCreating(false);
|
||||
};
|
||||
const field = (key: keyof CreateOptions, label: string) => (
|
||||
<OptionField
|
||||
id={`db-new-${key}`}
|
||||
label={label}
|
||||
value={opts[key] ?? ""}
|
||||
onChange={(value) => setOpts((o) => ({ ...o, [key]: value }))}
|
||||
/>
|
||||
);
|
||||
return (
|
||||
<Dialog
|
||||
open
|
||||
onClose={closeDialog}
|
||||
title={what === "database" ? "New Database" : "New Schema"}
|
||||
width={560}
|
||||
buttons={[
|
||||
{ label: "Cancel", role: "cancel" },
|
||||
{ label: "OK", role: "default", disabled: busy || !name.trim(), onClick: submit },
|
||||
]}
|
||||
>
|
||||
<div className={styles.form}>
|
||||
<label className={styles.formLabel} htmlFor="db-new-name">
|
||||
<T>Name:</T>
|
||||
</label>
|
||||
<Input id="db-new-name" autoFocus value={name} onChange={(e) => setName(e.target.value)} />
|
||||
{what === "database" && driver === "postgres" && (
|
||||
<>
|
||||
{field("owner", "Owner:")}
|
||||
<label className={styles.formLabel} htmlFor="db-new-template">
|
||||
<T>Template:</T>
|
||||
</label>
|
||||
<Select
|
||||
id="db-new-template"
|
||||
value={opts.template ?? ""}
|
||||
options={TEMPLATES}
|
||||
onChange={(template) => setOpts((o) => ({ ...o, template }))}
|
||||
/>
|
||||
<span />
|
||||
<span className={styles.formHint}>
|
||||
<T>Restoring a dump needs template0: template1 can already hold extensions and schemas.</T>
|
||||
</span>
|
||||
{field("encoding", "Encoding:")}
|
||||
{field("tablespace", "Tablespace:")}
|
||||
</>
|
||||
)}
|
||||
{what === "database" && driver === "sqlServer" && field("collation", "Collation:")}
|
||||
{what === "schema" && driver === "mysql" && (
|
||||
<>
|
||||
{field("charset", "Character set:")}
|
||||
{field("collation", "Collation:")}
|
||||
</>
|
||||
)}
|
||||
{what === "schema" && driver !== "mysql" && field("owner", "Owner:")}
|
||||
<div className={styles.formFull}>
|
||||
<SqlPreview sql={sql} />
|
||||
</div>
|
||||
</div>
|
||||
</Dialog>
|
||||
);
|
||||
}
|
||||
|
||||
/** PostgreSQL 13 added `drop database … with (force)`. */
|
||||
const PG_FORCE_DROP = 130000;
|
||||
|
||||
function DropDatabaseDialog({ id, database }: { id: string; database: string }) {
|
||||
const driver = driverOf(id);
|
||||
const [force, setForce] = useState(false);
|
||||
const [version, setVersion] = useState<number | null>(null);
|
||||
const [busy, setBusy] = useState(false);
|
||||
useEffect(() => {
|
||||
if (driver !== "postgres") return;
|
||||
let live = true;
|
||||
void withConnection(id, () => call(commands.dbServerVersion(id)))
|
||||
.then((v) => live && setVersion(v))
|
||||
.catch(() => {});
|
||||
return () => {
|
||||
live = false;
|
||||
};
|
||||
}, [id, driver]);
|
||||
const canForce = driver === "sqlServer" || (version ?? 0) >= PG_FORCE_DROP;
|
||||
const sql = dropDatabaseSql(driver, database, force && canForce);
|
||||
const submit = async () => {
|
||||
setBusy(true);
|
||||
if (await dropDatabase(id, database, sql)) closeDialog();
|
||||
else setBusy(false);
|
||||
};
|
||||
return (
|
||||
<Dialog
|
||||
open
|
||||
onClose={closeDialog}
|
||||
title="Confirm Drop"
|
||||
width={520}
|
||||
buttons={[
|
||||
{ label: "Cancel", role: "cancel" },
|
||||
{ label: "OK", role: "default", disabled: busy, onClick: () => void submit() },
|
||||
]}
|
||||
>
|
||||
<div className={styles.dialogBody}>
|
||||
<div className={styles.dialogLead}>
|
||||
{tx`Drop database`} <strong>{database}</strong>
|
||||
{tx`? This cannot be undone.`}
|
||||
</div>
|
||||
<span className={styles.formHint}>
|
||||
<T>The IDE closes its own connections to the database first.</T>
|
||||
</span>
|
||||
<Checkbox
|
||||
checked={force && canForce}
|
||||
onChange={setForce}
|
||||
disabled={!canForce}
|
||||
label="Close the sessions of other clients"
|
||||
/>
|
||||
<SqlPreview sql={sql} />
|
||||
</div>
|
||||
</Dialog>
|
||||
);
|
||||
}
|
||||
|
||||
// ---- Modify Table / New Table -----------------------------------------------
|
||||
|
||||
const TYPES: Record<DbDriver, string[]> = {
|
||||
@@ -726,6 +898,12 @@ export function ObjectDialogs() {
|
||||
return <DropDialog id={dialog.id} object={dialog.object} />;
|
||||
case "truncate":
|
||||
return <TruncateDialog id={dialog.id} schema={dialog.schema} table={dialog.table} />;
|
||||
case "createDatabase":
|
||||
return <CreateDialog id={dialog.id} what="database" />;
|
||||
case "createSchema":
|
||||
return <CreateDialog id={dialog.id} what="schema" />;
|
||||
case "dropDatabase":
|
||||
return <DropDatabaseDialog id={dialog.id} database={dialog.database} />;
|
||||
case "modifyTable":
|
||||
return (
|
||||
<ModifyTableDialog
|
||||
|
||||
@@ -4,8 +4,12 @@ import {
|
||||
alterTableSql,
|
||||
canDrop,
|
||||
canModifyTable,
|
||||
createDatabaseSql,
|
||||
createSchemaSql,
|
||||
createTableSql,
|
||||
draftOf,
|
||||
dropDatabaseSql,
|
||||
templateOf,
|
||||
dropSql,
|
||||
ident,
|
||||
reference,
|
||||
@@ -341,3 +345,49 @@ describe("snowflake object SQL", () => {
|
||||
expect(alterTableSql("snowflake", "HR", "EMP", "EMP", dropped)).toEqual(["alter table HR.EMP drop column NAME;"]);
|
||||
});
|
||||
});
|
||||
|
||||
describe("database and schema SQL", () => {
|
||||
it("creates a PostgreSQL database with only the options given", () => {
|
||||
expect(createDatabaseSql("postgres", "shop", {})).toBe("create database shop;");
|
||||
expect(
|
||||
createDatabaseSql("postgres", "Shop Copy", {
|
||||
owner: "app",
|
||||
template: "template0",
|
||||
encoding: "UTF8",
|
||||
tablespace: " ",
|
||||
}),
|
||||
).toBe(`create database "Shop Copy" owner app template template0 encoding 'UTF8';`);
|
||||
expect(createDatabaseSql("postgres", "shop", { encoding: "it's" })).toBe("create database shop encoding 'it''s';");
|
||||
});
|
||||
|
||||
it("names the database the server copies for a new one", () => {
|
||||
expect(templateOf("postgres", {})).toBe("template1");
|
||||
expect(templateOf("postgres", { template: "template0" })).toBe("template0");
|
||||
expect(templateOf("sqlServer", { template: "ignored" })).toBe("model");
|
||||
});
|
||||
|
||||
it("creates a SQL Server database with a collation", () => {
|
||||
expect(createDatabaseSql("sqlServer", "shop", { collation: "Latin1_General_CI_AS", owner: "ignored" })).toBe(
|
||||
"create database shop collate Latin1_General_CI_AS;",
|
||||
);
|
||||
});
|
||||
|
||||
it("creates a schema with an owner, and a MySQL schema as a database", () => {
|
||||
expect(createSchemaSql("postgres", "sales", {})).toBe("create schema sales;");
|
||||
expect(createSchemaSql("postgres", "sales", { owner: "app" })).toBe("create schema sales authorization app;");
|
||||
expect(createSchemaSql("sqlServer", "sales", { owner: "dbo" })).toBe("create schema sales authorization dbo;");
|
||||
expect(createSchemaSql("mysql", "shop", { charset: "utf8mb4", collation: "utf8mb4_0900_ai_ci" })).toBe(
|
||||
"create database shop character set utf8mb4 collate utf8mb4_0900_ai_ci;",
|
||||
);
|
||||
expect(createSchemaSql("mysql", "shop", {})).toBe("create database shop;");
|
||||
});
|
||||
|
||||
it("drops a database, forcing out other sessions when asked", () => {
|
||||
expect(dropDatabaseSql("postgres", "shop", false)).toBe("drop database shop;");
|
||||
expect(dropDatabaseSql("postgres", "shop", true)).toBe("drop database shop with (force);");
|
||||
expect(dropDatabaseSql("sqlServer", "shop", false)).toBe("drop database shop;");
|
||||
expect(dropDatabaseSql("sqlServer", "shop", true)).toBe(
|
||||
"alter database shop set single_user with rollback immediate;\ndrop database shop;",
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -180,6 +180,63 @@ export function truncateSql(
|
||||
return `truncate table ${q}${opts.restartIdentity ? " restart identity" : ""}${opts.cascade ? " cascade" : ""};`;
|
||||
}
|
||||
|
||||
const literal = (value: string) => `'${value.replace(/'/g, "''")}'`;
|
||||
|
||||
/** Options of New › Database / New › Schema; an empty or absent one is left to the server. */
|
||||
export interface CreateOptions {
|
||||
owner?: string;
|
||||
template?: string;
|
||||
encoding?: string;
|
||||
tablespace?: string;
|
||||
charset?: string;
|
||||
collation?: string;
|
||||
}
|
||||
|
||||
/** New › Database (PostgreSQL, SQL Server). */
|
||||
export function createDatabaseSql(driver: DbDriver, name: string, opts: CreateOptions): string {
|
||||
const clauses: string[] = [];
|
||||
const add = (keyword: string, value: string | undefined, quote = (v: string) => ident(driver, v)) => {
|
||||
if (value?.trim()) clauses.push(`${keyword} ${quote(value.trim())}`);
|
||||
};
|
||||
if (driver === "postgres") {
|
||||
add("owner", opts.owner);
|
||||
add("template", opts.template);
|
||||
add("encoding", opts.encoding, literal);
|
||||
add("tablespace", opts.tablespace);
|
||||
} else if (driver === "sqlServer") {
|
||||
add("collate", opts.collation, (v) => v);
|
||||
}
|
||||
return `create database ${ident(driver, name)}${clauses.map((c) => ` ${c}`).join("")};`;
|
||||
}
|
||||
|
||||
/** The database the server copies for New › Database: the chosen template on PostgreSQL, `model` on SQL Server. */
|
||||
export function templateOf(driver: DbDriver, opts: CreateOptions): string {
|
||||
return driver === "sqlServer" ? "model" : opts.template?.trim() || "template1";
|
||||
}
|
||||
|
||||
/** New › Schema; on MySQL a schema is a database, with a character set and collation instead of an owner. */
|
||||
export function createSchemaSql(driver: DbDriver, name: string, opts: CreateOptions): string {
|
||||
if (driver === "mysql") {
|
||||
const charset = opts.charset?.trim() ? ` character set ${opts.charset.trim()}` : "";
|
||||
const collation = opts.collation?.trim() ? ` collate ${opts.collation.trim()}` : "";
|
||||
return `create database ${ident(driver, name)}${charset}${collation};`;
|
||||
}
|
||||
const owner = opts.owner?.trim() ? ` authorization ${ident(driver, opts.owner.trim())}` : "";
|
||||
return `create schema ${ident(driver, name)}${owner};`;
|
||||
}
|
||||
|
||||
/**
|
||||
* Drop on a database node. `force` ends the sessions of other clients first:
|
||||
* `with (force)` on PostgreSQL 13+, single-user mode on SQL Server.
|
||||
*/
|
||||
export function dropDatabaseSql(driver: DbDriver, name: string, force: boolean): string {
|
||||
const db = ident(driver, name);
|
||||
// One batch: the session that sets single-user mode is the single user, so it must drop too.
|
||||
if (driver === "sqlServer" && force)
|
||||
return `alter database ${db} set single_user with rollback immediate;\ndrop database ${db};`;
|
||||
return `drop database ${db}${force && driver === "postgres" ? " with (force)" : ""};`;
|
||||
}
|
||||
|
||||
export type ScriptKind = "selectAll" | "selectFirst" | "insert" | "update" | "delete";
|
||||
|
||||
export const SCRIPT_LABELS: Record<ScriptKind, string> = {
|
||||
|
||||
@@ -130,6 +130,11 @@ export type DialogState =
|
||||
/** Confirm Drop / Truncate, with a preview of the statement. */
|
||||
| { kind: "drop"; id: string; object: DbObjectRef }
|
||||
| { kind: "truncate"; id: string; schema: string; table: string }
|
||||
/** New › Database of data source `id`; New › Schema in target `id`. */
|
||||
| { kind: "createDatabase"; id: string }
|
||||
| { kind: "createSchema"; id: string }
|
||||
/** Drop on database `database` of data source `id`. */
|
||||
| { kind: "dropDatabase"; id: string; database: string }
|
||||
/** Modify Table (`table` null: New › Table); `focusColumn` selects a column, `addColumn` starts a new one. */
|
||||
| { kind: "modifyTable"; id: string; schema: string; table: string | null; focusColumn?: string; addColumn?: boolean }
|
||||
/** Quick Documentation of a tree node, shown at `anchor` (client coordinates). */
|
||||
@@ -616,6 +621,20 @@ export function listsDatabases(source: DataSource | undefined): boolean {
|
||||
);
|
||||
}
|
||||
|
||||
/** New › Database and Drop on database nodes: PostgreSQL and SQL Server data sources that show their databases. */
|
||||
export function createsDatabases(source: DataSource | undefined): boolean {
|
||||
return listsDatabases(source) && source?.driver !== "snowflake";
|
||||
}
|
||||
|
||||
/** The target New › Schema creates a schema in: a database node, or a data source that shows schemas directly. */
|
||||
export function newSchemaTarget(n: DbNode): string | null {
|
||||
if (n.kind === "database") return createsDatabases(sourceById(n.id)) ? n.id : null;
|
||||
if (n.kind !== "source" || !n.source.id) return null;
|
||||
const driver = n.source.driver;
|
||||
if (driver !== "postgres" && driver !== "sqlServer" && driver !== "mysql") return null;
|
||||
return listsDatabases(n.source) ? null : n.source.id;
|
||||
}
|
||||
|
||||
interface LoadedLevels {
|
||||
schemas: string[];
|
||||
tables: [string, string][];
|
||||
@@ -1093,6 +1112,38 @@ export async function runSql(id: string, texts: string[]): Promise<boolean> {
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates a database on data source `id` with `sql` after disconnecting `template`, then refreshes
|
||||
* the data source, reloading what the tree had shown of `template` too.
|
||||
*/
|
||||
export async function createDatabase(id: string, template: string, sql: string): Promise<boolean> {
|
||||
const levels = loadedLevels(id);
|
||||
await disconnect(`${id}:${template}`);
|
||||
try {
|
||||
// Asks for a password the data source does not save, like any statement it runs.
|
||||
await withConnection(id, () => call(commands.dbCreateDatabase(id, template, sql)));
|
||||
} catch (e) {
|
||||
notifications().notify({ level: "error", title: tx`Cannot create database`, body: message(e) });
|
||||
void refresh(id, levels);
|
||||
return false;
|
||||
}
|
||||
void refresh(id, levels);
|
||||
return true;
|
||||
}
|
||||
|
||||
/** Drops `database` of data source `id` with `sql` after disconnecting it, then refreshes the data source. */
|
||||
export async function dropDatabase(id: string, database: string, sql: string): Promise<boolean> {
|
||||
await disconnect(`${id}:${database}`);
|
||||
try {
|
||||
await withConnection(id, () => call(commands.dbDropDatabase(id, database, sql)));
|
||||
} catch (e) {
|
||||
notifications().notify({ level: "error", title: tx`Cannot drop database ${database}`, body: message(e) });
|
||||
return false;
|
||||
}
|
||||
void refresh(id);
|
||||
return true;
|
||||
}
|
||||
|
||||
/** Opens the query console of `id` with `text` appended and selected (SQL Scripts › …). */
|
||||
export async function openConsoleWith(id: string, text: string): Promise<void> {
|
||||
let path: string;
|
||||
|
||||
@@ -15,6 +15,7 @@ import {
|
||||
DB_TOOL_WINDOW,
|
||||
OUTPUT_TAB,
|
||||
connect,
|
||||
createsDatabases,
|
||||
RESULTS_VIEW,
|
||||
detailsKey,
|
||||
disconnect,
|
||||
@@ -24,6 +25,7 @@ import {
|
||||
loadSources,
|
||||
loadTables,
|
||||
consoleFiles,
|
||||
newSchemaTarget,
|
||||
newConsole,
|
||||
openConsole,
|
||||
openConsoleFile,
|
||||
@@ -358,6 +360,9 @@ export function registerDatabaseTreeActions(): () => void {
|
||||
if (!n) return;
|
||||
const id = nodeTarget(n);
|
||||
if (n.kind === "source") return void removeSource(n.source);
|
||||
const source = sourceById(id);
|
||||
if (n.kind === "database" && !n.current && !source?.readOnly && createsDatabases(source))
|
||||
return openDialog({ kind: "dropDatabase", id: splitTarget(n.id).id, database: n.name });
|
||||
const o = objectOf(n);
|
||||
if (id && o && canDrop(driverOf(id), o)) openDialog({ kind: "drop", id, object: o });
|
||||
},
|
||||
@@ -390,6 +395,28 @@ export function registerDatabaseTreeActions(): () => void {
|
||||
});
|
||||
},
|
||||
}),
|
||||
tree({
|
||||
id: "db.newDatabase",
|
||||
title: "Database…",
|
||||
icon: "db-database",
|
||||
keywords: ["create database", "new database"],
|
||||
run: ({ arg }) => {
|
||||
const source = sourceOf(nodeFrom(arg));
|
||||
if (source?.id && !source.readOnly && createsDatabases(source))
|
||||
openDialog({ kind: "createDatabase", id: source.id });
|
||||
},
|
||||
}),
|
||||
tree({
|
||||
id: "db.newSchema",
|
||||
title: "Schema…",
|
||||
icon: "db-schema",
|
||||
keywords: ["create schema", "new schema"],
|
||||
run: ({ arg }) => {
|
||||
const n = nodeFrom(arg);
|
||||
const id = n && newSchemaTarget(n);
|
||||
if (id && !sourceById(id)?.readOnly) openDialog({ kind: "createSchema", id });
|
||||
},
|
||||
}),
|
||||
tree({
|
||||
id: "db.newTable",
|
||||
title: "Table",
|
||||
|
||||
@@ -5,7 +5,15 @@ import { fileSourceName, parseSourceUrl } from "./model";
|
||||
import { VENDORS, vendorPreset } from "./vendors";
|
||||
import { nodeTarget, objectOf, tableOf, type DbNode } from "./nodes";
|
||||
import { SCRIPT_LABELS, canDrop, canModifyTable, canRename, type ScriptKind } from "./objects";
|
||||
import { connectedTargets, openDialog, openSourceDialog, sourceById, useDatabase } from "./store";
|
||||
import {
|
||||
connectedTargets,
|
||||
createsDatabases,
|
||||
newSchemaTarget,
|
||||
openDialog,
|
||||
openSourceDialog,
|
||||
sourceById,
|
||||
useDatabase,
|
||||
} from "./store";
|
||||
import { readClipboardPlainText } from "@/platform/clipboard";
|
||||
import { useRemote } from "@/platform/remote";
|
||||
import { dumpScope, mysqlDumpScope } from "./dumpTools";
|
||||
@@ -113,6 +121,8 @@ export function nodeMenu(n: DbNode | null): MenuItem[] {
|
||||
const rename = act("db.rename", n, { disabled: !(n.kind === "source" || (o && canRename(driver, o))) });
|
||||
const drop = act("db.drop", n, { disabled: !o || !canDrop(driver, o) });
|
||||
const copyRef = act("db.copyReference", n);
|
||||
const readOnly = !!sourceById(id)?.readOnly;
|
||||
const newSchema = newSchemaTarget(n) ? [act("db.newSchema", n, { disabled: readOnly })] : [];
|
||||
const navigation = (extra: MenuItem[] = []): MenuItem => ({
|
||||
label: "Navigation",
|
||||
submenu: [...extra, act("db.jumpToConsole", n)],
|
||||
@@ -124,7 +134,18 @@ export function nodeMenu(n: DbNode | null): MenuItem[] {
|
||||
return [
|
||||
act("db.properties", n, { label: "Properties" }),
|
||||
sep,
|
||||
{ label: "New", icon: "plus", submenu: [newConsole, sep, ...dataSourceItems()] },
|
||||
{
|
||||
label: "New",
|
||||
icon: "plus",
|
||||
submenu: [
|
||||
newConsole,
|
||||
sep,
|
||||
...(createsDatabases(n.source) ? [act("db.newDatabase", n, { disabled: readOnly })] : []),
|
||||
...newSchema,
|
||||
...(createsDatabases(n.source) || newSchema.length ? [sep] : []),
|
||||
...dataSourceItems(),
|
||||
],
|
||||
},
|
||||
{ label: "Copy/Paste", submenu: [copyRef, act("db.duplicateSource", n)] },
|
||||
refresh,
|
||||
...(n.source.driver === "snowflake" ? [act("db.introspect", n)] : []),
|
||||
@@ -144,7 +165,7 @@ export function nodeMenu(n: DbNode | null): MenuItem[] {
|
||||
}
|
||||
case "database":
|
||||
return [
|
||||
{ label: "New", icon: "plus", submenu: [newConsole] },
|
||||
{ label: "New", icon: "plus", submenu: [newConsole, ...(newSchema.length ? [sep, ...newSchema] : [])] },
|
||||
{ label: "Copy/Paste", submenu: [copyRef] },
|
||||
refresh,
|
||||
act("db.disconnect", n, { disabled: !useDatabase.getState().connected.has(id) || n.current }),
|
||||
@@ -152,6 +173,7 @@ export function nodeMenu(n: DbNode | null): MenuItem[] {
|
||||
navigation(),
|
||||
sqlScripts(n, false),
|
||||
...importExport(dumpItems(n, true)),
|
||||
...(createsDatabases(sourceById(id)) ? [sep, act("db.drop", n, { disabled: n.current || readOnly })] : []),
|
||||
];
|
||||
case "schema":
|
||||
case "folder":
|
||||
|
||||
@@ -2459,6 +2459,22 @@
|
||||
"Resize Markdown preview": "Resize Markdown preview",
|
||||
"Run a Python script or module": "Run a Python script or module",
|
||||
"Replace every occurrence of '{pattern}' with '{replacement}' in the scope? The search hit its limit, so it runs again to find the occurrences not listed.": "Replace every occurrence of '{pattern}' with '{replacement}' in the scope? The search hit its limit, so it runs again to find the occurrences not listed.",
|
||||
"Server default": "Server default",
|
||||
"New Database": "New Database",
|
||||
"Owner:": "Owner:",
|
||||
"Restoring a dump needs template0: template1 can already hold extensions and schemas.": "Restoring a dump needs template0: template1 can already hold extensions and schemas.",
|
||||
"Encoding:": "Encoding:",
|
||||
"Tablespace:": "Tablespace:",
|
||||
"Collation:": "Collation:",
|
||||
"New Schema": "New Schema",
|
||||
"Character set:": "Character set:",
|
||||
"Drop database": "Drop database",
|
||||
"The IDE closes its own connections to the database first.": "The IDE closes its own connections to the database first.",
|
||||
"Close the sessions of other clients": "Close the sessions of other clients",
|
||||
"Cannot drop database {database}": "Cannot drop database {database}",
|
||||
"Cannot create database": "Cannot create database",
|
||||
"Database…": "Database…",
|
||||
"Schema…": "Schema…",
|
||||
"Alignment": "Alignment",
|
||||
"Align key-value pairs": "Align key-value pairs",
|
||||
"Align consecutive assignments": "Align consecutive assignments",
|
||||
|
||||
@@ -8834,6 +8834,22 @@
|
||||
"This Maven project is not loaded": "此 Maven 项目尚未加载",
|
||||
"Load Maven Project": "加载 Maven 项目",
|
||||
"Resize Markdown preview": "调整 Markdown 预览宽度",
|
||||
"Server default": "服务器默认值",
|
||||
"New Database": "新建数据库",
|
||||
"Owner:": "所有者:",
|
||||
"Restoring a dump needs template0: template1 can already hold extensions and schemas.": "恢复转储需要 template0:template1 中可能已有扩展和架构。",
|
||||
"Encoding:": "编码:",
|
||||
"Tablespace:": "表空间:",
|
||||
"Collation:": "排序规则:",
|
||||
"New Schema": "新建架构",
|
||||
"Character set:": "字符集:",
|
||||
"Drop database": "删除数据库",
|
||||
"The IDE closes its own connections to the database first.": "IDE 会先关闭它自己与该数据库的连接。",
|
||||
"Close the sessions of other clients": "关闭其他客户端的会话",
|
||||
"Cannot drop database {database}": "无法删除数据库 {database}",
|
||||
"Cannot create database": "无法创建数据库",
|
||||
"Database…": "数据库…",
|
||||
"Schema…": "架构…",
|
||||
"Alignment": "对齐",
|
||||
"Align key-value pairs": "对齐键值对",
|
||||
"Align consecutive assignments": "对齐连续赋值",
|
||||
|
||||
@@ -384,6 +384,7 @@ const ICONS = {
|
||||
"db-foreign-key": "openidea/database/foreignKey",
|
||||
"db-index": "openidea/database/index",
|
||||
"db-schema": "openidea/database/schema",
|
||||
"db-database": "openidea/database/database",
|
||||
"db-console": "openidea/database/console",
|
||||
"db-matview": "openidea/database/matview",
|
||||
"db-routine": "openidea/database/routine",
|
||||
|
||||
@@ -0,0 +1,4 @@
|
||||
<!-- OpenIDEA: database (two stacked rounded squares) -->
|
||||
<svg width="16" height="16" viewBox="0 0 16 16" fill="none" xmlns="http://www.w3.org/2000/svg">
|
||||
<path d="M5.5 4.5V3.5C5.5 2.94772 5.94772 2.5 6.5 2.5H12.5C13.0523 2.5 13.5 2.94772 13.5 3.5V9.5C13.5 10.0523 13.0523 10.5 12.5 10.5H11.5" stroke="#3574F0"/><rect x="2.5" y="4.5" width="9" height="9" rx="1" fill="#EDF3FF" stroke="#3574F0"/>
|
||||
</svg>
|
||||
|
After Width: | Height: | Size: 402 B |
@@ -0,0 +1,4 @@
|
||||
<!-- OpenIDEA: database (two stacked rounded squares) -->
|
||||
<svg width="16" height="16" viewBox="0 0 16 16" fill="none" xmlns="http://www.w3.org/2000/svg">
|
||||
<path d="M5.5 4.5V3.5C5.5 2.94772 5.94772 2.5 6.5 2.5H12.5C13.0523 2.5 13.5 2.94772 13.5 3.5V9.5C13.5 10.0523 13.0523 10.5 12.5 10.5H11.5" stroke="#548AF7"/><rect x="2.5" y="4.5" width="9" height="9" rx="1" fill="#25324D" stroke="#548AF7"/>
|
||||
</svg>
|
||||
|
After Width: | Height: | Size: 402 B |
Reference in New Issue
Block a user