@@ -9,12 +9,16 @@ new type through ``CREATE TYPE`` statements in CQL::
9
9
10
10
Version 2.1 of the Python driver adds support for user-defined types.
11
11
12
- Registering a Class to Map to a UDT
13
- -----------------------------------
12
+ Registering a UDT
13
+ -----------------
14
14
You can tell the Python driver to return columns of a specific UDT as
15
- instances of a class by registering them with your :class: `~.Cluster `
15
+ instances of a class or a dict by registering them with your :class: `~.Cluster `
16
16
instance through :meth: `.Cluster.register_user_type `:
17
17
18
+
19
+ Map a Class to a UDT
20
+ ++++++++++++++++++++
21
+
18
22
.. code-block :: python
19
23
20
24
cluster = Cluster(protocol_version = 3 )
@@ -39,7 +43,29 @@ instance through :meth:`.Cluster.register_user_type`:
39
43
# results will include Address instances
40
44
results = session.execute(" SELECT * FROM users" )
41
45
row = results[0 ]
42
- print row.id, row.location.street, row.location.zipcode
46
+ print (row.id, row.location.street, row.location.zipcode)
47
+
48
+ Map a dict to a UDT
49
+ +++++++++++++++++++
50
+
51
+ .. code-block :: python
52
+
53
+ cluster = Cluster(protocol_version = 3 )
54
+ session = cluster.connect()
55
+ session.set_keyspace(' mykeyspace' )
56
+ session.execute(" CREATE TYPE address (street text, zipcode int)" )
57
+ session.execute(" CREATE TABLE users (id int PRIMARY KEY, location frozen<address>)" )
58
+
59
+ cluster.register_user_type(' mykeyspace' , ' address' , dict )
60
+
61
+ # insert a row using a prepared statement and a tuple
62
+ insert_statement = session.prepare(" INSERT INTO mykeyspace.users (id, location) VALUES (?, ?)" )
63
+ session.execute(insert_statement, [0 , (" 123 Main St." , 78723 )])
64
+
65
+ # results will include dict instances
66
+ results = session.execute(" SELECT * FROM users" )
67
+ row = results[0 ]
68
+ print (row.id, row.location[' street' ], row.location[' zipcode' ])
43
69
44
70
Using UDTs Without Registering Them
45
71
-----------------------------------
@@ -79,7 +105,7 @@ for the UDT:
79
105
results = session.execute(" SELECT * FROM users" )
80
106
first_row = results[0 ]
81
107
address = first_row.location
82
- print address # prints "Address(street='123 Main St.', zipcode=78723)"
108
+ print ( address) # prints "Address(street='123 Main St.', zipcode=78723)"
83
109
street = address.street
84
110
zipcode = address.street
85
111
0 commit comments