From ad39b1c75ca04900c2e1d2ee8ce2988739abbd10 Mon Sep 17 00:00:00 2001 From: VivianDee <115420678+VivianDee@users.noreply.github.com> Date: Fri, 28 Mar 2025 09:56:27 +0100 Subject: [PATCH] [update] Remove foreign key constraints --- .gitignore | 4 +- app/__init__.py | 3 +- app/models/account.py | 11 +- app/models/customer.py | 1 + app/models/loan.py | 4 +- app/models/transaction.py | 2 +- migrations/env.py | 113 ++++++++++++++++++ .../versions/4a12e1b143a4_create_tables.py | 74 ++++++++++++ 8 files changed, 206 insertions(+), 6 deletions(-) create mode 100644 migrations/env.py create mode 100644 migrations/versions/4a12e1b143a4_create_tables.py diff --git a/.gitignore b/.gitignore index b316843..20bea99 100644 --- a/.gitignore +++ b/.gitignore @@ -1,4 +1,6 @@ __pycache__/ .env app.log -.DS_Store \ No newline at end of file +.DS_Store +migrations/__pycache__/ +migrations/*.pycg \ No newline at end of file diff --git a/app/__init__.py b/app/__init__.py index 2c29158..732af48 100644 --- a/app/__init__.py +++ b/app/__init__.py @@ -8,6 +8,7 @@ from app.errors import register_error_handlers from flask_sqlalchemy import SQLAlchemy from flask_migrate import Migrate + db = SQLAlchemy() migrate = Migrate() @@ -36,7 +37,7 @@ def create_app(): # Error Handlers register_error_handlers(app) - + from . import models # Database and Migrations db.init_app(app) diff --git a/app/models/account.py b/app/models/account.py index 1f52087..1c65985 100644 --- a/app/models/account.py +++ b/app/models/account.py @@ -6,13 +6,22 @@ class Account(db.Model): __table_args__ = {'schema': 'flask_app'} id = db.Column(db.String(50), primary_key=True) - customer_id = db.Column(db.String(50), db.ForeignKey('customer.id'), nullable=False) + customer_id = db.Column(db.String(50), nullable=False) account_type = db.Column(db.String(50)) status = db.Column(db.String(20), default='active') lien_amount = db.Column(db.Float, default=0.0) created_at = db.Column(db.DateTime, default=datetime.utcnow) updated_at = db.Column(db.DateTime, default=datetime.utcnow, onupdate=datetime.utcnow) + # Database relationship + # customer = db.relationship( + # 'Customer', + # primaryjoin='Account.customer_id == Customer.id', + # backref='accounts', + # foreign_keys=[customer_id], + # viewonly=True + # ) + def __repr__(self): return f'' \ No newline at end of file diff --git a/app/models/customer.py b/app/models/customer.py index 3f70a8f..54a7807 100644 --- a/app/models/customer.py +++ b/app/models/customer.py @@ -11,5 +11,6 @@ class Customer(db.Model): created_at = db.Column(db.DateTime, default=datetime.utcnow) updated_at = db.Column(db.DateTime, default=datetime.utcnow, onupdate=datetime.utcnow) + def __repr__(self): return f'' \ No newline at end of file diff --git a/app/models/loan.py b/app/models/loan.py index 879834a..ce26cd8 100644 --- a/app/models/loan.py +++ b/app/models/loan.py @@ -7,8 +7,8 @@ class Loan(db.Model): __table_args__ = {'schema': 'flask_app'} id = db.Column(db.String(50), primary_key=True) - customer_id = db.Column(db.String(50), db.ForeignKey('customer.id'), nullable=False) - account_id = db.Column(db.String(50), db.ForeignKey('account.id'), nullable=False) + customer_id = db.Column(db.String(50), nullable=False) + account_id = db.Column(db.String(50), nullable=False) product_id = db.Column(db.String(20), nullable=False) principal_amount = db.Column(db.Float, nullable=False) status = db.Column(db.String(20), default='pending') diff --git a/app/models/transaction.py b/app/models/transaction.py index 73bacf8..1bea982 100644 --- a/app/models/transaction.py +++ b/app/models/transaction.py @@ -6,7 +6,7 @@ class Transaction(db.Model): __table_args__ = {'schema': 'flask_app'} id = db.Column(db.String(50), primary_key=True) - account_id = db.Column(db.String(50), db.ForeignKey('account.id'), nullable=False) + account_id = db.Column(db.String(50), nullable=False) type = db.Column(db.String(50), nullable=False) amount = db.Column(db.Float, nullable=False) status = db.Column(db.String(20), default='pending') diff --git a/migrations/env.py b/migrations/env.py new file mode 100644 index 0000000..4c97092 --- /dev/null +++ b/migrations/env.py @@ -0,0 +1,113 @@ +import logging +from logging.config import fileConfig + +from flask import current_app + +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. +fileConfig(config.config_file_name) +logger = logging.getLogger('alembic.env') + + +def get_engine(): + try: + # this works with Flask-SQLAlchemy<3 and Alchemical + return current_app.extensions['migrate'].db.get_engine() + except (TypeError, AttributeError): + # this works with Flask-SQLAlchemy>=3 + return current_app.extensions['migrate'].db.engine + + +def get_engine_url(): + try: + return get_engine().url.render_as_string(hide_password=False).replace( + '%', '%%') + except AttributeError: + return str(get_engine().url).replace('%', '%%') + + +# add your model's MetaData object here +# for 'autogenerate' support +# from myapp import mymodel +# target_metadata = mymodel.Base.metadata +config.set_main_option('sqlalchemy.url', get_engine_url()) +target_db = current_app.extensions['migrate'].db + +# 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 get_metadata(): + if hasattr(target_db, 'metadatas'): + return target_db.metadatas[None] + return target_db.metadata + + +def run_migrations_offline(): + """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=get_metadata(), literal_binds=True + ) + + with context.begin_transaction(): + context.run_migrations() + + +def run_migrations_online(): + """Run migrations in 'online' mode. + + In this scenario we need to create an Engine + and associate a connection with the context. + + """ + + # this callback is used to prevent an auto-migration from being generated + # when there are no changes to the schema + # reference: http://alembic.zzzcomputing.com/en/latest/cookbook.html + def process_revision_directives(context, revision, directives): + if getattr(config.cmd_opts, 'autogenerate', False): + script = directives[0] + if script.upgrade_ops.is_empty(): + directives[:] = [] + logger.info('No changes in schema detected.') + + conf_args = current_app.extensions['migrate'].configure_args + if conf_args.get("process_revision_directives") is None: + conf_args["process_revision_directives"] = process_revision_directives + + connectable = get_engine() + + with connectable.connect() as connection: + context.configure( + connection=connection, + target_metadata=get_metadata(), + **conf_args + ) + + with context.begin_transaction(): + context.run_migrations() + + +if context.is_offline_mode(): + run_migrations_offline() +else: + run_migrations_online() diff --git a/migrations/versions/4a12e1b143a4_create_tables.py b/migrations/versions/4a12e1b143a4_create_tables.py new file mode 100644 index 0000000..c99e599 --- /dev/null +++ b/migrations/versions/4a12e1b143a4_create_tables.py @@ -0,0 +1,74 @@ +"""Create tables + +Revision ID: 4a12e1b143a4 +Revises: +Create Date: 2025-03-28 09:24:49.669509 + +""" +from alembic import op +import sqlalchemy as sa + + +# revision identifiers, used by Alembic. +revision = '4a12e1b143a4' +down_revision = None +branch_labels = None +depends_on = None + + +def upgrade(): + # ### commands auto generated by Alembic - please adjust! ### + op.create_table('accounts', + sa.Column('id', sa.String(length=50), nullable=False), + sa.Column('customer_id', sa.String(length=50), nullable=False), + sa.Column('account_type', sa.String(length=50), nullable=True), + sa.Column('status', sa.String(length=20), nullable=True), + sa.Column('lien_amount', sa.Float(), nullable=True), + sa.Column('created_at', sa.DateTime(), nullable=True), + sa.Column('updated_at', sa.DateTime(), nullable=True), + sa.PrimaryKeyConstraint('id'), + schema='flask_app' + ) + op.create_table('customers', + sa.Column('id', sa.String(length=50), nullable=False), + sa.Column('msisdn', sa.String(length=20), nullable=False), + sa.Column('country_code', sa.String(length=3), nullable=False), + sa.Column('created_at', sa.DateTime(), nullable=True), + sa.Column('updated_at', sa.DateTime(), nullable=True), + sa.PrimaryKeyConstraint('id'), + sa.UniqueConstraint('msisdn'), + schema='flask_app' + ) + op.create_table('loans', + sa.Column('id', sa.String(length=50), nullable=False), + sa.Column('customer_id', sa.String(length=50), nullable=False), + sa.Column('account_id', sa.String(length=50), nullable=False), + sa.Column('product_id', sa.String(length=20), nullable=False), + sa.Column('principal_amount', sa.Float(), nullable=False), + sa.Column('status', sa.String(length=20), nullable=True), + sa.Column('created_at', sa.DateTime(), nullable=True), + sa.Column('updated_at', sa.DateTime(), nullable=True), + sa.PrimaryKeyConstraint('id'), + schema='flask_app' + ) + op.create_table('transactions', + sa.Column('id', sa.String(length=50), nullable=False), + sa.Column('account_id', sa.String(length=50), nullable=False), + sa.Column('type', sa.String(length=50), nullable=False), + sa.Column('amount', sa.Float(), nullable=False), + sa.Column('status', sa.String(length=20), nullable=True), + sa.Column('created_at', sa.DateTime(), nullable=True), + sa.Column('updated_at', sa.DateTime(), nullable=True), + sa.PrimaryKeyConstraint('id'), + schema='flask_app' + ) + # ### end Alembic commands ### + + +def downgrade(): + # ### commands auto generated by Alembic - please adjust! ### + op.drop_table('transactions', schema='flask_app') + op.drop_table('loans', schema='flask_app') + op.drop_table('customers', schema='flask_app') + op.drop_table('accounts', schema='flask_app') + # ### end Alembic commands ###