Skip to content

Commit fc2a650

Browse files
authored
1376 Add Replace function (#1377)
* add `Replace` function * remove unused import
1 parent b3e888a commit fc2a650

2 files changed

Lines changed: 50 additions & 0 deletions

File tree

docs/src/piccolo/functions/string.rst

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -26,6 +26,11 @@ Ltrim
2626
.. autoclass:: Ltrim
2727
:class-doc-from: class
2828

29+
Replace
30+
-------
31+
32+
.. autoclass:: Replace
33+
2934
Reverse
3035
-------
3136

piccolo/query/functions/string.py

Lines changed: 45 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -107,10 +107,55 @@ def __init__(
107107
)
108108

109109

110+
class Replace(QueryString):
111+
def __init__(
112+
self,
113+
identifier: Union[Column, QueryString],
114+
old: str,
115+
new: str,
116+
alias: Optional[str] = None,
117+
):
118+
"""
119+
Replace any instances of ``old`` in the string with ``new``.
120+
121+
For example, a really basic slugify implementation::
122+
123+
class Venue(Table):
124+
name = Varchar()
125+
126+
>>> await Venue.select(Replace(Venue.name, ' ', '-'))
127+
[{'name': 'Amazing-Venue'}]
128+
129+
"""
130+
# Preserve the original alias from the column.
131+
132+
from piccolo.columns import Column
133+
134+
if isinstance(identifier, Column):
135+
alias = (
136+
alias
137+
or identifier._alias
138+
or identifier._meta.get_default_alias()
139+
)
140+
elif isinstance(identifier, QueryString):
141+
alias = alias or identifier._alias
142+
143+
#######################################################################
144+
145+
super().__init__(
146+
"REPLACE({}, {}, {})",
147+
identifier,
148+
old,
149+
new,
150+
alias=alias,
151+
)
152+
153+
110154
__all__ = (
111155
"Length",
112156
"Lower",
113157
"Ltrim",
158+
"Replace",
114159
"Reverse",
115160
"Rtrim",
116161
"Upper",

0 commit comments

Comments
 (0)