Merge pull request #1411 from rommapp/fix/postgresql-migrations

fix: Make migrations compatible with PostgreSQL
This commit is contained in:
Michael Manganiello
2024-12-31 10:37:25 -03:00
committed by GitHub
13 changed files with 196 additions and 59 deletions

View File

@@ -18,6 +18,8 @@ depends_on = None
def upgrade() -> None:
connection = op.get_bind()
try:
with op.batch_alter_table("platforms", schema=None) as batch_op:
batch_op.alter_column(
@@ -34,7 +36,12 @@ def upgrade() -> None:
)
# Move primary key to slug
batch_op.drop_constraint(constraint_name="PRIMARY", type_="primary")
pk_constraint_name = connection.dialect.get_pk_constraint(
connection, table_name="platforms"
)["name"]
batch_op.drop_constraint(
constraint_name=pk_constraint_name, type_="primary"
)
batch_op.create_primary_key(constraint_name=None, columns=["slug"])
except ValueError as e:
print(f"Cannot drop primary key on platforms table: {e}")
@@ -98,6 +105,8 @@ def upgrade() -> None:
def downgrade() -> None:
connection = op.get_bind()
with op.batch_alter_table("roms", schema=None) as batch_op:
batch_op.alter_column(
"igdb_id",
@@ -155,12 +164,18 @@ def downgrade() -> None:
try:
with op.batch_alter_table("platforms", schema=None) as batch_op:
# Move primary key back to fs_slug
pk_constraint_name = connection.dialect.get_pk_constraint(
connection, table_name="platforms"
)["name"]
batch_op.drop_constraint(
constraint_name=pk_constraint_name, type_="primary"
)
batch_op.alter_column(
"slug", existing_type=sa.VARCHAR(length=50), nullable=True
)
# Move primary key back to fs_slug
batch_op.drop_constraint(constraint_name="PRIMARY", type_="primary")
batch_op.create_primary_key(constraint_name=None, columns=["fs_slug"])
print("Moved primary key back to fs_slug column on platforms table")
except ValueError as e:

View File

@@ -17,7 +17,6 @@ depends_on = None
def upgrade() -> None:
# ### commands auto generated by Alembic - please adjust! ###
with op.batch_alter_table("platforms", schema=None) as batch_op:
batch_op.execute("UPDATE platforms SET igdb_id = NULL WHERE igdb_id = ''")
batch_op.execute("UPDATE platforms SET sgdb_id = NULL WHERE sgdb_id = ''")
@@ -27,12 +26,14 @@ def upgrade() -> None:
existing_type=sa.VARCHAR(length=10),
type_=sa.Integer(),
existing_nullable=True,
postgresql_using="igdb_id::integer",
)
batch_op.alter_column(
"sgdb_id",
existing_type=sa.VARCHAR(length=10),
type_=sa.Integer(),
existing_nullable=True,
postgresql_using="sgdb_id::integer",
)
with op.batch_alter_table("roms", schema=None) as batch_op:
@@ -44,16 +45,16 @@ def upgrade() -> None:
existing_type=sa.VARCHAR(length=10),
type_=sa.Integer(),
existing_nullable=True,
postgresql_using="igdb_id::integer",
)
batch_op.alter_column(
"sgdb_id",
existing_type=sa.VARCHAR(length=10),
type_=sa.Integer(),
existing_nullable=True,
postgresql_using="sgdb_id::integer",
)
# ### end Alembic commands ###
def downgrade() -> None:
# ### commands auto generated by Alembic - please adjust! ###

View File

@@ -32,13 +32,15 @@ def upgrade() -> None:
def downgrade() -> None:
# ### commands auto generated by Alembic - please adjust! ###
connection = op.get_bind()
with op.batch_alter_table("roms", schema=None) as batch_op:
batch_op.add_column(sa.Column("region", sa.VARCHAR(length=20), nullable=True))
with op.batch_alter_table("roms", schema=None) as batch_op:
batch_op.execute("UPDATE roms SET region = JSON_EXTRACT(regions, '$[0]')")
if connection.engine.name == "postgresql":
batch_op.execute("UPDATE roms SET region = regions->>0")
else:
batch_op.execute("UPDATE roms SET region = JSON_EXTRACT(regions, '$[0]')")
batch_op.drop_column("languages")
batch_op.drop_column("regions")
# ### end Alembic commands ###

View File

@@ -32,8 +32,10 @@ SIZE_UNIT_TO_BYTES = {
def migrate_to_supported_engine() -> None:
if ROMM_DB_DRIVER not in ("mariadb", "mysql"):
raise Exception("Version 3.0 requires MariaDB or MySQL as database driver!")
if ROMM_DB_DRIVER not in ("mariadb", "mysql", "postgresql"):
raise Exception(
"Version 3.0 requires MariaDB, MySQL, or PostgreSQL as database driver!"
)
# Skip if sqlite database is not mounted
if not os.path.exists(f"{SQLITE_DB_BASE_PATH}/romm.db"):
@@ -81,6 +83,8 @@ def migrate_to_supported_engine() -> None:
def upgrade() -> None:
migrate_to_supported_engine()
connection = op.get_bind()
op.create_table(
"saves",
sa.Column("emulator", sa.String(length=50), nullable=True),
@@ -153,13 +157,19 @@ def upgrade() -> None:
# Drop the primary key (slug)
with op.batch_alter_table("platforms", schema=None) as batch_op:
batch_op.drop_constraint(constraint_name="PRIMARY", type_="primary")
pk_constraint_name = connection.dialect.get_pk_constraint(
connection, table_name="platforms"
)["name"]
batch_op.drop_constraint(constraint_name=pk_constraint_name, type_="primary")
batch_op.drop_column("n_roms")
# Switch to new id column as platform primary key
op.execute(
"ALTER TABLE platforms ADD COLUMN id INTEGER(11) NOT NULL AUTO_INCREMENT PRIMARY KEY"
)
if connection.engine.name == "postgresql":
op.execute("ALTER TABLE platforms ADD COLUMN id SERIAL PRIMARY KEY")
else:
op.execute(
"ALTER TABLE platforms ADD COLUMN id INTEGER(11) NOT NULL AUTO_INCREMENT PRIMARY KEY"
)
# Add new columns to roms table
with op.batch_alter_table("roms", schema=None) as batch_op:
@@ -187,9 +197,19 @@ def upgrade() -> None:
batch_op.execute(
"update roms set file_name_no_ext = regexp_replace(file_name, '\\.[a-z]{2,}$', '')"
)
batch_op.execute(
"update roms inner join platforms on roms.platform_slug = platforms.slug set roms.platform_id = platforms.id"
)
if connection.engine.name == "postgresql":
batch_op.execute(
"""
UPDATE roms
SET platform_id = platforms.id
FROM platforms
WHERE roms.platform_slug = platforms.slug
"""
)
else:
batch_op.execute(
"update roms inner join platforms on roms.platform_slug = platforms.slug set roms.platform_id = platforms.id"
)
# Process filesize data and prepare for bulk update
connection = op.get_bind()
@@ -224,6 +244,8 @@ def upgrade() -> None:
def downgrade() -> None:
connection = op.get_bind()
with op.batch_alter_table("roms", schema=None) as batch_op:
batch_op.add_column(
sa.Column("platform_slug", sa.VARCHAR(length=50), nullable=False)
@@ -242,9 +264,19 @@ def downgrade() -> None:
batch_op.drop_constraint("fk_platform_id_roms", type_="foreignkey")
with op.batch_alter_table("roms", schema=None) as batch_op:
batch_op.execute(
"update roms inner join platforms on roms.platform_id = platforms.id set roms.platform_slug = platforms.slug"
)
if connection.engine.name == "postgresql":
batch_op.execute(
"""
UPDATE roms
SET platform_slug = platforms.slug
FROM platforms
WHERE roms.platform_id = platforms.id
"""
)
else:
batch_op.execute(
"update roms inner join platforms on roms.platform_id = platforms.id set roms.platform_slug = platforms.slug"
)
batch_op.execute(
"update roms set url_cover = 'https://images.igdb.com/igdb/image/upload/t_cover_big/nocover.png' where url_cover = ''"
)

View File

@@ -17,6 +17,9 @@ depends_on = None
def upgrade() -> None:
connection = op.get_bind()
false_value = "FALSE" if connection.engine.name == "postgresql" else "0"
with op.batch_alter_table("platforms", schema=None) as batch_op:
batch_op.execute("UPDATE platforms SET name = '' WHERE name IS NULL")
batch_op.alter_column(
@@ -25,20 +28,22 @@ def upgrade() -> None:
with op.batch_alter_table("rom_user", schema=None) as batch_op:
batch_op.execute(
"UPDATE rom_user SET note_is_public = 0 WHERE note_is_public IS NULL"
f"UPDATE rom_user SET note_is_public = {false_value} WHERE note_is_public IS NULL" # nosec B608
)
batch_op.alter_column(
"note_is_public", existing_type=sa.Boolean(), nullable=False
)
batch_op.execute(
"UPDATE rom_user SET is_main_sibling = 0 WHERE is_main_sibling IS NULL"
f"UPDATE rom_user SET is_main_sibling = {false_value} WHERE is_main_sibling IS NULL" # nosec B608
)
batch_op.alter_column(
"is_main_sibling", existing_type=sa.Boolean(), nullable=False
)
with op.batch_alter_table("roms", schema=None) as batch_op:
batch_op.execute("UPDATE roms SET multi = 0 WHERE multi IS NULL")
batch_op.execute(
f"UPDATE roms SET multi = {false_value} WHERE multi IS NULL" # nosec B608
)
batch_op.alter_column("multi", existing_type=sa.Boolean(), nullable=False)
with op.batch_alter_table("users", schema=None) as batch_op:
@@ -46,7 +51,9 @@ def upgrade() -> None:
batch_op.alter_column(
"username", existing_type=sa.String(length=255), nullable=False
)
batch_op.execute("UPDATE users SET enabled = 0 WHERE enabled IS NULL")
batch_op.execute(
f"UPDATE users SET enabled = {false_value} WHERE enabled IS NULL" # nosec B608
)
batch_op.alter_column("enabled", existing_type=sa.Boolean(), nullable=False)

View File

@@ -22,10 +22,13 @@ def upgrade() -> None:
batch_op.create_index("idx_roms_moby_id", ["moby_id"])
connection = op.get_bind()
null_safe_equal_operator = (
"IS NOT DISTINCT FROM" if connection.engine.name == "postgresql" else "<=>"
)
connection.execute(
sa.text(
"""
f"""
CREATE VIEW sibling_roms AS
SELECT
r1.id AS rom_id,
@@ -33,21 +36,21 @@ def upgrade() -> None:
r1.platform_id AS platform_id,
NOW() AS created_at,
NOW() AS updated_at,
CASE WHEN r1.igdb_id <=> r2.igdb_id THEN r1.igdb_id END AS igdb_id,
CASE WHEN r1.moby_id <=> r2.moby_id THEN r1.moby_id END AS moby_id
CASE WHEN r1.igdb_id {null_safe_equal_operator} r2.igdb_id THEN r1.igdb_id END AS igdb_id,
CASE WHEN r1.moby_id {null_safe_equal_operator} r2.moby_id THEN r1.moby_id END AS moby_id
FROM
roms r1
JOIN
roms r2
ON
JOIN
roms r2
ON
r1.platform_id = r2.platform_id
AND r1.id != r2.id
AND (
(r1.igdb_id = r2.igdb_id AND r1.igdb_id IS NOT NULL AND r1.igdb_id != '')
(r1.igdb_id = r2.igdb_id AND r1.igdb_id IS NOT NULL)
OR
(r1.moby_id = r2.moby_id AND r1.moby_id IS NOT NULL AND r1.moby_id != '')
(r1.moby_id = r2.moby_id AND r1.moby_id IS NOT NULL)
);
"""
""" # nosec B608
),
)

View File

@@ -8,6 +8,7 @@ Create Date: 2024-08-29 15:52:56.031850
import sqlalchemy as sa
from alembic import op
from sqlalchemy.dialects.postgresql import ENUM
# revision identifiers, used by Alembic.
revision = "0026_romuser_status_fields"
@@ -17,6 +18,7 @@ depends_on = None
def upgrade() -> None:
connection = op.get_bind()
with op.batch_alter_table("collections", schema=None) as batch_op:
batch_op.alter_column(
"path_cover_l",
@@ -31,6 +33,27 @@ def upgrade() -> None:
existing_nullable=True,
)
if connection.engine.name == "postgresql":
rom_user_status_enum = ENUM(
"INCOMPLETE",
"FINISHED",
"COMPLETED_100",
"RETIRED",
"NEVER_PLAYING",
name="romuserstatus",
create_type=False,
)
rom_user_status_enum.create(connection, checkfirst=False)
else:
rom_user_status_enum = sa.Enum(
"INCOMPLETE",
"FINISHED",
"COMPLETED_100",
"RETIRED",
"NEVER_PLAYING",
name="romuserstatus",
)
with op.batch_alter_table("rom_user", schema=None) as batch_op:
batch_op.add_column(
sa.Column("last_played", sa.DateTime(timezone=True), nullable=True)
@@ -41,23 +64,12 @@ def upgrade() -> None:
batch_op.add_column(sa.Column("rating", sa.Integer(), nullable=False))
batch_op.add_column(sa.Column("difficulty", sa.Integer(), nullable=False))
batch_op.add_column(sa.Column("completion", sa.Integer(), nullable=False))
batch_op.add_column(
sa.Column(
"status",
sa.Enum(
"INCOMPLETE",
"FINISHED",
"COMPLETED_100",
"RETIRED",
"NEVER_PLAYING",
name="romuserstatus",
),
nullable=True,
)
)
batch_op.add_column(sa.Column("status", rom_user_status_enum, nullable=True))
def downgrade() -> None:
connection = op.get_bind()
with op.batch_alter_table("rom_user", schema=None) as batch_op:
batch_op.drop_column("status")
batch_op.drop_column("completion")
@@ -68,6 +80,9 @@ def downgrade() -> None:
batch_op.drop_column("backlogged")
batch_op.drop_column("last_played")
if connection.engine.name == "postgresql":
ENUM(name="romuserstatus").drop(connection, checkfirst=False)
with op.batch_alter_table("collections", schema=None) as batch_op:
batch_op.alter_column(
"path_cover_s",

View File

@@ -16,7 +16,7 @@ depends_on = None
def upgrade() -> None:
# ### commands auto generated by Alembic - please adjust! ###
connection = op.get_bind()
with op.batch_alter_table("roms") as batch_op:
batch_op.execute(
"UPDATE roms SET file_path = REPLACE(file_path, '/romm/library/', '')"
@@ -27,10 +27,14 @@ def upgrade() -> None:
batch_op.execute(
"UPDATE roms SET path_cover_l = REPLACE(path_cover_l, '/romm/resources/', '')"
)
batch_op.execute(
"UPDATE roms SET path_screenshots = REPLACE(path_screenshots, '/romm/resources/', '')"
)
# ### end Alembic commands ###
if connection.engine.name == "postgresql":
batch_op.execute(
"UPDATE roms SET path_screenshots = REPLACE(path_screenshots::text, '/romm/resources/', '')::jsonb"
)
else:
batch_op.execute(
"UPDATE roms SET path_screenshots = REPLACE(path_screenshots, '/romm/resources/', '')"
)
def downgrade() -> None:

View File

@@ -8,6 +8,7 @@ Create Date: 2023-08-10 22:18:24.012779
import sqlalchemy as sa
from alembic import op
from sqlalchemy.dialects.postgresql import ENUM
# revision identifiers, used by Alembic.
revision = "2.0.0"
@@ -39,9 +40,12 @@ def upgrade() -> None:
def downgrade() -> None:
# ### commands auto generated by Alembic - please adjust! ###
connection = op.get_bind()
with op.batch_alter_table("users", schema=None) as batch_op:
batch_op.drop_index(batch_op.f("ix_users_username"))
op.drop_table("users")
# ### end Alembic commands ###
if connection.engine.name == "postgresql":
ENUM(name="role").drop(connection, checkfirst=False)

View File

@@ -93,6 +93,8 @@ class ConfigManager:
driver = "mariadb+mariadbconnector"
elif ROMM_DB_DRIVER == "mysql":
driver = "mysql+mysqlconnector"
elif ROMM_DB_DRIVER == "postgresql":
driver = "postgresql+psycopg"
else:
log.critical(f"{ROMM_DB_DRIVER} database not supported")
sys.exit(3)

View File

@@ -27,12 +27,15 @@ FROM python:${PYTHON_VERSION}-alpine${ALPINE_VERSION} AS backend-build
# git is needed to install py7zr fork
# libffi-dev is needed to fix poetry dependencies for >= v1.8 on arm64
# libpq-dev is needed to build psycopg-c
# mariadb-connector-c-dev is needed to build mariadb-connector
RUN apk add --no-cache \
gcc \
git \
libffi-dev \
libpq-dev \
mariadb-connector-c-dev \
musl-dev \
libffi-dev
musl-dev
RUN pip install poetry
@@ -104,6 +107,7 @@ RUN apk add --no-cache \
bash \
libmagic \
mariadb-connector-c \
libpq \
p7zip \
python3 \
tzdata \

48
poetry.lock generated
View File

@@ -1705,6 +1705,40 @@ files = [
dev = ["black", "check-manifest", "coverage", "packaging", "pylint", "pyperf", "pypinfo", "pytest-cov", "requests", "rstcheck", "ruff", "sphinx", "sphinx_rtd_theme", "toml-sort", "twine", "virtualenv", "wheel"]
test = ["pytest", "pytest-xdist", "setuptools"]
[[package]]
name = "psycopg"
version = "3.2.3"
description = "PostgreSQL database adapter for Python"
optional = false
python-versions = ">=3.8"
files = [
{file = "psycopg-3.2.3-py3-none-any.whl", hash = "sha256:644d3973fe26908c73d4be746074f6e5224b03c1101d302d9a53bf565ad64907"},
{file = "psycopg-3.2.3.tar.gz", hash = "sha256:a5764f67c27bec8bfac85764d23c534af2c27b893550377e37ce59c12aac47a2"},
]
[package.dependencies]
psycopg-c = {version = "3.2.3", optional = true, markers = "implementation_name != \"pypy\" and extra == \"c\""}
typing-extensions = {version = ">=4.6", markers = "python_version < \"3.13\""}
tzdata = {version = "*", markers = "sys_platform == \"win32\""}
[package.extras]
binary = ["psycopg-binary (==3.2.3)"]
c = ["psycopg-c (==3.2.3)"]
dev = ["ast-comments (>=1.1.2)", "black (>=24.1.0)", "codespell (>=2.2)", "dnspython (>=2.1)", "flake8 (>=4.0)", "mypy (>=1.11)", "types-setuptools (>=57.4)", "wheel (>=0.37)"]
docs = ["Sphinx (>=5.0)", "furo (==2022.6.21)", "sphinx-autobuild (>=2021.3.14)", "sphinx-autodoc-typehints (>=1.12)"]
pool = ["psycopg-pool"]
test = ["anyio (>=4.0)", "mypy (>=1.11)", "pproxy (>=2.7)", "pytest (>=6.2.5)", "pytest-cov (>=3.0)", "pytest-randomly (>=3.5)"]
[[package]]
name = "psycopg-c"
version = "3.2.3"
description = "PostgreSQL database adapter for Python -- C optimisation distribution"
optional = false
python-versions = ">=3.8"
files = [
{file = "psycopg_c-3.2.3.tar.gz", hash = "sha256:06ae7db8eaec1a3845960fa7f997f4ccdb1a7a7ab8dc593a680bcc74e1359671"},
]
[[package]]
name = "ptyprocess"
version = "0.7.0"
@@ -2859,6 +2893,7 @@ files = [
greenlet = {version = "!=0.4.17", markers = "python_version < \"3.13\" and (platform_machine == \"aarch64\" or platform_machine == \"ppc64le\" or platform_machine == \"x86_64\" or platform_machine == \"amd64\" or platform_machine == \"AMD64\" or platform_machine == \"win32\" or platform_machine == \"WIN32\")"}
mariadb = {version = ">=1.0.1,<1.1.2 || >1.1.2,<1.1.5 || >1.1.5,<1.1.10 || >1.1.10", optional = true, markers = "extra == \"mariadb-connector\""}
mysql-connector-python = {version = "*", optional = true, markers = "extra == \"mysql-connector\""}
psycopg = {version = ">=3.0.7", optional = true, markers = "extra == \"postgresql-psycopg\""}
typing-extensions = ">=4.6.0"
[package.extras]
@@ -3130,6 +3165,17 @@ files = [
{file = "typing_extensions-4.12.2.tar.gz", hash = "sha256:1a7ead55c7e559dd4dee8856e3a88b41225abfe1ce8df57b7c13915fe121ffb8"},
]
[[package]]
name = "tzdata"
version = "2024.2"
description = "Provider of IANA time zone data"
optional = false
python-versions = ">=2"
files = [
{file = "tzdata-2024.2-py2.py3-none-any.whl", hash = "sha256:a48093786cdcde33cad18c2555e8532f34422074448fbc874186f0abd79565cd"},
{file = "tzdata-2024.2.tar.gz", hash = "sha256:7d85cc416e9382e69095b7bdf4afd9e3880418a2413feec7069d533d6b4e31cc"},
]
[[package]]
name = "unidecode"
version = "1.3.8"
@@ -3566,4 +3612,4 @@ files = [
[metadata]
lock-version = "2.0"
python-versions = "^3.12"
content-hash = "e9380cae3aa9cbc412125bb79ed8c4107749117d16d219974480e70b9f34579d"
content-hash = "68abad24858cd9853f757d6587a6d0acf56a3188bff6c67b5ec3579ea8e99a7f"

View File

@@ -15,9 +15,11 @@ uvicorn = "0.29.0"
gunicorn = "22.0.0"
websockets = "12.0"
python-socketio = "5.11.1"
psycopg = { version = "^3.2", extras = ["c"] }
SQLAlchemy = { version = "^2.0.30", extras = [
"mariadb-connector",
"mysql-connector",
"postgresql-psycopg",
] }
alembic = "1.13.1"
PyYAML = "6.0.1"