Search in sources :

Example 1 with TupleComparator

use of herddb.model.TupleComparator in project herddb by diennea.

the class SQLPlanner method buildSelectStatement.

private ExecutionPlan buildSelectStatement(String defaultTableSpace, Select s, boolean scan, int maxRows) throws StatementExecutionException {
    PlainSelect selectBody = (PlainSelect) s.getSelectBody();
    net.sf.jsqlparser.schema.Table fromTable = (net.sf.jsqlparser.schema.Table) selectBody.getFromItem();
    TableRef mainTable = TableRef.buildFrom(fromTable, defaultTableSpace);
    String mainTableAlias = mainTable.tableAlias;
    String tableSpace = mainTable.tableSpace;
    TableSpaceManager tableSpaceManager = manager.getTableSpaceManager(tableSpace);
    if (tableSpaceManager == null) {
        throw new TableSpaceDoesNotExistException("no such tablespace " + tableSpace + " here at " + manager.getNodeId());
    }
    AbstractTableManager tableManager = tableSpaceManager.getTableManager(mainTable.tableName);
    if (tableManager == null) {
        throw new TableDoesNotExistException("no such table " + mainTable.tableName + " in tablespace " + tableSpace);
    }
    // linked hash map retains the order of insertions
    LinkedHashMap<String, JoinSupport> joins = new LinkedHashMap<>();
    boolean joinPresent = false;
    joins.put(mainTable.tableAlias, new JoinSupport(mainTable, tableManager));
    if (selectBody.getJoins() != null) {
        for (Join join : selectBody.getJoins()) {
            joinPresent = true;
            if (join.isLeft() || join.isCross() || join.isRight() || join.isOuter() || join.isSimple()) {
                throw new StatementExecutionException("unsupported JOIN type: " + join);
            }
            net.sf.jsqlparser.schema.Table joinedTable = (net.sf.jsqlparser.schema.Table) join.getRightItem();
            TableRef joinedTableRef = TableRef.buildFrom(joinedTable, defaultTableSpace);
            if (!joinedTableRef.tableSpace.equalsIgnoreCase(mainTable.tableSpace)) {
                throw new TableDoesNotExistException("unsupported cross-tablespace JOIN " + "between" + mainTable.tableSpace + "." + mainTable.tableName + " and " + joinedTableRef.tableSpace + "." + joinedTableRef.tableName);
            }
            AbstractTableManager joinedTableManager = tableSpaceManager.getTableManager(joinedTableRef.tableName);
            if (joinedTableManager == null) {
                throw new TableDoesNotExistException("no such table " + joinedTableRef.tableName + " in tablespace " + tableSpace);
            }
            JoinSupport joinSupport = new JoinSupport(joinedTableRef, joinedTableManager);
            joins.put(joinedTableRef.tableAlias, joinSupport);
        }
    }
    Projection mainTableProjection;
    Table table = tableManager.getTable();
    boolean allColumns = false;
    boolean containsAggregateFunctions = false;
    for (SelectItem c : selectBody.getSelectItems()) {
        if (c instanceof AllColumns) {
            allColumns = true;
            break;
        } else if (c instanceof AllTableColumns) {
            AllTableColumns allTableColumns = (AllTableColumns) c;
            TableRef ref = TableRef.buildFrom(allTableColumns.getTable(), defaultTableSpace);
            if (!joinPresent && ref.tableAlias.equals(mainTable.tableAlias)) {
                // select a.*  FROM table a
                allColumns = true;
            } else {
                // select a.*, b.* FROM table a JOIN table b
                joins.get(ref.tableAlias).allColumns = true;
            }
        } else if (c instanceof SelectExpressionItem) {
            SelectExpressionItem se = (SelectExpressionItem) c;
            if (isAggregateFunction(se.getExpression())) {
                containsAggregateFunctions = true;
            }
            if (!joinPresent) {
                joins.get(mainTable.tableAlias).selectItems.add(c);
            } else {
                ColumnReferencesDiscovery discoverMainTableAlias = discoverMainTableAlias(se.getExpression());
                String mainTableAliasForItem = discoverMainTableAlias.getMainTableAlias();
                if (discoverMainTableAlias.isContainsMixedAliases()) {
                    throw new StatementExecutionException("unsupported single SELECT ITEM with mixed aliases: " + c);
                }
                if (mainTableAliasForItem == null) {
                    mainTableAliasForItem = mainTable.tableAlias;
                }
                joins.get(mainTableAliasForItem).selectItems.add(c);
            }
        } else {
            throw new StatementExecutionException("unsupported SELECT ITEM type: " + c);
        }
    }
    if (allColumns) {
        mainTableProjection = Projection.IDENTITY(table.columnNames, table.columns);
        for (Map.Entry<String, JoinSupport> join : joins.entrySet()) {
            JoinSupport support = join.getValue();
            support.projection = Projection.IDENTITY(support.table.columnNames, support.table.columns);
            support.allColumns = true;
        }
    } else {
        if (!joinPresent) {
            mainTableProjection = new SQLProjection(table, mainTableAlias, selectBody.getSelectItems());
        } else {
            for (JoinSupport support : joins.values()) {
                if (support.allColumns) {
                    support.projection = Projection.IDENTITY(support.table.columnNames, support.table.columns);
                } else {
                    support.projection = new SQLProjection(support.table, support.tableRef.tableAlias, support.selectItems);
                }
            }
            mainTableProjection = joins.get(mainTableAlias).projection;
        }
    }
    if (scan) {
        if (!joinPresent) {
            SQLRecordPredicate where = selectBody.getWhere() != null ? new SQLRecordPredicate(table, mainTableAlias, selectBody.getWhere()) : null;
            if (where != null) {
                discoverIndexOperations(selectBody.getWhere(), table, mainTableAlias, where, tableSpaceManager);
            }
            Aggregator aggregator = null;
            ScanLimitsImpl scanLimits = null;
            if (containsAggregateFunctions || (selectBody.getGroupByColumnReferences() != null && !selectBody.getGroupByColumnReferences().isEmpty())) {
                aggregator = new SQLAggregator(selectBody.getSelectItems(), selectBody.getGroupByColumnReferences(), manager.getRecordSetFactory());
            }
            TupleComparator comparatorOnScan = null;
            TupleComparator comparatorOnPlan = null;
            if (selectBody.getOrderByElements() != null && !selectBody.getOrderByElements().isEmpty()) {
                if (aggregator != null) {
                    comparatorOnPlan = SingleColumnSQLTupleComparator.make(mainTableAlias, selectBody.getOrderByElements(), null);
                } else {
                    comparatorOnScan = SingleColumnSQLTupleComparator.make(mainTableAlias, selectBody.getOrderByElements(), table.primaryKey);
                }
            }
            Limit limit = selectBody.getLimit();
            Top top = selectBody.getTop();
            if (limit != null && top != null) {
                throw new StatementExecutionException("LIMIT and TOP cannot be used on the same query");
            }
            if (limit != null) {
                if (limit.isLimitAll() || limit.isLimitNull() || limit.getOffset() instanceof JdbcParameter) {
                    throw new StatementExecutionException("Invalid LIMIT clause (limit=" + limit + ")");
                }
                if (maxRows > 0 && limit.getRowCount() instanceof JdbcParameter) {
                    throw new StatementExecutionException("Invalid LIMIT clause (limit=" + limit + ") and JDBC setMaxRows=" + maxRows);
                }
                int rowCount;
                int rowCountJdbcParameter = -1;
                if (limit.getRowCount() instanceof JdbcParameter) {
                    rowCount = -1;
                    rowCountJdbcParameter = ((JdbcParameter) limit.getRowCount()).getIndex() - 1;
                } else {
                    rowCount = ((Number) resolveValue(limit.getRowCount(), false)).intValue();
                }
                int offset = limit.getOffset() != null ? ((Number) resolveValue(limit.getOffset(), false)).intValue() : 0;
                scanLimits = new ScanLimitsImpl(rowCount, offset, rowCountJdbcParameter + 1);
            } else if (top != null) {
                if (top.isPercentage() || top.getExpression() == null) {
                    throw new StatementExecutionException("Invalid TOP clause (top=" + top + ")");
                }
                try {
                    int rowCount = Integer.parseInt(resolveValue(top.getExpression(), false) + "");
                    scanLimits = new ScanLimitsImpl(rowCount, 0);
                } catch (NumberFormatException error) {
                    throw new StatementExecutionException("Invalid TOP clause: " + error, error);
                }
            }
            if (maxRows > 0) {
                if (scanLimits == null) {
                    scanLimits = new ScanLimitsImpl(maxRows, 0);
                } else if (scanLimits.getMaxRows() <= 0 || scanLimits.getMaxRows() > maxRows) {
                    scanLimits = new ScanLimitsImpl(maxRows, scanLimits.getOffset());
                }
            }
            ScanLimitsImpl limitsOnScan = null;
            ScanLimitsImpl limitsOnPlan = null;
            if (aggregator != null) {
                limitsOnPlan = scanLimits;
            } else {
                limitsOnScan = scanLimits;
            }
            try {
                ScanStatement statement = new ScanStatement(tableSpace, mainTable.tableName, mainTableProjection, where, comparatorOnScan, limitsOnScan);
                return ExecutionPlan.make(statement, aggregator, limitsOnPlan, comparatorOnPlan);
            } catch (IllegalArgumentException err) {
                throw new StatementExecutionException(err);
            }
        } else {
            if (containsAggregateFunctions || (selectBody.getGroupByColumnReferences() != null && !selectBody.getGroupByColumnReferences().isEmpty())) {
                throw new StatementExecutionException("AGGREGATEs are not yet supported with JOIN");
            }
            Limit limit = selectBody.getLimit();
            Top top = selectBody.getTop();
            if (limit != null && top != null) {
                throw new StatementExecutionException("LIMIT and TOP cannot be used on the same query");
            }
            ScanLimitsImpl scanLimits = null;
            if (limit != null) {
                if (limit.isLimitAll() || limit.isLimitNull() || limit.getOffset() instanceof JdbcParameter) {
                    throw new StatementExecutionException("Invalid LIMIT clause (limit=" + limit + ")");
                }
                if (maxRows > 0 && limit.getRowCount() instanceof JdbcParameter) {
                    throw new StatementExecutionException("Invalid LIMIT clause (limit=" + limit + ") and JDBC setMaxRows=" + maxRows);
                }
                int rowCount;
                int rowCountJdbcParameter = -1;
                if (limit.getRowCount() instanceof JdbcParameter) {
                    rowCount = -1;
                    rowCountJdbcParameter = ((JdbcParameter) limit.getRowCount()).getIndex() - 1;
                } else {
                    rowCount = ((Number) resolveValue(limit.getRowCount(), false)).intValue();
                }
                int offset = limit.getOffset() != null ? ((Number) resolveValue(limit.getOffset(), false)).intValue() : 0;
                scanLimits = new ScanLimitsImpl(rowCount, offset, rowCountJdbcParameter + 1);
            } else if (top != null) {
                if (top.isPercentage() || top.getExpression() == null) {
                    throw new StatementExecutionException("Invalid TOP clause");
                }
                try {
                    int rowCount = Integer.parseInt(resolveValue(top.getExpression(), false) + "");
                    scanLimits = new ScanLimitsImpl(rowCount, 0);
                } catch (NumberFormatException error) {
                    throw new StatementExecutionException("Invalid TOP clause: " + error, error);
                }
            }
            if (maxRows > 0) {
                if (scanLimits == null) {
                    scanLimits = new ScanLimitsImpl(maxRows, 0);
                } else if (scanLimits.getMaxRows() <= 0 || scanLimits.getMaxRows() > maxRows) {
                    scanLimits = new ScanLimitsImpl(maxRows, scanLimits.getOffset());
                }
            }
            List<ColumnReferencesDiscovery> conditionsOnJoinedResult = new ArrayList<>();
            List<ScanStatement> scans = new ArrayList<>();
            for (Map.Entry<String, JoinSupport> join : joins.entrySet()) {
                String alias = join.getKey();
                JoinSupport joinSupport = join.getValue();
                Expression collectedConditionsForAlias = collectConditionsForAlias(alias, selectBody.getWhere(), conditionsOnJoinedResult, mainTableAlias);
                LOG.severe("Collected WHERE for alias " + alias + ": " + collectedConditionsForAlias);
                if (collectedConditionsForAlias == null) {
                    joinSupport.predicate = null;
                } else {
                    joinSupport.predicate = new SQLRecordPredicate(join.getValue().table, alias, collectedConditionsForAlias);
                }
            }
            for (Join join : selectBody.getJoins()) {
                if (join.getOnExpression() != null) {
                    ColumnReferencesDiscovery discoverMainTableAliasForJoinCondition = discoverMainTableAlias(join.getOnExpression());
                    conditionsOnJoinedResult.add(discoverMainTableAliasForJoinCondition);
                    LOG.severe("Collected ON-condition on final JOIN result: " + join.getOnExpression());
                }
            }
            for (ColumnReferencesDiscovery e : conditionsOnJoinedResult) {
                LOG.severe("Collected WHERE on final JOIN result: " + e.getExpression());
                for (Map.Entry<String, List<net.sf.jsqlparser.schema.Column>> entry : e.getColumnsByTable().entrySet()) {
                    String tableAlias = entry.getKey();
                    List<net.sf.jsqlparser.schema.Column> filteredColumnsOnJoin = entry.getValue();
                    LOG.severe("for  TABLE " + tableAlias + " we need to load " + filteredColumnsOnJoin);
                    JoinSupport support = joins.get(tableAlias);
                    if (support == null) {
                        throw new StatementExecutionException("invalid table alias " + tableAlias);
                    }
                    if (!support.allColumns) {
                        for (net.sf.jsqlparser.schema.Column c : filteredColumnsOnJoin) {
                            support.selectItems.add(new SelectExpressionItem(c));
                        }
                        support.projection = new SQLProjection(support.table, support.tableRef.tableAlias, support.selectItems);
                    }
                }
            }
            Map<String, Table> tables = new HashMap<>();
            for (Map.Entry<String, JoinSupport> join : joins.entrySet()) {
                JoinSupport joinSupport = join.getValue();
                tables.put(join.getKey(), joinSupport.table);
                ScanStatement statement = new ScanStatement(tableSpace, joinSupport.table.name, joinSupport.projection, joinSupport.predicate, null, null);
                scans.add(statement);
            }
            TuplePredicate joinFilter = null;
            if (!conditionsOnJoinedResult.isEmpty()) {
                joinFilter = new SQLRecordPredicate(null, null, composeAndExpression(conditionsOnJoinedResult));
            }
            Projection joinProjection = null;
            if (!allColumns) {
                joinProjection = new SQLProjection(tableSpace, tables, selectBody.getSelectItems());
            }
            TupleComparator comparatorOnPlan = null;
            if (selectBody.getOrderByElements() != null && !selectBody.getOrderByElements().isEmpty()) {
                comparatorOnPlan = SingleColumnSQLTupleComparator.make(mainTableAlias, selectBody.getOrderByElements(), null);
            }
            try {
                return ExecutionPlan.joinedScan(scans, joinFilter, joinProjection, scanLimits, comparatorOnPlan);
            } catch (IllegalArgumentException err) {
                throw new StatementExecutionException(err);
            }
        }
    } else {
        if (selectBody.getWhere() == null) {
            throw new StatementExecutionException("unsupported GET without WHERE");
        }
        if (joinPresent) {
            throw new StatementExecutionException("unsupported GET with JOIN");
        }
        // SELECT * FROM WHERE KEY=? AND ....
        SQLRecordKeyFunction keyFunction = findPrimaryKeyIndexSeek(selectBody.getWhere(), table, mainTableAlias);
        if (keyFunction == null || !keyFunction.isFullPrimaryKey()) {
            throw new StatementExecutionException("unsupported GET not on PK, bad where clause: " + selectBody.getWhere() + " (" + selectBody.getWhere().getClass() + ")");
        }
        Predicate where = buildSimplePredicate(selectBody.getWhere(), table, mainTableAlias);
        try {
            return ExecutionPlan.simple(new GetStatement(tableSpace, mainTable.tableName, keyFunction, where, false));
        } catch (IllegalArgumentException err) {
            throw new StatementExecutionException(err);
        }
    }
}
Also used : TuplePredicate(herddb.model.TuplePredicate) LinkedHashMap(java.util.LinkedHashMap) HashMap(java.util.HashMap) ArrayList(java.util.ArrayList) Projection(herddb.model.Projection) StatementExecutionException(herddb.model.StatementExecutionException) LinkedHashMap(java.util.LinkedHashMap) TuplePredicate(herddb.model.TuplePredicate) Predicate(herddb.model.Predicate) TableSpaceManager(herddb.core.TableSpaceManager) ItemsList(net.sf.jsqlparser.expression.operators.relational.ItemsList) ArrayList(java.util.ArrayList) ExpressionList(net.sf.jsqlparser.expression.operators.relational.ExpressionList) ColumnsList(herddb.model.ColumnsList) MultiExpressionList(net.sf.jsqlparser.expression.operators.relational.MultiExpressionList) List(java.util.List) Top(net.sf.jsqlparser.statement.select.Top) AbstractTableManager(herddb.core.AbstractTableManager) GetStatement(herddb.model.commands.GetStatement) Map(java.util.Map) LinkedHashMap(java.util.LinkedHashMap) HashMap(java.util.HashMap) TableSpaceDoesNotExistException(herddb.model.TableSpaceDoesNotExistException) SelectExpressionItem(net.sf.jsqlparser.statement.select.SelectExpressionItem) PlainSelect(net.sf.jsqlparser.statement.select.PlainSelect) TupleComparator(herddb.model.TupleComparator) AllColumns(net.sf.jsqlparser.statement.select.AllColumns) Column(herddb.model.Column) SelectItem(net.sf.jsqlparser.statement.select.SelectItem) ScanStatement(herddb.model.commands.ScanStatement) Table(herddb.model.Table) CreateTable(net.sf.jsqlparser.statement.create.table.CreateTable) JdbcParameter(net.sf.jsqlparser.expression.JdbcParameter) Join(net.sf.jsqlparser.statement.select.Join) Aggregator(herddb.model.Aggregator) ScanLimitsImpl(herddb.model.ScanLimitsImpl) TableDoesNotExistException(herddb.model.TableDoesNotExistException) Expression(net.sf.jsqlparser.expression.Expression) AlterExpression(net.sf.jsqlparser.statement.alter.AlterExpression) BinaryExpression(net.sf.jsqlparser.expression.BinaryExpression) AndExpression(net.sf.jsqlparser.expression.operators.conditional.AndExpression) SignedExpression(net.sf.jsqlparser.expression.SignedExpression) CompiledSQLExpression(herddb.sql.expressions.CompiledSQLExpression) AllTableColumns(net.sf.jsqlparser.statement.select.AllTableColumns) Limit(net.sf.jsqlparser.statement.select.Limit)

Example 2 with TupleComparator

use of herddb.model.TupleComparator in project herddb by diennea.

the class RecordSetSuite method testSortNoSwap.

@Test
public void testSortNoSwap() throws Exception {
    RecordSetFactory factory = buildRecordSetFactory(Integer.MAX_VALUE);
    Column[] columns = new Column[2];
    columns[0] = Column.column("s1", ColumnTypes.STRING);
    columns[1] = Column.column("n1", ColumnTypes.LONG);
    String[] fieldNames = Column.buildFieldNamesList(columns);
    try (MaterializedRecordSet rs = factory.createRecordSet(fieldNames, columns)) {
        for (int i = 0; i < 100; i++) {
            Map<String, Object> record = new HashMap<>();
            String s1 = "test_" + i;
            record.put("s1", s1);
            record.put("n1", i);
            rs.add(new Tuple(record, fieldNames));
        }
        rs.writeFinished();
        // sort descending
        rs.sort(new TupleComparator() {

            @Override
            public int compare(DataAccessor o1, DataAccessor o2) {
                return ((Integer) o2.get(("n1"))).compareTo((Integer) o1.get("n1"));
            }
        });
        int last = Integer.MAX_VALUE;
        for (DataAccessor t : rs) {
            int n1 = (Integer) t.get("n1");
            assertTrue(last > n1);
            last = n1;
        }
    }
}
Also used : HashMap(java.util.HashMap) DataAccessor(herddb.utils.DataAccessor) TupleComparator(herddb.model.TupleComparator) Column(herddb.model.Column) Tuple(herddb.model.Tuple) Test(org.junit.Test)

Example 3 with TupleComparator

use of herddb.model.TupleComparator in project herddb by diennea.

the class CalcitePlannerTest method simplePlansTests.

@Test
public void simplePlansTests() throws Exception {
    String nodeId = "localhost";
    try (DBManager manager = new DBManager("localhost", new MemoryMetadataStorageManager(), new MemoryDataStorageManager(), new MemoryCommitLogManager(), null, null)) {
        assumeThat(manager.getPlanner(), instanceOf(CalcitePlanner.class));
        manager.start();
        CreateTableSpaceStatement st1 = new CreateTableSpaceStatement("tblspace1", Collections.singleton(nodeId), nodeId, 1, 0, 0);
        manager.executeStatement(st1, StatementEvaluationContext.DEFAULT_EVALUATION_CONTEXT(), TransactionContext.NO_TRANSACTION);
        manager.waitForTablespace("tblspace1", 10000);
        execute(manager, "CREATE TABLE tblspace1.tsql (k1 string primary key,n1 int,s1 string)", Collections.emptyList());
        execute(manager, "INSERT INTO tblspace1.tsql (k1,n1) values(?,?)", Arrays.asList("mykey", 1234), TransactionContext.NO_TRANSACTION);
        try (DataScanner scan = scan(manager, "SELECT n1,k1 FROM tblspace1.tsql where k1='mykey'", Collections.emptyList())) {
            assertEquals(1, scan.consume().size());
        }
        assertInstanceOf(plan(manager, "select * from tblspace1.tsql"), TableScanOp.class);
        assertInstanceOf(plan(manager, "select * from tblspace1.tsql where n1=1"), BindableTableScanOp.class);
        assertInstanceOf(plan(manager, "select n1 from tblspace1.tsql"), BindableTableScanOp.class);
        assertInstanceOf(plan(manager, "update tblspace1.tsql set n1=? where k1=?"), SimpleUpdateOp.class);
        assertInstanceOf(plan(manager, "update tblspace1.tsql set n1=? where k1=? and n1=?"), SimpleUpdateOp.class);
        assertInstanceOf(plan(manager, "update tblspace1.tsql set n1=?" + " where n1 in (select b.n1*2 from tblspace1.tsql b)"), UpdateOp.class);
        assertInstanceOf(plan(manager, "delete from tblspace1.tsql where k1=?"), SimpleDeleteOp.class);
        assertInstanceOf(plan(manager, "delete from tblspace1.tsql where k1=? and n1=?"), SimpleDeleteOp.class);
        assertInstanceOf(plan(manager, "delete from tblspace1.tsql where n1 in (select b.n1*2 from tblspace1.tsql b)"), DeleteOp.class);
        assertInstanceOf(plan(manager, "INSERT INTO tblspace1.tsql (k1,n1) values(?,?)"), SimpleInsertOp.class);
        assertInstanceOf(plan(manager, "INSERT INTO tblspace1.tsql (k1,n1) values(?,?),(?,?)"), InsertOp.class);
        assertInstanceOf(plan(manager, "select k1 from tblspace1.tsql order by k1"), SortedBindableTableScanOp.class);
        assertInstanceOf(plan(manager, "select k1 from tblspace1.tsql order by k1 limit 10"), LimitedSortedBindableTableScanOp.class);
        {
            BindableTableScanOp plan = assertInstanceOf(plan(manager, "select * from tblspace1.tsql where k1=?"), BindableTableScanOp.class);
            Projection projection = plan.getStatement().getProjection();
            System.out.println("projection:" + projection);
            assertThat(projection, instanceOf(IdentityProjection.class));
            assertNull(plan.getStatement().getComparator());
        }
        {
            SortedBindableTableScanOp plan = assertInstanceOf(plan(manager, "select n1,k1 from tblspace1.tsql order by n1"), SortedBindableTableScanOp.class);
            Projection projection = plan.getStatement().getProjection();
            System.out.println("projection:" + projection);
            assertThat(projection, instanceOf(ZeroCopyProjection.class));
            ZeroCopyProjection zero = (ZeroCopyProjection) projection;
            assertArrayEquals(new String[] { "n1", "k1" }, zero.getFieldNames());
            assertEquals("n1", zero.getColumns()[0].name);
            assertEquals("k1", zero.getColumns()[1].name);
            TupleComparator comparator = plan.getStatement().getComparator();
            System.out.println("comparator:" + comparator);
            assertThat(comparator, instanceOf(SortOp.class));
            SortOp sortOp = (SortOp) comparator;
            assertFalse(sortOp.isOnlyPrimaryKeyAndAscending());
        }
        {
            SortedBindableTableScanOp plan = assertInstanceOf(plan(manager, "select n1,k1 from tblspace1.tsql order by k1"), SortedBindableTableScanOp.class);
            Projection projection = plan.getStatement().getProjection();
            System.out.println("projection:" + projection);
            assertThat(projection, instanceOf(ZeroCopyProjection.class));
            ZeroCopyProjection zero = (ZeroCopyProjection) projection;
            assertArrayEquals(new String[] { "n1", "k1" }, zero.getFieldNames());
            assertEquals("n1", zero.getColumns()[0].name);
            assertEquals("k1", zero.getColumns()[1].name);
            TupleComparator comparator = plan.getStatement().getComparator();
            System.out.println("comparator:" + comparator);
            assertThat(comparator, instanceOf(SortOp.class));
            SortOp sortOp = (SortOp) comparator;
            assertTrue(sortOp.isOnlyPrimaryKeyAndAscending());
        }
        {
            SortedTableScanOp plan = assertInstanceOf(plan(manager, "select * from tblspace1.tsql order by n1"), SortedTableScanOp.class);
            Projection projection = plan.getStatement().getProjection();
            System.out.println("projection:" + projection);
            assertThat(projection, instanceOf(IdentityProjection.class));
            IdentityProjection zero = (IdentityProjection) projection;
            assertArrayEquals(new String[] { "k1", "n1", "s1" }, zero.getFieldNames());
            assertEquals("k1", zero.getColumns()[0].name);
            assertEquals("n1", zero.getColumns()[1].name);
            assertEquals("s1", zero.getColumns()[2].name);
            TupleComparator comparator = plan.getStatement().getComparator();
            System.out.println("comparator:" + comparator);
            assertThat(comparator, instanceOf(SortOp.class));
            SortOp sortOp = (SortOp) comparator;
            assertFalse(sortOp.isOnlyPrimaryKeyAndAscending());
        }
        {
            SortedTableScanOp plan = assertInstanceOf(plan(manager, "select * from tblspace1.tsql order by k1"), SortedTableScanOp.class);
            Projection projection = plan.getStatement().getProjection();
            System.out.println("projection:" + projection);
            assertThat(projection, instanceOf(IdentityProjection.class));
            IdentityProjection zero = (IdentityProjection) projection;
            assertArrayEquals(new String[] { "k1", "n1", "s1" }, zero.getFieldNames());
            assertEquals("k1", zero.getColumns()[0].name);
            assertEquals("n1", zero.getColumns()[1].name);
            assertEquals("s1", zero.getColumns()[2].name);
            TupleComparator comparator = plan.getStatement().getComparator();
            System.out.println("comparator:" + comparator);
            assertThat(comparator, instanceOf(SortOp.class));
            SortOp sortOp = (SortOp) comparator;
            assertTrue(sortOp.isOnlyPrimaryKeyAndAscending());
        }
    }
}
Also used : MemoryDataStorageManager(herddb.mem.MemoryDataStorageManager) ZeroCopyProjection(herddb.model.planner.ProjectOp.ZeroCopyProjection) IdentityProjection(herddb.model.planner.ProjectOp.IdentityProjection) Projection(herddb.model.Projection) TupleComparator(herddb.model.TupleComparator) SortedTableScanOp(herddb.model.planner.SortedTableScanOp) RawString(herddb.utils.RawString) SortOp(herddb.model.planner.SortOp) IdentityProjection(herddb.model.planner.ProjectOp.IdentityProjection) CreateTableSpaceStatement(herddb.model.commands.CreateTableSpaceStatement) DBManager(herddb.core.DBManager) DataScanner(herddb.model.DataScanner) ZeroCopyProjection(herddb.model.planner.ProjectOp.ZeroCopyProjection) MemoryCommitLogManager(herddb.mem.MemoryCommitLogManager) SortedBindableTableScanOp(herddb.model.planner.SortedBindableTableScanOp) LimitedSortedBindableTableScanOp(herddb.model.planner.LimitedSortedBindableTableScanOp) MemoryMetadataStorageManager(herddb.mem.MemoryMetadataStorageManager) BindableTableScanOp(herddb.model.planner.BindableTableScanOp) SortedBindableTableScanOp(herddb.model.planner.SortedBindableTableScanOp) LimitedSortedBindableTableScanOp(herddb.model.planner.LimitedSortedBindableTableScanOp) Test(org.junit.Test)

Example 4 with TupleComparator

use of herddb.model.TupleComparator in project herddb by diennea.

the class TableManager method scanWithStream.

private DataScanner scanWithStream(ScanStatement statement, StatementEvaluationContext context, Transaction transaction, boolean lockRequired, boolean forWrite) throws StatementExecutionException {
    final TupleComparator comparator = statement.getComparator();
    boolean sorted = comparator != null;
    boolean sortedByClusteredIndex = comparator != null && comparator.isOnlyPrimaryKeyAndAscending() && keyToPage.isSortedAscending();
    final Projection projection = statement.getProjection();
    final boolean applyProjectionDuringScan = projection != null && !sorted;
    ScanLimits limits = statement.getLimits();
    int maxRows = limits == null ? 0 : limits.computeMaxRows(context);
    int offset = limits == null ? 0 : limits.computeOffset(context);
    Stream<DataAccessor> result;
    Function<Record, DataAccessor> mapper = (Record record) -> {
        DataAccessor tuple;
        if (applyProjectionDuringScan) {
            tuple = projection.map(record.getDataAccessor(table), context);
        } else {
            tuple = record.getDataAccessor(table);
        }
        return tuple;
    };
    Stream<DataAccessor> fromTransactionSorted = streamTransactionData(transaction, statement.getPredicate(), context).map(mapper);
    if (comparator != null) {
        fromTransactionSorted = fromTransactionSorted.sorted(comparator);
    }
    Stream<DataAccessor> tableData = streamTableData(statement, context, transaction, lockRequired, forWrite).map(mapper);
    if (maxRows > 0) {
        if (sortedByClusteredIndex) {
            // already sorted from index
            tableData = tableData.limit(maxRows + offset);
            // already sorted if needed
            fromTransactionSorted = fromTransactionSorted.limit(maxRows + offset);
            // we need to re-sort
            result = Stream.concat(fromTransactionSorted, tableData).sorted(comparator);
        } else if (sorted) {
            // need to sort
            tableData = tableData.sorted(comparator);
            tableData = tableData.limit(maxRows + offset);
            // already sorted if needed
            fromTransactionSorted = fromTransactionSorted.limit(maxRows + offset);
            // we need to re-sort
            result = Stream.concat(fromTransactionSorted, tableData).sorted(comparator);
        } else {
            result = Stream.concat(fromTransactionSorted, tableData);
        }
    } else {
        if (sortedByClusteredIndex) {
            // already sorted from index
            tableData = tableData.sorted(comparator);
            // fromTransactionSorted is already sorted
            // we need to re-sort
            result = Stream.concat(fromTransactionSorted, tableData).sorted(comparator);
        } else if (sorted) {
            // tableData already sorted from index
            // fromTransactionSorted is already sorted
            // we need to re-sort
            result = Stream.concat(fromTransactionSorted, tableData).sorted(comparator);
        } else {
            // no need to sort
            result = Stream.concat(fromTransactionSorted, tableData);
        }
    }
    if (offset > 0) {
        result = result.skip(offset);
    }
    if (maxRows > 0) {
        result = result.limit(maxRows);
    }
    if (!applyProjectionDuringScan && projection != null) {
        result = result.map(r -> projection.map(r, context));
    }
    String[] fieldNames;
    Column[] columns;
    if (projection != null) {
        fieldNames = projection.getFieldNames();
        columns = projection.getColumns();
    } else {
        fieldNames = table.columnNames;
        columns = table.columns;
    }
    return new StreamDataScanner(transaction != null ? transaction.transactionId : 0, fieldNames, columns, result);
}
Also used : UpdateStatement(herddb.model.commands.UpdateStatement) Table(herddb.model.Table) TruncateTableStatement(herddb.model.commands.TruncateTableStatement) TupleComparator(herddb.model.TupleComparator) DuplicatePrimaryKeyException(herddb.model.DuplicatePrimaryKeyException) TableStatus(herddb.storage.TableStatus) ServerConfiguration(herddb.server.ServerConfiguration) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) Map(java.util.Map) RecordTooBigException(herddb.model.RecordTooBigException) DMLStatementExecutionResult(herddb.model.DMLStatementExecutionResult) LocalLockManager(herddb.utils.LocalLockManager) DataStorageManagerException(herddb.storage.DataStorageManagerException) Index(herddb.model.Index) DataAccessor(herddb.utils.DataAccessor) LogNotAvailableException(herddb.log.LogNotAvailableException) InsertStatement(herddb.model.commands.InsertStatement) DataScanner(herddb.model.DataScanner) CommitLogResult(herddb.log.CommitLogResult) DDLException(herddb.model.DDLException) RecordFunction(herddb.model.RecordFunction) StatementExecutionException(herddb.model.StatementExecutionException) TableContext(herddb.model.TableContext) Collection(java.util.Collection) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) Set(java.util.Set) LogSequenceNumber(herddb.log.LogSequenceNumber) Logger(java.util.logging.Logger) Collectors(java.util.stream.Collectors) RecordSerializer(herddb.codec.RecordSerializer) DataPageMetaData(herddb.core.PageSet.DataPageMetaData) ScanStatement(herddb.model.commands.ScanStatement) List(java.util.List) Stream(java.util.stream.Stream) FullTableScanConsumer(herddb.storage.FullTableScanConsumer) GetStatement(herddb.model.commands.GetStatement) Entry(java.util.Map.Entry) Statement(herddb.model.Statement) Bytes(herddb.utils.Bytes) LongAdder(java.util.concurrent.atomic.LongAdder) Holder(herddb.utils.Holder) LockHandle(herddb.utils.LockHandle) LogEntry(herddb.log.LogEntry) GetResult(herddb.model.GetResult) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) HashMap(java.util.HashMap) PrimaryIndexSeek(herddb.index.PrimaryIndexSeek) Function(java.util.function.Function) ArrayList(java.util.ArrayList) ConcurrentMap(java.util.concurrent.ConcurrentMap) Level(java.util.logging.Level) BatchOrderedExecutor(herddb.utils.BatchOrderedExecutor) Transaction(herddb.model.Transaction) ThreadLocalRandom(java.util.concurrent.ThreadLocalRandom) Projection(herddb.model.Projection) EnsureLongIncrementAccumulator(herddb.utils.EnsureLongIncrementAccumulator) LogEntryType(herddb.log.LogEntryType) ScanLimits(herddb.model.ScanLimits) DeleteStatement(herddb.model.commands.DeleteStatement) Iterator(java.util.Iterator) ReentrantLock(java.util.concurrent.locks.ReentrantLock) Record(herddb.model.Record) Semaphore(java.util.concurrent.Semaphore) DataPageDoesNotExistException(herddb.storage.DataPageDoesNotExistException) LogEntryFactory(herddb.log.LogEntryFactory) StatementExecutionResult(herddb.model.StatementExecutionResult) KeyToPageIndex(herddb.index.KeyToPageIndex) DataStorageManager(herddb.storage.DataStorageManager) ColumnTypes(herddb.model.ColumnTypes) TimeUnit(java.util.concurrent.TimeUnit) Consumer(java.util.function.Consumer) AtomicLong(java.util.concurrent.atomic.AtomicLong) Lock(java.util.concurrent.locks.Lock) CommitLog(herddb.log.CommitLog) IndexOperation(herddb.index.IndexOperation) Predicate(herddb.model.Predicate) Column(herddb.model.Column) StatementEvaluationContext(herddb.model.StatementEvaluationContext) Comparator(java.util.Comparator) Collections(java.util.Collections) SECONDS(java.util.concurrent.TimeUnit.SECONDS) StampedLock(java.util.concurrent.locks.StampedLock) TableManagerStats(herddb.core.stats.TableManagerStats) SystemProperties(herddb.utils.SystemProperties) ScanLimits(herddb.model.ScanLimits) DataAccessor(herddb.utils.DataAccessor) Projection(herddb.model.Projection) TupleComparator(herddb.model.TupleComparator) Column(herddb.model.Column) Record(herddb.model.Record)

Example 5 with TupleComparator

use of herddb.model.TupleComparator in project herddb by diennea.

the class RecordSetSuite method testSortSwap.

@Test
public void testSortSwap() throws Exception {
    RecordSetFactory factory = buildRecordSetFactory(1);
    Column[] columns = new Column[2];
    columns[0] = Column.column("s1", ColumnTypes.STRING);
    columns[1] = Column.column("n1", ColumnTypes.LONG);
    String[] fieldNames = Column.buildFieldNamesList(columns);
    try (MaterializedRecordSet rs = factory.createRecordSet(fieldNames, columns)) {
        for (int i = 0; i < 100; i++) {
            Map<String, Object> record = new HashMap<>();
            String s1 = "test_" + i;
            record.put("s1", s1);
            record.put("n1", i);
            rs.add(new Tuple(record, fieldNames));
        }
        rs.writeFinished();
        // sort descending
        rs.sort(new TupleComparator() {

            @Override
            public int compare(DataAccessor o1, DataAccessor o2) {
                return ((Integer) o2.get(("n1"))).compareTo((Integer) o1.get("n1"));
            }
        });
        int last = Integer.MAX_VALUE;
        for (DataAccessor t : rs) {
            int n1 = (Integer) t.get("n1");
            assertTrue(last > n1);
            last = n1;
        }
    }
}
Also used : HashMap(java.util.HashMap) DataAccessor(herddb.utils.DataAccessor) TupleComparator(herddb.model.TupleComparator) Column(herddb.model.Column) Tuple(herddb.model.Tuple) Test(org.junit.Test)

Aggregations

TupleComparator (herddb.model.TupleComparator)5 Column (herddb.model.Column)4 HashMap (java.util.HashMap)4 Projection (herddb.model.Projection)3 DataAccessor (herddb.utils.DataAccessor)3 Test (org.junit.Test)3 DataScanner (herddb.model.DataScanner)2 Predicate (herddb.model.Predicate)2 StatementExecutionException (herddb.model.StatementExecutionException)2 Table (herddb.model.Table)2 GetStatement (herddb.model.commands.GetStatement)2 ScanStatement (herddb.model.commands.ScanStatement)2 ArrayList (java.util.ArrayList)2 List (java.util.List)2 Map (java.util.Map)2 RecordSerializer (herddb.codec.RecordSerializer)1 AbstractTableManager (herddb.core.AbstractTableManager)1 DBManager (herddb.core.DBManager)1 DataPageMetaData (herddb.core.PageSet.DataPageMetaData)1 TableSpaceManager (herddb.core.TableSpaceManager)1