Keyboard shortcuts

Press ← or → to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

Catálogo físico e relações sys.*

O Amphi possui duas camadas de metadados:

  1. as tabelas físicas sys.*, persistidas pelo catálogo do cluster;
  2. as views públicas sys.catalog_*, destinadas a clientes, Console e ferramentas de inspeção.

As tabelas físicas são transparentes para diagnóstico e desenvolvimento do engine, mas seu formato é um contrato interno. Aplicações novas devem preferir as views públicas, que traduzem OIDs e códigos numéricos para nomes estáveis.

Relações físicas persistentes

O catálogo físico usa OIDs fixos. A lista abaixo mostra o OID e as colunas na ordem física de armazenamento:

1  schema              (oid int4, name text)
2  relation            (oid int4, storage_oid int4, schema int4, name text,
                        kind int2, engine int2, toast_rel int4, options bytea,
                        comment text)
3  attribute           (rel int4, attno int2, name text, type int4,
                        type_mod int4, not_null bool, dropped bool, comment text)
4  type                (oid int4, name text, len int2, schema int4,
                        element_type int4, array_type int4)
5  function            (oid int4, name text, arg_types bytea, ret_type int4,
                        native int4, aggregate bool, volatility int2,
                        schema int4, security_definer bool)
6  operator            (oid int4, name text, left int4, right int4,
                        ret_type int4, func int4, commutator int4, negator int4)
7  opclass             (oid int4, name text, am int2, type int4,
                        is_default bool, compare int4)
8  opclass_operator    (opclass int4, strategy int2, operator int4)
9  cast                (source int4, target int4, func int4, context int2)
10 index               (index_rel int4, table_rel int4, am int2, unique bool,
                        columns bytea, valid bool)
11 collection_dict    (rel int4, key_id int4, key text)
13 view_def            (rel int4, query text)
18 attr_def            (rel int4, attno int2, sequence int4)
19 sequence            (rel int4, high int8, start int8, increment int8,
                        min int8, max int8, cycle bool, cache int8)
20 role                (oid int4, name text, can_login bool, enabled bool,
                        is_admin bool, can_create_db bool, can_create_role bool,
                        inherit bool, valid_until int8)
21 group               (oid int4, name text)
22 group_member        (group int4, member int4)
23 role_credential     (role int4, salt bytea, iterations int4,
                        stored_key bytea, server_key bytea)
24 access_policy       (oid int4, name text, priority int4, subject_kind int2,
                        subject int4, source text, database text, allow bool,
                        rate_per_second int4, burst int4)
27 check_constraint    (oid int4, relation int4, name text, expression text)
28 foreign_key         (oid int4, relation int4, name text, columns bytea,
                        referenced_relation int4, referenced_columns bytea,
                        on_delete int2, on_update int2, deferrable bool,
                        initially_deferred bool)
40 foreign_server      (name text, connection text, options bytea)
41 foreign_table       (relation int4, server text, options bytea)
46 column_default     (rel int4, attno int2, expression text)
47 column_missing     (rel int4, attno int2, expression text)
48 acl                 (relation int4, grantee_kind int2, grantee int4,
                        grantor int4, privilege int2, scope_kind int2,
                        columns bytea, grant_option bool)
50 default_acl         (owner int4, object_kind int2, grantee_kind int2,
                        grantee int4, privilege int2, scope_kind int2,
                        columns bytea, grant_option bool)
74 object_comment     (object_oid int4, object_kind text, comment text)
76 named_object_identity (object_oid int4, object_kind text, object_name text)
12 meta                (catalog_version int4, ddl_seq int8, next_oid int4)
14 stat_user_tables    (relid int4, schema text, name text, n_tup_ins int8,
                        n_tup_upd int8, n_tup_del int8, n_live_tup int8,
                        n_dead_tup int8, last_vacuum int8, last_analyze int8)
17 stat_column         (relid int4, attno int4, null_frac float8,
                        n_distinct int8, correlation float8, mcv text,
                        histogram text)
36 schedule            (id int8, name text, owner int4, trigger_kind int2,
                        interval_us int8, start_at int8, at int8,
                        action_kind text, action_payload bytea, overlap int2,
                        catch_up int2, timeout_us int8, max_retries int4,
                        state int2, next_run int8, generation int8)
37 schedule_run        (run_id int8, schedule_id int8, scheduled_at int8,
                        started_at int8, finished_at int8, state int2,
                        attempt int4, origin int2, error text, rows int8)
45 external_connection (name text, provider text, options bytea)
52 trigger             (oid int4, relation int4, name text, function int4,
                        timing int2, level int2, events int2, scope int2,
                        arguments bytea, enabled bool)
54 partition           (relation int4, parent int4, bound text)
59 system_alarm        (id int8, kind text, owner int4, scheduled_at int8,
                        state int2, attempt int4, started_at int8,
                        finished_at int8, error text, affected_objects int4,
                        lease_owner int8, lease_until int8)
60 domain              (oid int4, schema int4, name text, base_type int4,
                        default_expression text, not_null bool, checks bytea)
61 partition_policy    (oid int4, name text, schema int4, is_default bool,
                        relation_kind int2, match_column text, match_type int4,
                        strategy text, key text, every text, retention text,
                        sub_strategy text, sub_key text, subpartitions int2,
                        retention_action text, retention_server text)
65 tablespace          (oid int4, name text, location text, owner int4,
                        is_default bool)
68 stat_progress       (operation_id int8, kind text, state text, phase text,
                        alarm_id int8, relation int4, rows_done int8,
                        rows_total int8, bytes_done int8, bytes_total int8,
                        started_at int8, updated_at int8, error text)
69 object_revision     (object_oid int4, object_kind text, version int8,
                        source text, arg_names bytea, created_at int8,
                        created_by int4, ddl_seq int8, dependencies bytea)
70 prepared_transactions (gid text, xid int8, prepared_at int8, owner text)
72 extension            (name text, schema int4, version text)

stat_activity e blocking_tree também aparecem na lista de relações do catálogo, mas são relações virtuais do processo e não possuem heap persistente.

Campos que exigem atenção

sys.attribute.type_mod contém os modificadores de tipo. Atualmente:

-1       sem modificador
5        varchar(5)
-6       char(5)

columns e referenced_columns em índices, ACLs e foreign keys são listas de posições codificadas em bytea. O catálogo físico usa OIDs e códigos numéricos; por exemplo, relation.kind, index.am, ações de FK e privilégios precisam ser traduzidos pela camada que conhece o contrato.

Relações apenas de runtime

O engine cria algumas relações no catálogo em memória para expor o estado atual das extensões e linguagens:

Oid(100) available_extensions
Oid(101) extension_lifecycle
Oid(102) extension_metrics
Oid(103) languages

Esses OIDs ficam deliberadamente fora da faixa das relações físicas persistentes e não devem ser reutilizados por novas relações sys.*. Uma colisão mistura schemas de RowCodec diferentes e pode fazer uma relação interna ser lida com o tipo errado.

Views públicas

As views sys.catalog_* são o contrato recomendado para ferramentas:

sys.catalog_schemas
sys.catalog_objects
sys.catalog_columns
sys.catalog_indexes
sys.catalog_types
sys.catalog_functions
sys.catalog_checks
sys.catalog_foreign_keys
sys.catalog_roles
sys.catalog_groups
sys.catalog_group_members
sys.catalog_acls
sys.catalog_default_acls
sys.catalog_domains
sys.catalog_partitions
sys.catalog_object_tags
sys.catalog_object_comments

Suas colunas e exemplos de consulta estão em Views de sistema.

Metadados de objetos e tags

Tags são metadados consultáveis, não apenas decoração da interface. A implementação usa um catálogo relacional próprio ligado à identidade estável do objeto (OID) e uma view pública sys.catalog_object_tags; não adicionar uma coluna de lista variável em sys.catalog_objects. Objetos suportados devem permitir inserir, alterar e remover tags por SQL, consultá-las em joins/filtros e visualizá-las no Web Console. Comentários continuam sendo texto livre e têm semântica separada.

Regra para novos tipos de objeto: ao introduzir um tipo de objeto persistente com identidade no catálogo, incluir sua identidade no contrato de tagging (SQL, catálogo/view, consulta, permissões, dump/restore e Console) ou registrar neste documento uma justificativa explícita para não se aplicar. Não considerar um tipo completo sem essa decisão. Objetos internos sem identidade administrável podem ser excluídos, mas a exclusão deve ser documentada.

O plano e o inventário inicial de tipos estão em Tags de objetos.

Compatibilidade e migração

Alterar uma coluna, seu tipo ou sua posição muda o formato físico do catálogo. Essas mudanças exigem incremento de CATALOG_VERSION e uma migração explícita. Não se deve reutilizar OIDs persistentes nem assumir que o número do OID indica a posição de uma tabela no arquivo de definição.