You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@cassandra.apache.org by ca...@codespot.com on 2012/02/02 17:13:09 UTC
[cassandra-jdbc] 6 new revisions pushed by wfs...@gmail.com on
2012-02-02 16:12 GMT
6 new revisions:
Revision: f891db5c963b
Author: Rick Shaw <wf...@gmail.com>
Date: Sat Dec 17 20:01:00 2011
Log: Support new prepared statement features in CQL in client side...
http://code.google.com/a/apache-extras.org/p/cassandra-jdbc/source/detail?r=f891db5c963b
Revision: 75ddfb82001c
Author: Rick Shaw <wf...@gmail.com>
Date: Wed Dec 21 20:57:28 2011
Log: Merge branch 'new-prepared' into trunk...
http://code.google.com/a/apache-extras.org/p/cassandra-jdbc/source/detail?r=75ddfb82001c
Revision: a18986c3e555
Author: Rick Shaw <wf...@gmail.com>
Date: Wed Dec 21 21:12:23 2011
Log: Rename the interface CassandraResultSet to
CassandraResultSetExtras...
http://code.google.com/a/apache-extras.org/p/cassandra-jdbc/source/detail?r=a18986c3e555
Revision: dbae7bf74566
Author: Rick Shaw <wf...@gmail.com>
Date: Wed Dec 21 21:16:09 2011
Log: Rename CResultSet to CassandraResultSet...
http://code.google.com/a/apache-extras.org/p/cassandra-jdbc/source/detail?r=dbae7bf74566
Revision: 1942c441ea5f
Author: Rick Shaw <wf...@gmail.com>
Date: Thu Feb 2 07:47:12 2012
Log: Client-side PreparedStatement updates for binary bind values...
http://code.google.com/a/apache-extras.org/p/cassandra-jdbc/source/detail?r=1942c441ea5f
Revision: f0e16ff1bc91
Author: Rick Shaw <wf...@gmail.com>
Date: Thu Feb 2 07:58:40 2012
Log: Update various Unit and Functional Tests...
http://code.google.com/a/apache-extras.org/p/cassandra-jdbc/source/detail?r=f0e16ff1bc91
==============================================================================
Revision: f891db5c963b
Author: Rick Shaw <wf...@gmail.com>
Date: Sat Dec 17 20:01:00 2011
Log: Support new prepared statement features in CQL in client side
Signed-off-by: Rick Shaw <wf...@gmail.com>
http://code.google.com/a/apache-extras.org/p/cassandra-jdbc/source/detail?r=f891db5c963b
Added:
/src/main/java/org/apache/cassandra/cql/jdbc/HandleObjects.java
/src/test/java/org/apache/cassandra/cql/TestClass.java
/src/test/java/org/apache/cassandra/cql/jdbc/HandleObjectsUnitTest.java
Modified:
/build.xml
/src/main/java/org/apache/cassandra/cql/jdbc/AbstractStatement.java
/src/main/java/org/apache/cassandra/cql/jdbc/CassandraPreparedStatement.java
/src/main/resources/log4j.properties
/src/test/java/org/apache/cassandra/cql/ConnectionDetails.java
/src/test/java/org/apache/cassandra/cql/JdbcDriverTest.java
/src/test/java/org/apache/cassandra/cql/jdbc/DataSourceTest.java
/src/test/resources/log4j.properties
/src/test/resources/org/apache/cassandra/cql/ConnectionDetails.properties
=======================================
--- /dev/null
+++ /src/main/java/org/apache/cassandra/cql/jdbc/HandleObjects.java Sat Dec
17 20:01:00 2011
@@ -0,0 +1,133 @@
+/*
+ *
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+package org.apache.cassandra.cql.jdbc;
+
+import java.io.ByteArrayOutputStream;
+import java.io.IOException;
+import java.io.ObjectOutput;
+import java.io.ObjectOutputStream;
+import java.math.BigDecimal;
+import java.math.BigInteger;
+import java.nio.ByteBuffer;
+import java.sql.SQLException;
+import java.sql.SQLNonTransientException;
+import java.sql.Types;
+
+import org.apache.cassandra.utils.ByteBufferUtil;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+/**
+ * @author rickshaw
+ *
+ */
+public class HandleObjects
+{
+ private static final Logger LOG =
LoggerFactory.getLogger(HandleObjects.class);
+
+ private static final String BAD_MAPPING = "encountered object of
class: %s, but only '%s' is supported to map to %s";
+
+
+ private static final SQLException makeBadMapping(Class<?> badclass,
String javatype, String jdbctype)
+ {
+ return new SQLNonTransientException(String.format(BAD_MAPPING,
badclass, javatype, jdbctype));
+ }
+
+ private static final String bufferAsHex(ByteBuffer buffer)
+ {
+ return ByteBufferUtil.bytesToHex(buffer);
+ }
+
+ private static final String javaObject(Object object) throws
SQLException
+ {
+ byte[] bytes = null;
+ try
+ {
+ // Serialize to a byte array
+ ByteArrayOutputStream bos = new ByteArrayOutputStream();
+ ObjectOutput out = new ObjectOutputStream(bos);
+ out.writeObject(object);
+ out.close();
+
+ // Get the bytes of the serialized object
+ bytes = bos.toByteArray();
+ }
+ catch (IOException e)
+ {
+ throw new SQLNonTransientException("Problem serializing the
Java object", e);
+ }
+
+ return bufferAsHex(ByteBuffer.wrap(bytes));
+ }
+
+
+ public static final String makeString(Object object, int
targetSqlType, int scaleOrLength) throws SQLException
+ {
+ Class<? extends Object> objectClass = object.getClass();
+
+ // see if we can map to an supported AbstractType
+ switch (targetSqlType)
+ {
+ case Types.JAVA_OBJECT:
+ return javaObject(object);
+
+ case Types.BINARY:
+ case Types.VARBINARY:
+ case Types.LONGVARBINARY:
+ if (objectClass.isAssignableFrom(ByteBuffer.class))
+ {
+ return bufferAsHex(((ByteBuffer) object));
+ }
+ else throw
makeBadMapping(objectClass, "ByteBuffer", "BINARY");
+
+ case Types.CHAR:
+ case Types.VARCHAR:
+ case Types.LONGVARCHAR:
+ case Types.NVARCHAR:
+ case Types.LONGNVARCHAR:
+ if (objectClass.isAssignableFrom(String.class))
+ {
+ return object.toString();
+ }
+ else throw makeBadMapping(objectClass, "String", "the
various VARCHAR types");
+
+ case Types.INTEGER:
+ // Strings should always work
+ if (objectClass == String.class) return object.toString();
+
+ // Only Numeric classes (besides String)
+ if (!Number.class.isAssignableFrom(object.getClass()))
throw makeBadMapping(objectClass, "a Numeric class (or String)", "INTEGER");
+
+ // All the integer (non floating-point) are simple
+ if (objectClass == Integer.class || objectClass ==
BigInteger.class || objectClass == Long.class ||
+ objectClass == Short.class || objectClass ==
Byte.class) return object.toString();
+
+ // Floating ones need to just pass the integer part
+ else if (objectClass == Double.class) return
Integer.valueOf(((Double) object).intValue()).toString();
+ else if (objectClass == Float.class) return
Integer.valueOf(((Float) object).intValue()).toString();
+ else if (objectClass == BigDecimal.class) return
Integer.valueOf(((BigDecimal) object).intValue()).toString();
+
+ default:
+ LOG.warn("Unhandled JDBC type: "+targetSqlType);
+ return null;
+ }
+ }
+}
=======================================
--- /dev/null
+++ /src/test/java/org/apache/cassandra/cql/TestClass.java Sat Dec 17
20:01:00 2011
@@ -0,0 +1,23 @@
+package org.apache.cassandra.cql;
+
+import java.io.Serializable;
+import java.util.List;
+
+public class TestClass implements Serializable
+{
+ private static final long serialVersionUID = 1L;
+ String s;
+ Integer i;
+ List<String> l;
+
+ public TestClass(String s, Integer i, List<String>l)
+ {
+ this.s = s;
+ this.i = i;
+ this.l = l;
+ }
+ public String toString()
+ {
+ return String.format("TestClass(%s, %d, %s)", s,i,l);
+ }
+}
=======================================
--- /dev/null
+++ /src/test/java/org/apache/cassandra/cql/jdbc/HandleObjectsUnitTest.java
Sat Dec 17 20:01:00 2011
@@ -0,0 +1,87 @@
+/*
+ *
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ *
+ */
+package org.apache.cassandra.cql.jdbc;
+
+import static org.junit.Assert.*;
+
+import java.io.Serializable;
+import java.math.BigDecimal;
+import java.sql.SQLException;
+import java.sql.Types;
+import java.util.ArrayList;
+import java.util.List;
+
+import org.apache.cassandra.cql.TestClass;
+import org.junit.BeforeClass;
+import org.junit.Test;
+
+/**
+ * @author rickshaw
+ *
+ */
+public class HandleObjectsUnitTest
+{
+
+ /**
+ * @throws java.lang.Exception
+ */
+ @BeforeClass
+ public static void setUpBeforeClass() throws Exception
+ {}
+
+ @Test
+ public void test1Varchar() throws SQLException
+ {
+ Object object = new String("This is a String");
+ String string = HandleObjects.makeString(object, Types.VARCHAR, 0);
+ assertEquals("This is a String", string);
+ }
+
+
+ @Test
+ public void test2Integer() throws SQLException
+ {
+ Object object = new Integer(12345);
+ String string = HandleObjects.makeString(object, Types.INTEGER, 0);
+ assertEquals("12345", string);
+
+ object = new Long(123457890);
+ string = HandleObjects.makeString(object, Types.INTEGER, 0);
+ assertEquals("123457890", string);
+
+ object = new BigDecimal(123457890.789);
+ string = HandleObjects.makeString(object, Types.INTEGER, 0);
+ assertEquals("123457890", string);
+ }
+
+ @Test
+ public void test9JavaObject() throws SQLException
+ {
+ List<String> myList = new ArrayList<String>();
+ myList.add("A");
+ myList.add("B");
+ myList.add("C");
+ Object object = new TestClass("This is a String", 3456,myList );
+ String string = HandleObjects.makeString(object,
Types.JAVA_OBJECT, 0);
+ System.out.println("Java object = "+ string);
+ }
+
+}
=======================================
--- /build.xml Tue Nov 1 09:05:39 2011
+++ /build.xml Sat Dec 17 20:01:00 2011
@@ -190,10 +190,9 @@
<target name="test" depends="build-test">
<junit fork="on" forkmode="perTest" timeout="${test.timeout}"
- showoutput="true" maxmemory="1024m"
failureproperty="test.failed">
+ showoutput="false" maxmemory="1024m"
failureproperty="test.failed">
<formatter type="brief" usefile="false"/>
<jvmarg value="-Dstorage-config=${test.dir}/conf" />
- <jvmarg value="-Dlog4j.configuration=log4j-junit.properties" />
<jvmarg value="-Dlegacy-sstable-root=${test.data}/legacy-sstables" />
<jvmarg value="-ea" />
<classpath>
=======================================
--- /src/main/java/org/apache/cassandra/cql/jdbc/AbstractStatement.java Thu
Dec 1 10:31:03 2011
+++ /src/main/java/org/apache/cassandra/cql/jdbc/AbstractStatement.java Sat
Dec 17 20:01:00 2011
@@ -198,16 +198,16 @@
throw new SQLFeatureNotSupportedException(NOT_SUPPORTED);
}
- public void setObject(int parameterIndex, Object x, int targetSqlType)
throws SQLException
- {
- throw new SQLFeatureNotSupportedException(NOT_SUPPORTED);
- }
+// public void setObject(int parameterIndex, Object x, int
targetSqlType) throws SQLException
+// {
+// throw new SQLFeatureNotSupportedException(NOT_SUPPORTED);
+// }
- public void setObject(int parameterIndex, Object x, int targetSqlType,
int scaleOrLength) throws SQLException
- {
- throw new SQLFeatureNotSupportedException(NOT_SUPPORTED);
- }
+// public void setObject(int parameterIndex, Object x, int
targetSqlType, int scaleOrLength) throws SQLException
+// {
+// throw new SQLFeatureNotSupportedException(NOT_SUPPORTED);
+// }
=======================================
---
/src/main/java/org/apache/cassandra/cql/jdbc/CassandraPreparedStatement.java
Mon Dec 12 14:45:57 2011
+++
/src/main/java/org/apache/cassandra/cql/jdbc/CassandraPreparedStatement.java
Sat Dec 17 20:01:00 2011
@@ -30,6 +30,7 @@
import java.io.ObjectOutput;
import java.io.ObjectOutputStream;
import java.math.BigDecimal;
+import java.math.BigInteger;
import java.net.URL;
import java.nio.ByteBuffer;
import java.sql.Date;
@@ -39,6 +40,7 @@
import java.sql.ResultSetMetaData;
import java.sql.RowId;
import java.sql.SQLException;
+import java.sql.SQLFeatureNotSupportedException;
import java.sql.SQLNonTransientConnectionException;
import java.sql.SQLNonTransientException;
import java.sql.SQLRecoverableException;
@@ -46,6 +48,7 @@
import java.sql.SQLTransientConnectionException;
import java.sql.Time;
import java.sql.Timestamp;
+import java.sql.Types;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.LinkedHashMap;
@@ -121,6 +124,7 @@
return values;
}
+
public void close() throws SQLException
{
connection.removeStatement(this);
@@ -174,8 +178,7 @@
public void addBatch() throws SQLException
{
- // TODO Auto-generated method stub
-
+ throw new SQLFeatureNotSupportedException(NOT_SUPPORTED);
}
@@ -214,15 +217,13 @@
public ResultSetMetaData getMetaData() throws SQLException
{
- // TODO Auto-generated method stub
- return null;
+ throw new SQLFeatureNotSupportedException(NOT_SUPPORTED);
}
public ParameterMetaData getParameterMetaData() throws SQLException
{
- // TODO Auto-generated method stub
- return null;
+ throw new SQLFeatureNotSupportedException(NOT_SUPPORTED);
}
@@ -331,30 +332,27 @@
public void setObject(int parameterIndex, Object object) throws
SQLException
+ {
+ // For now all objects are forced to String type
+ setObject(parameterIndex,object,Types.VARCHAR,0);
+ }
+
+ public void setObject(int parameterIndex, Object object, int
targetSqlType) throws SQLException
+ {
+ setObject(parameterIndex,object,targetSqlType,0);
+ }
+
+ public final void setObject(int parameterIndex, Object object, int
targetSqlType, int scaleOrLength) throws SQLException
{
checkNotClosed();
checkIndex(parameterIndex);
- byte[] bytes = null;
- try
- {
- // Serialize to a byte array
- ByteArrayOutputStream bos = new ByteArrayOutputStream() ;
- ObjectOutput out = new ObjectOutputStream(bos) ;
- out.writeObject(object);
- out.close();
-
- // Get the bytes of the serialized object
- bytes = bos.toByteArray();
- }
- catch (IOException e)
- {
- throw new SQLNonTransientException("Problem serializing the
object", e);
- }
-
- bindValues.put(parameterIndex,
ByteBufferUtil.bytesToHex(ByteBuffer.wrap(bytes)));
- }
-
+ String variable = HandleObjects.makeString(object, targetSqlType,
scaleOrLength);
+
+ if (variable==null) throw new SQLNonTransientException("Problem
mapping object to JDBC Type");
+
+ bindValues.put(parameterIndex, variable);
+ }
public void setRowId(int parameterIndex, RowId value) throws
SQLException
{
=======================================
--- /src/main/resources/log4j.properties Thu Dec 1 10:31:03 2011
+++ /src/main/resources/log4j.properties Sat Dec 17 20:01:00 2011
@@ -1,7 +1,7 @@
# Test Log4J Properties File
log4j.rootLogger=WARN, stdout
-log4j.logger.org.apache.cassandra.cql.jdbc=TRACE
+log4j.logger.org.apache.cassandra.cql.jdbc=INFO
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
=======================================
--- /src/test/java/org/apache/cassandra/cql/ConnectionDetails.java Thu Oct
13 01:56:33 2011
+++ /src/test/java/org/apache/cassandra/cql/ConnectionDetails.java Sat Dec
17 20:01:00 2011
@@ -29,6 +29,10 @@
// ignore
}
}
+ Properties sys = System.getProperties();
+// for (Object key : sys.keySet())
+// System.out.printf("%s => %s%n",key,sys.get(key));
+
host = p.getProperty("host", "localhost");
int port;
try {
=======================================
--- /src/test/java/org/apache/cassandra/cql/JdbcDriverTest.java Thu Oct 13
01:56:33 2011
+++ /src/test/java/org/apache/cassandra/cql/JdbcDriverTest.java Sat Dec 17
20:01:00 2011
@@ -110,22 +110,43 @@
assertEquals(valuCaseSense, md.isCaseSensitive(col));
}
- @Test(expected=SQLNonTransientConnectionException.class)
+ @Test
public void testNoHost() throws SQLException
{
- DriverManager.getConnection("jdbc:cassandra:localhost");
+ try
+ {
+ DriverManager.getConnection("jdbc:cassandra:localhost");
+ }
+ catch (Exception e)
+ {
+ assertEquals(SQLNonTransientConnectionException.class,
e.getClass());
+ }
}
- @Test(expected=SQLNonTransientConnectionException.class)
+ @Test
public void testBadKeyspace() throws SQLException
{
- DriverManager.getConnection("jdbc:cassandra://localhost/Keysp@ce");
+ try
+ {
+
DriverManager.getConnection("jdbc:cassandra://localhost/Keysp@ce");
+ }
+ catch (Exception e)
+ {
+ assertEquals(SQLNonTransientConnectionException.class,
e.getClass());
+ }
}
- @Test(expected=SQLNonTransientConnectionException.class)
+ @Test
public void testBadUserinfo() throws SQLException
{
-
DriverManager.getConnection("jdbc:cassandra://root;root@localhost");
+ try
+ {
+
DriverManager.getConnection("jdbc:cassandra://root;root@localhost");
+ }
+ catch (Exception e)
+ {
+ assertEquals(SQLNonTransientConnectionException.class,
e.getClass());
+ }
}
@Test
@@ -304,7 +325,7 @@
String badKey = bytesToHex(String.format("jsmith-%s",
System.currentTimeMillis()).getBytes());
selectQ = "SELECT 1, 2 FROM JdbcInteger WHERE KEY IN ('" + badKey
+ "', '" + jsmith + "')";
- checkResultSet(stmt.executeQuery(selectQ), "Int", 1,
keys, "1", "2");
+ checkResultSet(stmt.executeQuery(selectQ), "Int", 0,
keys, "1", "2");
}
@Test
@@ -349,7 +370,7 @@
String badKey = bytesToHex(String.format("jsmith-%s",
System.currentTimeMillis()).getBytes());
selectQ = "SELECT 1, 2 FROM JdbcInteger WHERE KEY IN ('" + badKey
+ "', '" + jsmith + "')";
- checkResultSet(executePreparedStatementWithResults(con,
selectQ), "Int", 1, keys, "1", "2");
+ checkResultSet(executePreparedStatementWithResults(con,
selectQ), "Int", 0, keys, "1", "2");
}
/* Method to test with Delete statement. */
=======================================
--- /src/test/java/org/apache/cassandra/cql/jdbc/DataSourceTest.java Thu
Oct 13 01:56:33 2011
+++ /src/test/java/org/apache/cassandra/cql/jdbc/DataSourceTest.java Sat
Dec 17 20:01:00 2011
@@ -51,23 +51,23 @@
DataSource ds = new
CassandraDataSource(HOST,PORT,KEYSPACE,USER,PASSWORD);
assertNotNull(ds);
- PrintWriter pw = new PrintWriter(System.err);
+// PrintWriter pw = new PrintWriter(System.err);
// null username and password
java.sql.Connection cnx = ds.getConnection(null, null);
assertFalse(cnx.isClosed());
ds.setLoginTimeout(5);
assertEquals(5, ds.getLoginTimeout());
- ds.setLogWriter(pw);
- assertNotNull(ds.getLogWriter());
+// ds.setLogWriter(pw);
+// assertNotNull(ds.getLogWriter());
// no username and password
cnx = ds.getConnection();
assertFalse(cnx.isClosed());
ds.setLoginTimeout(5);
assertEquals(5, ds.getLoginTimeout());
- ds.setLogWriter(pw);
- assertNotNull(ds.getLogWriter());
+// ds.setLogWriter(pw);
+// assertNotNull(ds.getLogWriter());
}
=======================================
--- /src/test/resources/log4j.properties Mon Nov 21 14:37:51 2011
+++ /src/test/resources/log4j.properties Sat Dec 17 20:01:00 2011
@@ -1,7 +1,7 @@
# Test Log4J Properties File
log4j.rootLogger=WARN, stdout
-log4j.logger.org.apache.cassandra.cql.jdbc=TRACE
+log4j.logger.org.apache.cassandra.cql.jdbc=INFO
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
=======================================
---
/src/test/resources/org/apache/cassandra/cql/ConnectionDetails.properties
Thu Oct 13 13:15:22 2011
+++
/src/test/resources/org/apache/cassandra/cql/ConnectionDetails.properties
Sat Dec 17 20:01:00 2011
@@ -1,2 +1,3 @@
-port=${cassandra.rpc.port}
+#port=${cassandra.rpc.port}
host=${cassandra.host}
+port=9160
==============================================================================
Revision: 75ddfb82001c
Author: Rick Shaw <wf...@gmail.com>
Date: Wed Dec 21 20:57:28 2011
Log: Merge branch 'new-prepared' into trunk
Conflicts:
pom.xml
src/test/java/org/apache/cassandra/cql/JdbcDriverTest.java
src/test/java/org/apache/cassandra/cql/jdbc/DataSourceTest.java
Signed-off-by: Rick Shaw <wf...@gmail.com>
http://code.google.com/a/apache-extras.org/p/cassandra-jdbc/source/detail?r=75ddfb82001c
Modified:
/build.xml
/pom.xml
/src/main/java/org/apache/cassandra/cql/jdbc/CassandraConnection.java
/src/test/java/org/apache/cassandra/cql/ConnectionDetails.java
/src/test/java/org/apache/cassandra/cql/JdbcDriverTest.java
/src/test/java/org/apache/cassandra/cql/jdbc/DataSourceTest.java
/src/test/java/org/apache/cassandra/cql/jdbc/PreparedStatementTest.java
=======================================
--- /build.xml Tue Nov 1 09:05:39 2011
+++ /build.xml Wed Dec 21 20:57:28 2011
@@ -36,7 +36,7 @@
<property name="debuglevel" value="source,lines,vars" />
<property name="test.name" value="*Test" />
<property name="test.timeout" value="60000" />
- <property name="base.version" value="1.0.5" />
+ <property name="base.version" value="1.1-dev" />
<condition property="version" value="${base.version}">
<isset property="release" />
@@ -190,10 +190,9 @@
<target name="test" depends="build-test">
<junit fork="on" forkmode="perTest" timeout="${test.timeout}"
- showoutput="true" maxmemory="1024m"
failureproperty="test.failed">
+ showoutput="false" maxmemory="1024m"
failureproperty="test.failed">
<formatter type="brief" usefile="false"/>
<jvmarg value="-Dstorage-config=${test.dir}/conf" />
- <jvmarg value="-Dlog4j.configuration=log4j-junit.properties" />
<jvmarg value="-Dlegacy-sstable-root=${test.data}/legacy-sstables" />
<jvmarg value="-ea" />
<classpath>
=======================================
--- /pom.xml Tue Dec 20 21:22:20 2011
+++ /pom.xml Wed Dec 21 20:57:28 2011
@@ -30,7 +30,7 @@
<groupId>org.apache-extras.cassandra-jdbc</groupId>
<artifactId>cassandra-jdbc</artifactId>
- <version>1.0.5-SNAPSHOT</version>
+ <version>1.1-dev-SNAPSHOT</version>
<name>JDBC driver for Cassandra/CQL</name>
<description>A JDBC-compliant driver for Cassandra using
CQL.</description>
@@ -98,7 +98,7 @@
<dependency>
<groupId>org.apache.cassandra</groupId>
<artifactId>cassandra-thrift</artifactId>
- <version>1.0.6</version>
+ <version>1.1-dev-SNAPSHOT</version>
<exclusions>
<exclusion>
<groupId>javax.servlet</groupId>
@@ -113,7 +113,7 @@
<dependency>
<groupId>org.apache.cassandra</groupId>
<artifactId>cassandra-clientutil</artifactId>
- <version>1.0.6</version>
+ <version>1.1-dev-SNAPSHOT</version>
</dependency>
<dependency>
<groupId>com.google.guava</groupId>
=======================================
--- /src/main/java/org/apache/cassandra/cql/jdbc/CassandraConnection.java
Tue Dec 6 10:14:48 2011
+++ /src/main/java/org/apache/cassandra/cql/jdbc/CassandraConnection.java
Wed Dec 21 20:57:28 2011
@@ -22,6 +22,7 @@
import java.sql.*;
import java.util.HashMap;
+import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.Set;
@@ -408,11 +409,55 @@
* @throws SchemaDisagreementException when the client side and server
side are at different versions of schema (Thrift)
* @throws TException when there is a error in Thrift
processing
*/
- protected CqlResult execute(String queryStr) throws
InvalidRequestException, UnavailableException, TimedOutException,
SchemaDisagreementException, TException
+ protected CqlResult execute(String queryStr)
+ throws InvalidRequestException, UnavailableException,
TimedOutException, SchemaDisagreementException, TException
{
return execute(queryStr, defaultCompression);
}
+ protected CqlResult execute(int itemId, List<String> values)
+ throws InvalidRequestException, UnavailableException,
TimedOutException, SchemaDisagreementException, TException
+ {
+ try
+ {
+ return client.execute_prepared_cql_query(itemId, values);
+ }
+ catch (TException error)
+ {
+ numFailures++;
+ timeOfLastFailure = System.currentTimeMillis();
+ throw error;
+ }
+ }
+
+ protected CqlPreparedResult prepare(String queryStr, Compression
compression)throws InvalidRequestException, TException
+ {
+ try
+ {
+ return client.prepare_cql_query(Utils.compressQuery(queryStr,
compression), compression);
+ }
+ catch (TException error)
+ {
+ numFailures++;
+ timeOfLastFailure = System.currentTimeMillis();
+ throw error;
+ }
+ }
+
+ protected CqlPreparedResult prepare(String queryStr) throws
InvalidRequestException, TException
+ {
+ try
+ {
+ return prepare(queryStr, defaultCompression);
+ }
+ catch (TException error)
+ {
+ numFailures++;
+ timeOfLastFailure = System.currentTimeMillis();
+ throw error;
+ }
+ }
+
/**
* Remove a Statement from the Open Statements List
*/
=======================================
--- /src/test/java/org/apache/cassandra/cql/ConnectionDetails.java Thu Oct
13 01:56:33 2011
+++ /src/test/java/org/apache/cassandra/cql/ConnectionDetails.java Wed Dec
21 20:57:28 2011
@@ -29,6 +29,7 @@
// ignore
}
}
+
host = p.getProperty("host", "localhost");
int port;
try {
=======================================
--- /src/test/java/org/apache/cassandra/cql/JdbcDriverTest.java Tue Dec 13
15:21:15 2011
+++ /src/test/java/org/apache/cassandra/cql/JdbcDriverTest.java Wed Dec 21
20:57:28 2011
@@ -111,22 +111,43 @@
assertEquals(valuCaseSense, md.isCaseSensitive(col));
}
- @Test(expected=SQLNonTransientConnectionException.class)
+ @Test
public void testNoHost() throws SQLException
{
- DriverManager.getConnection("jdbc:cassandra:localhost");
+ try
+ {
+ DriverManager.getConnection("jdbc:cassandra:localhost");
+ }
+ catch (Exception e)
+ {
+ assertEquals(SQLNonTransientConnectionException.class,
e.getClass());
+ }
}
- @Test(expected=SQLNonTransientConnectionException.class)
+ @Test
public void testBadKeyspace() throws SQLException
{
- DriverManager.getConnection("jdbc:cassandra://localhost/Keysp@ce");
+ try
+ {
+
DriverManager.getConnection("jdbc:cassandra://localhost/Keysp@ce");
+ }
+ catch (Exception e)
+ {
+ assertEquals(SQLNonTransientConnectionException.class,
e.getClass());
+ }
}
- @Test(expected=SQLNonTransientConnectionException.class)
+ @Test
public void testBadUserinfo() throws SQLException
{
-
DriverManager.getConnection("jdbc:cassandra://root;root@localhost");
+ try
+ {
+
DriverManager.getConnection("jdbc:cassandra://root;root@localhost");
+ }
+ catch (Exception e)
+ {
+ assertEquals(SQLNonTransientConnectionException.class,
e.getClass());
+ }
}
@Test
@@ -305,6 +326,10 @@
selectQ = "SELECT 1, 2 FROM JdbcInteger1 WHERE id IN (rowOne,
badRow)";
checkResultSet(stmt.executeQuery(selectQ), "String", 1,
keys, "1", "2");
+
+// String badKey = bytesToHex(String.format("jsmith-%s",
System.currentTimeMillis()).getBytes());
+// selectQ = "SELECT 1, 2 FROM JdbcInteger WHERE KEY IN ('" +
badKey + "', '" + jsmith + "')";
+// checkResultSet(stmt.executeQuery(selectQ), "Int", 0,
keys, "1", "2");
}
@Test
@@ -349,6 +374,10 @@
selectQ = "SELECT 1, 2 FROM JdbcInteger1 WHERE id IN (rowOne,
badRow)";
checkResultSet(executePreparedStatementWithResults(con,
selectQ), "String", 1, keys, "1", "2");
+
+// String badKey = bytesToHex(String.format("jsmith-%s",
System.currentTimeMillis()).getBytes());
+// selectQ = "SELECT 1, 2 FROM JdbcInteger WHERE KEY IN ('" +
badKey + "', '" + jsmith + "')";
+// checkResultSet(executePreparedStatementWithResults(con,
selectQ), "Int", 0, keys, "1", "2");
}
/* Method to test with Delete statement. */
=======================================
--- /src/test/java/org/apache/cassandra/cql/jdbc/DataSourceTest.java Mon
Dec 19 09:03:13 2011
+++ /src/test/java/org/apache/cassandra/cql/jdbc/DataSourceTest.java Wed
Dec 21 20:57:28 2011
@@ -51,19 +51,25 @@
DataSource ds = new
CassandraDataSource(HOST,PORT,KEYSPACE,USER,PASSWORD);
assertNotNull(ds);
- PrintWriter pw = new PrintWriter(System.err);
+// PrintWriter pw = new PrintWriter(System.err);
// null username and password
java.sql.Connection cnx = ds.getConnection(null, null);
assertFalse(cnx.isClosed());
ds.setLoginTimeout(5);
assertEquals(5, ds.getLoginTimeout());
+
+// ds.setLogWriter(pw);
+// assertNotNull(ds.getLogWriter());
// no username and password
cnx = ds.getConnection();
assertFalse(cnx.isClosed());
ds.setLoginTimeout(5);
assertEquals(5, ds.getLoginTimeout());
+
+// ds.setLogWriter(pw);
+// assertNotNull(ds.getLogWriter());
}
=======================================
--- /src/test/java/org/apache/cassandra/cql/jdbc/PreparedStatementTest.java
Tue Dec 13 15:21:15 2011
+++ /src/test/java/org/apache/cassandra/cql/jdbc/PreparedStatementTest.java
Wed Dec 21 20:57:28 2011
@@ -38,7 +38,9 @@
public class PreparedStatementTest
{
private static java.sql.Connection con = null;
- private static final Schema schema = new
Schema(ConnectionDetails.getHost(), ConnectionDetails.getPort());
+
+// private static final Schema schema = new
Schema(ConnectionDetails.getHost(), ConnectionDetails.getPort());
+ private static final Schema schema = new Schema("localhost", 9160);
@BeforeClass
public static void waxOn() throws Exception
@@ -46,6 +48,7 @@
schema.createSchema();
Class.forName("org.apache.cassandra.cql.jdbc.CassandraDriver");
con =
DriverManager.getConnection(String.format("jdbc:cassandra://%s:%d/%s",
ConnectionDetails.getHost(), ConnectionDetails.getPort(),
Schema.KEYSPACE_NAME));
+// con =
DriverManager.getConnection(String.format("jdbc:cassandra://%s:%d/%s", "localhost",
9160, Schema.KEYSPACE_NAME));
}
@Test
@@ -350,38 +353,6 @@
}
}
- @Test
- public void testParamSubstitution() throws SQLException
- {
- byte[] key = "key".getBytes();
- String q = "SELECT 'fo??est', ?, ? from JdbcUtf8 WHERE KEY = ?";
- CassandraPreparedStatement stmt =
(CassandraPreparedStatement)con.prepareStatement(q);
- stmt.setString(1, "pathological param: ?'make it?? '' sto'p?'");
- stmt.setString(2, "simple");
- stmt.setBytes(3, key);
- String qq = stmt.makeCql();
- assert qq.equals("SELECT 'fo??est', 'pathological param: ?''make
it?? '''' sto''p?''', 'simple' from JdbcUtf8 WHERE KEY = '6b6579'");
-
- q = "UPDATE JdbcUtf8 USING CONSISTENCY ONE
SET 'fru??us'=?, ?='gr''d?', ?=?, ?=? WHERE key=?";
- stmt = (CassandraPreparedStatement)con.prepareStatement(q);
- stmt.setString(1, "o?e");
- stmt.setString(2, "tw'o");
- stmt.setString(3, "thr'?'ee");
- stmt.setString(4, "fo''?'ur");
- stmt.setString(5, "five");
- stmt.setString(6, "six");
- stmt.setBytes(7, key);
- qq = stmt.makeCql();
- assert qq.equals("UPDATE JdbcUtf8 USING CONSISTENCY ONE
SET 'fru??us'='o?e', 'tw''o'='gr''d?', 'thr''?''ee'='fo''''?''ur', 'five'='six'
WHERE key='6b6579'");
-
- q = "DELETE ?, ? FROM JdbcUtf8 WHERE KEY=?";
- stmt = (CassandraPreparedStatement)con.prepareStatement(q);
- stmt.setString(1, "on'?'");
- stmt.setString(2, "two");
- stmt.setBytes(3, key);
- qq = stmt.makeCql();
- assert qq.equals("DELETE 'on''?''', 'two' FROM JdbcUtf8 WHERE
KEY='6b6579'");
- }
/**
* Copy bytes from int into bytes starting from offset.
==============================================================================
Revision: a18986c3e555
Author: Rick Shaw <wf...@gmail.com>
Date: Wed Dec 21 21:12:23 2011
Log: Rename the interface CassandraResultSet to
CassandraResultSetExtras
This name better signifies the interfaces purpose and will allow us to
rename CResultSet to CassandraResultSet to be consistent with naming
the JDBC implementations by prefixing 'Cassandra' to the JDBC interface
names.
Signed-off-by: Rick Shaw <wf...@gmail.com>
http://code.google.com/a/apache-extras.org/p/cassandra-jdbc/source/detail?r=a18986c3e555
Added:
/src/main/java/org/apache/cassandra/cql/jdbc/CassandraResultSetExtras.java
Deleted:
/src/main/java/org/apache/cassandra/cql/jdbc/CassandraResultSet.java
Modified:
/src/main/java/org/apache/cassandra/cql/jdbc/CResultSet.java
/src/test/java/org/apache/cassandra/cql/JdbcDriverTest.java
=======================================
--- /dev/null
+++
/src/main/java/org/apache/cassandra/cql/jdbc/CassandraResultSetExtras.java
Wed Dec 21 21:12:23 2011
@@ -0,0 +1,43 @@
+package org.apache.cassandra.cql.jdbc;
+/*
+ *
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ *
+ */
+
+import java.math.BigInteger;
+import java.sql.ResultSet;
+import java.sql.SQLException;
+
+public interface CassandraResultSetExtras extends ResultSet
+{
+ /**
+ * @return the current row key
+ */
+ public byte[] getKey()throws SQLException;;
+
+ /** @return a BigInteger value for the given column offset*/
+ public BigInteger getBigInteger(int i) throws SQLException;
+ /** @return a BigInteger value for the given column name */
+ public BigInteger getBigInteger(String name) throws SQLException;
+
+ /** @return the raw column data for the given column offset */
+ public TypedColumn getColumn(int i) throws SQLException;
+ /** @return the raw column data for the given column name */
+ public TypedColumn getColumn(String name) throws SQLException;
+}
=======================================
--- /src/main/java/org/apache/cassandra/cql/jdbc/CassandraResultSet.java
Thu Oct 13 00:45:22 2011
+++ /dev/null
@@ -1,43 +0,0 @@
-package org.apache.cassandra.cql.jdbc;
-/*
- *
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- *
- */
-
-import java.math.BigInteger;
-import java.sql.ResultSet;
-import java.sql.SQLException;
-
-public interface CassandraResultSet extends ResultSet
-{
- /**
- * @return the current row key
- */
- public byte[] getKey()throws SQLException;;
-
- /** @return a BigInteger value for the given column offset*/
- public BigInteger getBigInteger(int i) throws SQLException;
- /** @return a BigInteger value for the given column name */
- public BigInteger getBigInteger(String name) throws SQLException;
-
- /** @return the raw column data for the given column offset */
- public TypedColumn getColumn(int i) throws SQLException;
- /** @return the raw column data for the given column name */
- public TypedColumn getColumn(String name) throws SQLException;
-}
=======================================
--- /src/main/java/org/apache/cassandra/cql/jdbc/CResultSet.java Mon Dec 19
09:03:13 2011
+++ /src/main/java/org/apache/cassandra/cql/jdbc/CResultSet.java Wed Dec 21
21:12:23 2011
@@ -57,7 +57,7 @@
* </table>
*
*/
-class CResultSet extends AbstractResultSet implements CassandraResultSet
+class CResultSet extends AbstractResultSet implements
CassandraResultSetExtras
{
public static final int DEFAULT_TYPE = ResultSet.TYPE_FORWARD_ONLY;
public static final int DEFAULT_CONCURRENCY =
ResultSet.CONCUR_READ_ONLY;
@@ -906,7 +906,7 @@
public boolean isWrapperFor(Class<?> iface) throws SQLException
{
- return CassandraResultSet.class.isAssignableFrom(iface);
+ return CassandraResultSetExtras.class.isAssignableFrom(iface);
}
// Navigation between rows within the returned set of rows
@@ -988,7 +988,7 @@
public <T> T unwrap(Class<T> iface) throws SQLException
{
- if (iface.equals(CassandraResultSet.class)) return (T) this;
+ if (iface.equals(CassandraResultSetExtras.class)) return (T) this;
throw new
SQLFeatureNotSupportedException(String.format(NO_INTERFACE,
iface.getSimpleName()));
}
=======================================
--- /src/test/java/org/apache/cassandra/cql/JdbcDriverTest.java Wed Dec 21
20:57:28 2011
+++ /src/test/java/org/apache/cassandra/cql/JdbcDriverTest.java Wed Dec 21
21:12:23 2011
@@ -30,7 +30,7 @@
import java.util.Iterator;
import java.util.List;
-import org.apache.cassandra.cql.jdbc.CassandraResultSet;
+import org.apache.cassandra.cql.jdbc.CassandraResultSetExtras;
import org.apache.cassandra.cql.jdbc.JdbcAscii;
import org.apache.cassandra.cql.jdbc.JdbcBytes;
import org.apache.cassandra.cql.jdbc.JdbcInteger;
@@ -484,7 +484,7 @@
int actualRows = 0;
assert rs != null;
Iterator<String> keyIter = (keys == null) ? null : keys.iterator();
- CassandraResultSet cassandraRs = (CassandraResultSet)rs;
+ CassandraResultSetExtras cassandraRs =
(CassandraResultSetExtras)rs;
while (rs.next())
{
actualRows++;
==============================================================================
Revision: dbae7bf74566
Author: Rick Shaw <wf...@gmail.com>
Date: Wed Dec 21 21:16:09 2011
Log: Rename CResultSet to CassandraResultSet
This will to be consistent with naming the JDBC implementations by
prefixing 'Cassandra' to the JDBC interface names.
Signed-off-by: Rick Shaw <wf...@gmail.com>
http://code.google.com/a/apache-extras.org/p/cassandra-jdbc/source/detail?r=dbae7bf74566
Added:
/src/main/java/org/apache/cassandra/cql/jdbc/CassandraResultSet.java
Deleted:
/src/main/java/org/apache/cassandra/cql/jdbc/CResultSet.java
Modified:
/src/main/java/org/apache/cassandra/cql/jdbc/CassandraConnection.java
/src/main/java/org/apache/cassandra/cql/jdbc/CassandraDatabaseMetaData.java
/src/main/java/org/apache/cassandra/cql/jdbc/CassandraPreparedStatement.java
/src/main/java/org/apache/cassandra/cql/jdbc/CassandraStatement.java
=======================================
--- /dev/null
+++ /src/main/java/org/apache/cassandra/cql/jdbc/CassandraResultSet.java
Wed Dec 21 21:16:09 2011
@@ -0,0 +1,1150 @@
+/*
+ *
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ *
+ */
+package org.apache.cassandra.cql.jdbc;
+
+import static org.apache.cassandra.cql.jdbc.Utils.*;
+
+import java.math.BigDecimal;
+import java.math.BigInteger;
+import java.net.URL;
+import java.nio.ByteBuffer;
+import java.sql.*;
+import java.sql.Date;
+import java.util.*;
+
+import org.apache.cassandra.thrift.Column;
+import org.apache.cassandra.thrift.CqlMetadata;
+import org.apache.cassandra.thrift.CqlResult;
+import org.apache.cassandra.thrift.CqlRow;
+import org.apache.cassandra.utils.ByteBufferUtil;
+
+/**
+ * <p>The Supported Data types in CQL are as follows:</p>
+ * <table>
+ * <tr><th>type</th><th>java type</th><th>description</th></tr>
+ * <tr><td>ascii</td><td>String</td><td>ASCII character string</td></tr>
+ * <tr><td>bigint</td><td>Long</td><td>64-bit signed long</td></tr>
+ * <tr><td>blob</td><td>ByteBuffer</td><td>Arbitrary bytes (no
validation)</td></tr>
+ * <tr><td>boolean</td><td>Boolean</td><td>true or false</td></tr>
+ * <tr><td>counter</td><td>Long</td><td>Counter column (64-bit
long)</td></tr>
+ * <tr><td>decimal</td><td>BigDecimal</td><td>Variable-precision
decimal</td></tr>
+ * <tr><td>double</td><td>Double</td><td>64-bit IEEE-754 floating
point</td></tr>
+ * <tr><td>float</td><td>Float</td><td>32-bit IEEE-754 floating
point</td></tr>
+ * <tr><td>int</td><td>Integer</td><td>32-bit signed int</td></tr>
+ * <tr><td>text</td><td>String</td><td>UTF8 encoded string</td></tr>
+ * <tr><td>timestamp</td><td>Date</td><td>A timestamp</td></tr>
+ * <tr><td>uuid</td><td>UUID</td><td>Type 1 or type 4 UUID</td></tr>
+ * <tr><td>varchar</td><td>String</td><td>UTF8 encoded string</td></tr>
+ * <tr><td>varint</td><td>BigInteger</td><td>Arbitrary-precision
integer</td></tr>
+ * </table>
+ *
+ */
+class CassandraResultSet extends AbstractResultSet implements
CassandraResultSetExtras
+{
+ public static final int DEFAULT_TYPE = ResultSet.TYPE_FORWARD_ONLY;
+ public static final int DEFAULT_CONCURRENCY =
ResultSet.CONCUR_READ_ONLY;
+ public static final int DEFAULT_HOLDABILITY =
ResultSet.HOLD_CURSORS_OVER_COMMIT;
+
+ private final String keyspace;
+
+ /**
+ * The r set iter.
+ */
+ private Iterator<CqlRow> rSetIter;
+
+ int rowNumber = 0;
+ // the current row key when iterating through results.
+ private byte[] curRowKey = null;
+
+ /**
+ * The values.
+ */
+ private List<TypedColumn> values = new ArrayList<TypedColumn>();
+
+ /**
+ * The value map.
+ */
+ private Map<String, TypedColumn> valueMap = new HashMap<String,
TypedColumn>();
+
+ /**
+ * The index map.
+ */
+ private Map<String, Integer> indexMap = new HashMap<String, Integer>();
+
+ private final CResultSetMetaData meta;
+
+ private final Statement statement;
+
+ private int resultSetType;
+
+ private int fetchDirection;
+
+ private int fetchSize;
+
+ private boolean wasNull;
+
+ private CqlMetadata schema;
+
+ /**
+ * no argument constructor.
+ */
+ CassandraResultSet()
+ {
+ keyspace = null;
+ statement = null;
+ meta = new CResultSetMetaData();
+ }
+
+ /**
+ * Instantiates a new cassandra result set.
+ */
+ CassandraResultSet(Statement statement, CqlResult resultSet, String
keyspace) throws SQLException
+ {
+ this.statement = statement;
+ this.keyspace = keyspace;
+ this.resultSetType = statement.getResultSetType();
+ this.fetchDirection = statement.getFetchDirection();
+ this.fetchSize = statement.getFetchSize();
+ this.schema = resultSet.schema;
+
+ rSetIter = resultSet.getRowsIterator();
+ meta = new CResultSetMetaData();
+ }
+
+ public boolean absolute(int arg0) throws SQLException
+ {
+ throw new SQLFeatureNotSupportedException(NOT_SUPPORTED);
+ }
+
+ public void afterLast() throws SQLException
+ {
+ throw new SQLFeatureNotSupportedException(NOT_SUPPORTED);
+ }
+
+ public void beforeFirst() throws SQLException
+ {
+ throw new SQLFeatureNotSupportedException(NOT_SUPPORTED);
+ }
+
+ private final void checkIndex(int index) throws SQLException
+ {
+ // 1 <= index <= size()
+ if (index < 1 || index > values.size())
+ throw new
SQLSyntaxErrorException(String.format(MUST_BE_POSITIVE,
String.valueOf(index))+" "+values.size());
+ }
+
+ private final void checkName(String name) throws SQLException
+ {
+ if (valueMap.get(name) == null) throw new
SQLSyntaxErrorException(String.format(VALID_LABELS, name));
+ }
+
+ private final void checkNotClosed() throws SQLException
+ {
+ if (isClosed()) throw new SQLRecoverableException(WAS_CLOSED_RSLT);
+ }
+
+ public void clearWarnings() throws SQLException
+ {
+ // This implementation does not support the collection of warnings
so clearing is a no-op
+ // but it is still an exception to call this on a closed
connection.
+ checkNotClosed();
+ }
+
+ public void close() throws SQLException
+ {
+ valueMap = null;
+ values = null;
+ }
+
+ public int findColumn(String name) throws SQLException
+ {
+ checkNotClosed();
+ checkName(name);
+ return indexMap.get(name).intValue();
+ }
+
+ public boolean first() throws SQLException
+ {
+ throw new SQLFeatureNotSupportedException(NOT_SUPPORTED);
+ }
+
+
+ public BigDecimal getBigDecimal(int index) throws SQLException
+ {
+ checkIndex(index);
+ return getBigDecimal(values.get(index - 1));
+ }
+
+ /** @deprecated */
+ public BigDecimal getBigDecimal(int index, int scale) throws
SQLException
+ {
+ checkIndex(index);
+ return (getBigDecimal(values.get(index - 1))).setScale(scale);
+ }
+
+ public BigDecimal getBigDecimal(String name) throws SQLException
+ {
+ checkName(name);
+ return getBigDecimal(valueMap.get(name));
+ }
+
+ /** @deprecated */
+ public BigDecimal getBigDecimal(String name, int scale) throws
SQLException
+ {
+ checkName(name);
+ return (getBigDecimal(valueMap.get(name))).setScale(scale);
+ }
+
+ private BigDecimal getBigDecimal(TypedColumn column) throws
SQLException
+ {
+ checkNotClosed();
+ Object value = column.getValue();
+ wasNull = value == null;
+
+ if (wasNull) return BigDecimal.ZERO;
+
+ if (value instanceof BigDecimal) return (BigDecimal) value;
+
+ if (value instanceof Long) return BigDecimal.valueOf((Long) value);
+
+ if (value instanceof Double) return BigDecimal.valueOf((Double)
value);
+
+ if (value instanceof BigInteger) return new
BigDecimal((BigInteger) value);
+
+ try
+ {
+ if (value instanceof String) return (new BigDecimal((String)
value));
+ }
+ catch (NumberFormatException e)
+ {
+ throw new SQLSyntaxErrorException(e);
+ }
+
+ throw new SQLSyntaxErrorException(String.format(NOT_TRANSLATABLE,
value.getClass().getSimpleName(), "BigDecimal"));
+ }
+ public BigInteger getBigInteger(int index) throws SQLException
+ {
+ checkIndex(index);
+ return getBigInteger(values.get(index - 1));
+ }
+
+ public BigInteger getBigInteger(String name) throws SQLException
+ {
+ checkName(name);
+ return getBigInteger(valueMap.get(name));
+ }
+
+ private BigInteger getBigInteger(TypedColumn column) throws
SQLException
+ {
+ checkNotClosed();
+ Object value = column.getValue();
+ wasNull = value == null;
+
+ if (wasNull) return BigInteger.ZERO;
+
+ if (value instanceof BigInteger) return (BigInteger) value;
+
+ if (value instanceof Integer) return BigInteger.valueOf((Integer)
value);
+
+ if (value instanceof Long) return BigInteger.valueOf((Long) value);
+
+ try
+ {
+ if (value instanceof String) return (new BigInteger((String)
value));
+ }
+ catch (NumberFormatException e)
+ {
+ throw new SQLSyntaxErrorException(e);
+ }
+
+ throw new SQLSyntaxErrorException(String.format(NOT_TRANSLATABLE,
value.getClass().getSimpleName(), "BigInteger"));
+ }
+
+ public boolean getBoolean(int index) throws SQLException
+ {
+ checkIndex(index);
+ return getBoolean(values.get(index - 1));
+ }
+
+ public boolean getBoolean(String name) throws SQLException
+ {
+ checkName(name);
+ return getBoolean(valueMap.get(name));
+ }
+
+ private final Boolean getBoolean(TypedColumn column) throws
SQLException
+ {
+ checkNotClosed();
+ Object value = column.getValue();
+ wasNull = value == null;
+
+ if (wasNull) return false;
+
+ if (value instanceof Boolean) return (Boolean)value;
+
+ if (value instanceof Integer) return Boolean.valueOf(((Integer)
value) == 0 ? false : true);
+
+ if (value instanceof Long) return Boolean.valueOf(((Long) value)
== 0 ? false : true);
+
+ if (value instanceof BigInteger) return
Boolean.valueOf(((BigInteger) value).intValue() == 0 ? false : true);
+
+ if (value instanceof String)
+ {
+ String str = (String) value;
+ if (str.equalsIgnoreCase("true")) return true;
+ if (str.equalsIgnoreCase("false")) return false;
+
+ throw new SQLSyntaxErrorException(String.format(NOT_BOOLEAN,
str));
+ }
+
+ throw new SQLSyntaxErrorException(String.format(NOT_TRANSLATABLE,
value.getClass().getSimpleName(), "Boolean"));
+ }
+
+ public byte getByte(int index) throws SQLException
+ {
+ checkIndex(index);
+ return getByte(values.get(index - 1));
+ }
+
+ public byte getByte(String name) throws SQLException
+ {
+ checkName(name);
+ return getByte(valueMap.get(name));
+ }
+
+ private final Byte getByte(TypedColumn column) throws SQLException
+ {
+ checkNotClosed();
+ Object value = column.getValue();
+ wasNull = value == null;
+
+ if (wasNull) return 0;
+
+ if (value instanceof Integer) return ((Integer) value).byteValue();
+
+ if (value instanceof Long) return ((Long) value).byteValue();
+
+ if (value instanceof BigInteger) return ((BigInteger)
value).byteValue();
+
+ try
+ {
+ if (value instanceof String) return (new Byte((String) value));
+ }
+ catch (NumberFormatException e)
+ {
+ throw new SQLSyntaxErrorException(e);
+ }
+
+ throw new SQLSyntaxErrorException(String.format(NOT_TRANSLATABLE,
value.getClass().getSimpleName(), "Byte"));
+ }
+
+ public byte[] getBytes(int index) throws SQLException
+ {
+ return getBytes(values.get(index - 1));
+ }
+
+ public byte[] getBytes(String name) throws SQLException
+ {
+ return getBytes(valueMap.get(name));
+ }
+
+ private byte[] getBytes(TypedColumn column) throws SQLException
+ {
+ checkNotClosed();
+ ByteBuffer value = (ByteBuffer) column.getRawColumn().value;
+ wasNull = value == null;
+ return value == null ? null : ByteBufferUtil.clone(value).array();
+ }
+
+ public TypedColumn getColumn(int index) throws SQLException
+ {
+ checkIndex(index);
+ checkNotClosed();
+ return values.get(index - 1);
+ }
+
+ public TypedColumn getColumn(String name) throws SQLException
+ {
+ checkName(name);
+ checkNotClosed();
+ return valueMap.get(name);
+ }
+
+ public int getConcurrency() throws SQLException
+ {
+ checkNotClosed();
+ return statement.getResultSetConcurrency();
+ }
+
+ public Date getDate(int index) throws SQLException
+ {
+ checkIndex(index);
+ return getDate(values.get(index - 1));
+ }
+
+ public Date getDate(int index, Calendar calendar) throws SQLException
+ {
+ checkIndex(index);
+ // silently ignore the Calendar argument; its a hint we do not need
+ return getDate(index);
+ }
+
+ public Date getDate(String name) throws SQLException
+ {
+ checkName(name);
+ return getDate(valueMap.get(name));
+ }
+
+ public Date getDate(String name, Calendar calendar) throws SQLException
+ {
+ checkName(name);
+ // silently ignore the Calendar argument; its a hint we do not need
+ return getDate(name);
+ }
+
+ private Date getDate(TypedColumn column) throws SQLException
+ {
+ checkNotClosed();
+ Object value = column.getValue();
+ wasNull = value == null;
+
+ if (wasNull) return null;
+
+ if (value instanceof Long) return new Date((Long) value);
+
+ if (value instanceof java.util.Date) return new
Date(((java.util.Date) value).getTime());
+
+ try
+ {
+ if (value instanceof String) return Date.valueOf((String)
value);
+ }
+ catch (IllegalArgumentException e)
+ {
+ throw new SQLSyntaxErrorException(e);
+ }
+
+ throw new SQLSyntaxErrorException(String.format(NOT_TRANSLATABLE,
value.getClass().getSimpleName(), "SQL Date"));
+ }
+
+ public double getDouble(int index) throws SQLException
+ {
+ checkIndex(index);
+ return getDouble(values.get(index - 1));
+ }
+
+ public double getDouble(String name) throws SQLException
+ {
+ checkName(name);
+ return getDouble(valueMap.get(name));
+ }
+
+ private final Double getDouble(TypedColumn column) throws SQLException
+ {
+ checkNotClosed();
+ Object value = column.getValue();
+ wasNull = value == null;
+
+ if (wasNull) return 0.0;
+
+ if (value instanceof Double) return ((Double) value);
+
+ if (value instanceof Float) return ((Float) value).doubleValue();
+
+ if (value instanceof Integer) return new Double((Integer) value);
+
+ if (value instanceof Long) return new Double((Long) value);
+
+ if (value instanceof BigInteger) return new Double(((BigInteger)
value).doubleValue());
+
+ try
+ {
+ if (value instanceof String) return new Double((String) value);
+ }
+ catch (NumberFormatException e)
+ {
+ throw new SQLSyntaxErrorException(e);
+ }
+
+ throw new SQLSyntaxErrorException(String.format(NOT_TRANSLATABLE,
value.getClass().getSimpleName(), "Double"));
+ }
+
+ public int getFetchDirection() throws SQLException
+ {
+ checkNotClosed();
+ return fetchDirection;
+ }
+
+ public int getFetchSize() throws SQLException
+ {
+ checkNotClosed();
+ return fetchSize;
+ }
+
+ public float getFloat(int index) throws SQLException
+ {
+ checkIndex(index);
+ return getFloat(values.get(index - 1));
+ }
+
+ public float getFloat(String name) throws SQLException
+ {
+ checkName(name);
+ return getFloat(valueMap.get(name));
+ }
+
+ private final Float getFloat(TypedColumn column) throws SQLException
+ {
+ checkNotClosed();
+ Object value = column.getValue();
+ wasNull = value == null;
+
+ if (wasNull) return (float) 0.0;
+
+ if (value instanceof Float) return ((Float) value);
+
+ if (value instanceof Double) return ((Double) value).floatValue();
+
+ if (value instanceof Integer) return new Float((Integer) value);
+
+ if (value instanceof Long) return new Float((Long) value);
+
+ if (value instanceof BigInteger) return new Float(((BigInteger)
value).floatValue());
+
+ try
+ {
+ if (value instanceof String) return new Float((String) value);
+ }
+ catch (NumberFormatException e)
+ {
+ throw new SQLException(e);
+ }
+
+ throw new SQLSyntaxErrorException(String.format(NOT_TRANSLATABLE,
value.getClass().getSimpleName(), "Float"));
+ }
+
+ public int getHoldability() throws SQLException
+ {
+ checkNotClosed();
+ return statement.getResultSetHoldability();
+ }
+
+ public int getInt(int index) throws SQLException
+ {
+ checkIndex(index);
+ return getInt(values.get(index - 1));
+ }
+
+ public int getInt(String name) throws SQLException
+ {
+ checkName(name);
+ return getInt(valueMap.get(name));
+ }
+
+ private int getInt(TypedColumn column) throws SQLException
+ {
+ checkNotClosed();
+ Object value = column.getValue();
+ wasNull = value == null;
+
+ if (wasNull) return 0;
+
+ if (value instanceof Integer) return ((Integer) value);
+
+ if (value instanceof Long) return ((Long) value).intValue();
+
+ if (value instanceof BigInteger) return ((BigInteger)
value).intValue();
+
+ try
+ {
+ if (value instanceof String) return (Integer.parseInt((String)
value));
+ }
+ catch (NumberFormatException e)
+ {
+ throw new SQLSyntaxErrorException(e);
+ }
+
+ throw new SQLSyntaxErrorException(String.format(NOT_TRANSLATABLE,
value.getClass().getSimpleName(), "int"));
+ }
+
+ public byte[] getKey() throws SQLException
+ {
+ return curRowKey;
+ }
+
+ public long getLong(int index) throws SQLException
+ {
+ checkIndex(index);
+ return getLong(values.get(index - 1));
+ }
+
+ public long getLong(String name) throws SQLException
+ {
+ checkName(name);
+ return getLong(valueMap.get(name));
+ }
+
+ private Long getLong(TypedColumn column) throws SQLException
+ {
+ checkNotClosed();
+ Object value = column.getValue();
+ wasNull = value == null;
+
+ if (wasNull) return 0L;
+
+ if (value instanceof Long) return (Long) value;
+
+ if (value instanceof Integer) return Long.valueOf((Integer) value);
+
+ if (value instanceof BigInteger) return
getBigInteger(column).longValue();
+
+ if (value instanceof Long) return (Long) value;
+
+ try
+ {
+ if (value instanceof String) return (Long.parseLong((String)
value));
+ }
+ catch (NumberFormatException e)
+ {
+ throw new SQLSyntaxErrorException(e);
+ }
+
+ throw new SQLSyntaxErrorException(String.format(NOT_TRANSLATABLE,
value.getClass().getSimpleName(), "Long"));
+ }
+
+ public ResultSetMetaData getMetaData() throws SQLException
+ {
+ checkNotClosed();
+ return meta;
+ }
+
+ public Object getObject(int index) throws SQLException
+ {
+ checkIndex(index);
+ return getObject(values.get(index - 1));
+ }
+
+ public Object getObject(String name) throws SQLException
+ {
+ checkName(name);
+ return getObject(valueMap.get(name));
+ }
+
+
+ private Object getObject(TypedColumn column) throws SQLException
+ {
+ checkNotClosed();
+ Object value = column.getValue();
+ wasNull = value == null;
+ return (wasNull) ? null : value;
+ }
+
+ public int getRow() throws SQLException
+ {
+ checkNotClosed();
+ return rowNumber;
+ }
+
+ public RowId getRowId(int index) throws SQLException
+ {
+ checkIndex(index);
+ return getRowId(values.get(index - 1));
+ }
+
+ public RowId getRowId(String name) throws SQLException
+ {
+ checkName(name);
+ return getRowId(valueMap.get(name));
+ }
+
+ private final RowId getRowId(TypedColumn column) throws SQLException
+ {
+ checkNotClosed();
+ ByteBuffer value = column.getRawColumn().value;
+ wasNull = value == null;
+ return value == null ? null : new CassandraRowId(value);
+ }
+
+ public short getShort(int index) throws SQLException
+ {
+ checkIndex(index);
+ return getShort(values.get(index - 1));
+ }
+
+ public short getShort(String name) throws SQLException
+ {
+ checkName(name);
+ return getShort(valueMap.get(name));
+ }
+
+ private final Short getShort(TypedColumn column) throws SQLException
+ {
+ checkNotClosed();
+ Object value = column.getValue();
+ wasNull = value == null;
+
+ if (wasNull) return 0;
+
+ if (value instanceof Integer) return ((Integer)
value).shortValue();
+
+ if (value instanceof Long) return ((Long) value).shortValue();
+
+ if (value instanceof BigInteger) return ((BigInteger)
value).shortValue();
+
+ try
+ {
+ if (value instanceof String) return (new Short((String)
value));
+ }
+ catch (NumberFormatException e)
+ {
+ throw new SQLSyntaxErrorException(e);
+ }
+
+ throw new SQLSyntaxErrorException(String.format(NOT_TRANSLATABLE,
value.getClass().getSimpleName(), "Short"));
+ }
+
+ public Statement getStatement() throws SQLException
+ {
+ checkNotClosed();
+ return statement;
+ }
+
+ public String getString(int index) throws SQLException
+ {
+ checkIndex(index);
+ return getString(values.get(index - 1));
+ }
+
+ public String getString(String name) throws SQLException
+ {
+ checkName(name);
+ return getString(valueMap.get(name));
+ }
+
+ private String getString(TypedColumn column) throws SQLException
+ {
+ checkNotClosed();
+ Object value = column.getValue();
+ wasNull = value == null;
+ return (wasNull) ? null : value.toString();
+ }
+
+ public Time getTime(int index) throws SQLException
+ {
+ checkIndex(index);
+ return getTime(values.get(index - 1));
+ }
+
+ public Time getTime(int index, Calendar calendar) throws SQLException
+ {
+ checkIndex(index);
+ // silently ignore the Calendar argument; its a hint we do not need
+ return getTime(index);
+ }
+
+ public Time getTime(String name) throws SQLException
+ {
+ checkName(name);
+ return getTime(valueMap.get(name));
+ }
+
+ public Time getTime(String name, Calendar calendar) throws SQLException
+ {
+ checkName(name);
+ // silently ignore the Calendar argument; its a hint we do not need
+ return getTime(name);
+ }
+
+ private Time getTime(TypedColumn column) throws SQLException
+ {
+ checkNotClosed();
+ Object value = column.getValue();
+ wasNull = value == null;
+
+ if (wasNull) return null;
+
+ if (value instanceof Long) return new Time((Long) value);
+
+ if (value instanceof java.util.Date) return new
Time(((java.util.Date) value).getTime());
+
+ try
+ {
+ if (value instanceof String) return Time.valueOf((String)
value);
+ }
+ catch (IllegalArgumentException e)
+ {
+ throw new SQLSyntaxErrorException(e);
+ }
+
+ throw new SQLSyntaxErrorException(String.format(NOT_TRANSLATABLE,
value.getClass().getSimpleName(), "SQL Time"));
+ }
+
+ public Timestamp getTimestamp(int index) throws SQLException
+ {
+ checkIndex(index);
+ return getTimestamp(values.get(index - 1));
+ }
+
+ public Timestamp getTimestamp(int index, Calendar calendar) throws
SQLException
+ {
+ checkIndex(index);
+ // silently ignore the Calendar argument; its a hint we do not need
+ return getTimestamp(index);
+ }
+
+ public Timestamp getTimestamp(String name) throws SQLException
+ {
+ checkName(name);
+ return getTimestamp(valueMap.get(name));
+ }
+
+ public Timestamp getTimestamp(String name, Calendar calendar) throws
SQLException
+ {
+ checkName(name);
+ // silently ignore the Calendar argument; its a hint we do not need
+ return getTimestamp(name);
+ }
+
+ private Timestamp getTimestamp(TypedColumn column) throws SQLException
+ {
+ checkNotClosed();
+ Object value = column.getValue();
+ wasNull = value == null;
+
+ if (wasNull) return null;
+
+ if (value instanceof Long) return new Timestamp((Long) value);
+
+ if (value instanceof java.util.Date) return new
Timestamp(((java.util.Date) value).getTime());
+
+ try
+ {
+ if (value instanceof String) return Timestamp.valueOf((String)
value);
+ }
+ catch (IllegalArgumentException e)
+ {
+ throw new SQLSyntaxErrorException(e);
+ }
+
+ throw new SQLSyntaxErrorException(String.format(NOT_TRANSLATABLE,
value.getClass().getSimpleName(), "SQL Timestamp"));
+ }
+
+ public int getType() throws SQLException
+ {
+ checkNotClosed();
+ return resultSetType;
+ }
+
+ // URL (awaiting some clarifications as to how it is stored in C* ...
just a validated Sting in URL format?
+ public URL getURL(int arg0) throws SQLException
+ {
+ throw new SQLFeatureNotSupportedException(NOT_SUPPORTED);
+ }
+
+ public URL getURL(String arg0) throws SQLException
+ {
+ throw new SQLFeatureNotSupportedException(NOT_SUPPORTED);
+ }
+
+ // These Methods are planned to be implemented soon; but not right
now...
+ // Each set of methods has a more detailed set of issues that should
be considered fully...
+
+
+ public SQLWarning getWarnings() throws SQLException
+ {
+ checkNotClosed();
+ // the rationale is there are no warnings to return in this
implementation...
+ return null;
+ }
+
+
+ public boolean isAfterLast() throws SQLException
+ {
+ checkNotClosed();
+ return rowNumber == Integer.MAX_VALUE;
+ }
+
+ public boolean isBeforeFirst() throws SQLException
+ {
+ checkNotClosed();
+ return rowNumber == 0;
+ }
+
+ public boolean isClosed() throws SQLException
+ {
+ return valueMap == null;
+ }
+
+ public boolean isFirst() throws SQLException
+ {
+ checkNotClosed();
+ return rowNumber == 1;
+ }
+
+ public boolean isLast() throws SQLException
+ {
+ checkNotClosed();
+ return !rSetIter.hasNext();
+ }
+
+ public boolean isWrapperFor(Class<?> iface) throws SQLException
+ {
+ return CassandraResultSetExtras.class.isAssignableFrom(iface);
+ }
+
+ // Navigation between rows within the returned set of rows
+ // Need to use a list iterator so next() needs completely re-thought
+
+ public boolean last() throws SQLException
+ {
+ throw new SQLFeatureNotSupportedException(NOT_SUPPORTED);
+ }
+
+ public synchronized boolean next() throws SQLException
+ {
+ if (!values.isEmpty() || !valueMap.isEmpty())
+ {
+ values.clear();
+ valueMap.clear();
+ }
+ if (rSetIter != null && rSetIter.hasNext())
+ {
+ CqlRow row = rSetIter.next();
+ rowNumber++;
+ curRowKey = row.getKey();
+ List<Column> cols = row.getColumns();
+ for (Column col : cols)
+ {
+ TypedColumn c = createColumn(col);
+ String columnName = c.getNameString();
+ values.add(c);
+ indexMap.put(columnName, values.size()); // one greater
than 0 based index of a list
+ valueMap.put(columnName, c);
+ }
+ return !(values.isEmpty() || valueMap.isEmpty());
+ }
+ else
+ {
+ rowNumber = Integer.MAX_VALUE;
+ return false;
+ }
+ }
+
+ private TypedColumn createColumn(Column column)
+ {
+ String nameType = schema.name_types.get(column.name);
+ AbstractJdbcType<?> comparator =
TypesMap.getTypeForComparator(nameType == null ? schema.default_name_type :
nameType);
+ String valueType = schema.value_types.get(column.name);
+ AbstractJdbcType<?> validator =
TypesMap.getTypeForComparator(valueType == null ?
schema.default_value_type : valueType);
+ return new TypedColumn(column, comparator, validator);
+ }
+
+ public boolean previous() throws SQLException
+ {
+ throw new SQLFeatureNotSupportedException(NOT_SUPPORTED);
+ }
+
+ public boolean relative(int arg0) throws SQLException
+ {
+ throw new SQLFeatureNotSupportedException(NOT_SUPPORTED);
+ }
+
+ public void setFetchDirection(int direction) throws SQLException
+ {
+ checkNotClosed();
+
+ if (direction == FETCH_FORWARD || direction == FETCH_REVERSE ||
direction == FETCH_UNKNOWN)
+ {
+ if ((getType() == TYPE_FORWARD_ONLY) && (direction !=
FETCH_FORWARD))
+ throw new SQLSyntaxErrorException("attempt to set an
illegal direction : " + direction);
+ fetchDirection = direction;
+ }
+ throw new SQLSyntaxErrorException(String.format(BAD_FETCH_DIR,
direction));
+ }
+
+ public void setFetchSize(int size) throws SQLException
+ {
+ checkNotClosed();
+ if (size < 0) throw new SQLException(String.format(BAD_FETCH_SIZE,
size));
+ fetchSize = size;
+ }
+
+ public <T> T unwrap(Class<T> iface) throws SQLException
+ {
+ if (iface.equals(CassandraResultSetExtras.class)) return (T) this;
+
+ throw new
SQLFeatureNotSupportedException(String.format(NO_INTERFACE,
iface.getSimpleName()));
+ }
+
+ public boolean wasNull() throws SQLException
+ {
+ return wasNull;
***The diff for this file has been truncated for email.***
=======================================
--- /src/main/java/org/apache/cassandra/cql/jdbc/CResultSet.java Wed Dec 21
21:12:23 2011
+++ /dev/null
@@ -1,1150 +0,0 @@
-/*
- *
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- *
- */
-package org.apache.cassandra.cql.jdbc;
-
-import static org.apache.cassandra.cql.jdbc.Utils.*;
-
-import java.math.BigDecimal;
-import java.math.BigInteger;
-import java.net.URL;
-import java.nio.ByteBuffer;
-import java.sql.*;
-import java.sql.Date;
-import java.util.*;
-
-import org.apache.cassandra.thrift.Column;
-import org.apache.cassandra.thrift.CqlMetadata;
-import org.apache.cassandra.thrift.CqlResult;
-import org.apache.cassandra.thrift.CqlRow;
-import org.apache.cassandra.utils.ByteBufferUtil;
-
-/**
- * <p>The Supported Data types in CQL are as follows:</p>
- * <table>
- * <tr><th>type</th><th>java type</th><th>description</th></tr>
- * <tr><td>ascii</td><td>String</td><td>ASCII character string</td></tr>
- * <tr><td>bigint</td><td>Long</td><td>64-bit signed long</td></tr>
- * <tr><td>blob</td><td>ByteBuffer</td><td>Arbitrary bytes (no
validation)</td></tr>
- * <tr><td>boolean</td><td>Boolean</td><td>true or false</td></tr>
- * <tr><td>counter</td><td>Long</td><td>Counter column (64-bit
long)</td></tr>
- * <tr><td>decimal</td><td>BigDecimal</td><td>Variable-precision
decimal</td></tr>
- * <tr><td>double</td><td>Double</td><td>64-bit IEEE-754 floating
point</td></tr>
- * <tr><td>float</td><td>Float</td><td>32-bit IEEE-754 floating
point</td></tr>
- * <tr><td>int</td><td>Integer</td><td>32-bit signed int</td></tr>
- * <tr><td>text</td><td>String</td><td>UTF8 encoded string</td></tr>
- * <tr><td>timestamp</td><td>Date</td><td>A timestamp</td></tr>
- * <tr><td>uuid</td><td>UUID</td><td>Type 1 or type 4 UUID</td></tr>
- * <tr><td>varchar</td><td>String</td><td>UTF8 encoded string</td></tr>
- * <tr><td>varint</td><td>BigInteger</td><td>Arbitrary-precision
integer</td></tr>
- * </table>
- *
- */
-class CResultSet extends AbstractResultSet implements
CassandraResultSetExtras
-{
- public static final int DEFAULT_TYPE = ResultSet.TYPE_FORWARD_ONLY;
- public static final int DEFAULT_CONCURRENCY =
ResultSet.CONCUR_READ_ONLY;
- public static final int DEFAULT_HOLDABILITY =
ResultSet.HOLD_CURSORS_OVER_COMMIT;
-
- private final String keyspace;
-
- /**
- * The r set iter.
- */
- private Iterator<CqlRow> rSetIter;
-
- int rowNumber = 0;
- // the current row key when iterating through results.
- private byte[] curRowKey = null;
-
- /**
- * The values.
- */
- private List<TypedColumn> values = new ArrayList<TypedColumn>();
-
- /**
- * The value map.
- */
- private Map<String, TypedColumn> valueMap = new HashMap<String,
TypedColumn>();
-
- /**
- * The index map.
- */
- private Map<String, Integer> indexMap = new HashMap<String, Integer>();
-
- private final CResultSetMetaData meta;
-
- private final Statement statement;
-
- private int resultSetType;
-
- private int fetchDirection;
-
- private int fetchSize;
-
- private boolean wasNull;
-
- private CqlMetadata schema;
-
- /**
- * no argument constructor.
- */
- CResultSet()
- {
- keyspace = null;
- statement = null;
- meta = new CResultSetMetaData();
- }
-
- /**
- * Instantiates a new cassandra result set.
- */
- CResultSet(Statement statement, CqlResult resultSet, String keyspace)
throws SQLException
- {
- this.statement = statement;
- this.keyspace = keyspace;
- this.resultSetType = statement.getResultSetType();
- this.fetchDirection = statement.getFetchDirection();
- this.fetchSize = statement.getFetchSize();
- this.schema = resultSet.schema;
-
- rSetIter = resultSet.getRowsIterator();
- meta = new CResultSetMetaData();
- }
-
- public boolean absolute(int arg0) throws SQLException
- {
- throw new SQLFeatureNotSupportedException(NOT_SUPPORTED);
- }
-
- public void afterLast() throws SQLException
- {
- throw new SQLFeatureNotSupportedException(NOT_SUPPORTED);
- }
-
- public void beforeFirst() throws SQLException
- {
- throw new SQLFeatureNotSupportedException(NOT_SUPPORTED);
- }
-
- private final void checkIndex(int index) throws SQLException
- {
- // 1 <= index <= size()
- if (index < 1 || index > values.size())
- throw new
SQLSyntaxErrorException(String.format(MUST_BE_POSITIVE,
String.valueOf(index))+" "+values.size());
- }
-
- private final void checkName(String name) throws SQLException
- {
- if (valueMap.get(name) == null) throw new
SQLSyntaxErrorException(String.format(VALID_LABELS, name));
- }
-
- private final void checkNotClosed() throws SQLException
- {
- if (isClosed()) throw new SQLRecoverableException(WAS_CLOSED_RSLT);
- }
-
- public void clearWarnings() throws SQLException
- {
- // This implementation does not support the collection of warnings
so clearing is a no-op
- // but it is still an exception to call this on a closed
connection.
- checkNotClosed();
- }
-
- public void close() throws SQLException
- {
- valueMap = null;
- values = null;
- }
-
- public int findColumn(String name) throws SQLException
- {
- checkNotClosed();
- checkName(name);
- return indexMap.get(name).intValue();
- }
-
- public boolean first() throws SQLException
- {
- throw new SQLFeatureNotSupportedException(NOT_SUPPORTED);
- }
-
-
- public BigDecimal getBigDecimal(int index) throws SQLException
- {
- checkIndex(index);
- return getBigDecimal(values.get(index - 1));
- }
-
- /** @deprecated */
- public BigDecimal getBigDecimal(int index, int scale) throws
SQLException
- {
- checkIndex(index);
- return (getBigDecimal(values.get(index - 1))).setScale(scale);
- }
-
- public BigDecimal getBigDecimal(String name) throws SQLException
- {
- checkName(name);
- return getBigDecimal(valueMap.get(name));
- }
-
- /** @deprecated */
- public BigDecimal getBigDecimal(String name, int scale) throws
SQLException
- {
- checkName(name);
- return (getBigDecimal(valueMap.get(name))).setScale(scale);
- }
-
- private BigDecimal getBigDecimal(TypedColumn column) throws
SQLException
- {
- checkNotClosed();
- Object value = column.getValue();
- wasNull = value == null;
-
- if (wasNull) return BigDecimal.ZERO;
-
- if (value instanceof BigDecimal) return (BigDecimal) value;
-
- if (value instanceof Long) return BigDecimal.valueOf((Long) value);
-
- if (value instanceof Double) return BigDecimal.valueOf((Double)
value);
-
- if (value instanceof BigInteger) return new
BigDecimal((BigInteger) value);
-
- try
- {
- if (value instanceof String) return (new BigDecimal((String)
value));
- }
- catch (NumberFormatException e)
- {
- throw new SQLSyntaxErrorException(e);
- }
-
- throw new SQLSyntaxErrorException(String.format(NOT_TRANSLATABLE,
value.getClass().getSimpleName(), "BigDecimal"));
- }
- public BigInteger getBigInteger(int index) throws SQLException
- {
- checkIndex(index);
- return getBigInteger(values.get(index - 1));
- }
-
- public BigInteger getBigInteger(String name) throws SQLException
- {
- checkName(name);
- return getBigInteger(valueMap.get(name));
- }
-
- private BigInteger getBigInteger(TypedColumn column) throws
SQLException
- {
- checkNotClosed();
- Object value = column.getValue();
- wasNull = value == null;
-
- if (wasNull) return BigInteger.ZERO;
-
- if (value instanceof BigInteger) return (BigInteger) value;
-
- if (value instanceof Integer) return BigInteger.valueOf((Integer)
value);
-
- if (value instanceof Long) return BigInteger.valueOf((Long) value);
-
- try
- {
- if (value instanceof String) return (new BigInteger((String)
value));
- }
- catch (NumberFormatException e)
- {
- throw new SQLSyntaxErrorException(e);
- }
-
- throw new SQLSyntaxErrorException(String.format(NOT_TRANSLATABLE,
value.getClass().getSimpleName(), "BigInteger"));
- }
-
- public boolean getBoolean(int index) throws SQLException
- {
- checkIndex(index);
- return getBoolean(values.get(index - 1));
- }
-
- public boolean getBoolean(String name) throws SQLException
- {
- checkName(name);
- return getBoolean(valueMap.get(name));
- }
-
- private final Boolean getBoolean(TypedColumn column) throws
SQLException
- {
- checkNotClosed();
- Object value = column.getValue();
- wasNull = value == null;
-
- if (wasNull) return false;
-
- if (value instanceof Boolean) return (Boolean)value;
-
- if (value instanceof Integer) return Boolean.valueOf(((Integer)
value) == 0 ? false : true);
-
- if (value instanceof Long) return Boolean.valueOf(((Long) value)
== 0 ? false : true);
-
- if (value instanceof BigInteger) return
Boolean.valueOf(((BigInteger) value).intValue() == 0 ? false : true);
-
- if (value instanceof String)
- {
- String str = (String) value;
- if (str.equalsIgnoreCase("true")) return true;
- if (str.equalsIgnoreCase("false")) return false;
-
- throw new SQLSyntaxErrorException(String.format(NOT_BOOLEAN,
str));
- }
-
- throw new SQLSyntaxErrorException(String.format(NOT_TRANSLATABLE,
value.getClass().getSimpleName(), "Boolean"));
- }
-
- public byte getByte(int index) throws SQLException
- {
- checkIndex(index);
- return getByte(values.get(index - 1));
- }
-
- public byte getByte(String name) throws SQLException
- {
- checkName(name);
- return getByte(valueMap.get(name));
- }
-
- private final Byte getByte(TypedColumn column) throws SQLException
- {
- checkNotClosed();
- Object value = column.getValue();
- wasNull = value == null;
-
- if (wasNull) return 0;
-
- if (value instanceof Integer) return ((Integer) value).byteValue();
-
- if (value instanceof Long) return ((Long) value).byteValue();
-
- if (value instanceof BigInteger) return ((BigInteger)
value).byteValue();
-
- try
- {
- if (value instanceof String) return (new Byte((String) value));
- }
- catch (NumberFormatException e)
- {
- throw new SQLSyntaxErrorException(e);
- }
-
- throw new SQLSyntaxErrorException(String.format(NOT_TRANSLATABLE,
value.getClass().getSimpleName(), "Byte"));
- }
-
- public byte[] getBytes(int index) throws SQLException
- {
- return getBytes(values.get(index - 1));
- }
-
- public byte[] getBytes(String name) throws SQLException
- {
- return getBytes(valueMap.get(name));
- }
-
- private byte[] getBytes(TypedColumn column) throws SQLException
- {
- checkNotClosed();
- ByteBuffer value = (ByteBuffer) column.getRawColumn().value;
- wasNull = value == null;
- return value == null ? null : ByteBufferUtil.clone(value).array();
- }
-
- public TypedColumn getColumn(int index) throws SQLException
- {
- checkIndex(index);
- checkNotClosed();
- return values.get(index - 1);
- }
-
- public TypedColumn getColumn(String name) throws SQLException
- {
- checkName(name);
- checkNotClosed();
- return valueMap.get(name);
- }
-
- public int getConcurrency() throws SQLException
- {
- checkNotClosed();
- return statement.getResultSetConcurrency();
- }
-
- public Date getDate(int index) throws SQLException
- {
- checkIndex(index);
- return getDate(values.get(index - 1));
- }
-
- public Date getDate(int index, Calendar calendar) throws SQLException
- {
- checkIndex(index);
- // silently ignore the Calendar argument; its a hint we do not need
- return getDate(index);
- }
-
- public Date getDate(String name) throws SQLException
- {
- checkName(name);
- return getDate(valueMap.get(name));
- }
-
- public Date getDate(String name, Calendar calendar) throws SQLException
- {
- checkName(name);
- // silently ignore the Calendar argument; its a hint we do not need
- return getDate(name);
- }
-
- private Date getDate(TypedColumn column) throws SQLException
- {
- checkNotClosed();
- Object value = column.getValue();
- wasNull = value == null;
-
- if (wasNull) return null;
-
- if (value instanceof Long) return new Date((Long) value);
-
- if (value instanceof java.util.Date) return new
Date(((java.util.Date) value).getTime());
-
- try
- {
- if (value instanceof String) return Date.valueOf((String)
value);
- }
- catch (IllegalArgumentException e)
- {
- throw new SQLSyntaxErrorException(e);
- }
-
- throw new SQLSyntaxErrorException(String.format(NOT_TRANSLATABLE,
value.getClass().getSimpleName(), "SQL Date"));
- }
-
- public double getDouble(int index) throws SQLException
- {
- checkIndex(index);
- return getDouble(values.get(index - 1));
- }
-
- public double getDouble(String name) throws SQLException
- {
- checkName(name);
- return getDouble(valueMap.get(name));
- }
-
- private final Double getDouble(TypedColumn column) throws SQLException
- {
- checkNotClosed();
- Object value = column.getValue();
- wasNull = value == null;
-
- if (wasNull) return 0.0;
-
- if (value instanceof Double) return ((Double) value);
-
- if (value instanceof Float) return ((Float) value).doubleValue();
-
- if (value instanceof Integer) return new Double((Integer) value);
-
- if (value instanceof Long) return new Double((Long) value);
-
- if (value instanceof BigInteger) return new Double(((BigInteger)
value).doubleValue());
-
- try
- {
- if (value instanceof String) return new Double((String) value);
- }
- catch (NumberFormatException e)
- {
- throw new SQLSyntaxErrorException(e);
- }
-
- throw new SQLSyntaxErrorException(String.format(NOT_TRANSLATABLE,
value.getClass().getSimpleName(), "Double"));
- }
-
- public int getFetchDirection() throws SQLException
- {
- checkNotClosed();
- return fetchDirection;
- }
-
- public int getFetchSize() throws SQLException
- {
- checkNotClosed();
- return fetchSize;
- }
-
- public float getFloat(int index) throws SQLException
- {
- checkIndex(index);
- return getFloat(values.get(index - 1));
- }
-
- public float getFloat(String name) throws SQLException
- {
- checkName(name);
- return getFloat(valueMap.get(name));
- }
-
- private final Float getFloat(TypedColumn column) throws SQLException
- {
- checkNotClosed();
- Object value = column.getValue();
- wasNull = value == null;
-
- if (wasNull) return (float) 0.0;
-
- if (value instanceof Float) return ((Float) value);
-
- if (value instanceof Double) return ((Double) value).floatValue();
-
- if (value instanceof Integer) return new Float((Integer) value);
-
- if (value instanceof Long) return new Float((Long) value);
-
- if (value instanceof BigInteger) return new Float(((BigInteger)
value).floatValue());
-
- try
- {
- if (value instanceof String) return new Float((String) value);
- }
- catch (NumberFormatException e)
- {
- throw new SQLException(e);
- }
-
- throw new SQLSyntaxErrorException(String.format(NOT_TRANSLATABLE,
value.getClass().getSimpleName(), "Float"));
- }
-
- public int getHoldability() throws SQLException
- {
- checkNotClosed();
- return statement.getResultSetHoldability();
- }
-
- public int getInt(int index) throws SQLException
- {
- checkIndex(index);
- return getInt(values.get(index - 1));
- }
-
- public int getInt(String name) throws SQLException
- {
- checkName(name);
- return getInt(valueMap.get(name));
- }
-
- private int getInt(TypedColumn column) throws SQLException
- {
- checkNotClosed();
- Object value = column.getValue();
- wasNull = value == null;
-
- if (wasNull) return 0;
-
- if (value instanceof Integer) return ((Integer) value);
-
- if (value instanceof Long) return ((Long) value).intValue();
-
- if (value instanceof BigInteger) return ((BigInteger)
value).intValue();
-
- try
- {
- if (value instanceof String) return (Integer.parseInt((String)
value));
- }
- catch (NumberFormatException e)
- {
- throw new SQLSyntaxErrorException(e);
- }
-
- throw new SQLSyntaxErrorException(String.format(NOT_TRANSLATABLE,
value.getClass().getSimpleName(), "int"));
- }
-
- public byte[] getKey() throws SQLException
- {
- return curRowKey;
- }
-
- public long getLong(int index) throws SQLException
- {
- checkIndex(index);
- return getLong(values.get(index - 1));
- }
-
- public long getLong(String name) throws SQLException
- {
- checkName(name);
- return getLong(valueMap.get(name));
- }
-
- private Long getLong(TypedColumn column) throws SQLException
- {
- checkNotClosed();
- Object value = column.getValue();
- wasNull = value == null;
-
- if (wasNull) return 0L;
-
- if (value instanceof Long) return (Long) value;
-
- if (value instanceof Integer) return Long.valueOf((Integer) value);
-
- if (value instanceof BigInteger) return
getBigInteger(column).longValue();
-
- if (value instanceof Long) return (Long) value;
-
- try
- {
- if (value instanceof String) return (Long.parseLong((String)
value));
- }
- catch (NumberFormatException e)
- {
- throw new SQLSyntaxErrorException(e);
- }
-
- throw new SQLSyntaxErrorException(String.format(NOT_TRANSLATABLE,
value.getClass().getSimpleName(), "Long"));
- }
-
- public ResultSetMetaData getMetaData() throws SQLException
- {
- checkNotClosed();
- return meta;
- }
-
- public Object getObject(int index) throws SQLException
- {
- checkIndex(index);
- return getObject(values.get(index - 1));
- }
-
- public Object getObject(String name) throws SQLException
- {
- checkName(name);
- return getObject(valueMap.get(name));
- }
-
-
- private Object getObject(TypedColumn column) throws SQLException
- {
- checkNotClosed();
- Object value = column.getValue();
- wasNull = value == null;
- return (wasNull) ? null : value;
- }
-
- public int getRow() throws SQLException
- {
- checkNotClosed();
- return rowNumber;
- }
-
- public RowId getRowId(int index) throws SQLException
- {
- checkIndex(index);
- return getRowId(values.get(index - 1));
- }
-
- public RowId getRowId(String name) throws SQLException
- {
- checkName(name);
- return getRowId(valueMap.get(name));
- }
-
- private final RowId getRowId(TypedColumn column) throws SQLException
- {
- checkNotClosed();
- ByteBuffer value = column.getRawColumn().value;
- wasNull = value == null;
- return value == null ? null : new CassandraRowId(value);
- }
-
- public short getShort(int index) throws SQLException
- {
- checkIndex(index);
- return getShort(values.get(index - 1));
- }
-
- public short getShort(String name) throws SQLException
- {
- checkName(name);
- return getShort(valueMap.get(name));
- }
-
- private final Short getShort(TypedColumn column) throws SQLException
- {
- checkNotClosed();
- Object value = column.getValue();
- wasNull = value == null;
-
- if (wasNull) return 0;
-
- if (value instanceof Integer) return ((Integer)
value).shortValue();
-
- if (value instanceof Long) return ((Long) value).shortValue();
-
- if (value instanceof BigInteger) return ((BigInteger)
value).shortValue();
-
- try
- {
- if (value instanceof String) return (new Short((String)
value));
- }
- catch (NumberFormatException e)
- {
- throw new SQLSyntaxErrorException(e);
- }
-
- throw new SQLSyntaxErrorException(String.format(NOT_TRANSLATABLE,
value.getClass().getSimpleName(), "Short"));
- }
-
- public Statement getStatement() throws SQLException
- {
- checkNotClosed();
- return statement;
- }
-
- public String getString(int index) throws SQLException
- {
- checkIndex(index);
- return getString(values.get(index - 1));
- }
-
- public String getString(String name) throws SQLException
- {
- checkName(name);
- return getString(valueMap.get(name));
- }
-
- private String getString(TypedColumn column) throws SQLException
- {
- checkNotClosed();
- Object value = column.getValue();
- wasNull = value == null;
- return (wasNull) ? null : value.toString();
- }
-
- public Time getTime(int index) throws SQLException
- {
- checkIndex(index);
- return getTime(values.get(index - 1));
- }
-
- public Time getTime(int index, Calendar calendar) throws SQLException
- {
- checkIndex(index);
- // silently ignore the Calendar argument; its a hint we do not need
- return getTime(index);
- }
-
- public Time getTime(String name) throws SQLException
- {
- checkName(name);
- return getTime(valueMap.get(name));
- }
-
- public Time getTime(String name, Calendar calendar) throws SQLException
- {
- checkName(name);
- // silently ignore the Calendar argument; its a hint we do not need
- return getTime(name);
- }
-
- private Time getTime(TypedColumn column) throws SQLException
- {
- checkNotClosed();
- Object value = column.getValue();
- wasNull = value == null;
-
- if (wasNull) return null;
-
- if (value instanceof Long) return new Time((Long) value);
-
- if (value instanceof java.util.Date) return new
Time(((java.util.Date) value).getTime());
-
- try
- {
- if (value instanceof String) return Time.valueOf((String)
value);
- }
- catch (IllegalArgumentException e)
- {
- throw new SQLSyntaxErrorException(e);
- }
-
- throw new SQLSyntaxErrorException(String.format(NOT_TRANSLATABLE,
value.getClass().getSimpleName(), "SQL Time"));
- }
-
- public Timestamp getTimestamp(int index) throws SQLException
- {
- checkIndex(index);
- return getTimestamp(values.get(index - 1));
- }
-
- public Timestamp getTimestamp(int index, Calendar calendar) throws
SQLException
- {
- checkIndex(index);
- // silently ignore the Calendar argument; its a hint we do not need
- return getTimestamp(index);
- }
-
- public Timestamp getTimestamp(String name) throws SQLException
- {
- checkName(name);
- return getTimestamp(valueMap.get(name));
- }
-
- public Timestamp getTimestamp(String name, Calendar calendar) throws
SQLException
- {
- checkName(name);
- // silently ignore the Calendar argument; its a hint we do not need
- return getTimestamp(name);
- }
-
- private Timestamp getTimestamp(TypedColumn column) throws SQLException
- {
- checkNotClosed();
- Object value = column.getValue();
- wasNull = value == null;
-
- if (wasNull) return null;
-
- if (value instanceof Long) return new Timestamp((Long) value);
-
- if (value instanceof java.util.Date) return new
Timestamp(((java.util.Date) value).getTime());
-
- try
- {
- if (value instanceof String) return Timestamp.valueOf((String)
value);
- }
- catch (IllegalArgumentException e)
- {
- throw new SQLSyntaxErrorException(e);
- }
-
- throw new SQLSyntaxErrorException(String.format(NOT_TRANSLATABLE,
value.getClass().getSimpleName(), "SQL Timestamp"));
- }
-
- public int getType() throws SQLException
- {
- checkNotClosed();
- return resultSetType;
- }
-
- // URL (awaiting some clarifications as to how it is stored in C* ...
just a validated Sting in URL format?
- public URL getURL(int arg0) throws SQLException
- {
- throw new SQLFeatureNotSupportedException(NOT_SUPPORTED);
- }
-
- public URL getURL(String arg0) throws SQLException
- {
- throw new SQLFeatureNotSupportedException(NOT_SUPPORTED);
- }
-
- // These Methods are planned to be implemented soon; but not right
now...
- // Each set of methods has a more detailed set of issues that should
be considered fully...
-
-
- public SQLWarning getWarnings() throws SQLException
- {
- checkNotClosed();
- // the rationale is there are no warnings to return in this
implementation...
- return null;
- }
-
-
- public boolean isAfterLast() throws SQLException
- {
- checkNotClosed();
- return rowNumber == Integer.MAX_VALUE;
- }
-
- public boolean isBeforeFirst() throws SQLException
- {
- checkNotClosed();
- return rowNumber == 0;
- }
-
- public boolean isClosed() throws SQLException
- {
- return valueMap == null;
- }
-
- public boolean isFirst() throws SQLException
- {
- checkNotClosed();
- return rowNumber == 1;
- }
-
- public boolean isLast() throws SQLException
- {
- checkNotClosed();
- return !rSetIter.hasNext();
- }
-
- public boolean isWrapperFor(Class<?> iface) throws SQLException
- {
- return CassandraResultSetExtras.class.isAssignableFrom(iface);
- }
-
- // Navigation between rows within the returned set of rows
- // Need to use a list iterator so next() needs completely re-thought
-
- public boolean last() throws SQLException
- {
- throw new SQLFeatureNotSupportedException(NOT_SUPPORTED);
- }
-
- public synchronized boolean next() throws SQLException
- {
- if (!values.isEmpty() || !valueMap.isEmpty())
- {
- values.clear();
- valueMap.clear();
- }
- if (rSetIter != null && rSetIter.hasNext())
- {
- CqlRow row = rSetIter.next();
- rowNumber++;
- curRowKey = row.getKey();
- List<Column> cols = row.getColumns();
- for (Column col : cols)
- {
- TypedColumn c = createColumn(col);
- String columnName = c.getNameString();
- values.add(c);
- indexMap.put(columnName, values.size()); // one greater
than 0 based index of a list
- valueMap.put(columnName, c);
- }
- return !(values.isEmpty() || valueMap.isEmpty());
- }
- else
- {
- rowNumber = Integer.MAX_VALUE;
- return false;
- }
- }
-
- private TypedColumn createColumn(Column column)
- {
- String nameType = schema.name_types.get(column.name);
- AbstractJdbcType<?> comparator =
TypesMap.getTypeForComparator(nameType == null ? schema.default_name_type :
nameType);
- String valueType = schema.value_types.get(column.name);
- AbstractJdbcType<?> validator =
TypesMap.getTypeForComparator(valueType == null ?
schema.default_value_type : valueType);
- return new TypedColumn(column, comparator, validator);
- }
-
- public boolean previous() throws SQLException
- {
- throw new SQLFeatureNotSupportedException(NOT_SUPPORTED);
- }
-
- public boolean relative(int arg0) throws SQLException
- {
- throw new SQLFeatureNotSupportedException(NOT_SUPPORTED);
- }
-
- public void setFetchDirection(int direction) throws SQLException
- {
- checkNotClosed();
-
- if (direction == FETCH_FORWARD || direction == FETCH_REVERSE ||
direction == FETCH_UNKNOWN)
- {
- if ((getType() == TYPE_FORWARD_ONLY) && (direction !=
FETCH_FORWARD))
- throw new SQLSyntaxErrorException("attempt to set an
illegal direction : " + direction);
- fetchDirection = direction;
- }
- throw new SQLSyntaxErrorException(String.format(BAD_FETCH_DIR,
direction));
- }
-
- public void setFetchSize(int size) throws SQLException
- {
- checkNotClosed();
- if (size < 0) throw new SQLException(String.format(BAD_FETCH_SIZE,
size));
- fetchSize = size;
- }
-
- public <T> T unwrap(Class<T> iface) throws SQLException
- {
- if (iface.equals(CassandraResultSetExtras.class)) return (T) this;
-
- throw new
SQLFeatureNotSupportedException(String.format(NO_INTERFACE,
iface.getSimpleName()));
- }
-
- public boolean wasNull() throws SQLException
- {
- return wasNull;
***The diff for this file has been truncated for email.***
=======================================
--- /src/main/java/org/apache/cassandra/cql/jdbc/CassandraConnection.java
Wed Dec 21 20:57:28 2011
+++ /src/main/java/org/apache/cassandra/cql/jdbc/CassandraConnection.java
Wed Dec 21 21:16:09 2011
@@ -240,7 +240,7 @@
{
checkNotClosed();
// the rationale is there are really no commits in Cassandra so no
boundary...
- return CResultSet.DEFAULT_HOLDABILITY;
+ return CassandraResultSet.DEFAULT_HOLDABILITY;
}
public DatabaseMetaData getMetaData() throws SQLException
=======================================
---
/src/main/java/org/apache/cassandra/cql/jdbc/CassandraDatabaseMetaData.java
Thu Oct 13 00:45:22 2011
+++
/src/main/java/org/apache/cassandra/cql/jdbc/CassandraDatabaseMetaData.java
Wed Dec 21 21:16:09 2011
@@ -87,12 +87,12 @@
public ResultSet getAttributes(String arg0, String arg1, String arg2,
String arg3) throws SQLException
{
- return new CResultSet();
+ return new CassandraResultSet();
}
public ResultSet getBestRowIdentifier(String arg0, String arg1, String
arg2, int arg3, boolean arg4) throws SQLException
{
- return new CResultSet();
+ return new CassandraResultSet();
}
public String getCatalogSeparator() throws SQLException
@@ -107,22 +107,22 @@
public ResultSet getCatalogs() throws SQLException
{
- return new CResultSet();
+ return new CassandraResultSet();
}
public ResultSet getClientInfoProperties() throws SQLException
{
- return new CResultSet();
+ return new CassandraResultSet();
}
public ResultSet getColumnPrivileges(String arg0, String arg1, String
arg2, String arg3) throws SQLException
{
- return new CResultSet();
+ return new CassandraResultSet();
}
public ResultSet getColumns(String arg0, String arg1, String arg2,
String arg3) throws SQLException
{
- return new CResultSet();
+ return new CassandraResultSet();
}
public Connection getConnection() throws SQLException
@@ -132,7 +132,7 @@
public ResultSet getCrossReference(String arg0, String arg1, String
arg2, String arg3, String arg4, String arg5) throws SQLException
{
- return new CResultSet();
+ return new CassandraResultSet();
}
public int getDatabaseMajorVersion() throws SQLException
@@ -182,7 +182,7 @@
public ResultSet getExportedKeys(String arg0, String arg1, String
arg2) throws SQLException
{
- return new CResultSet();
+ return new CassandraResultSet();
}
public String getExtraNameCharacters() throws SQLException
@@ -192,12 +192,12 @@
public ResultSet getFunctionColumns(String arg0, String arg1, String
arg2, String arg3) throws SQLException
{
- return new CResultSet();
+ return new CassandraResultSet();
}
public ResultSet getFunctions(String arg0, String arg1, String arg2)
throws SQLException
{
- return new CResultSet();
+ return new CassandraResultSet();
}
public String getIdentifierQuoteString() throws SQLException
@@ -207,12 +207,12 @@
public ResultSet getImportedKeys(String arg0, String arg1, String
arg2) throws SQLException
{
- return new CResultSet();
+ return new CassandraResultSet();
}
public ResultSet getIndexInfo(String arg0, String arg1, String arg2,
boolean arg3, boolean arg4) throws SQLException
{
- return new CResultSet();
+ return new CassandraResultSet();
}
public int getJDBCMajorVersion() throws SQLException
@@ -333,12 +333,12 @@
public ResultSet getPrimaryKeys(String arg0, String arg1, String arg2)
throws SQLException
{
- return new CResultSet();
+ return new CassandraResultSet();
}
public ResultSet getProcedureColumns(String arg0, String arg1, String
arg2, String arg3) throws SQLException
{
- return new CResultSet();
+ return new CassandraResultSet();
}
public String getProcedureTerm() throws SQLException
@@ -348,12 +348,12 @@
public ResultSet getProcedures(String arg0, String arg1, String arg2)
throws SQLException
{
- return new CResultSet();
+ return new CassandraResultSet();
}
public int getResultSetHoldability() throws SQLException
{
- return CResultSet.DEFAULT_HOLDABILITY;
+ return CassandraResultSet.DEFAULT_HOLDABILITY;
}
public RowIdLifetime getRowIdLifetime() throws SQLException
@@ -378,12 +378,12 @@
public ResultSet getSchemas() throws SQLException
{
- return new CResultSet();
+ return new CassandraResultSet();
}
public ResultSet getSchemas(String arg0, String arg1) throws
SQLException
{
- return new CResultSet();
+ return new CassandraResultSet();
}
public String getSearchStringEscape() throws SQLException
@@ -398,12 +398,12 @@
public ResultSet getSuperTables(String arg0, String arg1, String arg2)
throws SQLException
{
- return new CResultSet();
+ return new CassandraResultSet();
}
public ResultSet getSuperTypes(String arg0, String arg1, String arg2)
throws SQLException
{
- return new CResultSet();
+ return new CassandraResultSet();
}
public String getSystemFunctions() throws SQLException
@@ -413,17 +413,17 @@
public ResultSet getTablePrivileges(String arg0, String arg1, String
arg2) throws SQLException
{
- return new CResultSet();
+ return new CassandraResultSet();
}
public ResultSet getTableTypes() throws SQLException
{
- return new CResultSet();
+ return new CassandraResultSet();
}
public ResultSet getTables(String arg0, String arg1, String arg2,
String[] arg3) throws SQLException
{
- return new CResultSet();
+ return new CassandraResultSet();
}
public String getTimeDateFunctions() throws SQLException
@@ -433,12 +433,12 @@
public ResultSet getTypeInfo() throws SQLException
{
- return new CResultSet();
+ return new CassandraResultSet();
}
public ResultSet getUDTs(String arg0, String arg1, String arg2, int[]
arg3) throws SQLException
{
- return new CResultSet();
+ return new CassandraResultSet();
}
public String getURL() throws SQLException
@@ -453,7 +453,7 @@
public ResultSet getVersionColumns(String arg0, String arg1, String
arg2) throws SQLException
{
- return new CResultSet();
+ return new CassandraResultSet();
}
public boolean insertsAreDetected(int arg0) throws SQLException
=======================================
---
/src/main/java/org/apache/cassandra/cql/jdbc/CassandraPreparedStatement.java
Sat Dec 17 20:01:00 2011
+++
/src/main/java/org/apache/cassandra/cql/jdbc/CassandraPreparedStatement.java
Wed Dec 21 21:16:09 2011
@@ -144,7 +144,7 @@
switch (result.getType())
{
case ROWS:
- currentResultSet = new CResultSet(this, result,
keyspace);
+ currentResultSet = new CassandraResultSet(this,
result, keyspace);
break;
case INT:
updateCount = result.getNum();
=======================================
--- /src/main/java/org/apache/cassandra/cql/jdbc/CassandraStatement.java
Thu Dec 1 10:31:03 2011
+++ /src/main/java/org/apache/cassandra/cql/jdbc/CassandraStatement.java
Wed Dec 21 21:16:09 2011
@@ -69,11 +69,11 @@
protected int maxRows = 0;
- protected int resultSetType = CResultSet.DEFAULT_TYPE;
-
- protected int resultSetConcurrency = CResultSet.DEFAULT_CONCURRENCY;
-
- protected int resultSetHoldability = CResultSet.DEFAULT_HOLDABILITY;
+ protected int resultSetType = CassandraResultSet.DEFAULT_TYPE;
+
+ protected int resultSetConcurrency =
CassandraResultSet.DEFAULT_CONCURRENCY;
+
+ protected int resultSetHoldability =
CassandraResultSet.DEFAULT_HOLDABILITY;
protected ResultSet currentResultSet = null;
@@ -164,7 +164,7 @@
switch (rSet.getType())
{
case ROWS:
- currentResultSet = new CResultSet(this, rSet,
keyspace);
+ currentResultSet = new CassandraResultSet(this, rSet,
keyspace);
break;
case INT:
updateCount = rSet.getNum();
==============================================================================
Revision: 1942c441ea5f
Author: Rick Shaw <wf...@gmail.com>
Date: Thu Feb 2 07:47:12 2012
Log: Client-side PreparedStatement updates for binary bind values
o CassandraConnection updated to pass a Binary as opposed to String list
o CassandraPreparedStetment rewrite
o new HandleObjects to support setObject() variations on a theme
o update pom.xml to use 0.7.0 of Thrift
http://code.google.com/a/apache-extras.org/p/cassandra-jdbc/source/detail?r=1942c441ea5f
Modified:
/pom.xml
/src/main/java/org/apache/cassandra/cql/jdbc/CassandraConnection.java
/src/main/java/org/apache/cassandra/cql/jdbc/CassandraPreparedStatement.java
/src/main/java/org/apache/cassandra/cql/jdbc/HandleObjects.java
=======================================
--- /pom.xml Wed Dec 21 20:57:28 2011
+++ /pom.xml Thu Feb 2 07:47:12 2012
@@ -135,7 +135,7 @@
<dependency>
<groupId>org.apache.thrift</groupId>
<artifactId>libthrift</artifactId>
- <version>0.6.1</version>
+ <version>0.7.0</version>
</dependency>
</dependencies>
=======================================
--- /src/main/java/org/apache/cassandra/cql/jdbc/CassandraConnection.java
Wed Dec 21 21:16:09 2011
+++ /src/main/java/org/apache/cassandra/cql/jdbc/CassandraConnection.java
Thu Feb 2 07:47:12 2012
@@ -20,6 +20,7 @@
*/
package org.apache.cassandra.cql.jdbc;
+import java.nio.ByteBuffer;
import java.sql.*;
import java.util.HashMap;
import java.util.List;
@@ -415,7 +416,7 @@
return execute(queryStr, defaultCompression);
}
- protected CqlResult execute(int itemId, List<String> values)
+ protected CqlResult execute(int itemId, List<ByteBuffer> values)
throws InvalidRequestException, UnavailableException,
TimedOutException, SchemaDisagreementException, TException
{
try
=======================================
---
/src/main/java/org/apache/cassandra/cql/jdbc/CassandraPreparedStatement.java
Wed Dec 21 21:16:09 2011
+++
/src/main/java/org/apache/cassandra/cql/jdbc/CassandraPreparedStatement.java
Thu Feb 2 07:47:12 2012
@@ -25,10 +25,6 @@
import static org.apache.cassandra.cql.jdbc.Utils.NO_UPDATE_COUNT;
import static org.apache.cassandra.cql.jdbc.Utils.SCHEMA_MISMATCH;
-import java.io.ByteArrayOutputStream;
-import java.io.IOException;
-import java.io.ObjectOutput;
-import java.io.ObjectOutputStream;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.net.URL;
@@ -77,7 +73,7 @@
private int count;
/** a Map of the current bound values encountered in setXXX methods */
- private Map<Integer,String> bindValues = new
LinkedHashMap<Integer,String>();
+ private Map<Integer,ByteBuffer> bindValues = new
LinkedHashMap<Integer,ByteBuffer>();
CassandraPreparedStatement(CassandraConnection con, String cql) throws
SQLException
@@ -107,9 +103,9 @@
if (index < 1 ) throw new
SQLRecoverableException(String.format("the column index must be a positive
number : %d", index));
}
- private List<String> getBindValues() throws SQLException
- {
- List<String> values = new ArrayList<String>();
+ private List<ByteBuffer> getBindValues() throws SQLException
+ {
+ List<ByteBuffer> values = new ArrayList<ByteBuffer>();
// System.out.println("bindValues.size() = "+bindValues.size());
// System.out.println("count = "+count);
if (bindValues.size() != count )
@@ -117,7 +113,7 @@
for (int i = 1; i <= count ; i++)
{
- String value = bindValues.get(i);
+ ByteBuffer value = bindValues.get(i);
if (value==null) throw new
SQLRecoverableException(String.format("the bound value for index: %d was
not set", i));
values.add(value);
}
@@ -231,7 +227,7 @@
{
checkNotClosed();
checkIndex(parameterIndex);
- bindValues.put(parameterIndex, decimal.toPlainString());
+ bindValues.put(parameterIndex,
JdbcDecimal.instance.decompose(decimal));
}
@@ -239,7 +235,7 @@
{
checkNotClosed();
checkIndex(parameterIndex);
- bindValues.put(parameterIndex, Boolean.valueOf(truth).toString());
+ bindValues.put(parameterIndex,
JdbcBoolean.instance.decompose(truth));
}
@@ -247,7 +243,7 @@
{
checkNotClosed();
checkIndex(parameterIndex);
- bindValues.put(parameterIndex, Byte.valueOf(b).toString());
+ bindValues.put(parameterIndex,
JdbcInteger.instance.decompose(BigInteger.valueOf(b)));
}
@@ -255,7 +251,7 @@
{
checkNotClosed();
checkIndex(parameterIndex);
- bindValues.put(parameterIndex,
ByteBufferUtil.bytesToHex(ByteBuffer.wrap(bytes)));
+ bindValues.put(parameterIndex, ByteBuffer.wrap(bytes));
}
@@ -263,9 +259,8 @@
{
checkNotClosed();
checkIndex(parameterIndex);
- // date type data is handled as an 8 byte Long value of
milliseconds since the epoch
- String millis = Long.valueOf(value.getTime()).toString();
- bindValues.put(parameterIndex, millis);
+ // date type data is handled as an 8 byte Long value of
milliseconds since the epoch (handled in decompose() )
+ bindValues.put(parameterIndex, JdbcDate.instance.decompose(value));
}
@@ -280,7 +275,7 @@
{
checkNotClosed();
checkIndex(parameterIndex);
- bindValues.put(parameterIndex, Double.valueOf(decimal).toString());
+ bindValues.put(parameterIndex,
JdbcDouble.instance.decompose(decimal));
}
@@ -288,7 +283,7 @@
{
checkNotClosed();
checkIndex(parameterIndex);
- bindValues.put(parameterIndex, Float.valueOf(decimal).toString());
+ bindValues.put(parameterIndex,
JdbcFloat.instance.decompose(decimal));
}
@@ -296,7 +291,7 @@
{
checkNotClosed();
checkIndex(parameterIndex);
- bindValues.put(parameterIndex,
Integer.valueOf(integer).toString());
+ bindValues.put(parameterIndex,
JdbcInt32.instance.decompose(integer));
}
@@ -304,7 +299,7 @@
{
checkNotClosed();
checkIndex(parameterIndex);
- bindValues.put(parameterIndex, Long.valueOf(bigint).toString());
+ bindValues.put(parameterIndex,
JdbcLong.instance.decompose(bigint));
}
@@ -320,7 +315,7 @@
checkNotClosed();
checkIndex(parameterIndex);
// silently ignore type for cassandra... just store an empty String
- bindValues.put(parameterIndex, "");
+ bindValues.put(parameterIndex, ByteBufferUtil.EMPTY_BYTE_BUFFER);
}
@@ -347,7 +342,7 @@
checkNotClosed();
checkIndex(parameterIndex);
- String variable = HandleObjects.makeString(object, targetSqlType,
scaleOrLength);
+ ByteBuffer variable = HandleObjects.makeBytes(object,
targetSqlType, scaleOrLength);
if (variable==null) throw new SQLNonTransientException("Problem
mapping object to JDBC Type");
@@ -358,7 +353,7 @@
{
checkNotClosed();
checkIndex(parameterIndex);
- bindValues.put(parameterIndex,
ByteBufferUtil.bytesToHex(ByteBuffer.wrap(value.getBytes())));
+ bindValues.put(parameterIndex, ByteBuffer.wrap(value.getBytes()));
}
@@ -366,7 +361,7 @@
{
checkNotClosed();
checkIndex(parameterIndex);
- bindValues.put(parameterIndex, Short.valueOf(smallint).toString());
+ bindValues.put(parameterIndex,
JdbcInteger.instance.decompose(BigInteger.valueOf(smallint)));
}
@@ -374,7 +369,7 @@
{
checkNotClosed();
checkIndex(parameterIndex);
- bindValues.put(parameterIndex, value);
+ bindValues.put(parameterIndex, ByteBufferUtil.bytes(value));
}
@@ -383,8 +378,7 @@
checkNotClosed();
checkIndex(parameterIndex);
// time type data is handled as an 8 byte Long value of
milliseconds since the epoch
- String millis = Long.valueOf(value.getTime()).toString();
- bindValues.put(parameterIndex, millis);
+ bindValues.put(parameterIndex,
JdbcLong.instance.decompose(Long.valueOf(value.getTime())));
}
@@ -399,9 +393,8 @@
{
checkNotClosed();
checkIndex(parameterIndex);
- // timestamp type data is handled as an 8 byte Long value of
milliseconds since the epoch
- String millis = Long.valueOf(value.getTime()).toString();
- bindValues.put(parameterIndex, millis);
+ // timestamp type data is handled as an 8 byte Long value of
milliseconds since the epoch. Nanos are not supported and are ignored
+ bindValues.put(parameterIndex,
JdbcLong.instance.decompose(Long.valueOf(value.getTime())));
}
@@ -418,6 +411,6 @@
checkIndex(parameterIndex);
// URl type data is handled as an string
String url = value.toString();
- bindValues.put(parameterIndex, url);
+ bindValues.put(parameterIndex, ByteBufferUtil.bytes(url));
}
}
=======================================
--- /src/main/java/org/apache/cassandra/cql/jdbc/HandleObjects.java Sat Dec
17 20:01:00 2011
+++ /src/main/java/org/apache/cassandra/cql/jdbc/HandleObjects.java Thu
Feb 2 07:47:12 2012
@@ -20,43 +20,75 @@
package org.apache.cassandra.cql.jdbc;
+import static org.apache.cassandra.cql.jdbc.JdbcDate.iso8601Patterns;
+
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectOutput;
import java.io.ObjectOutputStream;
import java.math.BigDecimal;
import java.math.BigInteger;
+import java.net.URL;
import java.nio.ByteBuffer;
+import java.sql.Date;
+import java.sql.RowId;
import java.sql.SQLException;
import java.sql.SQLNonTransientException;
+import java.sql.Time;
+import java.sql.Timestamp;
import java.sql.Types;
+import java.text.ParseException;
import org.apache.cassandra.utils.ByteBufferUtil;
+import org.apache.commons.lang.time.DateUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
-/**
- * @author rickshaw
- *
- */
public class HandleObjects
{
private static final Logger LOG =
LoggerFactory.getLogger(HandleObjects.class);
private static final String BAD_MAPPING = "encountered object of
class: %s, but only '%s' is supported to map to %s";
-
- private static final SQLException makeBadMapping(Class<?> badclass,
String javatype, String jdbctype)
- {
- return new SQLNonTransientException(String.format(BAD_MAPPING,
badclass, javatype, jdbctype));
+ private static final String STR_BOOL_NUMERIC = "String, Boolean, or a
Numeric class";
+
+ private static Long fromString(String source) throws SQLException
+ {
+ long millis = 0;
+ if (source.isEmpty() ||source.toLowerCase().equals("now")) return
System.currentTimeMillis();
+ // Milliseconds since epoch?
+ else if (source.matches("^\\d+$"))
+ {
+ try
+ {
+ Long.parseLong(source);
+ }
+ catch (NumberFormatException e)
+ {
+ throw new SQLNonTransientException(String.format("unable to
make long (for date) from: '%s'", source), e);
+ }
+ }
+ // Last chance, attempt to parse as date-time string
+ else
+ {
+ try
+ {
+ millis = DateUtils.parseDate(source,
iso8601Patterns).getTime();
+ }
+ catch (ParseException e1)
+ {
+ throw new SQLNonTransientException(String.format("unable to
coerce '%s' to a formatted date (long)", source), e1);
+ }
+ }
+ return millis;
}
- private static final String bufferAsHex(ByteBuffer buffer)
- {
- return ByteBufferUtil.bytesToHex(buffer);
+ private static final SQLException makeBadMapping(Class<?> badclass,
String javatype, String jdbctype)
+ {
+ return new SQLNonTransientException(String.format(BAD_MAPPING,
badclass, javatype, jdbctype));
}
- private static final String javaObject(Object object) throws
SQLException
+ private static final ByteBuffer javaObject(Object object) throws
SQLException
{
byte[] bytes = null;
try
@@ -75,58 +107,289 @@
throw new SQLNonTransientException("Problem serializing the
Java object", e);
}
- return bufferAsHex(ByteBuffer.wrap(bytes));
+ return ByteBuffer.wrap(bytes);
}
-
- public static final String makeString(Object object, int
targetSqlType, int scaleOrLength) throws SQLException
+ private static final Integer objectToINTEGER(Class<? extends Object>
objectClass, Object object)
+ {
+ // Strings should always work
+ if (objectClass == String.class) return Integer.valueOf((String)
object);
+
+ // Booleans are either false=0 or true=1
+ if (objectClass == Boolean.class) return ((Boolean) object) ==
false ? 0 : 1;
+
+ // All the integer (non floating-point) are simple
+ if (objectClass == Integer.class) return (Integer) object;
+ else if (objectClass == BigInteger.class) return ((BigInteger)
object).intValue();
+ else if (objectClass == Long.class) return ((Long)
object).intValue();
+ else if (objectClass == Short.class) return ((Short)
object).intValue();
+ else if (objectClass == Byte.class) return ((Byte)
object).intValue();
+
+ // Floating ones need to just pass the integer part
+ else if (objectClass == Double.class) return
Integer.valueOf(((Double) object).intValue());
+ else if (objectClass == Float.class) return
Integer.valueOf(((Float) object).intValue());
+ else if (objectClass == BigDecimal.class) return
Integer.valueOf(((BigDecimal) object).intValue());
+ else return null; // this should not happen
+ }
+
+ private static final Long objectToBIGINT(Class<? extends Object>
objectClass, Object object)
+ {
+ // Strings should always work
+ if (objectClass == String.class) return Long.valueOf((String)
object);
+
+ // Booleans are either false=0 or true=1
+ if (objectClass == Boolean.class) return ((Boolean) object) ==
false ? 0L : 1L;
+
+ // All the integer (non floating-point) are simple
+ if (objectClass == Integer.class) return Long.valueOf((Integer)
object);
+ else if (objectClass == BigInteger.class) return ((BigInteger)
object).longValue();
+ else if (objectClass == Long.class) return ((Long)
object).longValue();
+ else if (objectClass == Short.class) return ((Short)
object).longValue();
+ else if (objectClass == Byte.class) return ((Byte)
object).longValue();
+
+ // Floating ones need to just pass the integer part
+ else if (objectClass == Double.class) return
Long.valueOf(((Double) object).longValue());
+ else if (objectClass == Float.class) return Long.valueOf(((Float)
object).longValue());
+ else if (objectClass == BigDecimal.class) return
Long.valueOf(((BigDecimal) object).longValue());
+ else return null; // this should not happen
+ }
+
+ private static final Long objectToDATEorTIMEorTIMESTAMP(Class<?
extends Object> objectClass, Object object) throws SQLException
+ {
+ // Strings should always work
+ if (objectClass == String.class) return fromString((String)
object);
+
+ if (objectClass == java.util.Date.class) return ((java.util.Date)
object).getTime();
+ else if (objectClass == Date.class) return ((Date)
object).getTime();
+ else if (objectClass == Time.class) return ((Time)
object).getTime();
+ else if (objectClass == Timestamp.class) return ((Timestamp)
object).getTime();
+ else return null; // this should not happen
+ }
+
+ private static final Boolean objectToBOOLEAN(Class<? extends Object>
objectClass, Object object)
+ {
+ // Strings should always work
+ if (objectClass == String.class) return Boolean.valueOf((String)
object);
+
+ // Booleans are either false=0 or true=1
+ if (objectClass == Boolean.class) return ((Boolean) object);
+
+ // All the integer (non floating-point) are simple
+ if (objectClass == Integer.class) return ((Integer) object) == 0 ?
false : true;
+ else if (objectClass == BigInteger.class) return ((BigInteger)
object).intValue() == 0 ? false : true;
+ else if (objectClass == Long.class) return ((Long) object) == 0 ?
false : true;
+ else if (objectClass == Short.class) return ((Short) object) ==
0 ? false : true;
+ else if (objectClass == Byte.class) return ((Byte) object) == 0 ?
false : true;
+
+ // Floating ones need to just pass the integer part
+ else if (objectClass == Double.class) return
Integer.valueOf(((Double) object).intValue()) == 0 ? false : true;
+ else if (objectClass == Float.class) return
Integer.valueOf(((Float) object).intValue()) == 0 ? false : true;
+ else if (objectClass == BigDecimal.class) return
Integer.valueOf(((BigDecimal) object).intValue()) == 0 ? false : true;
+ else return null; // this should not happen
+ }
+
+ private static final BigInteger
objectToBITorTINYINTorSMALLINTorNUMERIC(Class<? extends Object>
objectClass, Object object)
+ {
+ // Strings should always work
+ if (objectClass == String.class) return new BigInteger((String)
object);
+
+ // Booleans are either false=0 or true=1
+ if (objectClass == Boolean.class) return ((Boolean) object) ==
false ? BigInteger.ZERO : BigInteger.ONE;
+
+ // All the integer (non floating-point) are simple
+ if (objectClass == Integer.class) return
BigInteger.valueOf((Integer) object);
+ else if (objectClass == BigInteger.class) return ((BigInteger)
object);
+ else if (objectClass == Long.class) return
BigInteger.valueOf(((Long) object));
+ else if (objectClass == Short.class) return
BigInteger.valueOf(((Short) object).longValue());
+ else if (objectClass == Byte.class) return
BigInteger.valueOf(((Byte) object).longValue());
+
+ // Floating ones need to just pass the integer part
+ else if (objectClass == Double.class) return
BigInteger.valueOf(((Double) object).longValue());
+ else if (objectClass == Float.class) return
BigInteger.valueOf(((Float) object).longValue());
+ else if (objectClass == BigDecimal.class) return
BigInteger.valueOf(((BigDecimal) object).intValue());
+ else return null; // this should not happen
+ }
+
+
+
+ public static final ByteBuffer makeBytes(Object object, int
targetSqlType, int scaleOrLength) throws SQLException
{
Class<? extends Object> objectClass = object.getClass();
- // see if we can map to an supported AbstractType
+ // Type check first
switch (targetSqlType)
{
- case Types.JAVA_OBJECT:
- return javaObject(object);
+ case Types.TINYINT:
+ // Only Numeric classes, Strings and Booleans are
supported for transformation to TINYINT
+ if (!(objectClass == String.class || objectClass ==
Boolean.class || Number.class.isAssignableFrom(object.getClass())))
+ throw
makeBadMapping(objectClass,STR_BOOL_NUMERIC,"TINYINT");
+ break;
+
+ case Types.SMALLINT:
+ // Only Numeric classes, Strings and Booleans are
supported for transformation to SMALLINT
+ if (!(objectClass == String.class || objectClass ==
Boolean.class || Number.class.isAssignableFrom(object.getClass())))
+ throw
makeBadMapping(objectClass,STR_BOOL_NUMERIC,"SMALLINT");
+ break;
+
+
+ case Types.INTEGER:
+ // Only Numeric classes, Strings and Booleans are
supported for transformation to INTEGER
+ if (!(objectClass == String.class || objectClass ==
Boolean.class || Number.class.isAssignableFrom(object.getClass())))
+ throw
makeBadMapping(objectClass,STR_BOOL_NUMERIC,"INTEGER");
+ break;
+
+ case Types.BIGINT:
+ // Only Numeric classes, Strings and Booleans are
supported for transformation to BIGINT
+ if (!(objectClass == String.class || objectClass ==
Boolean.class || Number.class.isAssignableFrom(object.getClass())))
+ throw
makeBadMapping(objectClass,STR_BOOL_NUMERIC,"BIGINT");
+ break;
+
+ case Types.REAL:
+ case Types.FLOAT:
+ case Types.DOUBLE:
+ case Types.DECIMAL:
+ // Only Numeric classes Strings and Booleans are supported
for transformation to REAL,FLOAT,DOUBLE,DECIMAL
+ if (!(objectClass == String.class || objectClass ==
Boolean.class || Number.class.isAssignableFrom(object.getClass())))
+ throw makeBadMapping(objectClass,STR_BOOL_NUMERIC,"the
floating point types");
+ break;
+
+ case Types.NUMERIC:
+ //NB This as a special case variation for Cassandra!!
NUMERIC is transformed to java BigInteger (varint CQL type)
+ //
+ // Only Numeric classes Strings and Booleans are supported
for transformation to NUMERIC
+ if (!(objectClass == String.class || objectClass ==
Boolean.class || Number.class.isAssignableFrom(object.getClass())))
+ throw
makeBadMapping(objectClass,STR_BOOL_NUMERIC,"NUMERIC");
+ break;
+
+ case Types.BIT:
+ // Only Numeric classes Strings and Booleans are supported
for transformation to BIT
+ if (!(objectClass == String.class || objectClass ==
Boolean.class || Number.class.isAssignableFrom(object.getClass())))
+ throw
makeBadMapping(objectClass,STR_BOOL_NUMERIC,"BIT");
+ break;
+
+ case Types.BOOLEAN:
+ // Only Numeric classes Strings and Booleans are supported
for transformation to BOOLEAN
+ if (!(objectClass == String.class || objectClass ==
Boolean.class || Number.class.isAssignableFrom(object.getClass())))
+ throw
makeBadMapping(objectClass,STR_BOOL_NUMERIC,"BOOLEAN");
+ break;
+
+ case Types.CHAR:
+ case Types.VARCHAR:
+ case Types.LONGVARCHAR:
+ case Types.NVARCHAR:
+ case Types.LONGNVARCHAR:
+ if (!objectClass.isAssignableFrom(String.class))
+ throw makeBadMapping(objectClass, "String", "the
various VARCHAR types");
+ break;
case Types.BINARY:
case Types.VARBINARY:
case Types.LONGVARBINARY:
- if (objectClass.isAssignableFrom(ByteBuffer.class))
- {
- return bufferAsHex(((ByteBuffer) object));
- }
- else throw
makeBadMapping(objectClass, "ByteBuffer", "BINARY");
+ if (!(objectClass.isAssignableFrom(ByteBuffer.class) ||
objectClass.getSimpleName().equals("byte[]")))
+ throw makeBadMapping(objectClass,"ByteBuffer or
byte[]","the BINARY Types");
+ break;
+
+ case Types.DATE:
+ if (!(objectClass == String.class || objectClass ==
java.util.Date.class || objectClass == Date.class || objectClass ==
Timestamp.class))
+ throw makeBadMapping(objectClass,"String, Date(java
and sql) or Timestamp types","DATE");
+ break;
+
+ case Types.TIME:
+ if (!(objectClass == String.class || objectClass ==
java.util.Date.class || objectClass == Time.class || objectClass ==
Timestamp.class))
+ throw makeBadMapping(objectClass,"String, Date (java),
Time or Timestamp types","TIME");
+ break;
+
+ case Types.TIMESTAMP:
+ if (!(objectClass == String.class || objectClass ==
java.util.Date.class || objectClass == Date.class || objectClass ==
Timestamp.class))
+ throw makeBadMapping(objectClass,"String, Date(java
and sql) or Timestamp types","TIMESTAMP");
+ break;
+
+ case Types.DATALINK:
+ if (objectClass != URL.class) throw
makeBadMapping(objectClass,"a URL type","DATALINK");
+ break;
+
+ case Types.JAVA_OBJECT:
+ break;
+
+ case Types.ROWID:
+ if (objectClass != RowId.class) throw
makeBadMapping(objectClass,"a RowId type","ROWID");
+ break;
+
+ default:
+ throw new SQLNonTransientException("Unsupported
transformation to Jdbc Type: "+ targetSqlType);
+ }
+
+ // see if we can map to an supported Type
+ switch (targetSqlType)
+ {
+ case Types.BIT:
+ BigInteger bitvalue =
objectToBITorTINYINTorSMALLINTorNUMERIC(objectClass, object);
+ assert bitvalue != null;
+ return JdbcInteger.instance.decompose((bitvalue ==
BigInteger.ZERO) ? BigInteger.ZERO : BigInteger.ONE);
+
+ case Types.TINYINT:
+ case Types.SMALLINT:
+ case Types.NUMERIC:
+ BigInteger varint =
objectToBITorTINYINTorSMALLINTorNUMERIC(objectClass, object);
+ assert varint != null;
+ return JdbcInteger.instance.decompose(varint);
+
+ case Types.INTEGER:
+ Integer value = objectToINTEGER(objectClass, object);
+ assert value != null;
+ return JdbcInt32.instance.decompose(value);
+
+ case Types.BIGINT:
+ Long longvalue = objectToBIGINT(objectClass, object);
+ assert longvalue != null;
+ return JdbcLong.instance.decompose(longvalue);
+
+ case Types.BOOLEAN:
+ Boolean bool = objectToBOOLEAN(objectClass, object);
+ assert bool != null;
+ return JdbcBoolean.instance.decompose(bool);
case Types.CHAR:
case Types.VARCHAR:
case Types.LONGVARCHAR:
case Types.NVARCHAR:
case Types.LONGNVARCHAR:
- if (objectClass.isAssignableFrom(String.class))
- {
- return object.toString();
- }
- else throw makeBadMapping(objectClass, "String", "the
various VARCHAR types");
-
- case Types.INTEGER:
- // Strings should always work
- if (objectClass == String.class) return object.toString();
-
- // Only Numeric classes (besides String)
- if (!Number.class.isAssignableFrom(object.getClass()))
throw makeBadMapping(objectClass, "a Numeric class (or String)", "INTEGER");
-
- // All the integer (non floating-point) are simple
- if (objectClass == Integer.class || objectClass ==
BigInteger.class || objectClass == Long.class ||
- objectClass == Short.class || objectClass ==
Byte.class) return object.toString();
-
- // Floating ones need to just pass the integer part
- else if (objectClass == Double.class) return
Integer.valueOf(((Double) object).intValue()).toString();
- else if (objectClass == Float.class) return
Integer.valueOf(((Float) object).intValue()).toString();
- else if (objectClass == BigDecimal.class) return
Integer.valueOf(((BigDecimal) object).intValue()).toString();
+ return ByteBufferUtil.bytes((String) object);
+
+ case Types.BINARY:
+ case Types.VARBINARY:
+ case Types.LONGVARBINARY:
+ if (objectClass.isAssignableFrom(ByteBuffer.class))
+ {
+ return ((ByteBuffer) object);
+ }
+ else if (objectClass.getSimpleName().equals("byte[]"))
+ {
+ return ByteBuffer.wrap((byte[]) object);
+ }
+ else return null; // this should not happen
+
+
+ case Types.DATE:
+ case Types.TIME:
+ case Types.TIMESTAMP:
+ Long millis = objectToDATEorTIMEorTIMESTAMP(objectClass,
object);
+ assert millis != null;
+ return JdbcLong.instance.decompose(millis);
+
+ case Types.DATALINK:
+ String urlAsString = ((URL) object).toExternalForm();
+ return JdbcUTF8.instance.decompose(urlAsString);
+
+ case Types.JAVA_OBJECT:
+ return javaObject(object);
+
+ case Types.ROWID:
+ byte[] bytes = ((RowId) object).getBytes();
+ return ByteBuffer.wrap(bytes);
default:
- LOG.warn("Unhandled JDBC type: "+targetSqlType);
+ LOG.warn("Unhandled JDBC type: " + targetSqlType);
return null;
}
}
==============================================================================
Revision: f0e16ff1bc91
Author: Rick Shaw <wf...@gmail.com>
Date: Thu Feb 2 07:58:40 2012
Log: Update various Unit and Functional Tests
o Update tests to make stand alone (Eclipse) testing easier by providing
CLI based (-D) argument overrides for host and port
o Provide a reasonably rigorous unit test for HandleObject helper class
http://code.google.com/a/apache-extras.org/p/cassandra-jdbc/source/detail?r=f0e16ff1bc91
Modified:
/src/test/java/org/apache/cassandra/cql/jdbc/DataSourceTest.java
/src/test/java/org/apache/cassandra/cql/jdbc/HandleObjectsUnitTest.java
/src/test/java/org/apache/cassandra/cql/jdbc/JdbcRegressionTest.java
/src/test/java/org/apache/cassandra/cql/jdbc/PreparedStatementTest.java
=======================================
--- /src/test/java/org/apache/cassandra/cql/jdbc/DataSourceTest.java Wed
Dec 21 20:57:28 2011
+++ /src/test/java/org/apache/cassandra/cql/jdbc/DataSourceTest.java Thu
Feb 2 07:58:40 2012
@@ -23,21 +23,44 @@
import static org.junit.Assert.*;
import java.io.PrintWriter;
+import java.sql.DriverManager;
import java.sql.SQLFeatureNotSupportedException;
+import java.sql.Statement;
import javax.sql.DataSource;
import org.apache.cassandra.cql.ConnectionDetails;
+import org.junit.BeforeClass;
import org.junit.Test;
public class DataSourceTest
{
- private static final String HOST = ConnectionDetails.getHost();
- private static final int PORT = ConnectionDetails.getPort();
- private static final String KEYSPACE = "Test";
+ private static final String HOST = System.getProperty("host",
ConnectionDetails.getHost());
+ private static final int PORT =
Integer.parseInt(System.getProperty("port",
ConnectionDetails.getPort()+""));
+ private static final String KEYSPACE = "JdbcTestKeyspace";
private static final String USER = "JohnDoe";
private static final String PASSWORD = "secret";
-
+
+ private static java.sql.Connection con = null;
+
+
+ @BeforeClass
+ public static void setUpBeforeClass() throws Exception
+ {
+ Class.forName("org.apache.cassandra.cql.jdbc.CassandraDriver");
+ con =
DriverManager.getConnection(String.format("jdbc:cassandra://%s:%d/%s",HOST,PORT,"system"));
+ Statement stmt = con.createStatement();
+
+ // Drop Keyspace
+ String dropKS = String.format("DROP KEYSPACE %s;",KEYSPACE);
+
+ try { stmt.execute(dropKS);}
+ catch (Exception e){/* Exception on DROP is OK */}
+
+ // Create KeySpace
+ String createKS = String.format("CREATE KEYSPACE %s WITH
strategy_class = SimpleStrategy AND strategy_options:replication_factor =
1;",KEYSPACE);
+ stmt.execute(createKS);
+ }
@Test
public void testConstructor() throws Exception
{
@@ -51,25 +74,17 @@
DataSource ds = new
CassandraDataSource(HOST,PORT,KEYSPACE,USER,PASSWORD);
assertNotNull(ds);
-// PrintWriter pw = new PrintWriter(System.err);
-
// null username and password
java.sql.Connection cnx = ds.getConnection(null, null);
assertFalse(cnx.isClosed());
ds.setLoginTimeout(5);
assertEquals(5, ds.getLoginTimeout());
-// ds.setLogWriter(pw);
-// assertNotNull(ds.getLogWriter());
-
// no username and password
cnx = ds.getConnection();
assertFalse(cnx.isClosed());
ds.setLoginTimeout(5);
assertEquals(5, ds.getLoginTimeout());
-
-// ds.setLogWriter(pw);
-// assertNotNull(ds.getLogWriter());
}
=======================================
--- /src/test/java/org/apache/cassandra/cql/jdbc/HandleObjectsUnitTest.java
Sat Dec 17 20:01:00 2011
+++ /src/test/java/org/apache/cassandra/cql/jdbc/HandleObjectsUnitTest.java
Thu Feb 2 07:58:40 2012
@@ -24,19 +24,20 @@
import java.io.Serializable;
import java.math.BigDecimal;
+import java.nio.ByteBuffer;
+import java.sql.Date;
import java.sql.SQLException;
+import java.sql.SQLNonTransientException;
+import java.sql.Time;
import java.sql.Types;
import java.util.ArrayList;
import java.util.List;
import org.apache.cassandra.cql.TestClass;
+import org.apache.cassandra.utils.ByteBufferUtil;
import org.junit.BeforeClass;
import org.junit.Test;
-/**
- * @author rickshaw
- *
- */
public class HandleObjectsUnitTest
{
@@ -48,40 +49,126 @@
{}
@Test
- public void test1Varchar() throws SQLException
+ public void test0Unsupported() throws Exception
{
Object object = new String("This is a String");
- String string = HandleObjects.makeString(object, Types.VARCHAR, 0);
- assertEquals("This is a String", string);
+ boolean passed = false;
+ int[] notsupported =
{Types.ARRAY,Types.BLOB,Types.CLOB,Types.DISTINCT,
+
Types.NCLOB,Types.NULL,Types.OTHER,Types.REF,Types.SQLXML,Types.STRUCT};
+
+ for (int item:notsupported)
+ {
+ passed = false;
+ try
+ {
+ ByteBuffer bb = HandleObjects.makeBytes(object, item, 0);
+ }
+ catch (Exception e)
+ {
+ passed = true;
+ }
+ assertTrue(passed);
+ }
}
+ @Test
+ public void test1Varchar() throws Exception
+ {
+ Object object = new String("This is a String");
+ ByteBuffer bb = HandleObjects.makeBytes(object, Types.VARCHAR, 0);
+ String string = ByteBufferUtil.string(bb);
+ assertEquals(object, string);
+ }
+
@Test
- public void test2Integer() throws SQLException
+ public void test2Integer() throws Exception
{
Object object = new Integer(12345);
- String string = HandleObjects.makeString(object, Types.INTEGER, 0);
- assertEquals("12345", string);
+ ByteBuffer bb = HandleObjects.makeBytes(object, Types.INTEGER, 0);
+ Integer integer = ByteBufferUtil.toInt(bb);
+ assertEquals(object, integer);
+
+ object = 12345;
+ Class<?> objectclass = object.getClass();
+ System.out.println("object class of 12345 is : " + objectclass );
+ bb = HandleObjects.makeBytes(object, Types.INTEGER, 0);
+ integer = ByteBufferUtil.toInt(bb);
+ assertEquals(object, integer);
object = new Long(123457890);
- string = HandleObjects.makeString(object, Types.INTEGER, 0);
- assertEquals("123457890", string);
+ bb = HandleObjects.makeBytes(object, Types.INTEGER, 0);
+ integer = ByteBufferUtil.toInt(bb);
+ Integer integeronly = ((Long)object).intValue();
+ assertEquals(integeronly, integer);
object = new BigDecimal(123457890.789);
- string = HandleObjects.makeString(object, Types.INTEGER, 0);
- assertEquals("123457890", string);
+ bb = HandleObjects.makeBytes(object, Types.INTEGER, 0);
+ integer = ByteBufferUtil.toInt(bb);
+ Integer integerpart = ((BigDecimal)object).intValue();
+
+ assertEquals(integerpart, integer);
+ }
+
+ @Test
+ public void test3Binary() throws Exception
+ {
+ String stringvalue = "A simple string value";
+ Object object = stringvalue.getBytes();
+ ByteBuffer bb = HandleObjects.makeBytes(object, Types.BINARY, 0);
+ assertEquals(stringvalue, ByteBufferUtil.string(bb));
}
@Test
- public void test9JavaObject() throws SQLException
+ public void test4Boolean() throws Exception
+ {
+ Object object = 0;
+ ByteBuffer bb = HandleObjects.makeBytes(object, Types.BOOLEAN, 0);
+ assertFalse(JdbcBoolean.instance.compose(bb));
+
+ object = 12345;
+ bb = HandleObjects.makeBytes(object, Types.BOOLEAN, 0);
+ assertTrue(JdbcBoolean.instance.compose(bb));
+
+ object = 0.0;
+ bb = HandleObjects.makeBytes(object, Types.BOOLEAN, 0);
+ assertFalse(JdbcBoolean.instance.compose(bb));
+
+ object = 12345.67;
+ bb = HandleObjects.makeBytes(object, Types.BOOLEAN, 0);
+ assertTrue(JdbcBoolean.instance.compose(bb));
+
+ object = true;
+ bb = HandleObjects.makeBytes(object, Types.BOOLEAN, 0);
+ assertTrue(JdbcBoolean.instance.compose(bb));
+ }
+
+ @Test
+ public void test5Date() throws Exception
+ {
+
+ Time time = new Time(3600L * 20);
+ Object object = time;
+ ByteBuffer bb = HandleObjects.makeBytes(object, Types.TIME, 0);
+ assertEquals(time.getTime(),
JdbcDate.instance.compose(bb).getTime());
+
+ java.util.Date now = new java.util.Date();
+ Date date = new Date(now.getTime());
+ object = date;
+ bb = HandleObjects.makeBytes(object, Types.DATE, 0);
+ assertEquals(date.getTime(),
JdbcDate.instance.compose(bb).getTime());
+ }
+
+ @Test
+ public void test99JavaObject() throws SQLException
{
List<String> myList = new ArrayList<String>();
myList.add("A");
myList.add("B");
myList.add("C");
Object object = new TestClass("This is a String", 3456,myList );
- String string = HandleObjects.makeString(object,
Types.JAVA_OBJECT, 0);
- System.out.println("Java object = "+ string);
+ ByteBuffer bb = HandleObjects.makeBytes(object, Types.JAVA_OBJECT,
0);
+ System.out.println("Java object = "+
ByteBufferUtil.bytesToHex(bb));
}
}
=======================================
--- /src/test/java/org/apache/cassandra/cql/jdbc/JdbcRegressionTest.java
Tue Dec 20 21:22:20 2011
+++ /src/test/java/org/apache/cassandra/cql/jdbc/JdbcRegressionTest.java
Thu Feb 2 07:58:40 2012
@@ -33,23 +33,31 @@
public class JdbcRegressionTest
{
+ private static final String HOST = System.getProperty("host",
ConnectionDetails.getHost());
+ private static final int PORT =
Integer.parseInt(System.getProperty("port",
ConnectionDetails.getPort()+""));
+ private static final String KEYSPACE = "JdbcTestKeyspace";
+
private static java.sql.Connection con = null;
+
@BeforeClass
public static void setUpBeforeClass() throws Exception
{
Class.forName("org.apache.cassandra.cql.jdbc.CassandraDriver");
- con =
DriverManager.getConnection(String.format("jdbc:cassandra://%s:%d/%s",
- ConnectionDetails.getHost(),
- ConnectionDetails.getPort(),
- "JdbcTestKeyspace"));
+ con =
DriverManager.getConnection(String.format("jdbc:cassandra://%s:%d/%s",HOST,PORT,KEYSPACE));
Statement stmt = con.createStatement();
+
+ // Drop Keyspace
+ String dropKS = String.format("DROP KEYSPACE %s;",KEYSPACE);
+
+ try { stmt.execute(dropKS);}
+ catch (Exception e){/* Exception on DROP is OK */}
// Create KeySpace
- String createKS = "CREATE KEYSPACE 'JdbcTestKeyspace' WITH "
- + "strategy_class = SimpleStrategy AND
strategy_options:replication_factor = 1;";
+ String createKS = String.format("CREATE KEYSPACE %s WITH
strategy_class = SimpleStrategy AND strategy_options:replication_factor =
1;",KEYSPACE);
+ stmt = con.createStatement();
stmt.execute(createKS);
-
+
// Create the target Column family
String createCF = "CREATE COLUMNFAMILY RegressionTest (KEY text
PRIMARY KEY,"
+ "bValue boolean, "
@@ -62,11 +70,7 @@
con.close();
// open it up again to see the new CF
- con =
DriverManager.getConnection(String.format("jdbc:cassandra://%s:%d/%s",
- ConnectionDetails.getHost(),
- ConnectionDetails.getPort(),
- "JdbcTestKeyspace"));
-
+ con =
DriverManager.getConnection(String.format("jdbc:cassandra://%s:%d/%s",HOST,PORT,KEYSPACE));
}
@Test
@@ -90,10 +94,10 @@
long l = result.getLong("notThere");
assertEquals(0,l);
- System.out.println("l = "+ l + " ... wasNull() = "+
result.wasNull());
+// System.out.println("l = "+ l + " ... wasNull() = "+
result.wasNull());
int i = result.getInt(3);
- System.out.println("i ="+ i + " ... wasNull() = "+
result.wasNull());
+// System.out.println("i ="+ i + " ... wasNull() = "+
result.wasNull());
assertEquals(2000, i);
}
=======================================
--- /src/test/java/org/apache/cassandra/cql/jdbc/PreparedStatementTest.java
Wed Dec 21 20:57:28 2011
+++ /src/test/java/org/apache/cassandra/cql/jdbc/PreparedStatementTest.java
Thu Feb 2 07:58:40 2012
@@ -38,17 +38,17 @@
public class PreparedStatementTest
{
private static java.sql.Connection con = null;
-
-// private static final Schema schema = new
Schema(ConnectionDetails.getHost(), ConnectionDetails.getPort());
- private static final Schema schema = new Schema("localhost", 9160);
+ private static String host = System.getProperty("host",
ConnectionDetails.getHost());
+ private static int port = Integer.parseInt(System.getProperty("port",
ConnectionDetails.getPort()+""));
+
+ private static final Schema schema = new Schema(host, port);
@BeforeClass
public static void waxOn() throws Exception
{
schema.createSchema();
Class.forName("org.apache.cassandra.cql.jdbc.CassandraDriver");
- con =
DriverManager.getConnection(String.format("jdbc:cassandra://%s:%d/%s",
ConnectionDetails.getHost(), ConnectionDetails.getPort(),
Schema.KEYSPACE_NAME));
-// con =
DriverManager.getConnection(String.format("jdbc:cassandra://%s:%d/%s", "localhost",
9160, Schema.KEYSPACE_NAME));
+ con =
DriverManager.getConnection(String.format("jdbc:cassandra://%s:%d/%s",
host, port, Schema.KEYSPACE_NAME));
}
@Test