mirror of
https://github.com/Xtao-Labs/misskey2telegram.git
synced 2024-11-22 05:53:09 +00:00
feat: use alembic to manage sql
This commit is contained in:
parent
84e003c972
commit
d0906f355f
110
alembic.ini
Normal file
110
alembic.ini
Normal file
@ -0,0 +1,110 @@
|
||||
# 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
|
||||
# see https://alembic.sqlalchemy.org/en/latest/tutorial.html#editing-the-ini-file
|
||||
# for all available tokens
|
||||
# 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-dateutil library that can be
|
||||
# installed by adding `alembic[tz]` to the pip requirements
|
||||
# string value is passed to dateutil.tz.gettz()
|
||||
# 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 = sqlite+aiosqlite:///data/data.db
|
||||
|
||||
|
||||
[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
|
||||
|
||||
# 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
|
1
alembic/README
Normal file
1
alembic/README
Normal file
@ -0,0 +1 @@
|
||||
Generic single-database configuration.
|
115
alembic/env.py
Normal file
115
alembic/env.py
Normal file
@ -0,0 +1,115 @@
|
||||
import asyncio
|
||||
import os
|
||||
import traceback
|
||||
from pathlib import Path
|
||||
from importlib import import_module
|
||||
from logging.config import fileConfig
|
||||
from typing import Iterator
|
||||
|
||||
from alembic import context
|
||||
from sqlalchemy import engine_from_config, pool
|
||||
from sqlalchemy.engine import Connection
|
||||
from sqlalchemy.ext.asyncio import AsyncEngine
|
||||
from sqlmodel import SQLModel
|
||||
|
||||
# this is the Alembic Config object, which provides
|
||||
# access to the values within the .ini file in use.
|
||||
alembic_cfg = context.config
|
||||
|
||||
# Interpret the config file for Python logging.
|
||||
# This line sets up loggers basically.
|
||||
if alembic_cfg.config_file_name is not None:
|
||||
fileConfig(alembic_cfg.config_file_name) # skipcq: PY-A6006
|
||||
|
||||
|
||||
def scan_models() -> Iterator[str]:
|
||||
"""扫描 models/models 目录下所有 *.py 文件"""
|
||||
models_path = Path("models/models")
|
||||
for path in list(models_path.glob("*.py")):
|
||||
yield str(path.with_suffix("")).replace(os.sep, ".")
|
||||
|
||||
|
||||
def import_models():
|
||||
"""导入我们所有的 models,使 alembic 可以自动对比 db scheme 创建 migration revision"""
|
||||
for pkg in scan_models():
|
||||
print("Importing models from %s" % pkg)
|
||||
try:
|
||||
import_module(pkg) # 导入 models
|
||||
except Exception: # pylint: disable=W0703
|
||||
traceback.print_exc()
|
||||
print("Error importing models from %s" % pkg)
|
||||
|
||||
|
||||
# register our models for alembic to auto-generate migrations
|
||||
import_models()
|
||||
|
||||
target_metadata = SQLModel.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.
|
||||
|
||||
# here we allow ourselves to pass interpolation vars to alembic.ini
|
||||
# from the application config module
|
||||
|
||||
sqlalchemy_url = alembic_cfg.get_main_option("sqlalchemy.url")
|
||||
|
||||
|
||||
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 = alembic_cfg.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_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 = AsyncEngine(
|
||||
engine_from_config(
|
||||
alembic_cfg.get_section(alembic_cfg.config_ini_section),
|
||||
prefix="sqlalchemy.",
|
||||
poolclass=pool.NullPool,
|
||||
future=True,
|
||||
)
|
||||
)
|
||||
|
||||
async with connectable.connect() as connection:
|
||||
await connection.run_sync(do_run_migrations)
|
||||
|
||||
await connectable.dispose()
|
||||
|
||||
|
||||
if context.is_offline_mode():
|
||||
run_migrations_offline()
|
||||
else:
|
||||
asyncio.run(run_migrations_online())
|
25
alembic/script.py.mako
Normal file
25
alembic/script.py.mako
Normal file
@ -0,0 +1,25 @@
|
||||
"""${message}
|
||||
|
||||
Revision ID: ${up_revision}
|
||||
Revises: ${down_revision | comma,n}
|
||||
Create Date: ${create_date}
|
||||
|
||||
"""
|
||||
from alembic import op
|
||||
import sqlalchemy as sa
|
||||
import sqlmodel
|
||||
${imports if imports else ""}
|
||||
|
||||
# revision identifiers, used by Alembic.
|
||||
revision = ${repr(up_revision)}
|
||||
down_revision = ${repr(down_revision)}
|
||||
branch_labels = ${repr(branch_labels)}
|
||||
depends_on = ${repr(depends_on)}
|
||||
|
||||
|
||||
def upgrade() -> None:
|
||||
${upgrades if upgrades else "pass"}
|
||||
|
||||
|
||||
def downgrade() -> None:
|
||||
${downgrades if downgrades else "pass"}
|
46
alembic/versions/a89b6e618441_user.py
Normal file
46
alembic/versions/a89b6e618441_user.py
Normal file
@ -0,0 +1,46 @@
|
||||
"""user
|
||||
|
||||
Revision ID: a89b6e618441
|
||||
Revises:
|
||||
Create Date: 2023-07-29 13:05:51.912893
|
||||
|
||||
"""
|
||||
from alembic import op
|
||||
import sqlalchemy as sa
|
||||
import sqlmodel
|
||||
|
||||
# revision identifiers, used by Alembic.
|
||||
revision = "a89b6e618441"
|
||||
down_revision = None
|
||||
branch_labels = None
|
||||
depends_on = None
|
||||
|
||||
|
||||
def upgrade() -> None:
|
||||
# ### commands auto generated by Alembic - please adjust! ###
|
||||
op.create_table(
|
||||
"user",
|
||||
sa.Column("user_id", sa.BigInteger(), nullable=False),
|
||||
sa.Column(
|
||||
"status",
|
||||
sa.Enum("STATUS_SUCCESS", "INVALID_TOKEN", name="tokenstatusenum"),
|
||||
nullable=True,
|
||||
),
|
||||
sa.Column("chat_id", sa.BigInteger(), nullable=False),
|
||||
sa.Column("push_chat_id", sa.BigInteger(), nullable=True),
|
||||
sa.Column("host", sqlmodel.AutoString(), nullable=False),
|
||||
sa.Column("token", sqlmodel.AutoString(), nullable=False),
|
||||
sa.Column("timeline_topic", sa.Integer(), nullable=False),
|
||||
sa.Column("notice_topic", sa.Integer(), nullable=False),
|
||||
sa.Column("instance_user_id", sqlmodel.AutoString(), nullable=False),
|
||||
sa.PrimaryKeyConstraint("user_id", "chat_id"),
|
||||
mysql_charset="utf8mb4",
|
||||
mysql_collate="utf8mb4_general_ci",
|
||||
)
|
||||
# ### end Alembic commands ###
|
||||
|
||||
|
||||
def downgrade() -> None:
|
||||
# ### commands auto generated by Alembic - please adjust! ###
|
||||
op.drop_table("user")
|
||||
# ### end Alembic commands ###
|
@ -91,7 +91,9 @@ def get_content(host: str, note: Note) -> str:
|
||||
action = "转推"
|
||||
if content:
|
||||
action = "引用"
|
||||
content = f"> {note.renote.content or ''}\n\n=====================\n\n{content}"
|
||||
content = (
|
||||
f"> {note.renote.content or ''}\n\n=====================\n\n{content}"
|
||||
)
|
||||
else:
|
||||
content = note.renote.content or ""
|
||||
origin = (
|
||||
@ -389,6 +391,8 @@ async def send_update(
|
||||
elif file_type.startswith("audio"):
|
||||
return [await send_audio(host, cid, url, note, topic_id, show_second)]
|
||||
else:
|
||||
return [await send_document(host, cid, url, note, topic_id, show_second)]
|
||||
return [
|
||||
await send_document(host, cid, url, note, topic_id, show_second)
|
||||
]
|
||||
case _:
|
||||
return await send_group(host, cid, files, note, topic_id, show_second)
|
||||
|
@ -1,5 +1,5 @@
|
||||
import enum
|
||||
|
||||
import sqlalchemy as sa
|
||||
from sqlmodel import SQLModel, Field, Enum, Column
|
||||
|
||||
|
||||
@ -11,12 +11,12 @@ class TokenStatusEnum(int, enum.Enum):
|
||||
class User(SQLModel, table=True):
|
||||
__table_args__ = dict(mysql_charset="utf8mb4", mysql_collate="utf8mb4_general_ci")
|
||||
|
||||
user_id: int = Field(primary_key=True)
|
||||
user_id: int = Field(sa_column=Column(sa.BigInteger, primary_key=True))
|
||||
host: str = Field(default="")
|
||||
token: str = Field(default="")
|
||||
status: TokenStatusEnum = Field(sa_column=Column(Enum(TokenStatusEnum)))
|
||||
chat_id: int = Field(default=0, primary_key=True)
|
||||
chat_id: int = Field(default=0, sa_column=Column(sa.BigInteger, primary_key=True))
|
||||
timeline_topic: int = Field(default=0)
|
||||
notice_topic: int = Field(default=0)
|
||||
instance_user_id: str = Field(default="")
|
||||
push_chat_id: int = Field(default=0)
|
||||
push_chat_id: int = Field(default=0, sa_column=Column(sa.BigInteger))
|
||||
|
@ -52,11 +52,7 @@ class UserAction:
|
||||
async def get_all_have_token_users() -> list[User]:
|
||||
async with sqlite.session() as session:
|
||||
session = cast(AsyncSession, session)
|
||||
statement = (
|
||||
select(User)
|
||||
.where(User.token != "")
|
||||
.where(User.host != "")
|
||||
)
|
||||
statement = select(User).where(User.token != "").where(User.host != "")
|
||||
results = await session.exec(statement)
|
||||
return [
|
||||
user[0]
|
||||
|
@ -9,3 +9,4 @@ PyYAML==6.0.1
|
||||
aiofiles==23.1.0
|
||||
pillow==10.0.0
|
||||
cashews==6.2.0
|
||||
alembic==1.11.1
|
||||
|
Loading…
Reference in New Issue
Block a user