NullPointerException while using JSON datatype with Jooq - jooq

I am using jooq 3.15.12 and I am getting the following error while generating code:
Error while generating table ArmourDb.REGEX
java.lang.RuntimeException: java.lang.RuntimeException: java.lang.NullPointerException
at org.jooq.meta.AbstractDatabase.onError(AbstractDatabase.java:3104)
at org.jooq.meta.AbstractDatabase.getRelations(AbstractDatabase.java:2317)
at org.jooq.meta.DefaultColumnDefinition.getPrimaryKey(DefaultColumnDefinition.java:100)
at org.jooq.meta.AbstractTableDefinition.getPrimaryKey(AbstractTableDefinition.java:91)
at org.jooq.codegen.JavaGenerator.generateTable(JavaGenerator.java:5019)
at org.jooq.codegen.JavaGenerator.generateTables(JavaGenerator.java:5000)
at org.jooq.codegen.JavaGenerator.generate(JavaGenerator.java:582)
at org.jooq.codegen.JavaGenerator.generate(JavaGenerator.java:537)
at org.jooq.codegen.JavaGenerator.generate(JavaGenerator.java:436)
at org.jooq.codegen.GenerationTool.run0(GenerationTool.java:879)
at org.jooq.codegen.GenerationTool.run(GenerationTool.java:233)
at org.jooq.codegen.GenerationTool.generate(GenerationTool.java:228)
at com.linkedin.gradle.mysql.tasks.MySQLJooqCodegenTask.taskAction(MySQLJooqCodegenTask.java:32)
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
The table looks like this:
CREATE TABLE REGEX (
ID BIGINT NOT NULL PRIMARY KEY AUTO_INCREMENT,
WORD VARCHAR(4000) NOT NULL,
DESCRIPTION VARCHAR(1000),
TRAITS JSON,
MODIFIED_BY VARCHAR(255) NOT NULL,
MODIFIED_AT TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
CREATED_AT TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP
) ENGINE = InnoDB;
I have observed that JSON field is causing this issue, if I change the datatype from json to some other type then the java files get generated without any issue.
As per the stack trace, NullPointerException is coming while getting relations of the table.

Related

java.lang.ClassCastException: java.util.ArrayList cannot be cast to java.util.UUID exception with cassandra?

I have a spring boot java application that talks to cassandra .
However one of my queries is failing .
public class ParameterisedListItemRepository {
private PreparedStatement findByIds;
public ParameterisedListItemRepository(Session session, Validator validator, ParameterisedListMsisdnRepository parameterisedListMsisdnRepository ) {
this.findByIds = session.prepare("SELECT * FROM mep_parameterisedListItem WHERE id IN ( :ids )");
}
public List<ParameterisedListItem> findAll(List<UUID> ids){
List<ParameterisedListItem> parameterisedListItemList = new ArrayList<>();
BoundStatement stmt =this.findByIds.bind();
stmt.setList("ids", ids);
session.execute(stmt)
.all()
.stream()
.map(parameterisedListItemMapper)
.forEach(parameterisedListItemList::add);
return parameterisedListItemList;
}
}
the following is the stack trace
java.lang.ClassCastException: java.util.ArrayList cannot be cast to java.util.UUID
at com.datastax.driver.core.TypeCodec$AbstractUUIDCodec.serialize(TypeCodec.java:1626)
at com.datastax.driver.core.AbstractData.setList(AbstractData.java:358)
at com.datastax.driver.core.AbstractData.setList(AbstractData.java:374)
at com.datastax.driver.core.BoundStatement.setList(BoundStatement.java:681)
at com.openmind.primecast.repository.ParameterisedListItemRepository.findAll(ParameterisedListItemRepository.java:128)
at com.openmind.primecast.repository.ParameterisedListItemRepository$$FastClassBySpringCGLIB$$46ffc15e.invoke(<generated>)
at org.springframework.cglib.proxy.MethodProxy.invoke(MethodProxy.java:204)
at org.springframework.aop.framework.CglibAopProxy$CglibMethodInvocation.invokeJoinpoint(CglibAopProxy.java:738)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:157)
at org.springframework.aop.interceptor.ExposeInvocationInterceptor.invoke(ExposeInvocationInterceptor.java:92)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
at org.springframework.aop.framework.CglibAopProxy$DynamicAdvisedInterceptor.intercept(CglibAopProxy.java:673)
at com.openmind.primecast.repository.ParameterisedListItemRepository$$EnhancerBySpringCGLIB$$b2db3c41.findAll(<generated>)
at com.openmind.primecast.service.impl.ParameterisedListItemServiceImpl.findByParameterisedList(ParameterisedListItemServiceImpl.java:102)
at com.openmind.primecast.web.rest.ParameterisedListItemResource.getParameterisedListItemsByParameterisedList(ParameterisedListItemResource.java:94)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
Any idea what is going wrong. I know this query is the problem
SELECT * FROM mep_parameterisedListItem WHERE id IN ( :ids )
any idea how I can change the findAll function to achieve the query?
this is the table definition
CREATE TABLE "Openmind".mep_parameterisedlistitem (
id uuid PRIMARY KEY,
data text,
msisdn text,
ordernumber int,
parameterisedlist uuid
) WITH COMPACT STORAGE;
Thank you.
Without knowing the table schema, my guess is that a change was made to the table so the schema no longer match the bindings in the prepared statement.
A big part of the problem is your query with SELECT *. Our recommendation for best practice is to explicitly name all the columns you're retrieving from the table. By specifying the columns in your query, you avoid surprises when the table schema changes.
In this instance, either a new column was added or an old column was dropped. With the cached prepared statement, it was expecting one column type and got another -- the ArrayList doesn't match UUID.
The solution is to re-prepare the statement and name all the columns. Cheers!

MemSQL - how to create a column default with the current date?

Getting this error when trying to create a table with a default value for a "_loaded_at" column:
ERROR 1067 (42000): Invalid default value for '_loaded_at'
This does not work:
CREATE TABLE json01(
id BIGINT PRIMARY KEY AUTO_INCREMENT
, _loaded_at DATETIME DEFAULT NOW()
, properties JSON NOT NULL
, SHARD KEY (id)
);
Whereas this does work:
CREATE TABLE json01(
id BIGINT PRIMARY KEY AUTO_INCREMENT
, _loaded_at DATETIME DEFAULT '1970-01-01 00:00:01'
, properties JSON NOT NULL
, SHARD KEY (id)
);
I also tried with the function UTC_TIMESTAMP(). Hoping that there is a way to specify a function as the default, since this is pretty standard functionality. Thanks so much for your help!
How about considering something like:
_loaded_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP
?

liquibase cassandra getting failed

I am using liquibase for creating cassarndra. My liquibase version is 3.0.0 and But its showing the following error.
D:\Liquibase -Cassandra\common-model\build.xml:89: liquibase.exception.DatabaseException: liquibase.exception.LockException: liquibase.exception.DatabaseException: Error executing SQL CREATE TABLE DATABASECHANGELOGLOCK (ID INT NOT NULL, LOCKED BOOLEAN NOT NULL, LOCKGRANTED datetime, LOCKEDBY VARCHAR(255), CONSTRAINT PK_DATABASECHANGELOGLOCK PRIMARY KEY (ID)); on jdbc:cassandra://192.168.1.219:9160/ems_testINSERT INTO DATABASECHANGELOGLOCK (ID, LOCKED) VALUES (1, FALSE): line1:121 missing EOF at ',' (... datetime, LOCKEDBY VARCHAR(255)[,] CONSTRAINT...)
'CREATE TABLE DATABASECHANGELOGLOCK (ID INT NOT NULL, LOCKED BOOLEAN NOT NULL, LOCKGRANTED datetime, LOCKEDBY VARCHAR(255), CONSTRAINT PK_DATABASECHANGELOGLOCKPRIMARY KEY (ID))'
at liquibase.Liquibase.dropAll(Liquibase.java:555)
at liquibase.Liquibase.dropAll(Liquibase.java:535)
at liquibase.integration.ant.DropAllTask.execute(DropAllTask.java:54)
at org.apache.tools.ant.UnknownElement.execute(UnknownElement.java:291)
at sun.reflect.GeneratedMethodAccessor4.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at org.apache.tools.ant.dispatch.DispatchUtils.execute(DispatchUtils.java:106)
at org.apache.tools.ant.Task.perform(Task.java:348)
at org.apache.tools.ant.Target.execute(Target.java:392)
at org.apache.tools.ant.Target.performTasks(Target.java:413)
at org.apache.tools.ant.Project.executeSortedTargets(Project.java:1399)
at org.apache.tools.ant.Project.executeTarget(Project.java:1368)
at org.apache.tools.ant.helper.DefaultExecutor.executeTargets(DefaultExecutor.java:41)
at org.apache.tools.ant.Project.executeTargets(Project.java:1251)
at org.apache.tools.ant.Main.runBuild(Main.java:811)
at org.apache.tools.ant.Main.startAnt(Main.java:217)
at org.apache.tools.ant.launch.Launcher.run(Launcher.java:280)
at org.apache.tools.ant.launch.Launcher.main(Launcher.java:109)
Caused by: liquibase.exception.LockException:liquibase.exception.DatabaseException: Error executing SQL CREATE TABLE DATABASECHANGELOGLOCK (ID INT NOT NULL, LOCKED BOOLEAN NOT NULL, LOCKGRANTED datetime, LOCKEDBY VARCHAR(255), CONSTRAINT PK_DATABASECHANGELOGLOCK PRIMARY KEY (ID)); on jdbc:cassandra://192.168.1.219:9160/ems_testINSERT INTO DATABASECHANGELOGLOCK (ID, LOCKED) VALUES (1, FALSE): line 1:121 missing EOF at ',' (... datetime, LOCKEDBY VARCHAR(255)[,] CONSTRAINT...) 'CREATE TABLE DATABASECHANGELOGLOCK (ID INT NOT NULL, LOCKED BOOLEAN NOT NULL, LOCKGRANTED datetime, LOCKEDBY VARCHAR(255), CONSTRAINT PK_DATABASECHANGELOGLOCKPRIMARY KEY (ID))'
at liquibase.lockservice.LockServiceImpl.acquireLock(LockServiceImpl.java:122)
This is my ANT target in build.xml
<target name="dropAll" depends="prepare" >
<dropAllDatabaseObjects
driver="${db.driver}"
url="${db.url}"
username="${db.username}"
password="${db.password}"
promptOnNonLocalDatabase="yes"
classpathref="classpath"
/>
</target>
Offhand, this looks like a bug in Liquibase. I would suggest trying it again with the latest version of Liquibase to see if it may have been fixed already, and if you can still reproduce it, file a bug in the Liquibase JIRA: https://liquibase.jira.com/secure/Dashboard.jspa
Liquibase requires the use of an extension to support Cassandra. Either https://github.com/liquibase/liquibase-cassandra should work, or you can try https://github.com/jsanda/cassandra-liquibase-ext

Cassandra: inserting timeuuid error

I have following table
create table test(
userId varchar,
notifId timeuuid,
notification varchar,
time bigint,read boolean,
primary key(userId, notifId)) with clustering order by (notifId desc);
I am running following query:
PreparedStatement pstmt = session.prepare("INSERT INTO notifications(userId, notifId, notification, time, read) VALUES(?, now(), ?, ?, ?)");
BoundStatement boundStatement = new BoundStatement(pstmt);
session.execute(boundStatement.bind("123", "hello", new Date().getTime(), false));
I am getting following error:
Exception in thread "main" com.datastax.driver.core.exceptions.InvalidQueryException: Type error: cannot assign result of function now (type timeuuid) to notifid (type 'org.apache.cassandra.db.marshal.ReversedType(org.apache.cassandra.db.marshal.TimeUUIDType)')
at com.datastax.driver.core.exceptions.InvalidQueryException.copy(InvalidQueryException.java:35)
at com.datastax.driver.core.ResultSetFuture.extractCause(ResultSetFuture.java:277)
at com.datastax.driver.core.Session.toPreparedStatement(Session.java:281)
at com.datastax.driver.core.Session.prepare(Session.java:172)
at com.example.cassandra.SimpleClient.loadData(SimpleClient.java:130)
at com.example.cassandra.SimpleClient.main(SimpleClient.java:214)
Caused by: com.datastax.driver.core.exceptions.InvalidQueryException: Type error: cannot assign result of function now (type timeuuid) to notifid (type 'org.apache.cassandra.db.marshal.ReversedType(org.apache.cassandra.db.marshal.TimeUUIDType)')
at com.datastax.driver.core.ResultSetFuture.convertException(ResultSetFuture.java:307)
I am using cassandra 1.2.2.
You should insert the timeuuid generated via datastax driver. In your case , since you are using version 1 timeuuid, you must use
UUIDs.timeBased()
You can find the above in following reference
http://www.datastax.com/drivers/java/2.0/com/datastax/driver/core/utils/UUIDs.html
It looks like a bug (similar or the same as https://issues.apache.org/jira/browse/CASSANDRA-5472) , and you're using pretty old version of Cassandra. I recommend you to upgrade to the latest 1.2.x release, retest your scenario and file an issue, if the problem still persists

Error using cql prepared statement in cassandra (astyanax)

I was experimenting with astyana write operation, and was using cqlsh for that.
If i simply use the query, I am able to get the result
keyspace.prepareQuery(COLUMN_FAMILY).withCql("insert into scan_request (customer_id, uuid, scan_type, status, content_size, request_time, request_content_hash) values ("+dao.getCustomerId()+","+"'"+dao.getUuId()+"',"+dao.getScanType()+","+dao.getStatus()+","+dao.getContentSize()+",'2012-12-12 12:12:12', '"+dao.getRequestContentHash()+"');")
.execute();
However if i use prepared statement to do the same, i get the below error.
this.getKeyspace()
.prepareQuery(COLUMN_FAMILY)
.withCql(INSERT_STATEMENT)
.asPreparedStatement()
.withIntegerValue(dao.getCustomerId())
.withStringValue(dao.getUuId())
.withIntegerValue(dao.getScanType())
.withIntegerValue(dao.getStatus())
.withIntegerValue(dao.getContentSize())
.withStringValue("'2012-12-12 12:12:12'")
.withStringValue(dao.getRequestContentHash())
.execute();
I get the below error
Exception in thread "main" java.lang.RuntimeException: failed to write data to C*
at com.tools.dbaccess.cassandra.astyanax.AstyanaxClient.write(AstyanaxClient.java:155)
at com.tools.dbaccess.cassandra.astyanax.AstyanaxClient.main(AstyanaxClient.java:164)
Caused by: com.netflix.astyanax.connectionpool.exceptions.BadRequestException: BadRequestException: [host=localhost(127.0.0.1):9160, latency=11(11), attempts=1]InvalidRequestException(why:Expected 8 or 0 byte long for date (21))
at com.netflix.astyanax.thrift.ThriftConverter.ToConnectionPoolException(ThriftConverter.java:159)
at com.netflix.astyanax.thrift.AbstractOperationImpl.execute(AbstractOperationImpl.java:65)
at com.netflix.astyanax.thrift.AbstractOperationImpl.execute(AbstractOperationImpl.java:28)
at com.netflix.astyanax.thrift.ThriftSyncConnectionFactoryImpl$ThriftConnection.execute(ThriftSyncConnectionFactoryImpl.java:151)
at com.netflix.astyanax.connectionpool.impl.AbstractExecuteWithFailoverImpl.tryOperation(AbstractExecuteWithFailoverImpl.java:69)
at com.netflix.astyanax.connectionpool.impl.AbstractHostPartitionConnectionPool.executeWithFailover(AbstractHostPartitionConnectionPool.java:256)
at com.netflix.astyanax.thrift.AbstractThriftCqlQuery$3.execute(AbstractThriftCqlQuery.java:80)
at com.tools.dbaccess.cassandra.astyanax.AstyanaxClient.write(AstyanaxClient.java:144)
... 1 more
Caused by: InvalidRequestException(why:Expected 8 or 0 byte long for date (21))
at org.apache.cassandra.thrift.Cassandra$execute_prepared_cql3_query_result.read(Cassandra.java:41868)
at org.apache.thrift.TServiceClient.receiveBase(TServiceClient.java:78)
at org.apache.cassandra.thrift.Cassandra$Client.recv_execute_prepared_cql3_query(Cassandra.java:1689)
at org.apache.cassandra.thrift.Cassandra$Client.execute_prepared_cql3_query(Cassandra.java:1674)
at com.netflix.astyanax.thrift.ThriftCql3Query.execute_prepared_cql_query(ThriftCql3Query.java:29)
at com.netflix.astyanax.thrift.AbstractThriftCqlQuery$3$1.internalExecute(AbstractThriftCqlQuery.java:92)
at com.netflix.astyanax.thrift.AbstractThriftCqlQuery$3$1.internalExecute(AbstractThriftCqlQuery.java:82)
at com.netflix.astyanax.thrift.AbstractOperationImpl.execute(AbstractOperationImpl.java:60)
I think its wrong when i try to store the timestamp into the table. But i didn't find anything adequeate in the preparedStatement to store timestamp. The datatype of the field in the database is "timestamp".
I should have used
.withByteBufferValue(new Date(), DateSerializer.get()).
Or if you have a custom object to serialize, extend the AbstractSerializer class.
Since what you get is a NullPointerException have you checked that some of your values aren't null?

Resources