field.py 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849
  1. # Copyright Materialize, Inc. and contributors. All rights reserved.
  2. #
  3. # Use of this software is governed by the Business Source License
  4. # included in the LICENSE file at the root of this repository.
  5. #
  6. # As of the Change Date specified in that file, in accordance with
  7. # the Business Source License, use of this software will be governed
  8. # by the Apache License, Version 2.0.
  9. from collections.abc import Callable
  10. from typing import Any
  11. from pg8000.native import literal
  12. from materialize.data_ingest.data_type import DataType
  13. def identity(x: Any) -> Any:
  14. return identity
  15. def formatted_value(value: Any) -> str:
  16. return literal(str(value))
  17. class Field:
  18. name: str
  19. data_type: type[DataType]
  20. is_key: bool
  21. # value_fn can be used to encode a value which is stored in this field, for example:
  22. # import uuid
  23. # namespace = uuid.uuid4()
  24. # value_fn = lambda x: uuid.uuid5(namespace, x)
  25. value_fn: Callable[[Any], Any]
  26. def __init__(
  27. self,
  28. name: str,
  29. data_type: type[DataType],
  30. is_key: bool,
  31. value_fn: Callable[[Any], Any] | None = None,
  32. ):
  33. self.name = name
  34. self.data_type = data_type
  35. self.is_key = is_key
  36. self.value_fn = value_fn or identity
  37. def __repr__(self) -> str:
  38. return f"Field({'key' if self.is_key else 'value'}, {self.name}: {self.data_type.__name__})"