@@ -102,10 +102,16 @@ def field_to_bigquery(self, field):
102
102
def convert_type (self , value , schema_type ):
103
103
"""
104
104
Takes a value from MySQLdb, and converts it to a value that's safe for
105
- JSON/Google Cloud Storage/BigQuery. Dates are converted to UTC seconds.
106
- Decimals are converted to floats. Binary type fields are encoded with base64,
107
- as imported BYTES data must be base64-encoded according to Bigquery SQL
108
- date type documentation: https://cloud.google.com/bigquery/data-types
105
+ JSON/Google Cloud Storage/BigQuery.
106
+
107
+ * Datetimes are converted to UTC seconds.
108
+ * Decimals are converted to floats.
109
+ * Dates are converted to ISO formatted string if given schema_type is
110
+ DATE, or UTC seconds otherwise.
111
+ * Binary type fields are converted to integer if given schema_type is
112
+ INTEGER, or encoded with base64 otherwise. Imported BYTES data must
113
+ be base64-encoded according to BigQuery documentation:
114
+ https://cloud.google.com/bigquery/data-types
109
115
110
116
:param value: MySQLdb column value
111
117
:type value: Any
@@ -114,12 +120,20 @@ def convert_type(self, value, schema_type):
114
120
"""
115
121
if value is None :
116
122
return value
117
- if isinstance (value , (datetime , date )):
118
- return calendar .timegm (value .timetuple ())
119
- if isinstance (value , timedelta ):
120
- return value .total_seconds ()
121
- if isinstance (value , Decimal ):
122
- return float (value )
123
- if isinstance (value , bytes ) or schema_type == "BYTES" :
124
- return base64 .standard_b64encode (value ).decode ('ascii' )
123
+ if isinstance (value , datetime ):
124
+ value = calendar .timegm (value .timetuple ())
125
+ elif isinstance (value , timedelta ):
126
+ value = value .total_seconds ()
127
+ elif isinstance (value , Decimal ):
128
+ value = float (value )
129
+ elif isinstance (value , date ):
130
+ if schema_type == "DATE" :
131
+ value = value .isoformat ()
132
+ else :
133
+ value = calendar .timegm (value .timetuple ())
134
+ elif isinstance (value , bytes ):
135
+ if schema_type == "INTEGER" :
136
+ value = int .from_bytes (value , "big" )
137
+ else :
138
+ value = base64 .standard_b64encode (value ).decode ('ascii' )
125
139
return value
0 commit comments