дзеркало
https://github.com/l0ng-ai/openidea.git
синхронізовано 2026-11-28 21:42:27 +02:00
Порівняти коміти
| Автор | SHA1 | Дата | |
|---|---|---|---|
|
|
012ba7ace8 | ||
|
|
d16b852054 | ||
|
|
06223d9bd7 | ||
|
|
93c74a1f0f |
No files matched your search
@@ -217,6 +217,61 @@ impl SecretStore for FileSecretStore {
|
||||
}
|
||||
}
|
||||
|
||||
/// Plugin secrets in the OS credential store (Secret Service, Windows Credential
|
||||
/// Manager), like saved SSH and agent values. Without a credential store a value
|
||||
/// stays in the owner-only [`FileSecretStore`] file, which also still answers for
|
||||
/// values saved there by an older version until they are set again.
|
||||
pub struct CredentialSecretStore {
|
||||
store: ide_ssh::secrets::SecretFile,
|
||||
fallback: FileSecretStore,
|
||||
}
|
||||
|
||||
impl CredentialSecretStore {
|
||||
/// `dir`: the plugins' data directory (the index file and the fallback files live there).
|
||||
pub fn new(dir: PathBuf) -> Self {
|
||||
Self::with_store(ide_ssh::secrets::SecretFile::new(dir.join("plugin-secrets.json")), dir)
|
||||
}
|
||||
|
||||
fn with_store(store: ide_ssh::secrets::SecretFile, dir: PathBuf) -> Self {
|
||||
Self { store, fallback: FileSecretStore { dir } }
|
||||
}
|
||||
|
||||
fn key(plugin: &str, name: &str) -> String {
|
||||
format!("{plugin}/{name}")
|
||||
}
|
||||
|
||||
/// Drops a value from the fallback file, writing it only when it held one.
|
||||
fn forget_fallback(&self, plugin: &str, name: &str) -> Result<(), String> {
|
||||
if self.fallback.get(plugin, name).is_none() {
|
||||
return Ok(());
|
||||
}
|
||||
self.fallback.set(plugin, name, None)
|
||||
}
|
||||
}
|
||||
|
||||
impl SecretStore for CredentialSecretStore {
|
||||
fn get(&self, plugin: &str, name: &str) -> Option<String> {
|
||||
self.store.get(&Self::key(plugin, name)).or_else(|| self.fallback.get(plugin, name))
|
||||
}
|
||||
|
||||
fn set(&self, plugin: &str, name: &str, value: Option<&str>) -> Result<(), String> {
|
||||
let key = Self::key(plugin, name);
|
||||
match value {
|
||||
Some(v) => match self.store.set(&key, v) {
|
||||
Ok(()) => self.forget_fallback(plugin, name),
|
||||
Err(e) => {
|
||||
tracing::warn!("plugin secrets: {key} is kept in the plugin's data directory: {}", e.message);
|
||||
self.fallback.set(plugin, name, Some(v))
|
||||
}
|
||||
},
|
||||
None => {
|
||||
self.store.delete(&key);
|
||||
self.forget_fallback(plugin, name)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Largest response body a plugin receives.
|
||||
const MAX_RESPONSE: usize = 16 << 20;
|
||||
/// Largest stdout / stderr kept from a process by default.
|
||||
@@ -4210,6 +4265,67 @@ mod tests {
|
||||
assert_eq!(std::fs::read_to_string(&outside).unwrap(), "unchanged");
|
||||
}
|
||||
|
||||
/// Plugin secrets go to the credential store; a value an older version left in
|
||||
/// the owner-only file keeps working until it is set again, and then leaves the file.
|
||||
#[test]
|
||||
fn plugin_secrets_go_to_the_credential_store() {
|
||||
ide_ssh::secrets::testing::use_memory_store();
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let dir = tmp.path().join("plugins");
|
||||
FileSecretStore { dir: dir.clone() }.set("acme.lint", "old", Some("legacy-3f9a")).unwrap();
|
||||
let secrets = CredentialSecretStore::new(dir.clone());
|
||||
assert_eq!(secrets.get("acme.lint", "old").as_deref(), Some("legacy-3f9a"));
|
||||
|
||||
secrets.set("acme.lint", "token", Some("value-7c1e")).unwrap();
|
||||
secrets.set("acme.lint", "old", Some("moved-5d2b")).unwrap();
|
||||
let on_disk = ide_ssh::secrets::testing::files_containing(tmp.path(), "value-7c1e");
|
||||
assert_eq!(on_disk, Vec::<PathBuf>::new());
|
||||
assert_eq!(ide_ssh::secrets::testing::files_containing(tmp.path(), "legacy-3f9a"), Vec::<PathBuf>::new());
|
||||
let again = CredentialSecretStore::new(dir);
|
||||
assert_eq!(again.get("acme.lint", "token").as_deref(), Some("value-7c1e"));
|
||||
assert_eq!(again.get("acme.lint", "old").as_deref(), Some("moved-5d2b"));
|
||||
assert_eq!(again.get("other.plugin", "token"), None);
|
||||
|
||||
again.set("acme.lint", "token", None).unwrap();
|
||||
assert_eq!(again.get("acme.lint", "token"), None);
|
||||
}
|
||||
|
||||
/// Without a credential store a value stays in the owner-only file.
|
||||
#[test]
|
||||
fn plugin_secrets_without_a_credential_store_stay_in_the_file() {
|
||||
struct NoStore;
|
||||
impl ide_ssh::secrets::Vault for NoStore {
|
||||
fn available(&self) -> bool {
|
||||
false
|
||||
}
|
||||
fn get(&self, _: &str, _: &str) -> ide_ssh::secrets::StoreResult<String> {
|
||||
Err(ide_ssh::secrets::StoreError::NoDefaultStore)
|
||||
}
|
||||
fn set(&self, _: &str, _: &str, _: &str) -> ide_ssh::secrets::StoreResult<()> {
|
||||
Err(ide_ssh::secrets::StoreError::NoDefaultStore)
|
||||
}
|
||||
fn delete(&self, _: &str, _: &str) -> ide_ssh::secrets::StoreResult<()> {
|
||||
Err(ide_ssh::secrets::StoreError::NoDefaultStore)
|
||||
}
|
||||
}
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let dir = tmp.path().join("plugins");
|
||||
let store = ide_ssh::secrets::SecretFile::with_vault(
|
||||
dir.join("plugin-secrets.json"),
|
||||
|v| serde_json::from_value(v).ok(),
|
||||
Arc::new(NoStore),
|
||||
);
|
||||
let secrets = CredentialSecretStore::with_store(store, dir.clone());
|
||||
secrets.set("acme.lint", "token", Some("value-7c1e")).unwrap();
|
||||
assert_eq!(
|
||||
ide_ssh::secrets::testing::files_containing(tmp.path(), "value-7c1e"),
|
||||
[dir.join("acme.lint").join("secrets.json")]
|
||||
);
|
||||
assert_eq!(secrets.get("acme.lint", "token").as_deref(), Some("value-7c1e"));
|
||||
secrets.set("acme.lint", "token", None).unwrap();
|
||||
assert_eq!(secrets.get("acme.lint", "token"), None);
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn storage_and_secrets_refuse_symlinked_private_directories() {
|
||||
|
||||
@@ -63,7 +63,7 @@ pub mod views;
|
||||
pub mod web;
|
||||
mod websocket;
|
||||
|
||||
pub use api::{FileSecretStore, HostWorkspace, PluginWorkspace, SecretStore};
|
||||
pub use api::{CredentialSecretStore, FileSecretStore, HostWorkspace, PluginWorkspace, SecretStore};
|
||||
pub use build_graph::{BuildGraph, GradleModule};
|
||||
pub(crate) use hover::merge as merge_hover;
|
||||
pub use icons::{
|
||||
@@ -1949,6 +1949,12 @@ impl PluginHost {
|
||||
*self.shared.secrets.write() = store;
|
||||
}
|
||||
|
||||
/// Keeps plugin secrets in the OS credential store, with the owner-only
|
||||
/// files under the plugins directory as the fallback.
|
||||
pub fn use_credential_store(&self) {
|
||||
self.set_secret_store(Arc::new(CredentialSecretStore::new(self.shared.data_dir.clone())));
|
||||
}
|
||||
|
||||
/// Stores (or, with `None`, deletes) a secret the plugin declares under
|
||||
/// `[[contributes.secrets]]`.
|
||||
pub fn set_secret(&self, id: &str, name: &str, value: Option<&str>) -> IdeResult<()> {
|
||||
|
||||
@@ -118,6 +118,9 @@ pub fn create_host(app: &AppHandle, data_dir: &Path, project_host: &Arc<ide_host
|
||||
host.set_downloads(project_host.global_settings.effective().tool_downloads);
|
||||
#[cfg(target_os = "macos")]
|
||||
host.set_secret_store(Arc::new(KeychainSecrets));
|
||||
// Secret Service / Windows Credential Manager elsewhere, like saved SSH and agent values.
|
||||
#[cfg(not(target_os = "macos"))]
|
||||
host.use_credential_store();
|
||||
ide_host::plugins::set_editor_providers(Some(&host));
|
||||
let weak = Arc::downgrade(project_host);
|
||||
host.set_project_policy(Arc::new(move |root| {
|
||||
|
||||
@@ -120,6 +120,20 @@ export function viewMenu(
|
||||
];
|
||||
}
|
||||
|
||||
/** Copy as › SQL INSERT / UPDATE / DELETE of the whole selected rows, in the selected order. */
|
||||
function sqlCopies(rows: readonly number[], extractor: ExtractorMenu): MenuItem[] {
|
||||
const copy = (format: ExportFormat) => () =>
|
||||
void Promise.resolve(extractor.table()).then((data) => {
|
||||
const picked = data && rows.flatMap((r) => (data.rows[r] ? [data.rows[r]] : []));
|
||||
if (picked?.length) void writeClipboardText(exportData(format, { ...data!, rows: picked }));
|
||||
});
|
||||
return [
|
||||
{ label: "SQL INSERT", run: copy("sql") },
|
||||
{ label: "SQL UPDATE", run: copy("sqlUpdates") },
|
||||
{ label: "SQL DELETE", run: copy("sqlDeletes") },
|
||||
];
|
||||
}
|
||||
|
||||
/** The Record / Value / Aggregates panel's toggle (IDEA's "Show Value Editor"). */
|
||||
export function PanelToggle({ panel, onChange }: { panel: DataPanel | null; onChange: (p: DataPanel | null) => void }) {
|
||||
return (
|
||||
@@ -300,6 +314,7 @@ export function DataView(props: DataViewProps) {
|
||||
driver={props.driver}
|
||||
sort={sort}
|
||||
onSort={onSort}
|
||||
copyAs={props.extractor && ((rows) => sqlCopies(rows.map(at), props.extractor!))}
|
||||
rowMenu={(rows) => {
|
||||
const own = props.rowMenu?.(rows.map(at)) ?? [];
|
||||
const view = viewMenu(panel, onPanelChange, props.extractor);
|
||||
|
||||
@@ -10,6 +10,7 @@ import { notifications } from "@/workbench/contributions";
|
||||
import {
|
||||
DEFAULT_EXPORT_OPTIONS,
|
||||
EXPORT_FORMATS,
|
||||
SQL_FORMATS,
|
||||
exportData,
|
||||
type ExportData,
|
||||
type ExportFormat,
|
||||
@@ -169,7 +170,7 @@ export function ExportDialog({
|
||||
<CodePreview
|
||||
className={styles.exportPreviewText}
|
||||
aria-label="Export preview"
|
||||
sql={format === "sql"}
|
||||
sql={SQL_FORMATS.has(format)}
|
||||
text={preview + (data.rows.length > PREVIEW_ROWS ? `\n… ${data.rows.length - PREVIEW_ROWS} more rows` : "")}
|
||||
/>
|
||||
</div>
|
||||
|
||||
@@ -1084,4 +1084,35 @@ describe("the data view's context menu (DataGrip)", () => {
|
||||
"false",
|
||||
);
|
||||
});
|
||||
|
||||
it("copies the selected whole rows as SQL INSERT / UPDATE / DELETE (#6143)", async () => {
|
||||
const writeText = vi.fn((_text: string) => Promise.resolve());
|
||||
Object.defineProperty(navigator, "clipboard", { configurable: true, value: { writeText } });
|
||||
const keyed = [{ ...columns[0]!, primaryKey: true }, columns[1]!];
|
||||
const table = () => ({ columns: keyed, rows: data, table: "cities", driver: "postgres" as const });
|
||||
render(
|
||||
<>
|
||||
<DataView
|
||||
columns={keyed}
|
||||
rowCount={2}
|
||||
value={value}
|
||||
panel={null}
|
||||
onPanelChange={() => {}}
|
||||
extractor={{ value: "csv", onChange: () => {}, table }}
|
||||
/>
|
||||
<ContextMenuHost />
|
||||
</>,
|
||||
);
|
||||
// Only the second row's city cell: the statements still cover its whole row.
|
||||
fireEvent.mouseDown(screen.getAllByRole("gridcell")[3]!, { button: 0 });
|
||||
const copyAs = async (entry: string) => {
|
||||
fireEvent.contextMenu(screen.getByRole("grid"), { clientX: 5, clientY: 5 });
|
||||
fireEvent.click(screen.getByRole("menuitem", { name: /^Copy as/ }));
|
||||
await act(async () => void fireEvent.click(screen.getByRole("menuitem", { name: new RegExp(`^${entry}`) })));
|
||||
return writeText.mock.lastCall?.[0];
|
||||
};
|
||||
expect(await copyAs("SQL INSERT")).toBe("INSERT INTO cities (id, city) VALUES (2, 'Beijing');");
|
||||
expect(await copyAs("SQL UPDATE")).toBe("UPDATE cities SET city = 'Beijing' WHERE id = 2;");
|
||||
expect(await copyAs("SQL DELETE")).toBe("DELETE FROM cities WHERE id = 2;");
|
||||
});
|
||||
});
|
||||
@@ -86,6 +86,8 @@ export interface GridProps {
|
||||
onSort?: (column: string, add: boolean) => void;
|
||||
/** Extra context menu items for the selected rows. */
|
||||
rowMenu?: (rows: number[]) => MenuItem[];
|
||||
/** More Copy as entries for the selected rows (SQL statements of the whole rows). */
|
||||
copyAs?: (rows: number[]) => MenuItem[];
|
||||
/** Row number shown for row 0 (paging). */
|
||||
firstRowNumber?: number;
|
||||
/** Row number shown for a row (local sort / filter reorder them); `firstRowNumber + row` otherwise. */
|
||||
@@ -629,6 +631,10 @@ export function Grid(props: GridProps) {
|
||||
{ kind: "action", action: "db.copyAsTsv", label: "TSV", arg: cellActions.current },
|
||||
{ kind: "action", action: "db.copyAsCsv", label: "CSV", arg: cellActions.current },
|
||||
{ kind: "action", action: "db.copyAsOneRow", label: "One-Row", arg: cellActions.current },
|
||||
...(() => {
|
||||
const more = props.copyAs?.(selectedRows()) ?? [];
|
||||
return more.length ? [{ kind: "separator" } as const, ...more] : [];
|
||||
})(),
|
||||
],
|
||||
},
|
||||
{ kind: "action", action: "db.copyWithHeader", arg: cellActions.current },
|
||||
|
||||
@@ -469,7 +469,12 @@ export function Result({ tab, onClose }: { tab: ResultTab; onClose?: () => void
|
||||
return null;
|
||||
}
|
||||
}
|
||||
return { columns, rows: rowsOf(r), driver, table: queryTable(text, { driver }) };
|
||||
return {
|
||||
columns: gridColumns.map((c) => ({ name: c.name, type: c.type, primaryKey: c.primaryKey })),
|
||||
rows: rowsOf(r),
|
||||
driver,
|
||||
table: queryTable(text, { driver }),
|
||||
};
|
||||
};
|
||||
const showExport = async (at: { x: number; y: number }) => {
|
||||
const data = await exportSource();
|
||||
|
||||
@@ -195,3 +195,60 @@ it.each<ExportFormat>(["csv", "tsv", "sql", "markdown", "onerow"])("%s retains e
|
||||
const value = "9223372036854775807";
|
||||
expect(exportData(format, data(value))).toContain(value);
|
||||
});
|
||||
|
||||
describe("SQL statements of rows (#6143)", () => {
|
||||
const rows: ExportData = {
|
||||
columns: [
|
||||
{ name: "id", type: "INTEGER", primaryKey: true },
|
||||
{ name: "name", type: "TEXT" },
|
||||
{ name: "note", type: "TEXT" },
|
||||
],
|
||||
rows: [
|
||||
["2", "O'Hara", null],
|
||||
["1", "Ann", "x"],
|
||||
],
|
||||
table: "people",
|
||||
driver: "postgres",
|
||||
};
|
||||
|
||||
it("writes one statement per row, in order, matching rows by the primary key", () => {
|
||||
expect(exportData("sql", rows)).toBe(
|
||||
[
|
||||
`INSERT INTO people (id, name, note) VALUES (2, 'O''Hara', NULL);`,
|
||||
`INSERT INTO people (id, name, note) VALUES (1, 'Ann', 'x');`,
|
||||
].join("\n"),
|
||||
);
|
||||
expect(exportData("sqlUpdates", rows)).toBe(
|
||||
[
|
||||
`UPDATE people SET name = 'O''Hara', note = NULL WHERE id = 2;`,
|
||||
`UPDATE people SET name = 'Ann', note = 'x' WHERE id = 1;`,
|
||||
].join("\n"),
|
||||
);
|
||||
expect(exportData("sqlDeletes", rows)).toBe(
|
||||
[`DELETE FROM people WHERE id = 2;`, `DELETE FROM people WHERE id = 1;`].join("\n"),
|
||||
);
|
||||
expect(exportData("where", rows)).toBe(`WHERE (id = 2) OR (id = 1)`);
|
||||
expect(exportData("where", { ...rows, rows: rows.rows.slice(1) })).toBe(`WHERE id = 1`);
|
||||
});
|
||||
|
||||
it("matches on every column, saying so, when no key is known, and writes IS NULL for a null", () => {
|
||||
const keyless = { ...rows, columns: rows.columns.map((c) => ({ ...c, primaryKey: false })), rows: [rows.rows[0]!] };
|
||||
expect(exportData("sqlDeletes", keyless)).toBe(
|
||||
`-- No primary key is known: rows are matched on every column.\n` +
|
||||
`DELETE FROM people WHERE id = 2 AND name = 'O''Hara' AND note IS NULL;`,
|
||||
);
|
||||
// A null key value too.
|
||||
const nullKey = { ...rows, rows: [[null, "x", "y"]] };
|
||||
expect(exportData("sqlDeletes", nullKey)).toBe(`DELETE FROM people WHERE id IS NULL;`);
|
||||
});
|
||||
|
||||
it("escapes backslashes for drivers that read them, as SQL Inserts did", () => {
|
||||
const d: ExportData = {
|
||||
columns: [{ name: "p", type: "String" }],
|
||||
rows: [["a\\b'"]],
|
||||
table: "t",
|
||||
driver: "clickhouse",
|
||||
};
|
||||
expect(exportData("sql", d)).toBe(`INSERT INTO t (p) VALUES ('a\\\\b''');`);
|
||||
});
|
||||
});
|
||||
@@ -7,24 +7,40 @@
|
||||
import type { DbDriver } from "@/platform/ipc";
|
||||
import { jsonNumber } from "@/platform/losslessJson";
|
||||
import { isNumericColumn } from "./Grid";
|
||||
import { toCsv, toOneRow, toTsv, type Cell } from "./model";
|
||||
import { sqlLiteral, toCsv, toOneRow, toTsv, type Cell } from "./model";
|
||||
import { quoteIdent } from "./sql/complete";
|
||||
|
||||
export type ExportFormat = "csv" | "tsv" | "json" | "sql" | "markdown" | "onerow";
|
||||
export type ExportFormat =
|
||||
| "csv"
|
||||
| "tsv"
|
||||
| "json"
|
||||
| "sql"
|
||||
| "sqlUpdates"
|
||||
| "sqlDeletes"
|
||||
| "where"
|
||||
| "markdown"
|
||||
| "onerow";
|
||||
|
||||
/** The formats written as SQL (highlighted as SQL in the Export Data preview). */
|
||||
export const SQL_FORMATS: ReadonlySet<ExportFormat> = new Set(["sql", "sqlUpdates", "sqlDeletes", "where"]);
|
||||
|
||||
export const EXPORT_FORMATS: ReadonlyArray<{ id: ExportFormat; label: string; extension: string }> = [
|
||||
{ id: "csv", label: "CSV", extension: "csv" },
|
||||
{ id: "tsv", label: "TSV", extension: "tsv" },
|
||||
{ id: "json", label: "JSON", extension: "json" },
|
||||
{ id: "sql", label: "SQL Inserts", extension: "sql" },
|
||||
{ id: "sqlUpdates", label: "SQL Updates", extension: "sql" },
|
||||
{ id: "sqlDeletes", label: "SQL Deletes", extension: "sql" },
|
||||
{ id: "where", label: "Where Clause", extension: "sql" },
|
||||
{ id: "markdown", label: "Markdown", extension: "md" },
|
||||
{ id: "onerow", label: "One-Row", extension: "txt" },
|
||||
];
|
||||
|
||||
export interface ExportData {
|
||||
columns: ReadonlyArray<{ name: string; type: string }>;
|
||||
/** `primaryKey` columns identify a row in SQL Updates, SQL Deletes and Where Clause. */
|
||||
columns: ReadonlyArray<{ name: string; type: string; primaryKey?: boolean }>;
|
||||
rows: ReadonlyArray<readonly Cell[]>;
|
||||
/** Target of SQL inserts (the query's table, when it reads one). */
|
||||
/** Target of SQL statements (the query's table, when it reads one). */
|
||||
table: string;
|
||||
driver: DbDriver;
|
||||
}
|
||||
@@ -89,16 +105,11 @@ export function exportData(
|
||||
});
|
||||
return rows.length ? `[\n${rows.join(",\n")}\n]` : "[]";
|
||||
}
|
||||
case "sql": {
|
||||
const literal = (v: Cell, i: number) =>
|
||||
v === null
|
||||
? "NULL"
|
||||
: numeric[i] && Number.isFinite(Number(v))
|
||||
? v
|
||||
: `'${(d.driver === "clickhouse" || d.driver === "snowflake" ? v.replace(/\\/g, "\\\\") : v).replace(/'/g, "''")}'`;
|
||||
const head = `INSERT INTO ${quoteIdent(d.table, d.driver)} (${names.map((n) => quoteIdent(n, d.driver)).join(", ")}) VALUES`;
|
||||
return d.rows.map((r) => `${head} (${r.map(literal).join(", ")});`).join("\n");
|
||||
}
|
||||
case "sql":
|
||||
case "sqlUpdates":
|
||||
case "sqlDeletes":
|
||||
case "where":
|
||||
return sqlStatements(format, d, numeric);
|
||||
case "markdown": {
|
||||
const cell = (v: Cell) => (v ?? "").replace(/\|/g, "\\|").replace(/\r?\n/g, " ");
|
||||
const t = laidOut(d, options);
|
||||
@@ -115,3 +126,41 @@ export function exportData(
|
||||
return toOneRow(d.rows, (c) => numeric[c]!);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* SQL Inserts, Updates, Deletes and the Where Clause of the rows, one statement per row in
|
||||
* their order. A row is identified by its primary key columns; with none known, by every
|
||||
* column, which the text says first.
|
||||
*/
|
||||
function sqlStatements(format: ExportFormat, d: ExportData, numeric: readonly boolean[]): string {
|
||||
const ident = (name: string) => quoteIdent(name, d.driver);
|
||||
const names = d.columns.map((c) => ident(c.name));
|
||||
const literal = (v: Cell | undefined, i: number) => sqlLiteral(v ?? null, numeric[i]!, d.driver);
|
||||
const table = ident(d.table);
|
||||
if (format === "sql")
|
||||
return d.rows
|
||||
.map((r) => `INSERT INTO ${table} (${names.join(", ")}) VALUES (${r.map(literal).join(", ")});`)
|
||||
.join("\n");
|
||||
const keys = d.columns.flatMap((c, i) => (c.primaryKey ? [i] : []));
|
||||
const match = keys.length ? keys : names.map((_, i) => i);
|
||||
const where = (r: readonly Cell[]) =>
|
||||
match.map((i) => (r[i] == null ? `${names[i]} IS NULL` : `${names[i]} = ${literal(r[i], i)}`)).join(" AND ");
|
||||
const note = keys.length || !d.rows.length ? "" : "-- No primary key is known: rows are matched on every column.\n";
|
||||
if (format === "where") {
|
||||
if (!d.rows.length) return "";
|
||||
const body = d.rows.length === 1 ? where(d.rows[0]!) : d.rows.map((r) => `(${where(r)})`).join(" OR ");
|
||||
return `${note}WHERE ${body}`;
|
||||
}
|
||||
if (format === "sqlDeletes") return note + d.rows.map((r) => `DELETE FROM ${table} WHERE ${where(r)};`).join("\n");
|
||||
// Updates set the other columns (every column when no key is known).
|
||||
const set = keys.length ? names.flatMap((_, i) => (keys.includes(i) ? [] : [i])) : match;
|
||||
return (
|
||||
note +
|
||||
d.rows
|
||||
.map(
|
||||
(r) =>
|
||||
`UPDATE ${table} SET ${set.map((i) => `${names[i]} = ${literal(r[i], i)}`).join(", ")} WHERE ${where(r)};`,
|
||||
)
|
||||
.join("\n")
|
||||
);
|
||||
}
|
||||
@@ -30,9 +30,18 @@ export function toTsv(header: readonly string[] | null, rows: ReadonlyArray<read
|
||||
* single-quoted with `'` doubled. `numeric(c)` decides quoting per column.
|
||||
*/
|
||||
export function toOneRow(rows: ReadonlyArray<readonly Cell[]>, numeric: (col: number) => boolean): string {
|
||||
const literal = (v: Cell, c: number) =>
|
||||
v === null ? "NULL" : numeric(c) && Number.isFinite(Number(v)) ? v : `'${v.replace(/'/g, "''")}'`;
|
||||
return rows.flatMap((r) => r.map(literal)).join(", ");
|
||||
return rows.flatMap((r) => r.map((v, c) => sqlLiteral(v, numeric(c)))).join(", ");
|
||||
}
|
||||
|
||||
/**
|
||||
* A value as an SQL literal: NULL, a number unquoted in a numeric column, else single-quoted
|
||||
* with `'` doubled (and `\\` doubled for drivers that read backslash escapes in strings).
|
||||
*/
|
||||
export function sqlLiteral(v: Cell, numeric: boolean, driver?: DbDriver): string {
|
||||
if (v === null) return "NULL";
|
||||
if (numeric && Number.isFinite(Number(v))) return v;
|
||||
const escaped = driver === "clickhouse" || driver === "snowflake" ? v.replace(/\\/g, "\\\\") : v;
|
||||
return `'${escaped.replace(/'/g, "''")}'`;
|
||||
}
|
||||
|
||||
/** RFC 4180 CSV; NULL is an empty field. */
|
||||
|
||||
@@ -4160,5 +4160,11 @@
|
||||
"Filter columns": "Filter columns",
|
||||
"Package Registries": "Package Registries",
|
||||
"Use only the configured package registries": "Use only the configured package registries",
|
||||
"For a company registry such as Nexus or Artifactory: installing tools and agents never retries against the public npm registry when the configured one refuses or misses a package, and the IDE fetches nothing from Maven Central, npm, PyPI or crates.io itself (the JUnit launcher, dependency version completion).": "For a company registry such as Nexus or Artifactory: installing tools and agents never retries against the public npm registry when the configured one refuses or misses a package, and the IDE fetches nothing from Maven Central, npm, PyPI or crates.io itself (the JUnit launcher, dependency version completion)."
|
||||
"For a company registry such as Nexus or Artifactory: installing tools and agents never retries against the public npm registry when the configured one refuses or misses a package, and the IDE fetches nothing from Maven Central, npm, PyPI or crates.io itself (the JUnit launcher, dependency version completion).": "For a company registry such as Nexus or Artifactory: installing tools and agents never retries against the public npm registry when the configured one refuses or misses a package, and the IDE fetches nothing from Maven Central, npm, PyPI or crates.io itself (the JUnit launcher, dependency version completion).",
|
||||
"SQL Updates": "SQL Updates",
|
||||
"SQL Deletes": "SQL Deletes",
|
||||
"Where Clause": "Where Clause",
|
||||
"SQL INSERT": "SQL INSERT",
|
||||
"SQL UPDATE": "SQL UPDATE",
|
||||
"SQL DELETE": "SQL DELETE"
|
||||
}
|
||||
@@ -10175,5 +10175,11 @@
|
||||
"Filter columns": "Фильтр столбцов",
|
||||
"Package Registries": "Реестры пакетов",
|
||||
"Use only the configured package registries": "Использовать только настроенные реестры пакетов",
|
||||
"For a company registry such as Nexus or Artifactory: installing tools and agents never retries against the public npm registry when the configured one refuses or misses a package, and the IDE fetches nothing from Maven Central, npm, PyPI or crates.io itself (the JUnit launcher, dependency version completion).": "Для корпоративного реестра, например Nexus или Artifactory: при установке инструментов и агентов не выполняется повторная попытка через публичный реестр npm, если настроенный реестр отклонил пакет или не нашёл его, а сама IDE ничего не загружает из Maven Central, npm, PyPI или crates.io (JUnit Launcher, автодополнение версий зависимостей)."
|
||||
"For a company registry such as Nexus or Artifactory: installing tools and agents never retries against the public npm registry when the configured one refuses or misses a package, and the IDE fetches nothing from Maven Central, npm, PyPI or crates.io itself (the JUnit launcher, dependency version completion).": "Для корпоративного реестра, например Nexus или Artifactory: при установке инструментов и агентов не выполняется повторная попытка через публичный реестр npm, если настроенный реестр отклонил пакет или не нашёл его, а сама IDE ничего не загружает из Maven Central, npm, PyPI или crates.io (JUnit Launcher, автодополнение версий зависимостей).",
|
||||
"SQL Updates": "SQL-обновления",
|
||||
"SQL Deletes": "SQL-удаления",
|
||||
"Where Clause": "Условие WHERE",
|
||||
"SQL INSERT": "SQL INSERT",
|
||||
"SQL UPDATE": "SQL UPDATE",
|
||||
"SQL DELETE": "SQL DELETE"
|
||||
}
|
||||
@@ -8836,5 +8836,11 @@
|
||||
"Filter columns": "Sütunları filtrele",
|
||||
"Package Registries": "Paket Kayıt Defterleri",
|
||||
"Use only the configured package registries": "Yalnızca yapılandırılmış paket kayıt defterlerini kullan",
|
||||
"For a company registry such as Nexus or Artifactory: installing tools and agents never retries against the public npm registry when the configured one refuses or misses a package, and the IDE fetches nothing from Maven Central, npm, PyPI or crates.io itself (the JUnit launcher, dependency version completion).": "Nexus veya Artifactory gibi bir şirket kayıt defteri için: araçlar ve ajanlar yüklenirken yapılandırılmış kayıt defteri bir paketi reddederse ya da bulamazsa genel npm kayıt defterinde yeniden denenmez ve IDE kendisi Maven Central, npm, PyPI veya crates.io'dan hiçbir şey indirmez (JUnit başlatıcısı, bağımlılık sürümü tamamlama)."
|
||||
"For a company registry such as Nexus or Artifactory: installing tools and agents never retries against the public npm registry when the configured one refuses or misses a package, and the IDE fetches nothing from Maven Central, npm, PyPI or crates.io itself (the JUnit launcher, dependency version completion).": "Nexus veya Artifactory gibi bir şirket kayıt defteri için: araçlar ve ajanlar yüklenirken yapılandırılmış kayıt defteri bir paketi reddederse ya da bulamazsa genel npm kayıt defterinde yeniden denenmez ve IDE kendisi Maven Central, npm, PyPI veya crates.io'dan hiçbir şey indirmez (JUnit başlatıcısı, bağımlılık sürümü tamamlama).",
|
||||
"SQL Updates": "SQL Güncelleme İfadeleri",
|
||||
"SQL Deletes": "SQL Silme İfadeleri",
|
||||
"Where Clause": "WHERE Koşulu",
|
||||
"SQL INSERT": "SQL INSERT",
|
||||
"SQL UPDATE": "SQL UPDATE",
|
||||
"SQL DELETE": "SQL DELETE"
|
||||
}
|
||||
@@ -9374,5 +9374,11 @@
|
||||
"Filter columns": "篩選欄",
|
||||
"Package Registries": "套件倉庫",
|
||||
"Use only the configured package registries": "僅使用已設定的套件倉庫",
|
||||
"For a company registry such as Nexus or Artifactory: installing tools and agents never retries against the public npm registry when the configured one refuses or misses a package, and the IDE fetches nothing from Maven Central, npm, PyPI or crates.io itself (the JUnit launcher, dependency version completion).": "適用於 Nexus、Artifactory 等公司倉庫:安裝工具和 agent 時,若已設定的倉庫拒絕或找不到某個套件,不再改從公開 npm 倉庫重試;IDE 本身也不會從 Maven Central、npm、PyPI 或 crates.io 取得任何內容(JUnit 啟動器、相依版本補全)。"
|
||||
"For a company registry such as Nexus or Artifactory: installing tools and agents never retries against the public npm registry when the configured one refuses or misses a package, and the IDE fetches nothing from Maven Central, npm, PyPI or crates.io itself (the JUnit launcher, dependency version completion).": "適用於 Nexus、Artifactory 等公司倉庫:安裝工具和 agent 時,若已設定的倉庫拒絕或找不到某個套件,不再改從公開 npm 倉庫重試;IDE 本身也不會從 Maven Central、npm、PyPI 或 crates.io 取得任何內容(JUnit 啟動器、相依版本補全)。",
|
||||
"SQL Updates": "SQL Update 陳述式",
|
||||
"SQL Deletes": "SQL Delete 陳述式",
|
||||
"Where Clause": "Where 子句",
|
||||
"SQL INSERT": "SQL INSERT 陳述式",
|
||||
"SQL UPDATE": "SQL UPDATE 陳述式",
|
||||
"SQL DELETE": "SQL DELETE 陳述式"
|
||||
}
|
||||
@@ -10604,5 +10604,11 @@
|
||||
"Filter columns": "过滤列",
|
||||
"Package Registries": "包仓库",
|
||||
"Use only the configured package registries": "仅使用已配置的包仓库",
|
||||
"For a company registry such as Nexus or Artifactory: installing tools and agents never retries against the public npm registry when the configured one refuses or misses a package, and the IDE fetches nothing from Maven Central, npm, PyPI or crates.io itself (the JUnit launcher, dependency version completion).": "适用于 Nexus、Artifactory 等公司仓库:安装工具和 agent 时,若已配置的仓库拒绝或找不到某个包,不再改从公共 npm 仓库重试;IDE 自身也不会从 Maven Central、npm、PyPI 或 crates.io 获取任何内容(JUnit 启动器、依赖版本补全)。"
|
||||
"For a company registry such as Nexus or Artifactory: installing tools and agents never retries against the public npm registry when the configured one refuses or misses a package, and the IDE fetches nothing from Maven Central, npm, PyPI or crates.io itself (the JUnit launcher, dependency version completion).": "适用于 Nexus、Artifactory 等公司仓库:安装工具和 agent 时,若已配置的仓库拒绝或找不到某个包,不再改从公共 npm 仓库重试;IDE 自身也不会从 Maven Central、npm、PyPI 或 crates.io 获取任何内容(JUnit 启动器、依赖版本补全)。",
|
||||
"SQL Updates": "SQL Update 语句",
|
||||
"SQL Deletes": "SQL Delete 语句",
|
||||
"Where Clause": "Where 子句",
|
||||
"SQL INSERT": "SQL INSERT 语句",
|
||||
"SQL UPDATE": "SQL UPDATE 语句",
|
||||
"SQL DELETE": "SQL DELETE 语句"
|
||||
}
|
||||
Reference in new issue
Заблокувати користувача