diff --git a/README.md b/README.md
index 43cb58b..a388d30 100644
--- a/README.md
+++ b/README.md
@@ -20,6 +20,8 @@ English | [Português (Brasil)](README.pt-BR.md)
See your schema the way you see it in SSMS. Add tables and their related tables, drag one column onto another to create a foreign key, change columns and primary keys inside the diagram, and let **Arrange Tables** lay everything out. Every change to the database is shown as a SQL script for review first. Diagrams are saved on the server, in a small `pgms` schema that PGMS asks permission to create.
+Diagrams also show each table's **indexes** (GIN, GiST, BRIN and operator classes such as `gin_trgm_ops`, in a section closed by default) and warn about foreign keys that no index serves. Tables, columns and relationships can carry **descriptions**, stored as PostgreSQL `COMMENT ON`. **Export for AI…** writes the diagram as Markdown (columns, keys, relationships, indexes and descriptions) to give an AI agent before it writes SQL; an optional `pgms.diagram_markdown(name)` function returns the same text inside the database. See [Using diagrams with AI agents](docs/en/user-guide.md#using-diagrams-with-ai-agents).
+
### Visual query designer

diff --git a/README.pt-BR.md b/README.pt-BR.md
index 535e818..9f968fb 100644
--- a/README.pt-BR.md
+++ b/README.pt-BR.md
@@ -20,6 +20,8 @@
Veja o seu schema como no SSMS. Adicione tabelas e as tabelas relacionadas, arraste uma coluna sobre outra para criar uma chave estrangeira, altere colunas e chaves primárias dentro do diagrama e deixe o **Arrange Tables** organizar tudo. Toda alteração no banco aparece antes como script SQL para revisão. Os diagramas ficam salvos no servidor, num pequeno schema `pgms` que o PGMS pede permissão para criar.
+O diagrama também mostra os **índices** de cada tabela (GIN, GiST, BRIN e classes de operadores como `gin_trgm_ops`, numa seção recolhida por padrão) e avisa das chaves estrangeiras sem índice. Tabelas, colunas e relações podem ter **descrições**, gravadas como `COMMENT ON` do PostgreSQL. **Export for AI…** gera o diagrama em Markdown (colunas, chaves, relações, índices e descrições) para entregar a um agente de IA antes de ele escrever SQL; a função opcional `pgms.diagram_markdown(nome)` devolve o mesmo texto dentro do banco. Veja [Usando diagramas com agentes de IA](docs/pt-BR/user-guide.md#usando-diagramas-com-agentes-de-ia).
+
### Query Designer visual

diff --git a/docs/en/release-notes.md b/docs/en/release-notes.md
index f3816bd..50bf414 100644
--- a/docs/en/release-notes.md
+++ b/docs/en/release-notes.md
@@ -8,7 +8,8 @@ Fifth public pre-release of PGMS. It is an alpha for evaluation with synthetic/d
These changes are on `main` and will be part of the next pre-release; the downloads below are still 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 (format 2) 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.
+- **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.
## What changed since v0.1.0-alpha.4
diff --git a/docs/en/user-guide.md b/docs/en/user-guide.md
index d4f9027..5e00181 100644
--- a/docs/en/user-guide.md
+++ b/docs/en/user-guide.md
@@ -20,7 +20,7 @@ Identity and sequence operations distinguish configured START from RESTART. A re
In Object Explorer, right-click **Database Diagrams** under a database and choose **New Database Diagram**. The first time, PGMS asks to create its support objects (schema `pgms`). Add tables with **Add Table** or **Add Related Tables**, drag a column onto another to create a foreign key, and use **Arrange Tables** to lay them out. Saving shows the SQL script of any change to the database for review.
-**Indexes.** Each table shows an **Indexes** section below its columns, closed by default so diagrams laid out before keep their spacing: the header gives the count and the methods other than b-tree (for example `Indexes (3) · GIN`), and its tooltip lists every index. Click the header to show one row per index: name, method when it is not b-tree (Hash, GIN, GiST, SP-GiST, BRIN), key columns or expressions, the operator class when it is not the default (such as `gin_trgm_ops`, `jsonb_path_ops` or `text_pattern_ops`), `INCLUDE` columns, and UNIQUE, EXCLUDE, partial or invalid. The row tooltip has the predicate of a partial index and the full `CREATE INDEX`. A gold key marks the primary key, a silver key a unique or exclusion constraint, and a tree a plain index. A warning triangle in the title marks a table with a foreign key that no index serves, by the same rule as **Find Unindexed Foreign Keys…**; click it, or use the item of the table menu, to open that window. **Show Indexes** in the diagram menu turns the sections and the warning off and on for that diagram, and **Refresh** reads the tables and their indexes again. The section is read only: create or change indexes in **Indexes/Keys…** (double-click an index row) and the other dialogs. Every save writes the indexes of each table, read from the catalog inside the save transaction, into the diagram definition (`pgms.diagrams.definition`, format 2), so tools and AI agents that read the diagram see them; changes made only in the database do not mark the diagram as changed and reach the definition on its next save. Diagrams saved by earlier versions open as they were and are written in the new format by their next save. SSMS 22.11 shows no indexes in a diagram; this section is a PGMS addition.
+**Indexes.** Each table shows an **Indexes** section below its columns, closed by default so diagrams laid out before keep their spacing: the header gives the count and the methods other than b-tree (for example `Indexes (3) · GIN`), and its tooltip lists every index. Click the header to show one row per index: name, method when it is not b-tree (Hash, GIN, GiST, SP-GiST, BRIN), key columns or expressions, the operator class when it is not the default (such as `gin_trgm_ops`, `jsonb_path_ops` or `text_pattern_ops`), `INCLUDE` columns, and UNIQUE, EXCLUDE, partial or invalid. The row tooltip has the predicate of a partial index and the full `CREATE INDEX`. A gold key marks the primary key, a silver key a unique or exclusion constraint, and a tree a plain index. A warning triangle in the title marks a table with a foreign key that no index serves, by the same rule as **Find Unindexed Foreign Keys…**; click it, or use the item of the table menu, to open that window. **Show Indexes** in the diagram menu turns the sections and the warning off and on for that diagram, and **Refresh** reads the tables and their indexes again. The section is read only: create or change indexes in **Indexes/Keys…** (double-click an index row) and the other dialogs. Every save writes the indexes of each table, read from the catalog inside the save transaction, into the diagram definition (`pgms.diagrams.definition`), so tools and AI agents that read the diagram see them; changes made only in the database do not mark the diagram as changed and reach the definition on its next save. Diagrams saved by earlier versions open as they were and are written in the new format by their next save. SSMS 22.11 shows no indexes in a diagram; this section is a PGMS addition.
## Query Designer
@@ -55,6 +55,24 @@ PGMS never loads, creates or configures the extension. The server needs `shared_
Filters (database, user, SQL text, minimum calls) and ordering run on the server before a 1,000-row limit. Clicking the Total, Mean, Max, Calls, Rows or metric headers reloads in that order; other headers sort only the loaded rows. **Window** shows cumulative values since the last reset, values since a saved baseline, or the last 5/15/60 minutes, computed by subtracting an earlier reading; sliding windows sample only while the window is open, and minimum/maximum are not available for a window. A top-N chart beside the grid follows the applied order. **Show Plan** opens the selected statement in a new query tab with `EXPLAIN (GENERIC_PLAN)`, without executing it or binding `$n` values. **Reset Selected** and **Reset All** call `pg_stat_statements_reset` after a confirmation whose default is No; the server decides whether the role may reset. Auto-refresh is optional and starts off. Filters, chart choices and baselines are stored per connection target in the PGMS state folder, without passwords or SQL results.
+**Descriptions.** A table, a column or a relationship can have a description: it is the PostgreSQL `COMMENT ON` of that object, so every tool that reads the catalog sees it. A small page icon marks a described table (in its title), column (at the end of its row) and relationship (on its line), and its tooltip shows the text. Right-click and choose **Table Description…**, **Column Description…** or **Relationship Description…**, or click the icon, to open **Description Property**: free text of several lines, up to 4 KiB of UTF-8. The change stays in the diagram, the table shows `*`, and **Save** applies it with `COMMENT ON` after the script review, like every change made in a diagram; **Generate Change Script…** shows it before. A change that is only descriptions does not lock the table: PGMS checks that the table, column or key is still the one the diagram read (by OID and name) and that nobody changed that description in the meantime. PostgreSQL lets only the owner of a table change its descriptions. When you do not own it, Save keeps the description only in the diagram, marked as not applied (an orange icon), and then shows the script to send to the owner; **Script Unapplied Descriptions…** in the table menu shows it again, and once the owner runs it the mark goes away. **Description Property** can also put that text back in the box or discard it. Each save writes a copy of the descriptions into the diagram definition (format 3), with the time the catalog was read. When the diagram opens or you choose **Refresh**, the catalog wins: if a description changed in the database since the save, the diagram shows the new text with an orange icon whose tooltip has the old copy, and the next save updates the copy. In SSMS 22.11, descriptions are edited in the Properties window of the diagram and saved as `MS_Description`; the icons, the copy and the export below are PGMS additions.
+
+## Using diagrams with AI agents
+
+An AI agent that writes SQL without seeing the model guesses column names and misses the indexes. A diagram with descriptions is that model, in three forms:
+
+- **The catalog.** Descriptions are `COMMENT ON`, so an agent connected to the database (through psql, an MCP server of your choice or any client) reads them with `obj_description` and `col_description`, or `\d+` in psql.
+- **Export for AI…** in the diagram menu writes the tables of the diagram as Markdown: an instruction for the agent at the top, then each table with its description, columns (type, null, default, description), keys and checks, foreign keys (with a note when no index serves one), the tables that reference it, and its indexes with their full definition, including the method and operator class (such as `gin_trgm_ops`). Tables and items come in a fixed order, so the same database gives the same text. **Copy** puts it on the clipboard and **Save As…** writes a `.md` file, ready for a system prompt, a `CLAUDE.md` or an `AGENTS.md`. The export reads the database as it is now: unsaved changes of the diagram are not in it.
+- **`pgms.diagram_markdown(name)`**, optional. **AI Export Function…** in the diagram menu, or the box in **Install Diagram Support** (unchecked by default), creates this function in the schema `pgms` after you review its script. `SELECT pgms.diagram_markdown('Sales');` returns the same Markdown as the export, read from the catalog, for the saved diagram with that name, or NULL when there is none. It is read only, runs with the privileges of the caller, who needs `SELECT` on `pgms.diagrams`, and the same dialog removes it.
+
+The saved diagram itself is the JSON in `pgms.diagrams.definition`: tables, positions, indexes and the copy of the descriptions, with `"applied": false` on descriptions that are not applied in the database.
+
+An example of an instruction for the system prompt of an agent:
+
+> Before writing SQL for the Sales database, read `docs/database-model.md` (exported from PGMS) or run `SELECT pgms.diagram_markdown('Sales');`. Use only the tables and columns listed there, with the names as written. If something you need is not there, ask instead of guessing a name. Check the indexes before filtering, joining or sorting large tables.
+
+PGMS has no MCP server of its own.
+
## Backup and restore
Choose compatible PostgreSQL tools and a new output file/directory. Custom, tar, plain SQL and directory formats support the documented content choices. Restore uses an existing target database; compatible objects/roles and permissions must already exist where required. Ownership and privileges are explicit choices. Directory backup supports parallel dump; restore remains serial. Global operations cover roles/memberships/tablespaces, not a physical cluster backup.
diff --git a/docs/pt-BR/release-notes.md b/docs/pt-BR/release-notes.md
index 649e1cf..131f97e 100644
--- a/docs/pt-BR/release-notes.md
+++ b/docs/pt-BR/release-notes.md
@@ -8,7 +8,8 @@ Quinta pré-release pública do PGMS. É uma alpha para avaliação com dados si
Estas mudanças estão no `main` e farão parte da próxima pré-release; os downloads abaixo continuam sendo da 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 (formato 2) 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.
+- **Í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.
## O que mudou desde a v0.1.0-alpha.4
diff --git a/docs/pt-BR/user-guide.md b/docs/pt-BR/user-guide.md
index c167b35..00798be 100644
--- a/docs/pt-BR/user-guide.md
+++ b/docs/pt-BR/user-guide.md
@@ -20,7 +20,7 @@ Identity e sequences distinguem START configurado de RESTART. Reiniciar pode rep
No Object Explorer, clique com o botão direito em **Database Diagrams**, dentro de um banco, e escolha **New Database Diagram**. Na primeira vez, o PGMS pede para criar seus objetos de suporte (schema `pgms`). Adicione tabelas com **Add Table** ou **Add Related Tables**, arraste uma coluna sobre outra para criar uma chave estrangeira e use **Arrange Tables** para organizar. Ao salvar, o PGMS mostra o script SQL de qualquer alteração no banco para revisão.
-**Índices.** Cada tabela mostra uma seção **Indexes** abaixo das colunas, recolhida por padrão para que diagramas já organizados mantenham o espaçamento: o cabeçalho traz a quantidade e os métodos que não são b-tree (por exemplo `Indexes (3) · GIN`), e a dica dele lista todos os índices. Clique no cabeçalho para ver uma linha por índice: nome, método quando não é b-tree (Hash, GIN, GiST, SP-GiST, BRIN), colunas ou expressões da chave, a classe de operadores quando não é a padrão (como `gin_trgm_ops`, `jsonb_path_ops` ou `text_pattern_ops`), colunas `INCLUDE` e UNIQUE, EXCLUDE, parcial (partial) ou inválido (invalid). A dica da linha traz o predicado de um índice parcial e o `CREATE INDEX` completo. Uma chave dourada marca a chave primária, uma chave prateada uma constraint UNIQUE ou de exclusão, e uma árvore um índice comum. Um triângulo de aviso no título marca a tabela com chave estrangeira que nenhum índice atende, pela mesma regra de **Find Unindexed Foreign Keys…**; clique nele, ou use o item do menu da tabela, para abrir essa janela. **Show Indexes**, no menu do diagrama, liga e desliga as seções e o aviso naquele diagrama, e **Refresh** lê de novo as tabelas e seus índices. A seção é só leitura: crie ou altere índices em **Indexes/Keys…** (duplo clique numa linha de índice) e nos outros diálogos. Toda gravação escreve os índices de cada tabela, lidos do catálogo dentro da transação da gravação, na definição do diagrama (`pgms.diagrams.definition`, formato 2), para que ferramentas e agentes de IA que leem o diagrama os vejam; mudanças feitas só no banco não marcam o diagrama como alterado e chegam à definição na próxima gravação. Diagramas salvos por versões anteriores abrem como estavam e passam ao formato novo na próxima gravação. O SSMS 22.11 não mostra índices no diagrama; esta seção é um acréscimo do PGMS.
+**Índices.** Cada tabela mostra uma seção **Indexes** abaixo das colunas, recolhida por padrão para que diagramas já organizados mantenham o espaçamento: o cabeçalho traz a quantidade e os métodos que não são b-tree (por exemplo `Indexes (3) · GIN`), e a dica dele lista todos os índices. Clique no cabeçalho para ver uma linha por índice: nome, método quando não é b-tree (Hash, GIN, GiST, SP-GiST, BRIN), colunas ou expressões da chave, a classe de operadores quando não é a padrão (como `gin_trgm_ops`, `jsonb_path_ops` ou `text_pattern_ops`), colunas `INCLUDE` e UNIQUE, EXCLUDE, parcial (partial) ou inválido (invalid). A dica da linha traz o predicado de um índice parcial e o `CREATE INDEX` completo. Uma chave dourada marca a chave primária, uma chave prateada uma constraint UNIQUE ou de exclusão, e uma árvore um índice comum. Um triângulo de aviso no título marca a tabela com chave estrangeira que nenhum índice atende, pela mesma regra de **Find Unindexed Foreign Keys…**; clique nele, ou use o item do menu da tabela, para abrir essa janela. **Show Indexes**, no menu do diagrama, liga e desliga as seções e o aviso naquele diagrama, e **Refresh** lê de novo as tabelas e seus índices. A seção é só leitura: crie ou altere índices em **Indexes/Keys…** (duplo clique numa linha de índice) e nos outros diálogos. Toda gravação escreve os índices de cada tabela, lidos do catálogo dentro da transação da gravação, na definição do diagrama (`pgms.diagrams.definition`), para que ferramentas e agentes de IA que leem o diagrama os vejam; mudanças feitas só no banco não marcam o diagrama como alterado e chegam à definição na próxima gravação. Diagramas salvos por versões anteriores abrem como estavam e passam ao formato novo na próxima gravação. O SSMS 22.11 não mostra índices no diagrama; esta seção é um acréscimo do PGMS.
## Query Designer
@@ -55,6 +55,24 @@ O PGMS nunca carrega, cria ou configura a extensão. O servidor precisa de `shar
Filtros (banco, usuário, texto SQL, mínimo de chamadas) e ordenação rodam no servidor antes do limite de 1.000 linhas. Clicar nos cabeçalhos Total, Mean, Max, Calls, Rows ou de métricas recarrega nessa ordem; os demais cabeçalhos ordenam só as linhas carregadas. **Window** mostra valores acumulados desde o último reset, desde uma linha de base gravada, ou dos últimos 5/15/60 minutos, calculados subtraindo uma leitura anterior; as janelas deslizantes só amostram enquanto a janela está aberta, e mínimo/máximo não existem para uma janela. Um gráfico top-N ao lado da grade segue a ordem aplicada. **Show Plan** abre o statement selecionado numa nova aba de consulta com `EXPLAIN (GENERIC_PLAN)`, sem executá-lo nem vincular valores aos `$n`. **Reset Selected** e **Reset All** chamam `pg_stat_statements_reset` depois de uma confirmação com Não como padrão; o servidor decide se a role pode zerar. O auto-refresh é opcional e começa desligado. Filtros, opções do gráfico e linhas de base ficam gravados por alvo de conexão na pasta de estado do PGMS, sem senhas nem resultados SQL.
+**Descrições.** Tabela, coluna e relação podem ter descrição: é o `COMMENT ON` do objeto no PostgreSQL, então qualquer ferramenta que lê o catálogo a enxerga. Um pequeno ícone de página marca a tabela descrita (no título), a coluna (no fim da linha) e a relação (na linha dela), e a dica mostra o texto. Clique com o botão direito e escolha **Table Description…**, **Column Description…** ou **Relationship Description…**, ou clique no ícone, para abrir **Description Property**: texto livre de várias linhas, até 4 KiB em UTF-8. A mudança fica no diagrama, a tabela mostra `*`, e **Save** a aplica com `COMMENT ON` depois da revisão do script, como toda mudança feita no diagrama; **Generate Change Script…** mostra antes. Uma mudança que é só de descrições não bloqueia a tabela: o PGMS confere que a tabela, a coluna ou a chave ainda é a que o diagrama leu (pelo OID e pelo nome) e que ninguém mudou aquela descrição nesse meio-tempo. O PostgreSQL só deixa o dono da tabela mudar as descrições dela. Quando você não é o dono, Save guarda a descrição só no diagrama, marcada como não aplicada (ícone laranja), e depois mostra o script para enviar ao dono; **Script Unapplied Descriptions…** no menu da tabela mostra de novo, e quando o dono roda o script a marca some. **Description Property** também pode trazer esse texto de volta para a caixa ou descartá-lo. Cada gravação escreve uma cópia das descrições na definição do diagrama (formato 3), com o horário em que o catálogo foi lido. Ao abrir o diagrama ou escolher **Refresh**, o catálogo prevalece: se uma descrição mudou no banco depois da gravação, o diagrama mostra o texto novo com um ícone laranja cuja dica traz a cópia antiga, e a próxima gravação atualiza a cópia. No SSMS 22.11 as descrições são editadas na janela Properties do diagrama e gravadas como `MS_Description`; os ícones, a cópia e a exportação abaixo são acréscimos do PGMS.
+
+## Usando diagramas com agentes de IA
+
+Um agente de IA que escreve SQL sem ver a modelagem chuta nome de coluna e não enxerga os índices. Um diagrama com descrições é essa modelagem, em três formas:
+
+- **O catálogo.** As descrições são `COMMENT ON`, então um agente conectado ao banco (por psql, por um servidor MCP de sua escolha ou por qualquer cliente) as lê com `obj_description` e `col_description`, ou com `\d+` no psql.
+- **Export for AI…** no menu do diagrama escreve as tabelas do diagrama em Markdown: uma instrução para o agente no topo e, para cada tabela, a descrição, as colunas (tipo, nulidade, default, descrição), chaves e checks, chaves estrangeiras (com aviso quando nenhum índice atende a chave), as tabelas que a referenciam e os índices com a definição completa, incluindo método e classe de operadores (como `gin_trgm_ops`). Tabelas e itens vêm em ordem fixa, então o mesmo banco gera o mesmo texto. **Copy** copia para a área de transferência e **Save As…** grava um arquivo `.md`, pronto para um system prompt, um `CLAUDE.md` ou um `AGENTS.md`. A exportação lê o banco como ele está agora: mudanças do diagrama ainda não gravadas não entram.
+- **`pgms.diagram_markdown(name)`**, opcional. **AI Export Function…** no menu do diagrama, ou a caixa em **Install Diagram Support** (desmarcada por padrão), cria essa função no schema `pgms` depois de você revisar o script. `SELECT pgms.diagram_markdown('Sales');` devolve o mesmo Markdown da exportação, lido do catálogo, para o diagrama gravado com esse nome, ou NULL quando não existe. É somente leitura, roda com os privilégios de quem chama, que precisa de `SELECT` em `pgms.diagrams`, e o mesmo diálogo a remove.
+
+O diagrama gravado em si é o JSON em `pgms.diagrams.definition`: tabelas, posições, índices e a cópia das descrições, com `"applied": false` nas descrições não aplicadas no banco.
+
+Um exemplo de instrução para o system prompt de um agente:
+
+> Antes de escrever SQL para o banco Sales, leia `docs/database-model.md` (exportado do PGMS) ou rode `SELECT pgms.diagram_markdown('Sales');`. Use só as tabelas e colunas listadas lá, com os nomes como estão escritos. Se faltar algo de que você precisa, pergunte em vez de chutar um nome. Confira os índices antes de filtrar, juntar ou ordenar tabelas grandes.
+
+O PGMS não tem servidor MCP próprio.
+
## Backup e restauração
Escolha ferramentas PostgreSQL compatíveis e arquivo/diretório de saída novo. Custom, tar, SQL e diretório oferecem as opções de conteúdo documentadas. Restore usa banco de destino existente; objetos/roles compatíveis e permissões precisam existir quando exigidos. Ownership e privilégios são escolhas explícitas. Backup em diretório oferece dump paralelo; restore continua serial. Operações globais cobrem roles/memberships/tablespaces, não backup físico do cluster.
diff --git a/src/PGMS.Desktop/DatabaseDiagramModel.cs b/src/PGMS.Desktop/DatabaseDiagramModel.cs
index 73d5e49..14dc4e9 100644
--- a/src/PGMS.Desktop/DatabaseDiagramModel.cs
+++ b/src/PGMS.Desktop/DatabaseDiagramModel.cs
@@ -55,6 +55,14 @@ public sealed class DiagramTableModel
public DiagramTableIndexes Catalog { get; set; } = DiagramTableIndexes.Empty;
/// The Indexes section is open; it starts closed (decisão do usuário, 11/11/2026).
public bool IndexesExpanded { get; set; }
+ /// The description of the table (COMMENT ON TABLE) as edited in the diagram (PGMS-045); Save writes it.
+ public string? Comment { get; set; }
+ /// The user owns the table (or is a member of its owner), so PostgreSQL lets them change its descriptions.
+ public bool CanComment { get; set; } = true;
+ /// The copy of the descriptions saved in the diagram, as the diagram was opened or last saved; null when the diagram had none (older format, or not saved).
+ public IReadOnlyList? SavedDescriptions { get; set; }
+ /// Descriptions the user could not apply (not the owner), kept in the diagram until the catalog has them or the user discards them.
+ public List Unapplied { get; } = [];
public DiagramTableModel(TableDesign design, double x, double y) { Original = design; X = x; Y = y; Reset(design); }
@@ -86,6 +94,7 @@ public IReadOnlyList VisibleColumns
public void Reset(TableDesign design)
{
Original = design;
+ Comment = design.Comment;
Columns.Clear(); Indexes.Clear(); ForeignKeys.Clear(); Checks.Clear();
Columns.AddRange(design.Columns);
Indexes.AddRange(design.Indexes.Select(i => new DesignerIndexRow(i)));
@@ -96,7 +105,7 @@ public void Reset(TableDesign design)
public TableDesign Current() => Original with
{
- Columns = Columns.ToArray(), Indexes = Indexes.Select(i => i.ToDesign()).ToArray(), ForeignKeys = ForeignKeys.Select(f => f.ToDesign()).ToArray(), Checks = Checks.Select(c => c.ToDesign()).ToArray()
+ Comment = Comment, Columns = Columns.ToArray(), Indexes = Indexes.Select(i => i.ToDesign()).ToArray(), ForeignKeys = ForeignKeys.Select(f => f.ToDesign()).ToArray(), Checks = Checks.Select(c => c.ToDesign()).ToArray()
};
public bool SchemaChanged => IsNew || Current().Fingerprint != baseline;
public string UniqueName(string name) => DesignerObjectKinds.UniqueName(name, Indexes, ForeignKeys, Checks);
diff --git a/src/PGMS.Desktop/DatabaseDiagramView.Descriptions.cs b/src/PGMS.Desktop/DatabaseDiagramView.Descriptions.cs
new file mode 100644
index 0000000..1bc12aa
--- /dev/null
+++ b/src/PGMS.Desktop/DatabaseDiagramView.Descriptions.cs
@@ -0,0 +1,205 @@
+using System.IO;
+using System.Windows;
+using System.Windows.Automation;
+using System.Windows.Controls;
+using System.Windows.Input;
+using System.Windows.Media;
+using System.Windows.Shapes;
+using Npgsql;
+using PGMS.PostgreSql;
+using Path = System.Windows.Shapes.Path;
+
+namespace PGMS.Desktop;
+
+/// The glyph of a description in the diagram: what it describes. Object is one of the DiagramDescription kinds; Name the column or foreign key.
+public sealed record DiagramDescriptionHit(DiagramTableModel Table, string Object, string? Name);
+
+/// Descriptions in the diagram and Export for AI (PGMS-045, docs/MARCO-M1062.md). In SSMS 22.11 the description of a table, column or relationship is
+/// edited in the Properties window ("Description Property") and saved with the diagram as MS_Description; the diagram itself shows no mark and its tooltips
+/// only names (pilotagem de 11/11/2026). In PostgreSQL the description is COMMENT ON, saved by Save after the script review, like every change in the diagram.
+/// The mark next to a described item, its tooltip, the copy kept in the diagram, Export for AI and the optional function are PGMS additions.
+public partial class DatabaseDiagramView
+{
+ private static readonly Brush NoteInk = Frozen("#6A6A6A"), NoteChangedInk = Frozen("#B85300"), NoteChangedFill = Frozen("#FFF1E0");
+
+ public enum DescriptionMark { None, Described, Differs, NotApplied }
+
+ internal Func? DescriptionPrompt { get; set; }
+ internal Func? ExportPrompt { get; set; }
+ internal Func? FunctionPrompt { get; set; }
+ /// Replaces the window with the script of descriptions not applied (intro, statements).
+ internal Action>? UnappliedScriptPrompt { get; set; }
+
+ private IReadOnlySet NotOwned() => tables.Where(t => !t.CanComment && !t.IsNew).Select(t => t.Original.Oid).ToHashSet();
+
+ /// The description an object of a table has in the diagram now (pending edits included).
+ public static string? DescriptionOf(DiagramTableModel table, string obj, string? name) => obj switch
+ {
+ DiagramDescription.TableObject => table.Comment,
+ DiagramDescription.ColumnObject => table.Column(name ?? "")?.Comment,
+ _ => table.ForeignKeys.FirstOrDefault(k => k.Name == name)?.Description is { Length: > 0 } text ? text : null
+ };
+
+ /// What the mark of an object says: described; not applied (kept in the diagram, the owner has to apply it); or changed in the database since
+ /// the diagram saved its copy (the diagram shows the catalog, the next save updates the copy).
+ public (DescriptionMark Mark, string Tip) MarkOf(DiagramTableModel table, string obj, string? name)
+ {
+ string? now = DescriptionOf(table, obj, name);
+ string Quote(string? text) => text is null ? "(no description)" : "“" + text + "”";
+ if (table.Unapplied.FirstOrDefault(u => u.Same(obj, name)) is { } pending)
+ return (DescriptionMark.NotApplied, (now ?? "No description in the database.") + $"\n\nNot applied in the database: only the owner of {table.Key} can change its descriptions. Kept in the diagram: "
+ + (pending.Text.Length == 0 ? "remove the description." : Quote(pending.Text)) + "\nUse Script Unapplied Descriptions… on the table to send the script to the owner.");
+ string? catalog = obj == DiagramDescription.ColumnObject ? table.Original.Columns.FirstOrDefault(c => c.Name == name)?.Comment : DiagramDescriptions.Text(table.Original, obj, name);
+ if (table.SavedDescriptions is { } saved && !table.IsNew)
+ {
+ var item = saved.FirstOrDefault(d => d.Same(obj, name));
+ // A copy not applied whose text the catalog now has was applied by the owner since: nothing differs.
+ string? copy = item is null ? null : item.Applied ? item.Text : (item.Text.Length == 0 ? null : item.Text) == catalog ? catalog : item.DatabaseText;
+ if (copy != catalog)
+ return (DescriptionMark.Differs, (now ?? "No description.") + "\n\nChanged in the database since the diagram was saved. The copy in the diagram had " + Quote(copy)
+ + ". The diagram shows the database; the next save updates its copy.");
+ }
+ return now is null ? (DescriptionMark.None, "") : (DescriptionMark.Described, now);
+ }
+
+ /// A small page with lines: grey for a description, orange when the diagram and the database differ or the description is not applied.
+ internal FrameworkElement NoteGlyph(DiagramDescriptionHit hit, DescriptionMark mark, string tip)
+ {
+ bool warn = mark is DescriptionMark.Differs or DescriptionMark.NotApplied;
+ var ink = warn ? NoteChangedInk : NoteInk;
+ var canvas = new Canvas { Width = 11, Height = 12, Margin = new Thickness(5, 0, 0, 0), VerticalAlignment = VerticalAlignment.Center, Background = Brushes.Transparent, Cursor = Cursors.Hand, Tag = hit };
+ canvas.Children.Add(new Path { Data = Geometry.Parse("M0.5,0.5 H7 L10.5,4 V11.5 H0.5 Z"), Fill = warn ? NoteChangedFill : Brushes.White, Stroke = ink, StrokeThickness = 1, IsHitTestVisible = false });
+ canvas.Children.Add(new Path { Data = Geometry.Parse("M7,0.5 V4 H10.5"), Stroke = ink, StrokeThickness = 1, IsHitTestVisible = false });
+ canvas.Children.Add(new Path { Data = Geometry.Parse("M2.5,6 H8.5 M2.5,8 H8.5 M2.5,10 H6.5"), Stroke = ink, StrokeThickness = 1, IsHitTestVisible = false });
+ canvas.ToolTip = tip + "\n\nClick to edit the description.";
+ ToolTipService.SetShowDuration(canvas, 60000);
+ AutomationProperties.SetName(canvas, mark switch { DescriptionMark.Differs => "Description changed in the database", DescriptionMark.NotApplied => "Description not applied", _ => "Description" });
+ AutomationProperties.SetHelpText(canvas, tip);
+ return canvas;
+ }
+
+ private FrameworkElement? MarkFor(DiagramTableModel table, string obj, string? name)
+ {
+ if (table.View == DiagramTableView.NameOnly && obj == DiagramDescription.ColumnObject) return null;
+ var (mark, tip) = MarkOf(table, obj, name);
+ return mark == DescriptionMark.None ? null : NoteGlyph(new(table, obj, name), mark, tip);
+ }
+
+ /// The tooltip of a relationship line, with its description when it has one.
+ private string RelationToolTip(DiagramRelation relation) => $"Relationship '{relation.Key.Name}' between '{relation.Primary.Caption}' and '{relation.Foreign.Caption}'"
+ + (DescriptionOf(relation.Foreign, DiagramDescription.ForeignKeyObject, relation.Key.Name) is { } text ? "\n\n" + text : "");
+
+ /// The mark of a relationship, in the middle of its line, above the label when labels are shown.
+ private void DrawRelationMark(DiagramRelation relation, DiagramRouting.Route route)
+ {
+ if (MarkFor(relation.Foreign, DiagramDescription.ForeignKeyObject, relation.Key.Name) is not { } glyph) return;
+ int middle = route.Points.Count / 2;
+ var at = new Point((route.Points[middle - 1].X + route.Points[middle].X) / 2, (route.Points[middle - 1].Y + route.Points[middle].Y) / 2);
+ glyph.Margin = new Thickness(0);
+ Canvas.SetLeft(glyph, at.X + 4); Canvas.SetTop(glyph, at.Y - (showLabels ? 30 : 16));
+ LinesLayer.Children.Add(glyph);
+ }
+
+ // ---- Editing ----
+ public void EditDescription(DiagramTableModel table, string obj, string? name)
+ {
+ if (IsBusy || !tables.Contains(table)) return;
+ CommitEdit();
+ string subject = obj switch
+ {
+ DiagramDescription.TableObject => "Table " + table.Key,
+ DiagramDescription.ColumnObject => $"Column {table.Key}.{name}",
+ _ => $"Relationship {name} of {table.Key}"
+ };
+ var (mark, _) = MarkOf(table, obj, name);
+ var notes = new List();
+ if (!table.CanComment && !table.IsNew)
+ notes.Add($"You do not own {table.Key}, and PostgreSQL lets only the owner change its descriptions. Save keeps this description only in the diagram, marked as not applied, and shows the script to send to the owner.");
+ if (mark == DescriptionMark.Differs) notes.Add("The database changed this description since the diagram was saved; the box shows the text of the database.");
+ var unapplied = table.Unapplied.FirstOrDefault(u => u.Same(obj, name));
+ var dialog = new DescriptionDialog(subject, DescriptionOf(table, obj, name), notes.Count == 0 ? null : string.Join("\n\n", notes), unapplied) { Owner = OwnerWindow };
+ DialogShown?.Invoke(dialog);
+ if (!(DescriptionPrompt ?? (d => d.ShowDialog() == true))(dialog)) return;
+ if (dialog.DiscardUnapplied || dialog.Changed) table.Unapplied.RemoveAll(u => u.Same(obj, name));
+ if (dialog.Changed) SetDescription(table, obj, name, dialog.Value);
+ Rebuild(); Touch();
+ }
+
+ /// Puts a description in the diagram as a pending change; Save writes it with COMMENT ON after the review.
+ public void SetDescription(DiagramTableModel table, string obj, string? name, string? text)
+ {
+ switch (obj)
+ {
+ case DiagramDescription.TableObject: table.Comment = text; break;
+ case DiagramDescription.ColumnObject:
+ int at = table.Columns.FindIndex(c => c.Name == name);
+ if (at >= 0) table.Columns[at] = table.Columns[at] with { Comment = text };
+ break;
+ default:
+ if (table.ForeignKeys.FirstOrDefault(k => k.Name == name) is { } key) key.Description = text ?? "";
+ break;
+ }
+ }
+
+ private void EditDescription(DiagramDescriptionHit hit) => EditDescription(hit.Table, hit.Object, hit.Name);
+
+ /// The statements that would apply the descriptions kept in the diagram but not applied, for the owner of the table.
+ public static IReadOnlyList UnappliedStatements(DiagramTableModel table) => table.Unapplied.Select(u => DiagramDescriptions.CommentSql(table.Schema, table.Name, u)).ToArray();
+
+ public void ShowUnappliedScript(DiagramTableModel table) =>
+ ShowUnappliedScript($"Descriptions of {table.Key} kept in the diagram but not applied: only the owner of the table can change them. Send this script to the owner, or to someone who can run it.", UnappliedStatements(table));
+
+ private void ShowUnappliedScript(string intro, IReadOnlyList statements)
+ {
+ if (statements.Count == 0) return;
+ if (UnappliedScriptPrompt is { } prompt) { prompt(intro, statements); return; }
+ var dialog = new ChangeScriptDialog(new TableDesignChange(statements, []), false, intro) { Owner = OwnerWindow, Title = "Unapplied Descriptions" };
+ DialogShown?.Invoke(dialog);
+ dialog.ShowDialog();
+ }
+
+ // ---- Export for AI ----
+ /// The layout the export reads: the saved tables of the diagram; a table not saved yet is not in the database.
+ internal DiagramLayout ExportLayout() { var layout = CurrentLayout(); return layout with { Tables = layout.Tables.Where(t => t.Oid != 0).ToArray() }; }
+
+ public async Task ExportForAiAsync()
+ {
+ if (IsBusy) return;
+ string markdown;
+ using (var cancellation = operation = new CancellationTokenSource())
+ {
+ Say("Reading the catalog…", cancellable: true); RefreshState();
+ try { markdown = await DiagramMarkdown.RenderAsync(connection, name, ExportLayout(), cancellation.Token); Say(""); }
+ catch (OperationCanceledException) { Say("Export canceled."); return; }
+ catch (Exception ex) when (ex is NpgsqlException or IOException or TimeoutException or InvalidOperationException) { Say("The diagram could not be exported: " + Message(ex)); return; }
+ finally { operation = null; Touch(); }
+ }
+ string? note = HasSchemaChanges ? "The export shows the database as it is now: the unsaved changes of this diagram are not in it. Save the diagram first to include them." : null;
+ var dialog = new DiagramExportDialog(markdown, name, note) { Owner = OwnerWindow };
+ DialogShown?.Invoke(dialog);
+ (ExportPrompt ?? (d => d.ShowDialog() == true))(dialog);
+ }
+
+ /// AI Export Function… of the diagram menu: reviews and creates, updates or removes pgms.diagram_markdown.
+ public async Task ManageMarkdownFunctionAsync()
+ {
+ if (IsBusy) return;
+ bool installed;
+ try { installed = await DiagramMarkdown.IsFunctionInstalledAsync(connection); }
+ catch (Exception ex) when (ex is NpgsqlException or IOException or TimeoutException) { Say("The database could not be read: " + Message(ex)); return; }
+ var dialog = new MarkdownFunctionDialog(installed, name) { Owner = OwnerWindow };
+ DialogShown?.Invoke(dialog);
+ if (!(FunctionPrompt ?? (d => d.ShowDialog() == true))(dialog) || dialog.Chosen == MarkdownFunctionDialog.Choice.None) return;
+ bool create = dialog.Chosen == MarkdownFunctionDialog.Choice.Create;
+ using var cancellation = operation = new CancellationTokenSource();
+ Say(create ? "Creating the function…" : "Removing the function…"); RefreshState();
+ try
+ {
+ await DiagramMarkdown.ApplyAsync(connection, create, cancellation.Token);
+ Say(create ? $"The function pgms.diagram_markdown is ready: an agent connected to this database can run SELECT pgms.diagram_markdown('{name.Replace("'", "''", StringComparison.Ordinal)}');" : "The function pgms.diagram_markdown was removed.");
+ }
+ catch (OperationCanceledException) { Say("Canceled. Nothing was changed."); }
+ catch (Exception ex) when (ex is NpgsqlException or IOException or TimeoutException or InvalidOperationException) { Say((create ? "The function was not created: " : "The function was not removed: ") + Message(ex)); }
+ finally { operation = null; Touch(); }
+ }
+}
diff --git a/src/PGMS.Desktop/DatabaseDiagramView.Indexes.cs b/src/PGMS.Desktop/DatabaseDiagramView.Indexes.cs
index a0e728b..17af7ed 100644
--- a/src/PGMS.Desktop/DatabaseDiagramView.Indexes.cs
+++ b/src/PGMS.Desktop/DatabaseDiagramView.Indexes.cs
@@ -37,14 +37,15 @@ public partial class DatabaseDiagramView
private bool ShowsIndexSection(DiagramTableModel table) => showIndexes && !table.IsNew && table.View != DiagramTableView.NameOnly;
private bool ShowsWarning(DiagramTableModel table) => showIndexes && !table.IsNew && table.Catalog.UnindexedForeignKeys.Count > 0;
- /// The title of a table: the caption and, when a foreign key of the table has no index, the warning on the right.
+ /// The title of a table: the caption, the mark of its description (PGMS-045) and, when a foreign key of the table has no index, the warning on the right.
private UIElement TitleContent(DiagramTableModel table, TextBlock caption)
{
- if (!ShowsWarning(table)) return caption;
+ var note = MarkFor(table, DiagramDescription.TableObject, null);
+ if (!ShowsWarning(table) && note is null) return caption;
var panel = new DockPanel();
- var warning = WarningGlyph(table);
- DockPanel.SetDock(warning, Dock.Right);
- panel.Children.Add(warning); panel.Children.Add(caption);
+ if (ShowsWarning(table)) { var warning = WarningGlyph(table); DockPanel.SetDock(warning, Dock.Right); panel.Children.Add(warning); }
+ if (note is not null) { note.Margin = new Thickness(6, 0, 0, 0); DockPanel.SetDock(note, Dock.Right); panel.Children.Add(note); }
+ panel.Children.Add(caption);
return panel;
}
diff --git a/src/PGMS.Desktop/DatabaseDiagramView.xaml.cs b/src/PGMS.Desktop/DatabaseDiagramView.xaml.cs
index cc05b2a..73950b1 100644
--- a/src/PGMS.Desktop/DatabaseDiagramView.xaml.cs
+++ b/src/PGMS.Desktop/DatabaseDiagramView.xaml.cs
@@ -165,13 +165,19 @@ public async Task LoadAsync()
Say("Reading diagram…", cancellable: true);
var service = new DiagramService(connection);
var diagram = await service.ReadAsync(info?.Id ?? openId!.Value, cancellation.Token);
- var (designs, missing, indexes) = await service.ReadTablesAndIndexesAsync(diagram.Layout.Tables, [], cancellation.Token);
+ var read = await service.ReadTablesAndIndexesAsync(diagram.Layout.Tables, [], cancellation.Token);
+ var (designs, missing, indexes) = read;
info = diagram.Info; name = diagram.Info.Name;
tables.Clear(); dropped.Clear(); selected.Clear(); selectedRelation = null;
var found = diagram.Layout.Tables.Where(p => !missing.Contains(p.Schema + "." + p.Name)).ToArray();
for (int i = 0; i < designs.Count && i < found.Length; i++)
{
- var table = new DiagramTableModel(designs[i], found[i].X, found[i].Y) { Catalog = indexes.GetValueOrDefault(designs[i].Oid) ?? DiagramTableIndexes.Empty };
+ var table = new DiagramTableModel(designs[i], found[i].X, found[i].Y)
+ {
+ Catalog = indexes.GetValueOrDefault(designs[i].Oid) ?? DiagramTableIndexes.Empty, CanComment = !read.NotOwned.Contains(designs[i].Oid), SavedDescriptions = found[i].Descriptions
+ };
+ // A description not applied that the catalog now has was applied by someone else: nothing is pending any more.
+ table.Unapplied.AddRange((found[i].Descriptions ?? []).Where(d => !d.Applied && DiagramDescriptions.Text(designs[i], d.Object, d.Name) != (d.Text.Length == 0 ? null : d.Text)));
ApplyPlacement(table, found[i]); tables.Add(table);
}
showIndexes = diagram.Layout.ShowIndexes;
@@ -194,12 +200,15 @@ public async Task LoadAsync()
}
// ---- State ----
- private DiagramLayout CurrentLayout() => new()
+ /// Descriptions that the save about to run leaves out (not the owner), by table, added to those the tables already keep.
+ private DiagramLayout CurrentLayout(IReadOnlyDictionary>? unapplied = null) => new()
{
Tables = tables.Select(t => new DiagramTablePlacement(t.Schema, t.Name, Math.Round(t.X), Math.Round(t.Y))
{
Oid = t.Original.Oid, View = t.View == DiagramTableView.ColumnNames ? null : t.View.ToString(), CustomColumns = t.CustomColumns.SequenceEqual(DiagramColumnFields.Standard) ? null : t.CustomColumns.ToArray(),
- IndexesExpanded = t.IndexesExpanded
+ IndexesExpanded = t.IndexesExpanded,
+ // Only the descriptions not applied: the save writes the copy of the others from the catalog, so they never make the tab look changed.
+ Descriptions = t.Unapplied.Concat(unapplied?.GetValueOrDefault(t.Original.Oid) ?? []).ToArray() is { Length: > 0 } kept ? DiagramDescriptions.Sorted(kept.Reverse().DistinctBy(d => (d.Object, d.Name))) : null
}).ToArray(),
// The indexes are written by DiagramService.SaveAsync from the catalog, so they never make the tab look changed.
Zoom = zoom, ShowRelationshipLabels = showLabels, ShowIndexes = showIndexes,
@@ -321,12 +330,15 @@ private void Rebuild()
ToolTip = "Drag to a column of another table to create a relationship."
};
// The whole row starts a relationship (pedido do usuário, 08/11/2026); before, only the selector did.
- row.ToolTip = selector.ToolTip;
+ row.ToolTip = column.Comment is { } described ? described + "\n\n" + selector.ToolTip : selector.ToolTip;
if (key.Contains(column.Name)) selector.Child = KeyGlyph();
var text = new TextBlock { Text = column.Name, Margin = new Thickness(5, 0, 10, 0), VerticalAlignment = VerticalAlignment.Center, Tag = new DiagramHit(table, column.Name, DiagramHitPart.Column, DiagramColumnFields.Name) };
Grid.SetColumn(text, 1);
row.Children.Add(selector); row.Children.Add(text);
AddFieldCells(row, table, column, fields, key.Contains(column.Name));
+ // The mark of a described column, in a last column shared by the rows, so the marks line up (PGMS-045).
+ row.ColumnDefinitions.Add(new() { Width = GridLength.Auto, SharedSizeGroup = "DiagramNote" });
+ if (MarkFor(table, DiagramDescription.ColumnObject, column.Name) is { } note) { note.Margin = new Thickness(2, 0, 4, 0); Grid.SetColumn(note, row.ColumnDefinitions.Count - 1); row.Children.Add(note); }
rowVisuals[(table, column.Name)] = (row, text);
AutomationProperties.SetName(row, column.Name + (key.Contains(column.Name) ? ", primary key" : ""));
stack.Children.Add(row);
@@ -464,7 +476,7 @@ private void DrawLines()
var visible = new Polyline { Points = points, Stroke = on ? SelectedLineBrush : LineBrush, StrokeThickness = 4, StrokeLineJoin = PenLineJoin.Miter, IsHitTestVisible = false };
var core = new Polyline { Points = points, Stroke = Brushes.White, StrokeThickness = 2, StrokeLineJoin = PenLineJoin.Miter, IsHitTestVisible = false };
LinesLayer.Children.Add(visible); LinesLayer.Children.Add(core); lineVisuals.Add((relation, visible));
- var hit = new Polyline { Points = points, Stroke = Brushes.Transparent, StrokeThickness = 9, Tag = relation, ToolTip = $"Relationship '{relation.Key.Name}' between '{relation.Primary.Caption}' and '{relation.Foreign.Caption}'" };
+ var hit = new Polyline { Points = points, Stroke = Brushes.Transparent, StrokeThickness = 9, Tag = relation, ToolTip = RelationToolTip(relation) };
AutomationProperties.SetName(hit, "Relationship " + relation.Key.Name);
LinesLayer.Children.Add(hit);
// Each segment can be dragged sideways; the cursor shows the direction (inferred: the SSMS cursor was not captured).
@@ -481,6 +493,7 @@ private void DrawLines()
// Key at the primary key table, ∞ at the foreign key table.
LinesLayer.Children.Add(EndGlyph(route.Points[0], route.PrimaryOut, key: true, relation));
LinesLayer.Children.Add(EndGlyph(route.Points[^1], route.ForeignOut, key: false, relation));
+ DrawRelationMark(relation, route);
if (showLabels)
{
int middle = route.Points.Count / 2;
@@ -563,7 +576,7 @@ public void FitZoom()
DependencyObject? found = null;
VisualTreeHelper.HitTest(Surface, null, result => { found = result.VisualHit; return HitTestResultBehavior.Stop; }, new PointHitTestParameters(point));
for (var element = found; element is not null && element != Surface; element = VisualTreeHelper.GetParent(element))
- if (element is FrameworkElement { Tag: DiagramHit or DiagramRelation or DiagramLineEnd or DiagramAnnotation } tagged) return tagged.Tag;
+ if (element is FrameworkElement { Tag: DiagramHit or DiagramRelation or DiagramLineEnd or DiagramAnnotation or DiagramDescriptionHit } tagged) return tagged.Tag;
return null;
}
@@ -573,6 +586,10 @@ public void FitZoom()
var hit = HitAt(point);
// An end of a line selects the line, like the line itself.
if (hit is DiagramLineEnd end) hit = end.Relation;
+ // The mark of a description selects what it describes.
+ if (hit is DiagramDescriptionHit described)
+ hit = described.Object == DiagramDescription.ForeignKeyObject ? Relations.FirstOrDefault(r => r.Foreign == described.Table && r.Key.Name == described.Name)
+ : described.Object == DiagramDescription.ColumnObject ? new DiagramHit(described.Table, described.Name, DiagramHitPart.Column) : new DiagramHit(described.Table, null, DiagramHitPart.Title);
if (!add || hit is DiagramAnnotation) selectedAnnotation = null;
switch (hit)
{
@@ -618,6 +635,8 @@ internal void Press(Point point, int clicks = 1, bool extend = false)
CancelSlowClick();
var end = HitAt(point) as DiagramLineEnd;
var selectedBefore = selectedColumnTable is { } before && selectedColumns.Count == 1 ? (before, selectedColumns.First()) : default((DiagramTableModel, string)?);
+ // A click on the mark of a description opens it after the click is over (PGMS-045).
+ if (!extend && HitAt(point) is DiagramDescriptionHit described) { SelectAt(point); drag = DragMode.None; if (clicks == 1) Dispatcher.BeginInvoke(() => EditDescription(described)); return; }
var hit = SelectAt(point, extend);
pendingCell = clicks == 1 && !extend && hit is DiagramHit { Column: { } clicked, Part: DiagramHitPart.Column } cell && selectedBefore == (cell.Table, clicked) ? cell : null;
// The Indexes header opens and closes on a click (a second click of a double click does nothing); the warning opens Find Unindexed Foreign Keys
@@ -889,6 +908,12 @@ MenuItem Add(string header, Action click, string name, string? icon = null, bool
// Only on a table with the warning (PGMS-044); not in the SSMS menu.
if (ShowsWarning(table)) Add("Find Unindexed Foreign Keys…", () => RequestUnindexedForeignKeys(table), "DiagramUnindexedForeignKeys");
Separator();
+ // SSMS edits descriptions in the Properties window; the diagram of PGMS edits them here (PGMS-045).
+ Add("Table Description…", () => EditDescription(table, DiagramDescription.TableObject, null), "DiagramTableDescription", enabled: single && !IsBusy);
+ if (target is DiagramHit { Column: { } describedColumn, Part: DiagramHitPart.Column or DiagramHitPart.Selector } && table.Column(describedColumn) is not null)
+ Add("Column Description…", () => EditDescription(table, DiagramDescription.ColumnObject, describedColumn), "DiagramColumnDescription", enabled: !IsBusy);
+ if (table.Unapplied.Count > 0) Add("Script Unapplied Descriptions…", () => ShowUnappliedScript(table), "DiagramUnappliedDescriptions");
+ Separator();
Add("Generate Change Script…", ShowChangeScript, "DiagramScript", "DesignerIconScript", HasSchemaChanges);
Separator();
Add("Properties", ShowProperties, "DiagramProperties", "DesignerIconProperties", single && !table.IsNew, "Alt+Enter");
@@ -898,6 +923,7 @@ MenuItem Add(string header, Action click, string name, string? icon = null, bool
case DiagramRelation relation:
Add("Delete Relationships from Database", () => DeleteRelationship(relation), "DiagramDeleteRelationship", "DesignerIconDelete", !relation.Foreign.IsReadOnly);
Separator();
+ Add("Relationship Description…", () => EditDescription(relation.Foreign, DiagramDescription.ForeignKeyObject, relation.Key.Name), "DiagramRelationshipDescription", enabled: !IsBusy);
Add("Properties", ShowProperties, "DiagramRelationshipProperties", "DesignerIconProperties", gesture: "Alt+Enter");
break;
case DiagramAnnotation note:
@@ -929,6 +955,9 @@ MenuItem Add(string header, Action click, string name, string? icon = null, bool
Add("Recalculate Page Breaks", RecalculatePageBreaks, "DiagramRecalculatePageBreaks");
Separator();
Add("Copy Diagram to Clipboard", () => CopyDiagram(), "DiagramCopy", enabled: ContentRects().Length > 0);
+ // Export for AI and the optional function are PGMS additions (PGMS-045).
+ Add("Export for AI…", () => _ = ExportForAiAsync(), "DiagramExportForAi", enabled: !IsBusy && tables.Any(t => !t.IsNew));
+ Add("AI Export Function…", () => _ = ManageMarkdownFunctionAsync(), "DiagramMarkdownFunction", enabled: !IsBusy);
Separator();
Add("Refresh", () => _ = RefreshAsync(), "DiagramRefresh", enabled: !IsBusy && tables.Any(t => !t.IsNew));
break;
@@ -966,8 +995,9 @@ public async Task AddTablesAsync(IReadOnlyList chosen)
{
Say("Reading tables…", cancellable: true);
var known = tables.Select(t => t.Original.Oid).ToHashSet();
- var (designs, missing, indexes) = await new DiagramService(connection).ReadTablesAndIndexesAsync(chosen.Where(c => !known.Contains(c.Oid)).Select(c => new DiagramTablePlacement(c.Schema, c.Name, 0, 0) { Oid = c.Oid }).ToArray(), [], cancellation.Token);
- var added = designs.Where(d => !known.Contains(d.Oid)).Select(d => new DiagramTableModel(d, 0, 0) { Catalog = indexes.GetValueOrDefault(d.Oid) ?? DiagramTableIndexes.Empty }).ToList();
+ var read = await new DiagramService(connection).ReadTablesAndIndexesAsync(chosen.Where(c => !known.Contains(c.Oid)).Select(c => new DiagramTablePlacement(c.Schema, c.Name, 0, 0) { Oid = c.Oid }).ToArray(), [], cancellation.Token);
+ var (designs, missing, indexes) = read;
+ var added = designs.Where(d => !known.Contains(d.Oid)).Select(d => new DiagramTableModel(d, 0, 0) { Catalog = indexes.GetValueOrDefault(d.Oid) ?? DiagramTableIndexes.Empty, CanComment = !read.NotOwned.Contains(d.Oid) }).ToList();
tables.AddRange(added);
Rebuild();
if (added.Count == 1)
@@ -1302,11 +1332,12 @@ public async Task RefreshTablesAsync()
var routes = CurrentLayout().Relationships ?? [];
bool wasDirty = IsDirty;
// The indexes of every table are read again, also of tables with pending changes: they come from the catalog and are not edited here.
- var (designs, _, indexes) = await new DiagramService(connection).ReadTablesAndIndexesAsync(clean.Select(t => new DiagramTablePlacement(t.Schema, t.Name, t.X, t.Y) { Oid = t.Original.Oid }).ToArray(),
+ var reread = await new DiagramService(connection).ReadTablesAndIndexesAsync(clean.Select(t => new DiagramTablePlacement(t.Schema, t.Name, t.X, t.Y) { Oid = t.Original.Oid }).ToArray(),
tables.Except(clean).Where(t => !t.IsNew).Select(t => t.Original.Oid).ToArray(), cancellation.Token);
+ var (designs, _, indexes) = reread;
var byOid = designs.ToDictionary(d => d.Oid);
foreach (var table in clean) if (byOid.TryGetValue(table.Original.Oid, out var read)) table.Reset(read);
- foreach (var table in tables) table.Catalog = indexes.GetValueOrDefault(table.Original.Oid) ?? DiagramTableIndexes.Empty;
+ foreach (var table in tables.Where(t => !t.IsNew)) { table.Catalog = indexes.GetValueOrDefault(table.Original.Oid) ?? DiagramTableIndexes.Empty; table.CanComment = !reread.NotOwned.Contains(table.Original.Oid); }
// Reset makes new key rows: the lines placed by hand are found again by name.
ApplyRoutes(routes);
if (!wasDirty) layoutBaseline = LayoutFingerprint();
@@ -1323,7 +1354,7 @@ public async Task RefreshTablesAsync()
public DiagramSchemaChanges.Result? BuildChanges()
{
CommitEdit();
- try { return DiagramSchemaChanges.Build(tables.Select(t => (t.Original, t.Current())).ToArray(), dropped); }
+ try { return DiagramSchemaChanges.Build(tables.Select(t => (t.Original, t.Current())).ToArray(), dropped, NotOwned()); }
catch (ArgumentException ex) { Say(ex.Message); return null; }
}
public void ShowChangeScript()
@@ -1355,23 +1386,35 @@ public async Task SaveAsync()
try
{
var service = new DiagramService(connection);
- var saved = await service.SaveAsync(info, chosen, CurrentLayout(), changes.Edits, cancellation.Token);
+ // Descriptions the user cannot apply go into the layout as not applied (PGMS-045); the save writes the copy of the others from the catalog.
+ var written = await service.SaveWithLayoutAsync(info, chosen, CurrentLayout(changes.Unapplied.ToDictionary(u => u.Oid, u => u.Items)), changes.Edits, cancellation.Token);
+ var saved = written.Info;
info = saved; name = saved.Name;
var savedLayout = CurrentLayout();
- var (designs, _, indexes) = await service.ReadTablesAndIndexesAsync(savedLayout.Tables, [], CancellationToken.None);
+ var reread = await service.ReadTablesAndIndexesAsync(savedLayout.Tables, [], CancellationToken.None);
+ var (designs, _, indexes) = reread;
+ var copies = written.Layout.Tables.ToDictionary(t => t.Schema + "." + t.Name, t => t.Descriptions, StringComparer.Ordinal);
var byOid = designs.ToDictionary(d => d.Oid);
var byName = designs.ToDictionary(d => d.Schema + "." + d.Name, StringComparer.Ordinal);
// A table created by this save had no OID when the layout was read: it is found by name.
var read = tables.ToDictionary(t => t, t => t.IsNew ? byName.GetValueOrDefault(t.Key) : byOid.GetValueOrDefault(t.Original.Oid));
tables.RemoveAll(t => read[t] is null);
- foreach (var table in tables) { table.Reset(read[table]!); table.Catalog = indexes.GetValueOrDefault(table.Original.Oid) ?? DiagramTableIndexes.Empty; }
+ foreach (var table in tables)
+ {
+ table.Reset(read[table]!); table.Catalog = indexes.GetValueOrDefault(table.Original.Oid) ?? DiagramTableIndexes.Empty; table.CanComment = !reread.NotOwned.Contains(table.Original.Oid);
+ table.SavedDescriptions = copies.GetValueOrDefault(table.Key);
+ table.Unapplied.Clear(); table.Unapplied.AddRange((table.SavedDescriptions ?? []).Where(d => !d.Applied));
+ }
// Reset makes new key rows: the lines placed by hand are found again by name.
ApplyRoutes(savedLayout.Relationships);
dropped.Clear();
layoutBaseline = LayoutFingerprint();
Rebuild();
- Say("Diagram saved.");
+ Say(changes.Unapplied.Count == 0 ? "Diagram saved." : "Diagram saved. Descriptions of tables you do not own were kept only in the diagram, marked as not applied.");
Saved?.Invoke(changes.Edits.Count > 0);
+ if (changes.Unapplied.Count > 0)
+ ShowUnappliedScript("These descriptions were not applied: only the owner of a table can change its descriptions. They are kept in the diagram, marked as not applied. Send this script to the owner, or to someone who can run it.",
+ changes.Unapplied.SelectMany(u => u.Statements).ToArray());
return true;
}
catch (OperationCanceledException) { Say("Save canceled. The transaction was rolled back."); return false; }
diff --git a/src/PGMS.Desktop/DiagramDescriptionDialogs.cs b/src/PGMS.Desktop/DiagramDescriptionDialogs.cs
new file mode 100644
index 0000000..96ec355
--- /dev/null
+++ b/src/PGMS.Desktop/DiagramDescriptionDialogs.cs
@@ -0,0 +1,245 @@
+using System.IO;
+using System.Text;
+using System.Windows;
+using System.Windows.Automation;
+using System.Windows.Controls;
+using System.Windows.Media;
+using PGMS.PostgreSql;
+
+namespace PGMS.Desktop;
+
+/// Description Property (PGMS-045), as SSMS 22.11 opens it from the "…" of Description in the Properties window (pilotagem de 11/11/2026,
+/// docs/MARCO-M1062.md): "Description:", a box of several lines, OK only after a change, Cancel. PGMS adds what it edits, the 4 KiB limit and,
+/// when it applies, why the description will not reach the database and the text kept in the diagram but not applied.
+public sealed class DescriptionDialog : Window
+{
+ private readonly string? original;
+ public TextBox Box { get; }
+ public Button OkButton { get; }
+ public TextBlock Counter { get; }
+ public TextBlock Notice { get; }
+ public Button UseSavedButton { get; }
+ public Button DiscardButton { get; }
+ /// The user chose to forget the description kept in the diagram but not applied.
+ public bool DiscardUnapplied { get; private set; }
+ /// The description as typed, with line breaks as \n and the ends trimmed; null removes it.
+ public string? Value => Normalize(Box.Text);
+ public bool Changed => Value != original;
+
+ internal static string? Normalize(string text) { string value = text.Replace("\r\n", "\n", StringComparison.Ordinal).Replace('\r', '\n').Trim(); return value.Length == 0 ? null : value; }
+
+ public DescriptionDialog(string subject, string? current, string? notice, DiagramDescription? unapplied)
+ {
+ original = current;
+ Title = "Description Property"; Width = 520; Height = 380; MinWidth = 400; MinHeight = 300;
+ WindowStartupLocation = WindowStartupLocation.CenterOwner; ShowInTaskbar = false; ResizeMode = ResizeMode.CanResizeWithGrip; Background = Frozen("#F0F0F0");
+ var root = new DockPanel { Margin = new Thickness(12) };
+ var heading = new TextBlock { Text = subject, Foreground = Frozen("#505050"), Margin = new Thickness(0, 0, 0, 6), TextTrimming = TextTrimming.CharacterEllipsis };
+ AutomationProperties.SetName(heading, "Object");
+ DockPanel.SetDock(heading, Dock.Top); root.Children.Add(heading);
+ var label = new TextBlock { Text = "Description:", Margin = new Thickness(0, 0, 0, 4) };
+ DockPanel.SetDock(label, Dock.Top); root.Children.Add(label);
+
+ Notice = new TextBlock { TextWrapping = TextWrapping.Wrap, Foreground = Frozen("#8A4B00"), Margin = new Thickness(0, 8, 0, 0), Visibility = notice is null ? Visibility.Collapsed : Visibility.Visible, Text = notice ?? "" };
+ AutomationProperties.SetName(Notice, "Notice");
+ UseSavedButton = new Button { Content = "_Use Diagram Text", Padding = new Thickness(8, 1, 8, 1), Margin = new Thickness(0, 0, 8, 0) };
+ DiscardButton = new Button { Content = "_Discard Diagram Text", Padding = new Thickness(8, 1, 8, 1) };
+ var savedPanel = new StackPanel { Margin = new Thickness(0, 8, 0, 0), Visibility = unapplied is null ? Visibility.Collapsed : Visibility.Visible };
+ if (unapplied is not null)
+ {
+ var savedText = new TextBlock
+ {
+ TextWrapping = TextWrapping.Wrap, Foreground = Frozen("#8A4B00"),
+ Text = "Kept in the diagram but not applied in the database (only the owner of the table can apply it): " + (unapplied.Text.Length == 0 ? "remove the description." : "“" + unapplied.Text + "”")
+ };
+ AutomationProperties.SetName(savedText, "Not applied");
+ savedPanel.Children.Add(savedText);
+ savedPanel.Children.Add(new StackPanel { Orientation = Orientation.Horizontal, Margin = new Thickness(0, 6, 0, 0), Children = { UseSavedButton, DiscardButton } });
+ }
+ UseSavedButton.Click += (_, _) => { Box!.Text = unapplied!.Text; Box.Focus(); Box.CaretIndex = Box.Text.Length; };
+ DiscardButton.Click += (_, _) => { DiscardUnapplied = true; DiscardButton.IsEnabled = false; UseSavedButton.IsEnabled = false; Refresh(); };
+
+ OkButton = new Button { Content = "OK", Width = 86, Height = 24, IsDefault = false, Margin = new Thickness(0, 0, 8, 0), IsEnabled = false };
+ var cancel = new Button { Content = "Cancel", Width = 86, Height = 24, IsCancel = true };
+ Counter = new TextBlock { VerticalAlignment = VerticalAlignment.Center, Foreground = Frozen("#505050") };
+ AutomationProperties.SetName(Counter, "Size");
+ var buttons = new DockPanel { Margin = new Thickness(0, 10, 0, 0), LastChildFill = false };
+ DockPanel.SetDock(Counter, Dock.Left); DockPanel.SetDock(cancel, Dock.Right); DockPanel.SetDock(OkButton, Dock.Right);
+ buttons.Children.Add(Counter); buttons.Children.Add(cancel); buttons.Children.Add(OkButton);
+ DockPanel.SetDock(buttons, Dock.Bottom); root.Children.Add(buttons);
+ DockPanel.SetDock(savedPanel, Dock.Bottom); root.Children.Add(savedPanel);
+ DockPanel.SetDock(Notice, Dock.Bottom); root.Children.Add(Notice);
+
+ // Enter starts a new line, as in the SSMS box; OK is a click or Alt+O away.
+ Box = new TextBox { Text = (current ?? "").Replace("\n", Environment.NewLine, StringComparison.Ordinal), AcceptsReturn = true, AcceptsTab = false, TextWrapping = TextWrapping.Wrap, VerticalScrollBarVisibility = ScrollBarVisibility.Auto };
+ AutomationProperties.SetName(Box, "Description");
+ root.Children.Add(Box);
+ Content = root;
+ Box.TextChanged += (_, _) => Refresh();
+ OkButton.Click += (_, _) => { if (IsLoaded) DialogResult = true; };
+ Loaded += (_, _) => { Box.Focus(); Box.SelectAll(); };
+ Refresh();
+ }
+
+ private void Refresh()
+ {
+ string? error = DiagramDescriptions.LimitError(Value);
+ int bytes = Value is null ? 0 : Encoding.UTF8.GetByteCount(Value);
+ Counter.Text = error ?? $"{bytes} of {DiagramDescriptions.MaxBytes} bytes";
+ Counter.Foreground = error is null ? Frozen("#505050") : Frozen("#A1260D");
+ OkButton.IsEnabled = error is null && (Changed || DiscardUnapplied);
+ }
+
+ internal static Brush Frozen(string color) { var brush = new SolidColorBrush((Color)ColorConverter.ConvertFromString(color)); brush.Freeze(); return brush; }
+}
+
+/// Export for AI (PGMS-045): the Markdown of the diagram, to copy into a system prompt, a CLAUDE.md or an AGENTS.md, or to save as a file.
+/// Not in SSMS.
+public sealed class DiagramExportDialog : Window
+{
+ public TextBox Text { get; }
+ public TextBlock Note { get; }
+ public Button CopyButton { get; }
+ public Button SaveButton { get; }
+ internal Action? ClipboardOverride { get; set; }
+ internal Func? SavePathOverride { get; set; }
+ public string? SavedTo { get; private set; }
+
+ public DiagramExportDialog(string markdown, string diagramName, string? note)
+ {
+ Title = "Export for AI"; Width = 820; Height = 600; MinWidth = 520; MinHeight = 360;
+ WindowStartupLocation = WindowStartupLocation.CenterOwner; ShowInTaskbar = false; ResizeMode = ResizeMode.CanResizeWithGrip; Background = DescriptionDialog.Frozen("#F0F0F0");
+ var root = new DockPanel { Margin = new Thickness(12) };
+ var intro = new TextBlock
+ {
+ TextWrapping = TextWrapping.Wrap, Margin = new Thickness(0, 0, 0, 6),
+ Text = "The tables of this diagram as Markdown, read now from the catalog: columns, keys, relationships, indexes and descriptions. Paste it into a system prompt, a CLAUDE.md or an AGENTS.md, so an AI agent reads the model before writing SQL."
+ };
+ DockPanel.SetDock(intro, Dock.Top); root.Children.Add(intro);
+ Note = new TextBlock { TextWrapping = TextWrapping.Wrap, Foreground = DescriptionDialog.Frozen("#8A4B00"), Margin = new Thickness(0, 0, 0, 6), Text = note ?? "", Visibility = note is null ? Visibility.Collapsed : Visibility.Visible };
+ AutomationProperties.SetName(Note, "Notice");
+ DockPanel.SetDock(Note, Dock.Top); root.Children.Add(Note);
+ CopyButton = new Button { Content = "_Copy", Width = 86, Height = 24, Margin = new Thickness(0, 0, 8, 0) };
+ SaveButton = new Button { Content = "_Save As…", Width = 96, Height = 24 };
+ var close = new Button { Content = "Close", Width = 86, Height = 24, IsCancel = true };
+ var buttons = new DockPanel { Margin = new Thickness(0, 10, 0, 0), LastChildFill = false };
+ DockPanel.SetDock(CopyButton, Dock.Left); DockPanel.SetDock(SaveButton, Dock.Left); DockPanel.SetDock(close, Dock.Right);
+ buttons.Children.Add(CopyButton); buttons.Children.Add(SaveButton); buttons.Children.Add(close);
+ DockPanel.SetDock(buttons, Dock.Bottom); root.Children.Add(buttons);
+ Text = new TextBox { Text = markdown.Replace("\n", Environment.NewLine, StringComparison.Ordinal), IsReadOnly = true, AcceptsReturn = true, FontFamily = new FontFamily("Consolas"), FontSize = 12, VerticalScrollBarVisibility = ScrollBarVisibility.Auto, HorizontalScrollBarVisibility = ScrollBarVisibility.Auto };
+ AutomationProperties.SetName(Text, "Markdown");
+ root.Children.Add(Text);
+ Content = root;
+ CopyButton.Click += (_, _) =>
+ {
+ if (ClipboardOverride is { } copy) copy(markdown);
+ else Clipboard.SetText(markdown.Replace("\n", Environment.NewLine, StringComparison.Ordinal));
+ CopyButton.Content = "Copied";
+ };
+ SaveButton.Click += (_, _) =>
+ {
+ string? path = SavePathOverride is { } choose ? choose() : Choose(diagramName);
+ if (path is null) return;
+ try { File.WriteAllText(path, markdown, new UTF8Encoding(false)); SavedTo = path; }
+ catch (Exception ex) when (ex is IOException or UnauthorizedAccessException) { MessageBox.Show(this, ex.Message, "PGMS", MessageBoxButton.OK, MessageBoxImage.Error); }
+ };
+ }
+
+ private string? Choose(string diagramName)
+ {
+ string file = string.Concat(diagramName.Select(c => Path.GetInvalidFileNameChars().Contains(c) ? '_' : c));
+ var dialog = new Microsoft.Win32.SaveFileDialog { Filter = "Markdown files (*.md)|*.md|All files (*.*)|*.*", DefaultExt = ".md", FileName = file + ".md" };
+ return dialog.ShowDialog(this) == true ? dialog.FileName : null;
+ }
+}
+
+/// The optional function pgms.diagram_markdown(name) (PGMS-045): the script to review, then Create (or Update) or Remove. Not in SSMS.
+public sealed class MarkdownFunctionDialog : Window
+{
+ public enum Choice { None, Create, Remove }
+ public Choice Chosen { get; private set; }
+ public TextBox Script { get; }
+ public TextBlock Status { get; }
+ public Button CreateButton { get; }
+ public Button RemoveButton { get; }
+
+ public MarkdownFunctionDialog(bool installed, string diagramName)
+ {
+ Title = "AI Export Function"; Width = 820; Height = 600; MinWidth = 520; MinHeight = 360;
+ WindowStartupLocation = WindowStartupLocation.CenterOwner; ShowInTaskbar = false; ResizeMode = ResizeMode.CanResizeWithGrip; Background = DescriptionDialog.Frozen("#F0F0F0");
+ var root = new DockPanel { Margin = new Thickness(12) };
+ string call = "SELECT pgms.diagram_markdown('" + diagramName.Replace("'", "''", StringComparison.Ordinal) + "');";
+ Status = new TextBlock
+ {
+ TextWrapping = TextWrapping.Wrap, Margin = new Thickness(0, 0, 0, 8),
+ Text = (installed ? "The function pgms.diagram_markdown is installed in this database." : "The function pgms.diagram_markdown is not installed in this database.")
+ + " It is optional: an AI agent connected to the database runs " + call + " and gets the same Markdown as Export for AI, read from the catalog."
+ + " It is read only, runs with the privileges of the caller (who needs SELECT on pgms.diagrams) and is created in the schema pgms. Review the script before you run it."
+ };
+ AutomationProperties.SetName(Status, "Status");
+ DockPanel.SetDock(Status, Dock.Top); root.Children.Add(Status);
+ CreateButton = new Button { Content = installed ? "_Update" : "_Create", Width = 86, Height = 24, Margin = new Thickness(0, 0, 8, 0) };
+ RemoveButton = new Button { Content = "_Remove", Width = 86, Height = 24, Margin = new Thickness(0, 0, 8, 0), IsEnabled = installed };
+ var save = new Button { Content = "Save to _File…", Width = 106, Height = 24 };
+ var close = new Button { Content = "Close", Width = 86, Height = 24, IsCancel = true };
+ var buttons = new DockPanel { Margin = new Thickness(0, 10, 0, 0), LastChildFill = false };
+ DockPanel.SetDock(save, Dock.Left); DockPanel.SetDock(close, Dock.Right); DockPanel.SetDock(RemoveButton, Dock.Right); DockPanel.SetDock(CreateButton, Dock.Right);
+ buttons.Children.Add(save); buttons.Children.Add(close); buttons.Children.Add(RemoveButton); buttons.Children.Add(CreateButton);
+ DockPanel.SetDock(buttons, Dock.Bottom); root.Children.Add(buttons);
+ Script = new TextBox { Text = DiagramMarkdown.CreateFunctionSql.Replace("\n", Environment.NewLine, StringComparison.Ordinal), IsReadOnly = true, AcceptsReturn = true, FontFamily = new FontFamily("Consolas"), FontSize = 12, VerticalScrollBarVisibility = ScrollBarVisibility.Auto, HorizontalScrollBarVisibility = ScrollBarVisibility.Auto };
+ AutomationProperties.SetName(Script, "Script");
+ root.Children.Add(Script);
+ Content = root;
+ CreateButton.Click += (_, _) => { Chosen = Choice.Create; if (IsLoaded) DialogResult = true; };
+ // Remove shows its script in the box first; the second click runs it.
+ RemoveButton.Click += (_, _) =>
+ {
+ if (Script.Text != DiagramMarkdown.DropFunctionSql) { Script.Text = DiagramMarkdown.DropFunctionSql; RemoveButton.Content = "Confirm _Remove"; CreateButton.IsEnabled = false; return; }
+ Chosen = Choice.Remove; if (IsLoaded) DialogResult = true;
+ };
+ save.Click += (_, _) =>
+ {
+ var dialog = new Microsoft.Win32.SaveFileDialog { Filter = "SQL files (*.sql)|*.sql|All files (*.*)|*.*", DefaultExt = ".sql", FileName = "pgms.diagram_markdown.sql" };
+ if (dialog.ShowDialog(this) != true) return;
+ try { File.WriteAllText(dialog.FileName, Script.Text, new UTF8Encoding(false)); }
+ catch (Exception ex) when (ex is IOException or UnauthorizedAccessException) { MessageBox.Show(this, ex.Message, "PGMS", MessageBoxButton.OK, MessageBoxImage.Error); }
+ };
+ }
+}
+
+/// Install Diagram Support with the SSMS question, the script PGMS runs and, unchecked by default, the optional function for AI agents (PGMS-045).
+public sealed class InstallDiagramSupportDialog : Window
+{
+ public CheckBox FunctionBox { get; }
+ public TextBox Script { get; }
+ public Button YesButton { get; }
+
+ public InstallDiagramSupportDialog(string question)
+ {
+ Title = "PGMS"; Width = 640; Height = 520; MinWidth = 480; MinHeight = 360;
+ WindowStartupLocation = WindowStartupLocation.CenterOwner; ShowInTaskbar = false; ResizeMode = ResizeMode.CanResizeWithGrip; Background = DescriptionDialog.Frozen("#F0F0F0");
+ var root = new DockPanel { Margin = new Thickness(12) };
+ var text = new TextBlock { Text = question, TextWrapping = TextWrapping.Wrap, Margin = new Thickness(0, 0, 0, 10) };
+ AutomationProperties.SetName(text, "Question");
+ DockPanel.SetDock(text, Dock.Top); root.Children.Add(text);
+ FunctionBox = new CheckBox
+ {
+ Margin = new Thickness(0, 0, 0, 8), IsChecked = false,
+ Content = new TextBlock { TextWrapping = TextWrapping.Wrap, Text = "Also create the function pgms.diagram_markdown(name), so an AI agent connected to this database can read a diagram as Markdown (optional)" }
+ };
+ AutomationProperties.SetName(FunctionBox, "Also create the function pgms.diagram_markdown");
+ DockPanel.SetDock(FunctionBox, Dock.Top); root.Children.Add(FunctionBox);
+ YesButton = new Button { Content = "_Yes", Width = 86, Height = 24, Margin = new Thickness(0, 0, 8, 0), IsDefault = true };
+ var no = new Button { Content = "_No", Width = 86, Height = 24, IsCancel = true };
+ var buttons = new StackPanel { Orientation = Orientation.Horizontal, HorizontalAlignment = HorizontalAlignment.Right, Margin = new Thickness(0, 10, 0, 0), Children = { YesButton, no } };
+ DockPanel.SetDock(buttons, Dock.Bottom); root.Children.Add(buttons);
+ Script = new TextBox { IsReadOnly = true, AcceptsReturn = true, FontFamily = new FontFamily("Consolas"), FontSize = 12, VerticalScrollBarVisibility = ScrollBarVisibility.Auto, HorizontalScrollBarVisibility = ScrollBarVisibility.Auto };
+ AutomationProperties.SetName(Script, "Script");
+ root.Children.Add(Script);
+ Content = root;
+ void Show() => Script.Text = (DiagramService.InstallSql + (FunctionBox.IsChecked == true ? "\n" + DiagramMarkdown.CreateFunctionSql : "")).Replace("\n", Environment.NewLine, StringComparison.Ordinal);
+ FunctionBox.Checked += (_, _) => Show(); FunctionBox.Unchecked += (_, _) => Show();
+ Show();
+ YesButton.Click += (_, _) => { if (IsLoaded) DialogResult = true; };
+ }
+}
diff --git a/src/PGMS.Desktop/MainWindow.Diagrams.cs b/src/PGMS.Desktop/MainWindow.Diagrams.cs
index c557a98..57a81c7 100644
--- a/src/PGMS.Desktop/MainWindow.Diagrams.cs
+++ b/src/PGMS.Desktop/MainWindow.Diagrams.cs
@@ -18,6 +18,8 @@ public partial class MainWindow
internal Func? DiagramConfirmPrompt { get; set; }
internal Func? DiagramNamePrompt { get; set; }
internal Func? DiagramClosePrompt { get; set; }
+ /// Replaces Install Diagram Support (question, script and the optional function of PGMS-045); without it, DiagramConfirmPrompt answers the question alone.
+ internal Func? DiagramInstallPrompt { get; set; }
private bool ConfirmDiagram(string text) => DiagramConfirmPrompt?.Invoke(text) ?? MessageBox.Show(this, text, "PGMS", MessageBoxButton.YesNo, MessageBoxImage.Question) == MessageBoxResult.Yes;
private string? AskDiagramName(string title, string suggested) => DiagramNamePrompt is { } prompt ? prompt(title, suggested) : NamePrompt.Show(this, title, "Enter a name for the diagram:", suggested);
@@ -34,9 +36,16 @@ internal async Task EnsureDiagramSupportAsync(string connection, bool askE
if (askEvenIfInstalled) Status.Text = "Diagram support is already installed in this database.";
return true;
}
- if (!ConfirmDiagram(InstallQuestion)) return false;
- await service.InstallAsync();
- Status.Text = "Diagram support installed (schema pgms, table pgms.diagrams).";
+ bool function = false;
+ if (DiagramInstallPrompt is null && DiagramConfirmPrompt is not null) { if (!ConfirmDiagram(InstallQuestion)) return false; }
+ else
+ {
+ var dialog = new InstallDiagramSupportDialog(InstallQuestion) { Owner = this };
+ if (!(DiagramInstallPrompt ?? (d => d.ShowDialog() == true))(dialog)) return false;
+ function = dialog.FunctionBox.IsChecked == true;
+ }
+ await service.InstallAsync(function);
+ Status.Text = function ? "Diagram support installed (schema pgms, table pgms.diagrams, function pgms.diagram_markdown)." : "Diagram support installed (schema pgms, table pgms.diagrams).";
return true;
}
catch (Exception ex) when (ex is Npgsql.NpgsqlException or IOException or TimeoutException or InvalidOperationException)
diff --git a/src/PGMS.PostgreSql/DatabaseDiagrams.cs b/src/PGMS.PostgreSql/DatabaseDiagrams.cs
index a7c04c8..8497400 100644
--- a/src/PGMS.PostgreSql/DatabaseDiagrams.cs
+++ b/src/PGMS.PostgreSql/DatabaseDiagrams.cs
@@ -20,6 +20,10 @@ public sealed record DiagramTablePlacement(string Schema, string Name, double X,
public IReadOnlyList? Indexes { get; init; }
/// Foreign keys of the table that no index serves, when the diagram was saved.
public IReadOnlyList? UnindexedForeignKeys { get; init; }
+ /// The descriptions (COMMENT ON) of the table, its columns and foreign keys when the diagram was saved (PGMS-045): a copy for tools and AI agents,
+ /// written by every save from the catalog; opening a diagram reads the catalog again and shows where this copy differs. Items with Applied false are
+ /// descriptions the user had no privilege to apply; the tab keeps them in its layout, so they survive saves until the catalog has them.
+ public IReadOnlyList? Descriptions { get; init; }
}
/// A text annotation placed on a diagram.
@@ -32,13 +36,13 @@ public sealed record DiagramRelationshipRoute(string Schema, string Table, strin
/// What a diagram stores: which tables it shows and where, and the lines placed by hand. Never table data (decision of 07/11/2026, docs/MARCO-M1043.md).
public sealed record DiagramLayout
{
- /// 1: layout only (M1043). 2: the indexes of each table, Show Indexes and IndexesExpanded (PGMS-044). A diagram of format 1 opens as it was
- /// and is written as format 2 by the next save; older versions of PGMS ignore what they do not know.
- public const int CurrentFormat = 2;
+ /// 1: layout only (M1043). 2: the indexes of each table, Show Indexes and IndexesExpanded (PGMS-044). 3: the descriptions of each table (PGMS-045).
+ /// A diagram of an older format opens as it was and is written in the current format by the next save; older versions of PGMS ignore what they do not know.
+ public const int CurrentFormat = 3;
public int Format { get; init; } = CurrentFormat;
/// Show Indexes of the diagram menu (PGMS-044), on by default and kept by diagram.
public bool ShowIndexes { get; init; } = true;
- /// When the save read the indexes written in Tables; null when they were not read (a layout not saved yet, or format 1).
+ /// When the save read the indexes and descriptions written in Tables; null when they were not read (a layout not saved yet, or format 1).
public DateTimeOffset? CatalogRead { get; init; }
public IReadOnlyList Tables { get; init; } = [];
/// Only the lines moved by hand; the others are routed automatically. Older versions of PGMS ignore this list.
@@ -86,10 +90,19 @@ public sealed record NewTableForeignKeysEdit(TableDesign Table) : IAdministrativ
/// its new key before another table references it, a foreign key goes away before the key it uses, the foreign keys of new tables follow, and dropped tables come last.
public static class DiagramSchemaChanges
{
- public sealed record Result(IReadOnlyList Edits, TableDesignChange Script);
+ public sealed record Result(IReadOnlyList Edits, TableDesignChange Script)
+ {
+ /// Description changes left out of the save because the user does not own the table (PGMS-045): kept in the diagram as not applied,
+ /// with the statements to send to someone who can run them.
+ public IReadOnlyList Unapplied { get; init; } = [];
+ }
+ public sealed record UnappliedDescriptions(uint Oid, string Schema, string Table, IReadOnlyList Items, IReadOnlyList Statements);
- public static Result Build(IReadOnlyList<(TableDesign Original, TableDesign Current)> tables, IReadOnlyList dropped)
+ /// Tables the user does not own. A table whose only change is descriptions is left out of the save when it is here; a table with
+ /// other changes still goes in, and PostgreSQL refuses it as before.
+ public static Result Build(IReadOnlyList<(TableDesign Original, TableDesign Current)> tables, IReadOnlyList dropped, IReadOnlySet? notOwned = null)
{
+ foreach (var (original, current) in tables) DiagramDescriptions.CheckLimits(original.Oid == 0 ? null : original, current);
// Columns renamed in one table are renamed in the foreign keys of the others by PostgreSQL itself: those keys are compared, and checked
// before saving, with the new names, so they are not rebuilt.
var fresh = tables.Where(t => t.Original.Oid == 0).Select(t => t.Current).ToArray();
@@ -97,11 +110,15 @@ public static Result Build(IReadOnlyList<(TableDesign Original, TableDesign Curr
var renamed = tables.Select(t => (t.Original, Renames: TableDesignColumns.Renames(t.Original, t.Current.Columns))).Where(r => r.Renames.Count > 0).ToArray();
TableDesign Adjusted(TableDesign original) => renamed.Aggregate(original, (design, r) => TableDesignColumns.WithReferencedRenames(design, r.Original.Schema, r.Original.Name, r.Renames));
var changed = new List<(TableDesign Original, TableDesign Current, TableDesignChange Change)>();
+ var described = new List<(TableDesign Original, TableDesign Current, TableDesignChange Change)>();
foreach (var (read, current) in tables)
{
var original = Adjusted(read);
var change = TableDesignScript.Build(original, current);
- if (change.Statements.Count > 0) changed.Add((original, current, change));
+ if (change.Statements.Count == 0) continue;
+ // Only descriptions: COMMENT ON runs without locking and comparing the whole table (PGMS-045).
+ if (TableDesignScript.Build(original, DiagramDescriptions.WithoutDescriptionChanges(original, current)).Statements.Count == 0) described.Add((original, current, change));
+ else changed.Add((original, current, change));
}
static string Key(DesignForeignKey f) => string.Join("\u0001", [string.Join(",", f.Columns), f.ReferencedSchema, f.ReferencedTable, string.Join(",", f.ReferencedColumns), f.OnUpdate.ToString(), f.OnDelete.ToString(), f.CheckExisting.ToString()]);
static IEnumerable Added(TableDesign before, TableDesign after) =>
@@ -146,6 +163,22 @@ static IEnumerable Removed(TableDesign before, TableDesign aft
statements.Add($"-- {changed[i].Original.Schema}.{changed[i].Original.Name}");
statements.AddRange(changed[i].Change.Statements); warnings.AddRange(changed[i].Change.Warnings);
}
+ var unapplied = new List();
+ foreach (var (original, current, change) in described.OrderBy(d => d.Original.Schema, StringComparer.Ordinal).ThenBy(d => d.Original.Name, StringComparer.Ordinal))
+ {
+ string table = original.Schema + "." + original.Name;
+ if (notOwned?.Contains(original.Oid) == true)
+ {
+ unapplied.Add(new(original.Oid, original.Schema, original.Name, DiagramDescriptions.Changed(original, current).Select(d => d with { Applied = false }).ToArray(), change.Statements));
+ statements.Add($"-- {table}: not applied. Only the owner of the table can change its descriptions; they are kept in the diagram, marked as not applied.");
+ statements.AddRange(change.Statements.Select(s => "-- " + s.Replace("\n", "\n-- ", StringComparison.Ordinal)));
+ warnings.Add($"You do not own {table}: its descriptions are saved only in the diagram, marked as not applied, and the script to send to the owner is shown after the save.");
+ continue;
+ }
+ edits.Add(new DescriptionEdit(original, current));
+ statements.Add($"-- {table}");
+ statements.AddRange(change.Statements);
+ }
foreach (var table in fresh.Where(t => t.ForeignKeys.Count > 0))
{
edits.Add(new NewTableForeignKeysEdit(table));
@@ -158,7 +191,7 @@ static IEnumerable Removed(TableDesign before, TableDesign aft
edits.Add(drop); statements.Add(drop.ToSql());
warnings.Add($"Deleting table {table.Schema}.{table.Name} deletes it and its data.");
}
- return new(edits, new(statements, warnings));
+ return new(edits, new(statements, warnings)) { Unapplied = unapplied };
}
}
@@ -197,12 +230,15 @@ public async Task IsInstalledAsync(CancellationToken token = default)
return await IsInstalledAsync(connection, null, token).ConfigureAwait(false);
}
- /// Creates the schema and table. Needs CREATE on the database (or an existing pgms schema the user can create in).
- public async Task InstallAsync(CancellationToken token = default)
+ /// Creates the schema and table and, when asked, the optional function pgms.diagram_markdown for AI agents (PGMS-045), in one transaction.
+ /// Needs CREATE on the database (or an existing pgms schema the user can create in).
+ public async Task InstallAsync(CancellationToken token = default) => await InstallAsync(false, token).ConfigureAwait(false);
+ public async Task InstallAsync(bool withMarkdownFunction, CancellationToken token = default)
{
await using var connection = await OpenAsync(token).ConfigureAwait(false);
await using var transaction = await connection.BeginTransactionAsync(token).ConfigureAwait(false);
- await using (var command = new NpgsqlCommand(InstallSql, connection, transaction) { CommandTimeout = 30 }) await command.ExecuteNonQueryAsync(token).ConfigureAwait(false);
+ string sql = InstallSql + (withMarkdownFunction ? "\n" + DiagramMarkdown.CreateFunctionSql : "");
+ await using (var command = new NpgsqlCommand(sql, connection, transaction) { CommandTimeout = 30 }) await command.ExecuteNonQueryAsync(token).ConfigureAwait(false);
await transaction.CommitAsync(token).ConfigureAwait(false);
}
@@ -276,7 +312,11 @@ private async Task> TablesAsync(string sql, uint[
return (read.Tables, read.Missing);
}
- public sealed record TablesRead(IReadOnlyList Tables, IReadOnlyList Missing, IReadOnlyDictionary Indexes);
+ public sealed record TablesRead(IReadOnlyList Tables, IReadOnlyList Missing, IReadOnlyDictionary Indexes)
+ {
+ /// Tables read whose owner the user is not: their descriptions cannot be changed by this user (PGMS-045).
+ public IReadOnlySet NotOwned { get; init; } = new HashSet();
+ }
/// The tables as reads them and, in the same snapshot, the indexes of those tables and of alsoIndexesOf
/// (tables of the diagram with pending changes, whose design is not read again but whose indexes are).
@@ -300,8 +340,9 @@ public async Task ReadTablesAndIndexesAsync(IReadOnlyList t.Oid).Concat(alsoIndexesOf).ToArray(), token).ConfigureAwait(false);
+ var notOwned = await DiagramDescriptions.NotOwnedAsync(connection, transaction, tables.Select(t => t.Oid).Concat(alsoIndexesOf).ToArray(), token).ConfigureAwait(false);
await transaction.CommitAsync(token).ConfigureAwait(false);
- return new(tables, missing, indexes);
+ return new(tables, missing, indexes) { NotOwned = notOwned };
}
/// The layout with the indexes each table has now, read inside the save transaction after the schema changes ran, so the saved diagram
@@ -320,6 +361,7 @@ private static async Task WithCatalogAsync(NpgsqlConnection conne
while (await reader.ReadAsync(token).ConfigureAwait(false)) found[reader.GetInt32(0) - 1] = reader.GetFieldValue(1);
}
var indexes = await DiagramIndexReader.ReadAsync(connection, transaction, found.Values.ToArray(), token).ConfigureAwait(false);
+ var descriptions = await DiagramDescriptions.ReadAsync(connection, transaction, found.Values.ToArray(), token).ConfigureAwait(false);
DateTimeOffset read;
await using (var now = new NpgsqlCommand("SELECT statement_timestamp()", connection, transaction) { CommandTimeout = 15 })
read = new DateTimeOffset(DateTime.SpecifyKind((DateTime)(await now.ExecuteScalarAsync(token).ConfigureAwait(false))!, DateTimeKind.Utc));
@@ -327,8 +369,12 @@ private static async Task WithCatalogAsync(NpgsqlConnection conne
{
Format = DiagramLayout.CurrentFormat, CatalogRead = read,
Tables = layout.Tables.Select((t, i) => found.TryGetValue(i, out var oid) && indexes.TryGetValue(oid, out var table)
- ? t with { Oid = oid, Indexes = table.Indexes, UnindexedForeignKeys = table.UnindexedForeignKeys }
- : t with { Indexes = null, UnindexedForeignKeys = null }).ToArray()
+ ? t with
+ {
+ Oid = oid, Indexes = table.Indexes, UnindexedForeignKeys = table.UnindexedForeignKeys,
+ Descriptions = DiagramDescriptions.Merge(descriptions.GetValueOrDefault(oid) ?? [], t.Descriptions ?? [])
+ }
+ : t with { Indexes = null, UnindexedForeignKeys = null, Descriptions = null }).ToArray()
};
}
private static async Task ExistsAsync(NpgsqlConnection connection, NpgsqlTransaction transaction, string schema, string name, CancellationToken token)
@@ -340,7 +386,13 @@ private static async Task ExistsAsync(NpgsqlConnection connection, NpgsqlT
/// Applies the schema changes and writes the diagram in one transaction (decision of 07/11/2026). A null existing creates the diagram.
/// The version guard refuses a save over a diagram changed or deleted elsewhere since it was read.
- public async Task SaveAsync(DiagramInfo? existing, string name, DiagramLayout layout, IReadOnlyList edits, CancellationToken token = default)
+ public async Task SaveAsync(DiagramInfo? existing, string name, DiagramLayout layout, IReadOnlyList edits, CancellationToken token = default) =>
+ (await SaveWithLayoutAsync(existing, name, layout, edits, token).ConfigureAwait(false)).Info;
+
+ public sealed record Saved(DiagramInfo Info, DiagramLayout Layout);
+
+ /// As , with the layout as written: the indexes and descriptions read from the catalog inside the save.
+ public async Task SaveWithLayoutAsync(DiagramInfo? existing, string name, DiagramLayout layout, IReadOnlyList edits, CancellationToken token = default)
{
name = ValidName(name);
await using var connection = await OpenAsync(token).ConfigureAwait(false);
@@ -371,7 +423,7 @@ public async Task SaveAsync(DiagramInfo? existing, string name, Dia
}
catch (PostgresException ex) when (ex.SqlState == PostgresErrorCodes.UniqueViolation) { throw new InvalidOperationException($"A diagram named {name} already exists in this database. Nothing was saved.", ex); }
await transaction.CommitAsync(token).ConfigureAwait(false);
- return saved;
+ return new(saved, layout);
}
/// Renames a saved diagram. With expectedVersion (the version an open tab read), a diagram changed or deleted since then is not renamed,
diff --git a/src/PGMS.PostgreSql/DiagramDescriptions.cs b/src/PGMS.PostgreSql/DiagramDescriptions.cs
new file mode 100644
index 0000000..afaba1e
--- /dev/null
+++ b/src/PGMS.PostgreSql/DiagramDescriptions.cs
@@ -0,0 +1,193 @@
+using System.Text;
+using Npgsql;
+using NpgsqlTypes;
+
+namespace PGMS.PostgreSql;
+
+/// One description kept in the saved diagram (PGMS-045): the COMMENT ON of a table, a column or a foreign key. The catalog is the source of truth;
+/// this copy lets tools and AI agents read the diagram without a connection. Applied false marks a description the user could not apply (only the owner
+/// of a table can comment on it and its columns and constraints): Text is the proposed description and DatabaseText what the catalog had at the save.
+public sealed record DiagramDescription(string Object, string? Name, string Text)
+{
+ public const string TableObject = "table", ColumnObject = "column", ForeignKeyObject = "foreignKey";
+ public bool Applied { get; init; } = true;
+ public string? DatabaseText { get; init; }
+
+ public bool Same(string obj, string? name) => Object == obj && Name == name;
+}
+
+/// Descriptions of the tables of a diagram: reading them from the catalog, the limit of the diagram, and the change of a table that is only descriptions.
+public static class DiagramDescriptions
+{
+ /// The limit of one description edited in a diagram (decisão do usuário, 11/11/2026): 4 KiB of UTF-8.
+ public const int MaxBytes = 4096;
+
+ public static string? LimitError(string? text) =>
+ text is null ? null : text.Contains('\0') ? "A description cannot contain the NUL character."
+ : Encoding.UTF8.GetByteCount(text) > MaxBytes ? $"A description can have at most {MaxBytes} bytes of UTF-8 ({Encoding.UTF8.GetByteCount(text)} now)." : null;
+
+ private static int Order(string obj) => obj switch { DiagramDescription.TableObject => 0, DiagramDescription.ColumnObject => 1, _ => 2 };
+ /// The stable order of the saved copy: the table, then columns, then foreign keys, each by name.
+ public static IReadOnlyList Sorted(IEnumerable items) =>
+ items.OrderBy(d => Order(d.Object)).ThenBy(d => d.Name ?? "", StringComparer.Ordinal).ToArray();
+
+ /// The descriptions a table has, as read with it.
+ public static IReadOnlyList Of(TableDesign design) => Sorted(
+ (design.Comment is { } table ? [new DiagramDescription(DiagramDescription.TableObject, null, table)] : Array.Empty())
+ .Concat(design.Columns.Where(c => c.Comment is not null).Select(c => new DiagramDescription(DiagramDescription.ColumnObject, c.Name, c.Comment!)))
+ .Concat(design.ForeignKeys.Where(k => k.Comment is not null).Select(k => new DiagramDescription(DiagramDescription.ForeignKeyObject, k.Name, k.Comment!))));
+
+ /// The description of one object of a design; null when it has none or the object is not there.
+ public static string? Text(TableDesign design, string obj, string? name) => obj switch
+ {
+ DiagramDescription.TableObject => design.Comment,
+ DiagramDescription.ColumnObject => design.Columns.FirstOrDefault(c => c.Name == name)?.Comment,
+ _ => design.ForeignKeys.FirstOrDefault(k => k.Name == name)?.Comment
+ };
+
+ /// The design with the descriptions of the original wherever the object existed before, so what is left to compare is structure.
+ public static TableDesign WithoutDescriptionChanges(TableDesign original, TableDesign current)
+ {
+ var columns = original.Columns.Where(c => c.Position is not null).ToDictionary(c => c.Position!.Value);
+ return current with
+ {
+ Comment = original.Comment,
+ Columns = current.Columns.Select(c => c.Position is { } p && columns.TryGetValue(p, out var before) ? c with { Comment = before.Comment } : c).ToArray(),
+ ForeignKeys = current.ForeignKeys.Select(k => k.OriginalName is { } was && original.ForeignKeys.FirstOrDefault(o => o.Name == was) is { } before ? k with { Comment = before.Comment } : k).ToArray()
+ };
+ }
+
+ /// Descriptions changed on objects that existed before; Text is the new description ("" when it is removed).
+ public static IReadOnlyList Changed(TableDesign original, TableDesign current)
+ {
+ var result = new List();
+ if (current.Comment != original.Comment) result.Add(new(DiagramDescription.TableObject, null, current.Comment ?? "") { DatabaseText = original.Comment });
+ var columns = original.Columns.Where(c => c.Position is not null).ToDictionary(c => c.Position!.Value);
+ foreach (var column in current.Columns)
+ if (column.Position is { } p && columns.TryGetValue(p, out var before) && before.Comment != column.Comment)
+ result.Add(new(DiagramDescription.ColumnObject, column.Name, column.Comment ?? "") { DatabaseText = before.Comment });
+ foreach (var key in current.ForeignKeys)
+ if (key.OriginalName is { } was && original.ForeignKeys.FirstOrDefault(o => o.Name == was) is { } before && before.Comment != key.Comment)
+ result.Add(new(DiagramDescription.ForeignKeyObject, key.Name, key.Comment ?? "") { DatabaseText = before.Comment });
+ return result;
+ }
+
+ /// Refuses a description edited in the diagram beyond the limit; descriptions read from the catalog as they are stay as they are.
+ public static void CheckLimits(TableDesign? original, TableDesign current)
+ {
+ string where = current.Schema + "." + current.Name;
+ void Check(string? text, string what) { if (LimitError(text) is { } error) throw new ArgumentException($"{what}: {error}"); }
+ if (current.Comment != original?.Comment) Check(current.Comment, where);
+ var columns = original?.Columns.Where(c => c.Position is not null).ToDictionary(c => c.Position!.Value) ?? [];
+ foreach (var column in current.Columns)
+ if (column.Position is not { } p || !columns.TryGetValue(p, out var before) || before.Comment != column.Comment) Check(column.Comment, $"{where}.{column.Name}");
+ foreach (var key in current.ForeignKeys)
+ if (key.OriginalName is not { } was || original?.ForeignKeys.FirstOrDefault(o => o.Name == was) is not { } before || before.Comment != key.Comment) Check(key.Comment, $"{where}, {key.Name}");
+ }
+
+ /// The COMMENT ON statement that sets one description of a table ("" or null removes it).
+ public static string CommentSql(string schema, string table, DiagramDescription item)
+ {
+ string relation = ObjectSql.Relation(schema, table), text = Literal(item.Text.Length == 0 ? null : item.Text);
+ return item.Object switch
+ {
+ DiagramDescription.TableObject => $"COMMENT ON TABLE {relation} IS {text};",
+ DiagramDescription.ColumnObject => $"COMMENT ON COLUMN {relation}.{SqlIdentifier.Quote(item.Name!)} IS {text};",
+ _ => $"COMMENT ON CONSTRAINT {SqlIdentifier.Quote(item.Name!)} ON {relation} IS {text};"
+ };
+ }
+ private static string Literal(string? value) => value is null ? "NULL" : "E'" + value.Replace("\\", "\\\\", StringComparison.Ordinal).Replace("'", "''", StringComparison.Ordinal) + "'";
+
+ private const string ReadSql = """
+ SELECT c.oid, 0, NULL::text, pg_catalog.obj_description(c.oid, 'pg_class') FROM pg_catalog.pg_class c
+ WHERE c.oid = ANY(@oids) AND pg_catalog.obj_description(c.oid, 'pg_class') IS NOT NULL
+ UNION ALL
+ SELECT a.attrelid, 1, a.attname::text, pg_catalog.col_description(a.attrelid, a.attnum) FROM pg_catalog.pg_attribute a
+ WHERE a.attrelid = ANY(@oids) AND a.attnum > 0 AND NOT a.attisdropped AND pg_catalog.col_description(a.attrelid, a.attnum) IS NOT NULL
+ UNION ALL
+ SELECT k.conrelid, 2, k.conname::text, pg_catalog.obj_description(k.oid, 'pg_constraint') FROM pg_catalog.pg_constraint k
+ WHERE k.conrelid = ANY(@oids) AND k.contype = 'f' AND pg_catalog.obj_description(k.oid, 'pg_constraint') IS NOT NULL
+ """;
+
+ /// The descriptions of tables, their columns and foreign keys, by table, in the stable order of the saved copy.
+ public static async Task>> ReadAsync(NpgsqlConnection connection, NpgsqlTransaction? transaction, IReadOnlyCollection oids, CancellationToken token = default)
+ {
+ var wanted = oids.Where(o => o != 0).Distinct().ToArray();
+ var found = wanted.ToDictionary(o => o, _ => new List());
+ if (wanted.Length > 0)
+ {
+ await using var command = new NpgsqlCommand(ReadSql, connection, transaction) { CommandTimeout = 30 };
+ command.Parameters.AddWithValue("oids", NpgsqlDbType.Array | NpgsqlDbType.Oid, wanted);
+ await using var reader = await command.ExecuteReaderAsync(token).ConfigureAwait(false);
+ while (await reader.ReadAsync(token).ConfigureAwait(false))
+ {
+ string obj = reader.GetInt32(1) switch { 0 => DiagramDescription.TableObject, 1 => DiagramDescription.ColumnObject, _ => DiagramDescription.ForeignKeyObject };
+ found[reader.GetFieldValue(0)].Add(new(obj, reader.IsDBNull(2) ? null : reader.GetString(2), reader.GetString(3)));
+ }
+ }
+ return found.ToDictionary(p => p.Key, p => Sorted(p.Value));
+ }
+
+ /// The copy a save writes: what the catalog has now and, for objects whose catalog text is not the proposed one, the descriptions not applied.
+ /// A description not applied that the catalog now has (someone with the privilege ran the script) is simply applied.
+ public static IReadOnlyList Merge(IReadOnlyList catalog, IEnumerable unapplied)
+ {
+ var pending = unapplied.Where(u => !u.Applied).GroupBy(u => (u.Object, u.Name)).Select(g => g.Last())
+ .Where(u => catalog.FirstOrDefault(c => c.Same(u.Object, u.Name))?.Text != (u.Text.Length == 0 ? null : u.Text)).ToArray();
+ return Sorted(catalog.Where(c => !pending.Any(u => u.Same(c.Object, c.Name)))
+ .Concat(pending.Select(u => u with { Applied = false, DatabaseText = catalog.FirstOrDefault(c => c.Same(u.Object, u.Name))?.Text })));
+ }
+
+ /// Tables among oids whose owner the current user is not (and is not a member of): PostgreSQL lets only the owner comment on a table and on its columns and constraints.
+ public static async Task> NotOwnedAsync(NpgsqlConnection connection, NpgsqlTransaction? transaction, IReadOnlyCollection oids, CancellationToken token = default)
+ {
+ var result = new HashSet();
+ var wanted = oids.Where(o => o != 0).Distinct().ToArray();
+ if (wanted.Length == 0) return result;
+ await using var command = new NpgsqlCommand("SELECT c.oid FROM pg_catalog.pg_class c WHERE c.oid = ANY(@oids) AND NOT pg_catalog.pg_has_role(c.relowner, 'USAGE')", connection, transaction) { CommandTimeout = 15 };
+ command.Parameters.AddWithValue("oids", NpgsqlDbType.Array | NpgsqlDbType.Oid, wanted);
+ await using var reader = await command.ExecuteReaderAsync(token).ConfigureAwait(false);
+ while (await reader.ReadAsync(token).ConfigureAwait(false)) result.Add(reader.GetFieldValue(0));
+ return result;
+ }
+}
+
+/// A table of a diagram whose only change is descriptions: COMMENT ON without the ACCESS EXCLUSIVE lock and full comparison of a structural change.
+/// Refused when the table, a column or a foreign key is no longer the one the diagram read (identity by OID, attnum and name), or when a description
+/// it changes was changed in the database since then.
+public sealed class DescriptionEdit(TableDesign original, TableDesign current) : IAdministrativeEdit
+{
+ public TableDesign Original => original;
+ public string ToSql() => TableDesignScript.Build(original, current).Sql;
+
+ public async Task ValidateAsync(NpgsqlConnection connection, NpgsqlTransaction transaction, CancellationToken token = default)
+ {
+ string table = original.Schema + "." + original.Name;
+ await using (var command = new NpgsqlCommand("SELECT c.oid, pg_catalog.obj_description(c.oid, 'pg_class') FROM pg_catalog.pg_class c JOIN pg_catalog.pg_namespace n ON n.oid=c.relnamespace WHERE n.nspname=@schema AND c.relname=@name AND c.relkind IN ('r','p')", connection, transaction) { CommandTimeout = 15 })
+ {
+ command.Parameters.AddWithValue("schema", original.Schema); command.Parameters.AddWithValue("name", original.Name);
+ await using var reader = await command.ExecuteReaderAsync(token).ConfigureAwait(false);
+ if (!await reader.ReadAsync(token).ConfigureAwait(false) || reader.GetFieldValue(0) != original.Oid)
+ throw new InvalidOperationException($"Table {table} changed since the diagram read it. Refresh the diagram before saving.");
+ if (current.Comment != original.Comment && (reader.IsDBNull(1) ? null : reader.GetString(1)) != original.Comment)
+ throw new InvalidOperationException($"The description of {table} changed in the database since the diagram read it. Refresh the diagram before saving.");
+ }
+ foreach (var item in DiagramDescriptions.Changed(original, current).Where(i => i.Object != DiagramDescription.TableObject))
+ {
+ bool column = item.Object == DiagramDescription.ColumnObject;
+ // A column is the attnum the diagram read, still with its name; a foreign key is the constraint of that name on this table.
+ var before = column ? original.Columns.First(c => c.Position == current.Columns.First(n => n.Name == item.Name).Position) : null;
+ string sql = column
+ ? "SELECT pg_catalog.col_description(a.attrelid, a.attnum) FROM pg_catalog.pg_attribute a WHERE a.attrelid=@oid AND a.attnum=@attnum AND a.attname=@name AND NOT a.attisdropped"
+ : "SELECT pg_catalog.obj_description(k.oid, 'pg_constraint') FROM pg_catalog.pg_constraint k WHERE k.conrelid=@oid AND k.conname=@name AND k.contype='f'";
+ await using var command = new NpgsqlCommand(sql, connection, transaction) { CommandTimeout = 15 };
+ command.Parameters.AddWithValue("oid", NpgsqlDbType.Oid, original.Oid); command.Parameters.AddWithValue("name", column ? before!.Name : item.Name!);
+ if (column) command.Parameters.AddWithValue("attnum", before!.Position!.Value);
+ await using var reader = await command.ExecuteReaderAsync(token).ConfigureAwait(false);
+ string what = column ? $"Column {table}.{before!.Name}" : $"Foreign key {item.Name} of {table}";
+ if (!await reader.ReadAsync(token).ConfigureAwait(false)) throw new InvalidOperationException($"{what} changed since the diagram read it. Refresh the diagram before saving.");
+ if ((reader.IsDBNull(0) ? null : reader.GetString(0)) != item.DatabaseText)
+ throw new InvalidOperationException($"The description of {what.ToLowerInvariant()[0]}{what[1..]} changed in the database since the diagram read it. Refresh the diagram before saving.");
+ }
+ }
+}
diff --git a/src/PGMS.PostgreSql/DiagramMarkdown.cs b/src/PGMS.PostgreSql/DiagramMarkdown.cs
new file mode 100644
index 0000000..41d7996
--- /dev/null
+++ b/src/PGMS.PostgreSql/DiagramMarkdown.cs
@@ -0,0 +1,146 @@
+using Npgsql;
+
+namespace PGMS.PostgreSql;
+
+/// Export for AI (PGMS-045): a diagram as Markdown for a system prompt or a CLAUDE.md/AGENTS.md, with tables, columns, keys, relationships, indexes
+/// and descriptions, read from the catalog in a stable order. One SQL query writes it, so the export of the diagram tab and the optional function
+/// pgms.diagram_markdown(name) give the same text: the tab runs the query with its layout, the function with the saved diagram. The query runs with
+/// search_path = pg_catalog, pg_temp, so every name outside pg_catalog is schema-qualified and the text does not depend on the session.
+public static class DiagramMarkdown
+{
+ public const string FunctionSignature = "pgms.diagram_markdown(text)";
+
+ /// The instruction at the top of the document, for the agent that reads it.
+ public const string Instruction = "Instructions for AI agents: read this document before writing SQL for this database. Use only the tables, columns and relationships listed here, with the names exactly as written; if what you need is not here, ask instead of guessing a name. Descriptions are the COMMENT ON of each object in PostgreSQL and say what it means. Check the indexes before writing queries that filter, join or sort large tables.";
+
+ // Markdown table cells and list items: a pipe would end the cell and a line break the row.
+ private static string Escape(string expression) => $"replace(replace(replace({expression}, '|', '\\|'), E'\\r\\n', ' '), E'\\n', ' ')";
+ private static string Cell(string expression) => $"COALESCE({Escape(expression)}, '')";
+ private static string Code(string expression) => $"CASE WHEN {expression} IS NULL THEN '' ELSE '`' || {Cell(expression)} || '`' END";
+
+ /// The query, with SQL expressions for the diagram definition (jsonb) and its name (text).
+ public static string Query(string definition, string name) => $$"""
+ WITH src AS (SELECT ({{definition}})::jsonb AS def, ({{name}})::text AS dname),
+ placed AS (
+ SELECT t.ord, t.item->>'schema' AS want_schema, t.item->>'name' AS want_name, COALESCE(
+ (SELECT c.oid FROM pg_catalog.pg_class c JOIN pg_catalog.pg_namespace n ON n.oid = c.relnamespace
+ WHERE n.nspname = t.item->>'schema' AND c.relname = t.item->>'name' AND c.relkind IN ('r','p')),
+ (SELECT c.oid FROM pg_catalog.pg_class c
+ WHERE (t.item->>'oid') ~ '^[1-9][0-9]{0,9}$' AND (t.item->>'oid')::bigint <= 4294967295 AND c.oid = (t.item->>'oid')::bigint::oid AND c.relkind IN ('r','p'))) AS oid
+ FROM src, pg_catalog.jsonb_array_elements(CASE WHEN pg_catalog.jsonb_typeof(src.def->'tables') = 'array' THEN src.def->'tables' ELSE '[]'::jsonb END) WITH ORDINALITY t(item, ord)
+ ),
+ tabs AS (
+ SELECT DISTINCT c.oid, n.nspname::text AS sch, c.relname::text AS tab
+ FROM placed p JOIN pg_catalog.pg_class c ON c.oid = p.oid JOIN pg_catalog.pg_namespace n ON n.oid = c.relnamespace
+ ),
+ sections AS (
+ SELECT t.sch, t.tab, pg_catalog.concat_ws(E'\n',
+ '## `' || t.sch || '.' || t.tab || '`',
+ '',
+ COALESCE(NULLIF(pg_catalog.btrim(pg_catalog.obj_description(t.oid, 'pg_class')), ''), '_No description._'),
+ '',
+ '| Column | Type | Null | Default | Description |',
+ '| --- | --- | --- | --- | --- |',
+ (SELECT pg_catalog.string_agg('| `' || {{Cell("a.attname::text")}} || '` | ' || {{Cell("pg_catalog.format_type(a.atttypid, a.atttypmod)")}} || ' | '
+ || CASE WHEN a.attnotnull THEN 'NOT NULL' ELSE 'NULL' END || ' | '
+ || CASE a.attidentity WHEN 'a' THEN 'GENERATED ALWAYS AS IDENTITY' WHEN 'd' THEN 'GENERATED BY DEFAULT AS IDENTITY'
+ ELSE CASE WHEN a.attgenerated <> '' THEN '`GENERATED ALWAYS AS (' || {{Cell("pg_catalog.pg_get_expr(d.adbin, d.adrelid)")}} || ') STORED`'
+ ELSE {{Code("pg_catalog.pg_get_expr(d.adbin, d.adrelid)")}} END END || ' | '
+ || {{Cell("pg_catalog.col_description(a.attrelid, a.attnum)")}} || ' |', E'\n' ORDER BY a.attnum)
+ FROM pg_catalog.pg_attribute a LEFT JOIN pg_catalog.pg_attrdef d ON d.adrelid = a.attrelid AND d.adnum = a.attnum
+ WHERE a.attrelid = t.oid AND a.attnum > 0 AND NOT a.attisdropped),
+ (SELECT E'\n**Keys and checks:**\n' || pg_catalog.string_agg('- ' || CASE k.contype WHEN 'p' THEN 'Primary key' WHEN 'u' THEN 'Unique' WHEN 'x' THEN 'Exclusion' ELSE 'Check' END
+ || ' `' || {{Cell("k.conname::text")}} || '`: `' || {{Cell("pg_catalog.pg_get_constraintdef(k.oid, true)")}} || '`'
+ || COALESCE(' — ' || {{Escape("NULLIF(pg_catalog.btrim(pg_catalog.obj_description(k.oid, 'pg_constraint')), '')")}}, ''),
+ E'\n' ORDER BY CASE k.contype WHEN 'p' THEN 0 WHEN 'u' THEN 1 WHEN 'x' THEN 2 ELSE 3 END, k.conname COLLATE "C")
+ FROM pg_catalog.pg_constraint k WHERE k.conrelid = t.oid AND k.contype IN ('p','u','x','c')),
+ (SELECT E'\n**Foreign keys:**\n' || pg_catalog.string_agg('- `' || {{Cell("k.conname::text")}} || '`: `' || {{Cell("pg_catalog.pg_get_constraintdef(k.oid, true)")}} || '`'
+ || COALESCE(' — ' || {{Escape("NULLIF(pg_catalog.btrim(pg_catalog.obj_description(k.oid, 'pg_constraint')), '')")}}, '')
+ || CASE WHEN EXISTS (
+ SELECT 1 FROM pg_catalog.pg_index i JOIN pg_catalog.pg_class ic ON ic.oid = i.indexrelid JOIN pg_catalog.pg_am am ON am.oid = ic.relam
+ WHERE i.indrelid = k.conrelid AND i.indisvalid AND i.indpred IS NULL AND am.amname IN ('btree','hash') AND i.indnkeyatts >= pg_catalog.cardinality(k.conkey)
+ AND (SELECT pg_catalog.array_agg(x ORDER BY x) FROM pg_catalog.unnest((i.indkey::int2[])[0:pg_catalog.cardinality(k.conkey) - 1]) x)
+ = (SELECT pg_catalog.array_agg(x ORDER BY x) FROM pg_catalog.unnest(k.conkey) x))
+ THEN '' ELSE E'\n - No index starts with these columns: deleting or updating a row of the referenced table reads this table to check the key.' END,
+ E'\n' ORDER BY k.conname COLLATE "C")
+ FROM pg_catalog.pg_constraint k WHERE k.conrelid = t.oid AND k.contype = 'f'),
+ (SELECT E'\n**Referenced by:**\n' || pg_catalog.string_agg('- `' || rn.nspname || '.' || r.relname || '`, foreign key `' || {{Cell("k.conname::text")}} || '`: `' || {{Cell("pg_catalog.pg_get_constraintdef(k.oid, true)")}} || '`',
+ E'\n' ORDER BY rn.nspname COLLATE "C", r.relname COLLATE "C", k.conname COLLATE "C")
+ FROM pg_catalog.pg_constraint k JOIN pg_catalog.pg_class r ON r.oid = k.conrelid JOIN pg_catalog.pg_namespace rn ON rn.oid = r.relnamespace
+ WHERE k.confrelid = t.oid AND k.contype = 'f'),
+ (SELECT E'\n**Indexes:**\n' || pg_catalog.string_agg('- `' || {{Cell("ic.relname::text")}} || '`'
+ || CASE WHEN i.indisprimary THEN ' (primary key)' WHEN NOT i.indisvalid THEN ' (invalid: the planner does not use it)' ELSE '' END
+ || ': `' || {{Cell("pg_catalog.pg_get_indexdef(i.indexrelid)")}} || '`'
+ || COALESCE(' — ' || {{Escape("NULLIF(pg_catalog.btrim(pg_catalog.obj_description(i.indexrelid, 'pg_class')), '')")}}, ''),
+ E'\n' ORDER BY i.indisprimary DESC, i.indisunique DESC, ic.relname COLLATE "C")
+ FROM pg_catalog.pg_index i JOIN pg_catalog.pg_class ic ON ic.oid = i.indexrelid
+ WHERE i.indrelid = t.oid AND i.indislive)
+ ) AS body
+ FROM tabs t
+ )
+ SELECT pg_catalog.concat_ws(E'\n',
+ '# Database model: ' || s.dname,
+ '',
+ '> {{Instruction.Replace("'", "''", StringComparison.Ordinal)}}',
+ '',
+ 'Database `' || pg_catalog.current_database() || '`, diagram "' || s.dname || '". Written by Postgres Management Studio (PGMS) from the PostgreSQL catalog. '
+ || (SELECT pg_catalog.count(*) FROM tabs) || ' table(s).',
+ '',
+ '## Tables',
+ '',
+ '| Table | Description |',
+ '| --- | --- |',
+ (SELECT pg_catalog.string_agg('| `' || t.sch || '.' || t.tab || '` | ' || {{Cell("NULLIF(pg_catalog.btrim(pg_catalog.obj_description(t.oid, 'pg_class')), '')")}} || ' |', E'\n' ORDER BY t.sch COLLATE "C", t.tab COLLATE "C") FROM tabs t),
+ (SELECT E'\nTables of the diagram that are no longer in the database: ' || pg_catalog.string_agg('`' || COALESCE(p.want_schema, '?') || '.' || COALESCE(p.want_name, '?') || '`', ', ' ORDER BY p.ord) || '.'
+ FROM placed p WHERE p.oid IS NULL),
+ (SELECT pg_catalog.string_agg(E'\n' || x.body, E'\n' ORDER BY x.sch COLLATE "C", x.tab COLLATE "C") FROM sections x)
+ ) || E'\n'
+ FROM src s WHERE s.def IS NOT NULL
+ """;
+
+ /// The function a connected agent can call; it reads the saved diagram by name and returns NULL when there is none.
+ public static string CreateFunctionSql => $"""
+ CREATE OR REPLACE FUNCTION pgms.diagram_markdown(diagram_name text) RETURNS text
+ LANGUAGE sql STABLE SECURITY INVOKER
+ SET search_path = pg_catalog, pg_temp
+ AS $pgms$
+ {Query("SELECT d.definition FROM pgms.diagrams d WHERE d.name = diagram_name", "diagram_name")}
+ $pgms$;
+ COMMENT ON FUNCTION {FunctionSignature} IS 'Postgres Management Studio (PGMS): the saved diagram of this name as Markdown for AI agents (tables, columns, keys, relationships, indexes and descriptions from the catalog). Read only; optional.';
+ """;
+
+ public const string DropFunctionSql = "DROP FUNCTION IF EXISTS pgms.diagram_markdown(text);";
+
+ /// The Markdown of a layout, read now from the catalog with the same query as the function.
+ public static async Task RenderAsync(string connectionString, string diagramName, DiagramLayout layout, CancellationToken token = default)
+ {
+ await using var connection = new NpgsqlConnection(connectionString);
+ await connection.OpenAsync(token).ConfigureAwait(false);
+ await using var transaction = await connection.BeginTransactionAsync(System.Data.IsolationLevel.RepeatableRead, token).ConfigureAwait(false);
+ await using (var setup = new NpgsqlCommand("SET TRANSACTION READ ONLY; SET LOCAL search_path = pg_catalog, pg_temp", connection, transaction)) await setup.ExecuteNonQueryAsync(token).ConfigureAwait(false);
+ await using var command = new NpgsqlCommand(Query("@definition", "@name"), connection, transaction) { CommandTimeout = 60 };
+ command.Parameters.AddWithValue("definition", NpgsqlTypes.NpgsqlDbType.Jsonb, layout.ToJson());
+ command.Parameters.AddWithValue("name", diagramName);
+ string text = (string)(await command.ExecuteScalarAsync(token).ConfigureAwait(false))!;
+ await transaction.CommitAsync(token).ConfigureAwait(false);
+ return text;
+ }
+
+ public static async Task IsFunctionInstalledAsync(string connectionString, CancellationToken token = default)
+ {
+ await using var connection = new NpgsqlConnection(connectionString);
+ await connection.OpenAsync(token).ConfigureAwait(false);
+ await using var command = new NpgsqlCommand($"SELECT pg_catalog.to_regprocedure('{FunctionSignature}') IS NOT NULL", connection) { CommandTimeout = 15 };
+ return (bool)(await command.ExecuteScalarAsync(token).ConfigureAwait(false))!;
+ }
+
+ /// Runs CreateFunctionSql or DropFunctionSql in one transaction. Creating needs CREATE on the schema pgms; removing, the ownership of the function.
+ public static async Task ApplyAsync(string connectionString, bool create, CancellationToken token = default)
+ {
+ await using var connection = new NpgsqlConnection(connectionString);
+ await connection.OpenAsync(token).ConfigureAwait(false);
+ await using var transaction = await connection.BeginTransactionAsync(token).ConfigureAwait(false);
+ await using (var command = new NpgsqlCommand(create ? CreateFunctionSql : DropFunctionSql, connection, transaction) { CommandTimeout = 30 }) await command.ExecuteNonQueryAsync(token).ConfigureAwait(false);
+ await transaction.CommitAsync(token).ConfigureAwait(false);
+ }
+}
diff --git a/tests/PGMS.DesktopTests/DatabaseDiagramChecks.cs b/tests/PGMS.DesktopTests/DatabaseDiagramChecks.cs
index 4e00bd5..686ba46 100644
--- a/tests/PGMS.DesktopTests/DatabaseDiagramChecks.cs
+++ b/tests/PGMS.DesktopTests/DatabaseDiagramChecks.cs
@@ -341,13 +341,13 @@ async Task Menu(CatalogEntry entry)
string[] Items(object? target) => view.FillMenu(new ContextMenu(), target).Items.OfType