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

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
gi.require_version('Gtk', '3.0')
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.catalogs import add_catalog, search_catalogs
from datetime import date, datetime, timedelta
@ -173,9 +173,20 @@ class MainWinHandler:
for p in patients:
pl.add(build_patient_row(p))
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):
cl = builder.get_object('catalog_list')
cl.unselect_all()
self.catalog_list_unselected()
cl.invalidate_filter()
def build_catalog_row(catalog):
@ -198,8 +209,8 @@ def build_reception_row(reception_datetime):
box = b.get_object('reception_box')
b.get_object('hour').set_text(reception_datetime.strftime('%H'))
b.get_object('minute').set_text(reception_datetime.strftime('%M'))
with dbo.db.atomic():
reception = dbo._Reception.select().where(dbo._Reception.time == reception_datetime) # @UndefinedVariable
with db.atomic():
reception = Reception.select().where(Reception.time == reception_datetime)
row = ReceptionRow()
if len(reception):
row.props.scheduled = True
@ -273,15 +284,15 @@ redraw_reception_list(datetime.now())
patient_list = builder.get_object('patient_list')
patient_list.set_sort_func(patient_sort_func)
patient_list.set_filter_func(patient_filter_func)
with dbo.db.atomic():
for p in dbo._Patient.select(): # @UndefinedVariable
with db.atomic():
for p in Patient.select():
patient_list.add(build_patient_row(p))
#####
catalog_list = builder.get_object('catalog_list')
catalog_list.set_sort_func(catalog_sort_func)
catalog_list.set_filter_func(catalog_filter_func)
with dbo.db.atomic():
for c in dbo._Catalog.select(): # @UndefinedVariable
with db.atomic():
for c in Catalog.select():
catalog_list.add(build_catalog_row(c))
def show_msg(text, sec_text='', level='info'):
@ -343,8 +354,8 @@ def get_patient_win_values(b):
'notes': notes
}
def set_patient_win_values(patient_id, b, edit=False):
with dbo.db.atomic():
pat = dbo._Patient.select().where(dbo._Patient.id == patient_id).get() # @UndefinedVariable
with db.atomic():
pat = Patient.select().where(Patient.id == patient_id).get()
b.get_object('last_name').set_text(pat.last_name)
b.get_object('first_name').set_text(pat.first_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)
if not values:
return
with dbo.db.atomic():
with db.atomic():
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:
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)
cur_row = list(filter(lambda x: x.props.db_id == patient_id, patient_list.get_children()))[0]
patient_list.remove(cur_row)
@ -430,9 +441,9 @@ def create_new_patient_win():
values = get_patient_win_values(b)
if not values:
return
with dbo.db.atomic():
with db.atomic():
try:
patient = dbo._Patient.create(**values) # @UndefinedVariable
patient = Patient.create(**values)
except peewee.IntegrityError:
return show_msg('Данный пациент уже существует', 'Пациент с указанными фамилией, именем\nи датой рождения уже есть с базе данных', level='warn')
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()
if not len(catname):
return show_msg('Не указано имя справочника', 'Данное поле должно быть заполнено', level='warn')
with dbo.db.atomic():
with db.atomic():
try:
catalog = add_catalog(catname)
except peewee.IntegrityError:

View File

@ -1,4 +1,4 @@
from mods.db import dbo
from mods.db import db, Catalog, CatalogIndex
sys_catalogs = {
'diagnoz': 'Диагноз',
@ -8,26 +8,26 @@ sys_catalogs = {
}
def add_catalog(name, system_id = ''):
catalog = dbo._Catalog.create(name=name, system_id=system_id) # @UndefinedVariable
dbo._CatalogIndex.insert( # @UndefinedVariable
catalog = Catalog.create(name=name, system_id=system_id)
CatalogIndex.insert(
{
dbo._CatalogIndex.rowid: catalog.id,
dbo._CatalogIndex.text: name
CatalogIndex.rowid: catalog.id,
CatalogIndex.text: name
}
).execute() # @UndefinedVariable
).execute()
return catalog
def search_catalogs(q):
with dbo.db.atomic():
return (dbo._Catalog.select() # @UndefinedVariable
.join( # @UndefinedVariable
dbo._CatalogIndex,
on=(dbo._Catalog.id == dbo._CatalogIndex.rowid))
.where(dbo._CatalogIndex.match(q)) # @UndefinedVariable
.order_by(dbo._CatalogIndex.bm25())) # @UndefinedVariable
with db.atomic():
return (Catalog.select()
.join(
CatalogIndex,
on=(Catalog.id == CatalogIndex.rowid))
.where(CatalogIndex.match(q))
.order_by(CatalogIndex.bm25()))
for s_id in sys_catalogs:
with dbo.db.atomic():
q = dbo._Catalog.select().where(dbo._Catalog.system_id == s_id) # @UndefinedVariable
with db.atomic():
q = Catalog.select().where(Catalog.system_id == s_id)
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):
os.mkdir(db_dir)
class DBO:
def __init__(self):
self.db = CSqliteExtDatabase(db_file, pragmas={
db = CSqliteExtDatabase(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 = self.db
class BaseFTSModel(FTS5Model):
class Meta:
database = self.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)
doc_type = CharField(32, null=True)
doc_serial = TextField(null=True)
doc_number = TextField(null=True)
policy_number = TextField(null=True)
policy_company = TextField(null=True)
snils_number = TextField(null=True)
notes = TextField(null=True)
class Catalog(BaseModel):
id = AutoIncrementField()
system_id = TextField(null=True)
name = TextField()
class CatalogIndex(BaseFTSModel):
rowid = RowIDField()
text = SearchField()
class CatalogRecord(BaseModel):
id = AutoIncrementField()
catalog = ForeignKeyField(Catalog, backref='catalog_records', on_delete='CASCADE')
text = TextField()
class CatalogRecordIndex(BaseFTSModel):
rowid = RowIDField()
text = SearchField()
class Reception(BaseModel):
id = AutoIncrementField()
patient = ForeignKeyField(Patient, backref='receptions', on_delete='CASCADE')
time = DateTimeField()
class ReceptionDiagnosis(BaseModel):
id = AutoIncrementField()
reception = ForeignKeyField(Reception, backref='reception_diagnosisses', on_delete='CASCADE')
diagnosis = ForeignKeyField(CatalogRecord, backref='reception_diagnosisses', on_delete='CASCADE')
class ReceptionAnamnesis(BaseModel):
id = AutoIncrementField()
reception = ForeignKeyField(Reception, backref='reception_anamnesisses', on_delete='CASCADE')
text = TextField()
class PatientIndex(BaseFTSModel):
rowid = RowIDField()
fio = SearchField()
### Настройки
class Settings(BaseModel):
key = TextField()
val = JSONField()
###
self._Patient = Patient
self._Catalog = Catalog
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')
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)
doc_type = CharField(32, null=True)
doc_serial = TextField(null=True)
doc_number = TextField(null=True)
policy_number = TextField(null=True)
policy_company = TextField(null=True)
snils_number = TextField(null=True)
notes = TextField(null=True)
class Catalog(BaseModel):
id = AutoIncrementField()
system_id = TextField(null=True)
name = TextField()
class CatalogIndex(BaseFTSModel):
rowid = RowIDField()
text = SearchField()
class CatalogRecord(BaseModel):
id = AutoIncrementField()
catalog = ForeignKeyField(Catalog, backref='catalog_records', on_delete='CASCADE')
text = TextField()
class CatalogRecordIndex(BaseFTSModel):
rowid = RowIDField()
text = SearchField()
class Reception(BaseModel):
id = AutoIncrementField()
patient = ForeignKeyField(Patient, backref='receptions', on_delete='CASCADE')
time = DateTimeField()
class ReceptionDiagnosis(BaseModel):
id = AutoIncrementField()
reception = ForeignKeyField(Reception, backref='reception_diagnosisses', on_delete='CASCADE')
diagnosis = ForeignKeyField(CatalogRecord, backref='reception_diagnosisses', on_delete='CASCADE')
class ReceptionAnamnesis(BaseModel):
id = AutoIncrementField()
reception = ForeignKeyField(Reception, backref='reception_anamnesisses', on_delete='CASCADE')
text = TextField()
class PatientIndex(BaseFTSModel):
rowid = RowIDField()
fio = SearchField()
### Настройки
class Settings(BaseModel):
key = TextField()
val = JSONField()
###
Patient.add_index(
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._Catalog.add_index(self._Catalog.index(fn.lower(self._Catalog.name), unique=True, name='catalog_name_unique'))
self.db.create_tables([
self._Patient,
self._PatientIndex,
self._Catalog,
self._CatalogIndex,
self._CatalogRecord,
self._CatalogRecordIndex,
self._Reception,
self._ReceptionDiagnosis,
self._ReceptionAnamnesis,
self._Settings
Catalog.add_index(Catalog.index(fn.lower(Catalog.name), unique=True, name='catalog_name_unique'))
db.create_tables([
Patient,
PatientIndex,
Catalog,
CatalogIndex,
CatalogRecord,
CatalogRecordIndex,
Reception,
ReceptionDiagnosis,
ReceptionAnamnesis,
Settings
])
def search_patients(q):
with dbo.db.atomic():
return (dbo._Patient.select()
with db.atomic():
return (Patient.select()
.join(
dbo._PatientIndex,
on=(dbo._Patient.id == dbo._PatientIndex.rowid))
.where(dbo._PatientIndex.match(q))
.order_by(dbo._PatientIndex.bm25()))
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)
dbo._PatientIndex.insert(
PatientIndex.insert(
{
dbo._PatientIndex.rowid: pat.id,
dbo._PatientIndex.fio: ' '.join(fio_list)
PatientIndex.rowid: pat.id,
PatientIndex.fio: ' '.join(fio_list)
}
).execute()
def update_patient_index(pat):
fio_list = [pat.last_name, pat.first_name]
if 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'
@ -12,7 +12,7 @@ def s_get_reception_list():
day_start = None
day_end = 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.day_start = s[S_RECEPTION_LIST_DAY_START]
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_INTERVAL: interval
}
with dbo.db.atomic():
q = dbo._Settings.select().where(dbo._Settings.key == S_KEY_RECEPTION_LIST) # @UndefinedVariable
with db.atomic():
q = Settings.select().where(Settings.key == S_KEY_RECEPTION_LIST)
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:
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():
q = dbo._Settings.select().where(dbo._Settings.key == S_KEY_RECEPTION_LIST) # @UndefinedVariable
with db.atomic():
q = Settings.select().where(Settings.key == S_KEY_RECEPTION_LIST)
if not len(q):
s_set_reception_list([8,0], [17,0], 30)

View File

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

View File

@ -353,8 +353,23 @@
</packing>
</child>
<child>
<object class="GtkToolButton">
<object class="GtkToolButton" id="catalog_open_button">
<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="label" translatable="yes">Переименовать</property>
<property name="use_underline">True</property>
@ -385,6 +400,7 @@
<object class="GtkListBox" id="catalog_list">
<property name="visible">True</property>
<property name="can_focus">False</property>
<signal name="row-selected" handler="catalog_list_selected" swapped="no"/>
</object>
</child>
</object>

View File

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

View File

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