1717from datetime import date , datetime , time , timedelta , timezone
1818from decimal import Decimal
1919from uuid import UUID
20+ import json
2021
2122# By convention, backend-specific SQLA types are defined in uppercase
22- # This dialect exposes Databricks SQL's TIMESTAMP and TINYINT types
23+ # This dialect exposes Databricks SQL's TIMESTAMP, TINYINT, and VARIANT types
2324# as these are not covered by the generic, camelcase types shown below
24- from databricks .sqlalchemy import TIMESTAMP , TINYINT
25+ from databricks .sqlalchemy import TIMESTAMP , TINYINT , DatabricksVariant
2526
2627# Beside the CamelCase types shown below, line comments reflect
2728# the underlying Databricks SQL / Delta table type
@@ -82,6 +83,12 @@ class SampleObject(Base):
8283 datetime_col_ntz = Column (DateTime )
8384 time_col = Column (Time )
8485 uuid_col = Column (Uuid )
86+ variant_col = Column (DatabricksVariant )
87+
88+ Base .metadata .drop_all (engine )
89+
90+ # Output SQL is:
91+ # DROP TABLE pysql_sqlalchemy_example_table
8592
8693# This generates a CREATE TABLE statement against the catalog and schema
8794# specified in the connection string
@@ -100,6 +107,7 @@ class SampleObject(Base):
100107# datetime_col_ntz TIMESTAMP_NTZ,
101108# time_col STRING,
102109# uuid_col STRING,
110+ # variant_col VARIANT,
103111# PRIMARY KEY (bigint_col)
104112# ) USING DELTA
105113
@@ -120,6 +128,23 @@ class SampleObject(Base):
120128 "datetime_col_ntz" : datetime (1990 , 12 , 4 , 6 , 33 , 41 ),
121129 "time_col" : time (23 , 59 , 59 ),
122130 "uuid_col" : UUID (int = 255 ),
131+ "variant_col" : {
132+ "name" : "John Doe" ,
133+ "age" : 30 ,
134+ "address" : {
135+ "street" : "123 Main St" ,
136+ "city" : "San Francisco" ,
137+ "state" : "CA" ,
138+ "zip" : "94105"
139+ },
140+ "hobbies" : ["reading" , "hiking" , "cooking" ],
141+ "is_active" : True ,
142+ "metadata" : {
143+ "created_at" : "2024-01-15T10:30:00Z" ,
144+ "version" : 1.2 ,
145+ "tags" : ["premium" , "verified" ]
146+ }
147+ },
123148}
124149sa_obj = SampleObject (** sample_object )
125150
@@ -140,7 +165,8 @@ class SampleObject(Base):
140165# datetime_col,
141166# datetime_col_ntz,
142167# time_col,
143- # uuid_col
168+ # uuid_col,
169+ # variant_col
144170# )
145171# VALUES
146172# (
@@ -154,7 +180,8 @@ class SampleObject(Base):
154180# :datetime_col,
155181# :datetime_col_ntz,
156182# :time_col,
157- # :uuid_col
183+ # :uuid_col,
184+ # PARSE_JSON(:variant_col)
158185# )
159186
160187# Here we build a SELECT query using ORM
@@ -165,6 +192,7 @@ class SampleObject(Base):
165192
166193# Finally, we read out the input data and compare it to the output
167194compare = {key : getattr (result , key ) for key in sample_object .keys ()}
195+ compare ['variant_col' ] = json .loads (compare ['variant_col' ])
168196assert compare == sample_object
169197
170198# Then we drop the demonstration table
0 commit comments