diff --git a/.github/ISSUE_TEMPLATE/bug_report.yml b/.github/ISSUE_TEMPLATE/bug_report.yml index 5f7e218..c58678d 100644 --- a/.github/ISSUE_TEMPLATE/bug_report.yml +++ b/.github/ISSUE_TEMPLATE/bug_report.yml @@ -13,7 +13,7 @@ body: attributes: label: PGMS version / Versão do PGMS description: Release tag or build label shown in Help > About. / Tag da release ou rótulo de build exibido em Help > About. - placeholder: v0.1.0-alpha.1 (M1008) + placeholder: v0.1.0-alpha.7 (M1117) validations: required: true - type: input @@ -55,6 +55,14 @@ body: description: Include the exact message, SQLSTATE and the Messages tab text when available. / Inclua a mensagem exata, SQLSTATE e o texto da aba Messages quando houver. validations: required: true + - type: textarea + id: log + attributes: + label: Error log / Log de erro + description: If PGMS showed the unexpected error window, paste the report from Copy Details or attach the file from %LOCALAPPDATA%\PGMS\logs. Read it first; an error message can quote what the server sent. / Se o PGMS mostrou a janela de erro inesperado, cole o relatório de Copy Details ou anexe o arquivo de %LOCALAPPDATA%\PGMS\logs. Leia antes; uma mensagem de erro pode citar o que o servidor enviou. + render: text + validations: + required: false - type: checkboxes id: confirm attributes: diff --git a/Directory.Build.props b/Directory.Build.props index 926c5a2..e2e1c18 100644 --- a/Directory.Build.props +++ b/Directory.Build.props @@ -1,6 +1,6 @@ - 0.1.0-alpha.6 + 0.1.0-alpha.7 enable enable true diff --git a/README.md b/README.md index 080ae73..b54096e 100644 --- a/README.md +++ b/README.md @@ -6,14 +6,24 @@ English | [Português (Brasil)](README.pt-BR.md) **The SQL Server Management Studio experience, for PostgreSQL.** A native Windows client with **database diagrams**, a **visual query designer** and **context-aware IntelliSense**, plus Object Explorer, F5 to run, execution plans, session monitoring and backup/restore, built for people who already think in SSMS. -**[Download v0.1.0-alpha.6 for Windows x64](https://github.com/leoars/PostgresManagementStudio/releases/tag/v0.1.0-alpha.6)** · Graphical installer (EN/pt-BR) or portable ZIP, .NET runtime included · Works with PostgreSQL 16–18 +**[Download v0.1.0-alpha.7 for Windows x64](https://github.com/leoars/PostgresManagementStudio/releases/tag/v0.1.0-alpha.7)** · Graphical installer (EN/pt-BR) or portable ZIP, .NET runtime included · Works with PostgreSQL 16–18 ![PGMS editor, Object Explorer and query results](docs/assets/pgms-results-m959.jpg) > Early pre-release. Querying, browsing and monitoring are the core of this alpha; administration and backup run through reviewable SQL and the official PostgreSQL tools. Full SSMS parity is not claimed. See [known limits](docs/en/validation.md) and [release notes](docs/en/release-notes.md). +**Contents:** [Highlights](#highlights) · [New in alpha.7](#new-in-alpha7) · [Why PGMS](#why-pgms) · [Features](#features) · [Get started](#get-started) · [Documentation](#documentation) · [Contribute and report problems](#contribute-and-report-problems) · [License](#license) + ## Highlights +### Write SQL with AI + +Describe what you need and **Query ▸ Generate SQL with AI…** (`Ctrl+I`) writes the SQL for you to review before it reaches the editor. Keep the conversation going with follow-up requests, or select SQL and use **Explain**, **Fix** or **Optimize SQL with AI** from the Query menu. It works with Anthropic, OpenAI or a local Ollama, with your own key. What goes to the provider: your request, the database structure (names, types, keys, comments) and, for **Fix**, the SQLSTATE and main message of the last error. Table data is never read or sent, nothing is sent until you press **Generate**, and the SQL is never executed for you. On large databases the provider first picks the relevant tables by name, within a context limit you set. **View Sent Context…** shows exactly what was sent. + +### Configure Server TLS + +A guided setup that creates or imports a certificate, installs it in the server's data directory, turns on TLS with `ALTER SYSTEM`, checks a TLS session with that certificate and restores the previous settings if anything fails. Saved profiles for that server then verify the certificate. It requires a superuser connection to a PostgreSQL server running on Windows. + ### Database diagrams ![A database diagram in PGMS with eight tables and their foreign keys](docs/assets/pgms-diagram.png) @@ -32,13 +42,26 @@ Build queries by clicking instead of typing. **Query ▸ Design Query in Editor* ![IntelliSense after JOIN suggesting a complete join from a foreign key](docs/assets/pgms-intellisense.png) -Press `Ctrl+Space` and get what fits that position. After `FROM`: tables, views and table functions, found by name across all your schemas. After `JOIN`: the whole join from your foreign keys, such as `orders o ON o.customer_id = c.id`. After an alias: its columns. Typing ignores accents, so `usuar` finds `Usuários`. Parameter Info, Quick Info and CTE columns are not available yet. +Press `Ctrl+Space` and get what fits that position. After `FROM`: tables, views and table functions, found by name across all your schemas. After `JOIN`: the whole join from your foreign keys, such as `orders o ON o.customer_id = c.id`. After an alias: its columns. Typing ignores accents, so `usuar` finds `Usuários`. Parameter Info (`Ctrl+Shift+Space`) shows the arguments of a function while you type, and Quick Info describes the name under the mouse. CTE columns are not known yet. ### Also in PGMS -- **Generate SQL with AI.** Describe a query and review the SQL before it reaches the editor, using Anthropic, OpenAI or a local Ollama with your own key. Your request and the database structure go to the provider you configure; table data is never read or sent. On large databases the provider first picks the relevant tables by name, within a context limit you set. - **Execution plan advice.** Graphical plans flag operators that discard many rows and suggest a missing index as a commented `CREATE INDEX` script, checked against the catalog and never run for you. -- **Configure Server TLS.** A guided setup that installs a certificate and turns on TLS, restoring the previous settings if it fails. Requires a superuser connection to a server running on Windows. +- **Schema Compare.** Compare two databases and get a change script in a query tab connected to the target, for you to review and run. +- **Query History.** Every query you run, grouped and searchable, stored only on your computer and encrypted for your Windows user. + +## New in alpha.7 + +- **AI conversation** and **Explain / Fix / Optimize SQL with AI**. +- **Dark theme**, Editor Appearance, Fonts and Colors, and Presenter Mode. +- **Unexpected errors are logged** to `%LOCALAPPDATA%\PGMS\logs` and shown in a window with **Report Issue**, instead of closing PGMS silently. +- Editor: Format SQL, Parameter Info and Quick Info, bookmarks, outlining, templates and snippets, Find in Files, spell checking of comments and strings, and the SSMS Edit ▸ Advanced commands. +- Schema Compare, Live Query Statistics (progress, waits and blockers), Object Explorer Details (`F7`), the Properties window (`F4`), Error List and Output. +- Object Explorer: extensions, maintenance (Vacuum, Analyze, Refresh Materialized View), menus for keys, constraints and triggers, composite types, foreign servers and logical replication. +- Backup with LZ4/Zstandard, parallel restore and restoring only chosen items; client certificates in Connect. +- Window layouts, Split Tab, Full Screen, Restore Closed Tab, a menu in the title bar with Search (`Ctrl+Q`), Keyboard and Query Shortcuts, Import and Export Settings and External Tools. + +See the [release notes](docs/en/release-notes.md) for details and limits. ## Why PGMS @@ -50,13 +73,14 @@ Press `Ctrl+Space` and get what fits that position. After `FROM`: tables, views ## Features -- SQL editor: highlighting, context-aware IntelliSense, find/replace, multiple tabs, save/load and encrypted draft recovery. +- SQL editor: highlighting, context-aware IntelliSense with Parameter Info and Quick Info, Format SQL, templates and snippets, bookmarks, find/replace and Find in Files, multiple tabs, save/load and encrypted draft recovery. - Database diagrams, Table Designer, View Designer and Query Designer. -- Independent PostgreSQL sessions, execute/cancel, Results/Messages, result grids in pages of 100,000 rows (configurable), results to text or file, copy and CSV/JSON export. -- Object Explorer, inspection, graphical execution plans (estimated and actual) and session configuration. +- Independent PostgreSQL sessions, execute/cancel, Results/Messages, result grids in pages of 100,000 rows (configurable), results to text or file, copy, Save Grid Results and CSV/JSON export, Query History and Live Query Statistics. +- Object Explorer and Object Explorer Details, the Properties window, Script as, extensions and maintenance, graphical execution plans (estimated and actual), Schema Compare and session configuration. - Reviewed SQL administration for supported databases, schemas, tables, columns, identity, indexes, constraints, sequences, roles and privileges. - Session/blocker monitoring, with distinct query cancellation and session termination. -- Logical backup/restore through external PostgreSQL tools: custom, tar, SQL and directory formats, plus reviewed global operations. +- Logical backup/restore through external PostgreSQL tools: custom, tar, SQL and directory formats, gzip/LZ4/Zstandard, parallel and partial restore, plus reviewed global operations. +- Light, dark or system theme, Fonts and Colors, keyboard shortcuts and window layouts. ## Get started @@ -75,7 +99,7 @@ Get-FileHash .\PGMS-* -Algorithm SHA256 Compare the hashes with `SHA256SUMS.txt` in the release. Starting with v0.1.0-alpha.2 the assets are built by the [release workflow](.github/workflows/release.yml) on GitHub Actions and carry a build provenance attestation, so you can also confirm that the ZIP or installer came from that workflow and this repository (requires the [GitHub CLI](https://cli.github.com/)): ```powershell -gh attestation verify .\PGMS-0.1.0-alpha.6-Setup-x64.exe --repo leoars/PostgresManagementStudio +gh attestation verify .\PGMS-0.1.0-alpha.7-Setup-x64.exe --repo leoars/PostgresManagementStudio ``` v0.1.0-alpha.1 was built on the maintainer's machine and has checksums only. Code signing through the SignPath Foundation open source program is planned. @@ -108,6 +132,8 @@ The self-contained portable package includes .NET/WPF, but no PostgreSQL server ## Contribute and report problems +**If PGMS hits an error.** An unexpected error opens a window with the details; PGMS also writes them to a daily log in `%LOCALAPPDATA%\PGMS\logs` (kept 30 days, nothing sent over the network). Choose **Report Issue**, describe what you were doing and attach the log or the text from **Copy Details** after reading it: an error message can quote what the server sent. You can usually choose **Continue**; your open queries keep their text. + See [CONTRIBUTING.md](CONTRIBUTING.md) and the [code of conduct](CODE_OF_CONDUCT.md). English and Brazilian Portuguese are welcome. Issue templates guide bug reports and feature requests; usage questions go to [Discussions](https://github.com/leoars/PostgresManagementStudio/discussions). Use synthetic data and remove credentials and personal information from reports. For vulnerabilities, follow [SECURITY.md](SECURITY.md). ## License diff --git a/README.pt-BR.md b/README.pt-BR.md index e36d11e..4971d1a 100644 --- a/README.pt-BR.md +++ b/README.pt-BR.md @@ -6,14 +6,24 @@ **A experiência do SQL Server Management Studio, para PostgreSQL.** Cliente nativo Windows com **diagramas de banco**, **Query Designer visual** e **IntelliSense por contexto**, além de Object Explorer, F5 para executar, planos de execução, monitor de sessões e backup/restore, feito para quem já pensa em SSMS. -**[Baixar v0.1.0-alpha.6 para Windows x64](https://github.com/leoars/PostgresManagementStudio/releases/tag/v0.1.0-alpha.6)** · Instalador gráfico (EN/pt-BR) ou ZIP portátil, runtime .NET incluído · Funciona com PostgreSQL 16 a 18 +**[Baixar v0.1.0-alpha.7 para Windows x64](https://github.com/leoars/PostgresManagementStudio/releases/tag/v0.1.0-alpha.7)** · Instalador gráfico (EN/pt-BR) ou ZIP portátil, runtime .NET incluído · Funciona com PostgreSQL 16 a 18 ![Editor, Object Explorer e resultados do PGMS](docs/assets/pgms-results-m959.jpg) > Pré-release inicial. Consultas, navegação e monitoramento são o núcleo desta alpha; administração e backup usam SQL revisável e as ferramentas oficiais do PostgreSQL. Não se declara paridade integral com SSMS. Veja os [limites conhecidos](docs/pt-BR/validation.md) e as [notas da versão](docs/pt-BR/release-notes.md). +**Conteúdo:** [Destaques](#destaques) · [Novidades da alpha.7](#novidades-da-alpha7) · [Por que o PGMS](#por-que-o-pgms) · [Funcionalidades](#funcionalidades) · [Começar](#começar) · [Documentação](#documentação) · [Contribuir e relatar problemas](#contribuir-e-relatar-problemas) · [Licença](#licença) + ## Destaques +### Escrever SQL com IA + +Descreva o que você precisa e **Query ▸ Generate SQL with AI…** (`Ctrl+I`) escreve o SQL para você revisar antes de ele ir para o editor. Continue a conversa com pedidos de seguimento, ou selecione um SQL e use **Explain**, **Fix** ou **Optimize SQL with AI** no menu Query. Funciona com Anthropic, OpenAI ou um Ollama local, com a sua própria chave. O que vai para o provedor: o seu pedido, a estrutura do banco (nomes, tipos, chaves, comentários) e, no **Fix**, o SQLSTATE e a mensagem principal do último erro. Dados das tabelas nunca são lidos nem enviados, nada é enviado antes de você clicar em **Generate**, e o SQL nunca é executado por conta própria. Em bancos grandes, o provedor primeiro escolhe as tabelas relevantes pelos nomes, dentro de um limite de contexto que você define. **View Sent Context…** mostra exatamente o que foi enviado. + +### Configure Server TLS + +Um assistente que cria ou importa um certificado, instala-o no diretório de dados do servidor, liga o TLS com `ALTER SYSTEM`, confere uma sessão TLS com esse certificado e restaura a configuração anterior se algo falhar. Os perfis salvos desse servidor passam a verificar o certificado. Exige conexão de superusuário a um servidor PostgreSQL rodando no Windows. + ### Diagramas de banco de dados ![Um diagrama de banco no PGMS com oito tabelas e suas chaves estrangeiras](docs/assets/pgms-diagram.png) @@ -32,13 +42,26 @@ Monte consultas clicando, em vez de digitar. **Query ▸ Design Query in Editor* ![IntelliSense depois de JOIN sugerindo uma junção completa a partir de uma chave estrangeira](docs/assets/pgms-intellisense.png) -Aperte `Ctrl+Space` e receba o que cabe naquela posição. Depois de `FROM`: tabelas, views e funções de tabela, encontradas pelo nome em todos os seus schemas. Depois de `JOIN`: a junção inteira a partir das chaves estrangeiras, como `orders o ON o.customer_id = c.id`. Depois de um alias: as colunas dele. A busca ignora acentos, então `usuar` encontra `Usuários`. Parameter Info, Quick Info e colunas de CTE ainda não existem. +Aperte `Ctrl+Space` e receba o que cabe naquela posição. Depois de `FROM`: tabelas, views e funções de tabela, encontradas pelo nome em todos os seus schemas. Depois de `JOIN`: a junção inteira a partir das chaves estrangeiras, como `orders o ON o.customer_id = c.id`. Depois de um alias: as colunas dele. A busca ignora acentos, então `usuar` encontra `Usuários`. Parameter Info (`Ctrl+Shift+Space`) mostra os argumentos de uma função enquanto você digita, e Quick Info descreve o nome sob o mouse. Colunas de CTE ainda não são conhecidas. ### Também no PGMS -- **Gerar SQL com IA.** Descreva a consulta e revise o SQL antes de ele ir para o editor, com Anthropic, OpenAI ou um Ollama local, usando a sua própria chave. O pedido e a estrutura do banco vão para o provedor que você configurar; dados das tabelas nunca são lidos nem enviados. Em bancos grandes, o provedor primeiro escolhe as tabelas relevantes pelos nomes, dentro de um limite de contexto que você define. - **Dicas no plano de execução.** O plano gráfico marca operadores que descartam muitas linhas e sugere um índice faltante como script `CREATE INDEX` comentado, conferido no catálogo e nunca executado por conta própria. -- **Configure Server TLS.** Assistente que instala um certificado e liga o TLS, restaurando a configuração anterior se algo falhar. Exige conexão de superusuário a um servidor em Windows. +- **Schema Compare.** Compare dois bancos e receba um script de mudanças numa aba de consulta conectada ao destino, para você revisar e executar. +- **Query History.** Cada consulta que você executa, agrupada e pesquisável, guardada só no seu computador e criptografada para o seu usuário do Windows. + +## Novidades da alpha.7 + +- **Conversa com a IA** e **Explain / Fix / Optimize SQL with AI**. +- **Tema escuro**, Editor Appearance, Fonts and Colors e Presenter Mode. +- **Erros inesperados ficam registrados** em `%LOCALAPPDATA%\PGMS\logs` e aparecem numa janela com **Report Issue**, em vez de fechar o PGMS em silêncio. +- Editor: Format SQL, Parameter Info e Quick Info, marcadores, outlining, modelos e trechos, Find in Files, verificação ortográfica de comentários e cadeias e os comandos de Edit ▸ Advanced do SSMS. +- Schema Compare, Live Query Statistics (progresso, esperas e bloqueios), Object Explorer Details (`F7`), a janela Properties (`F4`), Error List e Output. +- Object Explorer: extensões, manutenção (Vacuum, Analyze, Refresh Materialized View), menus de chaves, constraints e triggers, tipos compostos, servidores estrangeiros e replicação lógica. +- Backup com LZ4/Zstandard, restore paralelo e restauração só dos itens escolhidos; certificados de cliente no Connect. +- Layouts de janela, Split Tab, Full Screen, Restore Closed Tab, menu na barra de título com Search (`Ctrl+Q`), Keyboard e Query Shortcuts, Import and Export Settings e External Tools. + +Veja as [notas da versão](docs/pt-BR/release-notes.md) para detalhes e limites. ## Por que o PGMS @@ -50,13 +73,14 @@ Aperte `Ctrl+Space` e receba o que cabe naquela posição. Depois de `FROM`: tab ## Funcionalidades -- Editor SQL: destaque, IntelliSense por contexto, busca/substituição, múltiplas abas, abrir/salvar e recuperação criptografada de rascunhos. +- Editor SQL: destaque, IntelliSense por contexto com Parameter Info e Quick Info, Format SQL, modelos e trechos, marcadores, busca/substituição e Find in Files, múltiplas abas, abrir/salvar e recuperação criptografada de rascunhos. - Diagramas de banco, Table Designer, View Designer e Query Designer. -- Sessões PostgreSQL independentes, executar/cancelar, Results/Messages, grade em páginas de 100.000 linhas (configurável), resultados em texto ou arquivo, cópia e exportação CSV/JSON. -- Object Explorer, inspeção, planos de execução gráficos (estimados e reais) e configuração da sessão. +- Sessões PostgreSQL independentes, executar/cancelar, Results/Messages, grade em páginas de 100.000 linhas (configurável), resultados em texto ou arquivo, cópia, Save Grid Results e exportação CSV/JSON, Query History e Live Query Statistics. +- Object Explorer e Object Explorer Details, janela Properties, Script as, extensões e manutenção, planos de execução gráficos (estimados e reais), Schema Compare e configuração da sessão. - Administração com SQL revisável nos casos suportados de bancos, schemas, tabelas, colunas, identity, índices, constraints, sequences, roles e privilégios. - Monitor de sessões/bloqueadores, com cancelamento de consulta e encerramento de sessão distintos. -- Backup/restore lógico por ferramentas externas PostgreSQL: custom, tar, SQL e diretório, além de operações globais revisadas. +- Backup/restore lógico por ferramentas externas PostgreSQL: custom, tar, SQL e diretório, gzip/LZ4/Zstandard, restore paralelo e parcial, além de operações globais revisadas. +- Tema claro, escuro ou do sistema, Fonts and Colors, atalhos de teclado e layouts de janela. ## Começar @@ -75,7 +99,7 @@ Get-FileHash .\PGMS-* -Algorithm SHA256 Compare os hashes com o `SHA256SUMS.txt` da release. A partir da v0.1.0-alpha.2 os assets são compilados pelo [workflow de release](.github/workflows/release.yml) no GitHub Actions e trazem atestado de proveniência de build, então você também pode confirmar que o ZIP ou o instalador saiu desse workflow e deste repositório (exige o [GitHub CLI](https://cli.github.com/)): ```powershell -gh attestation verify .\PGMS-0.1.0-alpha.6-Setup-x64.exe --repo leoars/PostgresManagementStudio +gh attestation verify .\PGMS-0.1.0-alpha.7-Setup-x64.exe --repo leoars/PostgresManagementStudio ``` A v0.1.0-alpha.1 foi compilada na máquina do mantenedor e tem apenas checksums. A assinatura de código pelo programa open source da SignPath Foundation está planejada. @@ -108,6 +132,8 @@ O pacote portátil self-contained inclui .NET/WPF, sem servidor ou ferramentas P ## Contribuir e relatar problemas +**Se o PGMS der erro.** Um erro inesperado abre uma janela com os detalhes; o PGMS também os grava num log diário em `%LOCALAPPDATA%\PGMS\logs` (guardado por 30 dias, nada é enviado pela rede). Escolha **Report Issue**, conte o que você estava fazendo e anexe o log ou o texto de **Copy Details** depois de lê-lo: uma mensagem de erro pode citar o que o servidor enviou. Em geral dá para escolher **Continue**; as consultas abertas mantêm o texto. + Veja [CONTRIBUTING.pt-BR.md](CONTRIBUTING.pt-BR.md) e o [código de conduta](CODE_OF_CONDUCT.pt-BR.md). Os modelos de issue orientam relatos de defeito e pedidos de funcionalidade; dúvidas de uso vão para [Discussions](https://github.com/leoars/PostgresManagementStudio/discussions). Inglês e português do Brasil são bem-vindos. Use dados sintéticos e remova credenciais e informações pessoais dos relatos. Para vulnerabilidades, siga [SECURITY.pt-BR.md](SECURITY.pt-BR.md). ## Licença diff --git a/SECURITY.md b/SECURITY.md index f0afe09..3fc72ef 100644 --- a/SECURITY.md +++ b/SECURITY.md @@ -2,7 +2,7 @@ English | [Português (Brasil)](SECURITY.pt-BR.md) -PGMS is in development. There is no published supported release series or guaranteed response time. Current development and the v0.1.0-alpha.6 pre-release are the starting points for investigation; historical packages do not automatically receive fixes. +PGMS is in development. There is no published supported release series or guaranteed response time. Current development and the v0.1.0-alpha.7 pre-release are the starting points for investigation; historical packages do not automatically receive fixes. Do not disclose an unpatched vulnerability or real credentials in a public issue. Use GitHub's **Report a vulnerability** on this repository if private reporting is enabled. If it is unavailable, open an issue asking the maintainer for a private contact channel without including vulnerability details. Never post database dumps, saved profiles, DPAPI payloads, access tokens or private keys. diff --git a/SECURITY.pt-BR.md b/SECURITY.pt-BR.md index 7d4524c..05dbeff 100644 --- a/SECURITY.pt-BR.md +++ b/SECURITY.pt-BR.md @@ -2,7 +2,7 @@ [English](SECURITY.md) | Português (Brasil) -O PGMS está em desenvolvimento. Não há série de releases publicada com suporte nem prazo de resposta garantido. O desenvolvimento atual e a pré-release v0.1.0-alpha.6 são o ponto de partida para investigação; pacotes históricos não recebem correções automaticamente. +O PGMS está em desenvolvimento. Não há série de releases publicada com suporte nem prazo de resposta garantido. O desenvolvimento atual e a pré-release v0.1.0-alpha.7 são o ponto de partida para investigação; pacotes históricos não recebem correções automaticamente. Não divulgue vulnerabilidade sem correção ou credenciais reais em uma issue pública. Use **Report a vulnerability** no GitHub deste repositório se o relato privado estiver habilitado. Se estiver indisponível, abra uma issue pedindo ao mantenedor um canal privado, sem detalhes da vulnerabilidade. Nunca publique dumps, perfis salvos, payloads DPAPI, tokens ou chaves privadas. diff --git a/docs/en/distribution.md b/docs/en/distribution.md index c85e4e4..0c2fe3e 100644 --- a/docs/en/distribution.md +++ b/docs/en/distribution.md @@ -1,4 +1,4 @@ -# PGMS v0.1.0-alpha.6 — portable distribution (M1062) +# PGMS v0.1.0-alpha.7 — portable distribution (M1117) English | Português (Brasil): LEIA-ME.md in the package, or docs/pt-BR/distribution.md in the source repository. @@ -10,6 +10,8 @@ Each query tab has its own session. F5 executes selection/document. Ctrl+C copie State defaults to %LOCALAPPDATA%/PGMS; PGMS_STATE_DIRECTORY allows a separate trial directory. Saved credentials, recovery and journals use Windows current-user DPAPI. Close PGMS before backing up state; keep SQL files separately and review recovered tabs with Save As. State/credentials are not universally portable between users/machines or older builds. +Unexpected errors are written to a daily log in %LOCALAPPDATA%/PGMS/logs (logs under PGMS_STATE_DIRECTORY), kept 30 days, with password values in key=value text masked; nothing is sent over the network. The error window offers Copy Details, Open Log Folder, Report Issue, Continue and Close PGMS. To report a problem, use the issue templates of the repository below and attach the log after reading it: an error message can quote what the server sent. + Verify integrity with ./Verify-Package.ps1 -PackagePath . in PowerShell 7; manifest hashes detect differences, not authorship. Optional managed installation also requires PowerShell 7. From the extracted package: ./Install-Pgms.ps1 -PackagePath .; inspect ./Get-PgmsInstallation.ps1; launch ./Start-Pgms.ps1; use ./Set-PgmsActiveVersion.ps1 -Milestone for rollback and ./Uninstall-Pgms.ps1 -Milestone for removal. Use -InstallRoot for an isolated managed location. These scripts preserve user state and refuse unmanaged/nonempty roots and unsafe paths; close running instances first. Source, bilingual guides and reporting: https://github.com/leoars/PostgresManagementStudio . Original work is Apache-2.0; third-party licenses and trademark terms remain separate. PGMS is independent and does not claim full SSMS parity or endorsement. diff --git a/docs/en/getting-started.md b/docs/en/getting-started.md index 7125d1f..fd95180 100644 --- a/docs/en/getting-started.md +++ b/docs/en/getting-started.md @@ -2,7 +2,7 @@ English | [Português (Brasil)](../pt-BR/getting-started.md) -[Download v0.1.0-alpha.6](https://github.com/leoars/PostgresManagementStudio/releases/tag/v0.1.0-alpha.6): [graphical installer](graphical-installer.md), portable ZIP or PowerShell 7 installer. The graphical installer offers current-user and all-users modes and does not require PowerShell. See [release notes](release-notes.md). +[Download v0.1.0-alpha.7](https://github.com/leoars/PostgresManagementStudio/releases/tag/v0.1.0-alpha.7): [graphical installer](graphical-installer.md), portable ZIP or PowerShell 7 installer. The graphical installer offers current-user and all-users modes and does not require PowerShell. See [release notes](release-notes.md). ### Windows SmartScreen warning @@ -15,7 +15,7 @@ Get-FileHash .\PGMS-* -Algorithm SHA256 Compare the hashes with `SHA256SUMS.txt` in the release. Starting with v0.1.0-alpha.2 the assets are built by the [release workflow](../../.github/workflows/release.yml) on GitHub Actions and carry a build provenance attestation, so you can also confirm that the ZIP or installer came from that workflow and this repository (requires the [GitHub CLI](https://cli.github.com/); see [development](development.md)): ```powershell -gh attestation verify .\PGMS-0.1.0-alpha.6-Setup-x64.exe --repo leoars/PostgresManagementStudio +gh attestation verify .\PGMS-0.1.0-alpha.7-Setup-x64.exe --repo leoars/PostgresManagementStudio ``` v0.1.0-alpha.1 was built on the maintainer's machine and has checksums only. Code signing through the SignPath Foundation open source program is planned. diff --git a/docs/en/graphical-installer.md b/docs/en/graphical-installer.md index 1ba5d52..bc947b4 100644 --- a/docs/en/graphical-installer.md +++ b/docs/en/graphical-installer.md @@ -2,7 +2,7 @@ English | [Português (Brasil)](../pt-BR/graphical-installer.md) -Download `PGMS-0.1.0-alpha.6-Setup-x64.exe` from the [alpha.6 release](https://github.com/leoars/PostgresManagementStudio/releases/tag/v0.1.0-alpha.6) and check it against `SHA256SUMS.txt` (and, optionally, `gh attestation verify`). Since v0.1.0-alpha.2 the installer is built by the release workflow from the same payload as the portable ZIP of that release; in v0.1.0-alpha.1 it was added later to wrap the existing M1008 payload. The installer does not require PowerShell or a separately installed .NET runtime. +Download `PGMS-0.1.0-alpha.7-Setup-x64.exe` from the [alpha.7 release](https://github.com/leoars/PostgresManagementStudio/releases/tag/v0.1.0-alpha.7) and check it against `SHA256SUMS.txt` (and, optionally, `gh attestation verify`). Since v0.1.0-alpha.2 the installer is built by the release workflow from the same payload as the portable ZIP of that release; in v0.1.0-alpha.1 it was added later to wrap the existing M1008 payload. The installer does not require PowerShell or a separately installed .NET runtime. ## Installation choices diff --git a/docs/en/release-notes.md b/docs/en/release-notes.md index c9317b1..90f6b1f 100644 --- a/docs/en/release-notes.md +++ b/docs/en/release-notes.md @@ -1,28 +1,71 @@ -# v0.1.0-alpha.6 — Windows x64 +# v0.1.0-alpha.7 — Windows x64 English | [Português (Brasil)](../pt-BR/release-notes.md) -Sixth public pre-release of PGMS. It is an alpha for evaluation with synthetic/disposable data. Build label: M1062. The binaries are built and attested by the same [release workflow](../../.github/workflows/release.yml) as the previous releases. Original work is under Apache-2.0, with credits in `NOTICE`; releases through alpha.4 remain under MIT. - -## What changed since v0.1.0-alpha.5 - -- **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. -- **Script as in Object Explorer.** **Script … as** (CREATE, DROP and the verbs that apply, to a query window, a file or the clipboard) on databases, schemas, tables, views, sequences, functions, procedures, enums, domains, indexes, keys, constraints, triggers and roles; **Keys**, **Constraints** and **Triggers** folders under a table; **Rebuild** of an index and **Rebuild All**; **Take Offline** and **Bring Online** of a database (`ALLOW_CONNECTIONS`), with the offline database marked in the tree. -- **Warnings in graphical execution plans.** An operator whose filter discarded many rows in an actual plan shows a yellow triangle and a **Warnings** section with the Filter, Join Filter and Index Recheck counts. Thresholds (10 times the rows returned and at least 1,000 rows by default) are in Query Options and Tools ▸ Options. It is a PGMS rule; PostgreSQL itself emits no plan warnings. -- **Missing index suggestion from the plan.** For a warned scan with simple filters, a green line in the plan header and **Missing Index Details…** open a commented `CREATE INDEX` script, checked against the catalog. Nothing runs. It is a heuristic without selectivity estimates; joins, `OR`, expressions and `INCLUDE` are not covered. -- **Generate SQL with AI on large databases.** When the structure does not fit the context limit (now configurable, 200,000 characters by default), the provider first chooses the relevant tables from their names, and the tables sent are ordered by that choice, foreign keys and words shared with the request. **View Sent Context…** shows both calls. +Seventh public pre-release of PGMS. It is an alpha for evaluation with synthetic/disposable data. Build label: M1117. The binaries are built and attested by the same [release workflow](../../.github/workflows/release.yml) as the previous releases. Original work is under Apache-2.0, with credits in `NOTICE`; releases through alpha.4 remain under MIT. + +## Highlights + +- **AI assistant: conversation and Explain/Fix/Optimize.** The **Generate SQL with AI** window now takes follow-up requests: the last five requests of the conversation and the SQL written for them go with the next one, and **New Conversation** starts over. **Query ▸ Explain SQL with AI**, **Fix SQL with AI** and **Optimize SQL with AI** open the window with the selected SQL (or the document) and a request already written; **Fix** adds the SQLSTATE and the main message of the last error of the tab, but never its DETAIL, which can quote row values. Nothing is sent until you press **Generate**, and nothing is executed: the SQL only goes into the editor. The database structure goes to the provider you set (Anthropic, OpenAI or a local Ollama); table data is never read or sent. With Ollama, PGMS now asks for a context window that fits the prompt and trims the structure to the model's maximum, instead of letting the server cut the prompt silently. +- **Configure Server TLS** is unchanged: a guided setup that installs a certificate and turns on TLS, restoring the previous settings if it fails. It requires a superuser connection to a server running on Windows. +- **Unexpected errors are logged.** An error that PGMS did not handle no longer closes the program silently. It is written to a daily log in `%LOCALAPPDATA%\PGMS\logs` (kept 30 days; password values in `key=value` text are masked) and a window shows the error with **Copy Details**, **Open Log Folder**, **Report Issue**, **Continue** (the default) and **Close PGMS**. Nothing is sent over the network. +- **Dark theme.** **Tools ▸ Theme** offers Light, Dark and Use system setting. In the dark theme the shell, menus, standard controls, result grids, the tree and the Properties window follow it; database diagrams and graphical plans stay light, like paper. **Tools ▸ Editor Appearance** sets the editor colors on its own (including two extra-contrast modes) and **View ▸ Presenter Mode** (`Ctrl+Shift+F5`) enlarges the editor, results and window text for a presentation. + +## What changed since v0.1.0-alpha.6 + +**Editor** +- **Edit ▸ Advanced:** toggle line and block comments, upper/lower case, move, sort, join and duplicate lines, delete horizontal white space, tabify/untabify, indentation, Insert File As Text, Expand Selection, Containing Block, Expand to Line, next/previous subword, Incremental Search, **Format SQL** (`Ctrl+K`, `Ctrl+Q`; only spaces, line breaks and keyword case change) and **Toggle Spell Checker** (comments and strings, through the Windows spell checker). +- An editor information bar with zoom (20–400 %, `Ctrl`+wheel), line and column (opens Go To Line), tabs/spaces, line ending (CRLF/LF/CR) and encoding, with **Set End of Line Sequence**, **Set Indentation** and **Set Encoding** (Unicode encodings). +- **IntelliSense:** Parameter Info (`Ctrl+Shift+Space`) and Quick Info (`Ctrl+K`, `Ctrl+I`, or hovering). +- **Bookmarks** per tab (`Ctrl+K`, `Ctrl+K` and the SSMS chords) and **Outlining** by statement and block comment. +- **Templates and snippets:** Template Explorer (`Ctrl+Alt+T`) with PostgreSQL templates and your own `.sql` files, Specify Values for Template Parameters (`Ctrl+Shift+M`), Insert Snippet and Surround With. +- The error position reported by the server is underlined in the editor, counted in the information bar and reached by **Go To Next/Previous Issue in File** (`Alt+PgDn`/`Alt+PgUp`). +- **Find in Files** and **Replace in Files** (`Ctrl+Shift+H`) over a folder, the open documents or the current one, with a Find Results pane. +- Clipboard history (`Ctrl+Shift+V`) and Go To Last Edit Location (`Ctrl+Shift+Backspace`). +- Lines over 10,000 characters are shown cut, with a marker that opens the whole line, so the editor no longer pauses on them. + +**Files, tabs and windows** +- **File ▸ New ▸ Query with Current Connection** and **Database Engine Query**; **Open ▸ File** connects the new tab with the current connection, and **File Disconnected…** opens without connecting; **Disconnect All Queries**. +- Save All, Recent Files (count in Tools ▸ Options), Close All Tabs and **Restore Closed Tab**, also for queries without a file. +- **Window:** next/previous pane (`F6`), Show Results Pane (`Ctrl+R`), Split Tab, Dock, Auto Hide, Move To New Window, saved window layouts (up to ten) and **View ▸ Full Screen**. +- The menu now shares the title bar, with the window buttons and a **Search** box (`Ctrl+Q`) that finds menu commands and Tools ▸ Options pages and settings. +- **View ▸ Properties Window** (`F4`), **Error List** (`Ctrl+\`, `E`) with the last error of each tab, and **Output** (`Ctrl+Alt+O`) with the messages and executions of the session. +- **File ▸ Page Setup…** and **Print…** for the SQL of the active tab. +- Connection texts closer to SSMS: the server node shows `host:port (PostgreSQL version - login)` and the query status bar shows server, login with backend PID, database, time and rows. + +**Queries and results** +- Results/Messages tabs are above the results, and **Save Results As…** in the grid menu opens **Save Grid Results** (`.csv` comma separated or `.txt` tab separated, with headers). The export options band is still available from **Export Options…**. +- **Query ▸ Include Live Query Statistics** shows, once a second over a separate connection, the state, elapsed time, waits, blocking sessions and `pg_stat_progress_*` progress (CREATE INDEX, VACUUM, ANALYZE, CLUSTER, COPY) of the running query. PostgreSQL has no per-operator counters, so there is no live plan. +- **Query Shortcuts** (`Alt+F1`, `Ctrl+1` to `Ctrl+0`) in Tools ▸ Options, empty by default. +- Extension types such as PostGIS `geometry` are shown as the text the server sends (hexadecimal EWKB), without errors. + +**Object Explorer and administration** +- **Object Explorer Details** (`F7`), the contents of the selected node with search. +- **Keys**, **Constraints** and **Triggers**: Modify, Rename, Delete with the exact command (no CASCADE), New Foreign Key… and New Constraint…; Enable/Disable of triggers; New Function…, New Stored Procedure… and New Trigger… from templates. +- An **Extensions** folder per database with New Extension…, Update Extension… and Delete. +- A **Maintenance** submenu with Vacuum…, Analyze… and Refresh Materialized View…; the command opens in a query tab, not run directly. +- Composite Types, Foreign Servers and Replication (local publications and subscriptions), read only. +- The filter gains **Does not equal**. +- **Role Memberships** lists effective memberships, direct and inherited, with the path. +- **Tools ▸ Schema Compare** compares two databases (read only) and writes a change script into a query tab connected to the target. It never runs the script. +- **Back Up:** LZ4 and Zstandard compression. **Restore:** parallel jobs (1–32) and **Choose Items…** to restore only some items of an archive. +- **Connect:** client certificate, client key and key password (stored with DPAPI); backup and restore receive the key password through a temporary private service file. + +**Settings** +- Tools ▸ Options: **Fonts and Colors** (Text Editor, Grid Results, Text Results), **Keyboard** (one shortcut per menu command), Object Explorer **Scripting** options, **Designers** and **Connection Dialog** options. +- **Tools ▸ Import and Export Settings…** (a `.pgmssettings` file with the Options), **External Tools…** and **Customize…** for the toolbars. +- **Help ▸ View Help** (`Ctrl+F1`) opens the packaged guide; **Release Notes** opens the release list. + +**PostgreSQL 16:** four defects found by a complete regression on PostgreSQL 16.15 were fixed, among them `MAINTAIN` being offered on servers before 17. ## Downloads -From [this release](https://github.com/leoars/PostgresManagementStudio/releases/tag/v0.1.0-alpha.6): +From [this release](https://github.com/leoars/PostgresManagementStudio/releases/tag/v0.1.0-alpha.7): | File | Purpose | | --- | --- | -| `PGMS-0.1.0-alpha.6-Setup-x64.exe` | Graphical installer (English/pt-BR). Current user without administrator rights, or all users with elevation. No PowerShell or separate .NET runtime required. | -| `PGMS-0.1.0-alpha.6-win-x64.zip` | Portable application with .NET/WPF runtime. Extract the entire folder and run PGMS.exe. Includes the managed PowerShell 7 scripts. | +| `PGMS-0.1.0-alpha.7-Setup-x64.exe` | Graphical installer (English/pt-BR). Current user without administrator rights, or all users with elevation. No PowerShell or separate .NET runtime required. | +| `PGMS-0.1.0-alpha.7-win-x64.zip` | Portable application with .NET/WPF runtime. Extract the entire folder and run PGMS.exe. Includes the managed PowerShell 7 scripts. | | `SHA256SUMS.txt` | SHA256 of every asset in this release. Hashes check correspondence, not authorship. | | `package-manifest.json` | SHA256 manifest of every file inside the ZIP, as checked by `Verify-Package.ps1`. | | `RELEASE-NOTES.md`, `RELEASE-NOTES.pt-BR.md` | These notes. | @@ -33,25 +76,29 @@ The binaries are not code-signed, so Windows SmartScreen may warn on first launc ```powershell Get-FileHash .\PGMS-* -Algorithm SHA256 -gh attestation verify .\PGMS-0.1.0-alpha.6-Setup-x64.exe --repo leoars/PostgresManagementStudio +gh attestation verify .\PGMS-0.1.0-alpha.7-Setup-x64.exe --repo leoars/PostgresManagementStudio ``` Compare the hashes with `SHA256SUMS.txt`. The second command needs the [GitHub CLI](https://cli.github.com/) and confirms that the file was produced by this repository's release workflow at the tagged commit; run it for the ZIP as well. Code signing through the SignPath Foundation open source program is planned; no date is promised. +## Report a problem + +When PGMS shows the unexpected error window, choose **Report Issue** and attach the log from **Open Log Folder** (`%LOCALAPPDATA%\PGMS\logs`). Say what you were doing, the PostgreSQL version and whether it happens again. Read the log before attaching it: an error message can quote what the server sent. Use the [issue templates](https://github.com/leoars/PostgresManagementStudio/issues/new/choose). + ## Scope -SQL editor with IntelliSense and independent sessions, Object Explorer, paged Results and Results to Text/File, CSV/JSON export, database diagrams and designers, graphical plans, reviewed PostgreSQL administration, identity/privileges, Activity Monitor, query statistics and logical backup/restore. PostgreSQL 16 to 18 and same-major client tools are required for database operations and backup/restore; server/tools are not bundled. SSMS is neither required nor distributed. +SQL editor with IntelliSense and independent sessions, Object Explorer, paged Results and Results to Text/File, CSV/JSON export, database diagrams and designers, graphical plans, reviewed PostgreSQL administration, identity/privileges, Activity Monitor, query statistics, Schema Compare and logical backup/restore. PostgreSQL 16 to 18 and same-major client tools are required for database operations and backup/restore; server/tools are not bundled. SSMS is neither required nor distributed. ## Validation -Application behavior: the M1062 source passed the complete regression of this repository on PostgreSQL 17.11 (**3,018 integration + 4,586 WPF = 7,604 checks**) on an isolated loopback cluster; the host PostgreSQL service is not used. The features added since alpha.5 were not run as a complete regression on PostgreSQL 16 or 18. +Application behavior: the M1117 source passed the complete regression of this repository on PostgreSQL 17.11 (see [validation](validation.md#v010-alpha7--m1117--2026-11-17)) on an isolated loopback cluster; the host PostgreSQL service is not used. Most features added since alpha.6 were validated by focused automated suites while they were built; a complete regression on PostgreSQL 16.15 and 18.6 was last run on an earlier source (M1066). The new AI actions and the conversation were tested with a local fake provider only, not with a real one. PostGIS itself was not installed in the test cluster: a stand-in `geometry` type was used. -All-users (elevated) installation, a clean-Windows VM installation and physical DPI/keyboard/screen-reader observations of the new screens are not newly certified by this release. New screens were exercised by automated tests, not by hand with mouse and keyboard on this source. +A clean-Windows VM installation, another Windows user without privileges and physical DPI/keyboard/screen-reader observations of the new screens are not certified by this release. ## Known limits -Windows x64 only. Unsigned executable and installer; SmartScreen warns. No MSI, automatic update or production-support guarantee. Full SSMS parity is not claimed. Results: sorting, copy and export apply to the current page; rows after the first page stay in a temporary file, unencrypted, until the next execution or until the tab closes; Results to Text keeps the 10,000-row and 250,000-cell limits, and Results to File has neither. IntelliSense has no Parameter Info or Quick Info, and does not know CTE columns, temporary tables or `SET search_path` of the session. Query Designer: `UNION` and `WITH` open only in the SQL pane; Update, Delete and Insert Values take one table. Find Missing Foreign Keys is a heuristic: a matching name is a hint, not proof. +Windows x64 only. Unsigned executable and installer; SmartScreen warns. No MSI, automatic update or production-support guarantee. Full SSMS parity is not claimed. Dark theme: diagrams and plans stay light; colored themes are not available. One caret only (no multiple carets). Several result sets are shown in tabs, not stacked. Live Query Statistics has no live plan. PostGIS values are shown as hexadecimal text, without WKT, GeoJSON or a map. Results: sorting, copy and export apply to the current page; rows after the first page stay in a temporary file, unencrypted, until the next execution or until the tab closes; Results to Text keeps the 10,000-row and 250,000-cell limits, and Results to File has neither. IntelliSense does not know CTE columns, temporary tables or `SET search_path` of the session. Query Designer: `UNION` and `WITH` open only in the SQL pane. Find Missing Foreign Keys is a heuristic: a matching name is a hint, not proof. The error log masks passwords only in `key=value` form. ## Previous releases -v0.1.0-alpha.5 (2026-11-08, database diagrams, Query Designer, IntelliSense; Apache-2.0) remains available with its original assets and notes. v0.1.0-alpha.4 (2026-11-07, Activity Monitor in a tab), v0.1.0-alpha.3 (2026-11-02, Query Statistics), v0.1.0-alpha.2 (2026-11-01, first CI-built release with attestation) and v0.1.0-alpha.1 (2026-10-31) remain available with their original assets and notes, under MIT. +v0.1.0-alpha.6 (2026-11-13, diagram indexes and descriptions, Query History, Script as, plan warnings) and v0.1.0-alpha.5 (2026-11-08, database diagrams, Query Designer, IntelliSense; Apache-2.0) remain available with their original assets and notes. v0.1.0-alpha.4 (2026-11-07, Activity Monitor in a tab), v0.1.0-alpha.3 (2026-11-02, Query Statistics), v0.1.0-alpha.2 (2026-11-01, first CI-built release with attestation) and v0.1.0-alpha.1 (2026-10-31) remain available with their original assets and notes, under MIT. diff --git a/docs/en/user-guide.md b/docs/en/user-guide.md index 5c2cf4f..a43cbe2 100644 --- a/docs/en/user-guide.md +++ b/docs/en/user-guide.md @@ -4,7 +4,7 @@ English | [Português (Brasil)](../pt-BR/user-guide.md) ## Connect and query -Open **New Query** (`Ctrl+N`), then **Connect**. Enter host, port, database, role and TLS settings. The default VerifyFull requires a trusted certificate and matching hostname. **Test Connection** checks the connection without saving a profile. Save a profile explicitly; password storage is optional and protected by Windows DPAPI. Each query tab owns its own PostgreSQL session. Switching database needs a connection, not a SQL Server `USE` command. T-SQL is not translated. +Open **New Query** (`Ctrl+N`), then **Connect**. Enter host, port, database, role and TLS settings. The default VerifyFull requires a trusted certificate and matching hostname. **Test Connection** checks the connection without saving a profile. Save a profile explicitly; password storage is optional and protected by Windows DPAPI. Each query tab owns its own PostgreSQL session. Switching database needs a connection, not a SQL Server `USE` command. T-SQL is not translated. For certificate authentication, set **Client certificate**, **Client key** and, for an encrypted key, **Key password** (stored with DPAPI when you save it); backup and restore pass that password to the PostgreSQL tools through a temporary private service file. Use `F5` to execute the selection or document and **Cancel** to request cancellation. Cancellation does not prove that a server-side command or COMMIT was rolled back. Inspect the result before repeating a write. Results/Messages show results and diagnostics. Read timeout, server session settings and explain plans have dedicated controls. **Analyze Plan** executes SQL and requires review; use it only when that execution is intended. SQL with `$1`-style placeholders cannot run without parameter values: PGMS refuses it before sending, keeps the session open and points to the placeholder. `PREPARE` and function/procedure bodies are exempt, and **Estimated Plan** switches to a generic plan. @@ -30,7 +30,7 @@ In Object Explorer, right-click **Database Diagrams** under a database and choos ## IntelliSense -`Ctrl+Space` or `Ctrl+J` opens the list; typing a dot opens it by itself. `Tab` accepts and `Esc` closes. **Query ▸ IntelliSense Enabled** (`Ctrl+B`, `Ctrl+I`) turns it off for the tab, and **Edit ▸ IntelliSense ▸ Refresh Local Cache** (`Ctrl+Shift+R`) reads the catalog again after schema changes. After `FROM` and similar keywords it searches table names in every user schema; after `JOIN` it offers whole joins from foreign keys. +`Ctrl+Space` or `Ctrl+J` opens the list; typing a dot opens it by itself. `Tab` accepts and `Esc` closes. **Query ▸ IntelliSense Enabled** (`Ctrl+B`, `Ctrl+I`) turns it off for the tab, and **Edit ▸ IntelliSense ▸ Refresh Local Cache** (`Ctrl+Shift+R`) reads the catalog again after schema changes. After `FROM` and similar keywords it searches table names in every user schema; after `JOIN` it offers whole joins from foreign keys. Parameter Info and Quick Info are described under [Editor](#editor). ## Execution plans @@ -40,6 +40,8 @@ In Object Explorer, right-click **Database Diagrams** under a database and choos **Query ▸ Generate SQL with AI…** sends your request and the structure of the database (names, types, keys, comments; never table data) to the provider set in **Tools ▸ AI Assistant Settings…**: Anthropic, OpenAI or a local Ollama, with your own key, stored encrypted for your Windows user. The SQL is shown for review and only inserted into the editor. The structure sent is limited by **Context limit** in the settings (200,000 characters by default). When the database does not fit, PGMS first sends only the table names, with their comments, and lets the provider choose the relevant tables; then it sends those tables, the tables their foreign keys reference and the tables whose names share words with your request. Tables left out are listed by name. **View Sent Context…** shows what was sent in each call. The first call costs tokens too. +**Conversation.** After a result, type a follow-up request (for example, "also filter by status"): the last five requests of the conversation and the SQL written for them go with it. **New Conversation** clears them; closing the window ends the conversation. **Query ▸ Explain SQL with AI**, **Fix SQL with AI** and **Optimize SQL with AI** open the window with the selected SQL, or the document, and a request already written that you can edit. **Fix** adds the SQLSTATE and the main message of the last error of the tab, shown in the request before sending; the DETAIL of the error, which can quote row values, is never sent. Nothing is sent until you press **Generate**, and the SQL is only inserted into the editor. With Ollama, PGMS reads the model's maximum context and asks for a window that fits the prompt, trimming the structure (and saying so) when it does not fit. + ## Large results A grid result larger than **Query Options ▸ Results ▸ Grid ▸ Rows per result page** (100,000 by default) is shown in pages, with a bar below the grid. Rows after the first page are kept in a temporary file until the next execution or until the tab closes. Sorting, copy and export apply to the current page; **Results to File** writes every row. @@ -85,7 +87,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 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. +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. Compression can be gzip, LZ4 or Zstandard, with their levels. **Restore** accepts parallel jobs (1–32); above 1 it cannot use a single transaction, and the window warns. **Restore only chosen items** with **Choose Items…** lists the archive contents (`pg_restore --list`) and restores only the checked items; items they depend on are not added automatically. 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. @@ -97,6 +99,46 @@ Repeated queries are grouped: one row per distinct SQL on the same server, port **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. +## Editor + +**Edit ▸ Advanced** has the SSMS editing commands: comment and uncomment lines or blocks, upper and lower case, move, sort, join and duplicate lines, delete horizontal white space, tabify/untabify, increase and decrease indent, **Insert File As Text**, **Expand Selection** (`Shift+Alt+=`: word, quotes, parentheses, statement, document), **Containing Block**, **Expand to Line**, next/previous subword and **Incremental Search**. **Format SQL** (`Ctrl+K`, `Ctrl+Q`) lays out the selection or the document; only spaces, line breaks and the case of keywords change, and text it cannot read is left as it is. **Toggle Spell Checker** checks comments and strings with the Windows spell checker, in the language of Windows or in English, per tab. + +The information bar under the editor has the zoom (20–400 %, `Ctrl`+wheel), line and column (click for Go To Line), tabs or spaces, line ending and encoding. **Set End of Line Sequence**, **Set Indentation** and **Set Encoding** convert the whole document in one Undo step; only Unicode encodings are offered. + +**IntelliSense ▸ Parameter Info** (`Ctrl+Shift+Space`, also when typing `(` or `,`) shows the arguments of a function, and **Quick Info** (`Ctrl+K`, `Ctrl+I`, or the mouse) describes a table, column or function. **Bookmarks** (`Ctrl+K`, `Ctrl+K` to toggle, `Ctrl+K`, `Ctrl+N`/`Ctrl+P` to move) belong to each tab. **Outlining** folds statements of more than one line and block comments. + +**Template Explorer** (`Ctrl+Alt+T`) lists PostgreSQL templates and your own `.sql` files from the `Templates` folder of the PGMS state directory; **Specify Values for Template Parameters** (`Ctrl+Shift+M`) fills `` placeholders. **Insert Snippet** (`Ctrl+K`, `Ctrl+X`) and **Surround With** (`Ctrl+K`, `Ctrl+S`) insert snippets; `Tab` moves between fields. + +When the server reports the position of an error, the editor underlines it, the information bar counts it and **Go To Next/Previous Issue in File** (`Alt+PgDn`/`Alt+PgUp`) reaches it; editing clears it. **Find in Files** and **Replace in Files** (`Ctrl+Shift+H`) search a folder (`*.sql` by default), the open documents or the current one, and list the matches in **Find Results**; Replace All changes open tabs in the editor and other files on disk, with the same encoding, after a confirmation. **Edit ▸ Show Clipboard History** (`Ctrl+Shift+V`) keeps the last 20 copies in memory, and **Go To Last Edit Location** (`Ctrl+Shift+Backspace`) returns to the last change, even in another tab. + +A line longer than 10,000 characters is shown cut, with a marker that opens the whole line; the file and the SQL that runs are not changed. + +## Tabs, windows and settings + +**File ▸ New ▸ Query with Current Connection** (`Ctrl+N`) uses the connection of the active tab or of Object Explorer; **Database Engine Query** asks for one. **Open ▸ File…** connects the new tab the same way, and **File Disconnected…** opens without connecting. **File ▸ Recent Files**, **Save All**, **Window ▸ Close All Tabs** and **Restore Closed Tab** work as in SSMS; a closed query without a file comes back with its text, disconnected. **Window** also has **Next/Previous Pane** (`F6`/`Shift+F6`), **Show Results Pane** (`Ctrl+R`), **Split Tab**, **Dock**, **Auto Hide**, **Move To New Window**, up to ten saved window layouts and **Auto Hide All**; **View ▸ Full Screen** is `Shift+Alt+Enter`. + +The menu shares the title bar with the window buttons and **Search** (`Ctrl+Q`), which finds menu commands and Tools ▸ Options pages and settings; `Enter` runs or opens the result. **View ▸ Properties Window** (`F4`) shows the session of the active query (server, login, database, backend PID, version, SSL mode, last execution). **View ▸ Error List** (`Ctrl+\`, `E`) has the error of the last execution of each open tab; double-click goes to it. **View ▸ Output** (`Ctrl+Alt+O`) keeps the messages and executions of the session (5,000 lines in memory). **File ▸ Page Setup…** and **Print…** print the SQL of the active tab. + +**Tools ▸ Options** includes **Fonts and Colors** (editor, Grid Results and Text Results), **Keyboard** (one shortcut per menu command, which wins over the built-in one), **Query Shortcuts** (`Alt+F1`, `Ctrl+1` to `Ctrl+0`, empty by default; the text runs in the session of the active tab, followed by the selection), Object Explorer **Scripting**, **Designers** and **Connection Dialog**. **Tools ▸ Theme** chooses Light, Dark or the Windows setting; in Dark, diagrams and graphical plans stay light. **Tools ▸ Editor Appearance** sets the editor colors separately, with two extra-contrast modes, and **View ▸ Presenter Mode** (`Ctrl+Shift+F5`) enlarges the editor, results and window text for the session. **Tools ▸ Import and Export Settings…** saves, loads or resets the Options in a `.pgmssettings` file (without window position, recent files, connections, passwords or AI settings). **Tools ▸ External Tools…** adds programs to the Tools menu, run only when you choose them, and **Tools ▸ Customize…** shows or hides the toolbars. + +## Results and running queries + +Results, Messages, the plan and the session tabs are above the results. **Save Results As…** in the grid menu opens **Save Grid Results**: a `.csv` file separated by commas or a `.txt` file separated by tabs, always with headers, for the current page. **Export Options…** opens the CSV/JSON export band. Several result sets of one execution are shown in tabs. Values of extension types, such as PostGIS `geometry`, are shown as the text the server sends (hexadecimal EWKB); a type created while PGMS is open is named `unknown type (oid N)` until you reconnect. + +**Query ▸ Include Live Query Statistics** adds a tab that, once a second and over a separate connection, shows the state, elapsed time, waits and blocking PIDs of the running query, and the progress reported by `pg_stat_progress_*` for CREATE INDEX, VACUUM, ANALYZE, CLUSTER and COPY. PostgreSQL has no per-operator counters while a query runs, so there is no live plan. + +## Object Explorer additions + +**View ▸ Object Explorer Details** (`F7`) lists the contents of the selected node (name, type, schema, owner) with a search box; double-click or `Enter` opens an item and `Backspace` goes up. Keys, constraints and triggers have **Modify** (the Table Designer, or a DROP and CREATE script for a trigger), **Rename** (`F2`) and **Delete** with the exact command, never CASCADE; the folders have **New Foreign Key…**, **New Constraint…** and **New Trigger…**, and triggers **Enable** and **Disable**. **New Function…** and **New Stored Procedure…** open templates in a connected query. Each database has an **Extensions** folder with **New Extension…** (schema, version, CASCADE; OK or Script), **Update Extension…** and **Delete**. Tables, materialized views and databases have **Maintenance ▸ Vacuum…**, **Analyze…** and **Refresh Materialized View…**, which open the command in a query tab instead of running it. **Composite Types**, **Foreign Servers** and **Replication** (local publications and subscriptions) are read only; option values and `subconninfo` are not shown. The name and owner filters also have **Does not equal**. **Role Memberships** lists effective memberships, direct and inherited, with the shortest path. + +## Schema Compare + +**Tools ▸ Schema Compare** compares a source and a target database, chosen in the Connect window, in a read-only transaction. Differences are grouped by type, schema and action (Add, Change, Delete), with the two definitions side by side and the different lines marked. **Generate Script** writes the changes into a query tab connected to the target: `ALTER TYPE … ADD VALUE` first, the rest inside `BEGIN … COMMIT`, tables column by column, and possible data loss marked. PGMS never runs it; review it before executing. There is no Apply, no options page and no `.dacpac` or `.scmp` file. + +## When PGMS hits an error + +An error that PGMS did not handle is written to a daily log in `%LOCALAPPDATA%\PGMS\logs` (or `logs` under `PGMS_STATE_DIRECTORY`), kept for 30 days. The log has the time, the PGMS, Windows and .NET versions and the exception with its stack; password values written as `key=value` are masked. Nothing is sent over the network. An error in the interface also opens **PGMS - Unexpected Error** with **Copy Details**, **Open Log Folder**, **Report Issue**, **Continue** (the default; your open queries keep their text) and **Close PGMS** (closes normally, still offering to save files). An error in a background thread ends PGMS after logging it. When reporting, read the log first: an error message can quote what the server sent. + ## 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/en/validation.md b/docs/en/validation.md index 0d8ff10..8ad8e0f 100644 --- a/docs/en/validation.md +++ b/docs/en/validation.md @@ -2,11 +2,11 @@ English | [Português (Brasil)](../pt-BR/validation.md) -Current pre-release: v0.1.0-alpha.6, build label M1062 (adds indexes, descriptions and Export for AI in diagrams, Query History, Script as, warnings and missing index suggestions in plans, and table selection for AI-assisted SQL on large databases to the M1053 source of alpha.5; built by the release workflow on GitHub Actions with a build provenance attestation). Milestone labels are internal identifiers, not guarantees that a local rebuild has the same binary identity. The initial public source import used M1002. The private operational history and raw acceptance evidence are intentionally not included. +Current pre-release: v0.1.0-alpha.7, build label M1117 (adds the AI conversation and Explain/Fix/Optimize, the dark theme and appearance settings, logging of unexpected errors, many editor, window and Object Explorer commands, Schema Compare, Live Query Statistics and parallel/partial restore to the M1062 source of alpha.6; built by the release workflow on GitHub Actions with a build provenance attestation; see the [release notes](release-notes.md)). Milestone labels are internal identifiers, not guarantees that a local rebuild has the same binary identity. The initial public source import used M1002. The private operational history and raw acceptance evidence are intentionally not included. The imported implementation previously passed 5,187 automated checks (2,115 PostgreSQL integration and 3,072 WPF), plus package opening, installed profile preservation and three-draft recovery through rollback/restart. Those are historical observations, not newly executed tests for every source revision. Reproduce current behavior with the public build and test scripts; report your actual environment and results. The clean-import checks for the initial public revision are recorded below after execution. -Known limits: Windows x64; PostgreSQL 16–18 with same-major tools, complete regression on 17.11 and focused suites on 16.15/18.6; 15 and earlier unsupported. No full SSMS parity. Huge SQL lines may pause rendering. Results and recovery have bounded retention. Cancellation is not proof of rollback. DPAPI is user-bound. The package is unsigned, without MSI/automatic update; SmartScreen is not certified. DPI100/125/150/175% were exercised internally;200% was accepted without execution. Automatic reappearance after disconnect, cross-user DPAPI portability and a new clean-Windows test of this import are not certified. External clipboard/keyboard/screen-reader observations are historical and not reproduced by ordinary WPF tests. +Known limits: Windows x64; PostgreSQL 16–18 with same-major tools, complete regression on 17.11 and focused suites on 16.15/18.6; 15 and earlier unsupported. No full SSMS parity. SQL lines over 10,000 characters are displayed cut, with a marker to open them. Results and recovery have bounded retention. Cancellation is not proof of rollback. DPAPI is user-bound. The package is unsigned, without MSI/automatic update; SmartScreen is not certified. DPI100/125/150/175% were exercised internally;200% was accepted without execution. Automatic reappearance after disconnect, cross-user DPAPI portability and a new clean-Windows test of this import are not certified. External clipboard/keyboard/screen-reader observations are historical and not reproduced by ordinary WPF tests. ```powershell ./scripts/Build.ps1 -Configuration Release @@ -38,6 +38,10 @@ A complete run passed 2,236 integration + 3,315 WPF = 5,551 checks on PostgreSQL The window was compared, during development, with the Query Store of SSMS 22.11 on an identical synthetic workload against SQL Server LocalDB and the disposable PostgreSQL cluster. Both listed the same statements with matching counts. Differences found then: one window instead of seven Query Store reports; server-wide cumulative counters instead of per-database time intervals; no chart, plan, logical reads or header sorting; full records exposed as row names to screen readers. Header sorting, I/O and block metrics, generic plans, the top-N chart, time windows and short row names were added afterward. Remaining differences: one window instead of separate reports, windows computed by subtracting samples rather than stored intervals, and no per-statement CPU time, which PostgreSQL does not record. Physical DPI and screen-reader observations of this window are not newly certified. +## v0.1.0-alpha.7 / M1117 — 2026-11-17 + +A complete run passed 3,135 integration + 5,440 WPF = 8,575 checks on PostgreSQL 17.11, on a disposable loopback cluster with `pg_stat_statements` preloaded, in the first attempt. The locally built self-contained package passed manifest verification (526 files), guide and archive checks, the launch check and a current-user graphical installation and removal; the global installation was not run. The launch check now cancels the Connect dialog that PGMS opens at startup before closing the main window: it had been failing intermittently because the dialog could open before the close request. In the development repository, the features added since alpha.6 were validated by focused suites as they were built; the complete regression ran on PostgreSQL 16.15 and 18.6 only on an earlier source (M1066). The AI conversation and Explain/Fix/Optimize ran against a local fake provider, not a real one. PostGIS was not installed: a stand-in `geometry` type was used. Unexpected-error handling was exercised through the same methods the global handlers call; the handlers were not triggered by a real crash. New screens were exercised by automated tests and, for the dark theme and the title bar, by hand with keyboard and mouse on one monitor at 100 %; a clean-Windows VM and screen readers were not used. + ## v0.1.0-alpha.6 / M1062 — 2026-11-13 A complete run passed 3,018 integration + 4,586 WPF = 7,604 checks on PostgreSQL 17.11, on a disposable loopback cluster with `pg_stat_statements` preloaded, in the first attempt. The complete regression was not repeated on PostgreSQL 16 or 18. New screens were exercised by automated tests, not by hand with mouse and keyboard. Generate SQL with AI was not run against a real provider for the large-database table selection, and no real AI agent read the Markdown of Export for AI. diff --git a/docs/pt-BR/distribution.md b/docs/pt-BR/distribution.md index 42563a8..86053ca 100644 --- a/docs/pt-BR/distribution.md +++ b/docs/pt-BR/distribution.md @@ -1,4 +1,4 @@ -# PGMS v0.1.0-alpha.6 — distribuição portátil (M1062) +# PGMS v0.1.0-alpha.7 — distribuição portátil (M1117) [English]: READ-ME.md no pacote, ou docs/en/distribution.md no repositório. Português (Brasil). @@ -10,6 +10,8 @@ Cada aba tem sessão própria. F5 executa seleção/documento. Ctrl+C copia cél Estado padrão em %LOCALAPPDATA%/PGMS; PGMS_STATE_DIRECTORY permite pasta separada de avaliação. Credenciais salvas, recuperação e diários usam DPAPI do usuário Windows atual. Feche antes de copiar estado; preserve SQL separadamente e revise abas recuperadas com Save As. Estado/credenciais não são universalmente portáteis entre usuários/máquinas ou builds antigos. +Erros inesperados são gravados num log diário em %LOCALAPPDATA%/PGMS/logs (logs sob PGMS_STATE_DIRECTORY), guardado por 30 dias, com valores de senha em texto chave=valor mascarados; nada é enviado pela rede. A janela de erro oferece Copy Details, Open Log Folder, Report Issue, Continue e Close PGMS. Para relatar um problema, use os modelos de issue do repositório abaixo e anexe o log depois de lê-lo: uma mensagem de erro pode citar o que o servidor enviou. + Confira integridade com ./Verify-Package.ps1 -PackagePath . no PowerShell 7; hashes detectam diferenças, não autoria. Instalação gerenciada opcional também exige PowerShell 7. No pacote extraído: ./Install-Pgms.ps1 -PackagePath .; consulte ./Get-PgmsInstallation.ps1; abra ./Start-Pgms.ps1; use ./Set-PgmsActiveVersion.ps1 -Milestone no rollback e ./Uninstall-Pgms.ps1 -Milestone na remoção. Use -InstallRoot para local gerenciado isolado. Scripts preservam estado do usuário e recusam raiz não gerenciada/não vazia e caminhos inseguros; feche instâncias primeiro. Fonte, guias bilíngues e relatos: https://github.com/leoars/PostgresManagementStudio . Trabalho próprio Apache-2.0; licenças de terceiros e condições de marca são separadas. PGMS é independente, sem paridade integral SSMS ou endosso. diff --git a/docs/pt-BR/getting-started.md b/docs/pt-BR/getting-started.md index bf199a6..d866ac5 100644 --- a/docs/pt-BR/getting-started.md +++ b/docs/pt-BR/getting-started.md @@ -2,7 +2,7 @@ [English](../en/getting-started.md) | Português (Brasil) -[Baixar v0.1.0-alpha.6](https://github.com/leoars/PostgresManagementStudio/releases/tag/v0.1.0-alpha.6): [instalador gráfico](graphical-installer.md), ZIP portátil ou instalador PowerShell 7. O instalador gráfico oferece modos por usuário e para todos, dispensando PowerShell. Veja [notas da versão](release-notes.md). +[Baixar v0.1.0-alpha.7](https://github.com/leoars/PostgresManagementStudio/releases/tag/v0.1.0-alpha.7): [instalador gráfico](graphical-installer.md), ZIP portátil ou instalador PowerShell 7. O instalador gráfico oferece modos por usuário e para todos, dispensando PowerShell. Veja [notas da versão](release-notes.md). ### Aviso do SmartScreen do Windows @@ -15,7 +15,7 @@ Get-FileHash .\PGMS-* -Algorithm SHA256 Compare os hashes com o `SHA256SUMS.txt` da release. A partir da v0.1.0-alpha.2 os assets são compilados pelo [workflow de release](../../.github/workflows/release.yml) no GitHub Actions e trazem atestado de proveniência de build, então você também pode confirmar que o ZIP ou o instalador saiu desse workflow e deste repositório (exige o [GitHub CLI](https://cli.github.com/); veja [desenvolvimento](development.md)): ```powershell -gh attestation verify .\PGMS-0.1.0-alpha.6-Setup-x64.exe --repo leoars/PostgresManagementStudio +gh attestation verify .\PGMS-0.1.0-alpha.7-Setup-x64.exe --repo leoars/PostgresManagementStudio ``` A v0.1.0-alpha.1 foi compilada na máquina do mantenedor e tem apenas checksums. A assinatura de código pelo programa open source da SignPath Foundation está planejada. diff --git a/docs/pt-BR/graphical-installer.md b/docs/pt-BR/graphical-installer.md index 0df8d38..ece7f23 100644 --- a/docs/pt-BR/graphical-installer.md +++ b/docs/pt-BR/graphical-installer.md @@ -2,7 +2,7 @@ [English](../en/graphical-installer.md) | Português (Brasil) -Baixe `PGMS-0.1.0-alpha.6-Setup-x64.exe` na [release alpha.6](https://github.com/leoars/PostgresManagementStudio/releases/tag/v0.1.0-alpha.6) e confira contra o `SHA256SUMS.txt` (e, opcionalmente, com `gh attestation verify`). Desde a v0.1.0-alpha.2 o instalador é compilado pelo workflow de release a partir do mesmo payload do ZIP portátil daquela release; na v0.1.0-alpha.1 ele foi adicionado depois, embrulhando o payload M1008 existente. O instalador dispensa PowerShell e runtime .NET instalado separadamente. +Baixe `PGMS-0.1.0-alpha.7-Setup-x64.exe` na [release alpha.7](https://github.com/leoars/PostgresManagementStudio/releases/tag/v0.1.0-alpha.7) e confira contra o `SHA256SUMS.txt` (e, opcionalmente, com `gh attestation verify`). Desde a v0.1.0-alpha.2 o instalador é compilado pelo workflow de release a partir do mesmo payload do ZIP portátil daquela release; na v0.1.0-alpha.1 ele foi adicionado depois, embrulhando o payload M1008 existente. O instalador dispensa PowerShell e runtime .NET instalado separadamente. ## Opções de instalação diff --git a/docs/pt-BR/release-notes.md b/docs/pt-BR/release-notes.md index b9962bf..5fe50be 100644 --- a/docs/pt-BR/release-notes.md +++ b/docs/pt-BR/release-notes.md @@ -1,57 +1,104 @@ -# v0.1.0-alpha.6 — Windows x64 +# v0.1.0-alpha.7 — Windows x64 [English](../en/release-notes.md) | Português (Brasil) -Sexta pré-release pública do PGMS. É uma alpha para avaliação com dados sintéticos ou descartáveis. Rótulo de build: M1062. Os binários são gerados e atestados pelo mesmo [workflow de release](../../.github/workflows/release.yml) das versões anteriores. O trabalho próprio está sob Apache-2.0, com créditos no `NOTICE`; as versões até a alpha.4 continuam sob MIT. - -## O que mudou desde a v0.1.0-alpha.5 - -- **Í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. -- **Script as no Object Explorer.** **Script … as** (CREATE, DROP e os verbos que se aplicam, para uma janela de consulta, um arquivo ou a área de transferência) em bancos, schemas, tabelas, views, sequences, funções, procedures, enums, domínios, índices, chaves, constraints, triggers e roles; pastas **Keys**, **Constraints** e **Triggers** sob a tabela; **Rebuild** de índice e **Rebuild All**; **Take Offline** e **Bring Online** de banco (`ALLOW_CONNECTIONS`), com o banco offline marcado na árvore. -- **Avisos nos planos de execução gráficos.** No plano real, um operador cujo filtro descartou muitas linhas mostra um triângulo amarelo e uma seção **Warnings** com as contagens de Filter, Join Filter e Index Recheck. Os limiares (10 vezes as linhas retornadas e pelo menos 1.000 linhas por padrão) ficam em Query Options e Tools ▸ Options. É uma regra do PGMS; o PostgreSQL não emite avisos no plano. -- **Sugestão de índice a partir do plano.** Para uma varredura com aviso e filtros simples, uma linha verde no cabeçalho do plano e **Missing Index Details…** abrem um script `CREATE INDEX` comentado, conferido no catálogo. Nada é executado. É uma heurística sem estimativa de seletividade; não cobre junções, `OR`, expressões nem `INCLUDE`. -- **Gerar SQL com IA em bancos grandes.** Quando a estrutura não cabe no limite do contexto (agora configurável, 200.000 caracteres por padrão), o provedor primeiro escolhe as tabelas relevantes pelos nomes, e as tabelas enviadas seguem essa escolha, as chaves estrangeiras e as palavras em comum com o pedido. **View Sent Context…** mostra as duas chamadas. +Sétima pré-release pública do PGMS. É uma alpha para avaliação com dados sintéticos ou descartáveis. Rótulo de build: M1117. Os binários são gerados e atestados pelo mesmo [workflow de release](../../.github/workflows/release.yml) das versões anteriores. O trabalho próprio está sob Apache-2.0, com créditos no `NOTICE`; as versões até a alpha.4 continuam sob MIT. + +## Destaques + +- **Assistente de IA: conversa e Explain/Fix/Optimize.** A janela **Generate SQL with AI** agora aceita pedidos de seguimento: os cinco últimos pedidos da conversa e o SQL escrito para eles vão junto com o próximo, e **New Conversation** recomeça. **Query ▸ Explain SQL with AI**, **Fix SQL with AI** e **Optimize SQL with AI** abrem a janela com o SQL selecionado (ou o documento) e um pedido já escrito; o **Fix** acrescenta o SQLSTATE e a mensagem principal do último erro da aba, mas nunca o DETAIL, que pode citar valores de linhas. Nada é enviado antes de você clicar em **Generate**, e nada é executado: o SQL só vai para o editor. A estrutura do banco vai para o provedor que você configurar (Anthropic, OpenAI ou um Ollama local); dados das tabelas nunca são lidos nem enviados. Com o Ollama, o PGMS agora pede uma janela de contexto que caiba o prompt e corta a estrutura no máximo do modelo, em vez de deixar o servidor cortar o prompt em silêncio. +- **Configure Server TLS** não mudou: um assistente que instala um certificado e liga o TLS, restaurando as configurações anteriores se falhar. Exige conexão de superusuário a um servidor rodando no Windows. +- **Erros inesperados ficam registrados.** Um erro que o PGMS não tratou não fecha mais o programa em silêncio. Ele vai para um log diário em `%LOCALAPPDATA%\PGMS\logs` (guardado por 30 dias; valores de senha em texto `chave=valor` são mascarados) e uma janela mostra o erro com **Copy Details**, **Open Log Folder**, **Report Issue**, **Continue** (o padrão) e **Close PGMS**. Nada é enviado pela rede. +- **Tema escuro.** **Tools ▸ Theme** oferece Light, Dark e Use system setting. No tema escuro, a moldura, os menus, os controles padrão, as grades de resultados, a árvore e a janela Properties acompanham; diagramas e planos gráficos continuam claros, como papel. **Tools ▸ Editor Appearance** define as cores do editor separadamente (inclusive dois modos de contraste extra) e **View ▸ Presenter Mode** (`Ctrl+Shift+F5`) aumenta o texto do editor, dos resultados e da janela para apresentações. + +## O que mudou desde a v0.1.0-alpha.6 + +**Editor** +- **Edit ▸ Advanced:** comentar e descomentar linhas e blocos, maiúsculas/minúsculas, mover, ordenar, juntar e duplicar linhas, apagar espaços horizontais, tabify/untabify, indentação, Insert File As Text, Expand Selection, Containing Block, Expand to Line, próxima/anterior subpalavra, Incremental Search, **Format SQL** (`Ctrl+K`, `Ctrl+Q`; só espaços, quebras de linha e caixa das palavras-chave mudam) e **Toggle Spell Checker** (comentários e cadeias, pelo verificador ortográfico do Windows). +- Uma barra de informações do editor com zoom (20–400 %, `Ctrl`+roda), linha e coluna (abre Go To Line), tabulações/espaços, fim de linha (CRLF/LF/CR) e codificação, com **Set End of Line Sequence**, **Set Indentation** e **Set Encoding** (codificações Unicode). +- **IntelliSense:** Parameter Info (`Ctrl+Shift+Space`) e Quick Info (`Ctrl+K`, `Ctrl+I`, ou passando o mouse). +- **Marcadores** por aba (`Ctrl+K`, `Ctrl+K` e os acordes do SSMS) e **Outlining** por instrução e comentário de bloco. +- **Modelos e trechos:** Template Explorer (`Ctrl+Alt+T`) com modelos PostgreSQL e seus próprios arquivos `.sql`, Specify Values for Template Parameters (`Ctrl+Shift+M`), Insert Snippet e Surround With. +- A posição do erro informada pelo servidor fica sublinhada no editor, contada na barra de informações e alcançada por **Go To Next/Previous Issue in File** (`Alt+PgDn`/`Alt+PgUp`). +- **Find in Files** e **Replace in Files** (`Ctrl+Shift+H`) numa pasta, nos documentos abertos ou no atual, com o painel Find Results. +- Histórico da área de transferência (`Ctrl+Shift+V`) e Go To Last Edit Location (`Ctrl+Shift+Backspace`). +- Linhas com mais de 10.000 caracteres aparecem cortadas, com um marcador que abre a linha inteira, e o editor não trava mais nelas. + +**Arquivos, abas e janelas** +- **File ▸ New ▸ Query with Current Connection** e **Database Engine Query**; **Open ▸ File** conecta a aba nova com a conexão atual, e **File Disconnected…** abre sem conectar; **Disconnect All Queries**. +- Save All, Recent Files (quantidade em Tools ▸ Options), Close All Tabs e **Restore Closed Tab**, também para consultas sem arquivo. +- **Window:** próximo/anterior painel (`F6`), Show Results Pane (`Ctrl+R`), Split Tab, Dock, Auto Hide, Move To New Window, layouts de janela salvos (até dez) e **View ▸ Full Screen**. +- O menu agora divide a barra de título com os botões da janela e uma caixa **Search** (`Ctrl+Q`) que encontra comandos do menu e páginas e configurações de Tools ▸ Options. +- **View ▸ Properties Window** (`F4`), **Error List** (`Ctrl+\`, `E`) com o último erro de cada aba e **Output** (`Ctrl+Alt+O`) com as mensagens e execuções da sessão. +- **File ▸ Page Setup…** e **Print…** para o SQL da aba ativa. +- Textos de conexão mais próximos do SSMS: o nó do servidor mostra `host:porta (PostgreSQL versão - login)` e a barra de estado da consulta mostra servidor, login com o PID do backend, banco, tempo e linhas. + +**Consultas e resultados** +- As abas Results/Messages ficam acima dos resultados, e **Save Results As…** no menu da grade abre **Save Grid Results** (`.csv` separado por vírgula ou `.txt` separado por tabulação, com cabeçalhos). A faixa de opções de exportação continua em **Export Options…**. +- **Query ▸ Include Live Query Statistics** mostra, uma vez por segundo e por uma conexão separada, o estado, o tempo decorrido, as esperas, as sessões que bloqueiam e o progresso de `pg_stat_progress_*` (CREATE INDEX, VACUUM, ANALYZE, CLUSTER, COPY) da consulta em execução. O PostgreSQL não tem contadores por operador, então não há plano ao vivo. +- **Query Shortcuts** (`Alt+F1`, `Ctrl+1` a `Ctrl+0`) em Tools ▸ Options, vazios por padrão. +- Tipos de extensões, como o `geometry` do PostGIS, aparecem como o texto que o servidor envia (EWKB em hexadecimal), sem erro. + +**Object Explorer e administração** +- **Object Explorer Details** (`F7`), o conteúdo do nó selecionado com busca. +- **Keys**, **Constraints** e **Triggers**: Modify, Rename, Delete com o comando exato (sem CASCADE), New Foreign Key… e New Constraint…; Enable/Disable de triggers; New Function…, New Stored Procedure… e New Trigger… a partir de modelos. +- Uma pasta **Extensions** em cada banco com New Extension…, Update Extension… e Delete. +- Um submenu **Maintenance** com Vacuum…, Analyze… e Refresh Materialized View…; o comando abre numa aba de consulta, sem ser executado direto. +- Composite Types, Foreign Servers e Replication (publicações e assinaturas locais), só leitura. +- O filtro ganha **Does not equal**. +- **Role Memberships** lista as associações efetivas, diretas e herdadas, com o caminho. +- **Tools ▸ Schema Compare** compara dois bancos (só leitura) e escreve um script de mudanças numa aba de consulta conectada ao destino. Nunca executa o script. +- **Back Up:** compressão LZ4 e Zstandard. **Restore:** jobs paralelos (1–32) e **Choose Items…** para restaurar só alguns itens de um arquivo. +- **Connect:** certificado de cliente, chave de cliente e senha da chave (guardada com DPAPI); backup e restore recebem a senha da chave por um arquivo de serviço temporário e privado. + +**Configurações** +- Tools ▸ Options: **Fonts and Colors** (Text Editor, Grid Results, Text Results), **Keyboard** (um atalho por comando do menu), opções de **Scripting** do Object Explorer, **Designers** e **Connection Dialog**. +- **Tools ▸ Import and Export Settings…** (um arquivo `.pgmssettings` com as opções), **External Tools…** e **Customize…** para as barras de ferramentas. +- **Help ▸ View Help** (`Ctrl+F1`) abre o guia do pacote; **Release Notes** abre a lista de releases. + +**PostgreSQL 16:** quatro defeitos achados por uma regressão completa no PostgreSQL 16.15 foram corrigidos, entre eles o `MAINTAIN` oferecido em servidores anteriores ao 17. ## Downloads -Em [esta release](https://github.com/leoars/PostgresManagementStudio/releases/tag/v0.1.0-alpha.6): +Em [esta release](https://github.com/leoars/PostgresManagementStudio/releases/tag/v0.1.0-alpha.7): | Arquivo | Finalidade | | --- | --- | -| `PGMS-0.1.0-alpha.6-Setup-x64.exe` | Instalador gráfico (inglês/pt-BR). Usuário atual sem administrador, ou todos os usuários com elevação. Não exige PowerShell nem runtime .NET separado. | -| `PGMS-0.1.0-alpha.6-win-x64.zip` | Aplicativo portátil com runtime .NET/WPF. Extraia a pasta inteira e execute PGMS.exe. Inclui os scripts PowerShell 7 gerenciados. | -| `SHA256SUMS.txt` | SHA256 de cada arquivo desta release. Hashes conferem correspondência, não autoria. | +| `PGMS-0.1.0-alpha.7-Setup-x64.exe` | Instalador gráfico (inglês/pt-BR). Usuário atual sem administrador, ou todos os usuários com elevação. Não exige PowerShell nem runtime .NET separado. | +| `PGMS-0.1.0-alpha.7-win-x64.zip` | Aplicativo portátil com runtime .NET/WPF. Extraia a pasta inteira e execute PGMS.exe. Inclui os scripts gerenciados de PowerShell 7. | +| `SHA256SUMS.txt` | SHA256 de cada asset desta release. Hashes conferem correspondência, não autoria. | | `package-manifest.json` | Manifesto SHA256 de cada arquivo dentro do ZIP, conferido por `Verify-Package.ps1`. | | `RELEASE-NOTES.md`, `RELEASE-NOTES.pt-BR.md` | Estas notas. | ## Confira o que você baixou -Os binários não têm assinatura de código, então o Windows SmartScreen pode avisar na primeira execução. Antes de escolher **Executar assim mesmo**, confira o checksum e a origem: +Os binários não têm assinatura de código, então o Windows SmartScreen pode avisar na primeira execução. Antes de escolher **Executar assim mesmo**, confira o checksum e a procedência: ```powershell Get-FileHash .\PGMS-* -Algorithm SHA256 -gh attestation verify .\PGMS-0.1.0-alpha.6-Setup-x64.exe --repo leoars/PostgresManagementStudio +gh attestation verify .\PGMS-0.1.0-alpha.7-Setup-x64.exe --repo leoars/PostgresManagementStudio ``` -Compare os hashes com `SHA256SUMS.txt`. O segundo comando exige o [GitHub CLI](https://cli.github.com/) e confirma que o arquivo foi gerado pelo workflow de release deste repositório no commit da tag; rode também para o ZIP. A assinatura de código pelo programa open source da SignPath Foundation está planejada, sem data prometida. +Compare os hashes com `SHA256SUMS.txt`. O segundo comando precisa do [GitHub CLI](https://cli.github.com/) e confirma que o arquivo foi produzido pelo workflow de release deste repositório no commit da tag; rode-o também para o ZIP. A assinatura de código pelo programa de código aberto da SignPath Foundation está planejada; não há data prometida. + +## Relatar um problema + +Quando o PGMS mostrar a janela de erro inesperado, escolha **Report Issue** e anexe o log de **Open Log Folder** (`%LOCALAPPDATA%\PGMS\logs`). Diga o que você estava fazendo, a versão do PostgreSQL e se o erro se repete. Leia o log antes de anexar: uma mensagem de erro pode citar o que o servidor enviou. Use os [modelos de issue](https://github.com/leoars/PostgresManagementStudio/issues/new/choose). ## Escopo -Editor SQL com IntelliSense e sessões independentes, Object Explorer, Results em páginas e Results to Text/File, exportação CSV/JSON, diagramas de banco e designers, planos gráficos, administração PostgreSQL revisada, identidade/privilégios, Activity Monitor, estatísticas de consultas e backup/restore lógico. PostgreSQL 16 a 18 e ferramentas cliente da mesma versão principal são necessários para operações no banco e backup/restore; servidor e ferramentas não acompanham o pacote. O SSMS não é exigido nem distribuído. +Editor SQL com IntelliSense e sessões independentes, Object Explorer, Results paginados e Results to Text/File, exportação CSV/JSON, diagramas de banco e designers, planos gráficos, administração PostgreSQL revisada, identity/privilégios, Activity Monitor, estatísticas de consultas, Schema Compare e backup/restore lógico. PostgreSQL 16 a 18 e ferramentas cliente da mesma versão principal são necessários para operações de banco e backup/restore; servidor e ferramentas não acompanham. O SSMS não é necessário nem distribuído. ## Validação -Comportamento do aplicativo: a fonte M1062 passou na regressão completa deste repositório no PostgreSQL 17.11 (**3.018 de integração + 4.586 WPF = 7.604 verificações**), num cluster isolado em loopback; o serviço PostgreSQL do computador não é usado. Os recursos acrescentados desde a alpha.5 não passaram por regressão completa no PostgreSQL 16 ou 18. +Comportamento do aplicativo: a fonte M1117 passou na regressão completa deste repositório no PostgreSQL 17.11 (ver [validação](validation.md#v010-alpha7--m1117--17112026)) num cluster isolado em loopback; o serviço PostgreSQL do host não é usado. A maior parte das funções acrescentadas desde a alpha.6 foi validada por recortes automatizados durante a construção; a última regressão completa no PostgreSQL 16.15 e 18.6 foi sobre uma fonte anterior (M1066). As ações novas de IA e a conversa foram testadas só com um provedor falso local, não com um real. O PostGIS não foi instalado no cluster de testes: foi usado um tipo `geometry` substituto. -Instalação para todos os usuários (com elevação), instalação em VM Windows limpa e observações físicas de DPI, teclado e leitor de tela nas telas novas não são certificadas de novo por esta release. As telas novas foram exercitadas por testes automáticos, não à mão com mouse e teclado nesta fonte. +Instalação numa VM Windows limpa, outro usuário Windows sem privilégios e observações físicas de DPI, teclado e leitor de tela das telas novas não são certificadas por esta release. ## Limites conhecidos -Somente Windows x64. Executável e instalador sem assinatura; o SmartScreen avisa. Sem MSI, atualização automática ou garantia de suporte em produção. Não se declara paridade completa com o SSMS. Resultados: ordenação, cópia e exportação valem para a página atual; as linhas depois da primeira página ficam num arquivo temporário, sem criptografia, até a próxima execução ou até a aba fechar; Results to Text mantém os limites de 10.000 linhas e 250.000 células, e Results to File não tem nenhum dos dois. O IntelliSense não tem Parameter Info nem Quick Info, e não conhece colunas de CTE, tabelas temporárias nem o `SET search_path` da sessão. Query Designer: `UNION` e `WITH` abrem apenas no painel SQL; Update, Delete e Insert Values aceitam uma tabela. Find Missing Foreign Keys é heurística: um nome igual é indício, não prova. +Somente Windows x64. Executável e instalador sem assinatura; o SmartScreen avisa. Sem MSI, atualização automática ou garantia de suporte em produção. Não há alegação de paridade integral com o SSMS. Tema escuro: diagramas e planos continuam claros; não há temas coloridos. Um cursor só (sem cursores múltiplos). Vários conjuntos de resultados aparecem em abas, não empilhados. Live Query Statistics não tem plano ao vivo. Valores do PostGIS aparecem como texto hexadecimal, sem WKT, GeoJSON ou mapa. Resultados: ordenação, cópia e exportação valem para a página atual; as linhas depois da primeira página ficam num arquivo temporário, sem criptografia, até a próxima execução ou até fechar a aba; Results to Text mantém os limites de 10.000 linhas e 250.000 células, e Results to File não tem nenhum dos dois. O IntelliSense não conhece colunas de CTE, tabelas temporárias nem o `SET search_path` da sessão. Query Designer: `UNION` e `WITH` abrem só no painel SQL. Find Missing Foreign Keys é uma heurística: um nome parecido é pista, não prova. O log de erros mascara senhas só no formato `chave=valor`. ## Versões anteriores -v0.1.0-alpha.5 (08/11/2026, diagramas de banco, Query Designer, IntelliSense; Apache-2.0) continua disponível com seus arquivos e notas originais. v0.1.0-alpha.4 (07/11/2026, Activity Monitor em aba), v0.1.0-alpha.3 (02/11/2026, Query Statistics), v0.1.0-alpha.2 (01/11/2026, primeira release gerada por CI com atestado) e v0.1.0-alpha.1 (31/10/2026) continuam disponíveis com seus arquivos e notas originais, sob MIT. +v0.1.0-alpha.6 (13/11/2026, índices e descrições nos diagramas, Query History, Script as, avisos no plano) e v0.1.0-alpha.5 (08/11/2026, diagramas de banco, Query Designer, IntelliSense; Apache-2.0) continuam disponíveis com seus assets e notas originais. v0.1.0-alpha.4 (07/11/2026, Activity Monitor em aba), v0.1.0-alpha.3 (02/11/2026, Query Statistics), v0.1.0-alpha.2 (01/11/2026, primeira release do CI com atestado) e v0.1.0-alpha.1 (31/10/2026) continuam disponíveis com seus assets e notas originais, sob MIT. diff --git a/docs/pt-BR/user-guide.md b/docs/pt-BR/user-guide.md index 2505272..a2b2809 100644 --- a/docs/pt-BR/user-guide.md +++ b/docs/pt-BR/user-guide.md @@ -4,7 +4,7 @@ ## Conectar e consultar -Abra **New Query** (`Ctrl+N`) e **Connect**. Informe host, porta, banco, role e TLS. O padrão VerifyFull exige certificado confiável e hostname correspondente. **Test Connection** verifica a conexão sem salvar perfil. Salve o perfil explicitamente; armazenar senha é opcional e protegido por DPAPI Windows. Cada aba tem sua sessão PostgreSQL. Trocar de banco exige conexão, não o comando SQL Server `USE`. Não há tradução de T-SQL. +Abra **New Query** (`Ctrl+N`) e **Connect**. Informe host, porta, banco, role e TLS. O padrão VerifyFull exige certificado confiável e hostname correspondente. **Test Connection** verifica a conexão sem salvar perfil. Salve o perfil explicitamente; armazenar senha é opcional e protegido por DPAPI Windows. Cada aba tem sua sessão PostgreSQL. Trocar de banco exige conexão, não o comando SQL Server `USE`. Não há tradução de T-SQL. Para autenticação por certificado, informe **Client certificate**, **Client key** e, para chave criptografada, **Key password** (guardada com DPAPI quando você salva); backup e restore passam essa senha às ferramentas do PostgreSQL por um arquivo de serviço temporário e privado. Use `F5` para executar seleção ou documento e **Cancel** para solicitar cancelamento. Cancelar não comprova rollback de comando ou COMMIT no servidor. Confira o resultado antes de repetir uma escrita. Results/Messages apresentam resultados e diagnóstico. Read timeout, configurações da sessão e planos têm controles próprios. **Analyze Plan** executa SQL e exige revisão; use somente quando quiser essa execução. SQL com placeholders do tipo `$1` não executa sem valores de parâmetro: o PGMS recusa antes de enviar, mantém a sessão aberta e aponta o placeholder. `PREPARE` e corpos de funções/procedures ficam de fora da recusa, e **Estimated Plan** passa a usar um plano genérico. @@ -30,7 +30,7 @@ No Object Explorer, clique com o botão direito em **Database Diagrams**, dentro ## IntelliSense -`Ctrl+Space` ou `Ctrl+J` abrem a lista; digitar um ponto abre sozinho. `Tab` aceita e `Esc` fecha. **Query ▸ IntelliSense Enabled** (`Ctrl+B`, `Ctrl+I`) desliga na aba, e **Edit ▸ IntelliSense ▸ Refresh Local Cache** (`Ctrl+Shift+R`) relê o catálogo depois de mudanças de schema. Depois de `FROM` e palavras parecidas, busca o nome da tabela em todos os schemas de usuário; depois de `JOIN`, oferece junções inteiras a partir das chaves estrangeiras. +`Ctrl+Space` ou `Ctrl+J` abrem a lista; digitar um ponto abre sozinho. `Tab` aceita e `Esc` fecha. **Query ▸ IntelliSense Enabled** (`Ctrl+B`, `Ctrl+I`) desliga na aba, e **Edit ▸ IntelliSense ▸ Refresh Local Cache** (`Ctrl+Shift+R`) relê o catálogo depois de mudanças de schema. Depois de `FROM` e palavras parecidas, busca o nome da tabela em todos os schemas de usuário; depois de `JOIN`, oferece junções inteiras a partir das chaves estrangeiras. Parameter Info e Quick Info estão em [Editor](#editor). ## Planos de execução @@ -40,6 +40,8 @@ No Object Explorer, clique com o botão direito em **Database Diagrams**, dentro **Query ▸ Generate SQL with AI…** envia o seu pedido e a estrutura do banco (nomes, tipos, chaves, comentários; nunca dados das tabelas) ao provedor configurado em **Tools ▸ AI Assistant Settings…**: Anthropic, OpenAI ou um Ollama local, com a sua própria chave, guardada criptografada para o seu usuário do Windows. O SQL aparece para revisão e só é inserido no editor. A estrutura enviada é limitada pelo **Context limit** das configurações (200.000 caracteres por padrão). Quando o banco não cabe, o PGMS primeiro envia só os nomes das tabelas, com os comentários, e deixa o provedor escolher as relevantes; depois envia essas tabelas, as tabelas que as chaves estrangeiras delas referenciam e as tabelas cujos nomes têm palavras em comum com o pedido. As que ficam de fora são listadas pelo nome. **View Sent Context…** mostra o que foi enviado em cada chamada. A primeira chamada também consome tokens. +**Conversa.** Depois de um resultado, digite um pedido de seguimento (por exemplo, "filtre também pelo status"): os cinco últimos pedidos da conversa e o SQL escrito para eles vão junto. **New Conversation** os limpa; fechar a janela encerra a conversa. **Query ▸ Explain SQL with AI**, **Fix SQL with AI** e **Optimize SQL with AI** abrem a janela com o SQL selecionado, ou o documento, e um pedido já escrito que você pode editar. O **Fix** acrescenta o SQLSTATE e a mensagem principal do último erro da aba, visíveis no pedido antes de enviar; o DETAIL do erro, que pode citar valores de linhas, nunca é enviado. Nada é enviado antes de você clicar em **Generate**, e o SQL só é inserido no editor. Com o Ollama, o PGMS lê o contexto máximo do modelo e pede uma janela que caiba o prompt, cortando a estrutura (e avisando) quando não cabe. + ## Resultados grandes Um resultado na grade maior que **Query Options ▸ Results ▸ Grid ▸ Rows per result page** (100.000 por padrão) aparece em páginas, com uma barra abaixo da grade. As linhas depois da primeira página ficam num arquivo temporário até a próxima execução ou até a aba fechar. Ordenação, cópia e exportação valem para a página atual; **Results to File** grava todas as linhas. @@ -85,7 +87,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 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. +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. A compressão pode ser gzip, LZ4 ou Zstandard, com seus níveis. **Restore** aceita jobs paralelos (1–32); acima de 1 não pode usar transação única, e a janela avisa. **Restore only chosen items** com **Choose Items…** lista o conteúdo do arquivo (`pg_restore --list`) e restaura só os itens marcados; os itens de que eles dependem não são acrescentados automaticamente. 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. @@ -97,6 +99,46 @@ Consultas repetidas são agrupadas: uma linha por SQL distinto no mesmo servidor **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. +## Editor + +**Edit ▸ Advanced** tem os comandos de edição do SSMS: comentar e descomentar linhas ou blocos, maiúsculas e minúsculas, mover, ordenar, juntar e duplicar linhas, apagar espaços horizontais, tabify/untabify, aumentar e diminuir a indentação, **Insert File As Text**, **Expand Selection** (`Shift+Alt+=`: palavra, aspas, parênteses, instrução, documento), **Containing Block**, **Expand to Line**, próxima/anterior subpalavra e **Incremental Search**. **Format SQL** (`Ctrl+K`, `Ctrl+Q`) formata a seleção ou o documento; só mudam espaços, quebras de linha e a caixa das palavras-chave, e um texto que ele não consegue ler fica como está. **Toggle Spell Checker** verifica comentários e cadeias com o verificador ortográfico do Windows, no idioma do Windows ou em inglês, por aba. + +A barra de informações sob o editor tem o zoom (20–400 %, `Ctrl`+roda), linha e coluna (clique para Go To Line), tabulações ou espaços, fim de linha e codificação. **Set End of Line Sequence**, **Set Indentation** e **Set Encoding** convertem o documento inteiro num passo de Undo; só codificações Unicode são oferecidas. + +**IntelliSense ▸ Parameter Info** (`Ctrl+Shift+Space`, também ao digitar `(` ou `,`) mostra os argumentos de uma função, e **Quick Info** (`Ctrl+K`, `Ctrl+I`, ou o mouse) descreve uma tabela, coluna ou função. **Marcadores** (`Ctrl+K`, `Ctrl+K` para marcar, `Ctrl+K`, `Ctrl+N`/`Ctrl+P` para navegar) pertencem a cada aba. **Outlining** recolhe instruções de mais de uma linha e comentários de bloco. + +**Template Explorer** (`Ctrl+Alt+T`) lista modelos PostgreSQL e os seus próprios arquivos `.sql` da pasta `Templates` do diretório de estado do PGMS; **Specify Values for Template Parameters** (`Ctrl+Shift+M`) preenche os marcadores ``. **Insert Snippet** (`Ctrl+K`, `Ctrl+X`) e **Surround With** (`Ctrl+K`, `Ctrl+S`) inserem trechos; `Tab` passa entre os campos. + +Quando o servidor informa a posição de um erro, o editor o sublinha, a barra de informações o conta e **Go To Next/Previous Issue in File** (`Alt+PgDn`/`Alt+PgUp`) chega até ele; editar limpa a marca. **Find in Files** e **Replace in Files** (`Ctrl+Shift+H`) buscam numa pasta (`*.sql` por padrão), nos documentos abertos ou no atual, e listam as ocorrências em **Find Results**; Replace All troca nas abas abertas pelo editor e nos demais arquivos no disco, com a mesma codificação, depois de uma confirmação. **Edit ▸ Show Clipboard History** (`Ctrl+Shift+V`) guarda as 20 últimas cópias na memória, e **Go To Last Edit Location** (`Ctrl+Shift+Backspace`) volta à última alteração, mesmo em outra aba. + +Uma linha com mais de 10.000 caracteres aparece cortada, com um marcador que abre a linha inteira; o arquivo e o SQL executado não mudam. + +## Abas, janelas e configurações + +**File ▸ New ▸ Query with Current Connection** (`Ctrl+N`) usa a conexão da aba ativa ou do Object Explorer; **Database Engine Query** pede uma. **Open ▸ File…** conecta a aba nova do mesmo jeito, e **File Disconnected…** abre sem conectar. **File ▸ Recent Files**, **Save All**, **Window ▸ Close All Tabs** e **Restore Closed Tab** funcionam como no SSMS; uma consulta fechada sem arquivo volta com o texto, desconectada. **Window** também tem **Next/Previous Pane** (`F6`/`Shift+F6`), **Show Results Pane** (`Ctrl+R`), **Split Tab**, **Dock**, **Auto Hide**, **Move To New Window**, até dez layouts de janela salvos e **Auto Hide All**; **View ▸ Full Screen** é `Shift+Alt+Enter`. + +O menu divide a barra de título com os botões da janela e o **Search** (`Ctrl+Q`), que encontra comandos do menu e páginas e configurações de Tools ▸ Options; `Enter` executa ou abre o resultado. **View ▸ Properties Window** (`F4`) mostra a sessão da consulta ativa (servidor, login, banco, PID do backend, versão, modo SSL, última execução). **View ▸ Error List** (`Ctrl+\`, `E`) tem o erro da última execução de cada aba aberta; o duplo clique vai até ele. **View ▸ Output** (`Ctrl+Alt+O`) guarda as mensagens e execuções da sessão (5.000 linhas na memória). **File ▸ Page Setup…** e **Print…** imprimem o SQL da aba ativa. + +**Tools ▸ Options** inclui **Fonts and Colors** (editor, Grid Results e Text Results), **Keyboard** (um atalho por comando do menu, que ganha do atalho embutido), **Query Shortcuts** (`Alt+F1`, `Ctrl+1` a `Ctrl+0`, vazios por padrão; o texto roda na sessão da aba ativa, seguido da seleção), **Scripting** do Object Explorer, **Designers** e **Connection Dialog**. **Tools ▸ Theme** escolhe Light, Dark ou a configuração do Windows; no Dark, diagramas e planos gráficos continuam claros. **Tools ▸ Editor Appearance** define as cores do editor separadamente, com dois modos de contraste extra, e **View ▸ Presenter Mode** (`Ctrl+Shift+F5`) aumenta o texto do editor, dos resultados e da janela durante a sessão. **Tools ▸ Import and Export Settings…** salva, carrega ou redefine as opções num arquivo `.pgmssettings` (sem posição da janela, arquivos recentes, conexões, senhas ou configurações de IA). **Tools ▸ External Tools…** acrescenta programas ao menu Tools, executados só quando você os escolhe, e **Tools ▸ Customize…** mostra ou esconde as barras de ferramentas. + +## Resultados e consultas em execução + +As abas Results, Messages, do plano e da sessão ficam acima dos resultados. **Save Results As…** no menu da grade abre **Save Grid Results**: um arquivo `.csv` separado por vírgulas ou `.txt` separado por tabulações, sempre com cabeçalhos, com a página atual. **Export Options…** abre a faixa de exportação CSV/JSON. Vários conjuntos de resultados de uma execução aparecem em abas. Valores de tipos de extensões, como o `geometry` do PostGIS, aparecem como o texto que o servidor envia (EWKB em hexadecimal); um tipo criado com o PGMS aberto aparece como `unknown type (oid N)` até você reconectar. + +**Query ▸ Include Live Query Statistics** acrescenta uma aba que, uma vez por segundo e por uma conexão separada, mostra o estado, o tempo decorrido, as esperas e os PIDs que bloqueiam a consulta em execução, e o progresso informado por `pg_stat_progress_*` para CREATE INDEX, VACUUM, ANALYZE, CLUSTER e COPY. O PostgreSQL não tem contadores por operador durante a execução, então não há plano ao vivo. + +## Novidades no Object Explorer + +**View ▸ Object Explorer Details** (`F7`) lista o conteúdo do nó selecionado (nome, tipo, schema, dono) com uma caixa de busca; duplo clique ou `Enter` abre um item e `Backspace` sobe. Chaves, constraints e triggers têm **Modify** (o Table Designer, ou um script DROP e CREATE para trigger), **Rename** (`F2`) e **Delete** com o comando exato, nunca CASCADE; as pastas têm **New Foreign Key…**, **New Constraint…** e **New Trigger…**, e os triggers **Enable** e **Disable**. **New Function…** e **New Stored Procedure…** abrem modelos numa consulta conectada. Cada banco tem uma pasta **Extensions** com **New Extension…** (schema, versão, CASCADE; OK ou Script), **Update Extension…** e **Delete**. Tabelas, views materializadas e bancos têm **Maintenance ▸ Vacuum…**, **Analyze…** e **Refresh Materialized View…**, que abrem o comando numa aba de consulta em vez de executá-lo. **Composite Types**, **Foreign Servers** e **Replication** (publicações e assinaturas locais) são só leitura; valores de opções e `subconninfo` não aparecem. Os filtros de nome e dono também têm **Does not equal**. **Role Memberships** lista as associações efetivas, diretas e herdadas, com o caminho mais curto. + +## Schema Compare + +**Tools ▸ Schema Compare** compara um banco de origem e um de destino, escolhidos na janela Connect, numa transação só de leitura. As diferenças são agrupadas por tipo, schema e ação (Add, Change, Delete), com as duas definições lado a lado e as linhas diferentes marcadas. **Generate Script** escreve as mudanças numa aba de consulta conectada ao destino: `ALTER TYPE … ADD VALUE` primeiro, o resto dentro de `BEGIN … COMMIT`, tabelas coluna a coluna e possível perda de dados marcada. O PGMS nunca o executa; revise antes de executar. Não há Apply, página de opções nem arquivos `.dacpac` ou `.scmp`. + +## Quando o PGMS dá erro + +Um erro que o PGMS não tratou é gravado num log diário em `%LOCALAPPDATA%\PGMS\logs` (ou `logs` sob `PGMS_STATE_DIRECTORY`), guardado por 30 dias. O log tem o horário, as versões do PGMS, do Windows e do .NET e a exceção com a pilha; valores de senha escritos como `chave=valor` são mascarados. Nada é enviado pela rede. Um erro na interface também abre **PGMS - Unexpected Error** com **Copy Details**, **Open Log Folder**, **Report Issue**, **Continue** (o padrão; as consultas abertas mantêm o texto) e **Close PGMS** (fecha normalmente, ainda oferecendo salvar arquivos). Um erro numa thread de segundo plano encerra o PGMS depois de registrado. Ao relatar, leia o log antes: uma mensagem de erro pode citar o que o servidor enviou. + ## 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/docs/pt-BR/validation.md b/docs/pt-BR/validation.md index b17dcea..1d1210a 100644 --- a/docs/pt-BR/validation.md +++ b/docs/pt-BR/validation.md @@ -2,11 +2,11 @@ [English](../en/validation.md) | Português (Brasil) -Pré-release atual: v0.1.0-alpha.6, rótulo M1062 (acrescenta índices, descrições e Export for AI nos diagramas, Query History, Script as, avisos e sugestão de índice nos planos e a escolha de tabelas do SQL assistido por IA em bancos grandes à fonte M1053 da alpha.5; compilada pelo workflow de release no GitHub Actions com atestado de proveniência de build). Marcos são identificadores internos, não garantia de identidade binária de uma recompilação local. A importação pública inicial usou M1002. Histórico operacional e provas brutas privados não são incluídos intencionalmente. +Pré-release atual: v0.1.0-alpha.7, rótulo M1117 (acrescenta à fonte M1062 da alpha.6 a conversa e Explain/Fix/Optimize da IA, o tema escuro e as configurações de aparência, o registro de erros inesperados, muitos comandos do editor, das janelas e do Object Explorer, Schema Compare, Live Query Statistics e restore paralelo/parcial; gerada pelo workflow de release no GitHub Actions com atestado de proveniência; veja as [notas da versão](release-notes.md)). Anterior: v0.1.0-alpha.6, rótulo M1062 (acrescenta índices, descrições e Export for AI nos diagramas, Query History, Script as, avisos e sugestão de índice nos planos e a escolha de tabelas do SQL assistido por IA em bancos grandes à fonte M1053 da alpha.5; compilada pelo workflow de release no GitHub Actions com atestado de proveniência de build). Marcos são identificadores internos, não garantia de identidade binária de uma recompilação local. A importação pública inicial usou M1002. Histórico operacional e provas brutas privados não são incluídos intencionalmente. A implementação importada passou anteriormente em 5.187 checks automatizados (2.115 integração PostgreSQL e 3.072 WPF), além de abertura de pacote, preservação de perfil instalado e recuperação de três rascunhos entre rollback/reinício. São observações históricas, não testes novos a cada revisão. Reproduza o comportamento atual pelos scripts públicos e informe ambiente/resultados reais. As verificações da revisão pública inicial são registradas abaixo após execução. -Limites conhecidos: Windows x64; PostgreSQL 16 a 18 com ferramentas da mesma versão principal, regressão completa no 17.11 e suítes focadas no 16.15/18.6; 15 e anteriores não suportados. Sem paridade integral SSMS. Linhas SQL enormes podem pausar renderização. Resultados/recuperação têm limites. Cancelar não comprova rollback. DPAPI depende do usuário. Pacote sem assinatura/MSI/atualização automática; SmartScreen não certificado. DPI100/125/150/175% exercitados internamente;200% aceito sem execução. Reaparecimento automático após desconexão, DPAPI entre usuários e nova prova desta importação em Windows limpo não certificados. Observações de clipboard/teclado/leitor são históricas, não reproduzidas por checks WPF comuns. +Limites conhecidos: Windows x64; PostgreSQL 16 a 18 com ferramentas da mesma versão principal, regressão completa no 17.11 e suítes focadas no 16.15/18.6; 15 e anteriores não suportados. Sem paridade integral SSMS. Linhas SQL com mais de 10.000 caracteres aparecem cortadas, com um marcador para abri-las. Resultados/recuperação têm limites. Cancelar não comprova rollback. DPAPI depende do usuário. Pacote sem assinatura/MSI/atualização automática; SmartScreen não certificado. DPI100/125/150/175% exercitados internamente;200% aceito sem execução. Reaparecimento automático após desconexão, DPAPI entre usuários e nova prova desta importação em Windows limpo não certificados. Observações de clipboard/teclado/leitor são históricas, não reproduzidas por checks WPF comuns. ```powershell ./scripts/Build.ps1 -Configuration Release @@ -38,6 +38,10 @@ Uma execução completa passou em 2.236 checks de integração + 3.315 WPF = 5.5 Durante o desenvolvimento, a janela foi comparada com o Query Store do SSMS 22.11 sob carga sintética idêntica, contra SQL Server LocalDB e o cluster PostgreSQL descartável. Os dois listaram os mesmos statements com contagens iguais. Diferenças encontradas na época: uma janela em vez de sete relatórios do Query Store; contadores acumulados do servidor em vez de intervalos de tempo por banco; sem gráfico, plano, leituras lógicas ou ordenação pelo cabeçalho; registros inteiros expostos como nome das linhas a leitores de tela. Ordenação pelo cabeçalho, métricas de I/O e blocos, planos genéricos, gráfico top-N, janelas de tempo e nomes curtos de linha foram acrescentados depois. Diferenças que permanecem: uma janela em vez de relatórios separados, janelas calculadas subtraindo amostras em vez de intervalos armazenados, e sem tempo de CPU por statement, que o PostgreSQL não registra. Observações físicas de DPI e leitor de tela desta janela não recebem nova certificação. +## v0.1.0-alpha.7 / M1117 — 17/11/2026 + +Uma execução completa passou em 3.135 verificações de integração + 5.440 WPF = 8.575 no PostgreSQL 17.11, num cluster descartável em loopback com `pg_stat_statements` pré-carregado, na primeira tentativa. O pacote self-contained gerado localmente passou na verificação do manifesto (526 arquivos), nas conferências de guias e do arquivo, no teste de abertura e numa instalação e remoção gráfica por usuário; a instalação global não foi executada. O teste de abertura agora cancela o Connect que o PGMS abre na inicialização antes de fechar a janela principal: ele vinha falhando de forma intermitente porque o diálogo podia abrir antes do pedido de fechamento. No repositório de desenvolvimento, as funções acrescentadas desde a alpha.6 foram validadas por recortes enquanto eram construídas; a regressão completa no PostgreSQL 16.15 e 18.6 só rodou numa fonte anterior (M1066). A conversa e o Explain/Fix/Optimize da IA rodaram com um provedor falso local, não com um real. O PostGIS não foi instalado: foi usado um tipo `geometry` substituto. O tratamento de erros inesperados foi exercitado pelos mesmos métodos que os tratadores globais chamam; os tratadores não foram disparados por uma falha real. As telas novas foram exercitadas por testes automatizados e, no tema escuro e na barra de título, à mão com teclado e mouse num monitor a 100 %; não foram usados VM Windows limpa nem leitores de tela. + ## v0.1.0-alpha.6 / M1062 — 13/11/2026 Uma execução completa passou com 3.018 de integração + 4.586 WPF = 7.604 verificações no PostgreSQL 17.11, num cluster descartável em loopback com `pg_stat_statements` pré-carregado, na primeira tentativa. A regressão completa não foi repetida no PostgreSQL 16 ou 18. As telas novas foram exercitadas por testes automáticos, não à mão com mouse e teclado. A escolha de tabelas do Gerar SQL com IA em bancos grandes não foi executada com um provedor real, e nenhum agente de IA real leu o Markdown do Export for AI. diff --git a/installer/release.json b/installer/release.json index 9b53849..8407a43 100644 --- a/installer/release.json +++ b/installer/release.json @@ -1,6 +1,6 @@ { - "Version": "0.1.0-alpha.6", - "NumericVersion": "0.1.0.6", - "Milestone": "M1062", - "ManifestSha256": "ACD37A7DDAA2F116B09F566A02D682B5407ABD5A2E0C5A696B8BBFD94AAD84F6" + "Version": "0.1.0-alpha.7", + "NumericVersion": "0.1.0.7", + "Milestone": "M1117", + "ManifestSha256": "40D3EE2B8737B00DD928C14B9AFDB1B9C709512D521BDCA39083FCEBC4A5A75F" } diff --git a/scripts/Test-PackageLaunch.ps1 b/scripts/Test-PackageLaunch.ps1 index 35256e4..d4a79a6 100644 --- a/scripts/Test-PackageLaunch.ps1 +++ b/scripts/Test-PackageLaunch.ps1 @@ -33,7 +33,28 @@ try { $runtime = @($process.Modules | Where-Object ModuleName -IEQ 'coreclr.dll') if ($runtime.Count -ne 1 -or $runtime[0].FileName -ine (Join-Path $package 'coreclr.dll')) { throw 'Process did not load the bundled runtime.' } $runtimePath = $runtime[0].FileName - if (!$process.CloseMainWindow() -or !$process.WaitForExit(15000)) { throw 'Packaged executable did not close gracefully.' } + # PGMS opens Connect to Server at startup, as SSMS does, once the main window is idle. While that modal dialog is open the + # main window ignores a close request, so wait for it (up to 10 s) and cancel it through UI Automation before closing. + Add-Type -AssemblyName UIAutomationClient, UIAutomationTypes + $mainElement = [Windows.Automation.AutomationElement]::FromHandle($process.MainWindowHandle) + $windowCondition = [Windows.Automation.PropertyCondition]::new([Windows.Automation.AutomationElement]::ControlTypeProperty, [Windows.Automation.ControlType]::Window) + $dialogDeadline = [DateTime]::UtcNow.AddSeconds(10) + $startupDialogClosed = $false + do { + Start-Sleep -Milliseconds 200 + foreach ($dialog in $mainElement.FindAll([Windows.Automation.TreeScope]::Children, $windowCondition)) { + if ($dialog.Current.Name -ne 'Connect to Server') { continue } + $dialog.GetCurrentPattern([Windows.Automation.WindowPattern]::Pattern).Close() + $startupDialogClosed = $true + } + } while (!$startupDialogClosed -and [DateTime]::UtcNow -lt $dialogDeadline) + $closeDeadline = [DateTime]::UtcNow.AddSeconds(15) + $closeRequested = $false + do { + if ($process.CloseMainWindow()) { $closeRequested = $true; break } + Start-Sleep -Milliseconds 200 + } while ([DateTime]::UtcNow -lt $closeDeadline) + if (!$closeRequested -or !$process.WaitForExit(15000)) { throw 'Packaged executable did not close gracefully.' } if ($process.ExitCode -ne 0) { throw "Packaged executable failed: $($process.ExitCode)" } if (!(Test-Path -LiteralPath (Join-Path $state 'layout.xml'))) { throw 'Isolated layout was not persisted on close.' } if (Test-Path -LiteralPath (Join-Path $state 'connections.json')) { throw 'Unexpected connection profile created by blank launch.' } diff --git a/src/PGMS.Desktop/AboutWindow.xaml b/src/PGMS.Desktop/AboutWindow.xaml index 57817c1..08002a5 100644 --- a/src/PGMS.Desktop/AboutWindow.xaml +++ b/src/PGMS.Desktop/AboutWindow.xaml @@ -2,9 +2,9 @@ xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" Title="About PGMS" Icon="Resources/PGMS.ico" Width="640" Height="650" MinWidth="560" MinHeight="480" - Background="{StaticResource PanelBrush}" WindowStartupLocation="CenterOwner" ResizeMode="CanResizeWithGrip"> + Background="{DynamicResource PanelBrush}" WindowStartupLocation="CenterOwner" ResizeMode="CanResizeWithGrip"> - + + + + + + + + + + + + + + + + + + - + - + + + + + + + + - - + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + - - + + + @@ -54,7 +155,8 @@ - + + @@ -64,7 +166,7 @@ - + @@ -97,26 +199,68 @@ + + + + + + + + + + + + + + + + + - - + + + + + + + + + + + + + + + + + + + + + + - - - - + + + + + + + + + - + - + - + + @@ -128,11 +272,11 @@ - - + + diff --git a/src/PGMS.Desktop/MainWindow.xaml.cs b/src/PGMS.Desktop/MainWindow.xaml.cs index bf06e81..0d2840a 100644 --- a/src/PGMS.Desktop/MainWindow.xaml.cs +++ b/src/PGMS.Desktop/MainWindow.xaml.cs @@ -35,10 +35,16 @@ public partial class MainWindow : Window public MainWindow() { + var fontsDocument = EnvironmentSettings.Load(); + FontsAndColorsSettings.EditorAppearance = fontsDocument.EditorAppearanceChoice; + FontsAndColorsSettings.Current = EffectiveFontsAndColors(fontsDocument); InitializeComponent(); + PickInsertFile = PickInsertFileWithDialog; + InitializeTabCommands(); InitializeExplorerToolbar(); _ = QueryHistory; // startup cleanup of Query History WindowWorkArea.Attach(this); + ConfigureTitleBar(); // Keep the caption and status reachable on scaled or small work areas. var workArea = SystemParameters.WorkArea; if (!workArea.IsEmpty && workArea.Width > 0 && workArea.Height > 0) @@ -84,10 +90,29 @@ public MainWindow() InputBindings.Add(new KeyBinding(QueryView.GoToLineCommand,Key.G,ModifierKeys.Control)); CommandBindings.Add(new CommandBinding(SqlEditorCommands.Comment,(_,_)=>ActiveQuery?.CommentSelection(false),(_,e)=>e.CanExecute=ActiveQuery is not null && !closingWindow && !closeRequested)); CommandBindings.Add(new CommandBinding(SqlEditorCommands.Uncomment,(_,_)=>ActiveQuery?.CommentSelection(true),(_,e)=>e.CanExecute=ActiveQuery is not null && !closingWindow && !closeRequested)); + foreach(var (command,run) in SqlEditorCommands.TextEdits) + CommandBindings.Add(new CommandBinding(command,(_,_)=>ActiveQuery?.RunTextEdit(run),(_,e)=>e.CanExecute=ActiveQuery is not null && !closingWindow && !closeRequested)); + ConfigureEncodingCommands(); + ConfigureBookmarkCommands(); + ConfigureHelpCommands(); + ConfigureTemplateCommands(); + ConfigureFindInFilesCommands(); + ConfigurePaneCommands(); + ConfigurePropertiesWindow(); + ConfigureObjectDetails(); + ConfigureEditorConveniences(); + ConfigureCustomization(); + ApplyTheme(); + Closed += (_, _) => StopFollowingSystemTheme(); + HookOutput(); CommandBindings.Add(new CommandBinding(ApplicationCommands.Save, async (_, _) => { if (ActiveQuery is { } query) await SaveAsync(query); else if (ActiveDesigner is { } designer) await designer.SaveAsync(); else if (ActiveDiagram is { } diagram) await diagram.SaveAsync(); else if (ActiveViewDesigner is { } viewDesigner) await viewDesigner.SaveAsync(); }, (_, e) => e.CanExecute = ActiveDesigner is { CanEdit: true, IsDirty: true } || ActiveDiagram is { IsBusy: false, IsDirty: true } || ActiveViewDesigner is { IsBusy: false, IsDirty: true } || ActiveQuery is { } active && !IsSaving(active) && !closingWindow && !closingQueries.Contains(active))); PreviewKeyDown += async (_, e) => { + if (HandleWindowChord(e)) return; + if (HandleAssignedShortcut(e)) return; + if (HandleToolWindowShortcut(e)) return; if (HandleQueryMenuShortcut(e)) return; + if (await HandleQueryShortcutAsync(e)) return; if (e.Key == Key.F5) { e.Handled = true; @@ -102,16 +127,21 @@ public MainWindow() loading.CancelLoad(); e.Handled = true; } if (e.Key == Key.F8) { ShowExplorer(this, e); e.Handled = true; } + if (HandlePropertiesShortcut(e)) return; + if (e.Key == Key.F7 && Keyboard.Modifiers == ModifierKeys.None) { ShowObjectExplorerDetails(); e.Handled = true; } if (HandleResultsShortcut(e)) return; // 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; } + if ((e.Key == Key.System ? e.SystemKey : e.Key) == Key.H && Keyboard.Modifiers == (ModifierKeys.Control | ModifierKeys.Alt)) { ShowQueryHistory(); e.Handled = true; } if ((e.Key == Key.System ? e.SystemKey : e.Key) == Key.T && Keyboard.Modifiers == (ModifierKeys.Control | ModifierKeys.Alt)) { ShowTemplateExplorer(); e.Handled = true; } }; } internal Action? UiPhaseMeasured { get; set; } + /// A new, unconnected query tab with the text (tests and callers outside the window). + internal QueryView NewQueryTab(string? text = null) => NewQuery(text); + /// 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) { @@ -134,14 +164,17 @@ private QueryView NewQuery(string? text = null, string? path = null, Guid? recov var environment = EnvironmentSettings.Load(); view.ResultsDestination = environment.DefaultResults; view.ApplyQueryOptions(environment.QueryOptionDefaults); + if (!ReferenceEquals(view.Appearance, FontsAndColorsSettings.Current)) view.ApplyAppearance(FontsAndColorsSettings.Current); // a spare made before Options changed view.JsonLinkRequested += OpenJsonDocument; view.PlanTabRequested += statements => OpenPlanDocument(statements, "Execution plan", PlanOrigin(view)); view.MissingIndexDetailsRequested += OpenMissingIndexDetails; + view.ExecutionNoted += (_, _) => NoteExecutionForToolWindows(view); var document = new LayoutDocument { Title = path is null ? $"SQLQuery{++sequence}.sql" : Path.GetFileName(path), ContentId = Guid.NewGuid().ToString(), Content = view }; documents.Add(view, document); view.StateChanged += (_, _) => { document.Title = document.Title.TrimEnd('*') + (view.IsDirty ? "*" : ""); + UpdateConnectionTexts(); RefreshCommands(); }; document.Closing += (_, e) => @@ -150,7 +183,7 @@ private QueryView NewQuery(string? text = null, string? path = null, Guid? recov e.Cancel = true; _ = CloseQueryAsync(view); }; - document.Closed += async (_, _) => { documents.Remove(view); await view.DisposeAsync(); RefreshCommands(); }; + document.Closed += async (_, _) => { documents.Remove(view); RefreshPropertiesWindow(); UpdateConnectionTexts(); await view.DisposeAsync(); RefreshCommands(); }; AddDocument(document); if (activate) document.IsActive = true; // The editor is not yet in the visual tree when the document is inserted. @@ -176,20 +209,6 @@ private void AddDocument(LayoutDocument document) pane.Children.Add(document); } - private async void Open(object sender, ExecutedRoutedEventArgs e) - { - var dialog = new OpenFileDialog { Filter = "SQL files (*.sql)|*.sql|All files (*.*)|*.*", Multiselect = true }; - if (dialog.ShowDialog(this) != true) return; - foreach (var file in dialog.FileNames) - { - if (closeRequested || shuttingDown) break; - try { await OpenQueryFileAsync(file); } - catch (OperationCanceledException) { break; } - catch (Exception ex) when (ex is IOException or UnauthorizedAccessException or InvalidDataException) - { ShowError(ex); } - } - } - public bool TryOpenQueryFile(string path, out Exception? error) { try { OpenQueryFile(path); error = null; return true; } @@ -298,6 +317,7 @@ private async Task LoadExplorerAsync() if (token.IsCancellationRequested || explorerConnection != connection) return; // Disconnected while loading. ExplorerTree.Items.Clear(); ExplorerTree.Items.Add(root); + _ = LabelServerNodeAsync(root, connection, token); Status.Text = "Object Explorer refreshed. Expand a database to load its objects."; NewDatabaseMenu.IsEnabled = NewSchemaMenu.IsEnabled = NewRoleMenu.IsEnabled = BackupMenu.IsEnabled = RestoreMenu.IsEnabled = true; BackupGlobalsMenu.IsEnabled=RestoreGlobalsMenu.IsEnabled=true; @@ -588,7 +608,18 @@ private async void RoleProperties(object sender, RoutedEventArgs e) public static readonly RoutedUICommand DesignQueryInEditor = new("Design Query in Editor", nameof(DesignQueryInEditor), typeof(MainWindow)); public static readonly RoutedUICommand ShowQueryOptions = new("Query Options", nameof(ShowQueryOptions), typeof(MainWindow)); // Opens the assistant for the active query tab; the generated SQL only reaches the editor through Insert. - internal void OpenAiQuery(string? settingsPath = null) + internal void OpenAiQuery(string? settingsPath = null) => OpenAiQuery(null, settingsPath); + + /// Tests: receives the AI window instead of showing it modally. + internal Action? AiQueryShown { get; set; } + + private void ExplainSqlWithAi(object sender, RoutedEventArgs e) => OpenAiQuery(AiSqlAction.Explain); + private void FixSqlWithAi(object sender, RoutedEventArgs e) => OpenAiQuery(AiSqlAction.Fix); + private void OptimizeSqlWithAi(object sender, RoutedEventArgs e) => OpenAiQuery(AiSqlAction.Optimize); + + /// Explain, Fix or Optimize (M1115): the window opens with the selected SQL (or the whole document when nothing is + /// selected) and a request written for it, which the user can change before Generate. + internal void OpenAiQuery(AiSqlAction? action, string? settingsPath = null) { if (ActiveQuery is not { } query) return; if (!query.IsConnected || query.ConnectionString is not { } connection) { Status.Text = "Connect this query window before generating SQL with AI."; return; } @@ -610,7 +641,12 @@ internal void OpenAiQuery(string? settingsPath = null) } } if (provider is null) { Status.Text = "The AI assistant is not configured."; return; } - var dialog = new AiQueryDialog(provider, connection, query.SelectedSql, query.InsertGeneratedSql) { Owner = this }; + string? sql = query.SelectedSql; + if (action is not null && string.IsNullOrWhiteSpace(sql)) sql = query.Editor.Text; + if (action is not null && string.IsNullOrWhiteSpace(sql)) { Status.Text = "Write or select the SQL to " + action.Value.ToString().ToLowerInvariant() + " first."; return; } + var dialog = new AiQueryDialog(provider, connection, sql, query.InsertGeneratedSql) { Owner = this }; + if (action is { } chosen) dialog.Prefill(AiQueryGenerator.ActionRequest(chosen, chosen == AiSqlAction.Fix ? query.LastError?.Code : null, chosen == AiSqlAction.Fix ? query.LastError?.Message : null)); + if (AiQueryShown is { } shown) { shown(dialog); return; } if (dialog.ShowDialog() == true && dialog.WasInserted) Status.Text = "AI-generated SQL inserted into the editor. Review it before running."; } private void ConfigureServerTls(object sender, RoutedEventArgs e) @@ -907,8 +943,24 @@ public async Task RefreshSelectedExplorerAsync() } private async void SaveAs(object sender, RoutedEventArgs e) { if (ActiveQuery is { } query) await SaveAsync(query, true); } private void ViewMenuOpened(object sender,RoutedEventArgs e){WordWrapMenu.IsEnabled=ActiveQuery is not null;WordWrapMenu.IsChecked=ActiveQuery?.WordWrap==true;WhiteSpaceMenu.IsEnabled=ActiveQuery is not null;WhiteSpaceMenu.IsChecked=ActiveQuery?.ShowWhiteSpace==true;} - private void ToggleWordWrap(object sender,RoutedEventArgs e){if(ActiveQuery is { } query)query.WordWrap=WordWrapMenu.IsChecked;} - private void ToggleWhiteSpace(object sender,RoutedEventArgs e){if(ActiveQuery is { } query)query.ShowWhiteSpace=WhiteSpaceMenu.IsChecked;} + private void AdvancedMenuOpened(object sender,RoutedEventArgs e){SpellCheckerMenu.IsEnabled=ActiveQuery is not null;SpellCheckerMenu.IsChecked=ActiveQuery?.SpellCheck==true;AdvancedWordWrapMenu.IsEnabled=ActiveQuery is not null;AdvancedWordWrapMenu.IsChecked=ActiveQuery?.WordWrap==true;AdvancedWhiteSpaceMenu.IsEnabled=ActiveQuery is not null;AdvancedWhiteSpaceMenu.IsChecked=ActiveQuery?.ShowWhiteSpace==true;} + private void EditMenuOpened(object sender,RoutedEventArgs e){if(ReferenceEquals(e.OriginalSource,sender))InsertFileAsTextMenu.IsEnabled=ActiveQuery is not null && !closingWindow && !closeRequested;} + private void ToggleWordWrap(object sender,RoutedEventArgs e){if(ActiveQuery is { } query)query.WordWrap=((MenuItem)sender).IsChecked;} + private void ToggleWhiteSpace(object sender,RoutedEventArgs e){if(ActiveQuery is { } query)query.ShowWhiteSpace=((MenuItem)sender).IsChecked;} + /// Picks the file to insert; tests replace it to avoid the modal dialog. + internal Func PickInsertFile { get; set; } + private async void InsertFileAsText(object sender,RoutedEventArgs e) + { + if(ActiveQuery is not { } query)return; + if(PickInsertFile() is not { } path)return; + try{await query.InsertFileAsTextAsync(path);} + catch(Exception ex) when(ex is IOException or UnauthorizedAccessException or InvalidDataException){ShowError(ex);} + } + private string? PickInsertFileWithDialog() + { + var dialog=new OpenFileDialog{Title="Insert File",Filter="SQL files (*.sql)|*.sql|All files (*.*)|*.*"}; + return dialog.ShowDialog(this)==true?dialog.FileName:null; + } private void Find(object sender, RoutedEventArgs e) => ActiveQuery?.Find(); private void Exit(object sender, RoutedEventArgs e) => Close(); private void About(object sender, RoutedEventArgs e) => new AboutWindow { Owner = this }.ShowDialog(); @@ -988,10 +1040,24 @@ internal void SaveWindowPlacement() EnvironmentSettings.Update(d => d with { Window = new(Math.Round(bounds.Left), Math.Round(bounds.Top), Math.Round(bounds.Width), Math.Round(bounds.Height), maximized) }); } - private void ShowOptions(object sender, RoutedEventArgs e) + private void ShowOptions(object sender, RoutedEventArgs e) => ShowOptions(); + + /// Tools ▸ Options, on when given ("Keyboard" from Customize). + internal void ShowOptions(string? page = null) { - var dialog = new OptionsDialog(EnvironmentSettings, () => QueryHistory.ClearAsync()) { Owner = this }; - dialog.ShowDialog(); + var dialog = new OptionsDialog(EnvironmentSettings, () => QueryHistory.ClearAsync(), KeyboardCommands()) { Owner = this }; + if (page is not null && !dialog.SelectPagePath(page)) dialog.SelectPage(page); + if (OptionsShown is { } shown) { shown(dialog); return; } + if (dialog.ShowDialog() == true) { ApplyFontsAndColors(); ApplyCustomization(); } + } + + /// Fonts and Colors applies at once to every open query window, as in SSMS. + internal void ApplyFontsAndColors() + { + var fontsDocument = EnvironmentSettings.Load(); + FontsAndColorsSettings.EditorAppearance = fontsDocument.EditorAppearanceChoice; + FontsAndColorsSettings.Current = EffectiveFontsAndColors(fontsDocument); + foreach (var query in OpenQueries()) query.ApplyAppearance(FontsAndColorsSettings.Current); } private void RestoreSavedLayout() @@ -1004,6 +1070,10 @@ private void RestoreSavedLayout() { if (args.Model.ContentId == "explorer") args.Content = ExplorerContent; else if (args.Model.ContentId == RegisteredServersId) args.Content = RegisteredServers; + else if (args.Model.ContentId == TemplateExplorerId) args.Content = TemplateExplorer; + else if (args.Model.ContentId == FindResultsId) args.Content = FindResults; + else if (args.Model.ContentId == PropertiesWindowId) args.Content = PropertiesContent; + else if (ToolContentFor(args.Model.ContentId) is { } tool) args.Content = tool; else args.Cancel = true; // Never restore an empty tab pretending its text was saved. }; serializer.Deserialize(layoutFile); diff --git a/src/PGMS.Desktop/MaintenanceDialog.cs b/src/PGMS.Desktop/MaintenanceDialog.cs new file mode 100644 index 0000000..4610da8 --- /dev/null +++ b/src/PGMS.Desktop/MaintenanceDialog.cs @@ -0,0 +1,91 @@ +using System.Windows; +using System.Windows.Automation; +using System.Windows.Controls; +using PGMS.PostgreSql; + +namespace PGMS.Desktop; + +public enum MaintenanceKind { Vacuum, Analyze, Refresh } + +/// VACUUM, ANALYZE and REFRESH MATERIALIZED VIEW text for Object Explorer ▸ Maintenance (PGMS-062, M1089). A null relation means the whole database. +public static class MaintenanceCommands +{ + public static string Target(string? schema, string? relation) => relation is null ? "" : " " + SqlIdentifier.Quote(schema!) + "." + SqlIdentifier.Quote(relation); + + public static string Vacuum(string? schema, string? relation, bool full = false, bool freeze = false, bool analyze = false, bool verbose = false) + { + var options = new List(); + if (full) options.Add("FULL"); + if (freeze) options.Add("FREEZE"); + if (verbose) options.Add("VERBOSE"); + if (analyze) options.Add("ANALYZE"); + return "VACUUM" + (options.Count == 0 ? "" : " (" + string.Join(", ", options) + ")") + Target(schema, relation) + ";"; + } + + public static string Analyze(string? schema, string? relation, bool verbose = false) => "ANALYZE" + (verbose ? " (VERBOSE)" : "") + Target(schema, relation) + ";"; + + /// CONCURRENTLY needs a unique index on the view and cannot be combined with WITH NO DATA. + public static string Refresh(string schema, string relation, bool concurrently = false, bool withData = true) + { + if (concurrently && !withData) throw new ArgumentException("CONCURRENTLY cannot be used with WITH NO DATA."); + return "REFRESH MATERIALIZED VIEW" + (concurrently ? " CONCURRENTLY" : "") + Target(schema, relation) + (withData ? "" : " WITH NO DATA") + ";"; + } +} + +/// Options of one maintenance command with the statement it will open in a query editor, where it is reviewed and executed (never run from here). +public sealed class MaintenanceDialog : Window +{ + private readonly MaintenanceKind kind; + private readonly string? schema, relation; + private readonly TextBox preview = new() { IsReadOnly = true, FontFamily = new System.Windows.Media.FontFamily("Consolas"), TextWrapping = TextWrapping.Wrap, MinHeight = 48, Margin = new Thickness(0, 4, 0, 12) }; + private readonly TextBlock error = new() { Foreground = System.Windows.Media.Brushes.Firebrick, TextWrapping = TextWrapping.Wrap }; + private readonly Button ok = new() { Content = "_Open in Query Editor", Padding = new Thickness(12, 3, 12, 3), IsDefault = true, Margin = new Thickness(0, 0, 8, 0) }; + public CheckBox Full { get; } = Box("_FULL (rewrites the table; locks it exclusively)"); + public CheckBox Freeze { get; } = Box("F_REEZE"); + public CheckBox AnalyzeToo { get; } = Box("_ANALYZE (update planner statistics)"); + public CheckBox Verbose { get; } = Box("_VERBOSE (report progress in Messages)"); + public CheckBox Concurrently { get; } = Box("_CONCURRENTLY (needs a unique index; readers are not blocked)"); + public CheckBox NoData { get; } = Box("WITH _NO DATA (leaves the view unscannable)"); + public string Sql { get; private set; } = ""; + + private static CheckBox Box(string text) => new() { Content = text, Margin = new Thickness(0, 3, 0, 3) }; + + public MaintenanceDialog(MaintenanceKind kind, string database, string? schema, string? relation) + { + this.kind = kind; this.schema = schema; this.relation = relation; + Title = kind switch { MaintenanceKind.Vacuum => "Vacuum", MaintenanceKind.Analyze => "Analyze", _ => "Refresh Materialized View" }; + Width = 460; SizeToContent = SizeToContent.Height; ResizeMode = ResizeMode.NoResize; ShowInTaskbar = false; WindowStartupLocation = WindowStartupLocation.CenterOwner; + var panel = new StackPanel { Margin = new Thickness(12) }; + panel.Children.Add(new TextBlock { Text = relation is null ? $"Database: {database}" : $"{database} › {schema}.{relation}", FontWeight = FontWeights.SemiBold, Margin = new Thickness(0, 0, 0, 8), TextTrimming = TextTrimming.CharacterEllipsis }); + CheckBox[] boxes = kind switch { MaintenanceKind.Vacuum => [Full, Freeze, AnalyzeToo, Verbose], MaintenanceKind.Analyze => [Verbose], _ => [Concurrently, NoData] }; + foreach (var box in boxes) { panel.Children.Add(box); box.Checked += (_, _) => Update(); box.Unchecked += (_, _) => Update(); } + panel.Children.Add(new TextBlock { Text = "Statement:", Margin = new Thickness(0, 10, 0, 0) }); + AutomationProperties.SetName(preview, "Statement"); + panel.Children.Add(preview); + panel.Children.Add(error); + panel.Children.Add(new TextBlock { Text = "The statement opens in a query editor; nothing runs until you execute it there.", TextWrapping = TextWrapping.Wrap, Foreground = System.Windows.SystemColors.GrayTextBrush, Margin = new Thickness(0, 0, 0, 10) }); + var cancel = new Button { Content = "Cancel", Padding = new Thickness(12, 3, 12, 3), IsCancel = true }; + ok.Click += (_, _) => DialogResult = true; + panel.Children.Add(new StackPanel { Orientation = Orientation.Horizontal, HorizontalAlignment = HorizontalAlignment.Right, Children = { ok, cancel } }); + Content = panel; + Update(); + } + + private void Update() + { + try + { + Sql = kind switch + { + MaintenanceKind.Vacuum => MaintenanceCommands.Vacuum(schema, relation, Full.IsChecked == true, Freeze.IsChecked == true, AnalyzeToo.IsChecked == true, Verbose.IsChecked == true), + MaintenanceKind.Analyze => MaintenanceCommands.Analyze(schema, relation, Verbose.IsChecked == true), + _ => MaintenanceCommands.Refresh(schema!, relation!, Concurrently.IsChecked == true, NoData.IsChecked != true) + }; + error.Text = ""; ok.IsEnabled = true; + } + catch (ArgumentException ex) { Sql = ""; error.Text = ex.Message; ok.IsEnabled = false; } + preview.Text = Sql; + } + + public bool CanAccept => ok.IsEnabled; +} diff --git a/src/PGMS.Desktop/ObjectExplorerDetailsView.cs b/src/PGMS.Desktop/ObjectExplorerDetailsView.cs new file mode 100644 index 0000000..66d31da --- /dev/null +++ b/src/PGMS.Desktop/ObjectExplorerDetailsView.cs @@ -0,0 +1,147 @@ +using System.Text.RegularExpressions; +using System.Windows; +using System.Windows.Automation; +using System.Windows.Controls; +using System.Windows.Data; +using System.Windows.Input; +using PGMS.Desktop.ViewModels; +using PGMS.PostgreSql; + +namespace PGMS.Desktop; + +/// Object Explorer Details (View ▸ Object Explorer Details, F7; PGMS-052, M1085): a document listing what the node selected in Object Explorer contains. +public sealed partial class ObjectExplorerDetailsView : UserControl +{ + public sealed record Row(CatalogNode Node, string Name, string Type, string Schema, string Owner); + + private readonly TextBlock path = new() { Margin = new Thickness(0, 0, 0, 6), TextTrimming = TextTrimming.CharacterEllipsis, FontWeight = FontWeights.SemiBold }; + private readonly TextBox search = new() { Width = 220, Margin = new Thickness(8, 0, 0, 0) }; + private readonly TextBlock count = new() { Margin = new Thickness(0, 6, 0, 0) }; + private readonly Button up = new() { Content = "_Up", Padding = new Thickness(10, 2, 10, 2), ToolTip = "Show the folder that contains this one" }; + private readonly Button refresh = new() { Content = "_Refresh", Padding = new Thickness(10, 2, 10, 2), Margin = new Thickness(6, 0, 0, 0), ToolTip = "Read the list from the server again (F5 in Object Explorer)" }; + private readonly DataGrid grid = new() + { + AutoGenerateColumns = false, IsReadOnly = true, CanUserAddRows = false, CanUserDeleteRows = false, SelectionMode = DataGridSelectionMode.Extended, SelectionUnit = DataGridSelectionUnit.FullRow, + HeadersVisibility = DataGridHeadersVisibility.Column, GridLinesVisibility = DataGridGridLinesVisibility.None + }; + private IReadOnlyList all = []; + private int generation; + + public string Title => "Object Explorer Details"; + public CatalogNode? Current { get; private set; } + /// True while the list of is being read. + public bool IsLoading { get; private set; } + public DataGrid Grid => grid; + public TextBox Search => search; + public string PathText => path.Text; + public string CountText => count.Text; + public IReadOnlyList Rows => (IReadOnlyList?)grid.ItemsSource ?? []; + /// Asks Object Explorer to select a node (keeps both views in step); the main window sets it. + public Action? SelectInExplorer { get; set; } + + public ObjectExplorerDetailsView() + { + foreach (var (header, property, width) in new[] { ("Name", nameof(Row.Name), 2.0), ("Type", nameof(Row.Type), 1.0), ("Schema", nameof(Row.Schema), 1.0), ("Owner", nameof(Row.Owner), 1.0) }) + grid.Columns.Add(new DataGridTextColumn { Header = header, Binding = new Binding(property), Width = new DataGridLength(width, DataGridLengthUnitType.Star) }); + AutomationProperties.SetName(grid, "Object Explorer Details"); + AutomationProperties.SetName(search, "Search"); + search.TextChanged += (_, _) => ApplySearch(); + grid.MouseDoubleClick += (_, e) => { if (grid.SelectedItem is Row row) { _ = OpenAsync(row); e.Handled = true; } }; + grid.PreviewKeyDown += (_, e) => { if (e.Key == Key.Enter && grid.SelectedItem is Row row) { _ = OpenAsync(row); e.Handled = true; } else if (e.Key == Key.Back) { _ = UpAsync(); e.Handled = true; } }; + up.Click += (_, _) => _ = UpAsync(); + refresh.Click += (_, _) => _ = RefreshAsync(); + var bar = new DockPanel { Margin = new Thickness(0, 0, 0, 6) }; + var buttons = new StackPanel { Orientation = Orientation.Horizontal, Children = { up, refresh } }; + var find = new StackPanel { Orientation = Orientation.Horizontal, HorizontalAlignment = HorizontalAlignment.Right, Children = { new TextBlock { Text = "Search:", VerticalAlignment = VerticalAlignment.Center }, search } }; + DockPanel.SetDock(buttons, Dock.Left); bar.Children.Add(buttons); bar.Children.Add(find); + var root = new DockPanel { Margin = new Thickness(8) }; + DockPanel.SetDock(path, Dock.Top); DockPanel.SetDock(bar, Dock.Top); DockPanel.SetDock(count, Dock.Bottom); + root.Children.Add(path); root.Children.Add(bar); root.Children.Add(count); root.Children.Add(grid); + Content = root; + Background = SystemColors.WindowBrush; + _ = ShowAsync(null); + } + + /// Lists the contents of a folder or object; for an item that contains nothing, its siblings with it selected. Loads the node like expanding it would. + public async Task ShowAsync(CatalogNode? node) + { + int mine = ++generation; + CatalogNode? folder = node is null ? null : node.Entry.CanExpand ? node : node.Parent ?? node; + Current = folder; + if (folder is null) + { + path.Text = "Object Explorer is not connected, or nothing is selected."; IsLoading = false; all = []; ApplySearch(); up.IsEnabled = refresh.IsEnabled = false; return; + } + path.Text = PathOf(folder); + IsLoading = true; count.Text = "Loading…"; + up.IsEnabled = folder.Parent is not null; refresh.IsEnabled = true; + if (folder.Entry.CanExpand) await folder.LoadAsync(); + // A load already running (started by Object Explorer) returns at once: wait for it. + while (folder.IsBusy) { await Task.Delay(50); if (mine != generation) return; } + if (mine != generation) return; + IsLoading = false; + all = folder.Entry.CanExpand ? folder.Children.Where(c => !IsPlaceholder(c)).Select(ToRow).ToList() : []; + ApplySearch(); + if (node is not null && !ReferenceEquals(node, folder) && Rows.FirstOrDefault(r => ReferenceEquals(r.Node, node)) is { } selected) { grid.SelectedItem = selected; grid.ScrollIntoView(selected); } + } + + private static bool IsPlaceholder(CatalogNode node) => node.Entry.Kind == CatalogKind.Column && node.Entry.Name == "Expand to load…" && node.Parent is { } p && p.Entry.Kind != CatalogKind.Columns; + + public async Task OpenAsync(Row row) + { + if (!row.Node.Entry.CanExpand) return; + if (row.Node.Parent is { } parent) parent.IsExpanded = true; + SelectInExplorer?.Invoke(row.Node); + await ShowAsync(row.Node); + } + + public async Task UpAsync() + { + if (Current?.Parent is not { } parent) return; + var from = Current; + SelectInExplorer?.Invoke(parent); + await ShowAsync(parent); + if (Rows.FirstOrDefault(r => ReferenceEquals(r.Node, from)) is { } back) grid.SelectedItem = back; + } + + public async Task RefreshAsync() + { + if (Current is not { } folder) return; + await folder.LoadAsync(refresh: true); + await ShowAsync(folder); + } + + private void ApplySearch() + { + string text = search.Text.Trim(); + var shown = text.Length == 0 ? all : all.Where(r => r.Name.Contains(text, StringComparison.CurrentCultureIgnoreCase)).ToList(); + grid.ItemsSource = shown; + count.Text = Current is null ? "" : text.Length == 0 ? $"{all.Count:N0} item(s)" : $"{shown.Count:N0} of {all.Count:N0} item(s)"; + } + + private static Row ToRow(CatalogNode node) => new(node, node.Entry.Name, TypeOf(node.Entry), node.Entry.Schema ?? "", node.Entry.Owner ?? ""); + + internal static string PathOf(CatalogNode node) + { + var names = new List(); + for (var n = node; n is not null; n = n.Parent) names.Add(n.Entry.Name); + names.Reverse(); + return string.Join(" › ", names); + } + + [GeneratedRegex("(?<=[a-z])(?=[A-Z])")] + private static partial Regex WordBreak(); + + /// What a row is, in the words Object Explorer uses for it. + internal static string TypeOf(CatalogEntry entry) => entry.Kind switch + { + CatalogKind.Relation => entry.RelationType switch { "r" => "Table", "p" => "Partitioned Table", "v" => "View", "m" => "Materialized View", "S" => "Sequence", "f" => "Foreign Table", _ => "Relation" }, + CatalogKind.Routine => entry.RoutineKind switch { "p" => "Procedure", "a" => "Aggregate Function", "w" => "Window Function", _ => "Function" }, + CatalogKind.DataType => entry.DataTypeKind switch { "e" => "Enum", "d" => "Domain", "c" => "Composite Type", "r" => "Range Type", _ => "Data Type" }, + CatalogKind.Databases or CatalogKind.Schemas or CatalogKind.Tables or CatalogKind.Views or CatalogKind.MaterializedViews or CatalogKind.Sequences or CatalogKind.Functions or CatalogKind.Procedures + or CatalogKind.Columns or CatalogKind.Indexes or CatalogKind.Roles or CatalogKind.Enums or CatalogKind.Domains or CatalogKind.DatabaseDiagrams or CatalogKind.Keys or CatalogKind.Constraints or CatalogKind.Triggers or CatalogKind.Extensions + or CatalogKind.CompositeTypes or CatalogKind.ForeignServers or CatalogKind.Replication or CatalogKind.Publications or CatalogKind.Subscriptions => "Folder", + CatalogKind.DatabaseDiagram => "Database Diagram", + _ => WordBreak().Replace(entry.Kind.ToString(), " ") + }; +} diff --git a/src/PGMS.Desktop/ObjectPropertiesDialog.xaml b/src/PGMS.Desktop/ObjectPropertiesDialog.xaml index afa1a8f..fa5ed9c 100644 --- a/src/PGMS.Desktop/ObjectPropertiesDialog.xaml +++ b/src/PGMS.Desktop/ObjectPropertiesDialog.xaml @@ -1,8 +1,8 @@ + Title="Object Properties" Width="800" Height="600" MinWidth="600" MinHeight="440" Background="{DynamicResource Pgms.DialogBackground}" WindowStartupLocation="CenterOwner" Closing="OnClosing" PreviewKeyDown="OnPreviewKeyDown"> - + diff --git a/src/PGMS.Desktop/OptionsDialog.FontsAndColors.cs b/src/PGMS.Desktop/OptionsDialog.FontsAndColors.cs new file mode 100644 index 0000000..b981569 --- /dev/null +++ b/src/PGMS.Desktop/OptionsDialog.FontsAndColors.cs @@ -0,0 +1,213 @@ +using System.Globalization; +using System.Windows; +using System.Windows.Controls; +using System.Windows.Media; + +namespace PGMS.Desktop; + +/// Environment ▸ Fonts and Colors (PGMS-071). The page edits a working copy; OK saves it and the main window applies it to every open query +/// window. Colors are a name of the Visual Studio list or #RRGGBB; "Default" (empty) keeps the PGMS color. +public partial class OptionsDialog +{ + private const string DefaultColorText = "Default"; + private static readonly double[] StandardSizes = [6, 7, 8, 9, 10, 10.5, 11, 12, 14, 16, 18, 20, 22, 24, 26, 28, 36, 48, 72]; + private readonly string[] fontNames = new string[3]; + private readonly string[] fontSizes = new string[3]; + private readonly Dictionary itemDrafts = []; + private int fontCategory = -1; + private string? shownItem; + private bool loadingFonts; + + private void LoadFontsAndColors(FontsAndColorsSettings settings) + { + loadingFonts = true; + try + { + if (FontCategoryBox.Items.Count == 0) + { + foreach (var category in FontsAndColorsSettings.Categories) FontCategoryBox.Items.Add(category); + foreach (var family in Fonts.SystemFontFamilies.Select(f => f.Source).Distinct(StringComparer.OrdinalIgnoreCase).Order(StringComparer.CurrentCultureIgnoreCase)) FontNameBox.Items.Add(family); + foreach (double size in StandardSizes) FontSizeBox.Items.Add(SizeText(size)); + foreach (var item in FontsAndColorsSettings.EditorItemNames) DisplayItemsBox.Items.Add(item); + foreach (var box in new[] { ItemForegroundBox, ItemBackgroundBox }) + { + box.Items.Add(DefaultColorText); + foreach (var (name, _) in FontsAndColorsSettings.NamedColors) box.Items.Add(name); + } + } + fontNames[0] = settings.EditorFontName; fontSizes[0] = SizeText(settings.EditorPoints); + fontNames[1] = settings.GridFontName; fontSizes[1] = SizeText(settings.GridPoints); + fontNames[2] = settings.TextResultsFontName; fontSizes[2] = SizeText(settings.TextResultsPoints); + itemDrafts.Clear(); + foreach (var item in FontsAndColorsSettings.EditorItemNames) + if (settings.EditorItems is not null && settings.EditorItems.ContainsKey(item)) itemDrafts[item] = settings.Item(item); + fontCategory = -1; shownItem = null; + FontCategoryBox.SelectedIndex = 0; + ShowFontCategory(0); + DisplayItemsBox.SelectedIndex = 0; + ShowItem(FontsAndColorsSettings.PlainText); + } + finally { loadingFonts = false; } + UpdateFontSample(); + } + + private static string SizeText(double points) => points.ToString("0.##", CultureInfo.CurrentCulture); + + private void ShowFontCategory(int category) + { + KeepFontCategory(); + fontCategory = category; + FontNameBox.Text = fontNames[category]; + FontSizeBox.Text = fontSizes[category]; + var items = category == 0 ? Visibility.Visible : Visibility.Collapsed; + DisplayItemsLabel.Visibility = DisplayItemsBox.Visibility = ItemColorsPanel.Visibility = items; + } + + private void KeepFontCategory() + { + if (fontCategory < 0) return; + fontNames[fontCategory] = FontNameBox.Text.Trim(); + fontSizes[fontCategory] = FontSizeBox.Text.Trim(); + } + + private void ShowItem(string item) + { + KeepItem(); + shownItem = item; + var value = itemDrafts.TryGetValue(item, out var chosen) ? chosen : null; + var (foreground, background, bold) = FontsAndColorsSettings.Supports(item); + ItemForegroundBox.IsEnabled = foreground; ItemBackgroundBox.IsEnabled = background; ItemBoldBox.IsEnabled = bold; + ItemForegroundBox.Text = foreground && value?.Foreground is { } f ? FontsAndColorsSettings.ColorName(f) : DefaultColorText; + ItemBackgroundBox.Text = background && value?.Background is { } b ? FontsAndColorsSettings.ColorName(b) : DefaultColorText; + ItemBoldBox.IsChecked = bold && value?.Bold == true; + } + + /// Stores the shown item; false when a color cannot be read, so the page can say so. + private bool KeepItem() + { + if (shownItem is null) return true; + string? foreground = ColorInput(ItemForegroundBox.Text), background = ColorInput(ItemBackgroundBox.Text); + if (foreground == "" || background == "") return false; + var (canForeground, canBackground, canBold) = FontsAndColorsSettings.Supports(shownItem); + var item = new ColorItem(canForeground ? foreground : null, canBackground ? background : null, canBold && ItemBoldBox.IsChecked == true); + if (item == new ColorItem()) itemDrafts.Remove(shownItem); else itemDrafts[shownItem] = item; + return true; + } + + /// Null for Default (or empty), #RRGGBB for a color, and "" for text that is not a color. + private static string? ColorInput(string text) + { + if (string.IsNullOrWhiteSpace(text) || string.Equals(text.Trim(), DefaultColorText, StringComparison.OrdinalIgnoreCase)) return null; + return FontsAndColorsSettings.ParseColor(text) is { } color ? FontsAndColorsSettings.Hex(color) : ""; + } + + private void FontCategoryChanged(object sender, SelectionChangedEventArgs e) + { + if (loadingFonts || FontCategoryBox.SelectedIndex < 0) return; + loadingFonts = true; + try { ShowFontCategory(FontCategoryBox.SelectedIndex); } + finally { loadingFonts = false; } + UpdateFontSample(); + } + + private void DisplayItemChanged(object sender, SelectionChangedEventArgs e) + { + if (loadingFonts || DisplayItemsBox.SelectedItem is not string item) return; + loadingFonts = true; + try { ShowItem(item); } + finally { loadingFonts = false; } + UpdateFontSample(); + } + + private void FontSampleInputChanged(object sender, RoutedEventArgs e) { if (!loadingFonts) Dispatcher.BeginInvoke(UpdateFontSample); } + private void ItemColorInputChanged(object sender, RoutedEventArgs e) { if (!loadingFonts) Dispatcher.BeginInvoke(UpdateFontSample); } + + /// The sample shows the chosen font and size, and for Text Editor the colors of the selected item. + internal void UpdateFontSample() + { + if (fontCategory < 0) return; + try { FontSample.FontFamily = new FontFamily(string.IsNullOrWhiteSpace(FontNameBox.Text) ? "Segoe UI" : FontNameBox.Text.Trim()); } catch (ArgumentException) { } + if (FontsAndColorsSettings.ParseSize(FontSizeBox.Text) is { } size) FontSample.FontSize = FontsAndColorsSettings.Pixels(size); + var settings = fontCategory == 0 ? DraftSettings() : null; + string? item = fontCategory == 0 ? shownItem : null; + var plain = settings?.Item(FontsAndColorsSettings.PlainText) ?? new ColorItem("#000000", "#FFFFFF"); + var shown = item is not null && settings is not null ? settings.Item(item) : plain; + FontSample.Foreground = FontsAndColorsSettings.Brush(item == FontsAndColorsSettings.SelectedText ? plain.Foreground : shown.Foreground ?? plain.Foreground); + FontSampleBorder.Background = item == FontsAndColorsSettings.SelectedText ? FontsAndColorsSettings.SelectionBrush(shown.Background) : FontsAndColorsSettings.Brush(plain.Background); + FontSample.FontWeight = shown.Bold ? FontWeights.Bold : FontWeights.Normal; + } + + /// The page as settings, without checking; readable colors only. + private FontsAndColorsSettings DraftSettings() + { + var drafts = new Dictionary(itemDrafts); + if (shownItem is not null) + { + string? foreground = ColorInput(ItemForegroundBox.Text), background = ColorInput(ItemBackgroundBox.Text); + drafts[shownItem] = new ColorItem(foreground is "" ? null : foreground, background is "" ? null : background, ItemBoldBox.IsChecked == true); + } + return new FontsAndColorsSettings(EditorItems: drafts); + } + + private void ResetFontCategory(object sender, RoutedEventArgs e) => ResetFonts(allCategories: false); + private void ResetAllFontCategories(object sender, RoutedEventArgs e) => ResetFonts(allCategories: true); + + internal void ResetFonts(bool allCategories) + { + var defaults = new FontsAndColorsSettings(); + int category = Math.Max(0, fontCategory); + string[] names = [defaults.EditorFontName, defaults.GridFontName, defaults.TextResultsFontName]; + double[] sizes = [defaults.EditorPoints, defaults.GridPoints, defaults.TextResultsPoints]; + loadingFonts = true; + try + { + for (int i = 0; i < 3; i++) + { + if (!allCategories && i != category) continue; + fontNames[i] = names[i]; fontSizes[i] = SizeText(sizes[i]); + if (i == 0) itemDrafts.Clear(); + } + fontCategory = -1; shownItem = null; + ShowFontCategory(category); + ShowItem(DisplayItemsBox.SelectedItem as string ?? FontsAndColorsSettings.PlainText); + } + finally { loadingFonts = false; } + FontsError.Visibility = Visibility.Collapsed; + UpdateFontSample(); + } + + /// The page as settings for OK, or null after pointing at what is wrong. Sizes are 6 to 72 points; a font must be installed. + private FontsAndColorsSettings? ReadFontsAndColors() + { + KeepFontCategory(); + if (!KeepItem()) return FontsRejected($"Enter a color name from the list or #RRGGBB for {shownItem}.", fontCategory, ItemForegroundBox.IsEnabled && ColorInput(ItemForegroundBox.Text) == "" ? ItemForegroundBox : ItemBackgroundBox); + var installed = new HashSet(FontNameBox.Items.OfType(), StringComparer.OrdinalIgnoreCase); + var sizes = new double[3]; + for (int i = 0; i < 3; i++) + { + if (FontsAndColorsSettings.ParseSize(fontSizes[i]) is not { } size) + return FontsRejected($"Enter a size from {FontsAndColorsSettings.MinimumSize} to {FontsAndColorsSettings.MaximumSize} points for {FontsAndColorsSettings.Categories[i]}.", i, FontSizeBox); + sizes[i] = size; + if (!installed.Contains(fontNames[i])) return FontsRejected($"The font \"{fontNames[i]}\" is not installed. Choose a font from the list for {FontsAndColorsSettings.Categories[i]}.", i, FontNameBox); + } + var defaults = new FontsAndColorsSettings(); + // Values equal to the defaults are not stored, so a later change of a PGMS default reaches them. + return new FontsAndColorsSettings( + Same(fontNames[0], defaults.EditorFontName) ? null : fontNames[0], sizes[0] == defaults.EditorPoints ? 0 : sizes[0], + itemDrafts.Count == 0 ? null : new Dictionary(itemDrafts), + Same(fontNames[1], defaults.GridFontName) ? null : fontNames[1], sizes[1] == defaults.GridPoints ? 0 : sizes[1], + Same(fontNames[2], defaults.TextResultsFontName) ? null : fontNames[2], sizes[2] == defaults.TextResultsPoints ? 0 : sizes[2]); + } + + private static bool Same(string a, string b) => string.Equals(a, b, StringComparison.OrdinalIgnoreCase); + + private FontsAndColorsSettings? FontsRejected(string message, int category, Control wrong) + { + FontsAndColorsPage.IsSelected = true; + if (FontCategoryBox.SelectedIndex != category) FontCategoryBox.SelectedIndex = category; + FontsError.Text = message; FontsError.Visibility = Visibility.Visible; + System.Windows.Input.FocusManager.SetFocusedElement(this, wrong); + wrong.Focus(); + return null; + } +} diff --git a/src/PGMS.Desktop/OptionsDialog.Keyboard.cs b/src/PGMS.Desktop/OptionsDialog.Keyboard.cs new file mode 100644 index 0000000..94888eb --- /dev/null +++ b/src/PGMS.Desktop/OptionsDialog.Keyboard.cs @@ -0,0 +1,125 @@ +using System.Windows; +using System.Windows.Controls; +using System.Windows.Input; + +namespace PGMS.Desktop; + +/// Environment ▸ Keyboard (PGMS-072, M1106), the Visual Studio page SSMS 22.11 shows: filter, commands, the shortcuts of the selected one, +/// Press shortcut keys, Assign, Remove, "Shortcut currently used by" and Reset. Changes are written on OK. +public partial class OptionsDialog +{ + private IReadOnlyList keyboardCommands = []; + /// Command name → assigned shortcut, the working copy written on OK. + private readonly Dictionary keyboardShortcuts = new(StringComparer.OrdinalIgnoreCase); + private string? pressedGesture; + + private void LoadKeyboard(EnvironmentOptions.Document document, IReadOnlyList commands) + { + keyboardCommands = commands; + foreach (var (name, gesture) in document.CustomShortcuts) if (!string.IsNullOrWhiteSpace(gesture)) keyboardShortcuts[name] = gesture.Trim(); + FillKeyboardCommands(); + } + + /// Selects a page by its header ("Keyboard"); Customize ▸ Keyboard… opens there. + internal void SelectPage(string header) + { + foreach (var category in Pages.Items.OfType()) + foreach (var page in category.Items.OfType().Prepend(category)) + if (string.Equals(page.Header as string, header, StringComparison.OrdinalIgnoreCase) && page.Items.Count == 0) { page.IsSelected = true; return; } + } + + internal IReadOnlyList ShownCommands => KeyboardCommandList.Items.Cast().ToList(); + internal IReadOnlyDictionary AssignedShortcuts => keyboardShortcuts; + + private void FillKeyboardCommands() + { + string filter = KeyboardFilterBox.Text.Trim(); + var selected = KeyboardCommandList.SelectedItem as string; + KeyboardCommandList.ItemsSource = keyboardCommands.Select(c => c.Name).Where(n => filter.Length == 0 || n.Contains(filter, StringComparison.OrdinalIgnoreCase)).ToList(); + if (selected is not null && KeyboardCommandList.Items.Contains(selected)) KeyboardCommandList.SelectedItem = selected; + else if (KeyboardCommandList.Items.Count > 0) KeyboardCommandList.SelectedIndex = 0; + ShowKeyboardCommand(); + } + + private void KeyboardFilterChanged(object sender, TextChangedEventArgs e) => FillKeyboardCommands(); + private void KeyboardCommandChanged(object sender, SelectionChangedEventArgs e) => ShowKeyboardCommand(); + + /// The shortcuts of a command as the page lists them: the assigned one, then the one PGMS gives it. + internal string ShortcutsOf(string name) + { + var parts = new List(); + if (keyboardShortcuts.TryGetValue(name, out var assigned)) parts.Add(assigned); + if (keyboardCommands.FirstOrDefault(c => c.Name == name) is { DefaultShortcut.Length: > 0 } command) parts.Add(command.DefaultShortcut + " (PGMS)"); + return string.Join("; ", parts); + } + + private void ShowKeyboardCommand() + { + var name = KeyboardCommandList.SelectedItem as string; + KeyboardCurrentBox.Text = name is null ? "" : ShortcutsOf(name); + KeyboardRemoveButton.IsEnabled = name is not null && keyboardShortcuts.ContainsKey(name); + KeyboardAssignButton.IsEnabled = name is not null && pressedGesture is not null; + } + + private void KeyboardGestureKeyDown(object sender, KeyEventArgs e) + { + var key = e.Key == Key.System ? e.SystemKey : e.Key; + if (key is Key.Tab && Keyboard.Modifiers is ModifierKeys.None or ModifierKeys.Shift) return; // Tab leaves the box + e.Handled = true; + if (key is Key.Back or Key.Delete && Keyboard.Modifiers == ModifierKeys.None) { PressGesture(null); return; } + PressGesture(KeyboardMap.GestureName(key, Keyboard.Modifiers)); + } + + /// Takes a shortcut as if its keys were pressed in the box (also used by tests); null clears it. + internal void PressGesture(string? gesture) + { + pressedGesture = gesture; + KeyboardGestureBox.Text = gesture ?? ""; + KeyboardUsedByBox.Text = gesture is null ? "" : UsedBy(gesture); + ShowKeyboardCommand(); + } + + /// Which commands already answer to a shortcut: assigned ones, then PGMS ones (exact text, as the menus show them). + internal string UsedBy(string gesture) + { + var users = keyboardShortcuts.Where(p => string.Equals(p.Value, gesture, StringComparison.OrdinalIgnoreCase)).Select(p => p.Key) + .Concat(keyboardCommands.Where(c => c.DefaultShortcut.Equals(gesture, StringComparison.OrdinalIgnoreCase)).Select(c => c.Name + " (PGMS)")) + .Distinct().ToList(); + return string.Join("; ", users); + } + + private void KeyboardAssign(object sender, RoutedEventArgs e) => AssignShortcut(); + + /// Assigns the pressed shortcut to the selected command, taking it from another command it was assigned to. + internal bool AssignShortcut() + { + if (KeyboardCommandList.SelectedItem is not string name || pressedGesture is not { } gesture) return false; + foreach (var other in keyboardShortcuts.Where(p => string.Equals(p.Value, gesture, StringComparison.OrdinalIgnoreCase)).Select(p => p.Key).ToList()) keyboardShortcuts.Remove(other); + keyboardShortcuts[name] = gesture; + KeyboardUsedByBox.Text = UsedBy(gesture); + ShowKeyboardCommand(); + return true; + } + + private void KeyboardRemove(object sender, RoutedEventArgs e) + { + if (KeyboardCommandList.SelectedItem is string name && keyboardShortcuts.Remove(name)) ShowKeyboardCommand(); + } + + /// Tests: Remove for the selected command. + internal void RemoveSelectedShortcut() => KeyboardRemove(this, new RoutedEventArgs()); + + private void KeyboardReset(object sender, RoutedEventArgs e) + { + keyboardShortcuts.Clear(); + if (pressedGesture is { } gesture) KeyboardUsedByBox.Text = UsedBy(gesture); + ShowKeyboardCommand(); + } + + /// Tests: selects a command in the list (the filter is cleared when it hides it). + internal void SelectKeyboardCommand(string name) + { + if (!KeyboardCommandList.Items.Contains(name)) KeyboardFilterBox.Text = ""; + KeyboardCommandList.SelectedItem = name; + } +} diff --git a/src/PGMS.Desktop/OptionsDialog.Search.cs b/src/PGMS.Desktop/OptionsDialog.Search.cs new file mode 100644 index 0000000..d0827f3 --- /dev/null +++ b/src/PGMS.Desktop/OptionsDialog.Search.cs @@ -0,0 +1,65 @@ +using System.Windows; +using System.Windows.Controls; + +namespace PGMS.Desktop; + +/// One page of Tools ▸ Options for Search (M1114): its path in the tree ("Environment > Fonts and Colors") and the captions of its settings. +public sealed record OptionsPageIndex(string Path, IReadOnlyList Settings); + +public partial class OptionsDialog +{ + /// Every leaf page with the captions shown on it (check boxes, labels, group titles, short texts), read by showing each page in turn + /// without displaying the dialog. Search lists them as SSMS 22.11 lists settings next to commands (observed in M1114). + internal IReadOnlyList SearchIndex() + { + var result = new List(); + foreach (var (path, page) in LeafPages()) + { + page.IsSelected = true; + var captions = new List(); + Collect(Content as DependencyObject, captions); + result.Add(new(path, captions.Distinct(StringComparer.OrdinalIgnoreCase).ToList())); + } + return result; + } + + /// Selects a page by its path from ; false when there is no such page. + internal bool SelectPagePath(string path) + { + foreach (var (pagePath, page) in LeafPages()) + if (string.Equals(pagePath, path, StringComparison.OrdinalIgnoreCase)) { page.IsSelected = true; return true; } + return false; + } + + private IEnumerable<(string Path, TreeViewItem Page)> LeafPages() + { + foreach (var category in Pages.Items.OfType()) + { + string name = FeatureSearch.Text(category.Header); + if (category.Items.Count == 0) { yield return (name, category); continue; } + foreach (var page in category.Items.OfType()) yield return (name + " > " + FeatureSearch.Text(page.Header), page); + } + } + + /// Captions of the visible part of the page: the tree, buttons and long explanations are left out. + private void Collect(DependencyObject? node, List captions) + { + if (node is null || node == Pages || node is Button) return; + if (node is UIElement { Visibility: not Visibility.Visible }) return; + string? text = node switch + { + CheckBox { Content: string s } => s, + RadioButton { Content: string s } => s, + Label { Content: string s } => s, + GroupBox { Header: string s } => s, + TextBlock t when t.Parent is not (CheckBox or RadioButton or Label or Button) => t.Text, + _ => null, + }; + if (text is not null) + { + string clean = FeatureSearch.Text(text).Trim().TrimEnd(':').Trim(); + if (clean.Length is > 1 and <= 80) captions.Add(clean); + } + foreach (var child in LogicalTreeHelper.GetChildren(node).OfType()) Collect(child, captions); + } +} diff --git a/src/PGMS.Desktop/OptionsDialog.xaml b/src/PGMS.Desktop/OptionsDialog.xaml index b603922..38cbfb9 100644 --- a/src/PGMS.Desktop/OptionsDialog.xaml +++ b/src/PGMS.Desktop/OptionsDialog.xaml @@ -1,10 +1,16 @@ - + - + + + + + + + @@ -18,14 +24,22 @@ + - + - + + + + + + @@ -36,7 +50,7 @@ - + @@ -48,8 +62,8 @@ @@ -64,14 +78,111 @@