use of herddb.client.DMLResult in project herddb by diennea.
the class HerdDBStatement method executeLargeUpdateImpl.
private long executeLargeUpdateImpl(String sql, boolean returnValues) throws SQLException {
try {
parent.discoverTableSpace(sql);
DMLResult result = parent.getConnection().executeUpdate(parent.getTableSpace(), sql, parent.ensureTransaction(), returnValues, false, Collections.emptyList());
parent.bindToTransaction(result.transactionId);
lastUpdateCount = result.updateCount;
lastKey = result.key;
return lastUpdateCount;
} catch (ClientSideMetadataProviderException | HDBException err) {
throw SQLExceptionUtils.wrapException(err);
}
}
use of herddb.client.DMLResult in project herddb by diennea.
the class HistoryChangelogTest method test.
@Test
@Ignore
public void test() throws Exception {
Path baseDir = folder.newFolder().toPath();
ServerConfiguration serverConfiguration = newServerConfigurationWithAutoPort(baseDir);
serverConfiguration.set(ServerConfiguration.PROPERTY_MAX_LOGICAL_PAGE_SIZE, 10 * 1024);
serverConfiguration.set(ServerConfiguration.PROPERTY_MAX_DATA_MEMORY, 1024 * 1024);
serverConfiguration.set(ServerConfiguration.PROPERTY_MAX_PK_MEMORY, 1024 * 1024);
serverConfiguration.set(ServerConfiguration.PROPERTY_CHECKPOINT_PERIOD, 0);
serverConfiguration.set(ServerConfiguration.PROPERTY_DATADIR, folder.newFolder().getAbsolutePath());
serverConfiguration.set(ServerConfiguration.PROPERTY_LOGDIR, folder.newFolder().getAbsolutePath());
ConcurrentSkipListSet<Long> doneElements = new ConcurrentSkipListSet<>();
ConcurrentHashMap<Long, Element> elements = new ConcurrentHashMap<>();
try (Server server = new Server(serverConfiguration)) {
server.start();
server.waitForStandaloneBoot();
ClientConfiguration clientConfiguration = new ClientConfiguration(folder.newFolder().toPath());
try (HDBClient client = new HDBClient(clientConfiguration);
HDBConnection connection = client.openConnection()) {
client.setClientSideMetadataProvider(new StaticClientSideMetadataProvider(server));
long resultCreateTable = connection.executeUpdate(TableSpace.DEFAULT, "CREATE TABLE mytable (id long primary key, hid long, status integer)", 0, false, true, Collections.emptyList()).updateCount;
Assert.assertEquals(1, resultCreateTable);
long resultCreateTableHistory = connection.executeUpdate(TableSpace.DEFAULT, "CREATE TABLE history (id long, hid long, status integer, primary key (id,hid) )", 0, false, true, Collections.emptyList()).updateCount;
Assert.assertEquals(1, resultCreateTableHistory);
long tx = connection.beginTransaction(TableSpace.DEFAULT);
for (long i = 0; i < TABLESIZE; i++) {
int status = 0;
connection.executeUpdate(TableSpace.DEFAULT, "INSERT INTO mytable (id,hid,status) values(?,?,?)", tx, false, true, Arrays.asList(i, 0, status));
elements.put(i, new Element(0, status));
}
connection.commitTransaction(TableSpace.DEFAULT, tx);
ExecutorService threadPool = Executors.newFixedThreadPool(THREADPOLSIZE);
try {
List<Future> futures = new ArrayList<>();
AtomicLong updates = new AtomicLong();
for (int i = 0; i < TABLESIZE * MULTIPLIER; i++) {
futures.add(threadPool.submit(new Runnable() {
@Override
public void run() {
try {
long id = ThreadLocalRandom.current().nextInt(TABLESIZE);
doneElements.add(id);
Element element = elements.remove(id);
if (element == null) {
return;
}
int new_status = element.status + 1;
long next_hid = element.hid + 1;
long transactionId;
updates.incrementAndGet();
DMLResult updateResult = connection.executeUpdate(TableSpace.DEFAULT, "UPDATE mytable set hid=?,status=? WHERE id=?", TransactionContext.AUTOTRANSACTION_ID, false, true, Arrays.asList(next_hid, new_status, id));
transactionId = updateResult.transactionId;
if (updateResult.updateCount <= 0) {
throw new RuntimeException("not updated ?");
}
DMLResult insertResult = connection.executeUpdate(TableSpace.DEFAULT, "INSERT INTO history (id,hid,status) values (?,?,?)", transactionId, false, true, Arrays.asList(id, next_hid, new_status));
if (insertResult.updateCount <= 0) {
throw new RuntimeException("not inserted ?");
}
connection.commitTransaction(TableSpace.DEFAULT, transactionId);
// make the element available again
elements.put(id, new Element(new_status, next_hid));
} catch (Exception err) {
err.printStackTrace();
throw new RuntimeException(err);
}
}
}));
}
for (Future f : futures) {
f.get();
}
System.out.println("stats::updates:" + updates);
assertTrue(updates.get() > 0);
TableManagerStats stats = server.getManager().getTableSpaceManager(TableSpace.DEFAULT).getTableManager("mytable").getStats();
System.out.println("stats::tablesize:" + stats.getTablesize());
System.out.println("stats::dirty records:" + stats.getDirtyrecords());
System.out.println("stats::unload count:" + stats.getUnloadedPagesCount());
System.out.println("stats::load count:" + stats.getLoadedPagesCount());
System.out.println("stats::buffers used mem:" + stats.getBuffersUsedMemory());
assertEquals(TABLESIZE, stats.getTablesize());
for (Map.Entry<Long, Element> entry : elements.entrySet()) {
{
GetResult res = connection.executeGet(TableSpace.DEFAULT, "SELECT status,hid FROM mytable where id=?", TransactionContext.NOTRANSACTION_ID, true, Arrays.asList(entry.getKey()));
assertNotNull(res.data);
assertEquals(entry.getValue().status, res.data.get(RawString.of("status")));
assertEquals(entry.getValue().hid, res.data.get(RawString.of("hid")));
}
if (doneElements.contains(entry.getKey())) {
ScanResultSet res = connection.executeScan(TableSpace.DEFAULT, "SELECT id, status, hid, (SELECT MAX(hid) as mm from history where history.id=mytable.id) as maxhid " + "FROM mytable where id=?", true, Arrays.asList(entry.getKey()), TransactionContext.NOTRANSACTION_ID, -1, 10000, true);
List<Map<String, Object>> consume = res.consume();
assertEquals(1, consume.size());
Map<String, Object> data = consume.get(0);
System.out.println("data:" + data);
assertEquals(entry.getValue().status, data.get("status"));
assertEquals(entry.getValue().hid, data.get("hid"));
assertEquals(entry.getValue().hid, data.get("maxhid"));
assertEquals(entry.getKey(), data.get("id"));
}
}
} finally {
threadPool.shutdown();
threadPool.awaitTermination(1, TimeUnit.MINUTES);
}
}
}
// restart and recovery
try (Server server = new Server(serverConfiguration)) {
server.start();
server.waitForStandaloneBoot();
ClientConfiguration clientConfiguration = new ClientConfiguration(folder.newFolder().toPath());
try (HDBClient client = new HDBClient(clientConfiguration);
HDBConnection connection = client.openConnection()) {
client.setClientSideMetadataProvider(new StaticClientSideMetadataProvider(server));
for (Map.Entry<Long, Element> entry : elements.entrySet()) {
{
GetResult res = connection.executeGet(TableSpace.DEFAULT, "SELECT status,hid FROM mytable where id=?", TransactionContext.NOTRANSACTION_ID, true, Arrays.asList(entry.getKey()));
assertNotNull(res.data);
assertEquals(entry.getValue().status, res.data.get(RawString.of("status")));
assertEquals(entry.getValue().hid, res.data.get(RawString.of("hid")));
}
if (doneElements.contains(entry.getKey())) {
ScanResultSet res = connection.executeScan(TableSpace.DEFAULT, "SELECT id, status, hid, (SELECT MAX(hid) as mm from history where history.id=mytable.id) as maxhid " + "FROM mytable where id=?", true, Arrays.asList(entry.getKey()), TransactionContext.NOTRANSACTION_ID, -1, 10000, true);
List<Map<String, Object>> consume = res.consume();
assertEquals(1, consume.size());
Map<String, Object> data = consume.get(0);
System.out.println("data:" + data);
assertEquals(entry.getValue().status, data.get("status"));
assertEquals(entry.getValue().hid, data.get("hid"));
assertEquals(entry.getValue().hid, data.get("maxhid"));
assertEquals(entry.getKey(), data.get("id"));
}
}
}
}
}
use of herddb.client.DMLResult in project herddb by diennea.
the class ServerSideConnectionPeer method executeUpdate.
/**
* This method is like {@link #handleExecuteStatement(herddb.proto.Pdu, herddb.network.Channel) } but in "local" mode,
* we do not want here to marshal/unmarshal values, in order to save resources
*/
public DMLResult executeUpdate(String tablespace, String query, long txId, boolean returnValues, List<Object> parameters) throws HDBException {
// ensure we are dealing with the same data types that we see when the request id coming from the wire
parameters = PduCodec.normalizeParametersList(parameters);
TransactionContext transactionContext = new TransactionContext(txId);
TranslatedQuery translatedQuery;
try {
translatedQuery = server.getManager().getPlanner().translate(tablespace, query, parameters, false, true, returnValues, -1);
Statement statement = translatedQuery.plan.mainStatement;
CompletableFuture<StatementExecutionResult> res = server.getManager().executePlanAsync(translatedQuery.plan, translatedQuery.context, transactionContext);
CompletableFuture<DMLResult> finalResult = res.handle((result, err) -> {
if (err != null) {
while (err instanceof CompletionException) {
err = err.getCause();
}
if (err instanceof DuplicatePrimaryKeyException) {
throw new CompletionException(new SQLIntegrityConstraintViolationException(err));
} else {
throw new CompletionException(new SQLException(err));
}
}
if (result instanceof DMLStatementExecutionResult) {
DMLStatementExecutionResult dml = (DMLStatementExecutionResult) result;
if (returnValues && dml.getKey() != null) {
TableAwareStatement tableStatement = statement.unwrap(TableAwareStatement.class);
Table table = server.getManager().getTableSpaceManager(statement.getTableSpace()).getTableManager(tableStatement.getTable()).getTable();
final Map<RawString, Object> newRecord = new HashMap<>();
Object newKey = RecordSerializer.deserializePrimaryKey(dml.getKey(), table);
newRecord.put(RAWSTRING_KEY, newKey);
if (dml.getNewvalue() != null) {
Map<String, Object> toBean = RecordSerializer.toBean(new Record(dml.getKey(), dml.getNewvalue()), table);
toBean.forEach((k, v) -> {
newRecord.put(RawString.of(k), v);
});
}
return new DMLResult(dml.getUpdateCount(), newKey, newRecord, dml.transactionId);
} else {
return new DMLResult(dml.getUpdateCount(), null, null, dml.transactionId);
}
} else if (result instanceof DDLStatementExecutionResult) {
return new DMLResult(1, null, null, result.transactionId);
} else {
throw new CompletionException(new SQLException("Unknown result type " + result.getClass() + ": " + result));
}
});
return finalResult.get();
} catch (Throwable err) {
while (err instanceof CompletionException) {
err = err.getCause();
}
throw new HDBException(err);
}
}
use of herddb.client.DMLResult in project herddb by diennea.
the class MultipleConcurrentUpdatesTest method performTest.
private void performTest(boolean useTransactions, long checkPointPeriod, boolean withIndexes) throws Exception {
Path baseDir = folder.newFolder().toPath();
ServerConfiguration serverConfiguration = newServerConfigurationWithAutoPort(baseDir);
serverConfiguration.set(ServerConfiguration.PROPERTY_MAX_LOGICAL_PAGE_SIZE, 10 * 1024);
serverConfiguration.set(ServerConfiguration.PROPERTY_MAX_DATA_MEMORY, 1024 * 1024 / 4);
serverConfiguration.set(ServerConfiguration.PROPERTY_MAX_PK_MEMORY, 1024 * 1024);
serverConfiguration.set(ServerConfiguration.PROPERTY_CHECKPOINT_PERIOD, checkPointPeriod);
serverConfiguration.set(ServerConfiguration.PROPERTY_DATADIR, folder.newFolder().getAbsolutePath());
serverConfiguration.set(ServerConfiguration.PROPERTY_LOGDIR, folder.newFolder().getAbsolutePath());
ConcurrentHashMap<String, Long> expectedValue = new ConcurrentHashMap<>();
try (Server server = new Server(serverConfiguration)) {
server.start();
server.waitForStandaloneBoot();
ClientConfiguration clientConfiguration = new ClientConfiguration(folder.newFolder().toPath());
try (HDBClient client = new HDBClient(clientConfiguration);
HDBConnection connection = client.openConnection()) {
client.setClientSideMetadataProvider(new StaticClientSideMetadataProvider(server));
long resultCreateTable = connection.executeUpdate(TableSpace.DEFAULT, "CREATE TABLE mytable (id string primary key, n1 long, n2 integer)", 0, false, true, Collections.emptyList()).updateCount;
Assert.assertEquals(1, resultCreateTable);
if (withIndexes) {
long resultCreateIndex = connection.executeUpdate(TableSpace.DEFAULT, "CREATE INDEX theindex ON mytable (n1 long)", 0, false, true, Collections.emptyList()).updateCount;
Assert.assertEquals(1, resultCreateIndex);
}
long tx = connection.beginTransaction(TableSpace.DEFAULT);
for (int i = 0; i < TABLESIZE; i++) {
connection.executeUpdate(TableSpace.DEFAULT, "INSERT INTO mytable (id,n1,n2) values(?,?,?)", tx, false, true, Arrays.asList("test_" + i, 1, 2));
expectedValue.put("test_" + i, 1L);
}
connection.commitTransaction(TableSpace.DEFAULT, tx);
ExecutorService threadPool = Executors.newFixedThreadPool(THREADPOLSIZE);
try {
List<Future> futures = new ArrayList<>();
AtomicLong updates = new AtomicLong();
AtomicLong skipped = new AtomicLong();
AtomicLong gets = new AtomicLong();
for (int i = 0; i < TABLESIZE * MULTIPLIER; i++) {
futures.add(threadPool.submit(new Runnable() {
@Override
public void run() {
try {
boolean update = ThreadLocalRandom.current().nextBoolean();
int k = ThreadLocalRandom.current().nextInt(TABLESIZE);
long value = ThreadLocalRandom.current().nextInt(TABLESIZE);
long transactionId;
String key = "test_" + k;
Long actual = expectedValue.remove(key);
if (actual == null) {
// another thread working on this entry, skip
skipped.incrementAndGet();
return;
}
if (update) {
updates.incrementAndGet();
DMLResult updateResult = connection.executeUpdate(TableSpace.DEFAULT, "UPDATE mytable set n1=? WHERE id=?", useTransactions ? TransactionContext.AUTOTRANSACTION_ID : TransactionContext.NOTRANSACTION_ID, false, true, Arrays.asList(value, "test_" + k));
long count = updateResult.updateCount;
transactionId = updateResult.transactionId;
if (count <= 0) {
throw new RuntimeException("not updated ?");
}
} else {
gets.incrementAndGet();
GetResult res = connection.executeGet(TableSpace.DEFAULT, "SELECT * FROM mytable where id=?", useTransactions ? TransactionContext.AUTOTRANSACTION_ID : TransactionContext.NOTRANSACTION_ID, true, Arrays.asList("test_" + k));
if (res.data == null) {
throw new RuntimeException("not found?");
}
if (!res.data.get(N1).equals(actual)) {
throw new RuntimeException("unspected value " + res.data + ", expected: " + actual);
}
transactionId = res.transactionId;
// value did not change actually
value = actual;
}
if (useTransactions) {
if (transactionId <= 0) {
throw new RuntimeException("no transaction ?");
}
connection.commitTransaction(TableSpace.DEFAULT, transactionId);
}
expectedValue.put(key, value);
} catch (Exception err) {
throw new RuntimeException(err);
}
}
}));
}
for (Future f : futures) {
f.get();
}
System.out.println("stats::updates:" + updates);
System.out.println("stats::get:" + gets);
System.out.println("stats::skipped:" + skipped);
assertTrue(updates.get() > 0);
assertTrue(gets.get() > 0);
List<String> erroredKeys = new ArrayList<>();
for (Map.Entry<String, Long> entry : expectedValue.entrySet()) {
GetResult res = connection.executeGet(TableSpace.DEFAULT, "SELECT n1 FROM mytable where id=?", TransactionContext.NOTRANSACTION_ID, true, Arrays.asList(entry.getKey()));
assertNotNull(res.data);
if (!entry.getValue().equals(res.data.get(N1))) {
if (!entry.getValue().equals(res.data.get(N1))) {
System.out.println("expected value " + res.data.get(N1) + ", but got " + Long.valueOf(entry.getValue()) + " for key " + entry.getKey());
erroredKeys.add(entry.getKey());
}
}
}
assertTrue(erroredKeys.isEmpty());
TableManagerStats stats = server.getManager().getTableSpaceManager(TableSpace.DEFAULT).getTableManager("mytable").getStats();
System.out.println("stats::tablesize:" + stats.getTablesize());
System.out.println("stats::dirty records:" + stats.getDirtyrecords());
System.out.println("stats::unload count:" + stats.getUnloadedPagesCount());
System.out.println("stats::load count:" + stats.getLoadedPagesCount());
System.out.println("stats::buffers used mem:" + stats.getBuffersUsedMemory());
assertTrue(stats.getUnloadedPagesCount() > 0);
assertEquals(TABLESIZE, stats.getTablesize());
} finally {
threadPool.shutdown();
threadPool.awaitTermination(1, TimeUnit.MINUTES);
}
}
}
// restart and recovery
try (Server server = new Server(serverConfiguration)) {
server.start();
server.waitForTableSpaceBoot(TableSpace.DEFAULT, 300000, true);
ClientConfiguration clientConfiguration = new ClientConfiguration(folder.newFolder().toPath());
try (HDBClient client = new HDBClient(clientConfiguration);
HDBConnection connection = client.openConnection()) {
client.setClientSideMetadataProvider(new StaticClientSideMetadataProvider(server));
for (Map.Entry<String, Long> entry : expectedValue.entrySet()) {
GetResult res = connection.executeGet(TableSpace.DEFAULT, "SELECT n1 FROM mytable where id=?", TransactionContext.NOTRANSACTION_ID, true, Arrays.asList(entry.getKey()));
assertNotNull(res.data);
assertEquals(entry.getValue(), res.data.get(N1));
}
}
}
}
use of herddb.client.DMLResult in project herddb by diennea.
the class HerdDBPreparedStatement method doExecuteLargeUpdateWithParameters.
private long doExecuteLargeUpdateWithParameters(List<Object> actualParameters, boolean returnValues) throws SQLException {
try {
parent.discoverTableSpace(sql);
DMLResult result = parent.getConnection().executeUpdate(parent.getTableSpace(), sql, parent.ensureTransaction(), returnValues, true, actualParameters);
parent.bindToTransaction(result.transactionId);
lastUpdateCount = result.updateCount;
lastKey = result.key;
return lastUpdateCount;
} catch (ClientSideMetadataProviderException | HDBException err) {
throw SQLExceptionUtils.wrapException(err);
}
}
Aggregations