1from collections.abc import Callable, Sequence
2from typing import TYPE_CHECKING, Any
3
4from plain.preflight import PreflightResult
5from plain.validators import MaxLengthValidator
6
7from plain import validators
8
9from .base import NOT_PROVIDED, ChoicesField, ColumnField
10
11if TYPE_CHECKING:
12 from plain.postgres.functions.random import RandomString
13
14
15class TextField[T: (str, str | None) = str](ChoicesField[T]):
16 db_type_sql = "text"
17
18 def __init__(
19 self,
20 *,
21 max_length: int | None = None,
22 choices: Any = None,
23 required: bool = True,
24 allow_null: bool = False,
25 default: Any = NOT_PROVIDED,
26 validators: Sequence[Callable[..., Any]] = (),
27 ):
28 self.max_length = max_length
29 super().__init__(
30 choices=choices,
31 required=required,
32 allow_null=allow_null,
33 default=default,
34 validators=validators,
35 )
36 if self.max_length is not None:
37 self.validators.append(MaxLengthValidator(self.max_length))
38
39 def deconstruct(self) -> tuple[str, str, list[Any], dict[str, Any]]:
40 name, path, args, kwargs = super().deconstruct()
41 if self.max_length is not None:
42 kwargs["max_length"] = self.max_length
43 return name, path, args, kwargs
44
45 @property
46 def description(self) -> str:
47 if self.max_length is not None:
48 return "String (up to %(max_length)s)"
49 else:
50 return "String (unlimited)"
51
52 def preflight(self, **kwargs: Any) -> list[PreflightResult]:
53 return [
54 *super().preflight(**kwargs),
55 *self._check_max_length_attribute(),
56 ]
57
58 def _check_max_length_attribute(self, **kwargs: Any) -> list[PreflightResult]:
59 if self.max_length is None:
60 return []
61 elif (
62 not isinstance(self.max_length, int)
63 or isinstance(self.max_length, bool)
64 or self.max_length <= 0
65 ):
66 return [
67 PreflightResult(
68 fix="'max_length' must be a positive integer.",
69 obj=self,
70 id="fields.textfield_invalid_max_length",
71 )
72 ]
73 else:
74 return []
75
76 def _max_length_for_choices_check(self) -> int | None:
77 return self.max_length
78
79 def to_python(self, value: Any) -> str | None:
80 if isinstance(value, str) or value is None:
81 return value
82 return str(value)
83
84 def get_prep_value(self, value: Any) -> Any:
85 value = super().get_prep_value(value)
86 return self.to_python(value)
87
88
89class EmailField[T: (str, str | None) = str](TextField[T]):
90 default_validators = (validators.validate_email,)
91
92
93class URLField[T: (str, str | None) = str](TextField[T]):
94 default_validators = (validators.URLValidator(),)
95
96
97class RandomStringField[T: (str, str | None) = str](ColumnField[T]):
98 """Text column whose value is a Postgres-generated random hex string.
99
100 The column carries a ``DEFAULT`` that evaluates per row, so raw SQL and
101 ORM inserts both get a fresh ``length``-character hex string. Pass an
102 explicit value at ``create()`` time to override.
103 """
104
105 db_type_sql = "text"
106
107 def __init__(
108 self,
109 *,
110 length: int,
111 required: bool = True,
112 allow_null: bool = False,
113 validators: Sequence[Callable[..., Any]] = (),
114 ):
115 from plain.postgres.functions.random import RandomString
116
117 self._expression = RandomString(length=length)
118 super().__init__(
119 required=required,
120 allow_null=allow_null,
121 validators=validators,
122 )
123
124 def get_db_default_expression(self) -> RandomString:
125 return self._expression
126
127 def deconstruct(self) -> tuple[str, str, list[Any], dict[str, Any]]:
128 name, path, args, kwargs = super().deconstruct()
129 kwargs["length"] = self._expression.length
130 return name, path, args, kwargs