# Path: psqlextra/expressions.py
# class HStoreRef(expressions.F):
#     """Inline reference to a HStore key.
# 
#     Allows selecting individual keys in annotations.
#     """
# 
#     def __init__(self, name: str, key: str):
#         """Initializes a new instance of :see:HStoreRef.
# 
#         Arguments:
#             name:
#                 The name of the column/field to resolve.
# 
#             key:
#                 The name of the HStore key to select.
#         """
# 
#         super().__init__(name)
#         self.key = key
# 
#     def resolve_expression(self, *args, **kwargs):
#         """Resolves the expression into a :see:HStoreColumn expression."""
# 
#         original_expression: expressions.Col = super().resolve_expression(
#             *args, **kwargs
#         )
#         expression = HStoreColumn(
#             original_expression.alias, original_expression.target, self.key
#         )
#         return expression
# 
# Path: psqlextra/fields/hstore_field.py
# class HStoreField(DjangoHStoreField):
#     """Improved version of Django's :see:HStoreField that adds support for
#     database-level constraints.
# 
#     Notes:
#         - For the implementation of uniqueness, see the
#           custom database back-end.
#     """
# 
#     def __init__(
#         self,
#         *args,
#         uniqueness: Optional[List[Union[str, Tuple[str, ...]]]] = None,
#         required: Optional[List[str]] = None,
#         **kwargs
#     ):
#         """Initializes a new instance of :see:HStoreField.
# 
#         Arguments:
#             uniqueness:
#                 List of keys to enforce as unique. Use tuples
#                 to enforce multiple keys together to be unique.
# 
#             required:
#                 List of keys that should be enforced as required.
#         """
# 
#         super(HStoreField, self).__init__(*args, **kwargs)
# 
#         self.uniqueness = uniqueness
#         self.required = required
# 
#     def get_prep_value(self, value):
#         """Override the base class so it doesn't cast all values to strings.
# 
#         psqlextra supports expressions in hstore fields, so casting all
#         values to strings is a bad idea.
#         """
# 
#         value = Field.get_prep_value(self, value)
# 
#         if isinstance(value, dict):
#             prep_value = {}
#             for key, val in value.items():
#                 if isinstance(val, Expression):
#                     prep_value[key] = val
#                 elif val is not None:
#                     prep_value[key] = str(val)
#                 else:
#                     prep_value[key] = val
# 
#             value = prep_value
# 
#         if isinstance(value, list):
#             value = [str(item) for item in value]
# 
#         return value
# 
#     def deconstruct(self):
#         """Gets the values to pass to :see:__init__ when re-creating this
#         object."""
# 
#         name, path, args, kwargs = super(HStoreField, self).deconstruct()
# 
#         if self.uniqueness is not None:
#             kwargs["uniqueness"] = self.uniqueness
# 
#         if self.required is not None:
#             kwargs["required"] = self.required
# 
#         return name, path, args, kwargs
# 
# Path: tests/fake_model.py
# def get_fake_model(fields=None, model_base=PostgresModel, meta_options={}):
#     """Defines a fake model and creates it in the database."""
# 
#     model = define_fake_model(fields, model_base, meta_options)
# 
#     with connection.schema_editor() as schema_editor:
#         schema_editor.create_model(model)
# 
#     return model


from django.db import models
from django.db.models import Case, F, Q, Value, When
from psqlextra.expressions import HStoreRef
from psqlextra.fields import HStoreField
from .fake_model import get_fake_model
    performing update queries."""

    model = get_fake_model(
        {"name": models.CharField(max_length=255), "name_new": HStoreField()}
    )

    model.objects.create(name="waqas", name_new=dict(en="swen"))
    model.objects.update(name_new=dict(en=models.F("name")))

    inst = model.objects.all().first()
    assert inst.name_new.get("en") == "waqas"


def test_query_hstore_value_update_cast():
    """Tests whether values in a HStore field are automatically cast to strings
    when doing updates."""

    model = get_fake_model({"title": HStoreField()})

    model.objects.create(title=dict(en="test"))
    model.objects.update(title=dict(en=2))

    inst = model.objects.all().first()
    assert inst.title.get("en") == "2"


def test_query_hstore_value_update_escape():
    """Tests whether values in a HStore field are properly escaped using
    prepared statement values."""


# Path: psqlextra/expressions.py
# class HStoreRef(expressions.F):
#     """Inline reference to a HStore key.
# 
#     Allows selecting individual keys in annotations.
#     """
# 
#     def __init__(self, name: str, key: str):
#         """Initializes a new instance of :see:HStoreRef.
# 
#         Arguments:
#             name:
#                 The name of the column/field to resolve.
# 
#             key:
#                 The name of the HStore key to select.
#         """
# 
#         super().__init__(name)
#         self.key = key
# 
#     def resolve_expression(self, *args, **kwargs):
#         """Resolves the expression into a :see:HStoreColumn expression."""
# 
#         original_expression: expressions.Col = super().resolve_expression(
#             *args, **kwargs
#         )
#         expression = HStoreColumn(
#             original_expression.alias, original_expression.target, self.key
#         )
#         return expression
# 
# Path: psqlextra/fields/hstore_field.py
# class HStoreField(DjangoHStoreField):
#     """Improved version of Django's :see:HStoreField that adds support for
#     database-level constraints.
# 
#     Notes:
#         - For the implementation of uniqueness, see the
#           custom database back-end.
#     """
# 
#     def __init__(
#         self,
#         *args,
#         uniqueness: Optional[List[Union[str, Tuple[str, ...]]]] = None,
#         required: Optional[List[str]] = None,
#         **kwargs
#     ):
#         """Initializes a new instance of :see:HStoreField.
# 
#         Arguments:
#             uniqueness:
#                 List of keys to enforce as unique. Use tuples
#                 to enforce multiple keys together to be unique.
# 
#             required:
#                 List of keys that should be enforced as required.
#         """
# 
#         super(HStoreField, self).__init__(*args, **kwargs)
# 
#         self.uniqueness = uniqueness
#         self.required = required
# 
#     def get_prep_value(self, value):
#         """Override the base class so it doesn't cast all values to strings.
# 
#         psqlextra supports expressions in hstore fields, so casting all
#         values to strings is a bad idea.
#         """
# 
#         value = Field.get_prep_value(self, value)
# 
#         if isinstance(value, dict):
#             prep_value = {}
#             for key, val in value.items():
#                 if isinstance(val, Expression):
#                     prep_value[key] = val
#                 elif val is not None:
#                     prep_value[key] = str(val)
#                 else:
#                     prep_value[key] = val
# 
#             value = prep_value
# 
#         if isinstance(value, list):
#             value = [str(item) for item in value]
# 
#         return value
# 
#     def deconstruct(self):
#         """Gets the values to pass to :see:__init__ when re-creating this
#         object."""
# 
#         name, path, args, kwargs = super(HStoreField, self).deconstruct()
# 
#         if self.uniqueness is not None:
#             kwargs["uniqueness"] = self.uniqueness
# 
#         if self.required is not None:
#             kwargs["required"] = self.required
# 
#         return name, path, args, kwargs
# 
# Path: tests/fake_model.py
# def get_fake_model(fields=None, model_base=PostgresModel, meta_options={}):
#     """Defines a fake model and creates it in the database."""
# 
#     model = define_fake_model(fields, model_base, meta_options)
# 
#     with connection.schema_editor() as schema_editor:
#         schema_editor.create_model(model)
# 
#     return model


# Path: tests/test_query.py
from django.db import models
from django.db.models import Case, F, Q, Value, When
from psqlextra.expressions import HStoreRef
from psqlextra.fields import HStoreField
from .fake_model import get_fake_model

    performing update queries."""

    model = get_fake_model(
        {"name": models.CharField(max_length=255), "name_new": HStoreField()}
    )

    model.objects.create(name="waqas", name_new=dict(en="swen"))
    model.objects.update(name_new=dict(en=models.F("name")))

    inst = model.objects.all().first()
    assert inst.name_new.get("en") == "waqas"


def test_query_hstore_value_update_cast():
    """Tests whether values in a HStore field are automatically cast to strings
    when doing updates."""

    model = get_fake_model({"title": HStoreField()})

    model.objects.create(title=dict(en="test"))
    model.objects.update(title=dict(en=2))

    inst = model.objects.all().first()
    assert inst.title.get("en") == "2"


def test_query_hstore_value_update_escape():
    """Tests whether values in a HStore field are properly escaped using
    prepared statement values."""


    model = get_fake_model({"title": HStoreField()})