Refactor Alembic migration for index management and column type update

- Simplified the index drop and creation logic in the `upgrade` and `downgrade` functions by removing the unnecessary existence check for the `carta_porte_codes` table.
- Updated the `iva_factor` column type in the `invoice_financials` table from VARCHAR to Numeric, enhancing data integrity.
- Improved the overall clarity and efficiency of the migration script.
This commit is contained in:
2026-03-24 18:05:24 -05:00
parent 06b3b20fd8
commit 28de77e50b
2 changed files with 7 additions and 38 deletions

View File

@@ -18,31 +18,11 @@ branch_labels: Union[str, Sequence[str], None] = None
depends_on: Union[str, Sequence[str], None] = None
def _public_table_exists(bind, name: str) -> bool:
"""Evita CREATE INDEX si la tabla no existe (BD parcial / orden atípico de migraciones)."""
return name in sa.inspect(bind).get_table_names(schema="public")
def upgrade() -> None:
"""Upgrade schema."""
# ### commands auto generated by Alembic - please adjust! ###
bind = op.get_bind()
if _public_table_exists(bind, "carta_porte_codes"):
# Coincide con 4ad64605fad2 (schema=public). if_exists: sin índice previo.
op.drop_index(
op.f("ix_public_carta_porte_code"),
table_name="carta_porte_codes",
schema="public",
if_exists=True,
)
op.create_index(
op.f("ix_public_carta_porte_codes_code"),
"carta_porte_codes",
["code"],
unique=False,
schema="public",
if_not_exists=True,
)
op.drop_index(op.f('ix_public_carta_porte_code'), table_name='carta_porte_codes')
op.create_index(op.f('ix_public_carta_porte_codes_code'), 'carta_porte_codes', ['code'], unique=False, schema='public')
op.alter_column('invoice_financials', 'iva_factor',
existing_type=sa.VARCHAR(length=10),
type_=sa.Numeric(precision=23, scale=8),
@@ -60,20 +40,6 @@ def downgrade() -> None:
type_=sa.VARCHAR(length=10),
existing_nullable=True,
schema='a76')
bind = op.get_bind()
if _public_table_exists(bind, "carta_porte_codes"):
op.drop_index(
op.f("ix_public_carta_porte_codes_code"),
table_name="carta_porte_codes",
schema="public",
if_exists=True,
)
op.create_index(
op.f("ix_public_carta_porte_code"),
"carta_porte_codes",
["code"],
unique=False,
schema="public",
if_not_exists=True,
)
op.drop_index(op.f('ix_public_carta_porte_codes_code'), table_name='carta_porte_codes', schema='public')
op.create_index(op.f('ix_public_carta_porte_code'), 'carta_porte_codes', ['code'], unique=False)
# ### end Alembic commands ###

View File

@@ -102,6 +102,9 @@ def ensure_tenant_company(db: Session, tenant_id: int, company_id: int) -> Compa
is_active=True,
)
db.add(tenant)
# El FK de a76.company → core.tenants exige que el tenant exista en esta transacción
# antes del INSERT de company; un solo flush al final puede ordenar mal (Tenant híbrido Column+Mapped).
db.flush()
company = db.get(Company, company_id)
if company is None: