diff --git a/docs/en/release-notes.md b/docs/en/release-notes.md
index 50bf414..027d661 100644
--- a/docs/en/release-notes.md
+++ b/docs/en/release-notes.md
@@ -10,6 +10,7 @@ These changes are on `main` and will be part of the next pre-release; the downlo
- **Indexes in database diagrams.** Each table of a diagram has an **Indexes** section, closed by default, with one row per index when opened: method (GIN, GiST, SP-GiST, BRIN, Hash), key columns or expressions, operator class when not the default (such as `gin_trgm_ops`), `INCLUDE`, UNIQUE, EXCLUDE, partial and invalid, with the predicate and the full `CREATE INDEX` in the tooltip. A warning marks a table with a foreign key that no index serves and opens **Find Unindexed Foreign Keys…**, which also arrives in this change: on a database in Object Explorer it lists such keys from the catalog and creates the indexes from a reviewed script, concurrently or in one transaction. **Show Indexes** and **Refresh** are in the diagram menu. Each save writes the indexes of each table into the diagram definition for tools and AI agents that read it; older diagrams open unchanged. Read only: indexes are still created in **Indexes/Keys…**. SSMS 22.11 shows no indexes in a diagram. Suggested by a PGMS user.
- **Descriptions in database diagrams and Export for AI.** A table, column or relationship of a diagram can have a description, which is its PostgreSQL `COMMENT ON`, so any tool that reads the catalog sees it. Edit it in **Description Property** from the table, column or relationship menu (or click the small page icon that marks a described item, with the text in its tooltip); **Save** applies it after the script review, like every change in a diagram. If you do not own the table, the description is kept in the diagram as not applied and PGMS shows the script to send to the owner. Each save keeps a copy of the descriptions in the diagram definition (format 3); when the database changed one since, the diagram shows the database text and an orange icon. **Export for AI…** writes the tables of the diagram as Markdown (columns, keys, relationships, indexes and descriptions, in a fixed order, with an instruction for the agent at the top) to copy or save, for a system prompt, a `CLAUDE.md` or an `AGENTS.md`. The optional function `pgms.diagram_markdown(name)`, created only after you review its script, returns the same text to an agent connected to the database. See [Using diagrams with AI agents](user-guide.md#using-diagrams-with-ai-agents). In SSMS 22.11 descriptions are edited in the Properties window; the icons, the copy and the export are PGMS additions. Suggested by a PGMS user.
+- **Windows opened from an object follow that object.** **Restore Database…** and **Back Up…** ask for the database when the server or the Databases folder is selected, instead of using the login database, and a new name creates the database for the restore; **Pending Index Operation…** of a table shows only its operation; **Object Permissions…**, **Default Permissions…** and **Tools ▸ Table Operations…** start on the selection; the operation dialogs of a table also work from a folder, index or column under it; a plan tab no longer offers **Show Execution Plan In New Tab**, which did nothing there. In a diagram, **Table View** with no table selected changes every table, and **Undo** now also reverts a Table View change.
## What changed since v0.1.0-alpha.4
diff --git a/docs/en/user-guide.md b/docs/en/user-guide.md
index 5e00181..deaefff 100644
--- a/docs/en/user-guide.md
+++ b/docs/en/user-guide.md
@@ -18,9 +18,9 @@ Identity and sequence operations distinguish configured START from RESTART. A re
## Database diagrams
-In Object Explorer, right-click **Database Diagrams** under a database and choose **New Database Diagram**. The first time, PGMS asks to create its support objects (schema `pgms`). Add tables with **Add Table** or **Add Related Tables**, drag a column onto another to create a foreign key, and use **Arrange Tables** to lay them out. Saving shows the SQL script of any change to the database for review.
+In Object Explorer, right-click **Database Diagrams** under a database and choose **New Database Diagram**. The first time, PGMS asks to create its support objects (schema `pgms`). Add tables with **Add Table** or **Add Related Tables**, drag a column onto another to create a foreign key, and use **Arrange Tables** to lay them out. Saving shows the SQL script of any change to the database for review. **Table View** in the toolbar changes the selected tables; with no table selected it changes every table of the diagram, in one step of Undo.
-**Indexes.** Each table shows an **Indexes** section below its columns, closed by default so diagrams laid out before keep their spacing: the header gives the count and the methods other than b-tree (for example `Indexes (3) · GIN`), and its tooltip lists every index. Click the header to show one row per index: name, method when it is not b-tree (Hash, GIN, GiST, SP-GiST, BRIN), key columns or expressions, the operator class when it is not the default (such as `gin_trgm_ops`, `jsonb_path_ops` or `text_pattern_ops`), `INCLUDE` columns, and UNIQUE, EXCLUDE, partial or invalid. The row tooltip has the predicate of a partial index and the full `CREATE INDEX`. A gold key marks the primary key, a silver key a unique or exclusion constraint, and a tree a plain index. A warning triangle in the title marks a table with a foreign key that no index serves, by the same rule as **Find Unindexed Foreign Keys…**; click it, or use the item of the table menu, to open that window. **Show Indexes** in the diagram menu turns the sections and the warning off and on for that diagram, and **Refresh** reads the tables and their indexes again. The section is read only: create or change indexes in **Indexes/Keys…** (double-click an index row) and the other dialogs. Every save writes the indexes of each table, read from the catalog inside the save transaction, into the diagram definition (`pgms.diagrams.definition`), so tools and AI agents that read the diagram see them; changes made only in the database do not mark the diagram as changed and reach the definition on its next save. Diagrams saved by earlier versions open as they were and are written in the new format by their next save. SSMS 22.11 shows no indexes in a diagram; this section is a PGMS addition.
+**Indexes.** Each table shows an **Indexes** section below its columns, closed by default so diagrams laid out before keep their spacing: the header gives the count and the methods other than b-tree (for example `Indexes (3) · GIN`), and its tooltip lists every index. Click the header to show one row per index: name, method when it is not b-tree (Hash, GIN, GiST, SP-GiST, BRIN), key columns or expressions, the operator class when it is not the default (such as `gin_trgm_ops`, `jsonb_path_ops` or `text_pattern_ops`), `INCLUDE` columns, and UNIQUE, EXCLUDE, partial or invalid. The row tooltip has the predicate of a partial index and the full `CREATE INDEX`. A gold key marks the primary key, a silver key a unique or exclusion constraint, and a tree a plain index. A warning triangle in the title marks a table with a foreign key that no index serves, by the same rule as **Find Unindexed Foreign Keys…**; click it, or use the item of the table menu, to open that window for that table only, already scanned (from Object Explorer it covers the whole database and waits for **Scan**). **Show Indexes** in the diagram menu turns the sections and the warning off and on for that diagram, and **Refresh** reads the tables and their indexes again. The section is read only: create or change indexes in **Indexes/Keys…** (double-click an index row) and the other dialogs. Every save writes the indexes of each table, read from the catalog inside the save transaction, into the diagram definition (`pgms.diagrams.definition`), so tools and AI agents that read the diagram see them; changes made only in the database do not mark the diagram as changed and reach the definition on its next save. Diagrams saved by earlier versions open as they were and are written in the new format by their next save. SSMS 22.11 shows no indexes in a diagram; this section is a PGMS addition.
## Query Designer
@@ -75,7 +75,7 @@ PGMS has no MCP server of its own.
## Backup and restore
-Choose compatible PostgreSQL tools and a new output file/directory. Custom, tar, plain SQL and directory formats support the documented content choices. Restore uses an existing target database; compatible objects/roles and permissions must already exist where required. Ownership and privileges are explicit choices. Directory backup supports parallel dump; restore remains serial. Global operations cover roles/memberships/tablespaces, not a physical cluster backup.
+Choose compatible PostgreSQL tools and a new output file/directory. Custom, tar, plain SQL and directory formats support the documented content choices. Restore goes into the selected database; with the server or the Databases folder selected, PGMS asks for it, and a new name creates the database (`TEMPLATE template0`) after confirmation; compatible objects/roles and permissions must already exist where required. Ownership and privileges are explicit choices. Directory backup supports parallel dump; restore remains serial. Global operations cover roles/memberships/tablespaces, not a physical cluster backup.
Only run trusted SQL scripts: psql scripts may include local commands, reconnects and COMMIT. Single-transaction options cannot override those commands. Cancellation can arrive after a commit. Encrypted client keys, CR/LF in tool passwords and non-ASCII TEMP paths have documented restrictions. Keep the source backup unchanged and inspect the destination after failures. The [distribution guide](distribution.md) describes tools, permissions and package requirements.
diff --git a/docs/pt-BR/release-notes.md b/docs/pt-BR/release-notes.md
index 131f97e..910b2de 100644
--- a/docs/pt-BR/release-notes.md
+++ b/docs/pt-BR/release-notes.md
@@ -10,6 +10,7 @@ Estas mudanças estão no `main` e farão parte da próxima pré-release; os dow
- **Índices nos diagramas de banco.** Cada tabela de um diagrama tem uma seção **Indexes**, recolhida por padrão, com uma linha por índice quando aberta: método (GIN, GiST, SP-GiST, BRIN, Hash), colunas ou expressões da chave, classe de operadores quando não é a padrão (como `gin_trgm_ops`), `INCLUDE`, UNIQUE, EXCLUDE, parcial e inválido, com o predicado e o `CREATE INDEX` completo na dica. Um aviso marca a tabela com chave estrangeira que nenhum índice atende e abre **Find Unindexed Foreign Keys…**, que também chega nesta mudança: num banco do Object Explorer, lista essas chaves pelo catálogo e cria os índices a partir de um script revisado, de forma concorrente ou em uma transação. **Show Indexes** e **Refresh** ficam no menu do diagrama. Cada gravação escreve os índices de cada tabela na definição do diagrama para ferramentas e agentes de IA que a leem; diagramas antigos abrem sem mudança. Só leitura: índices continuam sendo criados em **Indexes/Keys…**. O SSMS 22.11 não mostra índices no diagrama. Sugestão de um usuário do PGMS.
- **Descrições nos diagramas de banco e exportação para IA.** Tabela, coluna e relação de um diagrama podem ter descrição, que é o `COMMENT ON` do objeto no PostgreSQL, então qualquer ferramenta que lê o catálogo a enxerga. Edite em **Description Property** pelo menu da tabela, da coluna ou da relação (ou clique no pequeno ícone de página que marca o item descrito, com o texto na dica); **Save** aplica depois da revisão do script, como toda mudança do diagrama. Se você não é o dono da tabela, a descrição fica no diagrama como não aplicada e o PGMS mostra o script para enviar ao dono. Cada gravação guarda uma cópia das descrições na definição do diagrama (formato 3); quando o banco mudou alguma depois disso, o diagrama mostra o texto do banco e um ícone laranja. **Export for AI…** escreve as tabelas do diagrama em Markdown (colunas, chaves, relações, índices e descrições, em ordem fixa, com uma instrução para o agente no topo) para copiar ou salvar, para um system prompt, um `CLAUDE.md` ou um `AGENTS.md`. A função opcional `pgms.diagram_markdown(name)`, criada só depois de você revisar o script, devolve o mesmo texto a um agente conectado ao banco. Veja [Usando diagramas com agentes de IA](user-guide.md#usando-diagramas-com-agentes-de-ia). No SSMS 22.11 as descrições são editadas na janela Properties; os ícones, a cópia e a exportação são acréscimos do PGMS. Sugestão de um usuário do PGMS.
+- **Janelas abertas a partir de um objeto seguem esse objeto.** **Restore Database…** e **Back Up…** pedem o banco quando o servidor ou a pasta Databases estão selecionados, em vez de usar o banco de login, e um nome novo cria o banco para a restauração; **Pending Index Operation…** de uma tabela mostra só a operação dela; **Object Permissions…**, **Default Permissions…** e **Tools ▸ Table Operations…** partem da seleção; os diálogos de operação de uma tabela funcionam também a partir de pasta, índice ou coluna dela; a aba de plano não oferece mais **Show Execution Plan In New Tab**, que nela não fazia nada. No diagrama, o **Table View** sem tabela selecionada muda todas as tabelas, e o **Undo** passa a desfazer também a troca de Table View.
## O que mudou desde a v0.1.0-alpha.4
diff --git a/docs/pt-BR/user-guide.md b/docs/pt-BR/user-guide.md
index 00798be..c6e36ef 100644
--- a/docs/pt-BR/user-guide.md
+++ b/docs/pt-BR/user-guide.md
@@ -18,9 +18,9 @@ Identity e sequences distinguem START configurado de RESTART. Reiniciar pode rep
## Diagramas de banco de dados
-No Object Explorer, clique com o botão direito em **Database Diagrams**, dentro de um banco, e escolha **New Database Diagram**. Na primeira vez, o PGMS pede para criar seus objetos de suporte (schema `pgms`). Adicione tabelas com **Add Table** ou **Add Related Tables**, arraste uma coluna sobre outra para criar uma chave estrangeira e use **Arrange Tables** para organizar. Ao salvar, o PGMS mostra o script SQL de qualquer alteração no banco para revisão.
+No Object Explorer, clique com o botão direito em **Database Diagrams**, dentro de um banco, e escolha **New Database Diagram**. Na primeira vez, o PGMS pede para criar seus objetos de suporte (schema `pgms`). Adicione tabelas com **Add Table** ou **Add Related Tables**, arraste uma coluna sobre outra para criar uma chave estrangeira e use **Arrange Tables** para organizar. Ao salvar, o PGMS mostra o script SQL de qualquer alteração no banco para revisão. O **Table View** da barra muda as tabelas selecionadas; sem tabela selecionada, muda todas as tabelas do diagrama, num passo de Undo.
-**Índices.** Cada tabela mostra uma seção **Indexes** abaixo das colunas, recolhida por padrão para que diagramas já organizados mantenham o espaçamento: o cabeçalho traz a quantidade e os métodos que não são b-tree (por exemplo `Indexes (3) · GIN`), e a dica dele lista todos os índices. Clique no cabeçalho para ver uma linha por índice: nome, método quando não é b-tree (Hash, GIN, GiST, SP-GiST, BRIN), colunas ou expressões da chave, a classe de operadores quando não é a padrão (como `gin_trgm_ops`, `jsonb_path_ops` ou `text_pattern_ops`), colunas `INCLUDE` e UNIQUE, EXCLUDE, parcial (partial) ou inválido (invalid). A dica da linha traz o predicado de um índice parcial e o `CREATE INDEX` completo. Uma chave dourada marca a chave primária, uma chave prateada uma constraint UNIQUE ou de exclusão, e uma árvore um índice comum. Um triângulo de aviso no título marca a tabela com chave estrangeira que nenhum índice atende, pela mesma regra de **Find Unindexed Foreign Keys…**; clique nele, ou use o item do menu da tabela, para abrir essa janela. **Show Indexes**, no menu do diagrama, liga e desliga as seções e o aviso naquele diagrama, e **Refresh** lê de novo as tabelas e seus índices. A seção é só leitura: crie ou altere índices em **Indexes/Keys…** (duplo clique numa linha de índice) e nos outros diálogos. Toda gravação escreve os índices de cada tabela, lidos do catálogo dentro da transação da gravação, na definição do diagrama (`pgms.diagrams.definition`), para que ferramentas e agentes de IA que leem o diagrama os vejam; mudanças feitas só no banco não marcam o diagrama como alterado e chegam à definição na próxima gravação. Diagramas salvos por versões anteriores abrem como estavam e passam ao formato novo na próxima gravação. O SSMS 22.11 não mostra índices no diagrama; esta seção é um acréscimo do PGMS.
+**Índices.** Cada tabela mostra uma seção **Indexes** abaixo das colunas, recolhida por padrão para que diagramas já organizados mantenham o espaçamento: o cabeçalho traz a quantidade e os métodos que não são b-tree (por exemplo `Indexes (3) · GIN`), e a dica dele lista todos os índices. Clique no cabeçalho para ver uma linha por índice: nome, método quando não é b-tree (Hash, GIN, GiST, SP-GiST, BRIN), colunas ou expressões da chave, a classe de operadores quando não é a padrão (como `gin_trgm_ops`, `jsonb_path_ops` ou `text_pattern_ops`), colunas `INCLUDE` e UNIQUE, EXCLUDE, parcial (partial) ou inválido (invalid). A dica da linha traz o predicado de um índice parcial e o `CREATE INDEX` completo. Uma chave dourada marca a chave primária, uma chave prateada uma constraint UNIQUE ou de exclusão, e uma árvore um índice comum. Um triângulo de aviso no título marca a tabela com chave estrangeira que nenhum índice atende, pela mesma regra de **Find Unindexed Foreign Keys…**; clique nele, ou use o item do menu da tabela, para abrir essa janela só com essa tabela, já varrida (pelo Object Explorer ela cobre o banco inteiro e espera o **Scan**). **Show Indexes**, no menu do diagrama, liga e desliga as seções e o aviso naquele diagrama, e **Refresh** lê de novo as tabelas e seus índices. A seção é só leitura: crie ou altere índices em **Indexes/Keys…** (duplo clique numa linha de índice) e nos outros diálogos. Toda gravação escreve os índices de cada tabela, lidos do catálogo dentro da transação da gravação, na definição do diagrama (`pgms.diagrams.definition`), para que ferramentas e agentes de IA que leem o diagrama os vejam; mudanças feitas só no banco não marcam o diagrama como alterado e chegam à definição na próxima gravação. Diagramas salvos por versões anteriores abrem como estavam e passam ao formato novo na próxima gravação. O SSMS 22.11 não mostra índices no diagrama; esta seção é um acréscimo do PGMS.
## Query Designer
@@ -75,7 +75,7 @@ O PGMS não tem servidor MCP próprio.
## Backup e restauração
-Escolha ferramentas PostgreSQL compatíveis e arquivo/diretório de saída novo. Custom, tar, SQL e diretório oferecem as opções de conteúdo documentadas. Restore usa banco de destino existente; objetos/roles compatíveis e permissões precisam existir quando exigidos. Ownership e privilégios são escolhas explícitas. Backup em diretório oferece dump paralelo; restore continua serial. Operações globais cobrem roles/memberships/tablespaces, não backup físico do cluster.
+Escolha ferramentas PostgreSQL compatíveis e arquivo/diretório de saída novo. Custom, tar, SQL e diretório oferecem as opções de conteúdo documentadas. Restore vai para o banco selecionado; com o servidor ou a pasta Databases selecionados, o PGMS pede o banco, e um nome novo cria o banco (`TEMPLATE template0`) depois de confirmar; objetos/roles compatíveis e permissões precisam existir quando exigidos. Ownership e privilégios são escolhas explícitas. Backup em diretório oferece dump paralelo; restore continua serial. Operações globais cobrem roles/memberships/tablespaces, não backup físico do cluster.
Execute apenas scripts SQL confiáveis: scripts psql podem conter comandos locais, reconexões e COMMIT. Transação única não anula esses comandos. Cancelamento pode chegar após commit. Chaves cliente criptografadas, CR/LF nas senhas das ferramentas e TEMP não ASCII têm restrições documentadas. Preserve o backup original e confira o destino após falhas. O [guia de distribuição](distribution.md) descreve ferramentas, permissões e requisitos do pacote.
diff --git a/src/PGMS.Desktop/BackupDialog.xaml b/src/PGMS.Desktop/BackupDialog.xaml
index da82826..94f660f 100644
--- a/src/PGMS.Desktop/BackupDialog.xaml
+++ b/src/PGMS.Desktop/BackupDialog.xaml
@@ -8,6 +8,7 @@
+
diff --git a/src/PGMS.Desktop/BackupDialog.xaml.cs b/src/PGMS.Desktop/BackupDialog.xaml.cs
index 4e19129..67725e1 100644
--- a/src/PGMS.Desktop/BackupDialog.xaml.cs
+++ b/src/PGMS.Desktop/BackupDialog.xaml.cs
@@ -19,18 +19,32 @@ private sealed record ScopeChoice(BackupDataScope Value,string Label);
private readonly string connectionString;
private CancellationTokenSource? cancellation;
public bool WasCompleted { get; private set; }
+ /// Opened without a database (the Databases folder or the server): the database is chosen in the dialog, and nothing runs until it is.
+ private readonly bool chooseDatabase;
+ private IReadOnlyList databases = [];
+ /// Replaces the confirmation before a new database is created for a restore; returns true to create it. Set by tests.
+ internal Func? ConfirmCreateDatabase { get; set; }
+ /// The database the operation ran against; with a chosen database, the one chosen.
+ public string? Database { get; private set; }
- public BackupDialog(bool restore, string connectionString, bool globals=false)
+ public BackupDialog(bool restore, string connectionString, bool globals=false, bool chooseDatabase=false)
{
InitializeComponent();
this.restore = restore;
this.globals = globals;
this.connectionString = connectionString;
+ this.chooseDatabase = chooseDatabase && !globals;
var c = new NpgsqlConnectionStringBuilder(connectionString);
Title = restore ? "Restore Database" : "Back Up Database";
if(globals)Title=restore?"Restore Global Objects":"Back Up Global Objects";
RunButton.Content = restore ? "Restore" : "Back Up";
- Target.Text = $"{Title}\nServer: {c.Host}:{c.Port} Database: {c.Database} User: {c.Username}";
+ Target.Text = $"{Title}\nServer: {c.Host}:{c.Port} Database: {(this.chooseDatabase ? "chosen below" : c.Database)} User: {c.Username}";
+ if(this.chooseDatabase)
+ {
+ DatabaseFields.Visibility=Visibility.Visible;DatabasePicker.IsEditable=restore;
+ DatabaseHelp.Text=restore?"Choose the database to restore into, or type a new name: the database is created first (CREATE DATABASE … TEMPLATE template0), after you confirm.":"Choose the database to back up.";
+ Loaded+=async(_,_)=>await LoadDatabasesAsync();
+ }
FormatSelector.ItemsSource=restore?new[]{new FormatChoice(BackupFormat.Custom,"Custom or tar archive"),new(BackupFormat.PlainSql,"Plain SQL script"),new(BackupFormat.Directory,"Directory archive")}
:new[]{new FormatChoice(BackupFormat.Custom,"Custom archive"),new(BackupFormat.Tar,"Tar archive"),new(BackupFormat.PlainSql,"Plain SQL script"),new(BackupFormat.Directory,"Directory archive")};FormatSelector.SelectedIndex=0;
ScopeSelector.ItemsSource=new[]{new ScopeChoice(BackupDataScope.All,"Schema and data"),new(BackupDataScope.SchemaOnly,"Schema only"),new(BackupDataScope.DataOnly,"Data only")};ScopeSelector.SelectedIndex=0;
@@ -46,6 +60,30 @@ public BackupDialog(bool restore, string connectionString, bool globals=false)
ready=true;
UpdateOptions();
}
+ internal async Task LoadDatabasesAsync()
+ {
+ try
+ {
+ await using var connection=new NpgsqlConnection(connectionString);await connection.OpenAsync();
+ await using var command=new NpgsqlCommand("SELECT datname FROM pg_catalog.pg_database WHERE NOT datistemplate AND datallowconn ORDER BY datname",connection);
+ var names=new List();await using(var reader=await command.ExecuteReaderAsync())while(await reader.ReadAsync())names.Add(reader.GetString(0));
+ databases=names;DatabasePicker.ItemsSource=names;
+ }
+ catch(Exception ex)when(ex is NpgsqlException or IOException or InvalidOperationException or TimeoutException){DatabaseHelp.Text="The list of databases could not be read: "+ex.Message+(restore?" Type the name of the database.":"");}
+ UpdateDatabase();
+ }
+ private string ChosenDatabase=>(DatabasePicker.IsEditable?DatabasePicker.Text:DatabasePicker.SelectedItem as string??"").Trim();
+ private bool ChosenIsNew=>ChosenDatabase.Length>0 && !databases.Contains(ChosenDatabase,StringComparer.Ordinal);
+ private void DatabaseChanged(object sender,System.Windows.Controls.SelectionChangedEventArgs e){if(ready)UpdateDatabase();}
+ private void DatabaseTextChanged(object sender,System.Windows.Controls.TextChangedEventArgs e){if(ready)UpdateDatabase();}
+ private void UpdateDatabase()
+ {
+ if(!chooseDatabase)return;
+ ClearPreviousFeedback();
+ if(ChosenDatabase.Length==0)DatabaseHelp.Text=restore?"Choose the database to restore into, or type a new name: the database is created first (CREATE DATABASE … TEMPLATE template0), after you confirm.":"Choose the database to back up.";
+ else if(ChosenIsNew)DatabaseHelp.Text=restore?$"{ChosenDatabase} does not exist: it is created first (CREATE DATABASE … TEMPLATE template0), after you confirm, and kept if the restore fails.":$"{ChosenDatabase} does not exist.";
+ else DatabaseHelp.Text=restore?$"The archive is restored into the existing database {ChosenDatabase}.":$"{ChosenDatabase} is backed up.";
+ }
private BackupFormat Format=>((FormatChoice)FormatSelector.SelectedItem).Value;
private BackupCompression Compression=>Format is BackupFormat.Custom or BackupFormat.Directory?((CompressionChoice)CompressionSelector.SelectedItem).Value:BackupCompression.Default;
private BackupDataScope Scope=>((ScopeChoice)ScopeSelector.SelectedItem).Value;
@@ -77,6 +115,7 @@ private void UpdateOptions()
Description.Text=restore
?sql?"Run a trusted SQL script with psql in this existing database. Ownership and privileges follow the script contents. Existing objects are not dropped automatically.":"Restore an archive into this existing database in one transaction. Choose content below. Definitions require absent target objects; data-only requires compatible existing tables. Existing objects are not dropped. Choose whether to restore archive ownership and object privileges below."
:"Back up this database using the selected format and content. Choose a new destination; existing files and directories are not overwritten. Server roles and tablespaces are not included.";
+ if(chooseDatabase)Description.Text=Description.Text.Replace("this existing database","the database chosen above").Replace("this database","the database chosen above");
FormatHelp.Text=restore
?sql?"psql requests one transaction and stops on errors. Explicit COMMIT, reconnect or transaction commands in a script can commit earlier changes. Review the script before running it.":"pg_restore reads custom, tar and directory archives. Restore errors before COMMIT roll back the transaction."
:Scope==BackupDataScope.DataOnly?"Data-only restore requires compatible tables already present in the destination.":sql?"Plain SQL is restored with psql. Choose ownership and privilege commands now; they cannot be omitted later by archive restore options.":"Custom, tar and directory archives use pg_restore. Ownership and privilege choices are made when restoring.";
@@ -134,6 +173,23 @@ internal async Task RunAsync()
if(cancellation is not null)return;
if (string.IsNullOrWhiteSpace(ArchivePath.Text) || string.IsNullOrWhiteSpace(ToolsPath.Text)) { Feedback.Text = "Select a backup path and the PostgreSQL bin folder."; return; }
WasCompleted = false;
+ string target=connectionString;
+ bool created=false;
+ if(chooseDatabase)
+ {
+ string name=ChosenDatabase;
+ if(name.Length==0){Feedback.Text=restore?"Choose the database to restore into, or type the name of a new one.":"Choose the database to back up.";return;}
+ if(ChosenIsNew)
+ {
+ if(!restore){Feedback.Text=$"{name} does not exist. Choose an existing database.";return;}
+ string question=$"Create the database {name} and restore into it?\n\nIt is created with CREATE DATABASE … TEMPLATE template0 and kept if the restore fails.";
+ if(!(ConfirmCreateDatabase?.Invoke(name) ?? MessageBox.Show(this,question,Title,MessageBoxButton.YesNo,MessageBoxImage.Question,MessageBoxResult.No)==MessageBoxResult.Yes))return;
+ try{await BackupService.CreateRestoreDatabaseAsync(connectionString,name);created=true;databases=[..databases,name];}
+ catch(Exception ex)when(ex is NpgsqlException or ArgumentException or IOException or InvalidOperationException or TimeoutException){Feedback.Text="The database was not created: "+(ex is PostgresException pg?$"{pg.SqlState}: {pg.MessageText}":ex.Message);return;}
+ }
+ target=new NpgsqlConnectionStringBuilder(connectionString){Database=name}.ConnectionString;
+ }
+ Database=new NpgsqlConnectionStringBuilder(target).Database;
if(globals && restore)
{
if(GlobalReviewed.IsChecked!=true){Feedback.Text="Review the global SQL script and destination, then confirm the review checkbox.";return;}
@@ -150,18 +206,19 @@ internal async Task RunAsync()
Feedback.Text = restore ? "Restoring database…" : "Creating backup…";
try
{
- var service = new BackupService(connectionString, ToolsPath.Text);
+ var service = new BackupService(target, ToolsPath.Text);
if(globals){if(restore)await service.RestoreGlobalsAsync(ArchivePath.Text,cancellation.Token);else await service.BackupGlobalsAsync(ArchivePath.Text,cancellation.Token);}
else if (restore){if(Format==BackupFormat.PlainSql)await service.RestoreSqlAsync(ArchivePath.Text,cancellation.Token);else if(Format==BackupFormat.Directory)await service.RestoreDirectoryAsync(ArchivePath.Text,Options,cancellation.Token);else await service.RestoreWithOptionsAsync(ArchivePath.Text,Options,cancellation.Token);}
else await service.BackupWithOptionsAsync(ArchivePath.Text,DumpOptions,cancellation.Token);
WasCompleted = true;
- Feedback.Text = restore ? "Restore completed successfully." : "Backup completed successfully.\n" + Path.GetFullPath(ArchivePath.Text);
+ Feedback.Text = restore ? "Restore completed successfully." + (chooseDatabase ? $" Database: {Database}." : "") : "Backup completed successfully.\n" + Path.GetFullPath(ArchivePath.Text);
}
catch (OperationCanceledException) { Feedback.Text = globals && restore?"Global restore canceled. Earlier statements may already be committed. Inspect the destination before retrying.":restore ? "Restore canceled. Check the destination before retrying: cancellation can arrive after the server commits." : "Backup canceled. No destination was published."; }
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException or ArgumentException or Win32Exception or InvalidOperationException) { Feedback.Text = ex.Message; }
finally
{
cancellation.Dispose(); cancellation = null;
+ if (created && !WasCompleted) Feedback.Text += $" The database {Database}, created for this restore, was kept; drop it if it is not needed.";
RunButton.IsEnabled = ArchivePath.IsEnabled = ToolsPath.IsEnabled = BrowseButton.IsEnabled = ToolsButton.IsEnabled = true;
RestoreScopeSelector.IsEnabled=RestoreOwner.IsEnabled=RestoreAcl.IsEnabled=true;
LargeObjectsSelector.IsEnabled=CompressionSelector.IsEnabled=CompressionLevelSelector.IsEnabled=JobsSelector.IsEnabled=FormatSelector.IsEnabled=ScopeSelector.IsEnabled=SqlDumpOwner.IsEnabled=SqlDumpAcl.IsEnabled=true;
diff --git a/src/PGMS.Desktop/ConcurrentIndexDialog.xaml.cs b/src/PGMS.Desktop/ConcurrentIndexDialog.xaml.cs
index 1a1f241..87ce67a 100644
--- a/src/PGMS.Desktop/ConcurrentIndexDialog.xaml.cs
+++ b/src/PGMS.Desktop/ConcurrentIndexDialog.xaml.cs
@@ -22,7 +22,10 @@ private sealed record MaintenanceChoice(IndexMaintenanceOperation Value,string L
private bool busy, initialized, unavailable, attempted, inspectedInactive;
public bool WasApplied { get; private set; }
public bool RequiresParentRefresh { get; private set; }
- public ConcurrentIndexDialog(string connection, ExpressionIndexEdit? proposal = null, MaintenanceIndexSnapshot? maintenance = null)
+ /// Pending Index Operation… of a table: shows the pending operation only when it is on this table, and otherwise names the table it is on.
+ public ConcurrentIndexDialog(string connection, CatalogEntry table) : this(connection, null, null, table) { }
+
+ public ConcurrentIndexDialog(string connection, ExpressionIndexEdit? proposal = null, MaintenanceIndexSnapshot? maintenance = null, CatalogEntry? table = null)
{
this.connection=connection;this.maintenance=maintenance;this.proposal=proposal;store=new(connection);service=new(connection,store);InitializeComponent();
var profile=new NpgsqlConnectionStringBuilder(connection);
@@ -43,8 +46,16 @@ public ConcurrentIndexDialog(string connection, ExpressionIndexEdit? proposal =
try
{
lease=store.AcquireLease();pending=store.Read();
+ // From a table: the pending operation of the connection is shown only when it is on that table; otherwise the table it is on is named.
+ string? relation=table is null?null:ObjectSql.Relation(table.Schema??"",table.Name);
+ ConcurrentIndexReceipt? elsewhere=null;
+ if(table is not null && pending is not null && !(table.Oid!=0 && pending.TableOid!=0 ? pending.TableOid==table.Oid : pending.Schema==table.Schema && pending.Table==table.Name)){elsewhere=pending;pending=null;}
+ if(relation is not null)Target.Text+="\n"+relation;
if(pending is not null){Preview.Text=pending.Sql;Target.Text+=$"\nPending: {ObjectSql.Relation(pending.Schema,pending.Table)} / {pending.Index}";}
- Feedback.Text=pending is null?(proposal is null?"No pending operation. Prepare an index proposal in Expression Index to create concurrently.":"Review the standalone command before creating the index."):"A previous operation is pending. Inspect its recorded target; the stored SQL will not be executed.";
+ Feedback.Text=elsewhere is not null?$"No pending operation on {relation}. The pending operation of this connection is on {ObjectSql.Relation(elsewhere.Schema,elsewhere.Table)} / {elsewhere.Index}; open Pending Index Operation… on that table to inspect it."
+ :pending is not null?"A previous operation is pending. Inspect its recorded target; the stored SQL will not be executed."
+ :relation is not null?$"No pending operation on {relation}."
+ :proposal is null?"No pending operation. Prepare an index proposal in Expression Index to create concurrently.":"Review the standalone command before creating the index.";
}
catch(Exception ex)when(Handled(ex)){unavailable=true;Feedback.Text=ex.Message;}
initialized=true;Update();Closed+=(_,_)=>lease?.Dispose();
diff --git a/src/PGMS.Desktop/DatabaseDiagramView.Editing.cs b/src/PGMS.Desktop/DatabaseDiagramView.Editing.cs
index 1252df9..00745f2 100644
--- a/src/PGMS.Desktop/DatabaseDiagramView.Editing.cs
+++ b/src/PGMS.Desktop/DatabaseDiagramView.Editing.cs
@@ -99,17 +99,23 @@ private void AddFieldCells(Grid row, DiagramTableModel table, DesignColumn colum
private void TableViewClick(object sender, RoutedEventArgs e)
{
var menu = new ContextMenu { PlacementTarget = TableViewButton, Placement = System.Windows.Controls.Primitives.PlacementMode.Bottom };
- FillTableViewItems(menu.Items, selected.FirstOrDefault());
+ FillTableViewItems(menu.Items, selected.FirstOrDefault(), toolbar: true);
menu.IsOpen = true;
}
- private void FillTableViewItems(ItemCollection items, DiagramTableModel? table)
+ /// The Table View items. From the toolbar with no table selected (pedido do usuário, 12/11/2026), the five views apply to every table of the diagram;
+ /// Modify Custom … stays off, since each table keeps its own custom columns.
+ /// The items the Table View button of the toolbar shows now; for tests.
+ internal void FillToolbarTableView(ItemCollection items) => FillTableViewItems(items, selected.FirstOrDefault(), toolbar: true);
+
+ private void FillTableViewItems(ItemCollection items, DiagramTableModel? table, bool toolbar = false)
{
items.Clear();
+ bool all = toolbar && selected.Count == 0 && tables.Count > 0;
void Add(string header, string name, DiagramTableView view)
{
- var item = new MenuItem { Header = header, Name = name, IsEnabled = table is not null, IsChecked = table is not null && selected.Count > 0 && selected.All(t => t.View == view) };
- item.Click += (_, _) => SetTableView(view);
+ var item = new MenuItem { Header = header, Name = name, IsEnabled = table is not null || all, IsChecked = all ? tables.All(t => t.View == view) : table is not null && selected.Count > 0 && selected.All(t => t.View == view) };
+ item.Click += (_, _) => { if (all) SetAllTablesView(view); else SetTableView(view); };
items.Add(item);
}
Add("Standard", "DiagramViewStandard", DiagramTableView.Standard);
@@ -123,12 +129,27 @@ void Add(string header, string name, DiagramTableView view)
items.Add(modify);
}
- /// Applies a view to the selected tables; the box and the lines follow its new size.
+ /// Applies a view to the selected tables; the box and the lines follow its new size. One step of Undo.
public void SetTableView(DiagramTableView view)
{
CommitEdit();
if (selected.Count == 0) return;
- foreach (var table in selected) table.View = view;
+ ApplyView(selected.ToList(), view);
+ }
+
+ /// Table View from the toolbar with nothing selected: every table of the diagram, in one step of Undo; the selection stays empty.
+ public void SetAllTablesView(DiagramTableView view)
+ {
+ CommitEdit();
+ if (tables.Count == 0) return;
+ ApplyView(tables, view);
+ }
+
+ private void ApplyView(IReadOnlyCollection targets, DiagramTableView view)
+ {
+ if (targets.All(t => t.View == view)) return;
+ PushUndo(TakeSnapshot());
+ foreach (var table in targets) table.View = view;
Rebuild(); Touch();
}
diff --git a/src/PGMS.Desktop/DatabaseDiagramView.xaml.cs b/src/PGMS.Desktop/DatabaseDiagramView.xaml.cs
index 73950b1..88e5415 100644
--- a/src/PGMS.Desktop/DatabaseDiagramView.xaml.cs
+++ b/src/PGMS.Desktop/DatabaseDiagramView.xaml.cs
@@ -236,7 +236,7 @@ private void ApplyRoutes(IEnumerable saved)
// ---- Undo of the layout (pedido do usuário, 08/11/2026): Arrange Tables, moving tables and moving lines record where things were ----
/// Positions by table key and hand-placed lines by (table key, foreign key name), so a refresh of the tables does not break it.
- private sealed record LayoutSnapshot(Dictionary Positions, Dictionary<(string Table, string Key), DiagramManualRoute> Routes, Dictionary Notes);
+ private sealed record LayoutSnapshot(Dictionary Positions, Dictionary<(string Table, string Key), DiagramManualRoute> Routes, Dictionary Notes, Dictionary Views);
private readonly List undoStack = [];
private const int UndoLimit = 100;
private LayoutSnapshot? pendingUndo;
@@ -246,7 +246,8 @@ private sealed record LayoutSnapshot(Dictionary Positions, Dictio
private LayoutSnapshot TakeSnapshot() => new(
tables.ToDictionary(t => t.Key, t => new Point(t.X, t.Y)),
Relations.Where(r => manualRoutes.ContainsKey(r.Key)).ToDictionary(r => (r.Foreign.Key, r.Key.Name), r => manualRoutes[r.Key]),
- annotations.ToDictionary(a => a, a => new Point(a.X, a.Y)));
+ annotations.ToDictionary(a => a, a => new Point(a.X, a.Y)),
+ tables.ToDictionary(t => t.Key, t => t.View));
private void PushUndo(LayoutSnapshot snapshot)
{
@@ -264,6 +265,10 @@ public void Undo()
if (undoStack.Count == 0 || IsBusy || drag != DragMode.None) { if (undoStack.Count == 0) Say("Nothing to undo."); return; }
var snapshot = undoStack[^1]; undoStack.RemoveAt(undoStack.Count - 1);
foreach (var table in tables) if (snapshot.Positions.TryGetValue(table.Key, out var at)) { table.X = at.X; table.Y = at.Y; }
+ // Table View is a step too (12/11/2026): the boxes change size, so they are built again.
+ bool views = false;
+ foreach (var table in tables) if (snapshot.Views.TryGetValue(table.Key, out var was) && table.View != was) { table.View = was; views = true; }
+ if (views) Rebuild();
foreach (var note in annotations) if (snapshot.Notes.TryGetValue(note, out var was)) { note.X = was.X; note.Y = was.Y; }
manualRoutes.Clear();
foreach (var relation in Relations)
@@ -1046,6 +1051,7 @@ public void ArrangeTables()
Position(); Touch();
}
public void SelectAll() { selected.Clear(); selected.UnionWith(tables); selectedRelation = null; RefreshTitles(); RefreshLineSelection(); }
+ internal void SelectNone() { selected.Clear(); selectedRelation = null; RefreshTitles(); RefreshLineSelection(); }
public void ToggleLabels() { showLabels = !showLabels; DrawLines(); Touch(); }
/// Add Related Tables: tables linked by a foreign key to the selected tables (to all when none is selected).
diff --git a/src/PGMS.Desktop/DefaultPrivilegeDialog.xaml.cs b/src/PGMS.Desktop/DefaultPrivilegeDialog.xaml.cs
index 21bf3f2..3f43060 100644
--- a/src/PGMS.Desktop/DefaultPrivilegeDialog.xaml.cs
+++ b/src/PGMS.Desktop/DefaultPrivilegeDialog.xaml.cs
@@ -19,7 +19,8 @@ public partial class DefaultPrivilegeDialog : Window
public bool HasUnconfirmedCommit { get; private set; }
public string? ScriptSql { get; private set; }
internal DefaultPrivilegeSnapshot? Snapshot => snapshot;
- public DefaultPrivilegeDialog(string connection)
+ /// With a schema (the one selected in Object Explorer), the scope starts on it instead of global; a restored transaction still wins.
+ public DefaultPrivilegeDialog(string connection, string? schema = null)
{
this.connection=connection;InitializeComponent();
Creator.AddHandler(System.Windows.Controls.Primitives.TextBoxBase.TextChangedEvent,new TextChangedEventHandler(ScopeChanged));
@@ -27,6 +28,7 @@ public DefaultPrivilegeDialog(string connection)
Target.Text=$"{settings.Host}:{settings.Port} / {settings.Database} \u2014 {settings.Username}";
Creator.Text=settings.Username;ObjectClass.ItemsSource=Enum.GetValues();ObjectClass.SelectedItem=DefaultPrivilegeTarget.Tables;
Privilege.ItemsSource=DefaultPrivilegeRequest.Allowed(DefaultPrivilegeTarget.Tables);Privilege.SelectedIndex=0;
+ if(schema is not null){GlobalScope.IsChecked=false;SchemaName.Text=schema;}
ready=true;RestorePending();Refresh();
}
private DefaultPrivilegeRequest Request => new((DefaultPrivilegeTarget)ObjectClass.SelectedItem,Creator.Text,RoleName.Text,(string?)Privilege.SelectedItem??"",GlobalScope.IsChecked==true?null:SchemaName.Text,Revoke.IsChecked==true,PublicRecipient.IsChecked==true,GrantOption.IsChecked==true);
diff --git a/src/PGMS.Desktop/ExecutionPlanView.cs b/src/PGMS.Desktop/ExecutionPlanView.cs
index d4fa85c..69e644b 100644
--- a/src/PGMS.Desktop/ExecutionPlanView.cs
+++ b/src/PGMS.Desktop/ExecutionPlanView.cs
@@ -239,14 +239,19 @@ MenuItem Add(string header, string name, Action act, string? gesture = null)
return item;
}
Add("_Save Execution Plan As…", "PlanSaveAs", () => SaveRequested?.Invoke(this, EventArgs.Empty));
- Add("Show Execution Plan In New _Tab", "PlanShowInNewTab", () => ShowInNewTabRequested?.Invoke(this, EventArgs.Empty));
+ var newTab = Add("Show Execution Plan In New _Tab", "PlanShowInNewTab", () => ShowInNewTabRequested?.Invoke(this, EventArgs.Empty));
Add("Find _Node", "PlanFindNode", OpenFind);
menu.Items.Add(new Separator());
Add("Zoom _In", "PlanZoomIn", () => Zoom *= ZoomStep);
Add("Zoom _Out", "PlanZoomOut", () => Zoom /= ZoomStep);
Add("_Custom Zoom…", "PlanCustomZoom", CustomZoom);
Add("Zoom to _Fit", "PlanZoomFit", ZoomToFit);
- menu.Opened += (_, _) => { foreach (var item in menu.Items.OfType