feat: added seseion for sqlite, alembic and ruff, model Timerr, schemas.py, mixin for id, cruds: create timer, get timer, settings.py for db
This commit is contained in:
0
kawai_focus/database/__init__.py
Normal file
0
kawai_focus/database/__init__.py
Normal file
1
kawai_focus/database/alembic/README
Normal file
1
kawai_focus/database/alembic/README
Normal file
@@ -0,0 +1 @@
|
||||
Generic single-database configuration.
|
||||
85
kawai_focus/database/alembic/env.py
Normal file
85
kawai_focus/database/alembic/env.py
Normal file
@@ -0,0 +1,85 @@
|
||||
from logging.config import fileConfig
|
||||
|
||||
from sqlalchemy import engine_from_config
|
||||
from sqlalchemy import pool
|
||||
|
||||
from alembic import context
|
||||
|
||||
from kawai_focus.settings import settings
|
||||
from kawai_focus.database.models import Base
|
||||
|
||||
|
||||
# this is the Alembic Config object, which provides
|
||||
# access to the values within the .ini file in use.
|
||||
config = context.config
|
||||
|
||||
config.set_main_option("sqlalchemy.url", settings.db_settings.get_url_db)
|
||||
|
||||
# Interpret the config file for Python logging.
|
||||
# This line sets up loggers basically.
|
||||
if config.config_file_name is not None:
|
||||
fileConfig(config.config_file_name)
|
||||
|
||||
# add your model's MetaData object here
|
||||
# for 'autogenerate' support
|
||||
# from myapp import mymodel
|
||||
# target_metadata = mymodel.Base.metadata
|
||||
|
||||
target_metadata = Base.metadata
|
||||
|
||||
# other values from the config, defined by the needs of env.py,
|
||||
# can be acquired:
|
||||
# my_important_option = config.get_main_option("my_important_option")
|
||||
# ... etc.
|
||||
|
||||
|
||||
def run_migrations_offline() -> None:
|
||||
"""Run migrations in 'offline' mode.
|
||||
|
||||
This configures the context with just a URL
|
||||
and not an Engine, though an Engine is acceptable
|
||||
here as well. By skipping the Engine creation
|
||||
we don't even need a DBAPI to be available.
|
||||
|
||||
Calls to context.execute() here emit the given string to the
|
||||
script output.
|
||||
|
||||
"""
|
||||
url = config.get_main_option("sqlalchemy.url")
|
||||
context.configure(
|
||||
url=url,
|
||||
target_metadata=target_metadata,
|
||||
literal_binds=True,
|
||||
dialect_opts={"paramstyle": "named"},
|
||||
)
|
||||
|
||||
with context.begin_transaction():
|
||||
context.run_migrations()
|
||||
|
||||
|
||||
def run_migrations_online() -> None:
|
||||
"""Run migrations in 'online' mode.
|
||||
|
||||
In this scenario we need to create an Engine
|
||||
and associate a connection with the context.
|
||||
|
||||
"""
|
||||
connectable = engine_from_config(
|
||||
config.get_section(config.config_ini_section, {}),
|
||||
prefix="sqlalchemy.",
|
||||
poolclass=pool.NullPool,
|
||||
)
|
||||
|
||||
with connectable.connect() as connection:
|
||||
context.configure(
|
||||
connection=connection, target_metadata=target_metadata
|
||||
)
|
||||
|
||||
with context.begin_transaction():
|
||||
context.run_migrations()
|
||||
|
||||
|
||||
if context.is_offline_mode():
|
||||
run_migrations_offline()
|
||||
else:
|
||||
run_migrations_online()
|
||||
28
kawai_focus/database/alembic/script.py.mako
Normal file
28
kawai_focus/database/alembic/script.py.mako
Normal file
@@ -0,0 +1,28 @@
|
||||
"""${message}
|
||||
|
||||
Revision ID: ${up_revision}
|
||||
Revises: ${down_revision | comma,n}
|
||||
Create Date: ${create_date}
|
||||
|
||||
"""
|
||||
from typing import Sequence, Union
|
||||
|
||||
from alembic import op
|
||||
import sqlalchemy as sa
|
||||
${imports if imports else ""}
|
||||
|
||||
# revision identifiers, used by Alembic.
|
||||
revision: str = ${repr(up_revision)}
|
||||
down_revision: Union[str, None] = ${repr(down_revision)}
|
||||
branch_labels: Union[str, Sequence[str], None] = ${repr(branch_labels)}
|
||||
depends_on: Union[str, Sequence[str], None] = ${repr(depends_on)}
|
||||
|
||||
|
||||
def upgrade() -> None:
|
||||
"""Upgrade schema."""
|
||||
${upgrades if upgrades else "pass"}
|
||||
|
||||
|
||||
def downgrade() -> None:
|
||||
"""Downgrade schema."""
|
||||
${downgrades if downgrades else "pass"}
|
||||
@@ -0,0 +1,42 @@
|
||||
"""migrration timer
|
||||
|
||||
Revision ID: e3e6ab4aede7
|
||||
Revises:
|
||||
Create Date: 2025-05-06 20:26:18.791745
|
||||
|
||||
"""
|
||||
|
||||
from typing import Sequence, Union
|
||||
|
||||
from alembic import op
|
||||
import sqlalchemy as sa
|
||||
|
||||
|
||||
# revision identifiers, used by Alembic.
|
||||
revision: str = "e3e6ab4aede7"
|
||||
down_revision: Union[str, None] = None
|
||||
branch_labels: Union[str, Sequence[str], None] = None
|
||||
depends_on: Union[str, Sequence[str], None] = None
|
||||
|
||||
|
||||
def upgrade() -> None:
|
||||
"""Upgrade schema."""
|
||||
# ### commands auto generated by Alembic - please adjust! ###
|
||||
op.create_table(
|
||||
"timer",
|
||||
sa.Column("название", sa.String(length=200), nullable=False),
|
||||
sa.Column("время помидора", sa.Integer(), nullable=False),
|
||||
sa.Column("время перерыва", sa.Integer(), nullable=False),
|
||||
sa.Column("время долгого перерыва", sa.Integer(), nullable=False),
|
||||
sa.Column("количество помидоров", sa.Integer(), nullable=False),
|
||||
sa.Column("id", sa.Integer(), autoincrement=True, nullable=False),
|
||||
sa.PrimaryKeyConstraint("id"),
|
||||
)
|
||||
# ### end Alembic commands ###
|
||||
|
||||
|
||||
def downgrade() -> None:
|
||||
"""Downgrade schema."""
|
||||
# ### commands auto generated by Alembic - please adjust! ###
|
||||
op.drop_table("timer")
|
||||
# ### end Alembic commands ###
|
||||
57
kawai_focus/database/cruds.py
Normal file
57
kawai_focus/database/cruds.py
Normal file
@@ -0,0 +1,57 @@
|
||||
from sqlalchemy import select, insert
|
||||
from sqlalchemy.exc import SQLAlchemyError, OperationalError, NoResultFound
|
||||
from pydantic import ValidationError
|
||||
|
||||
from kawai_focus.schemas import TimerModel
|
||||
from kawai_focus.database.session import db
|
||||
from kawai_focus.database.models import Timer
|
||||
from kawai_focus.main import Logger
|
||||
|
||||
|
||||
def get_timer(timer_id: int) -> TimerModel:
|
||||
"""Функция для получения данных таймера"""
|
||||
|
||||
try:
|
||||
with db.get_session() as session:
|
||||
timer_model = Timer
|
||||
query = select(
|
||||
timer_model.id,
|
||||
timer_model.title,
|
||||
timer_model.pomodoro_time,
|
||||
timer_model.break_time,
|
||||
timer_model.break_long_time,
|
||||
timer_model.count_pomodoro
|
||||
).where(timer_id == timer_model.id)
|
||||
result = session.execute(query)
|
||||
timer = result.mappings().first()
|
||||
|
||||
return TimerModel.model_validate(obj=timer, from_attributes=True)
|
||||
except (ConnectionError, SQLAlchemyError, TimeoutError, OperationalError, ValidationError, NoResultFound) as err:
|
||||
Logger.error(f'{err.__class__.__name__}: {err}')
|
||||
|
||||
|
||||
def new_timer(data: TimerModel) -> bool | None:
|
||||
"""Функция для создания нового таймера"""
|
||||
|
||||
try:
|
||||
with db.get_session() as session:
|
||||
timer_model = Timer
|
||||
query = insert(timer_model).values(**data.model_dump())
|
||||
session.execute(query)
|
||||
session.commit()
|
||||
except (ConnectionError, SQLAlchemyError, TimeoutError, OperationalError, ValidationError) as err:
|
||||
Logger.error(f'{err.__class__.__name__}: {err}')
|
||||
else:
|
||||
return True
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
# new_timer(data=TimerValidModel(
|
||||
# title='test_timer_2',
|
||||
# pomodoro_time=50,
|
||||
# break_long_time=25,
|
||||
# break_time=5,
|
||||
# count_pomodoro=4
|
||||
# ))
|
||||
|
||||
print(get_timer(timer_id=1))
|
||||
13
kawai_focus/database/mixins.py
Normal file
13
kawai_focus/database/mixins.py
Normal file
@@ -0,0 +1,13 @@
|
||||
from sqlalchemy.orm import Mapped, mapped_column
|
||||
from sqlalchemy import Integer
|
||||
|
||||
|
||||
class IDMixin:
|
||||
"""Базовый класс для моделей с id"""
|
||||
|
||||
id: Mapped[int] = mapped_column(
|
||||
Integer,
|
||||
name='id',
|
||||
primary_key=True,
|
||||
autoincrement=True
|
||||
)
|
||||
46
kawai_focus/database/models.py
Normal file
46
kawai_focus/database/models.py
Normal file
@@ -0,0 +1,46 @@
|
||||
from sqlalchemy.orm import DeclarativeBase, mapped_column, Mapped
|
||||
from sqlalchemy import Integer, String
|
||||
|
||||
from kawai_focus.database.mixins import IDMixin
|
||||
|
||||
|
||||
class Base(DeclarativeBase):
|
||||
"""Класс для корректной работы аннотаций"""
|
||||
|
||||
pass
|
||||
|
||||
|
||||
class Timer(IDMixin, Base):
|
||||
"""Модель таймера"""
|
||||
|
||||
__tablename__ = 'timer'
|
||||
|
||||
title: Mapped[str] = mapped_column(
|
||||
String(length=200),
|
||||
name='название',
|
||||
nullable=False
|
||||
)
|
||||
|
||||
pomodoro_time: Mapped[int] = mapped_column(
|
||||
Integer,
|
||||
name='время помидора',
|
||||
nullable=False
|
||||
)
|
||||
|
||||
break_time: Mapped[int] = mapped_column(
|
||||
Integer,
|
||||
name='время перерыва',
|
||||
nullable=False
|
||||
)
|
||||
|
||||
break_long_time: Mapped[int] = mapped_column(
|
||||
Integer,
|
||||
name='время долгого перерыва',
|
||||
nullable=False
|
||||
)
|
||||
|
||||
count_pomodoro: Mapped[int] = mapped_column(
|
||||
Integer,
|
||||
name='количество помидоров',
|
||||
nullable=False
|
||||
)
|
||||
28
kawai_focus/database/session.py
Normal file
28
kawai_focus/database/session.py
Normal file
@@ -0,0 +1,28 @@
|
||||
from sqlalchemy import create_engine
|
||||
from sqlalchemy.orm import sessionmaker, Session
|
||||
|
||||
from kawai_focus.settings import settings
|
||||
|
||||
|
||||
class SessionDB:
|
||||
"""Класс для управления подключением к базе данных."""
|
||||
|
||||
def __init__(self) -> None:
|
||||
self._engine = create_engine(
|
||||
url=settings.db_settings.get_url_db,
|
||||
echo=settings.db_settings.echo_db
|
||||
)
|
||||
self._session_factory = sessionmaker(
|
||||
bind=self._engine,
|
||||
expire_on_commit=False,
|
||||
autocommit=False
|
||||
)
|
||||
|
||||
@property
|
||||
def get_session(self) -> Session:
|
||||
"""Метод для получения сессии"""
|
||||
|
||||
return self._session_factory
|
||||
|
||||
|
||||
db = SessionDB()
|
||||
Reference in New Issue
Block a user