выернул на нормальное подключение к БД

This commit is contained in:
Бородин Роман 2019-11-19 15:37:53 +03:00
parent 6cf4e79f9f
commit fbafb5b5ee
8 changed files with 162 additions and 140 deletions

41
app.py
View File

@ -2,7 +2,7 @@ import gi
import os import os
gi.require_version('Gtk', '3.0') gi.require_version('Gtk', '3.0')
from gi.repository import Gtk, GObject, Gdk from gi.repository import Gtk, GObject, Gdk
from mods.db import store_patient_index, update_patient_index, search_patients, dbo from mods.db import store_patient_index, update_patient_index, search_patients, db, Patient, Reception, Catalog
from mods.settings import s_get_reception_list, s_set_reception_list from mods.settings import s_get_reception_list, s_set_reception_list
from mods.catalogs import add_catalog, search_catalogs from mods.catalogs import add_catalog, search_catalogs
from datetime import date, datetime, timedelta from datetime import date, datetime, timedelta
@ -173,9 +173,20 @@ class MainWinHandler:
for p in patients: for p in patients:
pl.add(build_patient_row(p)) pl.add(build_patient_row(p))
pl.show_all()''' pl.show_all()'''
def catalog_list_selected(self, *a):
open_button = builder.get_object('catalog_open_button')
rename_button = builder.get_object('catalog_rename_button')
open_button.set_sensitive(True)
rename_button.set_sensitive(True)
def catalog_list_unselected(self, *a):
open_button = builder.get_object('catalog_open_button')
rename_button = builder.get_object('catalog_rename_button')
open_button.set_sensitive(False)
rename_button.set_sensitive(False)
def catalog_filter_changed(self, filter_widget): def catalog_filter_changed(self, filter_widget):
cl = builder.get_object('catalog_list') cl = builder.get_object('catalog_list')
cl.unselect_all() cl.unselect_all()
self.catalog_list_unselected()
cl.invalidate_filter() cl.invalidate_filter()
def build_catalog_row(catalog): def build_catalog_row(catalog):
@ -198,8 +209,8 @@ def build_reception_row(reception_datetime):
box = b.get_object('reception_box') box = b.get_object('reception_box')
b.get_object('hour').set_text(reception_datetime.strftime('%H')) b.get_object('hour').set_text(reception_datetime.strftime('%H'))
b.get_object('minute').set_text(reception_datetime.strftime('%M')) b.get_object('minute').set_text(reception_datetime.strftime('%M'))
with dbo.db.atomic(): with db.atomic():
reception = dbo._Reception.select().where(dbo._Reception.time == reception_datetime) # @UndefinedVariable reception = Reception.select().where(Reception.time == reception_datetime)
row = ReceptionRow() row = ReceptionRow()
if len(reception): if len(reception):
row.props.scheduled = True row.props.scheduled = True
@ -273,15 +284,15 @@ redraw_reception_list(datetime.now())
patient_list = builder.get_object('patient_list') patient_list = builder.get_object('patient_list')
patient_list.set_sort_func(patient_sort_func) patient_list.set_sort_func(patient_sort_func)
patient_list.set_filter_func(patient_filter_func) patient_list.set_filter_func(patient_filter_func)
with dbo.db.atomic(): with db.atomic():
for p in dbo._Patient.select(): # @UndefinedVariable for p in Patient.select():
patient_list.add(build_patient_row(p)) patient_list.add(build_patient_row(p))
##### #####
catalog_list = builder.get_object('catalog_list') catalog_list = builder.get_object('catalog_list')
catalog_list.set_sort_func(catalog_sort_func) catalog_list.set_sort_func(catalog_sort_func)
catalog_list.set_filter_func(catalog_filter_func) catalog_list.set_filter_func(catalog_filter_func)
with dbo.db.atomic(): with db.atomic():
for c in dbo._Catalog.select(): # @UndefinedVariable for c in Catalog.select():
catalog_list.add(build_catalog_row(c)) catalog_list.add(build_catalog_row(c))
def show_msg(text, sec_text='', level='info'): def show_msg(text, sec_text='', level='info'):
@ -343,8 +354,8 @@ def get_patient_win_values(b):
'notes': notes 'notes': notes
} }
def set_patient_win_values(patient_id, b, edit=False): def set_patient_win_values(patient_id, b, edit=False):
with dbo.db.atomic(): with db.atomic():
pat = dbo._Patient.select().where(dbo._Patient.id == patient_id).get() # @UndefinedVariable pat = Patient.select().where(Patient.id == patient_id).get()
b.get_object('last_name').set_text(pat.last_name) b.get_object('last_name').set_text(pat.last_name)
b.get_object('first_name').set_text(pat.first_name) b.get_object('first_name').set_text(pat.first_name)
b.get_object('middle_name').set_text(pat.middle_name) b.get_object('middle_name').set_text(pat.middle_name)
@ -399,12 +410,12 @@ def create_edit_patient_win(patient_id):
values = get_patient_win_values(b) values = get_patient_win_values(b)
if not values: if not values:
return return
with dbo.db.atomic(): with db.atomic():
try: try:
dbo._Patient.update(**values).where(dbo._Patient.id == patient_id).execute() # @UndefinedVariable Patient.update(**values).where(Patient.id == patient_id).execute()
except peewee.IntegrityError: except peewee.IntegrityError:
return show_msg('Данный пациент уже существует', 'Другой пациент с указанными фамилией, именем\nи датой рождения уже есть с базе данных', level='warn') return show_msg('Данный пациент уже существует', 'Другой пациент с указанными фамилией, именем\nи датой рождения уже есть с базе данных', level='warn')
patient = dbo._Patient.select().where(dbo._Patient.id == patient_id).get() # @UndefinedVariable patient = Patient.select().where(Patient.id == patient_id).get()
update_patient_index(patient) update_patient_index(patient)
cur_row = list(filter(lambda x: x.props.db_id == patient_id, patient_list.get_children()))[0] cur_row = list(filter(lambda x: x.props.db_id == patient_id, patient_list.get_children()))[0]
patient_list.remove(cur_row) patient_list.remove(cur_row)
@ -430,9 +441,9 @@ def create_new_patient_win():
values = get_patient_win_values(b) values = get_patient_win_values(b)
if not values: if not values:
return return
with dbo.db.atomic(): with db.atomic():
try: try:
patient = dbo._Patient.create(**values) # @UndefinedVariable patient = Patient.create(**values)
except peewee.IntegrityError: except peewee.IntegrityError:
return show_msg('Данный пациент уже существует', 'Пациент с указанными фамилией, именем\nи датой рождения уже есть с базе данных', level='warn') return show_msg('Данный пациент уже существует', 'Пациент с указанными фамилией, именем\nи датой рождения уже есть с базе данных', level='warn')
store_patient_index(patient) store_patient_index(patient)
@ -476,7 +487,7 @@ def create_new_catalog_win():
catname = re.sub(r'\s+', ' ', b.get_object('catalog_name').get_text()).strip() catname = re.sub(r'\s+', ' ', b.get_object('catalog_name').get_text()).strip()
if not len(catname): if not len(catname):
return show_msg('Не указано имя справочника', 'Данное поле должно быть заполнено', level='warn') return show_msg('Не указано имя справочника', 'Данное поле должно быть заполнено', level='warn')
with dbo.db.atomic(): with db.atomic():
try: try:
catalog = add_catalog(catname) catalog = add_catalog(catname)
except peewee.IntegrityError: except peewee.IntegrityError:

View File

@ -1,4 +1,4 @@
from mods.db import dbo from mods.db import db, Catalog, CatalogIndex
sys_catalogs = { sys_catalogs = {
'diagnoz': 'Диагноз', 'diagnoz': 'Диагноз',
@ -8,26 +8,26 @@ sys_catalogs = {
} }
def add_catalog(name, system_id = ''): def add_catalog(name, system_id = ''):
catalog = dbo._Catalog.create(name=name, system_id=system_id) # @UndefinedVariable catalog = Catalog.create(name=name, system_id=system_id)
dbo._CatalogIndex.insert( # @UndefinedVariable CatalogIndex.insert(
{ {
dbo._CatalogIndex.rowid: catalog.id, CatalogIndex.rowid: catalog.id,
dbo._CatalogIndex.text: name CatalogIndex.text: name
} }
).execute() # @UndefinedVariable ).execute()
return catalog return catalog
def search_catalogs(q): def search_catalogs(q):
with dbo.db.atomic(): with db.atomic():
return (dbo._Catalog.select() # @UndefinedVariable return (Catalog.select()
.join( # @UndefinedVariable .join(
dbo._CatalogIndex, CatalogIndex,
on=(dbo._Catalog.id == dbo._CatalogIndex.rowid)) on=(Catalog.id == CatalogIndex.rowid))
.where(dbo._CatalogIndex.match(q)) # @UndefinedVariable .where(CatalogIndex.match(q))
.order_by(dbo._CatalogIndex.bm25())) # @UndefinedVariable .order_by(CatalogIndex.bm25()))
for s_id in sys_catalogs: for s_id in sys_catalogs:
with dbo.db.atomic(): with db.atomic():
q = dbo._Catalog.select().where(dbo._Catalog.system_id == s_id) # @UndefinedVariable q = Catalog.select().where(Catalog.system_id == s_id)
if not len(q): if not len(q):
add_catalog(sys_catalogs[s_id], s_id) # @UndefinedVariable add_catalog(sys_catalogs[s_id], s_id)

View File

@ -11,127 +11,110 @@ if not os.path.exists(var_dir):
if not os.path.exists(db_dir): if not os.path.exists(db_dir):
os.mkdir(db_dir) os.mkdir(db_dir)
class DBO: db = CSqliteExtDatabase(db_file, pragmas={
def __init__(self):
self.db = CSqliteExtDatabase(db_file, pragmas={
'journal_mode': 'wal', 'journal_mode': 'wal',
'cache_size': -1 * 64000, # 64MB 'cache_size': -1 * 64000, # 64MB
'foreign_keys': 'on', 'foreign_keys': 'on',
'ignore_check_constraints': 'off', 'ignore_check_constraints': 'off',
'synchronous': 'off'}) 'synchronous': 'off'})
class BaseModel(Model): class BaseModel(Model):
'Базовая таблица' 'Базовая таблица'
class Meta: class Meta:
database = self.db database = db
class BaseFTSModel(FTS5Model): class BaseFTSModel(FTS5Model):
class Meta: class Meta:
database = self.db database = db
options = {'tokenize': 'porter'} options = {'tokenize': 'porter'}
class Patient(BaseModel): class Patient(BaseModel):
id = AutoIncrementField() id = AutoIncrementField()
last_name = TextField() last_name = TextField()
first_name = TextField() first_name = TextField()
middle_name = TextField(null=True) middle_name = TextField(null=True)
birth_date = DateField() birth_date = DateField()
gender = CharField(6) gender = CharField(6)
doc_type = CharField(32, null=True) doc_type = CharField(32, null=True)
doc_serial = TextField(null=True) doc_serial = TextField(null=True)
doc_number = TextField(null=True) doc_number = TextField(null=True)
policy_number = TextField(null=True) policy_number = TextField(null=True)
policy_company = TextField(null=True) policy_company = TextField(null=True)
snils_number = TextField(null=True) snils_number = TextField(null=True)
notes = TextField(null=True) notes = TextField(null=True)
class Catalog(BaseModel): class Catalog(BaseModel):
id = AutoIncrementField() id = AutoIncrementField()
system_id = TextField(null=True) system_id = TextField(null=True)
name = TextField() name = TextField()
class CatalogIndex(BaseFTSModel): class CatalogIndex(BaseFTSModel):
rowid = RowIDField() rowid = RowIDField()
text = SearchField() text = SearchField()
class CatalogRecord(BaseModel): class CatalogRecord(BaseModel):
id = AutoIncrementField() id = AutoIncrementField()
catalog = ForeignKeyField(Catalog, backref='catalog_records', on_delete='CASCADE') catalog = ForeignKeyField(Catalog, backref='catalog_records', on_delete='CASCADE')
text = TextField() text = TextField()
class CatalogRecordIndex(BaseFTSModel): class CatalogRecordIndex(BaseFTSModel):
rowid = RowIDField() rowid = RowIDField()
text = SearchField() text = SearchField()
class Reception(BaseModel): class Reception(BaseModel):
id = AutoIncrementField() id = AutoIncrementField()
patient = ForeignKeyField(Patient, backref='receptions', on_delete='CASCADE') patient = ForeignKeyField(Patient, backref='receptions', on_delete='CASCADE')
time = DateTimeField() time = DateTimeField()
class ReceptionDiagnosis(BaseModel): class ReceptionDiagnosis(BaseModel):
id = AutoIncrementField() id = AutoIncrementField()
reception = ForeignKeyField(Reception, backref='reception_diagnosisses', on_delete='CASCADE') reception = ForeignKeyField(Reception, backref='reception_diagnosisses', on_delete='CASCADE')
diagnosis = ForeignKeyField(CatalogRecord, backref='reception_diagnosisses', on_delete='CASCADE') diagnosis = ForeignKeyField(CatalogRecord, backref='reception_diagnosisses', on_delete='CASCADE')
class ReceptionAnamnesis(BaseModel): class ReceptionAnamnesis(BaseModel):
id = AutoIncrementField() id = AutoIncrementField()
reception = ForeignKeyField(Reception, backref='reception_anamnesisses', on_delete='CASCADE') reception = ForeignKeyField(Reception, backref='reception_anamnesisses', on_delete='CASCADE')
text = TextField() text = TextField()
class PatientIndex(BaseFTSModel): class PatientIndex(BaseFTSModel):
rowid = RowIDField() rowid = RowIDField()
fio = SearchField() fio = SearchField()
### Настройки ### Настройки
class Settings(BaseModel): class Settings(BaseModel):
key = TextField() key = TextField()
val = JSONField() val = JSONField()
### ###
self._Patient = Patient Patient.add_index(
self._Catalog = Catalog Patient.index(fn.lower(Patient.last_name), fn.lower(Patient.first_name), Patient.birth_date, unique=True, name='patient_first_last_name_birth_date_unique')
self._CatalogIndex = CatalogIndex
self._CatalogRecord = CatalogRecord
self._CatalogRecordIndex = CatalogRecordIndex
self._Reception = Reception
self._ReceptionDiagnosis = ReceptionDiagnosis
self._ReceptionAnamnesis = ReceptionAnamnesis
self._PatientIndex = PatientIndex
self._Settings = Settings
self.db.connect()
def create(self):
self._Patient.add_index(
self._Patient.index(fn.lower(self._Patient.last_name), fn.lower(self._Patient.first_name), self._Patient.birth_date, unique=True, name='patient_first_last_name_birth_date_unique')
) )
self._Catalog.add_index(self._Catalog.index(fn.lower(self._Catalog.name), unique=True, name='catalog_name_unique')) Catalog.add_index(Catalog.index(fn.lower(Catalog.name), unique=True, name='catalog_name_unique'))
self.db.create_tables([ db.create_tables([
self._Patient, Patient,
self._PatientIndex, PatientIndex,
self._Catalog, Catalog,
self._CatalogIndex, CatalogIndex,
self._CatalogRecord, CatalogRecord,
self._CatalogRecordIndex, CatalogRecordIndex,
self._Reception, Reception,
self._ReceptionDiagnosis, ReceptionDiagnosis,
self._ReceptionAnamnesis, ReceptionAnamnesis,
self._Settings Settings
]) ])
def search_patients(q): def search_patients(q):
with dbo.db.atomic(): with db.atomic():
return (dbo._Patient.select() return (Patient.select()
.join( .join(
dbo._PatientIndex, PatientIndex,
on=(dbo._Patient.id == dbo._PatientIndex.rowid)) on=(Patient.id == PatientIndex.rowid))
.where(dbo._PatientIndex.match(q)) .where(PatientIndex.match(q))
.order_by(dbo._PatientIndex.bm25())) .order_by(PatientIndex.bm25()))
def store_patient_index(pat): def store_patient_index(pat):
fio_list = [pat.last_name, pat.first_name] fio_list = [pat.last_name, pat.first_name]
if pat.middle_name: if pat.middle_name:
fio_list.append(pat.middle_name) fio_list.append(pat.middle_name)
dbo._PatientIndex.insert( PatientIndex.insert(
{ {
dbo._PatientIndex.rowid: pat.id, PatientIndex.rowid: pat.id,
dbo._PatientIndex.fio: ' '.join(fio_list) PatientIndex.fio: ' '.join(fio_list)
} }
).execute() ).execute()
def update_patient_index(pat): def update_patient_index(pat):
fio_list = [pat.last_name, pat.first_name] fio_list = [pat.last_name, pat.first_name]
if pat.middle_name: if pat.middle_name:
fio_list.append(pat.middle_name) fio_list.append(pat.middle_name)
dbo._PatientIndex.update( PatientIndex.update(
{ {
dbo._PatientIndex.fio: ' '.join(fio_list) PatientIndex.fio: ' '.join(fio_list)
} }
).where(dbo._PatientIndex.rowid == pat.id).execute() ).where(PatientIndex.rowid == pat.id).execute()
dbo = DBO()
dbo.create()

View File

@ -1,4 +1,4 @@
from mods.db import dbo from mods.db import db, Settings
# Имена ключей параметров # Имена ключей параметров
S_KEY_RECEPTION_LIST = 'reception_list' S_KEY_RECEPTION_LIST = 'reception_list'
@ -12,7 +12,7 @@ def s_get_reception_list():
day_start = None day_start = None
day_end = None day_end = None
interval = None interval = None
s = dbo._Settings.get(dbo._Settings.key == S_KEY_RECEPTION_LIST).val # @UndefinedVariable s = Settings.get(Settings.key == S_KEY_RECEPTION_LIST).val
o = RLSettings() o = RLSettings()
o.day_start = s[S_RECEPTION_LIST_DAY_START] o.day_start = s[S_RECEPTION_LIST_DAY_START]
o.day_end = s[S_RECEPTION_LIST_DAY_END] o.day_end = s[S_RECEPTION_LIST_DAY_END]
@ -25,16 +25,16 @@ def s_set_reception_list(dstart, dend, interval):
S_RECEPTION_LIST_DAY_END: dend, S_RECEPTION_LIST_DAY_END: dend,
S_RECEPTION_LIST_INTERVAL: interval S_RECEPTION_LIST_INTERVAL: interval
} }
with dbo.db.atomic(): with db.atomic():
q = dbo._Settings.select().where(dbo._Settings.key == S_KEY_RECEPTION_LIST) # @UndefinedVariable q = Settings.select().where(Settings.key == S_KEY_RECEPTION_LIST)
if not len(q): if not len(q):
dbo._Settings.create(key=S_KEY_RECEPTION_LIST, val=v) # @UndefinedVariable Settings.create(key=S_KEY_RECEPTION_LIST, val=v)
else: else:
dbo._Settings.update(val=v).where(dbo._Settings.key == S_KEY_RECEPTION_LIST).execute() # @UndefinedVariable Settings.update(val=v).where(Settings.key == S_KEY_RECEPTION_LIST).execute()
### Инициализация начальных значений параметров ### Инициализация начальных значений параметров
# Начальный график приёмов # Начальный график приёмов
with dbo.db.atomic(): with db.atomic():
q = dbo._Settings.select().where(dbo._Settings.key == S_KEY_RECEPTION_LIST) # @UndefinedVariable q = Settings.select().where(Settings.key == S_KEY_RECEPTION_LIST)
if not len(q): if not len(q):
s_set_reception_list([8,0], [17,0], 30) s_set_reception_list([8,0], [17,0], 30)

View File

@ -7,6 +7,7 @@
<property name="can_focus">False</property> <property name="can_focus">False</property>
<property name="modal">True</property> <property name="modal">True</property>
<property name="window_position">center</property> <property name="window_position">center</property>
<property name="type_hint">dialog</property>
<signal name="destroy" handler="edit_patient_win_close" swapped="no"/> <signal name="destroy" handler="edit_patient_win_close" swapped="no"/>
<child type="titlebar"> <child type="titlebar">
<object class="GtkHeaderBar" id="header"> <object class="GtkHeaderBar" id="header">

View File

@ -353,8 +353,23 @@
</packing> </packing>
</child> </child>
<child> <child>
<object class="GtkToolButton"> <object class="GtkToolButton" id="catalog_open_button">
<property name="visible">True</property> <property name="visible">True</property>
<property name="sensitive">False</property>
<property name="can_focus">False</property>
<property name="label" translatable="yes">Открыть</property>
<property name="use_underline">True</property>
<property name="stock_id">gtk-open</property>
</object>
<packing>
<property name="expand">False</property>
<property name="homogeneous">True</property>
</packing>
</child>
<child>
<object class="GtkToolButton" id="catalog_rename_button">
<property name="visible">True</property>
<property name="sensitive">False</property>
<property name="can_focus">False</property> <property name="can_focus">False</property>
<property name="label" translatable="yes">Переименовать</property> <property name="label" translatable="yes">Переименовать</property>
<property name="use_underline">True</property> <property name="use_underline">True</property>
@ -385,6 +400,7 @@
<object class="GtkListBox" id="catalog_list"> <object class="GtkListBox" id="catalog_list">
<property name="visible">True</property> <property name="visible">True</property>
<property name="can_focus">False</property> <property name="can_focus">False</property>
<signal name="row-selected" handler="catalog_list_selected" swapped="no"/>
</object> </object>
</child> </child>
</object> </object>

View File

@ -7,6 +7,7 @@
<property name="can_focus">False</property> <property name="can_focus">False</property>
<property name="modal">True</property> <property name="modal">True</property>
<property name="window_position">center</property> <property name="window_position">center</property>
<property name="type_hint">dialog</property>
<child type="titlebar"> <child type="titlebar">
<object class="GtkHeaderBar" id="header"> <object class="GtkHeaderBar" id="header">
<property name="visible">True</property> <property name="visible">True</property>

View File

@ -7,6 +7,7 @@
<property name="can_focus">False</property> <property name="can_focus">False</property>
<property name="modal">True</property> <property name="modal">True</property>
<property name="window_position">center</property> <property name="window_position">center</property>
<property name="type_hint">dialog</property>
<child type="titlebar"> <child type="titlebar">
<object class="GtkHeaderBar" id="open_patient_bar"> <object class="GtkHeaderBar" id="open_patient_bar">
<property name="visible">True</property> <property name="visible">True</property>
@ -90,6 +91,9 @@
<property name="visible">True</property> <property name="visible">True</property>
<property name="can_focus">False</property> <property name="can_focus">False</property>
<property name="xalign">0</property> <property name="xalign">0</property>
<attributes>
<attribute name="weight" value="bold"/>
</attributes>
</object> </object>
<packing> <packing>
<property name="expand">False</property> <property name="expand">False</property>
@ -102,6 +106,9 @@
<property name="visible">True</property> <property name="visible">True</property>
<property name="can_focus">False</property> <property name="can_focus">False</property>
<property name="xalign">0</property> <property name="xalign">0</property>
<attributes>
<attribute name="weight" value="bold"/>
</attributes>
</object> </object>
<packing> <packing>
<property name="expand">False</property> <property name="expand">False</property>
@ -114,6 +121,9 @@
<property name="visible">True</property> <property name="visible">True</property>
<property name="can_focus">False</property> <property name="can_focus">False</property>
<property name="xalign">0</property> <property name="xalign">0</property>
<attributes>
<attribute name="weight" value="bold"/>
</attributes>
</object> </object>
<packing> <packing>
<property name="expand">False</property> <property name="expand">False</property>