diff --git a/alembic.ini b/alembic.ini new file mode 100644 index 0000000..c265a4f --- /dev/null +++ b/alembic.ini @@ -0,0 +1,148 @@ +# A generic, single database configuration. + +[alembic] +# path to migration scripts. +# this is typically a path given in POSIX (e.g. forward slashes) +# format, relative to the token %(here)s which refers to the location of this +# ini file +script_location = %(here)s/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 +# Or organize into date-based subdirectories (requires recursive_version_locations = true) +# file_template = %%(year)d/%%(month).2d/%%(day).2d_%%(hour).2d%%(minute).2d_%%(second).2d_%%(rev)s_%%(slug)s + +# sys.path path, will be prepended to sys.path if present. +# defaults to the current working directory. for multiple paths, the path separator +# is defined by "path_separator" below. +prepend_sys_path = . + + +# timezone to use when rendering the date within the migration file +# as well as the filename. +# If specified, requires the tzdata library which can be 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 /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 "path_separator" +# below. +# version_locations = %(here)s/bar:%(here)s/bat:%(here)s/alembic/versions + +# path_separator; This indicates what character is used to split lists of file +# paths, including version_locations and prepend_sys_path within configparser +# files such as alembic.ini. +# The default rendered in new alembic.ini files is "os", which uses os.pathsep +# to provide os-dependent path splitting. +# +# Note that in order to support legacy alembic.ini files, this default does NOT +# take place if path_separator is not present in alembic.ini. If this +# option is omitted entirely, fallback logic is as follows: +# +# 1. Parsing of the version_locations option falls back to using the legacy +# "version_path_separator" key, which if absent then falls back to the legacy +# behavior of splitting on spaces and/or commas. +# 2. Parsing of the prepend_sys_path option falls back to the legacy +# behavior of splitting on spaces, commas, or colons. +# +# Valid values for path_separator are: +# +# path_separator = : +# path_separator = ; +# path_separator = space +# path_separator = newline +# +# Use os.pathsep. Default configuration used for new projects. +path_separator = os + +# 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 + +# database URL. This is consumed by the user-maintained env.py script only. +# other means of configuring database URLs may be customized within the env.py +# file. +sqlalchemy.url = sqlite:///data/db/wce_grunderfassung.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 + +# lint with attempts to fix using "ruff" - use the module runner, against the "ruff" module +# hooks = ruff +# ruff.type = module +# ruff.module = ruff +# ruff.options = check --fix REVISION_SCRIPT_FILENAME + +# Alternatively, use the exec runner to execute a binary found on your PATH +# hooks = ruff +# ruff.type = exec +# ruff.executable = ruff +# ruff.options = check --fix REVISION_SCRIPT_FILENAME + +# Logging configuration. This is also consumed by the user-maintained +# env.py script only. +[loggers] +keys = root,sqlalchemy,alembic + +[handlers] +keys = console + +[formatters] +keys = generic + +[logger_root] +level = WARNING +handlers = console +qualname = + +[logger_sqlalchemy] +level = WARNING +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..98e4f9c --- /dev/null +++ b/alembic/README @@ -0,0 +1 @@ +Generic single-database configuration. \ No newline at end of file diff --git a/alembic/env.py b/alembic/env.py new file mode 100644 index 0000000..f72a084 --- /dev/null +++ b/alembic/env.py @@ -0,0 +1,80 @@ +from logging.config import fileConfig +from pathlib import Path + +import dotenv +from alembic import context +from sqlalchemy import engine_from_config, pool + +from wce_crm import constants, db + +# 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 +target_metadata = db.MD_MAIN + +# 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. +config.set_main_option("sqlalchemy.url", f"sqlite:///{constants.Config.DB_PATH_MAIN}") + + +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() diff --git a/alembic/script.py.mako b/alembic/script.py.mako new file mode 100644 index 0000000..1101630 --- /dev/null +++ b/alembic/script.py.mako @@ -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, Sequence[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"} diff --git a/alembic/versions/5f2af5179c47_added_new_column_and_renamed_table_for_.py b/alembic/versions/5f2af5179c47_added_new_column_and_renamed_table_for_.py new file mode 100644 index 0000000..4ec9390 --- /dev/null +++ b/alembic/versions/5f2af5179c47_added_new_column_and_renamed_table_for_.py @@ -0,0 +1,91 @@ +"""added new column and renamed table for initial recording + +Revision ID: 5f2af5179c47 +Revises: +Create Date: 2026-06-17 16:06:46.421562 + +""" + +from typing import Sequence, Union + +import sqlalchemy as sa +from alembic import op + +# revision identifiers, used by Alembic. +revision: str = "5f2af5179c47" +down_revision: Union[str, Sequence[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.rename_table("grunderfassung_unternehmen", "grunderfassung") + op.add_column( + "grunderfassung", + sa.Column("Metadaten_wiedereintrittsdatum", sa.Date, nullable=True, default=None), + ) + # ### end Alembic commands ### + + +def downgrade() -> None: + """Downgrade schema.""" + # ### commands auto generated by Alembic - please adjust! ### + op.create_table( + "grunderfassung_unternehmen", + sa.Column("erfassung_id", sa.INTEGER(), nullable=False), + sa.Column("Metadaten_erstellung", sa.DATETIME(), nullable=True), + sa.Column("Metadaten_aktualisierung", sa.DATETIME(), nullable=True), + sa.Column("Metadaten_nutzer", sa.VARCHAR(length=20), nullable=True), + sa.Column("Arbeitserfahrung", sa.TEXT(), nullable=True), + sa.Column("Grunderfassung_fallnummer", sa.TEXT(), nullable=True), + sa.Column("Grunderfassung_notiz", sa.TEXT(), nullable=True), + sa.Column("HoehereBildung", sa.TEXT(), nullable=True), + sa.Column("Kontaktperson__KP_adresse", sa.TEXT(), nullable=True), + sa.Column("Kontaktperson__KP_anrede_anschrift", sa.TEXT(), nullable=True), + sa.Column("Kontaktperson__KP_email", sa.TEXT(), nullable=True), + sa.Column("Kontaktperson__KP_festnetznummer", sa.TEXT(), nullable=True), + sa.Column("Kontaktperson__KP_funktion_beziehung", sa.TEXT(), nullable=True), + sa.Column("Kontaktperson__KP_mobilfunknummer", sa.TEXT(), nullable=True), + sa.Column("Kontaktperson__KP_name", sa.TEXT(), nullable=True), + sa.Column("Kontaktperson__KP_name_partner", sa.TEXT(), nullable=True), + sa.Column("Kontaktperson__KP_titel", sa.TEXT(), nullable=True), + sa.Column("Kontaktperson__KP_vorname", sa.TEXT(), nullable=True), + sa.Column("Partnersuche__kanal_aufmerksamkeit", sa.TEXT(), nullable=True), + sa.Column("Partnersuche__person_suche", sa.INTEGER(), nullable=True), + sa.Column("Partnersuche__un_suche", sa.INTEGER(), nullable=True), + sa.Column("Projektrelevanz__relevanz", sa.TEXT(), nullable=True), + sa.Column("Projektrelevanz__foerderperiode", sa.TEXT(), nullable=True), + sa.Column("Schulbildung", sa.TEXT(), nullable=True), + sa.Column("Sprachkenntnisse", sa.TEXT(), nullable=True), + sa.Column("Stammdaten__PLZ", sa.TEXT(), nullable=True), + sa.Column("Stammdaten__anrede_anschrift", sa.TEXT(), nullable=True), + sa.Column("Stammdaten__anzahl_kinder__alter", sa.TEXT(), nullable=True), + sa.Column("Stammdaten__anzahl_kinder__anzahl", sa.INTEGER(), nullable=True), + sa.Column("Stammdaten__aufenthaltsort", sa.TEXT(), nullable=True), + sa.Column("Stammdaten__bundesland", sa.TEXT(), nullable=True), + sa.Column("Stammdaten__land", sa.TEXT(), nullable=True), + sa.Column("Stammdaten__email", sa.TEXT(), nullable=True), + sa.Column("Stammdaten__familienstand", sa.TEXT(), nullable=True), + sa.Column("Stammdaten__festnetznummer", sa.TEXT(), nullable=True), + sa.Column("Stammdaten__geburtsdatum", sa.DATE(), nullable=True), + sa.Column("Stammdaten__hausnummer", sa.TEXT(), nullable=True), + sa.Column("Stammdaten__herkunftsland", sa.TEXT(), nullable=True), + sa.Column("Stammdaten__mobilfunknummer", sa.TEXT(), nullable=True), + sa.Column("Stammdaten__name", sa.TEXT(), nullable=True), + sa.Column("Stammdaten__ort", sa.TEXT(), nullable=True), + sa.Column("Stammdaten__rueckkehrer", sa.BOOLEAN(), nullable=True), + sa.Column("Stammdaten__staatsangehoerigkeit", sa.TEXT(), nullable=True), + sa.Column("Stammdaten__strasse", sa.TEXT(), nullable=True), + sa.Column("Stammdaten__titel", sa.TEXT(), nullable=True), + sa.Column("Stammdaten__vorname", sa.TEXT(), nullable=True), + sa.Column("WeitereInfos__WI_arbeitsstatus", sa.TEXT(), nullable=True), + sa.Column("WeitereInfos__WI_aufenthaltstitel", sa.TEXT(), nullable=True), + sa.Column("WeitereInfos__WI_deutsch_sprache", sa.TEXT(), nullable=True), + sa.Column("WeitereInfos__WI_gueltigkeit_aufenthaltstitel", sa.DATE(), nullable=True), + sa.Column("WeitereInfos__WI_meldung_institution", sa.TEXT(), nullable=True), + sa.PrimaryKeyConstraint("erfassung_id"), + ) + op.drop_table("grunderfassung") + # ### end Alembic commands ### diff --git a/deployment/.env b/deployment/.env index 4e75a4b..e2b29a0 100644 --- a/deployment/.env +++ b/deployment/.env @@ -1,4 +1,5 @@ DOPT_STOP_FOLDER_NAME=python DOPT_DB_CRM=data/wce_crm.db DOPT_DB_MAIN=data/wce_grunderfassung.db -DOPT_PATH_LOGGING=data/logs \ No newline at end of file +DOPT_PATH_LOGGING=data/logs +DOPT_ALEMBIC_BASE=python/alembic \ No newline at end of file diff --git a/pdm.lock b/pdm.lock index cd1f265..a9df463 100644 --- a/pdm.lock +++ b/pdm.lock @@ -5,7 +5,7 @@ groups = ["default", "dev", "lint", "nb", "tests"] strategy = ["inherit_metadata"] lock_version = "4.5.0" -content_hash = "sha256:25812ee6ba42033e1341c1799716828d8582092826c1d0889ea775a0f5c548a2" +content_hash = "sha256:bde2f66706034b9c34c6794bf192b44db6e116a287938d88c90c751a2666bdf7" [[metadata.targets]] requires_python = ">=3.11,<3.14" @@ -152,6 +152,23 @@ files = [ {file = "aiosignal-1.4.0.tar.gz", hash = "sha256:f47eecd9468083c2029cc99945502cb7708b082c232f9aca65da147157b251c7"}, ] +[[package]] +name = "alembic" +version = "1.18.4" +requires_python = ">=3.10" +summary = "A database migration tool for SQLAlchemy." +groups = ["default"] +dependencies = [ + "Mako", + "SQLAlchemy>=1.4.23", + "tomli; python_version < \"3.11\"", + "typing-extensions>=4.12", +] +files = [ + {file = "alembic-1.18.4-py3-none-any.whl", hash = "sha256:a5ed4adcf6d8a4cb575f3d759f071b03cd6e5c7618eb796cb52497be25bfe19a"}, + {file = "alembic-1.18.4.tar.gz", hash = "sha256:cb6e1fd84b6174ab8dbb2329f86d631ba9559dd78df550b57804d607672cedbc"}, +] + [[package]] name = "annotated-doc" version = "0.0.4" @@ -1845,7 +1862,7 @@ name = "mako" version = "1.3.11" requires_python = ">=3.8" summary = "A super-fast templating language that borrows the best ideas from the existing templating languages." -groups = ["dev"] +groups = ["default", "dev"] dependencies = [ "MarkupSafe>=0.9.2", ] @@ -1895,7 +1912,7 @@ name = "markupsafe" version = "3.0.3" requires_python = ">=3.9" summary = "Safely add untrusted strings to HTML/XML markup." -groups = ["dev", "nb"] +groups = ["default", "dev", "nb"] files = [ {file = "markupsafe-3.0.3-cp311-cp311-macosx_10_9_x86_64.whl", hash = "sha256:1cc7ea17a6824959616c525620e387f6dd30fec8cb44f649e31712db02123dad"}, {file = "markupsafe-3.0.3-cp311-cp311-macosx_11_0_arm64.whl", hash = "sha256:4bd4cd07944443f5a265608cc6aab442e4f74dff8088b0dfc8238647b8f6ae9a"}, diff --git a/pyproject.toml b/pyproject.toml index 5f1caf7..694d6f0 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -5,7 +5,7 @@ description = "GUI for CRM of NAFKA project with WCE" authors = [ {name = "d-opt GmbH, resp. Florian Förster", email = "f.foerster@d-opt.com"}, ] -dependencies = ["pyside6>=6.11.0", "sqlalchemy[asyncio]>=2.0.50", "polars>=1.40.1", "dopt-basics>=0.2.6", "pydantic[email]>=2.13.4", "babel>=2.18.0", "python-dotenv>=1.2.2"] +dependencies = ["pyside6>=6.11.0", "sqlalchemy[asyncio]>=2.0.50", "polars>=1.40.1", "dopt-basics>=0.2.6", "pydantic[email]>=2.13.4", "babel>=2.18.0", "python-dotenv>=1.2.2", "alembic>=1.18.4"] requires-python = "<3.14,>=3.11" readme = "README.md" license = {text = "LicenseRef-Proprietary"} diff --git a/scripts/alembic_revision.ps1 b/scripts/alembic_revision.ps1 new file mode 100644 index 0000000..ff49f59 --- /dev/null +++ b/scripts/alembic_revision.ps1 @@ -0,0 +1,5 @@ +param( + [string]$Message +) + +pdm run alembic revision --autogenerate -m $Message diff --git a/src/wce_crm/README.md b/src/wce_crm/README.md index 4ea9ef6..625eb85 100644 --- a/src/wce_crm/README.md +++ b/src/wce_crm/README.md @@ -5,3 +5,4 @@ - DOPT_DB_CRM: path to CRM database, relative to base path - DOPT_DB_MAIN: path to main database, relative to base path - DOPT_PATH_LOGGING: path to logging folder, relative to base path +- DOPT_ALEMBIC_BASE: path to all relevant alembic file diff --git a/src/wce_crm/constants.py b/src/wce_crm/constants.py index e555c32..70ac77d 100644 --- a/src/wce_crm/constants.py +++ b/src/wce_crm/constants.py @@ -24,3 +24,4 @@ class Config: ) PATH_LOGGING: Path = BASE_PATH / os.getenv("DOPT_PATH_LOGGING", "data/d-opt.log") LOG_FILENAME: str = "dopt.log" + ALEMBIC_PATH: Path = BASE_PATH / os.getenv("DOPT_ALEMBIC_BASE", "python/alembic") diff --git a/src/wce_crm/db.py b/src/wce_crm/db.py index fb380c6..f5d2db2 100644 --- a/src/wce_crm/db.py +++ b/src/wce_crm/db.py @@ -13,6 +13,7 @@ from wce_crm import constants from wce_crm import types as t +# // declarations class SafeDateTime(TypeDecorator): """Cleans non-standard ISO strings before parsing.""" @@ -57,8 +58,8 @@ class UTCDateTime(TypeDecorator): return value -md_crm = sql.MetaData() -md_main = sql.MetaData() +MD_CRM = sql.MetaData() +MD_MAIN = sql.MetaData() ENGINE = sql.create_engine(f"sqlite:///{constants.Config.DB_PATH_MAIN}") # ---------- OLD "Kontaktliste" ---------- @@ -141,7 +142,7 @@ ENGINE = sql.create_engine(f"sqlite:///{constants.Config.DB_PATH_MAIN}") ext_crm_master: sql.Table = Table( "Master", - md_crm, + MD_CRM, Column("ma_id", sql.Integer, nullable=False, unique=True), Column("wce_id", sql.ForeignKey("Nutzer.wce_id")), Column("ma_unternehmensname", sql.Text, nullable=True), @@ -218,7 +219,7 @@ DF_CRM_MASTER = get_ext_crm_master(constants.Config.DB_PATH_CRM) ext_crm_nutzer: sql.Table = Table( "Nutzer", - md_crm, + MD_CRM, Column("wce_id", sql.Integer, nullable=False, unique=True), Column("wce_name", sql.Text, nullable=True), Column("wce_vorname", sql.Text, nullable=True), @@ -246,7 +247,7 @@ ext_crm_nutzer_schema: t.PolarsSchema = { ext_crm_contact_person: sql.Table = Table( "Ansprechpartner", - md_crm, + MD_CRM, Column("an_id", sql.Integer, nullable=False, unique=True), Column("ma_id", sql.ForeignKey("Master.ma_id")), Column("wce_id", sql.ForeignKey("Nutzer.wce_id")), @@ -325,7 +326,7 @@ DF_CONTACT_PERSON = get_ext_crm_contact_person(constants.Config.DB_PATH_CRM) grunderfassung: sql.Table = Table( "grunderfassung", - md_main, + MD_MAIN, Column( "erfassung_id", sql.Integer, @@ -398,4 +399,4 @@ grunderfassung: sql.Table = Table( Column("WeitereInfos__WI_meldung_institution", sql.Text, nullable=True), ) -md_main.create_all(ENGINE) +MD_MAIN.create_all(ENGINE) diff --git a/src/wce_crm/db_migration.py b/src/wce_crm/db_migration.py new file mode 100644 index 0000000..55837bf --- /dev/null +++ b/src/wce_crm/db_migration.py @@ -0,0 +1,36 @@ +from alembic import command +from alembic.config import Config + +from wce_crm import constants +from wce_crm.logging import logger_base as logger + + +def check_and_run_migrations() -> None: + logger.info("[DB migration - Alembic] Start...") + alembic_base_folder = constants.Config.ALEMBIC_PATH + alembic_ini_file = alembic_base_folder / "alembic.ini" + alembic_working_dir = alembic_base_folder / "alembic" + + assert alembic_ini_file.exists(), "Alembic INI file not found" + assert alembic_working_dir.exists(), "Alembic working dir not found" + assert alembic_working_dir.is_dir(), "Alembic working dir is not a directory" + + logger.info("[DB migration - Alembic] Initialise config...") + alembic_cfg = Config(alembic_ini_file) + alembic_cfg.set_main_option("script_location", str(alembic_working_dir)) + + logger.info("[DB migration - Alembic] Run...") + try: + command.upgrade(alembic_cfg, "head") + logger.info("[DB migration - Alembic] Database up-to-date.") + except Exception as err: + logger.info( + "[DB migration - Alembic] An error occurred during the migration:\n%s", + err, + stack_info=True, + ) + + +if __name__ == "__main__": + # start migration process before app start + check_and_run_migrations()