Skip to content
Original file line number Diff line number Diff line change
Expand Up @@ -316,6 +316,10 @@ async def create(cls, attributes: dict):

return instance

@classmethod
async def insert(cls, values: dict | list) -> int | None:
return await cls.query().insert(values)

async def update(self, attributes: dict) -> bool:
if not self._exists:
return False
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -27,8 +27,7 @@ def test_compile_bulk_create_builds_multi_row_insert(self):

self.assertEqual(
sql,
'INSERT INTO "users" ("name", "email") VALUES '
"('Joe', 'joe@example.com'), ('Bob', 'bob@example.com')",
"INSERT INTO \"users\" (\"name\", \"email\") VALUES ('Joe', 'joe@example.com'), ('Bob', 'bob@example.com')",
)


Expand Down
21 changes: 21 additions & 0 deletions fastapi_startkit/tests/masoniteorm/postgres/models/test_model.py
Original file line number Diff line number Diff line change
Expand Up @@ -133,3 +133,24 @@ async def test_count_returns_correct_number(self):

count = await User.count()
self.assertEqual(count, 2)

async def test_insert_single_row(self):
await User.insert({"name": "Olivia", "email": "olivia@example.com", "is_admin": False})

user = await User.where("email", "olivia@example.com").first()
self.assertIsNotNone(user)
self.assertEqual(user.name, "Olivia")

async def test_insert_bulk_rows(self):
await User.insert(
[
{"name": "Peggy", "email": "peggy@example.com", "is_admin": False},
{"name": "Quentin", "email": "quentin@example.com", "is_admin": True},
]
)

count = await User.count()
self.assertEqual(count, 2)

admin = await User.where("is_admin", True).first()
self.assertEqual(admin.name, "Quentin")
Original file line number Diff line number Diff line change
Expand Up @@ -38,3 +38,18 @@ async def test_bulk_insert_sql_multiple(self):
sql, bindings = mock_insert.call_args[0]
self.assertEqual(sql, 'INSERT INTO "users" ("name") VALUES (?), (?), (?)')
self.assertEqual(list(bindings), ["Joe", "Bill", "John"])

async def test_insert_classmethod_single_row(self):
await User.insert({"email": "classmethod@test.com", "name": "CM User", "is_admin": False})
user = await User.where("email", "classmethod@test.com").first()
assert user is not None
assert user.name == "CM User"

async def test_insert_classmethod_bulk_rows(self):
mock_insert = AsyncMock(return_value=2)
DB.connection("sqlite").insert = mock_insert
await User.insert([{"name": "Alice"}, {"name": "Bob"}])
mock_insert.assert_called_once()
sql, bindings = mock_insert.call_args[0]
self.assertEqual(sql, 'INSERT INTO "users" ("name") VALUES (?), (?)')
self.assertEqual(list(bindings), ["Alice", "Bob"])
Loading