Skip to content

Commit 0d72845

Browse files
authored
Merge pull request scylladb#36 from riptano/python-1168
PYTHON-1168: Add an example to get a UDT as a simple dict
2 parents 4929dee + d24652c commit 0d72845

File tree

1 file changed

+31
-5
lines changed

1 file changed

+31
-5
lines changed

docs/user_defined_types.rst

Lines changed: 31 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -9,12 +9,16 @@ new type through ``CREATE TYPE`` statements in CQL::
99

1010
Version 2.1 of the Python driver adds support for user-defined types.
1111

12-
Registering a Class to Map to a UDT
13-
-----------------------------------
12+
Registering a UDT
13+
-----------------
1414
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`
1616
instance through :meth:`.Cluster.register_user_type`:
1717

18+
19+
Map a Class to a UDT
20+
++++++++++++++++++++
21+
1822
.. code-block:: python
1923
2024
cluster = Cluster(protocol_version=3)
@@ -39,7 +43,29 @@ instance through :meth:`.Cluster.register_user_type`:
3943
# results will include Address instances
4044
results = session.execute("SELECT * FROM users")
4145
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'])
4369
4470
Using UDTs Without Registering Them
4571
-----------------------------------
@@ -79,7 +105,7 @@ for the UDT:
79105
results = session.execute("SELECT * FROM users")
80106
first_row = results[0]
81107
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)"
83109
street = address.street
84110
zipcode = address.street
85111

0 commit comments

Comments
 (0)