diff --git a/docs/en/release-notes.md b/docs/en/release-notes.md
index 027d661..936e318 100644
--- a/docs/en/release-notes.md
+++ b/docs/en/release-notes.md
@@ -11,6 +11,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.
+- **Query History.** **View ▸ Query History…** (`Ctrl+Alt+H`) lists the SQL executed in query tabs, with server, database, user, start, duration, rows, result and origin (typed, Query Designer, AI, other). Repeated queries collapse into one row with the last run and the count, and expand to each execution. Filter by text, connection and period; reopen in a new query tab without executing, copy, pin or delete. It is stored only on this computer, encrypted with Windows DPAPI for the current Windows user, and never sent to a server. Retention is set in **Tools ▸ Options ▸ Query Execution ▸ Query History** (defaults: 90 days, 10,000 executions, 64 KiB of SQL per execution), and a saved connection profile can turn recording off for its server. SSMS 22.11 has no built-in equivalent. Suggested by a PGMS user.
## What changed since v0.1.0-alpha.4
diff --git a/docs/en/user-guide.md b/docs/en/user-guide.md
index deaefff..9c8f66f 100644
--- a/docs/en/user-guide.md
+++ b/docs/en/user-guide.md
@@ -79,6 +79,14 @@ Choose compatible PostgreSQL tools and a new output file/directory. Custom, tar,
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.
+## Query History
+
+**View ▸ Query History…** (`Ctrl+Alt+H`) lists the SQL executed in query tabs: `F5`/**Execute** with results to grid, text or file, SQL written by Query Designer or **Generate SQL with AI**, scripts opened by **Script as** and similar tools, and **Execute SQL** inside the Query Designer. Each execution keeps the SQL (up to 64 KiB by default; longer text is cut and marked), server, port, database, user, start time, duration, rows, result (SQLSTATE and message on errors, or canceled) and origin. SQL refused before it is sent, such as text with unbound `$1` placeholders, is not recorded. SSMS 22.11 has no built-in equivalent.
+
+Repeated queries are grouped: one row per distinct SQL on the same server, port and database (runs of spaces and line breaks are ignored, case is not), with the last run and the count. **+** or the right arrow lists each execution. Filter by text, connection and period. **Open in New Query** puts the SQL in a new tab, connected when PGMS already has a connection to that server and user, and never executes it. **Pin** keeps a query on top and its newest execution is never removed by the limits.
+
+**Privacy and storage.** Query History is stored only on this computer, in `%LOCALAPPDATA%\PGMS\history`, encrypted with Windows DPAPI for the current Windows user. It is never written to a server. SQL can hold sensitive values, such as literals or a password typed in `ALTER ROLE … PASSWORD`: anyone signed in as your Windows user can read it in PGMS. Limits and the on/off switch are in **Tools ▸ Options ▸ Query Execution ▸ Query History** (defaults: 90 days, 10,000 executions, 64 KiB per execution); **Clear History…** deletes everything. To record nothing for a server, such as production, check **Do not record query history for this server** in its saved connection profile; it applies to every connection to that host and port. Writing the history never delays or fails a query: a failure only shows a message in the status bar.
+
## Save and recover
Save SQL files explicitly. Background recovery stores bounded encrypted drafts and may reopen them disconnected after interruption. Review recovered tabs and use **Save As**. This is not a backup system or proof that every latest keystroke was persisted. Conflicting external file changes are refused. Close the app before backing up local state; DPAPI is tied to the Windows user. Builds earlier than M934 cannot read the newer recovery container. See [validation](validation.md) for the exact cross-version recovery tested.
diff --git a/docs/pt-BR/release-notes.md b/docs/pt-BR/release-notes.md
index 910b2de..cbedd04 100644
--- a/docs/pt-BR/release-notes.md
+++ b/docs/pt-BR/release-notes.md
@@ -11,6 +11,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.
+- **Histórico de consultas.** **View ▸ Query History…** (`Ctrl+Alt+H`) lista o SQL executado nas abas de consulta, com servidor, banco, usuário, início, duração, linhas, resultado e origem (digitado, Query Designer, IA, outro). Consultas repetidas viram uma linha com a última execução e a contagem, que se expande em cada execução. Filtre por texto, conexão e período; reabra numa aba nova sem executar, copie, fixe ou apague. Fica só neste computador, criptografado com DPAPI do Windows para o usuário Windows atual, e nunca é enviado ao servidor. A retenção fica em **Tools ▸ Options ▸ Query Execution ▸ Query History** (padrões: 90 dias, 10.000 execuções, 64 KiB de SQL por execução), e um perfil de conexão salvo pode desligar a gravação para o servidor dele. O SSMS 22.11 não tem equivalente nativo. Sugestão de um usuário do PGMS.
## 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 c6e36ef..bc79cc4 100644
--- a/docs/pt-BR/user-guide.md
+++ b/docs/pt-BR/user-guide.md
@@ -79,6 +79,14 @@ Escolha ferramentas PostgreSQL compatíveis e arquivo/diretório de saída novo.
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.
+## Histórico de consultas
+
+**View ▸ Query History…** (`Ctrl+Alt+H`) lista o SQL executado nas abas de consulta: `F5`/**Execute** com resultados em grade, texto ou arquivo, SQL escrito pelo Query Designer ou por **Generate SQL with AI**, scripts abertos por **Script as** e ferramentas parecidas, e **Execute SQL** dentro do Query Designer. Cada execução guarda o SQL (até 64 KiB por padrão; texto maior é cortado e marcado), servidor, porta, banco, usuário, início, duração, linhas, resultado (SQLSTATE e mensagem nos erros, ou cancelada) e origem. SQL recusado antes do envio, como texto com placeholders `$1` sem valor, não é gravado. O SSMS 22.11 não tem equivalente nativo.
+
+Consultas repetidas são agrupadas: uma linha por SQL distinto no mesmo servidor, porta e banco (sequências de espaços e quebras de linha são ignoradas; maiúsculas e minúsculas, não), com a última execução e a contagem. **+** ou a seta para a direita lista cada execução. Filtre por texto, conexão e período. **Open in New Query** põe o SQL numa aba nova, conectada quando o PGMS já tem uma conexão com aquele servidor e usuário, e nunca o executa. **Pin** deixa a consulta no topo, e a execução mais recente dela nunca é removida pelos limites.
+
+**Privacidade e armazenamento.** O histórico fica só neste computador, em `%LOCALAPPDATA%\PGMS\history`, criptografado com DPAPI do Windows para o usuário Windows atual. Nunca é gravado no servidor. O SQL pode ter valores sensíveis, como literais ou uma senha digitada em `ALTER ROLE … PASSWORD`: quem entrar com o seu usuário Windows consegue lê-lo no PGMS. Limites e a chave liga/desliga ficam em **Tools ▸ Options ▸ Query Execution ▸ Query History** (padrões: 90 dias, 10.000 execuções, 64 KiB por execução); **Clear History…** apaga tudo. Para não gravar nada de um servidor, como o de produção, marque **Do not record query history for this server** no perfil de conexão salvo; vale para toda conexão àquele host e porta. A gravação nunca atrasa nem faz falhar uma consulta: uma falha só mostra uma mensagem na barra de status.
+
## Salvar e recuperar
Salve arquivos SQL explicitamente. Recuperação em background mantém rascunhos criptografados com limites e pode reabri-los desconectados após interrupção. Revise abas recuperadas e use **Save As**. Isso não é sistema de backup nem prova de persistência de cada última tecla. Alterações externas conflitantes no arquivo são recusadas. Feche o app antes de copiar estado local; DPAPI depende do usuário Windows. Builds anteriores a M934 não leem o contêiner de recuperação mais recente. Veja a [validação](validation.md) para a recuperação entre versões realmente testada.
diff --git a/scripts/Test-Integration.ps1 b/scripts/Test-Integration.ps1
index c551166..94dc5f6 100644
--- a/scripts/Test-Integration.ps1
+++ b/scripts/Test-Integration.ps1
@@ -1,6 +1,6 @@
-param([switch]$ResultsTextOnly, [switch]$TableDesignOnly, [switch]$DiagramsOnly, [switch]$ServerTlsOnly, [switch]$SchemaContextOnly, [switch]$ReportsOnly, [switch]$SessionsOnly, [switch]$PlansOnly, [switch]$ExportOnly, [switch]$ActivityOnly, [switch]$QueryStatisticsOnly, [switch]$GlobalBackupOnly, [switch]$ColumnTypesOnly, [switch]$IndexMaintenanceOnly, [switch]$IndexExpressionsOnly, [switch]$PartitionTablesOnly, [switch]$DesktopOnly, [switch]$CascadeJournalOnly, [switch]$CascadeRoutinesOnly, [switch]$CascadeRollbackOnly, [switch]$RevokePreviewOnly, [switch]$GrantorConcurrencyOnly, [switch]$ExplicitGrantorOnly, [switch]$GrantorCatalogOnly, [switch]$DefaultProcessOnly, [switch]$DefaultDelegationOnly, [switch]$DefaultSchemasOnly, [switch]$DefaultTypesOnly, [switch]$DefaultRoutinesOnly, [switch]$DefaultSequencesOnly, [switch]$DefaultTablesOnly, [switch]$DefaultCancellationOnly, [switch]$DefaultUiOnly, [switch]$DefaultJournalOnly, [switch]$DefaultPrivilegesOnly, [switch]$RoutineBoundariesOnly, [switch]$RoutineProcessOnly, [switch]$RoutineConcurrencyOnly, [switch]$RoutinePrivilegesOnly, [string]$PostgresBin = 'C:\Program Files\PostgreSQL\17\bin', [switch]$BackupFormatsOnly, [switch]$IdentityColumnsOnly, [switch]$RestoreOwnershipOnly, [switch]$UnicodeBackupOnly, [switch]$PrivilegeJournalOnly, [switch]$MaintainPrivilegeOnly, [switch]$PrivilegeCommitOnly, [switch]$UnicodePasswordOnly, [switch]$MembershipOptionsOnly, [switch]$PrivilegeIdentityOnly, [switch]$ColumnPrivilegesOnly, [switch]$PrivilegeCancellationOnly, [switch]$EffectivePrivilegesOnly, [switch]$PrivilegeCommandsOnly, [switch]$SequencePrivilegesOnly, [switch]$CopyOnly, [switch]$AdvancedIndexesOnly, [switch]$SequencesOnly, [switch]$SequenceStateOnly, [switch]$SequenceOwnerOnly, [switch]$AccessibilityOnly, [switch]$ConnectionOnly, [switch]$StreamingOnly, [switch]$ExplorerOnly, [switch]$PropertiesOnly, [switch]$AcceptanceOnly, [ValidateRange(1024,65535)][int]$TestPort = 55439)
+param([switch]$ResultsTextOnly, [switch]$TableDesignOnly, [switch]$DiagramsOnly, [switch]$ServerTlsOnly, [switch]$SchemaContextOnly, [switch]$ReportsOnly, [switch]$SessionsOnly, [switch]$PlansOnly, [switch]$ExportOnly, [switch]$ActivityOnly, [switch]$QueryStatisticsOnly, [switch]$GlobalBackupOnly, [switch]$ColumnTypesOnly, [switch]$IndexMaintenanceOnly, [switch]$IndexExpressionsOnly, [switch]$PartitionTablesOnly, [switch]$DesktopOnly, [switch]$CascadeJournalOnly, [switch]$CascadeRoutinesOnly, [switch]$CascadeRollbackOnly, [switch]$RevokePreviewOnly, [switch]$GrantorConcurrencyOnly, [switch]$ExplicitGrantorOnly, [switch]$GrantorCatalogOnly, [switch]$DefaultProcessOnly, [switch]$DefaultDelegationOnly, [switch]$DefaultSchemasOnly, [switch]$DefaultTypesOnly, [switch]$DefaultRoutinesOnly, [switch]$DefaultSequencesOnly, [switch]$DefaultTablesOnly, [switch]$DefaultCancellationOnly, [switch]$DefaultUiOnly, [switch]$DefaultJournalOnly, [switch]$DefaultPrivilegesOnly, [switch]$RoutineBoundariesOnly, [switch]$RoutineProcessOnly, [switch]$RoutineConcurrencyOnly, [switch]$RoutinePrivilegesOnly, [string]$PostgresBin = 'C:\Program Files\PostgreSQL\17\bin', [switch]$BackupFormatsOnly, [switch]$IdentityColumnsOnly, [switch]$RestoreOwnershipOnly, [switch]$UnicodeBackupOnly, [switch]$PrivilegeJournalOnly, [switch]$MaintainPrivilegeOnly, [switch]$PrivilegeCommitOnly, [switch]$UnicodePasswordOnly, [switch]$MembershipOptionsOnly, [switch]$PrivilegeIdentityOnly, [switch]$ColumnPrivilegesOnly, [switch]$PrivilegeCancellationOnly, [switch]$EffectivePrivilegesOnly, [switch]$PrivilegeCommandsOnly, [switch]$SequencePrivilegesOnly, [switch]$CopyOnly, [switch]$AdvancedIndexesOnly, [switch]$SequencesOnly, [switch]$SequenceStateOnly, [switch]$SequenceOwnerOnly, [switch]$AccessibilityOnly, [switch]$ConnectionOnly, [switch]$StreamingOnly, [switch]$ExplorerOnly, [switch]$PropertiesOnly, [switch]$AcceptanceOnly, [ValidateRange(1024,65535)][int]$TestPort = 55439, [switch]$QueryHistoryOnly)
$ErrorActionPreference = 'Stop'
-if ((@($ResultsTextOnly, $TableDesignOnly, $DiagramsOnly, $SessionsOnly, $PlansOnly, $ExportOnly, $ActivityOnly, $QueryStatisticsOnly, $GlobalBackupOnly, $ColumnTypesOnly, $IndexMaintenanceOnly, $IndexExpressionsOnly, $PartitionTablesOnly, $CascadeJournalOnly, $CascadeRoutinesOnly, $CascadeRollbackOnly, $RevokePreviewOnly, $GrantorConcurrencyOnly, $ExplicitGrantorOnly, $GrantorCatalogOnly, $DefaultProcessOnly, $DefaultDelegationOnly, $DefaultSchemasOnly, $DefaultTypesOnly, $DefaultRoutinesOnly, $DefaultSequencesOnly, $DefaultTablesOnly, $DefaultCancellationOnly, $DefaultUiOnly, $DefaultJournalOnly, $DefaultPrivilegesOnly, $RoutineBoundariesOnly, $RoutineProcessOnly, $RoutineConcurrencyOnly, $RoutinePrivilegesOnly, $BackupFormatsOnly, $IdentityColumnsOnly, $RestoreOwnershipOnly, $UnicodeBackupOnly, $PrivilegeJournalOnly, $MaintainPrivilegeOnly, $PrivilegeCommitOnly, $UnicodePasswordOnly, $ServerTlsOnly, $SchemaContextOnly, $MembershipOptionsOnly, $PrivilegeIdentityOnly, $ColumnPrivilegesOnly, $PrivilegeCancellationOnly, $EffectivePrivilegesOnly, $PrivilegeCommandsOnly, $SequencePrivilegesOnly, $CopyOnly, $AdvancedIndexesOnly, $SequencesOnly, $SequenceStateOnly, $SequenceOwnerOnly, $AccessibilityOnly, $ConnectionOnly, $StreamingOnly, $ExplorerOnly, $ReportsOnly, $PropertiesOnly, $AcceptanceOnly) | Where-Object { $_ }).Count -gt 1) { throw 'Choose only one focused suite.' }
+if ((@($ResultsTextOnly, $TableDesignOnly, $DiagramsOnly, $SessionsOnly, $PlansOnly, $ExportOnly, $ActivityOnly, $QueryStatisticsOnly, $GlobalBackupOnly, $ColumnTypesOnly, $IndexMaintenanceOnly, $IndexExpressionsOnly, $PartitionTablesOnly, $CascadeJournalOnly, $CascadeRoutinesOnly, $CascadeRollbackOnly, $RevokePreviewOnly, $GrantorConcurrencyOnly, $ExplicitGrantorOnly, $GrantorCatalogOnly, $DefaultProcessOnly, $DefaultDelegationOnly, $DefaultSchemasOnly, $DefaultTypesOnly, $DefaultRoutinesOnly, $DefaultSequencesOnly, $DefaultTablesOnly, $DefaultCancellationOnly, $DefaultUiOnly, $DefaultJournalOnly, $DefaultPrivilegesOnly, $RoutineBoundariesOnly, $RoutineProcessOnly, $RoutineConcurrencyOnly, $RoutinePrivilegesOnly, $BackupFormatsOnly, $IdentityColumnsOnly, $RestoreOwnershipOnly, $UnicodeBackupOnly, $PrivilegeJournalOnly, $MaintainPrivilegeOnly, $PrivilegeCommitOnly, $UnicodePasswordOnly, $ServerTlsOnly, $SchemaContextOnly, $MembershipOptionsOnly, $PrivilegeIdentityOnly, $ColumnPrivilegesOnly, $PrivilegeCancellationOnly, $EffectivePrivilegesOnly, $PrivilegeCommandsOnly, $SequencePrivilegesOnly, $CopyOnly, $AdvancedIndexesOnly, $SequencesOnly, $SequenceStateOnly, $SequenceOwnerOnly, $AccessibilityOnly, $ConnectionOnly, $StreamingOnly, $ExplorerOnly, $ReportsOnly, $PropertiesOnly, $AcceptanceOnly, $QueryHistoryOnly) | Where-Object { $_ }).Count -gt 1) { throw 'Choose only one focused suite.' }
if ($DesktopOnly -and ($CascadeRoutinesOnly -or $CascadeRollbackOnly -or $RevokePreviewOnly -or $GrantorConcurrencyOnly -or $ExplicitGrantorOnly -or $GrantorCatalogOnly -or $DefaultDelegationOnly -or $DefaultSchemasOnly -or $DefaultTypesOnly -or $DefaultRoutinesOnly -or $DefaultSequencesOnly -or $DefaultTablesOnly -or $DefaultPrivilegesOnly -or $RoutineConcurrencyOnly -or $PrivilegeIdentityOnly -or $AcceptanceOnly -or $UnicodeBackupOnly)) { throw 'The selected focused suite has no desktop checks.' }
$projectRoot = Split-Path $PSScriptRoot -Parent
$testRoot = Join-Path $projectRoot 'artifacts\postgres-test'
@@ -110,7 +110,8 @@ try {
if ($TableDesignOnly) { $testArgs = @("--", "--table-design") }
if ($DiagramsOnly) { $testArgs = @("--", "--diagrams") }
if ($ResultsTextOnly) { $testArgs = @("--", "--results-text") }
- if (!$CascadeJournalOnly -and !$DefaultProcessOnly -and !$DefaultCancellationOnly -and !$DefaultUiOnly -and !$DefaultJournalOnly -and !$RoutineBoundariesOnly -and !$RoutineProcessOnly -and !$DesktopOnly -and !$PrivilegeJournalOnly -and !$CopyOnly -and !$AccessibilityOnly -and !$ConnectionOnly -and !$ExplorerOnly) {
+ if ($QueryHistoryOnly) { $testArgs = @("--", "--query-history") }
+ if (!$CascadeJournalOnly -and !$DefaultProcessOnly -and !$DefaultCancellationOnly -and !$DefaultUiOnly -and !$DefaultJournalOnly -and !$RoutineBoundariesOnly -and !$RoutineProcessOnly -and !$DesktopOnly -and !$PrivilegeJournalOnly -and !$CopyOnly -and !$AccessibilityOnly -and !$ConnectionOnly -and !$ExplorerOnly -and !$QueryHistoryOnly) {
dotnet run --project tests\PGMS.IntegrationTests\PGMS.IntegrationTests.csproj -c Release @testArgs
if ($LASTEXITCODE -ne 0) { throw 'Integration checks failed' }
}
diff --git a/src/PGMS.Desktop/ConnectionDialog.xaml b/src/PGMS.Desktop/ConnectionDialog.xaml
index 17f03fb..a3e7352 100644
--- a/src/PGMS.Desktop/ConnectionDialog.xaml
+++ b/src/PGMS.Desktop/ConnectionDialog.xaml
@@ -24,7 +24,7 @@
-
+
diff --git a/src/PGMS.Desktop/ConnectionDialog.xaml.cs b/src/PGMS.Desktop/ConnectionDialog.xaml.cs
index 10fc7fb..ba97750 100644
--- a/src/PGMS.Desktop/ConnectionDialog.xaml.cs
+++ b/src/PGMS.Desktop/ConnectionDialog.xaml.cs
@@ -90,7 +90,7 @@ private void ReloadProfiles(Guid? selected = null)
}
private void NewProfile(object sender, RoutedEventArgs e)
{
- Profiles.SelectedItem = null; selectedId = null; ProfileName.Clear(); Password.Clear(); RememberPassword.IsChecked = false; DeleteProfileButton.IsEnabled = false; Error.Text = "New profile. Enter settings and choose Save Profile.";
+ Profiles.SelectedItem = null; selectedId = null; ProfileName.Clear(); Password.Clear(); RememberPassword.IsChecked = false; DisableHistory.IsChecked = false; DeleteProfileButton.IsEnabled = false; Error.Text = "New profile. Enter settings and choose Save Profile.";
}
private void SelectProfile(object sender, SelectionChangedEventArgs e)
{
@@ -98,6 +98,7 @@ private void SelectProfile(object sender, SelectionChangedEventArgs e)
if (rememberChoice) preferences.Update(d => d with { LastProfile = p.Id });
selectedId = p.Id; ProfileName.Text = p.Name; Host.Text = p.Host; Port.Text = p.Port.ToString(); Database.Text = p.Database; Username.Text = p.Username;
Ssl.SelectedItem = Ssl.Items.OfType().First(i => (string)i.Content == p.SslMode); RootCertificate.Text = p.RootCertificate ?? "";
+ DisableHistory.IsChecked = p.DisableQueryHistory;
Password.Clear(); RememberPassword.IsChecked = false; DeleteProfileButton.IsEnabled = true; Error.Text = "";
try { Password.Password = p.RevealPassword(); RememberPassword.IsChecked = p.ProtectedPassword is not null; }
catch (Exception ex) when (IsProfileError(ex)) { Error.Text = "Saved password is unavailable. Re-enter it and save the profile to replace it."; }
@@ -108,7 +109,7 @@ private void SaveProfile(object sender, RoutedEventArgs e)
try
{
string? group = selectedId is { } existing ? store.Load().FirstOrDefault(p => p.Id == existing)?.Group : newProfileGroup;
- var profile = new ConnectionProfile(selectedId ?? Guid.NewGuid(), ProfileName.Text.Trim(), settings.Host!, settings.Port, settings.Database!, settings.Username!, settings.SslMode.ToString(), RootCertificate: string.IsNullOrEmpty(settings.RootCertificate) ? null : settings.RootCertificate, Group: group);
+ var profile = new ConnectionProfile(selectedId ?? Guid.NewGuid(), ProfileName.Text.Trim(), settings.Host!, settings.Port, settings.Database!, settings.Username!, settings.SslMode.ToString(), RootCertificate: string.IsNullOrEmpty(settings.RootCertificate) ? null : settings.RootCertificate, Group: group, DisableQueryHistory: DisableHistory.IsChecked == true);
profile.Validate();
profile = profile.WithPassword(Password.Password, RememberPassword.IsChecked == true);
string sessionPassword = Password.Password;
@@ -158,7 +159,7 @@ public async Task TestConnectionAsync()
}
private void SetTesting(bool testing)
{
- foreach (var control in new Control[] { Profiles, ProfileName, NewProfileButton, Host, Port, Database, Username, Password, Ssl, RootCertificate, BrowseRootButton, RememberPassword, SaveProfileButton, TestButton, ConnectButton })
+ foreach (var control in new Control[] { Profiles, ProfileName, NewProfileButton, Host, Port, Database, Username, Password, Ssl, RootCertificate, BrowseRootButton, RememberPassword, DisableHistory, SaveProfileButton, TestButton, ConnectButton })
control.IsEnabled = !testing;
DeleteProfileButton.IsEnabled = !testing && selectedId is not null;
CancelTestButton.Visibility = testing ? Visibility.Visible : Visibility.Collapsed;
diff --git a/src/PGMS.Desktop/ConnectionProfiles.cs b/src/PGMS.Desktop/ConnectionProfiles.cs
index 9dcb9c0..7925c8a 100644
--- a/src/PGMS.Desktop/ConnectionProfiles.cs
+++ b/src/PGMS.Desktop/ConnectionProfiles.cs
@@ -6,8 +6,9 @@
namespace PGMS.Desktop;
-/// A saved connection. Group is the Registered Servers group path ("Production/Billing"); null or empty is the top level.
-public sealed record ConnectionProfile(Guid Id, string Name, string Host, int Port, string Database, string Username, string SslMode, string? ProtectedPassword = null, string? RootCertificate = null, string? Group = null)
+/// A saved connection. Group is the Registered Servers group path ("Production/Billing"); null or empty is the top level.
+/// DisableQueryHistory turns Query History off for every connection to this host and port (PGMS-043); older files without it record history.
+public sealed record ConnectionProfile(Guid Id, string Name, string Host, int Port, string Database, string Username, string SslMode, string? ProtectedPassword = null, string? RootCertificate = null, string? Group = null, bool DisableQueryHistory = false)
{
public override string ToString() => Name;
public void Validate()
diff --git a/src/PGMS.Desktop/EnvironmentOptions.cs b/src/PGMS.Desktop/EnvironmentOptions.cs
index 6f94a42..650af71 100644
--- a/src/PGMS.Desktop/EnvironmentOptions.cs
+++ b/src/PGMS.Desktop/EnvironmentOptions.cs
@@ -12,8 +12,10 @@ public sealed record WindowPlacement(double Left, double Top, double Width, doub
/// RestoreWindowPlacement starts on, as the user chose; SSMS also reopens where it was closed. SelectTopRows and EditTopRows are the
/// Object Explorer ▸ Commands values for Select Top n Rows and Edit Top n Rows (1000 and 200, as in SSMS); files without them get the defaults.
public sealed record Document(int Version = 1, bool RestoreWindowPlacement = true, WindowPlacement? Window = null, int SelectTopRows = DefaultSelectTopRows, int EditTopRows = DefaultEditTopRows,
- ResultsDestination DefaultResultsDestination = ResultsDestination.Grid, QueryOptions? QueryDefaults = null)
+ ResultsDestination DefaultResultsDestination = ResultsDestination.Grid, QueryOptions? QueryDefaults = null, QueryHistorySettings? QueryHistory = null)
{
+ /// Query Execution ▸ Query History (PGMS-043); files without it record history with the default limits.
+ public QueryHistorySettings History => (QueryHistory ?? new QueryHistorySettings()).Normalized();
/// Query Execution and Query Results pages: what new query tabs start with.
public QueryOptions QueryOptionDefaults => (QueryDefaults ?? new QueryOptions()).Normalized();
/// Query Results ▸ General ▸ Default destination for results of new query tabs; an unknown value falls back to Grid.
diff --git a/src/PGMS.Desktop/MainWindow.QueryDesigner.cs b/src/PGMS.Desktop/MainWindow.QueryDesigner.cs
index cb6a3fa..679dc24 100644
--- a/src/PGMS.Desktop/MainWindow.QueryDesigner.cs
+++ b/src/PGMS.Desktop/MainWindow.QueryDesigner.cs
@@ -29,6 +29,7 @@ internal async Task OpenQueryDesignerAsync()
return;
}
var dialog = new QueryDesignerDialog(connection, selected) { Owner = this };
+ dialog.Designer.ExecutionObserved = query.RecordDesignerExecution;
bool accepted = QueryDesignerHost is { } host ? await host(dialog) : dialog.ShowDialog() == true;
if (!accepted || dialog.ResultSql.Length == 0) return;
string sql = dialog.ResultSql;
diff --git a/src/PGMS.Desktop/MainWindow.QueryHistory.cs b/src/PGMS.Desktop/MainWindow.QueryHistory.cs
new file mode 100644
index 0000000..e599b1e
--- /dev/null
+++ b/src/PGMS.Desktop/MainWindow.QueryHistory.cs
@@ -0,0 +1,67 @@
+using System.IO;
+using System.Windows;
+using Npgsql;
+
+namespace PGMS.Desktop;
+
+// Query History (PGMS-043, docs/MARCO-M1060.md): every execution of a query tab is recorded locally; View ▸ Query History… lists and reopens them.
+public partial class MainWindow
+{
+ private QueryHistoryRecorder? queryHistory;
+ private QueryHistoryWindow? historyWindow;
+ /// Shared by every query tab of this window. Created at startup, which also applies the age and count limits once.
+ internal QueryHistoryRecorder QueryHistory => queryHistory ??= CreateQueryHistory();
+ internal QueryHistoryWindow? OpenHistoryWindow => historyWindow;
+
+ private QueryHistoryRecorder CreateQueryHistory()
+ {
+ var recorder = new QueryHistoryRecorder(new QueryHistoryStore(QueryHistoryStore.DefaultDirectory), () => EnvironmentSettings.Load().History,
+ (server, port) => QueryHistoryRecorder.ProfileExcludes(ConnectionProfileStore.DefaultPath, server, port));
+ recorder.Warning += message => Dispatcher.BeginInvoke(() => Status.Text = message);
+ _ = recorder.PruneAsync();
+ return recorder;
+ }
+
+ private void AttachQueryHistory(QueryView view) => view.HistorySink = capture => _ = QueryHistory.RecordAsync(capture);
+
+ private void ShowQueryHistory(object sender, RoutedEventArgs e) => ShowQueryHistory();
+ /// One window per main window; asking again brings it to the front.
+ internal QueryHistoryWindow ShowQueryHistory()
+ {
+ if (historyWindow is { } open) { open.Activate(); return open; }
+ historyWindow = new QueryHistoryWindow(QueryHistory, async entry => await OpenHistoryEntryAsync(entry)) { Owner = this };
+ historyWindow.Closed += (_, _) => historyWindow = null;
+ historyWindow.Show();
+ return historyWindow;
+ }
+
+ /// The SQL in a new tab, connected when PGMS already has a connection to that server, port and user (its database is switched to the entry's). Never executed.
+ internal async Task OpenHistoryEntryAsync(QueryHistoryEntry entry)
+ {
+ var query = NewQuery(entry.ReopenText, origin: entry.Origin);
+ if (HistoryConnection(entry) is not { } connection)
+ {
+ Status.Text = $"Opened from Query History without a connection: PGMS has no open connection to {entry.Server}:{entry.Port} as {entry.User}. Use Query ▸ Connection ▸ Connect….";
+ return query;
+ }
+ try { await query.ConnectAsync(connection); Status.Text = $"Opened from Query History, connected to {entry.Server}:{entry.Port}/{entry.Database}. Nothing was executed."; }
+ catch (Exception ex) when (ex is NpgsqlException or IOException or OperationCanceledException or InvalidOperationException) { ShowError(ex); }
+ return query;
+ }
+
+ /// An open connection (query tabs, then Object Explorer) to the entry's server, port and user, pointed at its database. The password stays in memory only.
+ internal string? HistoryConnection(QueryHistoryEntry entry)
+ {
+ var candidates = documents.Keys.Select(q => q.ConnectionString).Append(explorerConnection).Append(catalogService?.ConnectionFor(null));
+ foreach (string? candidate in candidates)
+ {
+ if (candidate is null) continue;
+ NpgsqlConnectionStringBuilder c;
+ try { c = new NpgsqlConnectionStringBuilder(candidate); } catch (ArgumentException) { continue; }
+ if (!string.Equals(c.Host, entry.Server, StringComparison.OrdinalIgnoreCase) || c.Port != entry.Port || c.Username != entry.User) continue;
+ c.Database = entry.Database;
+ return c.ConnectionString;
+ }
+ return null;
+ }
+}
diff --git a/src/PGMS.Desktop/MainWindow.Recovery.cs b/src/PGMS.Desktop/MainWindow.Recovery.cs
index e827ad6..711ce4b 100644
--- a/src/PGMS.Desktop/MainWindow.Recovery.cs
+++ b/src/PGMS.Desktop/MainWindow.Recovery.cs
@@ -51,7 +51,7 @@ public RecoveryReport RecoverPendingQueries()
int available = Math.Max(0, QueryRecoveryStore.MaximumDocuments - occupied);
var result = QueryRecoverySession.Recover(Path.Combine(Path.GetDirectoryName(layoutFile)!, "recovery"), recoverySession.Store.DirectoryPath, draft =>
{
- var query = NewQuery(draft.Text);
+ var query = NewQuery(draft.Text, origin: QueryHistoryOrigin.Typed);
query.FileFormat = draft.Format;query.WordWrap=draft.WordWrap;query.ShowWhiteSpace=draft.ShowWhiteSpace;query.CommandTimeoutSeconds=draft.CommandTimeoutSeconds;
query.IsDirty = true;
string title = draft.Title.StartsWith("Recovered - ", StringComparison.Ordinal) ? draft.Title : "Recovered - " + draft.Title;
diff --git a/src/PGMS.Desktop/MainWindow.xaml b/src/PGMS.Desktop/MainWindow.xaml
index 5a537ce..36de37b 100644
--- a/src/PGMS.Desktop/MainWindow.xaml
+++ b/src/PGMS.Desktop/MainWindow.xaml
@@ -35,7 +35,7 @@
-
+
diff --git a/src/PGMS.Desktop/MainWindow.xaml.cs b/src/PGMS.Desktop/MainWindow.xaml.cs
index 79318c8..8178ad8 100644
--- a/src/PGMS.Desktop/MainWindow.xaml.cs
+++ b/src/PGMS.Desktop/MainWindow.xaml.cs
@@ -37,6 +37,7 @@ public MainWindow()
{
InitializeComponent();
InitializeExplorerToolbar();
+ _ = QueryHistory; // startup cleanup of Query History
WindowWorkArea.Attach(this);
// Keep the caption and status reachable on scaled or small work areas.
var workArea = SystemParameters.WorkArea;
@@ -105,12 +106,14 @@ public MainWindow()
// SSMS shortcut for Activity Monitor; with Alt held WPF reports the letter in SystemKey.
if ((e.Key == Key.System ? e.SystemKey : e.Key) == Key.A && Keyboard.Modifiers == (ModifierKeys.Control | ModifierKeys.Alt)) { ShowActivity(this, e); e.Handled = true; }
if ((e.Key == Key.System ? e.SystemKey : e.Key) == Key.G && Keyboard.Modifiers == (ModifierKeys.Control | ModifierKeys.Alt)) { ShowRegisteredServers(); e.Handled = true; }
+ if ((e.Key == Key.System ? e.SystemKey : e.Key) == Key.H && Keyboard.Modifiers == (ModifierKeys.Control | ModifierKeys.Alt)) { ShowQueryHistory(); e.Handled = true; }
};
}
internal Action? UiPhaseMeasured { get; set; }
- private QueryView NewQuery(string? text = null, string? path = null, Guid? recoveryId = null, bool activate = true, PreparedQueryDocument? prepared = null)
+ /// Query History origin of text given here without a file (scripts, generated SQL); recovered drafts pass Typed.
+ private QueryView NewQuery(string? text = null, string? path = null, Guid? recoveryId = null, bool activate = true, PreparedQueryDocument? prepared = null, QueryHistoryOrigin origin = QueryHistoryOrigin.Other)
{
QueryView view;
using (UiPhaseScope.Start(UiPhaseMeasured, "view-total"))
@@ -125,6 +128,8 @@ private QueryView NewQuery(string? text = null, string? path = null, Guid? recov
}
using var dockPhase = UiPhaseScope.Start(UiPhaseMeasured, "dock-and-commands");
view.IsDirty = false;
+ AttachQueryHistory(view);
+ if (prepared is null && path is null && !string.IsNullOrWhiteSpace(text)) view.MarkOrigin(text, origin);
// Tools ▸ Options ▸ Query Results ▸ General ▸ Default destination for results.
var environment = EnvironmentSettings.Load();
view.ResultsDestination = environment.DefaultResults;
@@ -984,7 +989,7 @@ internal void SaveWindowPlacement()
private void ShowOptions(object sender, RoutedEventArgs e)
{
- var dialog = new OptionsDialog(EnvironmentSettings) { Owner = this };
+ var dialog = new OptionsDialog(EnvironmentSettings, () => QueryHistory.ClearAsync()) { Owner = this };
dialog.ShowDialog();
}
diff --git a/src/PGMS.Desktop/OptionsDialog.xaml b/src/PGMS.Desktop/OptionsDialog.xaml
index a50ac67..b603922 100644
--- a/src/PGMS.Desktop/OptionsDialog.xaml
+++ b/src/PGMS.Desktop/OptionsDialog.xaml
@@ -9,6 +9,7 @@
+
@@ -50,6 +51,27 @@
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
diff --git a/src/PGMS.Desktop/OptionsDialog.xaml.cs b/src/PGMS.Desktop/OptionsDialog.xaml.cs
index 13bdde8..94af8c8 100644
--- a/src/PGMS.Desktop/OptionsDialog.xaml.cs
+++ b/src/PGMS.Desktop/OptionsDialog.xaml.cs
@@ -9,19 +9,46 @@ namespace PGMS.Desktop;
public partial class OptionsDialog : Window
{
private readonly EnvironmentOptions options;
+ private readonly Func>? clearHistory;
- public OptionsDialog(EnvironmentOptions options)
+ /// Clears Query History at once (not on OK) and returns how many executions were removed; null hides the button.
+ public OptionsDialog(EnvironmentOptions options, Func>? clearHistory = null)
{
InitializeComponent();
- this.options = options;
+ this.options = options; this.clearHistory = clearHistory;
var document = options.Load();
RestoreWindowBox.IsChecked = document.RestoreWindowPlacement;
SelectTopBox.Text = document.SelectTop.ToString(CultureInfo.CurrentCulture);
EditTopBox.Text = document.EditTop.ToString(CultureInfo.CurrentCulture);
DefaultResultsBox.SelectedIndex = document.DefaultResults switch { ResultsDestination.Text => 1, ResultsDestination.File => 2, _ => 0 };
QueryPages.Load(document.QueryOptionDefaults);
+ var history = document.History;
+ HistoryEnabledBox.IsChecked = history.Enabled;
+ HistoryDaysBox.Text = history.RetentionDays.ToString(CultureInfo.InvariantCulture);
+ HistoryCountBox.Text = history.MaxExecutions.ToString(CultureInfo.InvariantCulture);
+ HistorySizeBox.Text = history.MaxSqlKiB.ToString(CultureInfo.InvariantCulture);
+ ClearHistoryButton.Visibility = clearHistory is null ? Visibility.Collapsed : Visibility.Visible;
}
+ /// Asks before clearing; tests replace it.
+ internal Func? ConfirmClearHistory { get; set; }
+
+ private async void ClearHistory(object sender, RoutedEventArgs e) => await ClearHistoryAsync();
+ internal async Task ClearHistoryAsync()
+ {
+ if (clearHistory is null) return;
+ bool confirmed = ConfirmClearHistory?.Invoke() ?? MessageBox.Show(this, QueryHistoryWindow.ClearQuestion, "Clear Query History", MessageBoxButton.YesNo, MessageBoxImage.Warning, MessageBoxResult.No) == MessageBoxResult.Yes;
+ if (!confirmed) return;
+ ClearHistoryButton.IsEnabled = false; ClearHistoryStatus.Text = "Clearing…";
+ try { int removed = await clearHistory(); ClearHistoryStatus.Text = $"Query History cleared: {removed:N0} execution(s) removed."; }
+ catch (Exception ex) when (QueryHistoryRecorder.IsDiskError(ex)) { ClearHistoryStatus.Text = "Query History was not cleared. " + ex.Message; }
+ finally { ClearHistoryButton.IsEnabled = true; }
+ }
+
+ /// Whole number within the range, digits only.
+ internal static int? ParseRange(string text, int minimum, int maximum) =>
+ int.TryParse(text.Trim(), NumberStyles.None, CultureInfo.InvariantCulture, out int value) && value >= minimum && value <= maximum ? value : null;
+
private void PageChanged(object sender, RoutedPropertyChangedEventArgs