1
+ from __future__ import annotations
2
+
1
3
from typing import Optional , Union
2
4
3
5
from piccolo .columns .base import Column
6
+ from piccolo .custom_types import BasicTypes
4
7
from piccolo .querystring import QueryString
5
8
6
9
7
10
class Cast (QueryString ):
8
11
def __init__ (
9
12
self ,
10
- identifier : Union [Column , QueryString ],
13
+ identifier : Union [Column , QueryString , BasicTypes ],
11
14
as_type : Column ,
12
15
alias : Optional [str ] = None ,
13
16
):
@@ -17,25 +20,36 @@ def __init__(
17
20
>>> from piccolo.query.functions import Cast
18
21
19
22
>>> await Concert.select(
20
- ... Cast(Concert.starts, Time(), "start_time")
23
+ ... Cast(Concert.starts, Time(), alias= "start_time")
21
24
... )
22
25
[{"start_time": datetime.time(19, 0)}]
23
26
27
+ You may also need ``Cast`` to explicitly tell the database which type
28
+ you're sending in the query (though this is an edge case). Here is a
29
+ contrived example::
30
+
31
+ >>> from piccolo.query.functions.math import Count
32
+
33
+ # This fails with asyncpg:
34
+ >>> await Band.select(Count([1,2,3]))
35
+
36
+ If we explicitly specify the type of the array, then it works::
37
+
38
+ >>> await Band.select(
39
+ ... Count(
40
+ ... Cast(
41
+ ... [1,2,3],
42
+ ... Array(Integer())
43
+ ... ),
44
+ ... )
45
+ ... )
46
+
24
47
:param identifier:
25
- Identifies what is being converted (e.g. a column).
48
+ Identifies what is being converted (e.g. a column, or a raw value ).
26
49
:param as_type:
27
50
The type to be converted to.
28
51
29
52
"""
30
- # Make sure the identifier is a supported type.
31
-
32
- if not isinstance (identifier , (Column , QueryString )):
33
- raise ValueError (
34
- "The identifier is an unsupported type - only Column and "
35
- "QueryString instances are allowed."
36
- )
37
-
38
- #######################################################################
39
53
# Convert `as_type` to a string which can be used in the query.
40
54
41
55
if not isinstance (as_type , Column ):
@@ -44,6 +58,7 @@ def __init__(
44
58
# We need to give the column a reference to a table, and hence
45
59
# the database engine, as the column type is sometimes dependent
46
60
# on which database is being used.
61
+
47
62
from piccolo .table import Table , create_table_class
48
63
49
64
table : Optional [type [Table ]] = None
0 commit comments