import os from peewee import Model, CharField, BigAutoField, DateTimeField, IntegerField, fn, Field, Expression, TextField, ForeignKeyField, DateField from playhouse.sqlite_ext import SqliteExtDatabase, FTS5Model, AutoIncrementField, SearchField, RowIDField var_dir = os.path.join(os.path.abspath(os.environ['HOME']), '.eldoc') db_dir = os.path.join(var_dir, 'db') db_file = os.path.join(db_dir, 'eldoc.sqlite3') if not os.path.exists(var_dir): os.mkdir(var_dir) if not os.path.exists(db_dir): os.mkdir(db_dir) db = SqliteExtDatabase(db_file, pragmas={ 'journal_mode': 'wal', 'cache_size': -1 * 64000, # 64MB 'foreign_keys': 'on', 'ignore_check_constraints': 'off', 'synchronous': 'off'}) class BaseModel(Model): 'Базовая таблица' class Meta: database = db class BaseFTSModel(FTS5Model): class Meta: database = db options = {'tokenize': 'porter'} class Patient(BaseModel): id = AutoIncrementField() last_name = TextField() first_name = TextField() middle_name = TextField(null=True) birth_date = DateField() gender = CharField(6) Patient.add_index( Patient.index(Patient.last_name, Patient.first_name, Patient.birth_date, unique=True) ) class PatientIndex(BaseFTSModel): rowid = RowIDField() fio = SearchField() def search_patients(q): with db.atomic(): return (Patient.select() .join( PatientIndex, on=(Patient.id == PatientIndex.rowid)) .where(PatientIndex.match(q)) .order_by(PatientIndex.bm25())) def store_patient_index(pat): fio_list = [pat.last_name, pat.first_name] if pat.middle_name: fio_list.append(pat.middle_name) PatientIndex.insert( { PatientIndex.rowid: pat.id, PatientIndex.fio: ' '.join(fio_list) } ).execute() db.connect() db.create_tables([ Patient, PatientIndex ])