84 lines
1.9 KiB
Python
Executable File
84 lines
1.9 KiB
Python
Executable File
#!/usr/bin/env python
|
|
|
|
from flask import current_app, g
|
|
import os
|
|
import sqlite3
|
|
import typing
|
|
from typing import Optional
|
|
|
|
|
|
def get() -> sqlite3.Connection:
|
|
if 'db' not in g:
|
|
g.db = sqlite3.connect(
|
|
os.environ.get('DATABASE_PATH', 'db.sqlite'),
|
|
detect_types=sqlite3.PARSE_DECLTYPES,
|
|
)
|
|
g.db.row_factory = sqlite3.Row
|
|
|
|
return g.db
|
|
|
|
|
|
def init(db):
|
|
with open('schema.sql', 'r') as f:
|
|
db.executescript(f.read())
|
|
|
|
|
|
def close():
|
|
db = g.pop('db', None)
|
|
|
|
if db is not None:
|
|
db.close()
|
|
|
|
|
|
def init_app(app):
|
|
app.teardown_appcontext(close)
|
|
app.cli.add_command(init)
|
|
|
|
|
|
if __name__ == '__main__':
|
|
db = sqlite3.connect(
|
|
os.environ.get('DATABASE_PATH', 'db.sqlite'),
|
|
detect_types=sqlite3.PARSE_DECLTYPES,
|
|
)
|
|
db.row_factory = sqlite3.Row
|
|
init(db)
|
|
|
|
|
|
class Object:
|
|
@staticmethod
|
|
def select_args() -> str:
|
|
return 'id, name'
|
|
|
|
def __init__(self, object_id: int, name: str):
|
|
self.id = object_id
|
|
self.name = name
|
|
|
|
def save(self, db: sqlite3.Connection):
|
|
cur = db.cursor()
|
|
cur.execute(
|
|
'UPDATE object SET name = ? WHERE id = ?',
|
|
[self.name, self.id]
|
|
)
|
|
|
|
@staticmethod
|
|
def from_row(row: sqlite3.Row) -> 'Object':
|
|
return Object(*row)
|
|
|
|
@staticmethod
|
|
def get_from_id(object_id: int, db: sqlite3.Connection) -> Optional['Object']:
|
|
cur = db.cursor()
|
|
response = cur.execute(
|
|
'SELECT ' + Object.select_args() + ' FROM object WHERE id = ?;',
|
|
[object_id]
|
|
)
|
|
return Object.from_row(response.fetchone())
|
|
|
|
@staticmethod
|
|
def all(db: sqlite3.Connection) -> list['Object']:
|
|
cur = db.cursor()
|
|
response = cur.execute(
|
|
'SELECT ' + Object.select_args() + ' FROM object;',
|
|
[]
|
|
)
|
|
return list(map(Object.from_row, response.fetchall()))
|