absent1706 / sqlalchemy-mixins

Active Record, Django-like queries, nested eager load and beauty __repr__ for SQLAlchemy
MIT License
756 stars 67 forks source link

How to cover the original model by TimestampsMixin? #91

Open vba34520 opened 2 years ago

vba34520 commented 2 years ago

I have a table in MySQL like this

CREATE TABLE `user` (
  `id` int NOT NULL AUTO_INCREMENT,
  `name` varchar(255) DEFAULT NULL,
  `created_at` datetime DEFAULT NULL,
  `updated_at` datetime DEFAULT NULL,
  `deleted_at` datetime DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB;

Auto generate

pip install pymysql
pip install sqlacodegen

sqlacodegen mysql+pymysql://root:123456@127.0.0.1:3306/test

Result

class User(Base):
    __tablename__ = 'user'

    id = Column(Integer, primary_key=True)
    name = Column(String(255))
    created_at = Column(DateTime)
    updated_at = Column(DateTime)
    deleted_at = Column(DateTime)

And I combine it with sqlalchemy_mixins

main.py

from flask import Flask
from sqlalchemy_mixins import AllFeaturesMixin
from sqlalchemy_mixins.timestamp import TimestampsMixin
from sqlalchemy import Column, Integer, String, DateTime
from flask_sqlalchemy import SQLAlchemy

app = Flask(__name__)
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
# app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///data.db'
app.config['SQLALCHEMY_DATABASE_URI'] = 'mysql://root:123456@127.0.0.1:3306/test'
db = SQLAlchemy(app, session_options={'autocommit': True})

class Base(db.Model, AllFeaturesMixin, TimestampsMixin):
    __abstract__ = True

class User(Base):
    __tablename__ = 'user'

    id = Column(Integer, primary_key=True)
    name = Column(String(255))
    created_at = Column(DateTime)
    updated_at = Column(DateTime)
    deleted_at = Column(DateTime)

Base.set_session(db.session)
db.create_all()

if __name__ == '__main__':
    user = User.create(name='Bob')
    print(user.to_dict())
    # {'id': 1, 'name': 'Bob', 'created_at': None, 'updated_at': None, 'deleted_at': None}

How to make created_at and updated_at are not None without deleting their statements?

michaelbukachi commented 2 years ago

Remove created_at and updated_at from the User model definition and it should work as intended.

vba34520 commented 2 years ago

First, Removing them manually will increase workload after auto generate.

Second, It will affect the original order of fields.

vba34520 commented 2 years ago

How to achieve logical deleting by deleted_at? Thanks!

For example, a user record's deleted_at was set. I hope Product.find_or_fail(id) will raise sqlalchemy_mixins.ModelNotFoundError.