Returns the correct cast from JSON to PostgreSQL type
519412
function parse_predicate_pgcast(ObjType, document_type, key) {
	var pgtype = parse_predicate_pgtype(ObjType, document_type, key);
	return parse_predicate_pgcast_by_type(pgtype);
}
769620
def type_to_sql(type, limit = nil, precision = nil, scale = nil)
      return super unless NO_LIMIT_TYPES.include?(t = type.to_s.downcase.to_sym)

      native_type = NATIVE_DATABASE_TYPES[t]
      native_type.is_a?(Hash) ? native_type[:name] : native_type
    end
735439
def json2sql(raw_json=None, **definition):  # pylint: disable=too-many-branches
    
    if raw_json and definition:
        raise InputError("Cannot process dict and kwargs input at the same time")

    definition = load_input(raw_json or definition)
    if not isinstance(definition, dict):
        raise UnknownStatementError("Unknown statement parsed: %s (type: %s)"
                                    % (definition, type(definition)))

    try:
        statement = definition.pop('statement', None)
        if statement is None:
            raise NoStatementError("No statement provided")

        statement = statement.lower()

        if statement == 'delete':
            return delete2sql(definition)
        elif statement == 'insert':
            return insert2sql(definition)
        elif statement == 'select':
            return select2sql(definition)
        elif statement == 'update':
            return update2sql(definition)
        elif statement == 'replace':
            return replace2sql(definition)
        else:
            raise UnknownStatementError("Unknown statement provided '%s' in definition %s"
                                        % (statement, definition))
    except Exception as exc:  # pylint: disable=broad-except
        if isinstance(exc, Json2SqlError):
            raise

        raise Json2SqlInternalError("Internal json2sql error: %s" % str(exc)) from exc

    # Just to make Pylint happy :)
    raise Json2SqlInternalError("Unreachable state reached")
764803
private static void selectJsonRow(CqlSession session) {

    // Reading the whole row as a JSON object
    Statement stmt =
        selectFrom("examples", "json_jsr353_row")
            .json()
            .all()
            .whereColumn("id")
            .in(literal(1), literal(2))
            .build();

    ResultSet rows = session.execute(stmt);

    for (Row row : rows) {
      // SELECT JSON returns only one column for each row, of type VARCHAR,
      // containing the row as a JSON payload.
      // Note that the codec requires that the type passed to the get() method
      // be always JsonStructure, and not a subclass of it, such as JsonObject,
      // hence the need to downcast to JsonObject manually
      JsonObject user = (JsonObject) row.get(0, JsonStructure.class);
      System.out.printf("Retrieved user: %s%n", user);
    }
  }
514642
def parse_row(schema, data):
    
    def parse_value(data_type, value):
      """Parses a value returned from a BigQuery response.

      Args:
        data_type: the type of the value as specified by the schema.
        value: the raw value to return (before casting to data_type).

      Returns:
        The value cast to the data_type.
      """
      if value is not None:
        if value == 'null':
          value = None
        elif data_type == 'INTEGER':
          value = int(value)
        elif data_type == 'FLOAT':
          value = float(value)
        elif data_type == 'TIMESTAMP':
          value = datetime.datetime.utcfromtimestamp(float(value))
        elif data_type == 'BOOLEAN':
          value = value == 'true'
        elif (type(value) != str):
          # TODO(gram): Handle nested JSON records
          value = str(value)
      return value

    row = {}
    if data is None:
      return row

    for i, (field, schema_field) in enumerate(zip(data['f'], schema)):
      val = field['v']
      name = schema_field['name']
      data_type = schema_field['type']
      repeated = True if 'mode' in schema_field and schema_field['mode'] == 'REPEATED' else False

      if repeated and val is None:
        row[name] = []
      elif data_type == 'RECORD':
        sub_schema = schema_field['fields']
        if repeated:
          row[name] = [Parser.parse_row(sub_schema, v['v']) for v in val]
        else:
          row[name] = Parser.parse_row(sub_schema, val)
      elif repeated:
        row[name] = [parse_value(data_type, v['v']) for v in val]
      else:
        row[name] = parse_value(data_type, val)

    return row
1158775
def type_to_sql(type, limit = nil, precision = nil, scale = nil) #:nodoc:
      return super unless type == :integer

      native = native_database_types[type.to_s.downcase.to_sym]
      native.is_a?(Hash) ? native[:name] : native
    end
956334
@SuppressWarnings({ "unchecked", "rawtypes" })
    public static Object convert(Object value, Class<?> type) {
        if (value == null || type == null || type.isAssignableFrom(value.getClass())) {
            return value;
        }
        if (value instanceof String) {
            String string = (String) value;
            if (char.class.equals(type) || Character.class.equals(type)) {
                if (string.length() != 1) {
                    throw new IllegalArgumentException(String.format("can not convert String(%s) to char!" +
                        " when convert String to char, the String must only 1 char.", string));
                }
                return string.charAt(0);
            } else if (type.isEnum()) {
                return Enum.valueOf((Class<Enum>) type, string);
            } else if (type == BigInteger.class) {
                return new BigInteger(string);
            } else if (type == BigDecimal.class) {
                return new BigDecimal(string);
            } else if (type == Short.class || type == short.class) {
                return Short.valueOf(string);
            } else if (type == Integer.class || type == int.class) {
                return Integer.valueOf(string);
            } else if (type == Long.class || type == long.class) {
                return Long.valueOf(string);
            } else if (type == Double.class || type == double.class) {
                return new Double(string);
            } else if (type == Float.class || type == float.class) {
                return new Float(string);
            } else if (type == Byte.class || type == byte.class) {
                return Byte.valueOf(string);
            } else if (type == Boolean.class || type == boolean.class) {
                return Boolean.valueOf(string);
            } else if (type == Date.class || type == java.sql.Date.class || type == java.sql.Time.class ||
                type == java.sql.Timestamp.class) {
                try {
                    if (type == Date.class) {
                        return DateUtils.strToDate(string, DateUtils.DATE_FORMAT_TIME);
                    } else if (type == java.sql.Date.class) {
                        return new java.sql.Date(DateUtils.strToLong(string));
                    } else if (type == java.sql.Timestamp.class) {
                        return new java.sql.Timestamp(DateUtils.strToLong(string));
                    } else {
                        return new java.sql.Time(DateUtils.strToLong(string));
                    }
                } catch (ParseException e) {
                    throw new IllegalStateException("Failed to parse date " + value + " by format " +
                        DateUtils.DATE_FORMAT_TIME + ", cause: " + e.getMessage(), e);
                }
            } else if (type == Class.class) {
                return ClassTypeUtils.getClass((String) value);
            }
        } else if (value instanceof Number) {
            Number number = (Number) value;
            if (type == byte.class || type == Byte.class) {
                return number.byteValue();
            } else if (type == short.class || type == Short.class) {
                return number.shortValue();
            } else if (type == int.class || type == Integer.class) {
                return number.intValue();
            } else if (type == long.class || type == Long.class) {
                return number.longValue();
            } else if (type == float.class || type == Float.class) {
                return number.floatValue();
            } else if (type == double.class || type == Double.class) {
                return number.doubleValue();
            } else if (type == BigInteger.class) {
                return BigInteger.valueOf(number.longValue());
            } else if (type == BigDecimal.class) {
                return BigDecimal.valueOf(number.doubleValue());
            } else if (type == Date.class) {
                return new Date(number.longValue());
            } else if (type == java.sql.Date.class) {
                return new java.sql.Date(number.longValue());
            } else if (type == java.sql.Time.class) {
                return new java.sql.Time(number.longValue());
            } else if (type == java.sql.Timestamp.class) {
                return new java.sql.Timestamp(number.longValue());
            }
        } else if (value instanceof Collection) {
            Collection collection = (Collection) value;
            if (type.isArray()) {
                int length = collection.size();
                Object array = Array.newInstance(type.getComponentType(), length);
                int i = 0;
                for (Object item : collection) {
                    Array.set(array, i++, item);
                }
                return array;
            } else if (!type.isInterface()) {
                try {
                    Collection result = (Collection) type.newInstance();
                    result.addAll(collection);
                    return result;
                } catch (Throwable ignore) { // NOPMD
                }
            } else if (type == List.class) {
                return new ArrayList<Object>(collection);
            } else if (type == Set.class) {
                return new HashSet<Object>(collection);
            }
        } else if (value.getClass().isArray() && Collection.class.isAssignableFrom(type)) {
            Collection collection;
            if (!type.isInterface()) {
                try {
                    collection = (Collection) type.newInstance();
                } catch (Throwable e) {
                    collection = new ArrayList<Object>();
                }
            } else if (type == Set.class) {
                collection = new HashSet<Object>();
            } else {
                collection = new ArrayList<Object>();
            }
            int length = Array.getLength(value);
            for (int i = 0; i < length; i++) {
                collection.add(Array.get(value, i));
            }
            return collection;
        }
        return value;
    }
832511
def field_to_json(self, type_code, key, *args, **kwargs):
        """"""
        assert ':' not in key
        to_json = self.field_function(type_code, 'to_json')
        key_and_type = "%s:%s" % (key, type_code)
        json_value = to_json(*args, **kwargs)
        return key_and_type, json_value
435943
def from_json(cls, json):
    """"""
    obj = cls(key_range.KeyRange.from_json(json["key_range"]),
              model.QuerySpec.from_json(json["query_spec"]))
    cursor = json["cursor"]
    # lint bug. Class method can access protected fields.
    # pylint: disable=protected-access
    if cursor and json["cursor_object"]:
      obj._cursor = datastore_query.Cursor.from_websafe_string(cursor)
    else:
      obj._cursor = cursor
    return obj
1255663
function serializeMember(value, columnType) {
    
    // Start by checking if the specified column type is valid
    if (!isColumnTypeValid(columnType)) {
        throw new Error('Column type ' + columnType + ' is not supported');
    }

    // Now check if the specified value can be stored in a column of type columnType
    if (!isJSValueCompatibleWithColumnType(value, columnType)) {
        throw new Error('Converting value ' + JSON.stringify(value) + ' of type ' + typeof value + ' to type ' + columnType + ' is not supported.');
    }

    // If we are here, it means we are good to proceed with serialization
    
    var sqliteType = getSqliteType(columnType),
        serializedValue;
    
    switch (sqliteType) {
        case "TEXT":
            serializedValue = typeConverter.convertToText(value);
            break;
        case "INTEGER":
            serializedValue = typeConverter.convertToInteger(value);
            break;
        case "REAL":
            serializedValue = typeConverter.convertToReal(value);
            break;
        default:
            throw new Error('Column type ' + columnType + ' is not supported');
    }
    
    return serializedValue;
}
809186
function toJSON( err ) {
	var keys;
	var out;
	var i;
	if ( !( err instanceof Error ) ) {
		throw new TypeError( 'invalid input argument. Must provide an error object. Value: `' + err + '`.' );
	}
	out = {};

	// Guaranteed properties:
	out.type = typeName( err );
	out.message = err.message;

	// Possible general error properties...
	if ( err.name ) {
		out.name = err.name;
	}
	if ( err.stack ) {
		out.stack = err.stack;
	}
	// Possible Node.js (system error) properties...
	if ( err.code ) {
		out.code = err.code;
	}
	if ( err.errno ) {
		out.errno = err.errno;
	}
	if ( err.syscall ) {
		out.syscall = err.syscall;
	}
	// Any enumerable properties...
	keys = getKeys( err );
	for ( i = 0; i < keys.length; i++ ) {
		out[ keys[i] ] = copy( err[ keys[i] ] );
	}
	return out;
}
687510
function deserializeMember(value, columnType) {
    
    // Handle this special case first.
    // Simply return 'value' if a corresponding columnType is not defined.   
    if (!columnType) {
        return value;
    }

    // Start by checking if the specified column type is valid.
    if (!isColumnTypeValid(columnType)) {
            throw new Error('Column type ' + columnType + ' is not supported');
    }

    // Now check if the specified value can be stored in a column of type columnType.
    if (!isSqliteValueCompatibleWithColumnType(value, columnType)) {
        throw new Error('Converting value ' + JSON.stringify(value) + ' of type ' + typeof value +
                            ' to type ' + columnType + ' is not supported.');
    }

    // If we are here, it means we are good to proceed with deserialization
    
    var deserializedValue, error;

    switch (columnType) {
        case ColumnType.Object:
            deserializedValue = typeConverter.convertToObject(value);
            break;
        case ColumnType.Array:
            deserializedValue = typeConverter.convertToArray(value);
            break;
        case ColumnType.String:
        case ColumnType.Text:
            deserializedValue = typeConverter.convertToText(value);
            break;
        case ColumnType.Integer:
        case ColumnType.Int:
            deserializedValue = typeConverter.convertToInteger(value);
            break;
        case ColumnType.Boolean:
        case ColumnType.Bool:
            deserializedValue = typeConverter.convertToBoolean(value);
            break;
        case ColumnType.Date:
            deserializedValue = typeConverter.convertToDate(value);
            break;
        case ColumnType.Real:
        case ColumnType.Float:
            deserializedValue = typeConverter.convertToReal(value);
            break;
        default:
            throw new Error(_.format(Platform.getResourceString("sqliteSerializer_UnsupportedColumnType"), columnType));
    }

    return deserializedValue;
}
217597
def _cast_to_type(self, value):
        
        if isinstance(value, str) or value is None:
            return value
        return str(value)
80604
def fromJSON(value):
        
        j = json.loads(value)
        v = GPMultiValue(gptype=j['dataType'])
        if "defaultValue" in j:
            v.value = j['defaultValue']
        else:
            v.value = j['value']
        if 'paramName' in j:
            v.paramName = j['paramName']
        elif 'name' in j:
            v.paramName = j['name']
        return v
934893
def _json_safe(cls, value):
        """"""
        # Date
        if type(value) == date:
            return str(value)

        # Datetime
        elif type(value) == datetime:
            return value.strftime('%Y-%m-%d %H:%M:%S')

        # Object Id
        elif isinstance(value, ObjectId):
            return str(value)

        # Frame
        elif isinstance(value, _BaseFrame):
            return value.to_json_type()

        # Lists
        elif isinstance(value, (list, tuple)):
            return [cls._json_safe(v) for v in value]

        # Dictionaries
        elif isinstance(value, dict):
            return {k:cls._json_safe(v) for k, v in value.items()}

        return value
489768
function MetaType($t,$len=-1,$fieldobj=false)
	{
		if (is_object($t)) {
			$fieldobj = $t;
			$t = $fieldobj->type;
			$len = $fieldobj->max_length;
		}
		$is_serial = is_object($fieldobj) && $fieldobj->primary_key && $fieldobj->auto_increment;

		$len = -1; // mysql max_length is not accurate
		switch (strtoupper($t)) {
		case 'STRING':
		case 'CHAR':
		case 'VARCHAR':
		case 'TINYBLOB':
		case 'TINYTEXT':
		case 'ENUM':
		case 'SET':
			if ($len <= $this->blobSize) return 'C';

		case 'TEXT':
		case 'LONGTEXT':
		case 'MEDIUMTEXT':
			return 'X';

		// php_mysql extension always returns 'blob' even if 'text'
		// so we have to check whether binary...
		case 'IMAGE':
		case 'LONGBLOB':
		case 'BLOB':
		case 'MEDIUMBLOB':
			return !empty($fieldobj->binary) ? 'B' : 'X';

		case 'YEAR':
		case 'DATE': return 'D';

		case 'TIME':
		case 'DATETIME':
		case 'TIMESTAMP': return 'T';

		case 'FLOAT':
		case 'DOUBLE':
			return 'F';

		case 'INT':
		case 'INTEGER': return $is_serial ? 'R' : 'I';
		case 'TINYINT': return $is_serial ? 'R' : 'I1';
		case 'SMALLINT': return $is_serial ? 'R' : 'I2';
		case 'MEDIUMINT': return $is_serial ? 'R' : 'I4';
		case 'BIGINT':  return $is_serial ? 'R' : 'I8';
		default: return 'N';
		}
	}
938586
def _rows_from_json(values, schema):
    """"""
    from google.cloud.bigquery import Row

    field_to_index = _field_to_index_mapping(schema)
    return [Row(_row_tuple_from_json(r, schema), field_to_index) for r in values]