Skip to content

Commit

Permalink
Add before_insert decorator shortcut
Browse files Browse the repository at this point in the history
  • Loading branch information
nsiregar committed Aug 17, 2021
1 parent 5f45ae3 commit a69a548
Show file tree
Hide file tree
Showing 2 changed files with 29 additions and 2 deletions.
10 changes: 10 additions & 0 deletions src/sqlalchemy_events.py
Original file line number Diff line number Diff line change
Expand Up @@ -44,3 +44,13 @@ def wrapper(fn):
return fn

return wrapper


def before_insert(*args):
def wrapper(fn):
setattr(fn, _EventObject.ATTR, _EventObject(None, "before_insert"))
return fn

if args and callable(args[0]):
return wrapper(args[0])
return wrapper
21 changes: 19 additions & 2 deletions tests/orm/mapper_event_test.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
from sqlalchemy.orm import sessionmaker
from sqlalchemy import Column, Integer, String
from sqlalchemy.ext.declarative import declarative_base
from src.sqlalchemy_events import listen_events, on
from src.sqlalchemy_events import listen_events, on, before_insert

Base = declarative_base()

Expand All @@ -28,7 +28,7 @@ def setup_database():
session.close()


def test_before_commit(setup_database):
def test_before_insert(setup_database):
@listen_events
class User(BaseModel):
@on("before_insert")
Expand All @@ -47,3 +47,20 @@ def lowercase_username(mapper, conn, self):
mary = session.query(User).filter(User.username == "mary").first()
assert john.username == "john"
assert mary.username == "mary"


def test_before_insert_decorator(setup_database):
@listen_events
class User(BaseModel):
@before_insert
def lowercase_username(mapper, conn, self):
self.username = self.username.lower()

session = setup_database
user_1 = User(username="John")

session.add(user_1)
session.commit()

john = session.query(User).filter(User.username == "john").first()
assert john.username == "john"

0 comments on commit a69a548

Please sign in to comment.