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.1.tar.gz (9.8 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.1-py3-none-any.whl (12.3 kB view details)

Uploaded Python 3

File details

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

File metadata

  • Download URL: pyeasymatrixdb-0.2.1.tar.gz
  • Upload date:
  • Size: 9.8 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.1.tar.gz
Algorithm Hash digest
SHA256 818f9f2c6f37191e136b11b4850838297532497d9cdd9b8a6193d2cfd8e2f67b
MD5 3a0720f3e51dd4753610f502891bae93
BLAKE2b-256 303aff24cd76d569da3e4a5b8da70b2d79314569120a3b084027976235332cea

See more details on using hashes here.

File details

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

File metadata

  • Download URL: pyeasymatrixdb-0.2.1-py3-none-any.whl
  • Upload date:
  • Size: 12.3 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.1-py3-none-any.whl
Algorithm Hash digest
SHA256 ecb344c026bd5f90eff402227615ac0b86ad58c118c2573ce32267ca305bb9ea
MD5 b9a414e2add5971a928cff253807fc08
BLAKE2b-256 825933a4af340b9c2c5000931bed7da1c9573e93df909a604330038b58518247

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