Skip to main content

tmjlite (Python)

Driver Python do TMJLite — banco de dados SQL embarcado, em um único arquivo .tmjp, com branches de dados git-native. O motor nativo (Rust) já vem dentro do wheel: nada para instalar além do pip.

pip install tmjlite

Plataformas: macOS (Apple Silicon), Linux x86-64, Windows x86-64 · Python ≥ 3.8.

import tmjlite

db = tmjlite.connect("app.tmjp")
db.execute("CREATE TABLE users (id PK, name TEXT, age INT);")
db.execute("INSERT INTO users (name, age) VALUES ('Alice', 30);")
for row in db.query("SELECT name, age FROM users WHERE age > 18;"):
    print(row["name"], row["age"])

with db.transaction():
    db.execute("INSERT INTO users (name, age) VALUES ('Bob', 25);")
db.close()

Branches — trabalhe numa cópia lógica e faça merge no arquivo principal, enquanto a aplicação continua enxergando o banco intocado:

b = tmjlite.open_branch("app.tmjp", "importacao")
b.execute("INSERT INTO users (name, age) VALUES ('Carol', 41);")
b.seal("primeira leva", author="thiago")   # commit na branch
applied = b.commit()                        # merge no app.tmjp
print(f"{applied} linha(s) aplicadas")

Vários processos ao mesmo tempo? tmjlite.connect_shadow(path) dá a cada worker uma sessão própria; commit() mergeia por chave primária.

Lotes e upsert (0.2.9+): prepared statements com ?, INSERT … ON CONFLICT e transação na conexão compartilhada — um commit só:

db = tmjlite.connect_shared("app.tmjp")
st = db.prepare("INSERT INTO rs (ns, k, samples) VALUES (?, ?, ?) "
                "ON CONFLICT (ns, k) DO UPDATE SET samples = excluded.samples;")
with db.transaction():
    for it in lote:
        st.execute([it.ns, it.k, it.samples])

Leitura grande sem estourar memória (0.3.1+): cursor em streaming direto do snapshot — uma linha por vez, qualquer N:

with db.cursor("SELECT samples, cpu_hist FROM rs WHERE ns = ?", ["ns3"]) as cur:
    for row in cur:
        total += row["samples"]

Tipos, chaves estrangeiras e VACUUM (0.5.0+)

  • Os valores voltam com o tipo da coluna. '007' numa coluna TEXT volta texto (antes virava o número 7) e SUM de coluna INT volta inteiro. Quem dependia da conversão implícita de texto para número passa a converter no código.
  • Chaves estrangeiras: cliente TEXT REFERENCES clientes ON DELETE CASCADE (ou RESTRICT / SET NULL). INSERT e UPDATE no filho exigem o pai; crie um índice na coluna da FK para o DELETE do pai não varrer a tabela filha.
  • VACUUM; compacta o arquivo (ele nunca encolhia sozinho). Exige a conexão clássica, exclusiva, fora de transação.
  • Apelido de coluna: SELECT COUNT(*) AS total FROM clientes;.
  • Formato de arquivo v3: o .tmjp é atualizado sozinho na primeira abertura e versões ≤ 0.4.0 deixam de abri-lo. Atualize CLI, drivers e Studio juntos.

Erro de abertura com o motivo, um statement por chamada, PK do upsert (0.5.1+)

try:
    db = tmjlite.connect_shared("app.tmjp")
except tmjlite.TMJLiteError as e:
    print(e)   # ...: database 'app.tmjp' is locked by another process
               # ...: 'app.tmjp' is not a TMJLite database (unrecognized file format)

r = db.execute("INSERT INTO clientes (nome, email) VALUES ('Ana', 'ana@x') "
               "ON CONFLICT (email) DO UPDATE SET nome = excluded.nome;")
print(r.rows_affected, r.last_pk)   # 1  <uuid da linha inserida OU atualizada>
  • Abertura: o erro traz o motivo real (travado por outro processo, não é um banco TMJLite, permissão negada, diretório inexistente). Antes toda falha parecia "em uso por outro processo". Um arquivo de 0 bytes é aceito como banco novo.

  • Upsert devolve a PK em last_pk, tanto quando insere quanto quando atualiza (uma linha; em lote de várias linhas continua vazio, como no INSERT).

  • Um statement por chamada. a; b numa chamada só é erro (antes só a rodava, em silêncio). Texto sobrando depois do statement também: OFFSET, RETURNING, DELETE … LIMIT e UPDATE … FROM ainda não existem e agora dão erro de sintaxe em vez de serem ignorados.

  • UPDATE que viola um índice UNIQUE falha sem alterar nenhuma linha.

  • Texto com byte NUL (\0) é recusado, em literal e em parâmetro.

  • Permissões (Unix): arquivos novos nascem 0600; os auxiliares (.pwal, .lock) herdam o modo do .tmjp que já existe. Para um banco mais aberto, crie o arquivo vazio com o modo desejado antes de abrir. Um banco criado por versão anterior mantém a permissão que tinha: chmod 600 nele uma vez. O .lock vazio ao lado do banco é esperado e fica depois de fechar.

  • Upsert de várias linhas é tudo ou nada: um erro em qualquer linha desfaz as anteriores.

  • Manual: https://tmjlite.com.br/manual.html

  • Branches e concorrência (guia + FAQ): https://tmjlite.com.br/branches.html

  • Exemplo completo (sistema de cadastro): https://tmjlite.com.br/examples.html

  • Changelog: https://github.com/TMJacometti/TMJPlatform/blob/main/CHANGELOG.md

Licença MIT · TMJ Sistemas de Informação.

Metadata

Release files for tmjlite 0.6.2

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Built distributions (wheels)

Table of built distributions (wheels) for tmjlite 0.6.2
File Interpreter ABI Platform Actions
tmjlite-0.6.2-py3-none-win_amd64.whl Python 3 none Windows x86-64 Details for tmjlite-0.6.2-py3-none-win_amd64.whl
tmjlite-0.6.2-py3-none-manylinux_2_34_x86_64.whl Python 3 none Linux glibc 2.34+ x86-64 Details for tmjlite-0.6.2-py3-none-manylinux_2_34_x86_64.whl
tmjlite-0.6.2-py3-none-macosx_11_0_arm64.whl Python 3 none macOS 11.0+ ARM64 Details for tmjlite-0.6.2-py3-none-macosx_11_0_arm64.whl

Total release size: 3.7 MB

Release files / tmjlite-0.6.2-py3-none-win_amd64.whl

Download URL tmjlite-0.6.2-py3-none-win_amd64.whl
Size 1.3 MB
Tags Python 3 Windows x86-64
SHA-256 checksum
How to use checksums
bfc5aced3c75709e95c159412499eb7cbb81b81051fbbcdcd84565f227b71fa5
BLAKE2b-256 checksum
How to use checksums
6076e693a4fc68794a347ecc7ab58fddb64b023063f59a4288964b625b0bca49
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via twine/7.0.0 CPython/3.13.16

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Nov 25, 2026.

Transparency log

Release files / tmjlite-0.6.2-py3-none-manylinux_2_34_x86_64.whl

Download URL tmjlite-0.6.2-py3-none-manylinux_2_34_x86_64.whl
Size 1.3 MB
Tags Linux glibc 2.34+ x86-64 Python 3
SHA-256 checksum
How to use checksums
6543c1ce1e8c347682d659a7c2657ff2f6c6db6fdf7d42dad64d343cfa3769b2
BLAKE2b-256 checksum
How to use checksums
bc45ebd3940c9b55210516298838dd76226e443b11eb1d30e788a0364f5efb60
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via twine/7.0.0 CPython/3.13.16

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Nov 25, 2026.

Transparency log

Release files / tmjlite-0.6.2-py3-none-macosx_11_0_arm64.whl

Download URL tmjlite-0.6.2-py3-none-macosx_11_0_arm64.whl
Size 1.1 MB
Tags Python 3 macOS 11.0+ ARM64
SHA-256 checksum
How to use checksums
3a545ca952711907c9a6eb382213728c2f3f825853eabfb29edd65c33c810c3a
BLAKE2b-256 checksum
How to use checksums
ebb6f8e618aa6db195a5289039aefba01e4c3acb7b8459a6bdd5eb3f715f826c
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via twine/7.0.0 CPython/3.13.16

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Nov 25, 2026.

Transparency log

Security for tmjlite 0.6.2

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

Full provenance

All 3 files in this release have been uploaded with provenance metadata.

Select from 3 files

Attestation for tmjlite-0.6.2-py3-none-win_amd64.whl

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Nov 25, 2026.

Transparency log

A note on package security

PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.

To learn more about protecting yourself from malicious actors, visit our package security documentation.

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page