Search in sources :

Example 6 with Variable

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

the class Session method setVariable.

/**
 * Set the value of the given variable for this session.
 *
 * @param name the name of the variable (may not be null)
 * @param value the new value (may not be null)
 */
public void setVariable(String name, Value value) {
    initVariables();
    modificationId++;
    Value old;
    if (value == ValueNull.INSTANCE) {
        old = variables.remove(name);
    } else {
        // link LOB values, to make sure we have our own object
        value = value.copy(database, LobStorageFrontend.TABLE_ID_SESSION_VARIABLE);
        old = variables.put(name, value);
    }
    if (old != null) {
        // remove the old value (in case it is a lob)
        old.remove();
    }
}
Also used : Value(org.h2.value.Value)

Example 7 with Variable

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

the class Function method optimize.

@Override
public Expression optimize(Session session) {
    boolean allConst = info.deterministic;
    for (int i = 0; i < args.length; i++) {
        Expression e = args[i];
        if (e == null) {
            continue;
        }
        e = e.optimize(session);
        args[i] = e;
        if (!e.isConstant()) {
            allConst = false;
        }
    }
    int t, s, d;
    long p;
    Expression p0 = args.length < 1 ? null : args[0];
    switch(info.type) {
        case IFNULL:
        case NULLIF:
        case COALESCE:
        case LEAST:
        case GREATEST:
            {
                t = Value.UNKNOWN;
                s = 0;
                p = 0;
                d = 0;
                for (Expression e : args) {
                    if (e != ValueExpression.getNull()) {
                        int type = e.getType();
                        if (type != Value.UNKNOWN && type != Value.NULL) {
                            t = Value.getHigherOrder(t, type);
                            s = Math.max(s, e.getScale());
                            p = Math.max(p, e.getPrecision());
                            d = Math.max(d, e.getDisplaySize());
                        }
                    }
                }
                if (t == Value.UNKNOWN) {
                    t = Value.STRING;
                    s = 0;
                    p = Integer.MAX_VALUE;
                    d = Integer.MAX_VALUE;
                }
                break;
            }
        case CASE:
        case DECODE:
            {
                t = Value.UNKNOWN;
                s = 0;
                p = 0;
                d = 0;
                // (expr, when, then, when, then, else)
                for (int i = 2, len = args.length; i < len; i += 2) {
                    Expression then = args[i];
                    if (then != ValueExpression.getNull()) {
                        int type = then.getType();
                        if (type != Value.UNKNOWN && type != Value.NULL) {
                            t = Value.getHigherOrder(t, type);
                            s = Math.max(s, then.getScale());
                            p = Math.max(p, then.getPrecision());
                            d = Math.max(d, then.getDisplaySize());
                        }
                    }
                }
                if (args.length % 2 == 0) {
                    Expression elsePart = args[args.length - 1];
                    if (elsePart != ValueExpression.getNull()) {
                        int type = elsePart.getType();
                        if (type != Value.UNKNOWN && type != Value.NULL) {
                            t = Value.getHigherOrder(t, type);
                            s = Math.max(s, elsePart.getScale());
                            p = Math.max(p, elsePart.getPrecision());
                            d = Math.max(d, elsePart.getDisplaySize());
                        }
                    }
                }
                if (t == Value.UNKNOWN) {
                    t = Value.STRING;
                    s = 0;
                    p = Integer.MAX_VALUE;
                    d = Integer.MAX_VALUE;
                }
                break;
            }
        case CASEWHEN:
            t = Value.getHigherOrder(args[1].getType(), args[2].getType());
            p = Math.max(args[1].getPrecision(), args[2].getPrecision());
            d = Math.max(args[1].getDisplaySize(), args[2].getDisplaySize());
            s = Math.max(args[1].getScale(), args[2].getScale());
            break;
        case NVL2:
            switch(args[1].getType()) {
                case Value.STRING:
                case Value.CLOB:
                case Value.STRING_FIXED:
                case Value.STRING_IGNORECASE:
                    t = args[1].getType();
                    break;
                default:
                    t = Value.getHigherOrder(args[1].getType(), args[2].getType());
                    break;
            }
            p = Math.max(args[1].getPrecision(), args[2].getPrecision());
            d = Math.max(args[1].getDisplaySize(), args[2].getDisplaySize());
            s = Math.max(args[1].getScale(), args[2].getScale());
            break;
        case CAST:
        case CONVERT:
        case TRUNCATE_VALUE:
            // data type, precision and scale is already set
            t = dataType;
            p = precision;
            s = scale;
            d = displaySize;
            break;
        case TRUNCATE:
            t = p0.getType();
            s = p0.getScale();
            p = p0.getPrecision();
            d = p0.getDisplaySize();
            if (t == Value.NULL) {
                t = Value.INT;
                p = ValueInt.PRECISION;
                d = ValueInt.DISPLAY_SIZE;
                s = 0;
            } else if (t == Value.TIMESTAMP) {
                t = Value.DATE;
                p = ValueDate.PRECISION;
                s = 0;
                d = ValueDate.PRECISION;
            }
            break;
        case ABS:
        case FLOOR:
        case ROUND:
            t = p0.getType();
            s = p0.getScale();
            p = p0.getPrecision();
            d = p0.getDisplaySize();
            if (t == Value.NULL) {
                t = Value.INT;
                p = ValueInt.PRECISION;
                d = ValueInt.DISPLAY_SIZE;
                s = 0;
            }
            break;
        case SET:
            {
                Expression p1 = args[1];
                t = p1.getType();
                p = p1.getPrecision();
                s = p1.getScale();
                d = p1.getDisplaySize();
                if (!(p0 instanceof Variable)) {
                    throw DbException.get(ErrorCode.CAN_ONLY_ASSIGN_TO_VARIABLE_1, p0.getSQL());
                }
                break;
            }
        case FILE_READ:
            {
                if (args.length == 1) {
                    t = Value.BLOB;
                } else {
                    t = Value.CLOB;
                }
                p = Integer.MAX_VALUE;
                s = 0;
                d = Integer.MAX_VALUE;
                break;
            }
        case SUBSTRING:
        case SUBSTR:
            {
                t = info.returnDataType;
                p = args[0].getPrecision();
                s = 0;
                if (args[1].isConstant()) {
                    // if only two arguments are used,
                    // subtract offset from first argument length
                    p -= args[1].getValue(session).getLong() - 1;
                }
                if (args.length == 3 && args[2].isConstant()) {
                    // if the third argument is constant it is at most this value
                    p = Math.min(p, args[2].getValue(session).getLong());
                }
                p = Math.max(0, p);
                d = MathUtils.convertLongToInt(p);
                break;
            }
        default:
            t = info.returnDataType;
            DataType type = DataType.getDataType(t);
            p = PRECISION_UNKNOWN;
            d = 0;
            s = type.defaultScale;
    }
    dataType = t;
    precision = p;
    scale = s;
    displaySize = d;
    if (allConst) {
        Value v = getValue(session);
        if (v == ValueNull.INSTANCE) {
            if (info.type == CAST || info.type == CONVERT) {
                return this;
            }
        }
        return ValueExpression.get(v);
    }
    return this;
}
Also used : Value(org.h2.value.Value) DataType(org.h2.value.DataType)

Example 8 with Variable

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

the class DateTimeFunctions method truncateDate.

/**
 * Truncate the given date to the unit specified
 *
 * @param datePartStr the time unit (e.g. 'DAY', 'HOUR', etc.)
 * @param valueDate the date
 * @return date truncated to 'day'
 */
public static Value truncateDate(String datePartStr, Value valueDate) {
    int timeUnit = getDatePart(datePartStr);
    // Retrieve the dateValue and the time in nanoseconds of the date.
    long[] fieldDateAndTime = DateTimeUtils.dateAndTimeFromValue(valueDate);
    long dateValue = fieldDateAndTime[0];
    long timeNanosRetrieved = fieldDateAndTime[1];
    // Variable used to the time in nanoseconds of the date truncated.
    long timeNanos;
    // result to nanoseconds.
    switch(timeUnit) {
        case MICROSECOND:
            long nanoInMicroSecond = 1_000L;
            long microseconds = timeNanosRetrieved / nanoInMicroSecond;
            timeNanos = microseconds * nanoInMicroSecond;
            break;
        case MILLISECOND:
            long nanoInMilliSecond = 1_000_000L;
            long milliseconds = timeNanosRetrieved / nanoInMilliSecond;
            timeNanos = milliseconds * nanoInMilliSecond;
            break;
        case SECOND:
            long nanoInSecond = 1_000_000_000L;
            long seconds = timeNanosRetrieved / nanoInSecond;
            timeNanos = seconds * nanoInSecond;
            break;
        case MINUTE:
            long nanoInMinute = 60_000_000_000L;
            long minutes = timeNanosRetrieved / nanoInMinute;
            timeNanos = minutes * nanoInMinute;
            break;
        case HOUR:
            long nanoInHour = 3_600_000_000_000L;
            long hours = timeNanosRetrieved / nanoInHour;
            timeNanos = hours * nanoInHour;
            break;
        case DAY_OF_MONTH:
            timeNanos = 0L;
            break;
        case WEEK:
            long absoluteDay = DateTimeUtils.absoluteDayFromDateValue(dateValue);
            int dayOfWeek = DateTimeUtils.getDayOfWeekFromAbsolute(absoluteDay, 1);
            if (dayOfWeek != 1) {
                dateValue = DateTimeUtils.dateValueFromAbsoluteDay(absoluteDay - dayOfWeek + 1);
            }
            timeNanos = 0L;
            break;
        case MONTH:
            {
                long year = DateTimeUtils.yearFromDateValue(dateValue);
                int month = DateTimeUtils.monthFromDateValue(dateValue);
                dateValue = DateTimeUtils.dateValue(year, month, 1);
                timeNanos = 0L;
                break;
            }
        case QUARTER:
            {
                long year = DateTimeUtils.yearFromDateValue(dateValue);
                int month = DateTimeUtils.monthFromDateValue(dateValue);
                month = ((month - 1) / 3) * 3 + 1;
                dateValue = DateTimeUtils.dateValue(year, month, 1);
                timeNanos = 0L;
                break;
            }
        case YEAR:
            {
                long year = DateTimeUtils.yearFromDateValue(dateValue);
                dateValue = DateTimeUtils.dateValue(year, 1, 1);
                timeNanos = 0L;
                break;
            }
        case DECADE:
            {
                long year = DateTimeUtils.yearFromDateValue(dateValue);
                year = (year / 10) * 10;
                dateValue = DateTimeUtils.dateValue(year, 1, 1);
                timeNanos = 0L;
                break;
            }
        case CENTURY:
            {
                long year = DateTimeUtils.yearFromDateValue(dateValue);
                year = ((year - 1) / 100) * 100 + 1;
                dateValue = DateTimeUtils.dateValue(year, 1, 1);
                timeNanos = 0L;
                break;
            }
        case MILLENNIUM:
            {
                long year = DateTimeUtils.yearFromDateValue(dateValue);
                year = ((year - 1) / 1000) * 1000 + 1;
                dateValue = DateTimeUtils.dateValue(year, 1, 1);
                timeNanos = 0L;
                break;
            }
        default:
            // Return an exception in the timeUnit is not recognized
            throw DbException.getUnsupportedException(datePartStr);
    }
    Value result;
    if (valueDate instanceof ValueTimestampTimeZone) {
        // Case we create a timestamp with timezone with the dateValue and
        // timeNanos computed.
        ValueTimestampTimeZone vTmp = (ValueTimestampTimeZone) valueDate;
        result = ValueTimestampTimeZone.fromDateValueAndNanos(dateValue, timeNanos, vTmp.getTimeZoneOffsetMins());
    } else {
        // By default, we create a timestamp with the dateValue and
        // timeNanos computed.
        result = ValueTimestamp.fromDateValueAndNanos(dateValue, timeNanos);
    }
    return result;
}
Also used : Value(org.h2.value.Value) ValueTimestampTimeZone(org.h2.value.ValueTimestampTimeZone)

Example 9 with Variable

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

the class TableInspector method generateColumn.

private StatementBuilder generateColumn(Set<String> imports, ColumnInspector col, boolean trimStrings) {
    StatementBuilder sb = new StatementBuilder();
    Class<?> clazz = col.clazz;
    String column = ModelUtils.convertColumnToFieldName(col.name.toLowerCase());
    sb.append('\t');
    if (clazz == null) {
        // unsupported type
        clazz = Object.class;
        sb.append("// unsupported type " + col.type);
    } else {
        // @JQColumn
        imports.add(clazz.getCanonicalName());
        sb.append('@').append(JQColumn.class.getSimpleName());
        // JQColumn annotation parameters
        AnnotationBuilder ap = new AnnotationBuilder();
        // JQColumn.name
        if (!col.name.equalsIgnoreCase(column)) {
            ap.addParameter("name", col.name);
        }
        // composite primary keys are annotated on the table
        if (col.isPrimaryKey && primaryKeys.size() == 1) {
            ap.addParameter("primaryKey=true");
        }
        // JQColumn.maxLength
        if ((clazz == String.class) && (col.size > 0) && (col.size < Integer.MAX_VALUE)) {
            ap.addParameter("maxLength", col.size);
            // JQColumn.trimStrings
            if (trimStrings) {
                ap.addParameter("trimString=true");
            }
        } else {
            // JQColumn.AutoIncrement
            if (col.isAutoIncrement) {
                ap.addParameter("autoIncrement=true");
            }
        }
        // JQColumn.allowNull
        if (!col.allowNull) {
            ap.addParameter("allowNull=false");
        }
        // JQColumn.defaultValue
        if (!StringUtils.isNullOrEmpty(col.defaultValue)) {
            ap.addParameter("defaultValue=\"" + col.defaultValue + "\"");
        }
        // add leading and trailing ()
        if (ap.length() > 0) {
            AnnotationBuilder b = new AnnotationBuilder();
            b.append('(').append(ap.toString()).append(')');
            ap = b;
        }
        sb.append(ap.toString());
    }
    sb.append(EOL);
    // variable declaration
    sb.append("\t" + "public ");
    sb.append(clazz.getSimpleName());
    sb.append(' ');
    sb.append(column);
    sb.append(';');
    sb.append(EOL).append(EOL);
    return sb;
}
Also used : StatementBuilder(org.h2.util.StatementBuilder) JQColumn(org.h2.jaqu.Table.JQColumn)

Aggregations

Value (org.h2.value.Value)5 IOException (java.io.IOException)2 SQLException (java.sql.SQLException)2 Sequence (org.h2.schema.Sequence)2 ValueString (org.h2.value.ValueString)2 JTAEnvironmentBean (com.arjuna.ats.jta.common.JTAEnvironmentBean)1 MysqlConnectionPoolDataSource (com.mysql.jdbc.jdbc2.optional.MysqlConnectionPoolDataSource)1 MysqlXADataSource (com.mysql.jdbc.jdbc2.optional.MysqlXADataSource)1 BufferedOutputStream (java.io.BufferedOutputStream)1 FileOutputStream (java.io.FileOutputStream)1 InputStream (java.io.InputStream)1 InputStreamReader (java.io.InputStreamReader)1 PipedInputStream (java.io.PipedInputStream)1 PipedOutputStream (java.io.PipedOutputStream)1 Reader (java.io.Reader)1 Connection (java.sql.Connection)1 ResultSet (java.sql.ResultSet)1 Date (java.util.Date)1 PatternSyntaxException (java.util.regex.PatternSyntaxException)1 ConnectionPoolDataSource (javax.sql.ConnectionPoolDataSource)1