private CassandraColumnHandle buildColumnHandle(AbstractTableMetadata tableMetadata, ColumnMetadata columnMeta, boolean partitionKey, boolean clusteringKey, int ordinalPosition, boolean hidden) { CassandraType cassandraType = CassandraType.getCassandraType(columnMeta.getType().getName()); List<CassandraType> typeArguments = null; if (cassandraType != null && cassandraType.getTypeArgumentSize() > 0) { List<DataType> typeArgs = columnMeta.getType().getTypeArguments(); switch (cassandraType.getTypeArgumentSize()) { case 1: typeArguments = ImmutableList.of(CassandraType.getCassandraType(typeArgs.get(0).getName())); break; case 2: typeArguments = ImmutableList.of(CassandraType.getCassandraType(typeArgs.get(0).getName()), CassandraType.getCassandraType(typeArgs.get(1).getName())); break; default: throw new IllegalArgumentException("Invalid type arguments: " + typeArgs); } } boolean indexed = false; SchemaTableName schemaTableName = new SchemaTableName(tableMetadata.getKeyspace().getName(), tableMetadata.getName()); if (!isMaterializedView(schemaTableName)) { TableMetadata table = (TableMetadata) tableMetadata; for (IndexMetadata idx : table.getIndexes()) { if (idx.getTarget().equals(columnMeta.getName())) { indexed = true; break; } } } return new CassandraColumnHandle(connectorId, columnMeta.getName(), ordinalPosition, cassandraType, typeArguments, partitionKey, clusteringKey, indexed, hidden); }
protected static String getPrimitiveAvroTypeFromCassandraType(DataType dataType) { // Map types from Cassandra to Avro where possible if (dataType.equals(DataType.ascii()) || dataType.equals(DataType.text()) || dataType.equals(DataType.varchar()) // Nonstandard types represented by this processor as a string || dataType.equals(DataType.timestamp()) || dataType.equals(DataType.timeuuid()) || dataType.equals(DataType.uuid()) || dataType.equals(DataType.inet()) || dataType.equals(DataType.varint())) { return "string"; } else if (dataType.equals(DataType.cboolean())) { return "boolean"; } else if (dataType.equals(DataType.cint())) { return "int"; } else if (dataType.equals(DataType.bigint()) || dataType.equals(DataType.counter())) { return "long"; } else if (dataType.equals(DataType.cfloat())) { return "float"; } else if (dataType.equals(DataType.cdouble())) { return "double"; } else if (dataType.equals(DataType.blob())) { return "bytes"; } else { throw new IllegalArgumentException("createSchema: Unknown Cassandra data type " + dataType.getName() + " cannot be converted to Avro type"); } }
throw new IllegalArgumentException("Column[" + i + "] " + dataType.getName() + " is a collection but no type arguments were specified!");
/** * Return the closing character to use when formatting values as CQL literals. * * @return The closing character to use when formatting values as CQL literals. */ private char getClosingChar() { return cqlType.getName() == Name.LIST ? ']' : '}'; } }
/** * Return the opening character to use when formatting values as CQL literals. * * @return The opening character to use when formatting values as CQL literals. */ private char getOpeningChar() { return cqlType.getName() == Name.LIST ? '[' : '{'; }
private CustomCodec(DataType custom) { super(custom, ByteBuffer.class); assert custom.getName() == Name.CUSTOM; }
List<DataType> typeArguments = dataType.getTypeArguments(); if (typeArguments == null || typeArguments.size() == 0) { throw new IllegalArgumentException("Column[" + i + "] " + dataType.getName() + " is a collection but no type arguments were specified!");
@Override public Token getToken(int i) { if (tokenFactory == null) throw new DriverInternalError( "Token factory not set. This should only happen at initialization time"); checkType(i, tokenFactory.getTokenType().getName()); ByteBuffer value = data.get(i); if (value == null || value.remaining() == 0) return null; return tokenFactory.deserialize(value, protocolVersion); }
@Override public boolean apply(DataType dataType) { return protocolVersion.compareTo(dataType.getName().minProtocolVersion) >= 0; } });
protected void checkType(int i, DataType.Name actual) { DataType.Name expected = getType(i).getName(); if (!actual.isCompatibleWith(expected)) throw new InvalidTypeException( String.format("Value %s is of type %s, not %s", getName(i), expected, actual)); }
T setToken(int i, Token v) { if (v == null) throw new NullPointerException( String.format("Cannot set a null token for column %s", getName(i))); checkType(i, v.getType().getName()); // Bypass CodecRegistry when serializing tokens return setValue(i, v.serialize(protocolVersion)); }
@Override public <E> List<E> getColumnsById(String schemaName, String tableName, String pKeyColumnName, String columnName, Object pKeyColumnValue, Class columnJavaType) { // select columnName from tableName where pKeyColumnName = // pKeyColumnValue List results = new ArrayList(); CQLTranslator translator = new CQLTranslator(); String selectQuery = translator.SELECT_QUERY; selectQuery = StringUtils.replace(selectQuery, CQLTranslator.COLUMN_FAMILY, translator.ensureCase(new StringBuilder(), tableName, false).toString()); selectQuery = StringUtils.replace(selectQuery, CQLTranslator.COLUMNS, translator.ensureCase(new StringBuilder(), columnName, false).toString()); StringBuilder selectQueryBuilder = new StringBuilder(selectQuery); selectQueryBuilder.append(CQLTranslator.ADD_WHERE_CLAUSE); translator.buildWhereClause(selectQueryBuilder, columnJavaType, pKeyColumnName, pKeyColumnValue, CQLTranslator.EQ_CLAUSE, false); selectQueryBuilder.delete(selectQueryBuilder.lastIndexOf(CQLTranslator.AND_CLAUSE), selectQueryBuilder.length()); ResultSet rSet = execute(selectQueryBuilder.toString(), null); Iterator<Row> rowIter = rSet.iterator(); while (rowIter.hasNext()) { Row row = rowIter.next(); DataType dataType = row.getColumnDefinitions().getType(columnName); Object columnValue = DSClientUtilities.assign(row, null, null, dataType.getName(), null, columnName, null, null); results.add(columnValue); } return results; }
/** * Iterate and return. * * @param rSet * the r set * @return the list */ private List iterateAndReturn(ResultSet rSet) { Iterator<Row> rowIter = rSet.iterator(); List results = new ArrayList(); while (rowIter.hasNext()) { Row row = rowIter.next(); ColumnDefinitions columnDefs = row.getColumnDefinitions(); Iterator<Definition> columnDefIter = columnDefs.iterator(); Map rowData = new HashMap(); while (columnDefIter.hasNext()) { Definition columnDef = columnDefIter.next(); rowData.put(columnDef.getName(), DSClientUtilities.assign(row, null, null, columnDef.getType().getName(), null, columnDef.getName(), null, null)); } results.add(rowData); } return results; }
@Override public <T> T get(int i, TypeCodec<T> codec) { checkType(i, codec.getCqlType().getName()); ByteBuffer value = getValue(i); return codec.deserialize(value, protocolVersion); } }
@Override public <V> T set(int i, V v, TypeCodec<V> codec) { checkType(i, codec.getCqlType().getName()); return setValue(i, codec.serialize(v, protocolVersion)); }
@Override public <V> T set(int i, V v, TypeCodec<V> codec) { checkType(i, codec.getCqlType().getName()); return setValue(i, codec.serialize(v, protocolVersion)); }
@SuppressWarnings("unchecked") private <T> TypeCodec<T> lookupCodec(DataType cqlType, TypeToken<T> javaType) { checkNotNull(cqlType, "Parameter cqlType cannot be null"); TypeCodec<?> codec = BUILT_IN_CODECS_MAP.get(cqlType.getName()); if (codec != null && (javaType == null || codec.accepts(javaType))) { logger.trace("Returning built-in codec {}", codec); return (TypeCodec<T>) codec; } if (logger.isTraceEnabled()) logger.trace("Querying cache for codec [{} <-> {}]", toString(cqlType), toString(javaType)); try { CacheKey cacheKey = new CacheKey(cqlType, javaType); codec = cache.get(cacheKey); } catch (UncheckedExecutionException e) { if (e.getCause() instanceof CodecNotFoundException) { throw (CodecNotFoundException) e.getCause(); } throw new CodecNotFoundException(e.getCause(), cqlType, javaType); } catch (RuntimeException e) { throw new CodecNotFoundException(e.getCause(), cqlType, javaType); } catch (ExecutionException e) { throw new CodecNotFoundException(e.getCause(), cqlType, javaType); } logger.trace("Returning cached codec {}", codec); return (TypeCodec<T>) codec; }
@Test(groups = "unit") public void parseUserTypes() { String s = "org.apache.cassandra.db.marshal.UserType(foo,61646472657373,737472656574:org.apache.cassandra.db.marshal.UTF8Type,7a6970636f6465:org.apache.cassandra.db.marshal.Int32Type,70686f6e6573:org.apache.cassandra.db.marshal.SetType(org.apache.cassandra.db.marshal.UserType(foo,70686f6e65,6e616d65:org.apache.cassandra.db.marshal.UTF8Type,6e756d626572:org.apache.cassandra.db.marshal.UTF8Type)))"; UserType def = (UserType) DataTypeClassNameParser.parseOne(s, protocolVersion, codecRegistry); assertEquals(def.getKeyspace(), "foo"); assertEquals(def.getTypeName(), "address"); Iterator<UserType.Field> iter = def.iterator(); UserType.Field field1 = iter.next(); assertEquals(field1.getName(), "street"); assertEquals(field1.getType(), DataType.text()); UserType.Field field2 = iter.next(); assertEquals(field2.getName(), "zipcode"); assertEquals(field2.getType(), DataType.cint()); UserType.Field field3 = iter.next(); assertEquals(field3.getName(), "phones"); DataType st = field3.getType(); assertEquals(st.getName(), DataType.Name.SET); UserType subDef = (UserType) st.getTypeArguments().get(0); assertEquals(subDef.getKeyspace(), "foo"); assertEquals(subDef.getTypeName(), "phone"); Iterator<UserType.Field> subIter = subDef.iterator(); UserType.Field subField1 = subIter.next(); assertEquals(subField1.getName(), "name"); assertEquals(subField1.getType(), DataType.text()); UserType.Field subField2 = subIter.next(); assertEquals(subField2.getName(), "number"); assertEquals(subField2.getType(), DataType.text()); }