From dce3aede0b3decc016d3cd2433e56e75b08ba61c Mon Sep 17 00:00:00 2001 From: LevaniVashadze Date: Wed, 27 Dec 2023 20:16:46 +0400 Subject: [PATCH] fix IDs --- alembic.ini | 114 +++++++++++++++++++ alembic/README | 1 + alembic/env.py | 98 ++++++++++++++++ alembic/script.py.mako | 26 +++++ alembic/versions/e24d47b712a1_first.py | 149 +++++++++++++++++++++++++ requirements.txt | 6 +- setup.sql | 2 +- utils/bot.py | 6 +- utils/db_models.py | 126 +++++++++++++++++++++ utils/models.py | 16 +-- 10 files changed, 532 insertions(+), 12 deletions(-) create mode 100644 alembic.ini create mode 100644 alembic/README create mode 100644 alembic/env.py create mode 100644 alembic/script.py.mako create mode 100644 alembic/versions/e24d47b712a1_first.py create mode 100644 utils/db_models.py diff --git a/alembic.ini b/alembic.ini new file mode 100644 index 0000000..3af24e9 --- /dev/null +++ b/alembic.ini @@ -0,0 +1,114 @@ +# A generic, single database configuration. + +[alembic] +# path to migration scripts +script_location = alembic + +# template used to generate migration file names; The default value is %%(rev)s_%%(slug)s +# Uncomment the line below if you want the files to be prepended with date and time +# file_template = %%(year)d_%%(month).2d_%%(day).2d_%%(hour).2d%%(minute).2d-%%(rev)s_%%(slug)s + +# sys.path path, will be prepended to sys.path if present. +# defaults to the current working directory. +prepend_sys_path = . + +# timezone to use when rendering the date within the migration file +# as well as the filename. +# If specified, requires the python>=3.9 or backports.zoneinfo library. +# Any required deps can installed by adding `alembic[tz]` to the pip requirements +# string value is passed to ZoneInfo() +# leave blank for localtime +# timezone = + +# max length of characters to apply to the +# "slug" field +# truncate_slug_length = 40 + +# set to 'true' to run the environment during +# the 'revision' command, regardless of autogenerate +# revision_environment = false + +# set to 'true' to allow .pyc and .pyo files without +# a source .py file to be detected as revisions in the +# versions/ directory +# sourceless = false + +# version location specification; This defaults +# to alembic/versions. When using multiple version +# directories, initial revisions must be specified with --version-path. +# The path separator used here should be the separator specified by "version_path_separator" below. +# version_locations = %(here)s/bar:%(here)s/bat:alembic/versions + +# version path separator; As mentioned above, this is the character used to split +# version_locations. The default within new alembic.ini files is "os", which uses os.pathsep. +# If this key is omitted entirely, it falls back to the legacy behavior of splitting on spaces and/or commas. +# Valid values for version_path_separator are: +# +# version_path_separator = : +# version_path_separator = ; +# version_path_separator = space +version_path_separator = os # Use os.pathsep. Default configuration used for new projects. + +# set to 'true' to search source files recursively +# in each "version_locations" directory +# new in Alembic version 1.10 +# recursive_version_locations = false + +# the output encoding used when revision files +# are written from script.py.mako +# output_encoding = utf-8 + +sqlalchemy.url = driver://user:pass@localhost/dbname + + +[post_write_hooks] +# post_write_hooks defines scripts or Python functions that are run +# on newly generated revision scripts. See the documentation for further +# detail and examples + +# format using "black" - use the console_scripts runner, against the "black" entrypoint +# hooks = black +# black.type = console_scripts +# black.entrypoint = black +# black.options = -l 79 REVISION_SCRIPT_FILENAME + +# lint with attempts to fix using "ruff" - use the exec runner, execute a binary +# hooks = ruff +# ruff.type = exec +# ruff.executable = %(here)s/.venv/bin/ruff +# ruff.options = --fix REVISION_SCRIPT_FILENAME + +# Logging configuration +[loggers] +keys = root,sqlalchemy,alembic + +[handlers] +keys = console + +[formatters] +keys = generic + +[logger_root] +level = WARN +handlers = console +qualname = + +[logger_sqlalchemy] +level = WARN +handlers = +qualname = sqlalchemy.engine + +[logger_alembic] +level = INFO +handlers = +qualname = alembic + +[handler_console] +class = StreamHandler +args = (sys.stderr,) +level = NOTSET +formatter = generic + +[formatter_generic] +format = %(levelname)-5.5s [%(name)s] %(message)s +datefmt = %H:%M:%S diff --git a/alembic/README b/alembic/README new file mode 100644 index 0000000..e0d0858 --- /dev/null +++ b/alembic/README @@ -0,0 +1 @@ +Generic single-database configuration with an async dbapi. \ No newline at end of file diff --git a/alembic/env.py b/alembic/env.py new file mode 100644 index 0000000..ece9da3 --- /dev/null +++ b/alembic/env.py @@ -0,0 +1,98 @@ +import asyncio +import os +from logging.config import fileConfig +from dotenv import load_dotenv + +from sqlalchemy import pool +from sqlalchemy.engine import Connection +from sqlalchemy.ext.asyncio import async_engine_from_config + +from alembic import context + +# this is the Alembic Config object, which provides +# access to the values within the .ini file in use. +config = context.config + +# 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 +from utils.db_models import Base + +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. +load_dotenv("secrets.env") +config.set_main_option("sqlalchemy.url", os.environ["POSTGRES_CONNECTION_STRING"]) + + +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 do_run_migrations(connection: Connection) -> None: + context.configure(connection=connection, target_metadata=target_metadata) + + with context.begin_transaction(): + context.run_migrations() + + +async def run_async_migrations() -> None: + """In this scenario we need to create an Engine + and associate a connection with the context. + + """ + + connectable = async_engine_from_config( + config.get_section( + config.config_ini_section, + {}, + ), + prefix="sqlalchemy.", + poolclass=pool.NullPool, + ) + + async with connectable.connect() as connection: + await connection.run_sync(do_run_migrations) + + await connectable.dispose() + + +def run_migrations_online() -> None: + """Run migrations in 'online' mode.""" + + asyncio.run(run_async_migrations()) + + +if context.is_offline_mode(): + run_migrations_offline() +else: + run_migrations_online() diff --git a/alembic/script.py.mako b/alembic/script.py.mako new file mode 100644 index 0000000..fbc4b07 --- /dev/null +++ b/alembic/script.py.mako @@ -0,0 +1,26 @@ +"""${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: + ${upgrades if upgrades else "pass"} + + +def downgrade() -> None: + ${downgrades if downgrades else "pass"} diff --git a/alembic/versions/e24d47b712a1_first.py b/alembic/versions/e24d47b712a1_first.py new file mode 100644 index 0000000..224861b --- /dev/null +++ b/alembic/versions/e24d47b712a1_first.py @@ -0,0 +1,149 @@ +"""First + +Revision ID: e24d47b712a1 +Revises: +Create Date: 2023-12-27 20:06:25.739954 + +""" +from typing import Sequence, Union + +from alembic import op +import sqlalchemy as sa + + +# revision identifiers, used by Alembic. +revision: str = 'e24d47b712a1' +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: + # ### commands auto generated by Alembic - please adjust! ### + op.create_table('birthday', + sa.Column('id', sa.Integer(), nullable=False), + sa.Column('user_id', sa.BigInteger(), nullable=True), + sa.Column('birthday', sa.Text(), nullable=True), + sa.Column('birthday_last_changed', sa.BigInteger(), nullable=True), + sa.PrimaryKeyConstraint('id') + ) + op.create_table('blacklist', + sa.Column('id', sa.Integer(), nullable=False), + sa.Column('user_id', sa.BigInteger(), nullable=True), + sa.Column('reason', sa.Text(), nullable=True), + sa.Column('bot', sa.Boolean(), nullable=True), + sa.Column('tickets', sa.Boolean(), nullable=True), + sa.Column('tags', sa.Boolean(), nullable=True), + sa.Column('expires', sa.BigInteger(), nullable=True), + sa.PrimaryKeyConstraint('id') + ) + op.create_table('commands', + sa.Column('id', sa.Integer(), nullable=False), + sa.Column('guild_id', sa.BigInteger(), nullable=True), + sa.Column('command', sa.Text(), nullable=True), + sa.Column('command_used', sa.Integer(), nullable=True), + sa.PrimaryKeyConstraint('id') + ) + op.create_table('config', + sa.Column('guild_id', sa.BigInteger(), nullable=False), + sa.Column('xp_boost', sa.Integer(), nullable=True), + sa.Column('xp_boost_expiry', sa.BigInteger(), nullable=True), + sa.Column('xp_boost_enabled', sa.Boolean(), nullable=True), + sa.PrimaryKeyConstraint('guild_id') + ) + op.create_table('flag_quiz', + sa.Column('id', sa.BigInteger(), nullable=False), + sa.Column('user_id', sa.BigInteger(), nullable=True), + sa.Column('tries', sa.Integer(), nullable=True), + sa.Column('correct', sa.Integer(), nullable=True), + sa.Column('completed', sa.Integer(), nullable=True), + sa.Column('guild_id', sa.BigInteger(), nullable=True), + sa.PrimaryKeyConstraint('id') + ) + op.create_table('levels', + sa.Column('id', sa.Integer(), nullable=False), + sa.Column('guild_id', sa.BigInteger(), nullable=True), + sa.Column('user_id', sa.BigInteger(), nullable=True), + sa.Column('level', sa.Integer(), nullable=True), + sa.Column('xp', sa.Integer(), nullable=True), + sa.PrimaryKeyConstraint('id') + ) + op.create_table('reaction_roles', + sa.Column('id', sa.Integer(), nullable=False), + sa.Column('message_id', sa.BigInteger(), nullable=True), + sa.Column('role_id', sa.BigInteger(), nullable=True), + sa.Column('emoji', sa.Text(), nullable=True), + sa.Column('roles_given', sa.Integer(), nullable=True), + sa.PrimaryKeyConstraint('id') + ) + op.create_table('role_rewards', + sa.Column('id', sa.Integer(), nullable=False), + sa.Column('guild_id', sa.BigInteger(), nullable=True), + sa.Column('role_id', sa.BigInteger(), nullable=True), + sa.Column('required_lvl', sa.Integer(), nullable=True), + sa.PrimaryKeyConstraint('id') + ) + op.create_table('tag_relations', + sa.Column('id', sa.Integer(), nullable=False), + sa.Column('tag_id', sa.Text(), nullable=True), + sa.Column('alias', sa.Text(), nullable=True), + sa.PrimaryKeyConstraint('id') + ) + op.create_table('tags', + sa.Column('tag_id', sa.Text(), nullable=False), + sa.Column('content', sa.Text(), nullable=True), + sa.Column('owner', sa.BigInteger(), nullable=True), + sa.Column('created_at', sa.BigInteger(), nullable=True), + sa.Column('views', sa.Integer(), nullable=True), + sa.PrimaryKeyConstraint('tag_id') + ) + op.create_table('timezone', + sa.Column('id', sa.Integer(), nullable=False), + sa.Column('user_id', sa.BigInteger(), nullable=True), + sa.Column('timezone', sa.Text(), nullable=True), + sa.Column('timezone_last_changed', sa.BigInteger(), nullable=True), + sa.PrimaryKeyConstraint('id') + ) + op.create_table('total_commands', + sa.Column('id', sa.Integer(), nullable=False), + sa.Column('guild_id', sa.BigInteger(), nullable=True), + sa.Column('total_commands_used', sa.Integer(), nullable=True), + sa.PrimaryKeyConstraint('id'), + sa.UniqueConstraint('guild_id') + ) + op.create_table('trivia', + sa.Column('id', sa.BigInteger(), nullable=False), + sa.Column('correct', sa.Integer(), nullable=True), + sa.Column('incorrect', sa.Integer(), nullable=True), + sa.Column('streak', sa.Integer(), nullable=True), + sa.Column('longest_streak', sa.Integer(), nullable=True), + sa.PrimaryKeyConstraint('id') + ) + op.create_table('warnings', + sa.Column('warning_id', sa.Integer(), nullable=False), + sa.Column('user_id', sa.BigInteger(), nullable=True), + sa.Column('moderator_id', sa.BigInteger(), nullable=True), + sa.Column('reason', sa.Text(), nullable=True), + sa.Column('guild_id', sa.BigInteger(), nullable=True), + sa.PrimaryKeyConstraint('warning_id') + ) + # ### end Alembic commands ### + + +def downgrade() -> None: + # ### commands auto generated by Alembic - please adjust! ### + op.drop_table('warnings') + op.drop_table('trivia') + op.drop_table('total_commands') + op.drop_table('timezone') + op.drop_table('tags') + op.drop_table('tag_relations') + op.drop_table('role_rewards') + op.drop_table('reaction_roles') + op.drop_table('levels') + op.drop_table('flag_quiz') + op.drop_table('config') + op.drop_table('commands') + op.drop_table('blacklist') + op.drop_table('birthday') + # ### end Alembic commands ### diff --git a/requirements.txt b/requirements.txt index d98a1a2..7aa827a 100644 --- a/requirements.txt +++ b/requirements.txt @@ -1,4 +1,4 @@ -aiohttp~=3.8.3 +aiohttp~=3.9.1 asyncpg==0.29.0 akinator~=1.0.3 disnake==2.9.1 @@ -13,4 +13,6 @@ cachetools==5.3.0 python-dateutil~=2.8.2 pytz==2022.7.1 discord_together==1.2.6 -better_profanity==0.7.0 \ No newline at end of file +better_profanity==0.7.0 +sqlalchemy[asyncio]==2.0.23 +alembic==1.13.1 \ No newline at end of file diff --git a/setup.sql b/setup.sql index fd9232b..2fbf020 100644 --- a/setup.sql +++ b/setup.sql @@ -9,7 +9,7 @@ CREATE TABLE IF NOT EXISTS tags CREATE TABLE IF NOT EXISTS tag_relations ( - tag_id TEXT PRIMARY KEY, + tag_id TEXT, alias TEXT ); diff --git a/utils/bot.py b/utils/bot.py index 55ad6b2..7a1b80a 100644 --- a/utils/bot.py +++ b/utils/bot.py @@ -1,12 +1,12 @@ import asyncio from datetime import datetime -from os import listdir +from sqlalchemy.ext.asyncio import create_async_engine +from db_models import Base import asyncpg import disnake from disnake import ApplicationCommandInteraction, OptionType from disnake.ext import commands -from disnake.ext.commands.interaction_bot_base import CFT from utils.CONSTANTS import __VERSION__ from utils.DBhandlers import BlacklistHandler @@ -128,6 +128,8 @@ async def load_db(self): pass async def start(self, *args, **kwargs): + + # engine = create_async_engine(self.config.Database.connection_string) self.db = await asyncpg.create_pool(self.config.Database.connection_string) await self.db.execute(SETUP_SQL) # run the db migrations in /migrations diff --git a/utils/db_models.py b/utils/db_models.py new file mode 100644 index 0000000..a0f77a7 --- /dev/null +++ b/utils/db_models.py @@ -0,0 +1,126 @@ +from sqlalchemy import Column, Integer, BigInteger, Text, Boolean, UniqueConstraint +from sqlalchemy.orm import declarative_base + +Base = declarative_base() + + +class Tags(Base): + __tablename__ = "tags" + tag_id = Column(Text, primary_key=True) + content = Column(Text) + owner = Column(BigInteger) + created_at = Column(BigInteger) + views = Column(Integer) + + +class TagRelations(Base): + __tablename__ = "tag_relations" + id = Column(Integer, primary_key=True) + tag_id = Column(Text) + alias = Column(Text) + + +class Blacklist(Base): + __tablename__ = "blacklist" + id = Column(Integer, primary_key=True) + user_id = Column(BigInteger) + reason = Column(Text) + bot = Column(Boolean) + tickets = Column(Boolean) + tags = Column(Boolean) + expires = Column(BigInteger) + + +class FlagQuiz(Base): + __tablename__ = "flag_quiz" + id = Column(BigInteger, primary_key=True) + user_id = Column(BigInteger) + tries = Column(Integer) + correct = Column(Integer) + completed = Column(Integer) + guild_id = Column(BigInteger) + + +class Trivia(Base): + __tablename__ = "trivia" + id = Column(BigInteger, primary_key=True) + user_id = Column(BigInteger) + correct = Column(Integer) + incorrect = Column(Integer) + streak = Column(Integer) + longest_streak = Column(Integer) + + +class ReactionRoles(Base): + __tablename__ = "reaction_roles" + id = Column(Integer, primary_key=True) + message_id = Column(BigInteger) + role_id = Column(BigInteger) + emoji = Column(Text) + roles_given = Column(Integer, default=0) + + +class Warnings(Base): + __tablename__ = "warnings" + warning_id = Column(Integer, primary_key=True) + user_id = Column(BigInteger) + moderator_id = Column(BigInteger) + reason = Column(Text) + guild_id = Column(BigInteger) + + +class Levels(Base): + __tablename__ = "levels" + id = Column(Integer, primary_key=True) + guild_id = Column(BigInteger) + user_id = Column(BigInteger) + level = Column(Integer, default=0) + xp = Column(Integer, default=0) + + +class RoleRewards(Base): + __tablename__ = "role_rewards" + id = Column(Integer, primary_key=True) + guild_id = Column(BigInteger) + role_id = Column(BigInteger) + required_lvl = Column(Integer, default=0) + + +class Birthday(Base): + __tablename__ = "birthday" + id = Column(Integer, primary_key=True) + user_id = Column(BigInteger) + birthday = Column(Text, default=None) + birthday_last_changed = Column(BigInteger, default=None) + + +class Timezone(Base): + __tablename__ = "timezone" + id = Column(Integer, primary_key=True) + user_id = Column(BigInteger) + timezone = Column(Text, default=None) + timezone_last_changed = Column(BigInteger, default=None) + + +class Config(Base): + __tablename__ = "config" + guild_id = Column(BigInteger, primary_key=True) + xp_boost = Column(Integer, default=1) + xp_boost_expiry = Column(BigInteger, default=0) + xp_boost_enabled = Column(Boolean, default=True) + + +class Commands(Base): + __tablename__ = "commands" + id = Column(Integer, primary_key=True) + guild_id = Column(BigInteger) + command = Column(Text) + command_used = Column(Integer, default=0) + UniqueConstraint("guild_id", "command", name="guild_command") + + +class TotalCommands(Base): + __tablename__ = "total_commands" + id = Column(Integer, primary_key=True) + guild_id = Column(BigInteger, unique=True) + total_commands_used = Column(Integer, default=0) diff --git a/utils/models.py b/utils/models.py index 172032c..3234bd8 100644 --- a/utils/models.py +++ b/utils/models.py @@ -36,19 +36,15 @@ def get_exp(self, level: int): @property def total_exp(self): return sum( - [ - exp - for exp in [ - self.get_exp(lvl) for lvl in range(1, self.lvl + 1) - ] - ][::-1] + [exp for exp in [self.get_exp(lvl) for lvl in range(1, self.lvl + 1)]][::-1] + [self.xp] ) @dataclass class TriviaUser: - id: int # user id + id: int + user_id: int correct: int = 0 incorrect: int = 0 streak: int = 0 @@ -91,6 +87,7 @@ def get_expiry(self): @dataclass class Tag: + tag_id: int name: str content: str owner: int @@ -100,12 +97,14 @@ class Tag: @dataclass class Alias: + id: int tag_id: str alias: str @dataclass class FlagQuizUser: + id: int user_id: int tries: int correct: int @@ -115,6 +114,7 @@ class FlagQuizUser: @dataclass class ReactionRole: + id: int message_id: int role_id: int emoji: str @@ -132,6 +132,7 @@ class WarningModel: @dataclass class BirthdayModel: + id: int user_id: int birthday: str birthday_last_changed: int @@ -139,6 +140,7 @@ class BirthdayModel: @dataclass class TimezoneModel: + id: int user_id: int timezone: str timezone_last_changed: int