Search in sources :

Example 41 with Alias

use of org.h2.expression.Alias in project felix by apache.

the class H2Activator method start.

@Override
public void start(BundleContext context) throws Exception {
    ds = new JdbcDataSource();
    ds.setURL("jdbc:h2:mem:test;DB_CLOSE_DELAY=-1;DB_CLOSE_ON_EXIT=FALSE");
    Dictionary<String, String> props = new Hashtable<String, String>();
    props.put("dataSourceName", "test");
    context.registerService(DataSource.class.getName(), ds, props);
    loadData(ds);
    // Register the H2 console servlet
    Dictionary<String, String> servletProps = new Hashtable<String, String>();
    servletProps.put("alias", "/h2");
    servletProps.put("init.webAllowOthers", "true");
    context.registerService(Servlet.class.getName(), new WebServlet(), servletProps);
}
Also used : WebServlet(org.h2.server.web.WebServlet) Hashtable(java.util.Hashtable) JdbcDataSource(org.h2.jdbcx.JdbcDataSource) Servlet(javax.servlet.Servlet) WebServlet(org.h2.server.web.WebServlet) DataSource(javax.sql.DataSource) JdbcDataSource(org.h2.jdbcx.JdbcDataSource)

Example 42 with Alias

use of org.h2.expression.Alias in project ignite by apache.

the class GridReduceQueryExecutor method createMergeTable.

/**
 * @param conn Connection.
 * @param qry Query.
 * @param explain Explain.
 * @return Table.
 * @throws IgniteCheckedException If failed.
 */
@SuppressWarnings("unchecked")
private GridMergeTable createMergeTable(JdbcConnection conn, GridCacheSqlQuery qry, boolean explain) throws IgniteCheckedException {
    try {
        Session ses = (Session) conn.getSession();
        CreateTableData data = new CreateTableData();
        data.tableName = "T___";
        data.schema = ses.getDatabase().getSchema(ses.getCurrentSchemaName());
        data.create = true;
        if (!explain) {
            LinkedHashMap<String, ?> colsMap = qry.columns();
            assert colsMap != null;
            ArrayList<Column> cols = new ArrayList<>(colsMap.size());
            for (Map.Entry<String, ?> e : colsMap.entrySet()) {
                String alias = e.getKey();
                GridSqlType t = (GridSqlType) e.getValue();
                assert !F.isEmpty(alias);
                Column c = new Column(alias, t.type(), t.precision(), t.scale(), t.displaySize());
                cols.add(c);
            }
            data.columns = cols;
        } else
            data.columns = planColumns();
        boolean sortedIndex = !F.isEmpty(qry.sortColumns());
        GridMergeTable tbl = new GridMergeTable(data);
        ArrayList<Index> idxs = new ArrayList<>(2);
        if (explain) {
            idxs.add(new GridMergeIndexUnsorted(ctx, tbl, sortedIndex ? MERGE_INDEX_SORTED : MERGE_INDEX_UNSORTED));
        } else if (sortedIndex) {
            List<GridSqlSortColumn> sortCols = (List<GridSqlSortColumn>) qry.sortColumns();
            GridMergeIndexSorted sortedMergeIdx = new GridMergeIndexSorted(ctx, tbl, MERGE_INDEX_SORTED, GridSqlSortColumn.toIndexColumns(tbl, sortCols));
            idxs.add(GridMergeTable.createScanIndex(sortedMergeIdx));
            idxs.add(sortedMergeIdx);
        } else
            idxs.add(new GridMergeIndexUnsorted(ctx, tbl, MERGE_INDEX_UNSORTED));
        tbl.indexes(idxs);
        return tbl;
    } catch (Exception e) {
        U.closeQuiet(conn);
        throw new IgniteCheckedException(e);
    }
}
Also used : ArrayList(java.util.ArrayList) Index(org.h2.index.Index) CreateTableData(org.h2.command.ddl.CreateTableData) QueryCancelledException(org.apache.ignite.cache.query.QueryCancelledException) IgniteClientDisconnectedException(org.apache.ignite.IgniteClientDisconnectedException) IgniteCheckedException(org.apache.ignite.IgniteCheckedException) IgniteException(org.apache.ignite.IgniteException) SQLException(java.sql.SQLException) IgniteInterruptedCheckedException(org.apache.ignite.internal.IgniteInterruptedCheckedException) CacheException(javax.cache.CacheException) TransactionException(org.apache.ignite.transactions.TransactionException) IgniteCheckedException(org.apache.ignite.IgniteCheckedException) GridSqlSortColumn(org.apache.ignite.internal.processors.query.h2.sql.GridSqlSortColumn) Column(org.h2.table.Column) GridSqlSortColumn(org.apache.ignite.internal.processors.query.h2.sql.GridSqlSortColumn) GridSqlType(org.apache.ignite.internal.processors.query.h2.sql.GridSqlType) Collections.singletonList(java.util.Collections.singletonList) GridIntList(org.apache.ignite.internal.util.GridIntList) List(java.util.List) ArrayList(java.util.ArrayList) Map(java.util.Map) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) HashMap(java.util.HashMap) ConcurrentMap(java.util.concurrent.ConcurrentMap) LinkedHashMap(java.util.LinkedHashMap) Session(org.h2.engine.Session)

Example 43 with Alias

use of org.h2.expression.Alias in project h2database by h2database.

the class Query method initOrder.

/**
 * Initialize the order by list. This call may extend the expressions list.
 *
 * @param session the session
 * @param expressions the select list expressions
 * @param expressionSQL the select list SQL snippets
 * @param orderList the order by list
 * @param visible the number of visible columns in the select list
 * @param mustBeInResult all order by expressions must be in the select list
 * @param filters the table filters
 */
static void initOrder(Session session, ArrayList<Expression> expressions, ArrayList<String> expressionSQL, ArrayList<SelectOrderBy> orderList, int visible, boolean mustBeInResult, ArrayList<TableFilter> filters) {
    Database db = session.getDatabase();
    for (SelectOrderBy o : orderList) {
        Expression e = o.expression;
        if (e == null) {
            continue;
        }
        // special case: SELECT 1 AS A FROM DUAL ORDER BY A
        // (oracle supports it, but only in order by, not in group by and
        // not in having):
        // SELECT 1 AS A FROM DUAL ORDER BY -A
        boolean isAlias = false;
        int idx = expressions.size();
        if (e instanceof ExpressionColumn) {
            // order by expression
            ExpressionColumn exprCol = (ExpressionColumn) e;
            String tableAlias = exprCol.getOriginalTableAliasName();
            String col = exprCol.getOriginalColumnName();
            for (int j = 0; j < visible; j++) {
                boolean found = false;
                Expression ec = expressions.get(j);
                if (ec instanceof ExpressionColumn) {
                    // select expression
                    ExpressionColumn c = (ExpressionColumn) ec;
                    found = db.equalsIdentifiers(col, c.getColumnName());
                    if (found && tableAlias != null) {
                        String ca = c.getOriginalTableAliasName();
                        if (ca == null) {
                            found = false;
                            if (filters != null) {
                                // select id from test order by test.id
                                for (TableFilter f : filters) {
                                    if (db.equalsIdentifiers(f.getTableAlias(), tableAlias)) {
                                        found = true;
                                        break;
                                    }
                                }
                            }
                        } else {
                            found = db.equalsIdentifiers(ca, tableAlias);
                        }
                    }
                } else if (!(ec instanceof Alias)) {
                    continue;
                } else if (tableAlias == null && db.equalsIdentifiers(col, ec.getAlias())) {
                    found = true;
                } else {
                    Expression ec2 = ec.getNonAliasExpression();
                    if (ec2 instanceof ExpressionColumn) {
                        ExpressionColumn c2 = (ExpressionColumn) ec2;
                        String ta = exprCol.getSQL();
                        String tb = c2.getSQL();
                        String s2 = c2.getColumnName();
                        found = db.equalsIdentifiers(col, s2);
                        if (!db.equalsIdentifiers(ta, tb)) {
                            found = false;
                        }
                    }
                }
                if (found) {
                    idx = j;
                    isAlias = true;
                    break;
                }
            }
        } else {
            String s = e.getSQL();
            if (expressionSQL != null) {
                for (int j = 0, size = expressionSQL.size(); j < size; j++) {
                    String s2 = expressionSQL.get(j);
                    if (db.equalsIdentifiers(s2, s)) {
                        idx = j;
                        isAlias = true;
                        break;
                    }
                }
            }
        }
        if (!isAlias) {
            if (mustBeInResult) {
                throw DbException.get(ErrorCode.ORDER_BY_NOT_IN_RESULT, e.getSQL());
            }
            expressions.add(e);
            String sql = e.getSQL();
            expressionSQL.add(sql);
        }
        o.columnIndexExpr = ValueExpression.get(ValueInt.get(idx + 1));
        o.expression = expressions.get(idx).getNonAliasExpression();
    }
}
Also used : ValueExpression(org.h2.expression.ValueExpression) Expression(org.h2.expression.Expression) TableFilter(org.h2.table.TableFilter) Alias(org.h2.expression.Alias) Database(org.h2.engine.Database) ExpressionColumn(org.h2.expression.ExpressionColumn)

Example 44 with Alias

use of org.h2.expression.Alias in project h2database by h2database.

the class Select method init.

@Override
public void init() {
    if (SysProperties.CHECK && checkInit) {
        DbException.throwInternalError();
    }
    expandColumnList();
    visibleColumnCount = expressions.size();
    ArrayList<String> expressionSQL;
    if (orderList != null || group != null) {
        expressionSQL = New.arrayList();
        for (int i = 0; i < visibleColumnCount; i++) {
            Expression expr = expressions.get(i);
            expr = expr.getNonAliasExpression();
            String sql = expr.getSQL();
            expressionSQL.add(sql);
        }
    } else {
        expressionSQL = null;
    }
    if (orderList != null) {
        initOrder(session, expressions, expressionSQL, orderList, visibleColumnCount, distinct, filters);
    }
    distinctColumnCount = expressions.size();
    if (having != null) {
        expressions.add(having);
        havingIndex = expressions.size() - 1;
        having = null;
    } else {
        havingIndex = -1;
    }
    Database db = session.getDatabase();
    // and 'GROUP BY' expressions at the end
    if (group != null) {
        int size = group.size();
        int expSize = expressionSQL.size();
        groupIndex = new int[size];
        for (int i = 0; i < size; i++) {
            Expression expr = group.get(i);
            String sql = expr.getSQL();
            int found = -1;
            for (int j = 0; j < expSize; j++) {
                String s2 = expressionSQL.get(j);
                if (db.equalsIdentifiers(s2, sql)) {
                    found = j;
                    break;
                }
            }
            if (found < 0) {
                // special case: GROUP BY a column alias
                for (int j = 0; j < expSize; j++) {
                    Expression e = expressions.get(j);
                    if (db.equalsIdentifiers(sql, e.getAlias())) {
                        found = j;
                        break;
                    }
                    sql = expr.getAlias();
                    if (db.equalsIdentifiers(sql, e.getAlias())) {
                        found = j;
                        break;
                    }
                }
            }
            if (found < 0) {
                int index = expressions.size();
                groupIndex[i] = index;
                expressions.add(expr);
            } else {
                groupIndex[i] = found;
            }
        }
        groupByExpression = new boolean[expressions.size()];
        for (int gi : groupIndex) {
            groupByExpression[gi] = true;
        }
        group = null;
    }
    // map columns in select list and condition
    for (TableFilter f : filters) {
        mapColumns(f, 0);
    }
    if (havingIndex >= 0) {
        Expression expr = expressions.get(havingIndex);
        SelectListColumnResolver res = new SelectListColumnResolver(this);
        expr.mapColumns(res, 0);
    }
    checkInit = true;
}
Also used : Database(org.h2.engine.Database)

Example 45 with Alias

use of org.h2.expression.Alias in project h2database by h2database.

the class TableLink method getRowCount.

@Override
public synchronized long getRowCount(Session session) {
    // The foo alias is used to support the PostgreSQL syntax
    String sql = "SELECT COUNT(*) FROM " + qualifiedTableName + " as foo";
    try {
        PreparedStatement prep = execute(sql, null, false);
        ResultSet rs = prep.getResultSet();
        rs.next();
        long count = rs.getLong(1);
        rs.close();
        reusePreparedStatement(prep, sql);
        return count;
    } catch (Exception e) {
        throw wrapException(sql, e);
    }
}
Also used : ResultSet(java.sql.ResultSet) PreparedStatement(java.sql.PreparedStatement) DbException(org.h2.message.DbException) SQLException(java.sql.SQLException) JdbcSQLException(org.h2.jdbc.JdbcSQLException)

Aggregations

ResultSet (java.sql.ResultSet)38 Statement (java.sql.Statement)38 Connection (java.sql.Connection)31 SimpleResultSet (org.h2.tools.SimpleResultSet)31 PreparedStatement (java.sql.PreparedStatement)28 CallableStatement (java.sql.CallableStatement)18 ValueString (org.h2.value.ValueString)17 SQLException (java.sql.SQLException)11 Column (org.h2.table.Column)10 GridSqlColumn (org.apache.ignite.internal.processors.query.h2.sql.GridSqlColumn)6 Expression (org.h2.expression.Expression)6 ArrayList (java.util.ArrayList)5 HashMap (java.util.HashMap)5 GridSqlAlias (org.apache.ignite.internal.processors.query.h2.sql.GridSqlAlias)5 GridH2Table (org.apache.ignite.internal.processors.query.h2.opt.GridH2Table)4 GridSqlElement (org.apache.ignite.internal.processors.query.h2.sql.GridSqlElement)4 GridSqlSelect (org.apache.ignite.internal.processors.query.h2.sql.GridSqlSelect)4 GridSqlTable (org.apache.ignite.internal.processors.query.h2.sql.GridSqlTable)4 Session (org.h2.engine.Session)4 ValueExpression (org.h2.expression.ValueExpression)4