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.1.0.tar.gz (9.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.1.0-py3-none-any.whl (11.9 kB view details)

Uploaded Python 3

File details

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

File metadata

  • Download URL: pyeasymatrixdb-0.1.0.tar.gz
  • Upload date:
  • Size: 9.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.1.0.tar.gz
Algorithm Hash digest
SHA256 337ca823e104c4a2459fbb96c94e415a900b8c90221696b1285e45f5b266ae99
MD5 fa63371c3fad348a2b34881bff847808
BLAKE2b-256 0fb758600edf34b2fce3d5814c5d0c250061c1839d39d6c980bce90498fc33c6

See more details on using hashes here.

File details

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

File metadata

  • Download URL: pyeasymatrixdb-0.1.0-py3-none-any.whl
  • Upload date:
  • Size: 11.9 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.1.0-py3-none-any.whl
Algorithm Hash digest
SHA256 76313da530e93c4a1313dc80cb206851c31b809e750c87ab92439bdd186013db
MD5 b256162015472bca89dfbb886aedf26f
BLAKE2b-256 a98ade7ffdf4d24748d42ea0f52f8ee9164d56cfa923fa53ee50388ee88a1522

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