Skip to content

Commit

Permalink
Merge branch '2.0' into sfink-fix-stuff
Browse files Browse the repository at this point in the history
  • Loading branch information
josephmancuso authored Sep 30, 2023
2 parents e0be900 + d9c8e13 commit a37ef7b
Show file tree
Hide file tree
Showing 7 changed files with 64 additions and 25 deletions.
2 changes: 1 addition & 1 deletion setup.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@
# Versions should comply with PEP440. For a discussion on single-sourcing
# the version across setup.py and the project code, see
# https://packaging.python.org/en/latest/single_source_version.html
version="2.19.1",
version="2.19.2",
package_dir={"": "src"},
description="The Official Masonite ORM",
long_description=long_description,
Expand Down
12 changes: 3 additions & 9 deletions src/masoniteorm/models/Model.py
Original file line number Diff line number Diff line change
Expand Up @@ -265,6 +265,7 @@ class Model(TimeStampsMixin, ObservesEvents, metaclass=ModelMeta):
"with_count",
"latest",
"oldest",
"value"
)
)

Expand Down Expand Up @@ -559,14 +560,10 @@ def create(
"""
if query:
return cls.builder.create(
dictionary, query=True, id_key=cls.__primary_key__, cast=cast, **kwargs
dictionary, query=True, cast=cast, **kwargs
).to_sql()

# when 'id_key' is already present in kwargs, the previous version raised
kwargs['id_key'] = cls.__primary_key__
return cls.builder.create(
dictionary, cast=cast, **kwargs
)
return cls.builder.create(dictionary, cast=cast, **kwargs)

@classmethod
def cast_value(cls, attribute: str, value: Any):
Expand Down Expand Up @@ -662,7 +659,6 @@ def serialize(self, exclude=None, include=None):

remove_keys = []
for key, value in serialized_dictionary.items():

if key in self.__hidden__:
remove_keys.append(key)
if hasattr(value, "serialize"):
Expand Down Expand Up @@ -1032,7 +1028,6 @@ def set_appends(self, appends):
return self

def save_many(self, relation, relating_records):

if isinstance(relating_records, Model):
raise ValueError(
"Saving many records requires an iterable like a collection or a list of models and not a Model object. To attach a model, use the 'attach' method."
Expand All @@ -1048,7 +1043,6 @@ def save_many(self, relation, relating_records):
related.attach_related(self, related_record)

def detach_many(self, relation, relating_records):

if isinstance(relating_records, Model):
raise ValueError(
"Detaching many records requires an iterable like a collection or a list of models and not a Model object. To detach a model, use the 'detach' method."
Expand Down
6 changes: 6 additions & 0 deletions src/masoniteorm/query/QueryBuilder.py
Original file line number Diff line number Diff line change
Expand Up @@ -1754,6 +1754,9 @@ def sole(self, query=False):

return result.first()

def sole_value(self, column: str, query=False):
return self.sole()[column]

def first_where(self, column, *args):
"""Gets the first record with the given key / value pair"""
if not args:
Expand Down Expand Up @@ -2282,3 +2285,6 @@ def oldest(self, *fields):
fields = ("created_at",)

return self.order_by(column=",".join(fields), direction="ASC")

def value(self, column: str):
return self.get().first()[column]
11 changes: 6 additions & 5 deletions src/masoniteorm/scopes/TimeStampsScope.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
from .BaseScope import BaseScope

from ..expressions.expressions import UpdateQueryExpression
from .BaseScope import BaseScope


class TimeStampsScope(BaseScope):
Expand All @@ -27,8 +26,8 @@ def set_timestamp_create(self, builder):

builder._creates.update(
{
"updated_at": builder._model.get_new_date().to_datetime_string(),
"created_at": builder._model.get_new_date().to_datetime_string(),
builder._model.date_updated_at: builder._model.get_new_date().to_datetime_string(),
builder._model.date_created_at: builder._model.get_new_date().to_datetime_string(),
}
)

Expand All @@ -38,6 +37,8 @@ def set_timestamp_update(self, builder):

builder._updates += (
UpdateQueryExpression(
{"updated_at": builder._model.get_new_date().to_datetime_string()}
{
builder._model.date_updated_at: builder._model.get_new_date().to_datetime_string()
}
),
)
28 changes: 19 additions & 9 deletions src/masoniteorm/scopes/UUIDPrimaryKeyScope.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import uuid

from .BaseScope import BaseScope


Expand All @@ -9,6 +10,9 @@ def on_boot(self, builder):
builder.set_global_scope(
"_UUID_primary_key", self.set_uuid_create, action="insert"
)
builder.set_global_scope(
"_UUID_primary_key", self.set_bulk_uuid_create, action="bulk_create"
)

def on_remove(self, builder):
pass
Expand All @@ -22,15 +26,21 @@ def generate_uuid(self, builder, uuid_version, bytes=False):

return uuid_func(*args).bytes if bytes else str(uuid_func(*args))

def build_uuid_pk(self, builder):
uuid_version = getattr(builder._model, "__uuid_version__", 4)
uuid_bytes = getattr(builder._model, "__uuid_bytes__", False)
return {
builder._model.__primary_key__: self.generate_uuid(
builder, uuid_version, uuid_bytes
)
}

def set_uuid_create(self, builder):
# if there is already a primary key, no need to set a new one
if builder._model.__primary_key__ not in builder._creates:
uuid_version = getattr(builder._model, "__uuid_version__", 4)
uuid_bytes = getattr(builder._model, "__uuid_bytes__", False)
builder._creates.update(
{
builder._model.__primary_key__: self.generate_uuid(
builder, uuid_version, uuid_bytes
)
}
)
builder._creates.update(self.build_uuid_pk(builder))

def set_bulk_uuid_create(self, builder):
for idx, create_atts in enumerate(builder._creates):
if builder._model.__primary_key__ not in create_atts:
builder._creates[idx].update(self.build_uuid_pk(builder))
3 changes: 2 additions & 1 deletion tests/mysql/model/test_model.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,10 +2,11 @@
import json
import os
import unittest

import pendulum

from src.masoniteorm.exceptions import ModelNotFound
from src.masoniteorm.collection import Collection
from src.masoniteorm.exceptions import ModelNotFound
from src.masoniteorm.models import Model
from tests.User import User

Expand Down
27 changes: 27 additions & 0 deletions tests/scopes/test_default_global_scopes.py
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,12 @@ class UserWithTimeStamps(Model, TimeStampsMixin):
__dry__ = True


class UserWithCustomTimeStamps(Model, TimeStampsMixin):
__dry__ = True
date_updated_at = "updated_ts"
date_created_at = "created_ts"


class UserSoft(Model, SoftDeletesMixin):
__dry__ = True

Expand Down Expand Up @@ -112,3 +118,24 @@ def test_timestamps_can_be_disabled(self):
self.scope.set_timestamp_create(self.builder)
self.assertNotIn("created_at", self.builder._creates)
self.assertNotIn("updated_at", self.builder._creates)

def test_uses_custom_timestamp_columns_on_create(self):
self.builder = MockBuilder(UserWithCustomTimeStamps)
self.scope.set_timestamp_create(self.builder)
created_column = UserWithCustomTimeStamps.date_created_at
updated_column = UserWithCustomTimeStamps.date_updated_at
self.assertNotIn("created_at", self.builder._creates)
self.assertNotIn("updated_at", self.builder._creates)
self.assertIn(created_column, self.builder._creates)
self.assertIn(updated_column, self.builder._creates)
self.assertIsInstance(
pendulum.parse(self.builder._creates[created_column]), pendulum.DateTime
)
self.assertIsInstance(
pendulum.parse(self.builder._creates[updated_column]), pendulum.DateTime
)

def test_uses_custom_updated_column_on_update(self):
user = UserWithCustomTimeStamps.hydrate({"id": 1})
sql = user.update({"id": 2}).to_sql()
self.assertTrue(UserWithCustomTimeStamps.date_updated_at in sql)

0 comments on commit a37ef7b

Please sign in to comment.