From 5f2e8c1af20fd4d9d790b00205f4a070edc2e16b Mon Sep 17 00:00:00 2001 From: WanderMotta Date: Sat, 25 Jul 2026 00:12:31 -0300 Subject: [PATCH] Commit inicial - upload de todos os arquivos da pasta --- app/database.py | 22 +++++++++++++++------- 1 file changed, 15 insertions(+), 7 deletions(-) diff --git a/app/database.py b/app/database.py index 9cc37ca..cbc653a 100644 --- a/app/database.py +++ b/app/database.py @@ -16,6 +16,14 @@ from typing import Any, Iterator from .config import get_settings +_CATEGORIA_SCHEMA = """ +CREATE TABLE IF NOT EXISTS categoria ( + id INTEGER PRIMARY KEY AUTOINCREMENT, + categoria TEXT NOT NULL, + palavra_chave TEXT NOT NULL +); +""" + SCHEMA = """ CREATE TABLE IF NOT EXISTS users ( id INTEGER PRIMARY KEY AUTOINCREMENT, @@ -67,12 +75,7 @@ CREATE TABLE IF NOT EXISTS detected_documents ( updated_at TEXT NOT NULL DEFAULT CURRENT_TIMESTAMP ); -CREATE TABLE IF NOT EXISTS categoria ( - id INTEGER PRIMARY KEY AUTOINCREMENT, - categoria TEXT NOT NULL, - palavra_chave TEXT NOT NULL -); - +__CATEGORIA_PLACEHOLDER__ CREATE TABLE IF NOT EXISTS fiscal_documents ( id INTEGER PRIMARY KEY AUTOINCREMENT, detected_document_id INTEGER REFERENCES detected_documents(id) ON DELETE SET NULL, @@ -90,7 +93,7 @@ CREATE TABLE IF NOT EXISTS fiscal_documents ( CREATE INDEX IF NOT EXISTS idx_fiscal_competencia ON fiscal_documents(ano, mes); CREATE INDEX IF NOT EXISTS idx_detected_batch ON detected_documents(batch_id, status); -""" +""".replace("__CATEGORIA_PLACEHOLDER__", _CATEGORIA_SCHEMA) _RESERVED_CATEGORIA_SEED = ( "INSERT OR IGNORE INTO categoria (id, categoria, palavra_chave) VALUES (1, 'Não Encontrado', '')" @@ -233,6 +236,11 @@ def _migrate_competencia(conn: sqlite3.Connection) -> None: def init_db(conn: sqlite3.Connection) -> None: + # `categoria` precisa existir antes da migração: `_rebuild_fiscal_documents` + # recria `fiscal_documents` com `categoria_id REFERENCES categoria(id)`, e com + # `PRAGMA foreign_keys = ON` o INSERT falha com "no such table" se a tabela + # referenciada ainda não existir num banco pré-existente sem ela. + conn.execute(_CATEGORIA_SCHEMA) _migrate_competencia(conn) conn.executescript(SCHEMA) columns = {row["name"] for row in conn.execute("PRAGMA table_info(fiscal_documents)")}