citbi 0.4.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- cit_bi/__init__.py +26 -0
- cit_bi/bitacora.py +15 -0
- citbi/__init__.py +39 -0
- citbi/__main__.py +7 -0
- citbi/bd.py +509 -0
- citbi/bitacora.py +805 -0
- citbi/config.py +78 -0
- citbi/log_archivo.py +111 -0
- citbi-0.4.0.dist-info/METADATA +742 -0
- citbi-0.4.0.dist-info/RECORD +14 -0
- citbi-0.4.0.dist-info/WHEEL +5 -0
- citbi-0.4.0.dist-info/entry_points.txt +3 -0
- citbi-0.4.0.dist-info/licenses/LICENSE +21 -0
- citbi-0.4.0.dist-info/top_level.txt +2 -0
cit_bi/__init__.py
ADDED
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
"""cit_bi — Nombre anterior del paquete `citbi`. Se mantiene solo por compatibilidad.
|
|
2
|
+
|
|
3
|
+
Los scripts que usan `from cit_bi import ...` (o `cit_bi.bd`, `cit_bi.bitacora`, etc.) siguen
|
|
4
|
+
funcionando igual, pero muestran un aviso. Cambiar a `from citbi import ...`.
|
|
5
|
+
Este módulo se eliminará en una versión futura.
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
import sys as _sys
|
|
9
|
+
import warnings as _warnings
|
|
10
|
+
|
|
11
|
+
_warnings.warn(
|
|
12
|
+
"El paquete 'cit_bi' ahora se llama 'citbi': cambia 'from cit_bi import ...' por "
|
|
13
|
+
"'from citbi import ...'. El nombre anterior se eliminará en una versión futura.",
|
|
14
|
+
FutureWarning,
|
|
15
|
+
stacklevel=2,
|
|
16
|
+
)
|
|
17
|
+
|
|
18
|
+
import citbi as _citbi # noqa: E402
|
|
19
|
+
from citbi import * # noqa: E402, F403
|
|
20
|
+
from citbi import __all__, __version__, bd, bitacora, config, log_archivo # noqa: E402, F401
|
|
21
|
+
|
|
22
|
+
# `import cit_bi.bd`, `from cit_bi.config import ...`, etc. resuelven a los módulos de citbi
|
|
23
|
+
# (mismo objeto: los monkeypatch y el estado se comparten). `cit_bi.bitacora` es un archivo
|
|
24
|
+
# propio (cit_bi/bitacora.py) para que además funcione `python -m cit_bi.bitacora`.
|
|
25
|
+
for _nombre in ("bd", "config", "log_archivo"):
|
|
26
|
+
_sys.modules[f"{__name__}.{_nombre}"] = getattr(_citbi, _nombre)
|
cit_bi/bitacora.py
ADDED
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
"""cit_bi.bitacora — Nombre anterior de `citbi.bitacora` (compatibilidad).
|
|
2
|
+
|
|
3
|
+
- `import cit_bi.bitacora` / `from cit_bi.bitacora import ...` -> el mismo módulo citbi.bitacora.
|
|
4
|
+
- `python -m cit_bi.bitacora ...` -> la CLI de citbi (igual que `citbi-bitacora`).
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
import sys
|
|
8
|
+
|
|
9
|
+
import citbi.bitacora as _bitacora
|
|
10
|
+
|
|
11
|
+
if __name__ == "__main__":
|
|
12
|
+
sys.exit(_bitacora._main())
|
|
13
|
+
else:
|
|
14
|
+
# Se reemplaza a sí mismo por el módulo real: mismo objeto, mismo estado.
|
|
15
|
+
sys.modules[__name__] = _bitacora
|
citbi/__init__.py
ADDED
|
@@ -0,0 +1,39 @@
|
|
|
1
|
+
"""citbi — Utilidades de BI para Python: conexión homologada a bases de datos,
|
|
2
|
+
bitácora de ejecución de scripts y log diario.
|
|
3
|
+
|
|
4
|
+
from citbi import BaseDatos, BitacoraScript, configurar_log
|
|
5
|
+
|
|
6
|
+
Al importarse carga el .env (ver citbi.config). Para desactivarlo: CITBI_SIN_ENV=1
|
|
7
|
+
(se acepta también el nombre anterior, CIT_BI_SIN_ENV=1).
|
|
8
|
+
"""
|
|
9
|
+
|
|
10
|
+
import os as _os
|
|
11
|
+
|
|
12
|
+
from .config import archivo_entorno, cargar_entorno, directorio_base, resolver_ruta
|
|
13
|
+
|
|
14
|
+
if "1" not in (_os.getenv("CITBI_SIN_ENV"), _os.getenv("CIT_BI_SIN_ENV")):
|
|
15
|
+
cargar_entorno()
|
|
16
|
+
|
|
17
|
+
from .bd import BaseDatos, Resultado # noqa: E402
|
|
18
|
+
from .bitacora import ADVERTENCIA, EN_CURSO, ERROR, EXITO, BitacoraScript # noqa: E402
|
|
19
|
+
from .log_archivo import configurar_log, registrar_fin, ruta_log # noqa: E402
|
|
20
|
+
|
|
21
|
+
__version__ = "0.4.0"
|
|
22
|
+
|
|
23
|
+
__all__ = [
|
|
24
|
+
"BaseDatos",
|
|
25
|
+
"Resultado",
|
|
26
|
+
"BitacoraScript",
|
|
27
|
+
"EN_CURSO",
|
|
28
|
+
"EXITO",
|
|
29
|
+
"ADVERTENCIA",
|
|
30
|
+
"ERROR",
|
|
31
|
+
"configurar_log",
|
|
32
|
+
"registrar_fin",
|
|
33
|
+
"ruta_log",
|
|
34
|
+
"cargar_entorno",
|
|
35
|
+
"archivo_entorno",
|
|
36
|
+
"directorio_base",
|
|
37
|
+
"resolver_ruta",
|
|
38
|
+
"__version__",
|
|
39
|
+
]
|
citbi/__main__.py
ADDED
citbi/bd.py
ADDED
|
@@ -0,0 +1,509 @@
|
|
|
1
|
+
"""
|
|
2
|
+
citbi.bd — Acceso homologado a bases de datos.
|
|
3
|
+
|
|
4
|
+
Una sola clase, BaseDatos, para dos motores. Solo se indica cuál se quiere:
|
|
5
|
+
|
|
6
|
+
"AZ" SQL Server / Azure SQL (pyodbc) -> lectura y escritura
|
|
7
|
+
"PG" PostgreSQL (psycopg2) -> SOLO lectura (sesión read-only + bloqueo en la clase)
|
|
8
|
+
|
|
9
|
+
La configuración se toma de variables de entorno (normalmente del .env que carga citbi.config):
|
|
10
|
+
AZ: AZ_SERVER, AZ_DATABASE, AZ_USER, AZ_PASSWORD
|
|
11
|
+
opcionales: AZ_DRIVER (default "ODBC Driver 18 for SQL Server"),
|
|
12
|
+
AZ_ENCRYPT (yes|no, default yes), AZ_TRUST_CERT (yes|no, default no)
|
|
13
|
+
PG: PG_HOST, PG_DB, PG_USER, PG_PASSWORD
|
|
14
|
+
opcionales: PG_PORT (default 5432), PG_SSLMODE (default prefer)
|
|
15
|
+
|
|
16
|
+
Parámetros: en ambos motores se usa "?" como marcador (en PG se traduce a %s).
|
|
17
|
+
Limitación PG: el operador jsonb "?" no se puede usar; usar jsonb_exists(col, 'llave').
|
|
18
|
+
|
|
19
|
+
Uso
|
|
20
|
+
---
|
|
21
|
+
from citbi import BaseDatos
|
|
22
|
+
|
|
23
|
+
# Lectura (AZ y PG) ------------------------------------------------------
|
|
24
|
+
with BaseDatos("PG") as pg:
|
|
25
|
+
r = pg.select_tabla("public.mi_tabla") # SELECT *
|
|
26
|
+
r = pg.select_tabla("public.mi_tabla", campos=["id", "nombre"],
|
|
27
|
+
filtros={"activo": True}, orden="fecha DESC", limite=100)
|
|
28
|
+
r = pg.consulta("SELECT a.id, b.importe FROM a JOIN b ON b.id = a.id WHERE a.fecha >= ?",
|
|
29
|
+
["2026-01-01"])
|
|
30
|
+
r.columnas, r.filas, r.dicts(), r.dataframe(), r.escalar()
|
|
31
|
+
|
|
32
|
+
# Escritura (solo AZ) ------------------------------------------------------
|
|
33
|
+
# Con "with": COMMIT al terminar sin error, ROLLBACK si hay excepción.
|
|
34
|
+
with BaseDatos("AZ") as az:
|
|
35
|
+
az.insertar("dbo.MI_TABLA", [{"ID": 1, "NOMBRE": "A"}, {"ID": 2, "NOMBRE": "B"}])
|
|
36
|
+
az.insertar("dbo.MI_TABLA", [(3, "C"), (4, "D")], campos=["ID", "NOMBRE"])
|
|
37
|
+
az.actualizar("dbo.MI_TABLA", {"NOMBRE": "Z"}, filtros={"ID": 1})
|
|
38
|
+
az.actualizar("dbo.MI_TABLA", {"NOMBRE": "Z"}, filtros="ID > ? AND ACTIVO = 1", params=[10])
|
|
39
|
+
r = az.ejecutar_sp("dbo.MI_SP", {"Ejercicio": 2026})
|
|
40
|
+
az.ejecutar("TRUNCATE TABLE dbo.MI_TABLA") # DML/DDL libre
|
|
41
|
+
|
|
42
|
+
Nombres de tablas y campos: "esquema.tabla" se cita automáticamente ([..] en AZ, ".." en PG).
|
|
43
|
+
Si el nombre ya trae corchetes/comillas (p. ej. "[OTRA_BASE].[dbo].[X]") se usa tal cual.
|
|
44
|
+
"""
|
|
45
|
+
|
|
46
|
+
from __future__ import annotations
|
|
47
|
+
|
|
48
|
+
import logging
|
|
49
|
+
import os
|
|
50
|
+
import time
|
|
51
|
+
from collections.abc import Iterator, Mapping, Sequence
|
|
52
|
+
from contextlib import contextmanager
|
|
53
|
+
from typing import Any
|
|
54
|
+
|
|
55
|
+
from .config import archivo_entorno
|
|
56
|
+
|
|
57
|
+
log = logging.getLogger("citbi.bd")
|
|
58
|
+
|
|
59
|
+
MOTORES = ("AZ", "PG")
|
|
60
|
+
|
|
61
|
+
|
|
62
|
+
def _env_si(nombre: str, default: bool) -> bool:
|
|
63
|
+
"""Lee una variable yes/no (también true/false, 1/0)."""
|
|
64
|
+
valor = (os.getenv(nombre) or "").strip().lower()
|
|
65
|
+
if not valor:
|
|
66
|
+
return default
|
|
67
|
+
return valor in ("yes", "si", "sí", "true", "1")
|
|
68
|
+
|
|
69
|
+
|
|
70
|
+
_REQUERIDAS = {
|
|
71
|
+
"AZ": ("AZ_SERVER", "AZ_DATABASE", "AZ_USER", "AZ_PASSWORD"),
|
|
72
|
+
"PG": ("PG_HOST", "PG_DB", "PG_USER", "PG_PASSWORD"),
|
|
73
|
+
}
|
|
74
|
+
_CARACTERES_EXPRESION = set("()*+-/,' ")
|
|
75
|
+
|
|
76
|
+
|
|
77
|
+
# ---------------------------------------------------------------------------
|
|
78
|
+
# Resultado de una lectura
|
|
79
|
+
# ---------------------------------------------------------------------------
|
|
80
|
+
class Resultado:
|
|
81
|
+
"""Filas de una consulta con sus columnas.
|
|
82
|
+
|
|
83
|
+
columnas: nombres de columna.
|
|
84
|
+
tipos: AZ -> tipo Python de cada columna; PG -> OID del tipo en Postgres.
|
|
85
|
+
filas: lista de tuplas.
|
|
86
|
+
"""
|
|
87
|
+
|
|
88
|
+
def __init__(self, columnas: list[str], tipos: list[Any], filas: list[tuple]):
|
|
89
|
+
self.columnas = columnas
|
|
90
|
+
self.tipos = tipos
|
|
91
|
+
self.filas = filas
|
|
92
|
+
|
|
93
|
+
@classmethod
|
|
94
|
+
def desde_cursor(cls, cur, filas=None) -> Resultado:
|
|
95
|
+
if cur.description is None: # la sentencia no devolvió filas
|
|
96
|
+
return cls([], [], [])
|
|
97
|
+
columnas = [d[0] for d in cur.description]
|
|
98
|
+
tipos = [d[1] for d in cur.description]
|
|
99
|
+
if filas is None:
|
|
100
|
+
filas = cur.fetchall()
|
|
101
|
+
return cls(columnas, tipos, [tuple(f) for f in filas])
|
|
102
|
+
|
|
103
|
+
def __len__(self) -> int:
|
|
104
|
+
return len(self.filas)
|
|
105
|
+
|
|
106
|
+
def __iter__(self):
|
|
107
|
+
return iter(self.filas)
|
|
108
|
+
|
|
109
|
+
def __repr__(self) -> str:
|
|
110
|
+
return f"Resultado({len(self.filas)} filas x {len(self.columnas)} columnas)"
|
|
111
|
+
|
|
112
|
+
def dicts(self) -> list[dict]:
|
|
113
|
+
return [dict(zip(self.columnas, f, strict=False)) for f in self.filas]
|
|
114
|
+
|
|
115
|
+
def dataframe(self):
|
|
116
|
+
import pandas as pd
|
|
117
|
+
|
|
118
|
+
return pd.DataFrame.from_records(self.filas, columns=self.columnas)
|
|
119
|
+
|
|
120
|
+
def escalar(self):
|
|
121
|
+
"""Primer valor de la primera fila (o None)."""
|
|
122
|
+
return self.filas[0][0] if self.filas else None
|
|
123
|
+
|
|
124
|
+
|
|
125
|
+
# ---------------------------------------------------------------------------
|
|
126
|
+
# Conexión
|
|
127
|
+
# ---------------------------------------------------------------------------
|
|
128
|
+
class BaseDatos:
|
|
129
|
+
"""Conexión a "AZ" (lectura/escritura) o "PG" (solo lectura).
|
|
130
|
+
|
|
131
|
+
motor: "AZ" o "PG".
|
|
132
|
+
autocommit: solo AZ. False (default) = las escrituras se confirman con commit(),
|
|
133
|
+
con transaccion() o al salir de un bloque "with" sin error.
|
|
134
|
+
confiar_certificado: solo AZ. TrustServerCertificate=yes (certificado autofirmado on-premises).
|
|
135
|
+
None (default) = se toma de AZ_TRUST_CERT.
|
|
136
|
+
reintentos, espera: intentos de conexión y segundos entre ellos (Azure serverless puede
|
|
137
|
+
estar pausada).
|
|
138
|
+
"""
|
|
139
|
+
|
|
140
|
+
def __init__(
|
|
141
|
+
self,
|
|
142
|
+
motor: str = "AZ",
|
|
143
|
+
*,
|
|
144
|
+
autocommit: bool = False,
|
|
145
|
+
confiar_certificado: bool | None = None,
|
|
146
|
+
reintentos: int = 3,
|
|
147
|
+
espera: int = 20,
|
|
148
|
+
):
|
|
149
|
+
motor = motor.upper()
|
|
150
|
+
if motor not in MOTORES:
|
|
151
|
+
raise ValueError(f"Motor no soportado: {motor!r}. Usar 'AZ' o 'PG'.")
|
|
152
|
+
self.motor = motor
|
|
153
|
+
self.autocommit = autocommit
|
|
154
|
+
# None -> se toma de AZ_TRUST_CERT (yes/no); default no
|
|
155
|
+
if confiar_certificado is None:
|
|
156
|
+
confiar_certificado = _env_si("AZ_TRUST_CERT", False)
|
|
157
|
+
self.confiar_certificado = confiar_certificado
|
|
158
|
+
self.reintentos = max(1, reintentos)
|
|
159
|
+
self.espera = espera
|
|
160
|
+
self._cn = None
|
|
161
|
+
|
|
162
|
+
# ---- ciclo de vida ------------------------------------------------------
|
|
163
|
+
def conectar(self) -> BaseDatos:
|
|
164
|
+
if self._cn is not None:
|
|
165
|
+
return self
|
|
166
|
+
faltantes = [v for v in _REQUERIDAS[self.motor] if not os.getenv(v)]
|
|
167
|
+
if faltantes:
|
|
168
|
+
origen = archivo_entorno() or "el entorno (no se cargó ningún .env)"
|
|
169
|
+
raise OSError(f"Faltan variables en {origen}: {', '.join(faltantes)}")
|
|
170
|
+
|
|
171
|
+
conectar = self._conectar_az if self.motor == "AZ" else self._conectar_pg
|
|
172
|
+
ultimo = None
|
|
173
|
+
for i in range(1, self.reintentos + 1):
|
|
174
|
+
try:
|
|
175
|
+
self._cn = conectar()
|
|
176
|
+
return self
|
|
177
|
+
except Exception as e: # pyodbc.Error / psycopg2.Error
|
|
178
|
+
ultimo = e
|
|
179
|
+
log.warning(
|
|
180
|
+
"Conexión %s falló (intento %d/%d): %s",
|
|
181
|
+
self.motor,
|
|
182
|
+
i,
|
|
183
|
+
self.reintentos,
|
|
184
|
+
e,
|
|
185
|
+
)
|
|
186
|
+
if i < self.reintentos:
|
|
187
|
+
time.sleep(self.espera)
|
|
188
|
+
raise ultimo
|
|
189
|
+
|
|
190
|
+
def _conectar_az(self):
|
|
191
|
+
import pyodbc
|
|
192
|
+
|
|
193
|
+
# Sin pooling de ODBC: en Linux (unixODBC) una conexión reutilizada del pool puede no
|
|
194
|
+
# respetar autocommit y quedarse con una transacción abierta (y la fila bloqueada) tras
|
|
195
|
+
# cerrarla; la siguiente escritura sobre esa fila espera indefinidamente. Debe fijarse
|
|
196
|
+
# antes de la primera conexión del proceso.
|
|
197
|
+
pyodbc.pooling = False
|
|
198
|
+
cadena = (
|
|
199
|
+
f"Driver={{{os.getenv('AZ_DRIVER') or 'ODBC Driver 18 for SQL Server'}}};"
|
|
200
|
+
f"Server={os.getenv('AZ_SERVER')};"
|
|
201
|
+
f"Database={os.getenv('AZ_DATABASE')};"
|
|
202
|
+
f"Uid={os.getenv('AZ_USER')};Pwd={os.getenv('AZ_PASSWORD')};"
|
|
203
|
+
f"Encrypt={'yes' if _env_si('AZ_ENCRYPT', True) else 'no'};"
|
|
204
|
+
f"TrustServerCertificate={'yes' if self.confiar_certificado else 'no'};"
|
|
205
|
+
"Connection Timeout=60;"
|
|
206
|
+
)
|
|
207
|
+
return pyodbc.connect(cadena, autocommit=self.autocommit)
|
|
208
|
+
|
|
209
|
+
def _conectar_pg(self):
|
|
210
|
+
import psycopg2
|
|
211
|
+
|
|
212
|
+
cn = psycopg2.connect(
|
|
213
|
+
host=os.getenv("PG_HOST"),
|
|
214
|
+
port=int(os.getenv("PG_PORT") or 5432),
|
|
215
|
+
dbname=os.getenv("PG_DB"),
|
|
216
|
+
user=os.getenv("PG_USER"),
|
|
217
|
+
password=os.getenv("PG_PASSWORD"),
|
|
218
|
+
sslmode=os.getenv("PG_SSLMODE") or "prefer",
|
|
219
|
+
connect_timeout=30,
|
|
220
|
+
)
|
|
221
|
+
cn.set_session(readonly=True) # el servidor rechaza cualquier escritura
|
|
222
|
+
return cn
|
|
223
|
+
|
|
224
|
+
def cerrar(self) -> None:
|
|
225
|
+
if self._cn is not None:
|
|
226
|
+
try:
|
|
227
|
+
self._cn.close()
|
|
228
|
+
finally:
|
|
229
|
+
self._cn = None
|
|
230
|
+
|
|
231
|
+
close = cerrar # compatibilidad con código que espera una conexión DB-API
|
|
232
|
+
|
|
233
|
+
def __enter__(self) -> BaseDatos:
|
|
234
|
+
return self.conectar()
|
|
235
|
+
|
|
236
|
+
def __exit__(self, tipo_exc, exc, tb) -> None:
|
|
237
|
+
try:
|
|
238
|
+
if self._cn is not None and not self.autocommit:
|
|
239
|
+
if tipo_exc is None:
|
|
240
|
+
self.commit()
|
|
241
|
+
else:
|
|
242
|
+
self.rollback()
|
|
243
|
+
finally:
|
|
244
|
+
self.cerrar()
|
|
245
|
+
|
|
246
|
+
# ---- acceso de bajo nivel ------------------------------------------------
|
|
247
|
+
@property
|
|
248
|
+
def conexion(self):
|
|
249
|
+
"""Conexión nativa (pyodbc / psycopg2) para casos que la clase no cubre."""
|
|
250
|
+
return self.conectar()._cn
|
|
251
|
+
|
|
252
|
+
def cursor(self, *args, **kwargs):
|
|
253
|
+
"""Cursor nativo. En PG acepta name=... para cursor del lado servidor."""
|
|
254
|
+
return self.conexion.cursor(*args, **kwargs)
|
|
255
|
+
|
|
256
|
+
def commit(self) -> None:
|
|
257
|
+
if self._cn is not None:
|
|
258
|
+
self._cn.commit()
|
|
259
|
+
|
|
260
|
+
def rollback(self) -> None:
|
|
261
|
+
if self._cn is not None:
|
|
262
|
+
self._cn.rollback()
|
|
263
|
+
|
|
264
|
+
@contextmanager
|
|
265
|
+
def transaccion(self) -> Iterator[BaseDatos]:
|
|
266
|
+
"""COMMIT si el bloque termina bien, ROLLBACK si lanza excepción."""
|
|
267
|
+
self.conectar()
|
|
268
|
+
try:
|
|
269
|
+
yield self
|
|
270
|
+
self.commit()
|
|
271
|
+
except Exception:
|
|
272
|
+
self.rollback()
|
|
273
|
+
raise
|
|
274
|
+
|
|
275
|
+
# ---- utilidades internas ---------------------------------------------------
|
|
276
|
+
def _cita(self, nombre: str) -> str:
|
|
277
|
+
"""Cita un identificador (esquema.tabla / campo). Si ya viene citado, lo deja igual."""
|
|
278
|
+
if any(c in nombre for c in '[]"'):
|
|
279
|
+
return nombre
|
|
280
|
+
if self.motor == "AZ":
|
|
281
|
+
return ".".join("[" + p.replace("]", "]]") + "]" for p in nombre.split("."))
|
|
282
|
+
return ".".join('"' + p.replace('"', '""') + '"' for p in nombre.split("."))
|
|
283
|
+
|
|
284
|
+
def _campo(self, campo: str) -> str:
|
|
285
|
+
"""Campo de un SELECT: se cita salvo que sea una expresión (función, alias, *, etc.)."""
|
|
286
|
+
if campo == "*" or any(c in _CARACTERES_EXPRESION for c in campo):
|
|
287
|
+
return campo
|
|
288
|
+
return self._cita(campo)
|
|
289
|
+
|
|
290
|
+
def _sql(self, sql: str, params) -> str:
|
|
291
|
+
"""Traduce "?" -> "%s" para PG (fuera de literales) y escapa "%" si hay parámetros."""
|
|
292
|
+
if self.motor == "AZ" or not params:
|
|
293
|
+
return sql
|
|
294
|
+
salida, comilla = [], None
|
|
295
|
+
for c in sql:
|
|
296
|
+
if comilla:
|
|
297
|
+
if c == comilla:
|
|
298
|
+
comilla = None
|
|
299
|
+
salida.append("%%" if c == "%" else c)
|
|
300
|
+
elif c in ("'", '"'):
|
|
301
|
+
comilla = c
|
|
302
|
+
salida.append(c)
|
|
303
|
+
elif c == "?":
|
|
304
|
+
salida.append("%s")
|
|
305
|
+
elif c == "%":
|
|
306
|
+
salida.append("%%")
|
|
307
|
+
else:
|
|
308
|
+
salida.append(c)
|
|
309
|
+
return "".join(salida)
|
|
310
|
+
|
|
311
|
+
def _filtros(self, filtros, params) -> tuple[str, list]:
|
|
312
|
+
"""dict -> "a = ? AND b IS NULL"; str -> se usa tal cual con params."""
|
|
313
|
+
if not filtros:
|
|
314
|
+
return "", list(params or [])
|
|
315
|
+
if isinstance(filtros, Mapping):
|
|
316
|
+
partes, valores = [], []
|
|
317
|
+
for campo, valor in filtros.items():
|
|
318
|
+
if valor is None:
|
|
319
|
+
partes.append(f"{self._cita(campo)} IS NULL")
|
|
320
|
+
else:
|
|
321
|
+
partes.append(f"{self._cita(campo)} = ?")
|
|
322
|
+
valores.append(valor)
|
|
323
|
+
return " WHERE " + " AND ".join(partes), valores + list(params or [])
|
|
324
|
+
return f" WHERE {filtros}", list(params or [])
|
|
325
|
+
|
|
326
|
+
def _ejecutar(self, cur, sql: str, params=None):
|
|
327
|
+
params = list(params) if params else None
|
|
328
|
+
sql = self._sql(sql, params)
|
|
329
|
+
if params:
|
|
330
|
+
cur.execute(sql, params)
|
|
331
|
+
else:
|
|
332
|
+
cur.execute(sql)
|
|
333
|
+
return cur
|
|
334
|
+
|
|
335
|
+
def _solo_az(self, accion: str) -> None:
|
|
336
|
+
if self.motor != "AZ":
|
|
337
|
+
raise PermissionError(
|
|
338
|
+
f"{accion}: la conexión {self.motor} es de solo lectura."
|
|
339
|
+
)
|
|
340
|
+
|
|
341
|
+
# ---- lectura (AZ y PG) -----------------------------------------------------
|
|
342
|
+
def consulta(self, sql: str, params: Sequence | None = None) -> Resultado:
|
|
343
|
+
"""Consulta libre (con JOINs, CTEs, etc.). Devuelve todas las filas."""
|
|
344
|
+
cur = self.cursor()
|
|
345
|
+
try:
|
|
346
|
+
return Resultado.desde_cursor(self._ejecutar(cur, sql, params))
|
|
347
|
+
finally:
|
|
348
|
+
cur.close()
|
|
349
|
+
|
|
350
|
+
def select_tabla(
|
|
351
|
+
self,
|
|
352
|
+
tabla: str,
|
|
353
|
+
campos: Sequence[str] | None = None,
|
|
354
|
+
filtros: Mapping[str, Any] | str | None = None,
|
|
355
|
+
params: Sequence | None = None,
|
|
356
|
+
orden: str | Sequence[str] | None = None,
|
|
357
|
+
limite: int | None = None,
|
|
358
|
+
) -> Resultado:
|
|
359
|
+
"""SELECT sobre una tabla o vista.
|
|
360
|
+
|
|
361
|
+
campos: None = todos (*); lista de campos o expresiones ("COUNT(*) AS N").
|
|
362
|
+
filtros: dict {campo: valor} (igualdad, None -> IS NULL) o texto WHERE con "?" + params.
|
|
363
|
+
orden: texto ("FECHA DESC") o lista de campos.
|
|
364
|
+
limite: máximo de filas (TOP en AZ, LIMIT en PG).
|
|
365
|
+
"""
|
|
366
|
+
lista = ", ".join(self._campo(c) for c in campos) if campos else "*"
|
|
367
|
+
top = f"TOP ({int(limite)}) " if (limite and self.motor == "AZ") else ""
|
|
368
|
+
where, valores = self._filtros(filtros, params)
|
|
369
|
+
sql = f"SELECT {top}{lista} FROM {self._cita(tabla)}{where}"
|
|
370
|
+
if orden:
|
|
371
|
+
sql += " ORDER BY " + (
|
|
372
|
+
orden
|
|
373
|
+
if isinstance(orden, str)
|
|
374
|
+
else ", ".join(self._campo(c) for c in orden)
|
|
375
|
+
)
|
|
376
|
+
if limite and self.motor == "PG":
|
|
377
|
+
sql += f" LIMIT {int(limite)}"
|
|
378
|
+
return self.consulta(sql, valores)
|
|
379
|
+
|
|
380
|
+
def iterar(
|
|
381
|
+
self, sql: str, params: Sequence | None = None, lote: int = 5000
|
|
382
|
+
) -> Iterator[Resultado]:
|
|
383
|
+
"""Lee una consulta grande por lotes sin cargarla completa en memoria.
|
|
384
|
+
En PG usa un cursor del lado servidor."""
|
|
385
|
+
if self.motor == "PG":
|
|
386
|
+
cur = self.cursor(name=f"citbi_{id(self)}")
|
|
387
|
+
cur.itersize = lote
|
|
388
|
+
else:
|
|
389
|
+
cur = self.cursor()
|
|
390
|
+
try:
|
|
391
|
+
self._ejecutar(cur, sql, params)
|
|
392
|
+
while True:
|
|
393
|
+
filas = cur.fetchmany(lote)
|
|
394
|
+
if not filas:
|
|
395
|
+
break
|
|
396
|
+
yield Resultado.desde_cursor(cur, filas)
|
|
397
|
+
finally:
|
|
398
|
+
cur.close()
|
|
399
|
+
|
|
400
|
+
# ---- escritura (solo AZ) -----------------------------------------------------
|
|
401
|
+
def insertar(
|
|
402
|
+
self,
|
|
403
|
+
tabla: str,
|
|
404
|
+
datos,
|
|
405
|
+
campos: Sequence[str] | None = None,
|
|
406
|
+
lote: int = 5000,
|
|
407
|
+
rapido: bool = True,
|
|
408
|
+
) -> int:
|
|
409
|
+
"""INSERT de una o varias filas. Devuelve el número de filas insertadas.
|
|
410
|
+
|
|
411
|
+
datos: dict (una fila), lista de dicts, o lista de tuplas (en ese caso campos es obligatorio).
|
|
412
|
+
campos: columnas destino; con dicts se toman de la primera fila si no se indican.
|
|
413
|
+
rapido: fast_executemany de pyodbc (desactivarlo si hay problemas con NVARCHAR(MAX)).
|
|
414
|
+
"""
|
|
415
|
+
self._solo_az("insertar")
|
|
416
|
+
if isinstance(datos, Mapping):
|
|
417
|
+
datos = [datos]
|
|
418
|
+
datos = list(datos)
|
|
419
|
+
if not datos:
|
|
420
|
+
return 0
|
|
421
|
+
if isinstance(datos[0], Mapping):
|
|
422
|
+
campos = list(campos or datos[0].keys())
|
|
423
|
+
filas = [tuple(d.get(c) for c in campos) for d in datos]
|
|
424
|
+
else:
|
|
425
|
+
if not campos:
|
|
426
|
+
raise ValueError(
|
|
427
|
+
"insertar: con filas en tupla hay que indicar 'campos'."
|
|
428
|
+
)
|
|
429
|
+
filas = [tuple(f) for f in datos]
|
|
430
|
+
|
|
431
|
+
sql = (
|
|
432
|
+
f"INSERT INTO {self._cita(tabla)} ({', '.join(self._cita(c) for c in campos)}) "
|
|
433
|
+
f"VALUES ({', '.join('?' for _ in campos)})"
|
|
434
|
+
)
|
|
435
|
+
cur = self.cursor()
|
|
436
|
+
try:
|
|
437
|
+
cur.fast_executemany = rapido
|
|
438
|
+
for i in range(0, len(filas), lote):
|
|
439
|
+
cur.executemany(sql, filas[i : i + lote])
|
|
440
|
+
finally:
|
|
441
|
+
cur.close()
|
|
442
|
+
log.debug("insertar %s: %d filas", tabla, len(filas))
|
|
443
|
+
return len(filas)
|
|
444
|
+
|
|
445
|
+
def actualizar(
|
|
446
|
+
self,
|
|
447
|
+
tabla: str,
|
|
448
|
+
valores: Mapping[str, Any],
|
|
449
|
+
filtros: Mapping[str, Any] | str,
|
|
450
|
+
params: Sequence | None = None,
|
|
451
|
+
) -> int:
|
|
452
|
+
"""UPDATE tabla SET ... WHERE ... Devuelve filas afectadas.
|
|
453
|
+
|
|
454
|
+
filtros es obligatorio para no actualizar la tabla completa por accidente;
|
|
455
|
+
si de verdad se quiere, pasar filtros="1=1".
|
|
456
|
+
"""
|
|
457
|
+
self._solo_az("actualizar")
|
|
458
|
+
if not valores:
|
|
459
|
+
raise ValueError("actualizar: 'valores' está vacío.")
|
|
460
|
+
if not filtros:
|
|
461
|
+
raise ValueError(
|
|
462
|
+
"actualizar: indica 'filtros' (usa \"1=1\" para toda la tabla)."
|
|
463
|
+
)
|
|
464
|
+
sets = ", ".join(f"{self._cita(c)} = ?" for c in valores)
|
|
465
|
+
where, valores_where = self._filtros(filtros, params)
|
|
466
|
+
sql = f"UPDATE {self._cita(tabla)} SET {sets}{where}"
|
|
467
|
+
cur = self.cursor()
|
|
468
|
+
try:
|
|
469
|
+
return self._ejecutar(
|
|
470
|
+
cur, sql, list(valores.values()) + valores_where
|
|
471
|
+
).rowcount
|
|
472
|
+
finally:
|
|
473
|
+
cur.close()
|
|
474
|
+
|
|
475
|
+
def ejecutar_sp(
|
|
476
|
+
self, nombre: str, params: Mapping[str, Any] | Sequence | None = None
|
|
477
|
+
) -> Resultado:
|
|
478
|
+
"""EXEC de un stored procedure. Devuelve su primer conjunto de resultados (o vacío).
|
|
479
|
+
|
|
480
|
+
params: dict {"Parametro": valor} -> EXEC sp @Parametro = ? (el @ es opcional)
|
|
481
|
+
lista [v1, v2] -> EXEC sp ?, ? (posicional)
|
|
482
|
+
"""
|
|
483
|
+
self._solo_az("ejecutar_sp")
|
|
484
|
+
if isinstance(params, Mapping):
|
|
485
|
+
args = ", ".join(f"@{k.lstrip('@')} = ?" for k in params)
|
|
486
|
+
valores = list(params.values())
|
|
487
|
+
elif params:
|
|
488
|
+
args = ", ".join("?" for _ in params)
|
|
489
|
+
valores = list(params)
|
|
490
|
+
else:
|
|
491
|
+
args, valores = "", []
|
|
492
|
+
sql = f"SET NOCOUNT ON; EXEC {self._cita(nombre)} {args}".rstrip()
|
|
493
|
+
cur = self.cursor()
|
|
494
|
+
try:
|
|
495
|
+
self._ejecutar(cur, sql, valores)
|
|
496
|
+
while cur.description is None and cur.nextset():
|
|
497
|
+
pass
|
|
498
|
+
return Resultado.desde_cursor(cur)
|
|
499
|
+
finally:
|
|
500
|
+
cur.close()
|
|
501
|
+
|
|
502
|
+
def ejecutar(self, sql: str, params: Sequence | None = None) -> int:
|
|
503
|
+
"""Sentencia libre de escritura (DELETE, TRUNCATE, CREATE, MERGE...). Devuelve rowcount."""
|
|
504
|
+
self._solo_az("ejecutar")
|
|
505
|
+
cur = self.cursor()
|
|
506
|
+
try:
|
|
507
|
+
return self._ejecutar(cur, sql, params).rowcount
|
|
508
|
+
finally:
|
|
509
|
+
cur.close()
|