Skip to main content

Easiest way to search and update a database using matrix like queries

Project description

pyEasyDb

Biblioteca Python para consultar e modificar bancos de dados usando matrizes bidimensionais como interface.
Abstrai SELECT, INSERT, UPDATE e DELETE via SQLAlchemy Core — funciona com qualquer banco suportado (SQLite, PostgreSQL, MySQL, etc.).

Instalação

pip install pyeasymatrixdb

GitHub

https://github.com/RicNazar/toxt-p10_dbdriver

Início Rápido

from sqlalchemy import create_engine, MetaData, Table, Column, Integer, String, ForeignKey

# Cria uma engine em memória
engine = create_engine("sqlite+pysqlite:///:memory:")
metadata = MetaData()

users = Table("users", metadata,
    Column("id", Integer, primary_key=True),
    Column("name", String(100), nullable=False),
    Column("email", String(150), nullable=False),
)

orders = Table("orders", metadata,
    Column("id", Integer, primary_key=True),
    Column("user_id", ForeignKey("users.id"), nullable=False),
    Column("product", String(100), nullable=False),
)

# Cria as tabelas caso não existam
metadata.create_all(engine)

from pyeasydb import DbDriver
db = DbDriver(metadata, engine)

Funcionalidades

1. SQL puro — execute() / execute_stmt()

# SQL como texto
resultado = db.execute("SELECT id, name FROM users ORDER BY id")
# → [["__result__", "__result__"], ["id", "name"], [1, "Ana"], [2, "Bruno"]]

# Statement SQLAlchemy
from sqlalchemy import select
stmt = select(users.c.id, users.c.name).where(users.c.id >= 2)
resultado = db.execute_stmt(stmt)

Comandos sem retorno de linhas devolvem [["__meta__"], ["rowcount"], [n]].


2. Pesquisa — db.Pesquisar

Pesquisa simples

resultado = (
    db.Pesquisar
    .define_header([
        ["users", "users"],
        ["id",    "name"],
    ])
    .search()
)
# → [["users", "users"], ["id", "name"], [1, "Ana"], [2, "Bruno"], ...]

Pesquisa com JOIN + filtro

resultado = (
    db.Pesquisar
    .define_header([
        ["users",  "orders",  "orders"],
        ["name",   "product", "status"],
    ])
    .define_relationships([
        ["orders", "users", "user_id", "id", 1],  # INNER JOIN
    ])
    .define_filter([
        ["orders"],
        ["status"],
        ["OPEN"],
    ])
    .search()
)

Filtro com OR (múltiplas linhas)

resultado = (
    db.Pesquisar
    .define_header([["users", "users"], ["id", "name"]])
    .define_filter([
        ["users"],
        ["name"],
        ["Ana"],     # OR
        ["Carla"],
    ])
    .search()
)

Filtro com operadores

.define_filter([
    ["users"],
    ["id"],
    [(">=", 2)],  # operadores: !=, >, >=, <, <=, like
])

Pesquisa completa (todas as colunas)

resultado = db.Pesquisar.define_header(header).search(complete=True, default=None)
# Expande a saída para todas as colunas das tabelas envolvidas.
# Colunas ausentes são preenchidas com o valor de `default`.

3. Atualização — db.Atualizar

A coluna MD (última) controla a operação por linha:

  • "U" / "A" → Upsert (UPDATE se PK existe ou exclusivo Filtro, INSERT caso contrário)
  • "D" → DELETE (exige PK ou exclusifi Filtro)

Upsert (update + insert)

resultado = (
    db.Atualizar
    .define_data([
        ["users", "users", "users",     "users"],
        ["id",    "name",  "email",     "MD"   ],
        [1,       "Ana R.","ana@x.com", "U"    ],  # atualiza id=1
        [5,       "Novo",  "novo@x.com","U"    ],  # insere id=5
    ])
    .update()
)

Delete

resultado = (
    db.Atualizar
    .define_data([
        ["orders", "orders",  "orders"],
        ["id",     "product", "MD"    ],
        [101,      "Mouse",   "D"    ],
    ])
    .update()
)

Atualização com filtro extra

resultado = (
    db.Atualizar
    .define_data([
        ["orders", "orders", "orders",  "orders"],
        ["id",     "user_id","status",  "MD"    ],
        [100,      1,        "CLOSED",  "U"     ],
    ])
    .define_filter([
        ["orders"],
        ["status"],
        ["OPEN"],       # só atualiza se status = "OPEN"
    ])
    .update()
)

Retorno completo

resultado = db.Atualizar.define_data(data).update(complete=True, default="<vazio>")
# Expande a saída para todas as colunas das tabelas, preenchendo ausentes com o default.

4. Encadeamento (fluent API)

Todos os métodos define_* retornam self, permitindo encadeamento:

db.Pesquisar.define_header(h).define_relationships(r).define_filter(f).search()
db.Atualizar.define_data(d).define_filter(f).update()

5. Reset automático

Por padrão, search() e update() executam reset() após a operação, limpando header/filter/data para a próxima chamada. Passe reset=False para manter o estado.


Formato das Matrizes

Modelo Linhas Descrição
header 2 [tabelas, colunas] — define colunas do SELECT
filter ≥ 3 [tabelas, colunas, valores...] — AND entre colunas, OR entre linhas
data ≥ 3 [tabelas, colunas, valores...] — última coluna = "MD"
relationships N [[tabelaA, tabelaB, colA, colB, inner?], ...]

Estrutura do Projeto

app/
  DbDriver/
    DbDriver.py        — Classe principal (execute, execute_stmt)
    subclasses/
      DbDriverCore.py   — Classe base (reset, define_filter, define_relationships)
      DbDriverSearch.py — Pesquisa (define_header, search)
      DbDriverUpdate.py — Escrita (define_data, update)
      DbDriverUtils.py  — Utilitários estáticos (builders, validações)

Licença

Consulte o arquivo de licença do repositório.

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

pyeasymatrixdb-0.2.4.tar.gz (12.5 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

pyeasymatrixdb-0.2.4-py3-none-any.whl (15.1 kB view details)

Uploaded Python 3

File details

Details for the file pyeasymatrixdb-0.2.4.tar.gz.

File metadata

  • Download URL: pyeasymatrixdb-0.2.4.tar.gz
  • Upload date:
  • Size: 12.5 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.2.0 CPython/3.13.7

File hashes

Hashes for pyeasymatrixdb-0.2.4.tar.gz
Algorithm Hash digest
SHA256 31c0932dc5ed3c815a7540a21e679bbdcb3751a5f6c5dfbda400cf60a19057fe
MD5 659934ef4a3bdff07fcc61721890d8ed
BLAKE2b-256 a5844c0b481908a59b0021ff80128c7976bb43e1ce1f1c46143ba82211ce1cdb

See more details on using hashes here.

File details

Details for the file pyeasymatrixdb-0.2.4-py3-none-any.whl.

File metadata

  • Download URL: pyeasymatrixdb-0.2.4-py3-none-any.whl
  • Upload date:
  • Size: 15.1 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.2.0 CPython/3.13.7

File hashes

Hashes for pyeasymatrixdb-0.2.4-py3-none-any.whl
Algorithm Hash digest
SHA256 9bb7483a714da4a591b9ea0949a17632b16194581d5595e43e5ce782225a1096
MD5 322671be6429d8596b7f028d1dab6d85
BLAKE2b-256 bf64e9d98ab6067655657a3f856561ec0af50e94981aa4de98f80a0e21c2d79a

See more details on using hashes here.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page