Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
27 changes: 24 additions & 3 deletions .github/workflows/ci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -10,8 +10,8 @@ concurrency:
cancel-in-progress: true

jobs:
lint-type-test:
name: ${{ matrix.python-version }} · lint · type · test
unit:
name: unit · ${{ matrix.python-version }}
runs-on: ubuntu-latest
strategy:
fail-fast: false
Expand All @@ -37,5 +37,26 @@ jobs:
- name: Mypy
run: mypy

- name: Pytest
- name: Pytest (unit)
run: pytest -q

integration:
name: integration · MySQL + Postgres (testcontainers)
runs-on: ubuntu-latest
needs: unit
steps:
- uses: actions/checkout@v4

- name: Setup Python
uses: actions/setup-python@v5
with:
python-version: "3.12"
cache: pip

- name: Install
run: |
python -m pip install --upgrade pip
pip install -e ".[dev]"

- name: Pytest (integration)
run: pytest -m integration tests/integration -v
9 changes: 7 additions & 2 deletions pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -26,11 +26,14 @@ classifiers = [
dependencies = ["pymysql>=1.1"]

[project.optional-dependencies]
postgres = ["psycopg[binary]>=3.1"]
dev = [
"pytest>=8",
"pytest-cov>=5",
"ruff>=0.6",
"mypy>=1.10",
"psycopg[binary]>=3.1",
"testcontainers[mysql,postgres]>=4.7",
]

[project.urls]
Expand All @@ -49,7 +52,6 @@ select = ["E", "F", "I", "B", "UP", "SIM", "RUF", "ANN", "A"]
ignore = [
"ANN401", # permitir Any explícito
"A004", # sombreamos ConnectionError a propósito (parte de la API pública)
"UP038", # `isinstance(x, X | Y)` rompe en py3.10 sin from __future__ import
]

[tool.ruff.lint.per-file-ignores]
Expand All @@ -68,4 +70,7 @@ ignore_missing_imports = true

[tool.pytest.ini_options]
testpaths = ["tests"]
addopts = "-ra --strict-markers"
addopts = "-ra --strict-markers -m 'not integration'"
markers = [
"integration: requiere Docker (MySQL/Postgres reales con Testcontainers)",
]
120 changes: 96 additions & 24 deletions shiba/__init__.py
Original file line number Diff line number Diff line change
@@ -1,31 +1,27 @@
"""Shiba — librería ligera para hablar con bases de datos relacionales.

Punto de entrada público:

.. code-block:: python

import shiba as s
import shiba

with s.ShibaConnection(host="localhost", port=3306,
user="u", password="p") as cx:
cx.create_database("my_db")
cx.use_database("my_db")
cx.create_table("users") \\
.increments("id", primary_key=True) \\
.string("name") \\
.build()
# Forma 1 — DSN explícito (recomendado para multi-dialecto):
cx = shiba.connect("mysql://user:pass@localhost:3306/my_db")
cx = shiba.connect("postgres://user:pass@localhost:5432/my_db")

cx.table("users").insert({"name": "John"})
rows = cx.table("users").where("name", "John").get()
# Forma 2 — construcción directa MySQL (legacy):
cx = shiba.ShibaConnection(host="localhost", port=3306,
user="u", password="p")
"""
from __future__ import annotations

from contextlib import AbstractContextManager
from typing import TYPE_CHECKING
from typing import TYPE_CHECKING, Any
from urllib.parse import urlparse

from shiba import error_codes
from shiba.core.query_builder import QueryBuilder
from shiba.core.table_builder import TableBuilder
from shiba.dialects.base import Dialect
from shiba.dialects.mysql import Database, MySQLDialect
from shiba.errors import (
ConnectionError,
Expand All @@ -35,23 +31,43 @@
SchemaError,
ShibaError,
)
from shiba.orm import Model, fields, set_default_connection

if TYPE_CHECKING:
from types import TracebackType


class ShibaConnection:
"""Fachada de alto nivel sobre un :class:`Database` MySQL."""
"""Fachada de alto nivel agnóstica de dialecto.

Acepta dos formas de construcción:

* Legacy MySQL: ``ShibaConnection(host, port, user, password)``.
* Inyectada: ``ShibaConnection(db=Database(...), dialect=Dialect(...))``
(la usa :func:`connect`).
"""

def __init__(
self,
host: str,
port: int,
user: str,
password: str,
host: str | None = None,
port: int | None = None,
user: str | None = None,
password: str | None = None,
*,
database: str | None = None,
db: Any = None,
dialect: Dialect | None = None,
) -> None:
if db is not None and dialect is not None:
self.dialect: Dialect = dialect
self.db: Any = db
return

if host is None or port is None or user is None or password is None:
error_codes.MISSING_REQUIRED_DATA.raise_(
"ShibaConnection requiere host/port/user/password o "
"db+dialect inyectados."
)
self.dialect = MySQLDialect()
self.db = Database(host, port, user, password, database=database)

Expand All @@ -77,10 +93,10 @@ def close(self) -> None:
# API pública
# ------------------------------------------------------------------

def create_database(self, database: str) -> Database:
def create_database(self, database: str) -> Any:
return self.db.create_database(database)

def use_database(self, database: str) -> Database:
def use_database(self, database: str) -> Any:
return self.db.use_database(database)

def create_table(self, table_name: str) -> TableBuilder:
Expand All @@ -89,22 +105,78 @@ def create_table(self, table_name: str) -> TableBuilder:
def table(self, table_name: str) -> QueryBuilder:
return QueryBuilder(self.db, table_name, dialect=self.dialect)

def transaction(self) -> AbstractContextManager[Database]:
"""Context manager transaccional. Ver :meth:`Database.transaction`."""
return self.db.transaction()
def transaction(self) -> AbstractContextManager[Any]:
"""Context manager transaccional."""
cm: AbstractContextManager[Any] = self.db.transaction()
return cm

def raw(
self,
query: str,
params: object = None,
*,
many: bool = False,
) -> list[dict[str, object]]:
rows: list[dict[str, object]] = self.db.raw(query, params, many=many)
return rows


# ---------------------------------------------------------------------------
# Factory connect(dsn)
# ---------------------------------------------------------------------------


_DEFAULT_PORTS = {"mysql": 3306, "postgres": 5432, "postgresql": 5432}


def connect(dsn: str) -> ShibaConnection:
"""Construye una :class:`ShibaConnection` desde un DSN tipo URL.

Schemes soportados:

* ``mysql://user:pass@host:port/dbname``
* ``postgres://user:pass@host:port/dbname`` (alias: ``postgresql://``)
"""
parsed = urlparse(dsn)
scheme = parsed.scheme.lower()
if scheme not in _DEFAULT_PORTS:
error_codes.NOT_IMPLEMENTED.raise_(
f"DSN scheme '{scheme}' no soportado. Usa: {sorted(_DEFAULT_PORTS)}."
)
host = parsed.hostname or "localhost"
port = parsed.port or _DEFAULT_PORTS[scheme]
user = parsed.username or ""
password = parsed.password or ""
database = parsed.path.lstrip("/") or None

if scheme == "mysql":
db: Any = Database(host, port, user, password, database=database)
return ShibaConnection(db=db, dialect=MySQLDialect())

# postgres / postgresql
from shiba.dialects.postgres import PostgresDialect
from shiba.dialects.postgres.driver import Database as PgDatabase

db = PgDatabase(host, port, user, password, database=database)
return ShibaConnection(db=db, dialect=PostgresDialect())


__all__ = [
"ConnectionError",
"Database",
"Dialect",
"IntegrityError",
"MissingDataError",
"Model",
"MySQLDialect",
"QueryBuilder",
"QueryError",
"SchemaError",
"ShibaConnection",
"ShibaError",
"TableBuilder",
"connect",
"error_codes",
"fields",
"set_default_connection",
]
Loading
Loading