Saltar a contenido

Especificación Técnica: cat_ciudades

Esquema: core.identidad
Base de Datos: core
Servicio: svc-identidad
Tabla Legacy Origen: core_sigfa.cat_ciudades
Propósito: Catálogo global de ciudades, vinculadas a su país de pertenencia.


1. Justificación y Mejoras de Arquitectura

  • Global: identifica ciudades sin contexto empresarial.
  • FK a cat_paises garantiza integridad referencial del territorio.
  • Índice ix_cat_ciudades_pais_id acelera búsquedas por país.
  • Evolución del legacy core_sigfa.cat_ciudades en core.identidad.

2. Definiciones de Implementación

Table core.identidad.cat_ciudades {
    id                         uuid          [pk, default: `gen_random_uuid()`]
    pais_id                    uuid          [not null, ref: > cat_paises.id]
    nombre                     varchar(100)  [not null]

    // Auditoría General
    is_activo               boolean       [not null, default: `true`, note: 'Estado lógico del registro']
    created_at              timestamptz   [not null, default: `now()`, note: 'Fecha de creación']
    updated_at              timestamptz   [not null, default: `now()`, note: 'Fecha de última actualización']
    deleted_at              timestamptz   [note: 'Fecha de eliminación lógica']
    created_by              uuid          [note: 'Usuario creador']
    updated_by              uuid          [note: 'Usuario modificador']

    Indexes {
        pais_id [name: 'ix_cat_ciudades_pais_id']
    }
}
CREATE TABLE IF NOT EXISTS core.identidad.cat_ciudades (
    id UUID NOT NULL DEFAULT gen_random_uuid() PRIMARY KEY,
    pais_id UUID NOT NULL,
    nombre VARCHAR(100) NOT NULL,

    -- Auditoría General
    is_activo BOOLEAN NOT NULL DEFAULT true,
    created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
    updated_at TIMESTAMPTZ NOT NULL DEFAULT now(),
    deleted_at TIMESTAMPTZ,
    created_by UUID,
    updated_by UUID,
    CONSTRAINT fk_cat_ciudades_pais FOREIGN KEY (pais_id) REFERENCES core.identidad.cat_paises (id)
);
CREATE INDEX IF NOT EXISTS ix_cat_ciudades_pais_id ON core.identidad.cat_ciudades (pais_id);

-- Comentarios
COMMENT ON COLUMN core.identidad.cat_ciudades.pais_id IS 'País al que pertenece la ciudad';
COMMENT ON COLUMN core.identidad.cat_ciudades.nombre IS 'Nombre de la ciudad';
from datetime import datetime, date
from typing import Optional
import uuid

from sqlalchemy import (
    BigInteger,
    Boolean,
    CheckConstraint,
    Date,
    DateTime,
    ForeignKey,
    Identity,
    Index,
    Integer,
    SmallInteger,
    String,
    Text,
    UniqueConstraint,
    text,
)
from sqlalchemy.dialects import postgresql
from sqlalchemy.orm import DeclarativeBase, Mapped, mapped_column


class Base(DeclarativeBase):
    pass

class CatCiudades(Base):
    __tablename__ = 'cat_ciudades'
    __table_args__ = (
        Index('ix_cat_ciudades_pais_id', 'pais_id'),
        {"schema": 'core.identidad'},
    )

    id: Mapped[uuid.UUID] = mapped_column(
        UUID(as_uuid=True),
        primary_key=True,
        server_default=text("gen_random_uuid()"),
    )
    pais_id: Mapped[uuid.UUID] = mapped_column(
        UUID(as_uuid=True),
        nullable=False,
        ForeignKey("cat_paises.id"),
        comment='País al que pertenece la ciudad',
    )
    nombre: Mapped[str] = mapped_column(
        String(100),
        nullable=False,
        comment='Nombre de la ciudad',
    )

    # Auditoría General
    is_activo: Mapped[bool] = mapped_column(
        Boolean,
        nullable=False,
        server_default=text("true"),
        comment='Estado lógico del registro',
    )
    created_at: Mapped[datetime] = mapped_column(
        DateTime(timezone=True),
        nullable=False,
        server_default=text("now()"),
        comment='Fecha de creación',
    )
    updated_at: Mapped[datetime] = mapped_column(
        DateTime(timezone=True),
        nullable=False,
        server_default=text("now()"),
        comment='Fecha de última actualización',
    )
    deleted_at: Mapped[datetime | None] = mapped_column(
        DateTime(timezone=True),
        comment='Fecha de eliminación lógica',
    )
    created_by: Mapped[uuid.UUID | None] = mapped_column(
        UUID(as_uuid=True),
        comment='Usuario creador',
    )
    updated_by: Mapped[uuid.UUID | None] = mapped_column(
        UUID(as_uuid=True),
        comment='Usuario modificador',
    )
"""revision: core_id_0002
create table core.identidad.cat_ciudades
"""

from alembic import op
import sqlalchemy as sa
from sqlalchemy.dialects import postgresql


revision: str = 'core_id_0002'
down_revision: str | None = 'core_id_0001'
branch_labels: str | None = None
depends_on: str | None = None


def upgrade() -> None:
    op.create_table(
        'cat_ciudades',
        sa.Column("id", postgresql.UUID(as_uuid=True), primary_key=True, server_default=sa.text("gen_random_uuid()")),
        sa.Column("pais_id", postgresql.UUID(as_uuid=True), nullable=False),
        sa.Column("nombre", sa.String(length=100), nullable=False),
        sa.Column("is_activo", sa.Boolean(), nullable=False, server_default=sa.text("true")),
        sa.Column("created_at", sa.DateTime(timezone=True), nullable=False, server_default=sa.text("now()")),
        sa.Column("updated_at", sa.DateTime(timezone=True), nullable=False, server_default=sa.text("now()")),
        sa.Column("deleted_at", sa.DateTime(timezone=True)),
        sa.Column("created_by", postgresql.UUID(as_uuid=True)),
        sa.Column("updated_by", postgresql.UUID(as_uuid=True)),
        sa.ForeignKeyConstraint(['pais_id'], ['core.identidad.cat_paises.id'], name='fk_cat_ciudades_pais'),
        schema='core.identidad',
    )
    op.create_index('ix_cat_ciudades_pais_id', 'cat_ciudades', ['pais_id'], unique=False, schema='core.identidad')


def downgrade() -> None:
    op.drop_table('cat_ciudades', schema='core.identidad')