Search in sources :

Example 56 with Server

use of herddb.server.Server in project herddb by diennea.

the class AdvancedInsertSyntaxTest method testInsertFromSelect.

@Test
public void testInsertFromSelect() throws Exception {
    try (Server server = new Server(TestUtils.newServerConfigurationWithAutoPort(folder.newFolder().toPath()))) {
        server.start();
        server.waitForStandaloneBoot();
        try (HDBClient client = new HDBClient(new ClientConfiguration(folder.newFolder().toPath()))) {
            client.setClientSideMetadataProvider(new StaticClientSideMetadataProvider(server));
            try (BasicHerdDBDataSource dataSource = new BasicHerdDBDataSource(client);
                Connection con = dataSource.getConnection();
                Statement create = con.createStatement();
                PreparedStatement statement = con.prepareStatement("INSERT INTO mytable (name) values(?)")) {
                create.execute("CREATE TABLE mytable (n1 int primary key auto_increment, name string)");
                create.execute("CREATE TABLE mytable2 (n1 int primary key auto_increment, name string)");
                {
                    for (int i = 0; i < 100; i++) {
                        statement.setString(1, "v" + i);
                        statement.addBatch();
                    }
                    int[] results = statement.executeBatch();
                    for (int i = 0; i < 100; i++) {
                        assertEquals(1, results[i]);
                    }
                    try (ResultSet rs = statement.executeQuery("SELECT * FROM mytable ORDER BY n1")) {
                        int count = 0;
                        while (rs.next()) {
                            assertEquals("v" + count, rs.getString("name"));
                            assertEquals(count + 1, rs.getInt("n1"));
                            count++;
                        }
                        assertEquals(100, count);
                    }
                }
                statement.executeUpdate("INSERT INTO mytable2(n1,name) SELECT n1, name from mytable order by name desc");
                try (ResultSet rs = statement.executeQuery("SELECT COUNT(*) FROM mytable2")) {
                    assertTrue(rs.next());
                    assertEquals(100, rs.getInt(1));
                }
                // leverage auto_increment
                statement.executeUpdate("INSERT INTO mytable2(name) SELECT name from mytable order by name desc");
                try (ResultSet rs = statement.executeQuery("SELECT COUNT(*) FROM mytable2")) {
                    assertTrue(rs.next());
                    assertEquals(200, rs.getInt(1));
                }
                try (ResultSet rs = statement.executeQuery("SELECT n1 FROM mytable2 order by n1")) {
                    Set<Integer> ids = new HashSet<>();
                    while (rs.next()) {
                        int id = rs.getInt(1);
                        assertTrue(ids.add(id));
                    }
                    assertEquals(200, ids.size());
                }
            }
        }
    }
}
Also used : Server(herddb.server.Server) PreparedStatement(java.sql.PreparedStatement) Statement(java.sql.Statement) Connection(java.sql.Connection) PreparedStatement(java.sql.PreparedStatement) StaticClientSideMetadataProvider(herddb.server.StaticClientSideMetadataProvider) HDBClient(herddb.client.HDBClient) ResultSet(java.sql.ResultSet) ClientConfiguration(herddb.client.ClientConfiguration) HashSet(java.util.HashSet) Test(org.junit.Test)

Example 57 with Server

use of herddb.server.Server in project herddb by diennea.

the class CommonsDBCPTest method test.

@Test
public void test() throws Exception {
    try (Server server = new Server(TestUtils.newServerConfigurationWithAutoPort(folder.newFolder().toPath()))) {
        server.start();
        BasicDataSource dataSource = new BasicDataSource();
        dataSource.setUrl(server.getJdbcUrl());
        dataSource.setDriverClassName(Driver.class.getName());
        try (Connection connection = dataSource.getConnection();
            Statement statement = connection.createStatement();
            ResultSet rs = statement.executeQuery("SELECT * FROM SYSTABLES")) {
            int count = 0;
            while (rs.next()) {
                System.out.println("table: " + rs.getString(1));
                count++;
            }
            assertTrue(count > 0);
        }
        dataSource.close();
    }
}
Also used : Server(herddb.server.Server) Statement(java.sql.Statement) Connection(java.sql.Connection) ResultSet(java.sql.ResultSet) BasicDataSource(org.apache.commons.dbcp.BasicDataSource) Test(org.junit.Test)

Example 58 with Server

use of herddb.server.Server 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));
            }
        }
    }
}
Also used : Server(herddb.server.Server) ServerConfiguration(herddb.server.ServerConfiguration) ArrayList(java.util.ArrayList) RawString(herddb.utils.RawString) HDBConnection(herddb.client.HDBConnection) StaticClientSideMetadataProvider(herddb.server.StaticClientSideMetadataProvider) HDBClient(herddb.client.HDBClient) DMLResult(herddb.client.DMLResult) TableManagerStats(herddb.core.stats.TableManagerStats) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) Path(java.nio.file.Path) GetResult(herddb.client.GetResult) AtomicLong(java.util.concurrent.atomic.AtomicLong) AtomicLong(java.util.concurrent.atomic.AtomicLong) ExecutorService(java.util.concurrent.ExecutorService) Future(java.util.concurrent.Future) Map(java.util.Map) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) ClientConfiguration(herddb.client.ClientConfiguration)

Example 59 with Server

use of herddb.server.Server in project herddb by diennea.

the class JAASMD5Test method test.

@Test
public void test() throws Exception {
    System.setProperty("java.security.auth.login.config", new File("src/test/resources/test_jaas_md5.conf").getAbsolutePath());
    try (Server server = new Server(newServerConfigurationWithAutoPort(folder.newFolder().toPath()))) {
        server.start();
        try (HDBClient client = new HDBClient(new ClientConfiguration(folder.newFolder().toPath()));
            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);
            Assert.assertEquals(1, connection.executeUpdate(TableSpace.DEFAULT, "INSERT INTO mytable (id,n1,n2) values(?,?,?)", 0, false, true, Arrays.asList("test_0", 1, 2)).updateCount);
            Map<RawString, Object> newValue = connection.executeUpdate(TableSpace.DEFAULT, "UPDATE mytable set n1= n1+1 where id=?", 0, true, true, Arrays.asList("test_0")).newvalue;
            assertEquals(Long.valueOf(2), newValue.get(RawString.of("n1")));
        }
    } finally {
        System.clearProperty("java.security.auth.login.config");
    }
}
Also used : HDBConnection(herddb.client.HDBConnection) StaticClientSideMetadataProvider(herddb.server.StaticClientSideMetadataProvider) HDBClient(herddb.client.HDBClient) Server(herddb.server.Server) RawString(herddb.utils.RawString) File(java.io.File) ClientConfiguration(herddb.client.ClientConfiguration) Test(org.junit.Test)

Example 60 with Server

use of herddb.server.Server in project herddb by diennea.

the class DirectMultipleConcurrentUpdatesSuite method performTest.

protected void performTest(boolean useTransactions, long checkPointPeriod, boolean withIndexes, boolean uniqueIndexes) 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();
        DBManager manager = server.getManager();
        execute(manager, "CREATE TABLE mytable (id string primary key, n1 long, n2 integer)", Collections.emptyList());
        if (withIndexes) {
            if (uniqueIndexes) {
                // use n1 + id in order to not have collisions and lock timeouts
                execute(manager, "CREATE UNIQUE INDEX theindex ON mytable (n1, id)", Collections.emptyList());
            } else {
                execute(manager, "CREATE INDEX theindex ON mytable (n1)", Collections.emptyList());
            }
        }
        long tx = TestUtils.beginTransaction(manager, TableSpace.DEFAULT);
        for (int i = 0; i < TABLESIZE; i++) {
            TestUtils.executeUpdate(manager, "INSERT INTO mytable (id,n1,n2) values(?,?,?)", Arrays.asList("test_" + i, 1, 2), new TransactionContext(tx));
            expectedValue.put("test_" + i, 1L);
        }
        TestUtils.commitTransaction(manager, 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();
                                DMLStatementExecutionResult updateResult = TestUtils.executeUpdate(manager, "UPDATE mytable set n1=? WHERE id=?", Arrays.asList(value, "test_" + k), new TransactionContext(useTransactions ? TransactionContext.AUTOTRANSACTION_ID : TransactionContext.NOTRANSACTION_ID));
                                long count = updateResult.getUpdateCount();
                                transactionId = updateResult.transactionId;
                                if (count <= 0) {
                                    throw new RuntimeException("not updated ?");
                                }
                            } else {
                                gets.incrementAndGet();
                                DataScanner res = TestUtils.scanKeepReadLocks(manager, "SELECT * FROM mytable where id=?", Arrays.asList("test_" + k), new TransactionContext(useTransactions ? TransactionContext.AUTOTRANSACTION_ID : TransactionContext.NOTRANSACTION_ID));
                                if (!res.hasNext()) {
                                    throw new RuntimeException("not found?");
                                }
                                res.close();
                                transactionId = res.getTransactionId();
                                // value did not change actually
                                value = actual;
                            }
                            if (useTransactions) {
                                if (transactionId <= 0) {
                                    throw new RuntimeException("no transaction ?");
                                }
                                commitTransaction(manager, 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);
            assertTrue(updates.get() > 0);
            assertTrue(gets.get() > 0);
            List<String> erroredKeys = new ArrayList<>();
            for (Map.Entry<String, Long> entry : expectedValue.entrySet()) {
                List<DataAccessor> records;
                DataAccessor data;
                try (DataScanner res = scan(manager, "SELECT n1 FROM mytable where id=?", Arrays.asList(entry.getKey()))) {
                    records = res.consume();
                    data = records.get(0);
                }
                assertEquals(1, records.size());
                if (!entry.getValue().equals(data.get("n1"))) {
                    System.out.println("expected value " + 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);
        DBManager manager = server.getManager();
        List<String> erroredKeys = new ArrayList<>();
        for (Map.Entry<String, Long> entry : expectedValue.entrySet()) {
            List<DataAccessor> records;
            DataAccessor data;
            try (DataScanner res = scan(manager, "SELECT n1 FROM mytable where id=?", Arrays.asList(entry.getKey()))) {
                records = res.consume();
                data = records.get(0);
            }
            assertEquals(1, records.size());
            if (!entry.getValue().equals(data.get("n1"))) {
                System.out.println("expected value " + data.get("n1") + ", but got " + Long.valueOf(entry.getValue()) + " for key " + entry.getKey());
                erroredKeys.add(entry.getKey());
            }
        }
        assertTrue(erroredKeys.isEmpty());
    }
}
Also used : Server(herddb.server.Server) DataAccessor(herddb.utils.DataAccessor) ServerConfiguration(herddb.server.ServerConfiguration) ArrayList(java.util.ArrayList) DataScanner(herddb.model.DataScanner) TableManagerStats(herddb.core.stats.TableManagerStats) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) Path(java.nio.file.Path) AtomicLong(java.util.concurrent.atomic.AtomicLong) DBManager(herddb.core.DBManager) DMLStatementExecutionResult(herddb.model.DMLStatementExecutionResult) TransactionContext(herddb.model.TransactionContext) AtomicLong(java.util.concurrent.atomic.AtomicLong) ExecutorService(java.util.concurrent.ExecutorService) Future(java.util.concurrent.Future) Map(java.util.Map) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap)

Aggregations

Server (herddb.server.Server)119 Test (org.junit.Test)111 ServerConfiguration (herddb.server.ServerConfiguration)60 ClientConfiguration (herddb.client.ClientConfiguration)56 StaticClientSideMetadataProvider (herddb.server.StaticClientSideMetadataProvider)56 Connection (java.sql.Connection)53 HDBClient (herddb.client.HDBClient)52 Statement (java.sql.Statement)47 ResultSet (java.sql.ResultSet)37 Table (herddb.model.Table)36 CreateTableStatement (herddb.model.commands.CreateTableStatement)35 InsertStatement (herddb.model.commands.InsertStatement)32 PreparedStatement (java.sql.PreparedStatement)30 HashSet (java.util.HashSet)24 AlterTableSpaceStatement (herddb.model.commands.AlterTableSpaceStatement)19 Path (java.nio.file.Path)19 DataScanner (herddb.model.DataScanner)18 TableSpaceManager (herddb.core.TableSpaceManager)15 HDBConnection (herddb.client.HDBConnection)14 Index (herddb.model.Index)14