def convert_value(value, proto_value, allow_lists=False): """Convert a variable from python type to proto type+value. Args: value: the python value. proto_value: the proto3 object, needs a type and value field. allow_lists: allows the use of python lists. """ if isinstance(value, bool): proto_value.type = query_pb2.INT64 proto_value.value = str(int(value)) elif isinstance(value, int): proto_value.type = query_pb2.INT64 proto_value.value = str(value) elif isinstance(value, long): if value < INT_UPPERBOUND_PLUS_ONE: proto_value.type = query_pb2.INT64 else: proto_value.type = query_pb2.UINT64 proto_value.value = str(value) elif isinstance(value, float): proto_value.type = query_pb2.FLOAT64 proto_value.value = str(value) elif hasattr(value, '__sql_literal__'): proto_value.type = query_pb2.VARBINARY proto_value.value = str(value.__sql_literal__()) elif isinstance(value, datetime.datetime): proto_value.type = query_pb2.VARBINARY proto_value.value = times.DateTimeToString(value) elif isinstance(value, datetime.date): proto_value.type = query_pb2.VARBINARY proto_value.value = times.DateToString(value) elif isinstance(value, str): proto_value.type = query_pb2.VARBINARY proto_value.value = value elif isinstance(value, field_types.NoneType): proto_value.type = query_pb2.NULL_TYPE elif allow_lists and isinstance(value, (set, tuple, list)): # this only works for bind variables, not for entities. proto_value.type = query_pb2.TUPLE for v in list(value): proto_v = proto_value.values.add() convert_value(v, proto_v) else: proto_value.type = query_pb2.VARBINARY proto_value.value = str(value)
def convert_bind_vars(bind_variables): new_vars = {} for key, val in bind_variables.iteritems(): if hasattr(val, '__sql_literal__'): new_vars[key] = val.__sql_literal__() elif isinstance(val, datetime.datetime): new_vars[key] = times.DateTimeToString(val) elif isinstance(val, datetime.date): new_vars[key] = times.DateToString(val) elif isinstance(val, (int, long, float, str, NoneType)): new_vars[key] = val else: # NOTE(msolomon) begrudgingly I allow this - we just have too much code # that relies on this. # This accidentally solves our hideous dependency on mx.DateTime. new_vars[key] = str(val) return new_vars