contlity 0.3.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.
- contlity/__init__.py +64 -0
- contlity/client.py +227 -0
- contlity/dbapi.py +408 -0
- contlity/exceptions.py +45 -0
- contlity/resources/__init__.py +22 -0
- contlity/resources/account.py +33 -0
- contlity/resources/cargas.py +97 -0
- contlity/resources/cfdis.py +27 -0
- contlity/resources/clients.py +15 -0
- contlity/resources/credits.py +26 -0
- contlity/resources/sat.py +50 -0
- contlity/resources/sql.py +46 -0
- contlity/resources/webhooks.py +93 -0
- contlity/resources/workflows.py +36 -0
- contlity/sqlalchemy_dialect.py +266 -0
- contlity/webhook_handler.py +92 -0
- contlity-0.3.0.dist-info/METADATA +362 -0
- contlity-0.3.0.dist-info/RECORD +21 -0
- contlity-0.3.0.dist-info/WHEEL +5 -0
- contlity-0.3.0.dist-info/entry_points.txt +2 -0
- contlity-0.3.0.dist-info/top_level.txt +1 -0
contlity/__init__.py
ADDED
|
@@ -0,0 +1,64 @@
|
|
|
1
|
+
"""
|
|
2
|
+
Contlity Python SDK — cliente oficial para la API de Contlity.
|
|
3
|
+
|
|
4
|
+
Uso rápido:
|
|
5
|
+
from contlity import ContlityClient, WebhookHandler
|
|
6
|
+
|
|
7
|
+
client = ContlityClient("ctly_live_...")
|
|
8
|
+
|
|
9
|
+
# Listar clientes
|
|
10
|
+
clients = client.clients.list()
|
|
11
|
+
|
|
12
|
+
# Ejecutar SQL
|
|
13
|
+
result = client.sql.execute("SELECT COUNT(*) AS total FROM cfdi")
|
|
14
|
+
|
|
15
|
+
# Driver SQL (DB-API 2.0) y SQLAlchemy
|
|
16
|
+
import contlity.dbapi as ctly
|
|
17
|
+
cur = ctly.connect(database="despacho").cursor()
|
|
18
|
+
cur.execute("SELECT * FROM ventas.facturas WHERE total > %s", (1000,))
|
|
19
|
+
# create_engine("contlity:///despacho") → pip install "contlity[sqlalchemy]"
|
|
20
|
+
|
|
21
|
+
# SAT Descarga
|
|
22
|
+
job = client.sat.sync("RFC123456789", "recibidos", "2026-01-01", "2026-01-31")
|
|
23
|
+
status = client.sat.job_status(job["job_id"])
|
|
24
|
+
|
|
25
|
+
# Webhooks
|
|
26
|
+
sub = client.webhooks.create(
|
|
27
|
+
url="https://mi-erp.com/hooks/contlity",
|
|
28
|
+
events=["sat.sync.completed", "invoice.created"],
|
|
29
|
+
)
|
|
30
|
+
print(sub["secret"]) # ¡Guárdalo! Solo visible aquí.
|
|
31
|
+
|
|
32
|
+
# Verificar webhook entrante
|
|
33
|
+
handler = WebhookHandler(secret="whsec_...")
|
|
34
|
+
payload = handler.verify(request_body, request_headers)
|
|
35
|
+
print(payload["event"]) # "sat.sync.completed"
|
|
36
|
+
|
|
37
|
+
Documentación: https://contlity.tech-mx.cloud/docs/sdk
|
|
38
|
+
"""
|
|
39
|
+
from .client import ContlityClient, ENV_VAR
|
|
40
|
+
from .webhook_handler import WebhookHandler
|
|
41
|
+
from .exceptions import (
|
|
42
|
+
ContlityError,
|
|
43
|
+
AuthError,
|
|
44
|
+
NotFoundError,
|
|
45
|
+
RateLimitError,
|
|
46
|
+
CreditError,
|
|
47
|
+
PlanError,
|
|
48
|
+
WebhookError,
|
|
49
|
+
)
|
|
50
|
+
|
|
51
|
+
__version__ = "0.3.0"
|
|
52
|
+
__all__ = [
|
|
53
|
+
"ContlityClient",
|
|
54
|
+
"ENV_VAR",
|
|
55
|
+
"WebhookHandler",
|
|
56
|
+
"ContlityError",
|
|
57
|
+
"AuthError",
|
|
58
|
+
"NotFoundError",
|
|
59
|
+
"RateLimitError",
|
|
60
|
+
"CreditError",
|
|
61
|
+
"PlanError",
|
|
62
|
+
"WebhookError",
|
|
63
|
+
"__version__",
|
|
64
|
+
]
|
contlity/client.py
ADDED
|
@@ -0,0 +1,227 @@
|
|
|
1
|
+
"""
|
|
2
|
+
client.py — ContlityClient, clase base del SDK de Contlity.
|
|
3
|
+
|
|
4
|
+
Uso rápido:
|
|
5
|
+
from contlity import ContlityClient
|
|
6
|
+
|
|
7
|
+
# Desde variable de entorno CONTLITY_API_KEY (recomendado)
|
|
8
|
+
client = ContlityClient.from_env()
|
|
9
|
+
|
|
10
|
+
# O explícito
|
|
11
|
+
client = ContlityClient("ctly_live_...")
|
|
12
|
+
|
|
13
|
+
print(client.account.info())
|
|
14
|
+
print(client.credits.balance())
|
|
15
|
+
jobs = client.sat.jobs()
|
|
16
|
+
"""
|
|
17
|
+
from __future__ import annotations
|
|
18
|
+
|
|
19
|
+
import os
|
|
20
|
+
|
|
21
|
+
import requests
|
|
22
|
+
|
|
23
|
+
from .exceptions import AuthError, NotFoundError, RateLimitError, CreditError, PlanError, ContlityError
|
|
24
|
+
from .resources.account import AccountResource
|
|
25
|
+
from .resources.clients import ClientsResource
|
|
26
|
+
from .resources.cfdis import CFDIsResource
|
|
27
|
+
from .resources.sat import SATResource
|
|
28
|
+
from .resources.sql import SQLResource
|
|
29
|
+
from .resources.workflows import WorkflowsResource
|
|
30
|
+
from .resources.webhooks import WebhooksResource
|
|
31
|
+
from .resources.credits import CreditsResource
|
|
32
|
+
from .resources.cargas import CargasResource
|
|
33
|
+
|
|
34
|
+
__version__ = "0.3.0"
|
|
35
|
+
|
|
36
|
+
ENV_VAR = "CONTLITY_API_KEY"
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
class ContlityClient:
|
|
40
|
+
"""
|
|
41
|
+
Cliente oficial del SDK de Contlity.
|
|
42
|
+
|
|
43
|
+
Inicialización
|
|
44
|
+
--------------
|
|
45
|
+
Recomendado — desde variable de entorno:
|
|
46
|
+
|
|
47
|
+
export CONTLITY_API_KEY="ctly_live_abc123..."
|
|
48
|
+
|
|
49
|
+
from contlity import ContlityClient
|
|
50
|
+
client = ContlityClient.from_env()
|
|
51
|
+
|
|
52
|
+
Explícito (no recomendado en código fuente):
|
|
53
|
+
|
|
54
|
+
client = ContlityClient("ctly_live_abc123...")
|
|
55
|
+
|
|
56
|
+
Parámetros
|
|
57
|
+
----------
|
|
58
|
+
api_key: API key con formato ctly_live_... — créala en /desarrollador.
|
|
59
|
+
base_url: URL base (default: https://contlity-api.tech-mx.cloud/api).
|
|
60
|
+
Úsala para self-hosted o staging.
|
|
61
|
+
timeout: Timeout HTTP en segundos (default: 30).
|
|
62
|
+
|
|
63
|
+
Recursos disponibles
|
|
64
|
+
--------------------
|
|
65
|
+
client.account → info de cuenta
|
|
66
|
+
client.clients → clientes / RFCs
|
|
67
|
+
client.cfdis → catálogo de CFDIs
|
|
68
|
+
client.sat → SAT Descarga Masiva
|
|
69
|
+
client.sql → SQL fiscal
|
|
70
|
+
client.workflows → workflows
|
|
71
|
+
client.webhooks → suscripciones webhook
|
|
72
|
+
client.credits → balance de créditos
|
|
73
|
+
"""
|
|
74
|
+
|
|
75
|
+
DEFAULT_BASE_URL = "https://contlity-api.tech-mx.cloud/api"
|
|
76
|
+
|
|
77
|
+
def __init__(
|
|
78
|
+
self,
|
|
79
|
+
api_key: str,
|
|
80
|
+
base_url: str | None = None,
|
|
81
|
+
timeout: int = 30,
|
|
82
|
+
):
|
|
83
|
+
if not api_key or not api_key.startswith("ctly_"):
|
|
84
|
+
raise ValueError("api_key inválida. Formato esperado: ctly_live_...")
|
|
85
|
+
self._api_key = api_key
|
|
86
|
+
self._base_url = (base_url or self.DEFAULT_BASE_URL).rstrip("/")
|
|
87
|
+
self._timeout = timeout
|
|
88
|
+
|
|
89
|
+
self._session = requests.Session()
|
|
90
|
+
self._session.headers.update({
|
|
91
|
+
"Authorization": f"Bearer {api_key}",
|
|
92
|
+
"User-Agent": f"contlity-python/{__version__}",
|
|
93
|
+
"Accept": "application/json",
|
|
94
|
+
"Content-Type": "application/json",
|
|
95
|
+
})
|
|
96
|
+
|
|
97
|
+
# Recursos
|
|
98
|
+
self.account = AccountResource(self)
|
|
99
|
+
self.clients = ClientsResource(self)
|
|
100
|
+
self.cfdis = CFDIsResource(self)
|
|
101
|
+
self.sat = SATResource(self)
|
|
102
|
+
self.sql = SQLResource(self)
|
|
103
|
+
self.workflows = WorkflowsResource(self)
|
|
104
|
+
self.webhooks = WebhooksResource(self)
|
|
105
|
+
self.credits = CreditsResource(self)
|
|
106
|
+
self.cargas = CargasResource(self)
|
|
107
|
+
|
|
108
|
+
# ── Constructores alternativos ────────────────────────────────────────────
|
|
109
|
+
|
|
110
|
+
@classmethod
|
|
111
|
+
def from_env(
|
|
112
|
+
cls,
|
|
113
|
+
env_var: str = ENV_VAR,
|
|
114
|
+
base_url: str | None = None,
|
|
115
|
+
timeout: int = 30,
|
|
116
|
+
) -> "ContlityClient":
|
|
117
|
+
"""
|
|
118
|
+
Inicializa el cliente leyendo la API key de una variable de entorno.
|
|
119
|
+
|
|
120
|
+
La variable por defecto es ``CONTLITY_API_KEY``. Es la forma recomendada
|
|
121
|
+
de autenticarse: nunca hardcodees keys en el código fuente.
|
|
122
|
+
|
|
123
|
+
Uso::
|
|
124
|
+
|
|
125
|
+
# ~/.bashrc o .env
|
|
126
|
+
export CONTLITY_API_KEY="ctly_live_abc123..."
|
|
127
|
+
|
|
128
|
+
from contlity import ContlityClient
|
|
129
|
+
client = ContlityClient.from_env()
|
|
130
|
+
print(client.account.info())
|
|
131
|
+
|
|
132
|
+
Args:
|
|
133
|
+
env_var: Nombre de la variable de entorno (default: CONTLITY_API_KEY).
|
|
134
|
+
base_url: URL base opcional (default: https://contlity-api.tech-mx.cloud/api).
|
|
135
|
+
timeout: Timeout HTTP en segundos (default: 30).
|
|
136
|
+
|
|
137
|
+
Raises:
|
|
138
|
+
EnvironmentError: si la variable de entorno no está definida o está vacía.
|
|
139
|
+
"""
|
|
140
|
+
key = os.environ.get(env_var, "").strip()
|
|
141
|
+
if not key:
|
|
142
|
+
raise EnvironmentError(
|
|
143
|
+
f"La variable de entorno '{env_var}' no está definida o está vacía.\n"
|
|
144
|
+
f"Defínela antes de usar ContlityClient.from_env():\n\n"
|
|
145
|
+
f" export {env_var}=\"ctly_live_...\"\n\n"
|
|
146
|
+
f"O pásala explícitamente: ContlityClient(api_key=\"ctly_live_...\")"
|
|
147
|
+
)
|
|
148
|
+
return cls(api_key=key, base_url=base_url, timeout=timeout)
|
|
149
|
+
|
|
150
|
+
# ── Utilidades ────────────────────────────────────────────────────────────
|
|
151
|
+
|
|
152
|
+
def ping(self) -> dict:
|
|
153
|
+
"""
|
|
154
|
+
Verifica la conexión y validez de la API key haciendo una petición
|
|
155
|
+
ligera a GET /v1/account.
|
|
156
|
+
|
|
157
|
+
Returns:
|
|
158
|
+
dict con account_id, name y plan si la key es válida.
|
|
159
|
+
|
|
160
|
+
Raises:
|
|
161
|
+
AuthError: si la key es inválida o revocada.
|
|
162
|
+
ContlityError: si hay un problema de red.
|
|
163
|
+
|
|
164
|
+
Uso::
|
|
165
|
+
|
|
166
|
+
from contlity import ContlityClient
|
|
167
|
+
client = ContlityClient.from_env()
|
|
168
|
+
info = client.ping()
|
|
169
|
+
print(f"Conectado como: {info['name']} (plan: {info['plan']})")
|
|
170
|
+
"""
|
|
171
|
+
return self.account.info()
|
|
172
|
+
|
|
173
|
+
def __repr__(self) -> str:
|
|
174
|
+
masked = self._api_key[:12] + "..." if len(self._api_key) > 12 else "***"
|
|
175
|
+
return f"ContlityClient(api_key=\"{masked}\", base_url=\"{self._base_url}\")"
|
|
176
|
+
|
|
177
|
+
# ── Método base ───────────────────────────────────────────────────────────
|
|
178
|
+
|
|
179
|
+
def _request(self, method: str, path: str, **kwargs) -> dict:
|
|
180
|
+
"""
|
|
181
|
+
Hace una petición a /v1{path} y retorna el JSON parseado.
|
|
182
|
+
Traduce códigos HTTP a excepciones del SDK.
|
|
183
|
+
"""
|
|
184
|
+
url = f"{self._base_url}/v1{path}"
|
|
185
|
+
try:
|
|
186
|
+
resp = self._session.request(
|
|
187
|
+
method, url, timeout=self._timeout, **kwargs
|
|
188
|
+
)
|
|
189
|
+
except requests.exceptions.Timeout:
|
|
190
|
+
raise ContlityError(f"Timeout después de {self._timeout}s en {method} {path}")
|
|
191
|
+
except requests.exceptions.ConnectionError as exc:
|
|
192
|
+
raise ContlityError(f"Error de conexión: {exc}")
|
|
193
|
+
|
|
194
|
+
self._raise_for_status(resp)
|
|
195
|
+
try:
|
|
196
|
+
return resp.json()
|
|
197
|
+
except Exception:
|
|
198
|
+
return {"raw": resp.text}
|
|
199
|
+
|
|
200
|
+
def _raise_for_status(self, resp: requests.Response) -> None:
|
|
201
|
+
if resp.ok:
|
|
202
|
+
return
|
|
203
|
+
try:
|
|
204
|
+
body = resp.json()
|
|
205
|
+
except Exception:
|
|
206
|
+
body = {"message": resp.text}
|
|
207
|
+
|
|
208
|
+
detail = body.get("detail") or body
|
|
209
|
+
message = (
|
|
210
|
+
detail.get("message") if isinstance(detail, dict) else str(detail)
|
|
211
|
+
) or resp.reason
|
|
212
|
+
|
|
213
|
+
sc = resp.status_code
|
|
214
|
+
if sc == 401:
|
|
215
|
+
raise AuthError(message, status_code=sc, response=body)
|
|
216
|
+
if sc == 402:
|
|
217
|
+
d = detail if isinstance(detail, dict) else {}
|
|
218
|
+
raise CreditError(message, balance=d.get("balance", 0),
|
|
219
|
+
cost=d.get("cost", 0), plan=d.get("plan", ""))
|
|
220
|
+
if sc == 403:
|
|
221
|
+
raise PlanError(message, status_code=sc, response=body)
|
|
222
|
+
if sc == 404:
|
|
223
|
+
raise NotFoundError(message, status_code=sc, response=body)
|
|
224
|
+
if sc == 429:
|
|
225
|
+
d = detail if isinstance(detail, dict) else {}
|
|
226
|
+
raise RateLimitError(message, retry_after=d.get("retry_after", 60))
|
|
227
|
+
raise ContlityError(message, status_code=sc, response=body)
|
contlity/dbapi.py
ADDED
|
@@ -0,0 +1,408 @@
|
|
|
1
|
+
"""
|
|
2
|
+
contlity.dbapi — driver SQL de Contlity (PEP 249 / DB-API 2.0).
|
|
3
|
+
|
|
4
|
+
Habla con Contlity por HTTPS (como los drivers de Snowflake o Athena): cada consulta corre en el
|
|
5
|
+
motor de Contlity con los permisos, la cartera de clientes y los créditos del usuario de la API key
|
|
6
|
+
(alcance «sql»). Solo lectura.
|
|
7
|
+
|
|
8
|
+
Uso::
|
|
9
|
+
|
|
10
|
+
import contlity.dbapi as ctly
|
|
11
|
+
|
|
12
|
+
con = ctly.connect() # API key en CONTLITY_API_KEY
|
|
13
|
+
cur = con.cursor()
|
|
14
|
+
cur.execute("SELECT rfc_emisor, sum(total) FROM comprobantes WHERE fecha >= %(desde)s GROUP BY 1",
|
|
15
|
+
{"desde": datetime.date(2026, 1, 1)})
|
|
16
|
+
for rfc, total in cur:
|
|
17
|
+
print(rfc, total)
|
|
18
|
+
|
|
19
|
+
Con pandas::
|
|
20
|
+
|
|
21
|
+
import pandas as pd
|
|
22
|
+
df = pd.read_sql("SELECT * FROM ventas.facturas", ctly.connect(database="despacho"))
|
|
23
|
+
"""
|
|
24
|
+
from __future__ import annotations
|
|
25
|
+
|
|
26
|
+
import datetime as _dt
|
|
27
|
+
import decimal as _dec
|
|
28
|
+
import math as _math
|
|
29
|
+
import re as _re
|
|
30
|
+
import time as _time
|
|
31
|
+
import uuid as _uuid
|
|
32
|
+
from typing import Any, Iterable, Optional, Sequence
|
|
33
|
+
|
|
34
|
+
from . import exceptions as _exc
|
|
35
|
+
|
|
36
|
+
# ── Globales PEP 249 ──────────────────────────────────────────────────────────
|
|
37
|
+
|
|
38
|
+
apilevel = "2.0"
|
|
39
|
+
threadsafety = 1 # los hilos comparten el módulo, no las conexiones
|
|
40
|
+
paramstyle = "pyformat" # %(nombre)s y %s, como psycopg
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
class Warning(Exception): # noqa: A001 (nombre exigido por PEP 249)
|
|
44
|
+
pass
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
class Error(Exception):
|
|
48
|
+
pass
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+
class InterfaceError(Error):
|
|
52
|
+
pass
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
class DatabaseError(Error):
|
|
56
|
+
pass
|
|
57
|
+
|
|
58
|
+
|
|
59
|
+
class DataError(DatabaseError):
|
|
60
|
+
pass
|
|
61
|
+
|
|
62
|
+
|
|
63
|
+
class OperationalError(DatabaseError):
|
|
64
|
+
pass
|
|
65
|
+
|
|
66
|
+
|
|
67
|
+
class IntegrityError(DatabaseError):
|
|
68
|
+
pass
|
|
69
|
+
|
|
70
|
+
|
|
71
|
+
class InternalError(DatabaseError):
|
|
72
|
+
pass
|
|
73
|
+
|
|
74
|
+
|
|
75
|
+
class ProgrammingError(DatabaseError):
|
|
76
|
+
pass
|
|
77
|
+
|
|
78
|
+
|
|
79
|
+
class NotSupportedError(DatabaseError):
|
|
80
|
+
pass
|
|
81
|
+
|
|
82
|
+
|
|
83
|
+
# ── Tipos ─────────────────────────────────────────────────────────────────────
|
|
84
|
+
|
|
85
|
+
class _Tipo:
|
|
86
|
+
def __init__(self, *nombres: str):
|
|
87
|
+
self.nombres = frozenset(nombres)
|
|
88
|
+
|
|
89
|
+
def __eq__(self, other: object) -> bool:
|
|
90
|
+
return isinstance(other, str) and _base_tipo(other) in self.nombres
|
|
91
|
+
|
|
92
|
+
def __hash__(self) -> int:
|
|
93
|
+
return hash(self.nombres)
|
|
94
|
+
|
|
95
|
+
|
|
96
|
+
def _base_tipo(t: str) -> str:
|
|
97
|
+
return _re.sub(r"\(.*\)", "", (t or "text").lower()).strip()
|
|
98
|
+
|
|
99
|
+
|
|
100
|
+
STRING = _Tipo("text", "varchar", "character varying", "character", "char", "uuid", "json", "jsonb", "name")
|
|
101
|
+
BINARY = _Tipo("bytea")
|
|
102
|
+
NUMBER = _Tipo("integer", "bigint", "smallint", "numeric", "decimal", "real", "double", "double precision", "float")
|
|
103
|
+
DATETIME = _Tipo("date", "timestamp", "timestamptz", "timestamp with time zone", "timestamp without time zone",
|
|
104
|
+
"time", "time without time zone", "interval")
|
|
105
|
+
ROWID = _Tipo("oid")
|
|
106
|
+
|
|
107
|
+
Date = _dt.date
|
|
108
|
+
Time = _dt.time
|
|
109
|
+
Timestamp = _dt.datetime
|
|
110
|
+
|
|
111
|
+
|
|
112
|
+
def DateFromTicks(ticks: float) -> _dt.date:
|
|
113
|
+
return _dt.date(*_time.localtime(ticks)[:3])
|
|
114
|
+
|
|
115
|
+
|
|
116
|
+
def TimeFromTicks(ticks: float) -> _dt.time:
|
|
117
|
+
return _dt.time(*_time.localtime(ticks)[3:6])
|
|
118
|
+
|
|
119
|
+
|
|
120
|
+
def TimestampFromTicks(ticks: float) -> _dt.datetime:
|
|
121
|
+
return _dt.datetime(*_time.localtime(ticks)[:6])
|
|
122
|
+
|
|
123
|
+
|
|
124
|
+
def Binary(x: bytes) -> bytes:
|
|
125
|
+
return bytes(x)
|
|
126
|
+
|
|
127
|
+
|
|
128
|
+
# ── Parámetros (se incrustan como literales seguros; el servidor recibe una sola sentencia) ──
|
|
129
|
+
|
|
130
|
+
def literal(v: Any) -> str:
|
|
131
|
+
"""Valor de Python → literal SQL."""
|
|
132
|
+
if v is None:
|
|
133
|
+
return "NULL"
|
|
134
|
+
if isinstance(v, bool):
|
|
135
|
+
return "TRUE" if v else "FALSE"
|
|
136
|
+
if isinstance(v, int):
|
|
137
|
+
return str(v)
|
|
138
|
+
if isinstance(v, float):
|
|
139
|
+
if _math.isnan(v) or _math.isinf(v):
|
|
140
|
+
return f"'{v}'::float8"
|
|
141
|
+
return repr(v)
|
|
142
|
+
if isinstance(v, _dec.Decimal):
|
|
143
|
+
return f"'{v}'::numeric" if not v.is_finite() else str(v)
|
|
144
|
+
if isinstance(v, _dt.datetime):
|
|
145
|
+
return f"'{v.isoformat()}'::" + ("timestamptz" if v.tzinfo else "timestamp")
|
|
146
|
+
if isinstance(v, _dt.date):
|
|
147
|
+
return f"'{v.isoformat()}'::date"
|
|
148
|
+
if isinstance(v, _dt.time):
|
|
149
|
+
return f"'{v.isoformat()}'::time"
|
|
150
|
+
if isinstance(v, _uuid.UUID):
|
|
151
|
+
return f"'{v}'::uuid"
|
|
152
|
+
if isinstance(v, (bytes, bytearray, memoryview)):
|
|
153
|
+
return f"'\\x{bytes(v).hex()}'::bytea"
|
|
154
|
+
if isinstance(v, tuple): # IN %s
|
|
155
|
+
if not v:
|
|
156
|
+
raise ProgrammingError("Una tupla vacía no es válida en IN")
|
|
157
|
+
return "(" + ", ".join(literal(x) for x in v) + ")"
|
|
158
|
+
if isinstance(v, list):
|
|
159
|
+
return "ARRAY[" + ", ".join(literal(x) for x in v) + "]"
|
|
160
|
+
if isinstance(v, dict):
|
|
161
|
+
import json
|
|
162
|
+
return _texto(json.dumps(v, ensure_ascii=False, default=str)) + "::jsonb"
|
|
163
|
+
return _texto(str(v))
|
|
164
|
+
|
|
165
|
+
|
|
166
|
+
def _texto(s: str) -> str:
|
|
167
|
+
if "\x00" in s:
|
|
168
|
+
raise DataError("El texto contiene un carácter nulo")
|
|
169
|
+
s = s.replace("'", "''")
|
|
170
|
+
if "\\" in s: # independiente de standard_conforming_strings
|
|
171
|
+
return "E'" + s.replace("\\", "\\\\") + "'"
|
|
172
|
+
return "'" + s + "'"
|
|
173
|
+
|
|
174
|
+
|
|
175
|
+
_MARCA = _re.compile(r"%(?:\((?P<nombre>[^)]+)\))?(?P<tipo>[sr%])")
|
|
176
|
+
|
|
177
|
+
|
|
178
|
+
def formatear(sql: str, params: Any) -> str:
|
|
179
|
+
"""Aplica `params` a la sentencia como psycopg: con params=None no se toca (ni los %)."""
|
|
180
|
+
if params is None:
|
|
181
|
+
return sql
|
|
182
|
+
posicional = iter(params) if isinstance(params, (list, tuple)) else None
|
|
183
|
+
|
|
184
|
+
def _rep(m: _re.Match) -> str:
|
|
185
|
+
if m.group("tipo") == "%":
|
|
186
|
+
return "%"
|
|
187
|
+
nombre = m.group("nombre")
|
|
188
|
+
if nombre is not None:
|
|
189
|
+
if not isinstance(params, dict):
|
|
190
|
+
raise ProgrammingError("La sentencia usa %(nombre)s pero los parámetros no son un dict")
|
|
191
|
+
if nombre not in params:
|
|
192
|
+
raise ProgrammingError(f"Falta el parámetro «{nombre}»")
|
|
193
|
+
return literal(params[nombre])
|
|
194
|
+
if posicional is None:
|
|
195
|
+
raise ProgrammingError("La sentencia usa %s pero los parámetros no son una secuencia")
|
|
196
|
+
try:
|
|
197
|
+
return literal(next(posicional))
|
|
198
|
+
except StopIteration:
|
|
199
|
+
raise ProgrammingError("Faltan parámetros para la sentencia") from None
|
|
200
|
+
|
|
201
|
+
out = _MARCA.sub(_rep, sql)
|
|
202
|
+
if posicional is not None and next(posicional, _FIN) is not _FIN:
|
|
203
|
+
raise ProgrammingError("Sobran parámetros para la sentencia")
|
|
204
|
+
return out
|
|
205
|
+
|
|
206
|
+
|
|
207
|
+
_FIN = object()
|
|
208
|
+
|
|
209
|
+
|
|
210
|
+
# ── Conversión de resultados ──────────────────────────────────────────────────
|
|
211
|
+
|
|
212
|
+
def _convertidor(tipo: str):
|
|
213
|
+
t = _base_tipo(tipo)
|
|
214
|
+
if t in ("numeric", "decimal"):
|
|
215
|
+
return lambda v: v if v is None or isinstance(v, _dec.Decimal) else _dec.Decimal(str(v))
|
|
216
|
+
if t == "date":
|
|
217
|
+
return lambda v: _dt.date.fromisoformat(v) if isinstance(v, str) else v
|
|
218
|
+
if t.startswith("timestamp"):
|
|
219
|
+
return lambda v: _dt.datetime.fromisoformat(v) if isinstance(v, str) else v
|
|
220
|
+
if t.startswith("time"):
|
|
221
|
+
return lambda v: _dt.time.fromisoformat(v) if isinstance(v, str) else v
|
|
222
|
+
return None
|
|
223
|
+
|
|
224
|
+
|
|
225
|
+
# ── Conexión y cursor ─────────────────────────────────────────────────────────
|
|
226
|
+
|
|
227
|
+
def connect(api_key: Optional[str] = None, database: Optional[str] = None, schema: Optional[str] = None,
|
|
228
|
+
base_url: Optional[str] = None, timeout: int = 120, client: Any = None) -> "Connection":
|
|
229
|
+
"""
|
|
230
|
+
Abre una conexión.
|
|
231
|
+
|
|
232
|
+
Args:
|
|
233
|
+
api_key: API key con alcance «sql» (por omisión, la variable CONTLITY_API_KEY)
|
|
234
|
+
database: base en uso para nombres esquema.objeto (por omisión, la principal)
|
|
235
|
+
schema: esquema en uso, para escribir solo el nombre del objeto
|
|
236
|
+
base_url: URL de la API (por omisión, la de producción)
|
|
237
|
+
timeout: segundos de espera por consulta
|
|
238
|
+
client: un ContlityClient ya creado (en lugar de api_key/base_url/timeout)
|
|
239
|
+
"""
|
|
240
|
+
if client is None:
|
|
241
|
+
from .client import ContlityClient
|
|
242
|
+
try:
|
|
243
|
+
client = (ContlityClient(api_key, base_url=base_url, timeout=timeout) if api_key
|
|
244
|
+
else ContlityClient.from_env(base_url=base_url, timeout=timeout))
|
|
245
|
+
except (ValueError, EnvironmentError) as e:
|
|
246
|
+
raise InterfaceError(str(e)) from e
|
|
247
|
+
return Connection(client, database, schema)
|
|
248
|
+
|
|
249
|
+
|
|
250
|
+
def _error(e: Exception) -> Error:
|
|
251
|
+
if isinstance(e, Error):
|
|
252
|
+
return e
|
|
253
|
+
if isinstance(e, _exc.ContlityError):
|
|
254
|
+
return OperationalError(str(e))
|
|
255
|
+
return InterfaceError(str(e))
|
|
256
|
+
|
|
257
|
+
|
|
258
|
+
class Connection:
|
|
259
|
+
def __init__(self, client: Any, database: Optional[str] = None, schema: Optional[str] = None):
|
|
260
|
+
self._client = client
|
|
261
|
+
self.database = database
|
|
262
|
+
self.schema = schema
|
|
263
|
+
self._cerrada = False
|
|
264
|
+
self._catalogo: Optional[tuple[float, dict]] = None
|
|
265
|
+
|
|
266
|
+
# PEP 249
|
|
267
|
+
def close(self) -> None:
|
|
268
|
+
self._cerrada = True
|
|
269
|
+
|
|
270
|
+
def commit(self) -> None: # solo lectura: no hay transacción que confirmar
|
|
271
|
+
self._abierta()
|
|
272
|
+
|
|
273
|
+
def rollback(self) -> None:
|
|
274
|
+
self._abierta()
|
|
275
|
+
|
|
276
|
+
def cursor(self) -> "Cursor":
|
|
277
|
+
self._abierta()
|
|
278
|
+
return Cursor(self)
|
|
279
|
+
|
|
280
|
+
@property
|
|
281
|
+
def closed(self) -> bool:
|
|
282
|
+
return self._cerrada
|
|
283
|
+
|
|
284
|
+
def __enter__(self) -> "Connection":
|
|
285
|
+
return self
|
|
286
|
+
|
|
287
|
+
def __exit__(self, *a) -> None:
|
|
288
|
+
self.close()
|
|
289
|
+
|
|
290
|
+
# Extensiones
|
|
291
|
+
def catalog(self, refrescar: bool = False) -> dict:
|
|
292
|
+
"""Esquemas, tablas y columnas visibles en la base de la conexión (en caché 60 s)."""
|
|
293
|
+
self._abierta()
|
|
294
|
+
if refrescar or not self._catalogo or _time.time() - self._catalogo[0] > 60:
|
|
295
|
+
try:
|
|
296
|
+
params = {"database": self.database} if self.database else None
|
|
297
|
+
self._catalogo = (_time.time(), self._client._request("GET", "/catalog", params=params))
|
|
298
|
+
except Exception as e:
|
|
299
|
+
raise _error(e) from e
|
|
300
|
+
return self._catalogo[1]
|
|
301
|
+
|
|
302
|
+
def _ejecutar(self, sql: str) -> dict:
|
|
303
|
+
self._abierta()
|
|
304
|
+
body: dict = {"query": sql}
|
|
305
|
+
if self.database:
|
|
306
|
+
body["database"] = self.database
|
|
307
|
+
if self.schema:
|
|
308
|
+
body["schema_name"] = self.schema
|
|
309
|
+
try:
|
|
310
|
+
r = self._client._request("POST", "/sql", json=body)
|
|
311
|
+
except Exception as e:
|
|
312
|
+
raise _error(e) from e
|
|
313
|
+
if r.get("error"):
|
|
314
|
+
raise ProgrammingError(r["error"])
|
|
315
|
+
return r
|
|
316
|
+
|
|
317
|
+
def _abierta(self) -> None:
|
|
318
|
+
if self._cerrada:
|
|
319
|
+
raise InterfaceError("La conexión está cerrada")
|
|
320
|
+
|
|
321
|
+
|
|
322
|
+
class Cursor:
|
|
323
|
+
def __init__(self, connection: Connection):
|
|
324
|
+
self.connection = connection
|
|
325
|
+
self.arraysize = 1
|
|
326
|
+
self.description: Optional[list[tuple]] = None
|
|
327
|
+
self.rowcount = -1
|
|
328
|
+
self._filas: list = []
|
|
329
|
+
self._i = 0
|
|
330
|
+
self._cerrado = False
|
|
331
|
+
|
|
332
|
+
def execute(self, operation: str, parameters: Any = None) -> "Cursor":
|
|
333
|
+
if self._cerrado:
|
|
334
|
+
raise InterfaceError("El cursor está cerrado")
|
|
335
|
+
sql = formatear(operation, parameters)
|
|
336
|
+
r = self.connection._ejecutar(sql)
|
|
337
|
+
cols = r.get("columns") or []
|
|
338
|
+
conv = [_convertidor(c.get("type") or "text") for c in cols]
|
|
339
|
+
filas = []
|
|
340
|
+
for fila in r.get("rows") or []:
|
|
341
|
+
if any(conv):
|
|
342
|
+
fila = [f(v) if f and v is not None else v for f, v in zip(conv, fila)]
|
|
343
|
+
filas.append(tuple(fila))
|
|
344
|
+
self.description = [(c["name"], c.get("type") or "text", None, None, None, None, None) for c in cols] or None
|
|
345
|
+
self._filas, self._i = filas, 0
|
|
346
|
+
self.rowcount = len(filas)
|
|
347
|
+
return self
|
|
348
|
+
|
|
349
|
+
def executemany(self, operation: str, seq_of_parameters: Iterable[Any]) -> None:
|
|
350
|
+
for p in seq_of_parameters:
|
|
351
|
+
self.execute(operation, p)
|
|
352
|
+
|
|
353
|
+
def fetchone(self) -> Optional[tuple]:
|
|
354
|
+
self._con_resultado()
|
|
355
|
+
if self._i >= len(self._filas):
|
|
356
|
+
return None
|
|
357
|
+
self._i += 1
|
|
358
|
+
return self._filas[self._i - 1]
|
|
359
|
+
|
|
360
|
+
def fetchmany(self, size: Optional[int] = None) -> list[tuple]:
|
|
361
|
+
self._con_resultado()
|
|
362
|
+
n = self.arraysize if size is None else size
|
|
363
|
+
out = self._filas[self._i:self._i + n]
|
|
364
|
+
self._i += len(out)
|
|
365
|
+
return out
|
|
366
|
+
|
|
367
|
+
def fetchall(self) -> list[tuple]:
|
|
368
|
+
self._con_resultado()
|
|
369
|
+
out = self._filas[self._i:]
|
|
370
|
+
self._i = len(self._filas)
|
|
371
|
+
return out
|
|
372
|
+
|
|
373
|
+
def close(self) -> None:
|
|
374
|
+
self._cerrado = True
|
|
375
|
+
self._filas = []
|
|
376
|
+
|
|
377
|
+
def callproc(self, *a, **k):
|
|
378
|
+
raise NotSupportedError("Contlity no ejecuta procedimientos por el driver; usa SELECT")
|
|
379
|
+
|
|
380
|
+
def nextset(self) -> None:
|
|
381
|
+
return None
|
|
382
|
+
|
|
383
|
+
def setinputsizes(self, sizes: Sequence[Any]) -> None:
|
|
384
|
+
pass
|
|
385
|
+
|
|
386
|
+
def setoutputsize(self, size: int, column: Optional[int] = None) -> None:
|
|
387
|
+
pass
|
|
388
|
+
|
|
389
|
+
def __iter__(self):
|
|
390
|
+
return self
|
|
391
|
+
|
|
392
|
+
def __next__(self) -> tuple:
|
|
393
|
+
fila = self.fetchone()
|
|
394
|
+
if fila is None:
|
|
395
|
+
raise StopIteration
|
|
396
|
+
return fila
|
|
397
|
+
|
|
398
|
+
def __enter__(self) -> "Cursor":
|
|
399
|
+
return self
|
|
400
|
+
|
|
401
|
+
def __exit__(self, *a) -> None:
|
|
402
|
+
self.close()
|
|
403
|
+
|
|
404
|
+
def _con_resultado(self) -> None:
|
|
405
|
+
if self._cerrado:
|
|
406
|
+
raise InterfaceError("El cursor está cerrado")
|
|
407
|
+
if self.description is None:
|
|
408
|
+
raise ProgrammingError("No hay resultado: ejecuta una consulta primero")
|