Search in sources :

Example 1 with Param

use of org.jooq.Param in project keywhiz by square.

the class ClientDAO method sawClient.

public void sawClient(Client client) {
    Instant now = Instant.now();
    Instant lastSeen = Optional.ofNullable(client.getLastSeen()).map(ls -> Instant.ofEpochSecond(ls.toEpochSecond())).orElse(null);
    // this way we can have less granularity on lastSeen and save db writes
    if (lastSeen == null || now.isAfter(lastSeen.plus(lastSeenThreshold, SECONDS))) {
        dslContext.transaction(configuration -> {
            Param<Long> val = DSL.val(now.getEpochSecond(), CLIENTS.LASTSEEN);
            DSL.using(configuration).update(CLIENTS).set(CLIENTS.LASTSEEN, DSL.when(CLIENTS.LASTSEEN.isNull(), val).otherwise(DSL.greatest(CLIENTS.LASTSEEN, val))).where(CLIENTS.ID.eq(client.getId())).execute();
        });
    }
}
Also used : SECONDS(java.time.temporal.ChronoUnit.SECONDS) MEMBERSHIPS(keywhiz.jooq.tables.Memberships.MEMBERSHIPS) ImmutableSet(com.google.common.collect.ImmutableSet) DSL(org.jooq.impl.DSL) ClientsRecord(keywhiz.jooq.tables.records.ClientsRecord) ApiDate(keywhiz.api.ApiDate) Readonly(keywhiz.service.config.Readonly) Preconditions.checkNotNull(com.google.common.base.Preconditions.checkNotNull) Instant(java.time.Instant) Inject(javax.inject.Inject) Param(org.jooq.Param) Configuration(org.jooq.Configuration) List(java.util.List) CLIENTS(keywhiz.jooq.tables.Clients.CLIENTS) OffsetDateTime(java.time.OffsetDateTime) ChronoUnit(java.time.temporal.ChronoUnit) Optional(java.util.Optional) DSLContext(org.jooq.DSLContext) Client(keywhiz.api.model.Client) Instant(java.time.Instant)

Example 2 with Param

use of org.jooq.Param in project jOOQ by jOOQ.

the class QuantifiedComparisonCondition method accept0.

@SuppressWarnings({ "unchecked" })
private final void accept0(Context<?> ctx) {
    boolean quantifiedArray = query.array instanceof Param<?>;
    boolean emulateOperator;
    switch(comparator) {
        case LIKE:
        case NOT_LIKE:
        case LIKE_IGNORE_CASE:
        case NOT_LIKE_IGNORE_CASE:
            emulateOperator = escape != null || NO_SUPPORT_QUANTIFIED_LIKE.contains(ctx.dialect());
            break;
        case SIMILAR_TO:
        case NOT_SIMILAR_TO:
            emulateOperator = escape != null || NO_SUPPORT_QUANTIFIED_SIMILAR_TO.contains(ctx.dialect());
            break;
        default:
            emulateOperator = false;
            break;
    }
    // arrays, such as x = any(?::int[]) in PostgreSQL
    if (quantifiedArray && SUPPORTS_QUANTIFIED_ARRAYS.contains(ctx.dialect()) && !emulateOperator) {
        accept1(ctx);
    } else if (query.values != null || quantifiedArray) {
        ctx.visit(DSL.condition(query.quantifier == Quantifier.ALL ? Operator.AND : Operator.OR, query.values != null ? map(query.values, v -> comparisonCondition(comparator, (Field<String>) v)) : map(((Param<? extends Object[]>) query.array).getValue(), v -> v instanceof Field ? comparisonCondition(comparator, (Field<String>) v) : comparisonCondition(comparator, v))));
    } else if ((query.array != null || query.query != null) && emulateOperator) {
        Field<String> pattern = DSL.field(name("pattern"), VARCHAR);
        Condition cond;
        Field<Boolean> lhs;
        switch(comparator) {
            case NOT_LIKE:
            case NOT_SIMILAR_TO:
            case NOT_LIKE_IGNORE_CASE:
                cond = comparisonCondition(inverse(comparator), pattern);
                lhs = inline(false);
                break;
            case LIKE:
            case SIMILAR_TO:
            case LIKE_IGNORE_CASE:
                cond = comparisonCondition(comparator, pattern);
                lhs = inline(true);
                break;
            default:
                throw new IllegalStateException();
        }
        Table<?> t = query.array != null ? new ArrayTable(query.array).asTable("t", "pattern") : new AliasedSelect<>(query.query, true, true, name("pattern")).as("t");
        Select<Record1<Boolean>> select = select(DSL.field(cond)).from(t);
        ctx.visit(lhs.eq(query.quantifier.apply(select)));
    } else {
        accept1(ctx);
    }
}
Also used : Condition(org.jooq.Condition) Field(org.jooq.Field) Param(org.jooq.Param) Record1(org.jooq.Record1)

Example 3 with Param

use of org.jooq.Param in project jOOQ by jOOQ.

the class ParsingConnection method translate.

static final Rendered translate(Configuration configuration, String sql, Param<?>... bindValues) {
    log.debug("Translating from", sql);
    Rendered result = null;
    Supplier<CacheValue> miss = () -> {
        log.debug("Translation cache miss", sql);
        return new CacheValue(configuration, sql, bindValues);
    };
    Settings settings = configuration.settings();
    if (CACHE_PARSING_CONNECTION.category.predicate.test(settings) && bindValues.length > 0) {
        switch(getParamType(settings)) {
            case INLINED:
            case NAMED_OR_INLINED:
                result = miss.get().rendered(bindValues);
                break;
        }
    }
    if (result == null)
        result = Cache.run(configuration, miss, CACHE_PARSING_CONNECTION, () -> Cache.key(sql, map(nonNull(bindValues), f -> f.getDataType()))).rendered(bindValues);
    log.debug("Translating to", result.sql);
    return result;
}
Also used : DataAccessException(org.jooq.exception.DataAccessException) DetachedException(org.jooq.exception.DetachedException) Tools.map(org.jooq.impl.Tools.map) JooqLogger(org.jooq.tools.JooqLogger) Collections.emptyList(java.util.Collections.emptyList) Settings(org.jooq.conf.Settings) HashMap(java.util.HashMap) PreparedStatement(java.sql.PreparedStatement) Supplier(java.util.function.Supplier) ArrayList(java.util.ArrayList) Param(org.jooq.Param) Configuration(org.jooq.Configuration) SQLException(java.sql.SQLException) List(java.util.List) SettingsTools.getParamType(org.jooq.conf.SettingsTools.getParamType) EMPTY_PARAM(org.jooq.impl.Tools.EMPTY_PARAM) Map(java.util.Map) Rendered(org.jooq.impl.DefaultRenderContext.Rendered) Statement(java.sql.Statement) CallableStatement(java.sql.CallableStatement) DSLContext(org.jooq.DSLContext) DefaultConnection(org.jooq.tools.jdbc.DefaultConnection) CACHE_PARSING_CONNECTION(org.jooq.impl.CacheType.CACHE_PARSING_CONNECTION) Rendered(org.jooq.impl.DefaultRenderContext.Rendered) Settings(org.jooq.conf.Settings)

Example 4 with Param

use of org.jooq.Param in project jOOQ by jOOQ.

the class AbstractResult method format0.

/**
 * @param value The value to be formatted
 * @param visual Whether the formatted output is to be consumed visually
 *            (HTML, TEXT) or by a machine (CSV, JSON, XML)
 */
private static final String format0(Object value, boolean changed, boolean visual) {
    // [#2741] TODO: This logic will be externalised in new SPI
    String formatted = changed && visual ? "*" : "";
    if (value == null) {
        formatted += visual ? "{null}" : null;
    } else if (value.getClass() == byte[].class) {
        formatted += DatatypeConverter.printBase64Binary((byte[]) value);
    } else if (value.getClass().isArray()) {
        // [#6545] Nested arrays are handled recursively
        formatted += Arrays.stream((Object[]) value).map(f -> format0(f, false, visual)).collect(joining(", ", "[", "]"));
    } else if (value instanceof EnumType) {
        EnumType e = (EnumType) value;
        formatted += e.getLiteral();
    } else if (value instanceof List) {
        List<?> l = (List<?>) value;
        formatted += l.stream().map(f -> format0(f, false, visual)).collect(joining(", ", "[", "]"));
    } else if (value instanceof Record) {
        Record r = (Record) value;
        formatted += Arrays.stream(r.intoArray()).map(f -> format0(f, false, visual)).collect(joining(", ", "(", ")"));
    } else // [#6080] Support formatting of nested ROWs
    if (value instanceof Param) {
        formatted += format0(((Param<?>) value).getValue(), false, visual);
    } else // [#5238] Oracle DATE is really a TIMESTAMP(0)...
    if (value instanceof Date) {
        Date d = (Date) value;
        String date = value.toString();
        if (Date.valueOf(date).equals(value))
            formatted += date;
        else
            formatted += new Timestamp(d.getTime());
    } else {
        formatted += value.toString();
    }
    return formatted;
}
Also used : Arrays(java.util.Arrays) Row(org.jooq.Row) Display(org.jooq.ChartFormat.Display) Table(org.jooq.Table) DatatypeConverter(jakarta.xml.bind.DatatypeConverter) VALUE_ELEMENTS_WITH_FIELD_ATTRIBUTE(org.jooq.XMLFormat.RecordFormat.VALUE_ELEMENTS_WITH_FIELD_ATTRIBUTE) IOException(org.jooq.exception.IOException) Document(org.w3c.dom.Document) StringUtils.leftPad(org.jooq.tools.StringUtils.leftPad) DSLContext(org.jooq.DSLContext) AttributesImpl(org.xml.sax.helpers.AttributesImpl) StringUtils.rightPad(org.jooq.tools.StringUtils.rightPad) DSL.name(org.jooq.impl.DSL.name) Timestamp(java.sql.Timestamp) SettingsTools.renderLocale(org.jooq.conf.SettingsTools.renderLocale) Constants(org.jooq.Constants) Field(org.jooq.Field) TableRecord(org.jooq.TableRecord) Math.min(java.lang.Math.min) ChartFormat(org.jooq.ChartFormat) Result(org.jooq.Result) Cursor(org.jooq.Cursor) Collectors.joining(java.util.stream.Collectors.joining) DocumentFragment(org.w3c.dom.DocumentFragment) List(java.util.List) TableField(org.jooq.TableField) COLUMN_NAME_ELEMENTS(org.jooq.XMLFormat.RecordFormat.COLUMN_NAME_ELEMENTS) SAXException(org.xml.sax.SAXException) Writer(java.io.Writer) Math.max(java.lang.Math.max) DocumentBuilderFactory(javax.xml.parsers.DocumentBuilderFactory) JSONValue(org.jooq.tools.json.JSONValue) XML(org.jooq.XML) EnumType(org.jooq.EnumType) Deque(java.util.Deque) FormattingProvider(org.jooq.FormattingProvider) ArrayList(java.util.ArrayList) JSONFormat(org.jooq.JSONFormat) DSL.insertInto(org.jooq.impl.DSL.insertInto) Schema(org.jooq.Schema) Attributes(org.xml.sax.Attributes) CSVFormat(org.jooq.CSVFormat) ContentHandler(org.xml.sax.ContentHandler) Record(org.jooq.Record) InputSource(org.xml.sax.InputSource) XMLFormat(org.jooq.XMLFormat) NodeList(org.w3c.dom.NodeList) Iterator(java.util.Iterator) JSON(org.jooq.JSON) TXTFormat(org.jooq.TXTFormat) Formattable(org.jooq.Formattable) StringUtils(org.jooq.tools.StringUtils) Date(java.sql.Date) Param(org.jooq.Param) DefaultHandler(org.xml.sax.helpers.DefaultHandler) Configuration(org.jooq.Configuration) StringUtils.abbreviate(org.jooq.tools.StringUtils.abbreviate) Element(org.w3c.dom.Element) StringReader(java.io.StringReader) TreeMap(java.util.TreeMap) ParserConfigurationException(javax.xml.parsers.ParserConfigurationException) DocumentBuilder(javax.xml.parsers.DocumentBuilder) JSONB(org.jooq.JSONB) ArrayDeque(java.util.ArrayDeque) DSL.table(org.jooq.impl.DSL.table) Collections(java.util.Collections) EnumType(org.jooq.EnumType) Param(org.jooq.Param) List(java.util.List) ArrayList(java.util.ArrayList) NodeList(org.w3c.dom.NodeList) TableRecord(org.jooq.TableRecord) Record(org.jooq.Record) Timestamp(java.sql.Timestamp) Date(java.sql.Date)

Example 5 with Param

use of org.jooq.Param in project jOOQ by jOOQ.

the class DefaultRenderContext method scopeEnd0.

@Override
void scopeEnd0() {
    ScopeMarker[] markers = ScopeMarker.values();
    ScopeStackElement[] beforeFirst = new ScopeStackElement[markers.length];
    ScopeStackElement[] afterLast = new ScopeStackElement[markers.length];
    ScopeContent[] content = new ScopeContent[markers.length];
    for (ScopeMarker marker : markers) {
        if (!marker.topLevelOnly || subqueryLevel() == 0) {
            int i = marker.ordinal();
            ScopeContent o = content[i] = (ScopeContent) data(marker.key);
            if (o != null && !o.isEmpty()) {
                beforeFirst[i] = scopeStack.get(marker.beforeFirst);
                afterLast[i] = scopeStack.get(marker.afterLast);
            }
        }
    }
    outer: for (ScopeStackElement e1 : scopeStack.iterable(e -> e.scopeLevel == scopeStack.scopeLevel())) {
        String replacedSQL = null;
        QueryPartList<Param<?>> insertedBindValues = null;
        if (e1.positions == null) {
            continue outer;
        } else // TODO: subqueryLevel() is lower than scopeLevel if we use implicit join in procedural logic
        if (e1.joinNode != null && !e1.joinNode.children.isEmpty()) {
            replacedSQL = configuration.dsl().renderContext().declareTables(true).sql('(').formatIndentStart(e1.indent).formatIndentStart().formatNewLine().visit(e1.joinNode.joinTree()).formatNewLine().sql(')').render();
        } else {
            elementLoop: for (int i = 0; i < beforeFirst.length; i++) {
                ScopeStackElement e = beforeFirst[i];
                ScopeContent c = content[i];
                if (e1 == e && c != null) {
                    DefaultRenderContext ctx = new DefaultRenderContext(this, false);
                    markers[i].renderer.render((DefaultRenderContext) ctx.formatIndentStart(e.indent), e, afterLast[i], c);
                    replacedSQL = ctx.render();
                    insertedBindValues = ctx.bindValues();
                    break elementLoop;
                }
            }
        }
        if (replacedSQL != null) {
            sql.replace(e1.positions[0], e1.positions[1], replacedSQL);
            int shift = replacedSQL.length() - (e1.positions[1] - e1.positions[0]);
            inner: for (ScopeStackElement e2 : scopeStack) {
                if (e2.positions == null)
                    continue inner;
                if (e2.positions[0] > e1.positions[0]) {
                    e2.positions[0] = e2.positions[0] + shift;
                    e2.positions[1] = e2.positions[1] + shift;
                }
            }
            if (insertedBindValues != null) {
                bindValues.addAll(e1.bindIndex - 1, insertedBindValues);
                inner: for (ScopeStackElement e2 : scopeStack) {
                    if (e2.positions == null)
                        continue inner;
                    if (e2.bindIndex > e1.bindIndex)
                        e2.bindIndex = e2.bindIndex + insertedBindValues.size();
                }
            }
        }
    }
}
Also used : QUOTE_START_DELIMITER(org.jooq.impl.Identifiers.QUOTE_START_DELIMITER) Arrays(java.util.Arrays) RenderKeywordCase(org.jooq.conf.RenderKeywordCase) Table(org.jooq.Table) QUOTES(org.jooq.impl.Identifiers.QUOTES) ForeignKey(org.jooq.ForeignKey) INLINED(org.jooq.conf.ParamType.INLINED) Deque(java.util.Deque) QUOTE_END_DELIMITER(org.jooq.impl.Identifiers.QUOTE_END_DELIMITER) ArrayList(java.util.ArrayList) BindContext(org.jooq.BindContext) HashSet(java.util.HashSet) RenderContext(org.jooq.RenderContext) DATA_COUNT_BIND_VALUES(org.jooq.impl.Tools.BooleanDataKey.DATA_COUNT_BIND_VALUES) SQLITE(org.jooq.SQLDialect.SQLITE) DATA_PREPEND_SQL(org.jooq.impl.Tools.DataKey.DATA_PREPEND_SQL) DATA_APPEND_SQL(org.jooq.impl.Tools.DataKey.DATA_APPEND_SQL) RenderNameCase(org.jooq.conf.RenderNameCase) SQLDialect(org.jooq.SQLDialect) QUOTE_END_DELIMITER_ESCAPED(org.jooq.impl.Identifiers.QUOTE_END_DELIMITER_ESCAPED) Select(org.jooq.Select) ControlFlowSignal(org.jooq.exception.ControlFlowSignal) DataAccessException(org.jooq.exception.DataAccessException) QueryPartInternal(org.jooq.QueryPartInternal) JooqLogger(org.jooq.tools.JooqLogger) SettingsTools(org.jooq.conf.SettingsTools) SettingsTools.renderLocale(org.jooq.conf.SettingsTools.renderLocale) Set(java.util.Set) Constants(org.jooq.Constants) Settings(org.jooq.conf.Settings) Field(org.jooq.Field) StringUtils(org.jooq.tools.StringUtils) QueryPart(org.jooq.QueryPart) ScopeContent(org.jooq.impl.ScopeMarker.ScopeContent) Param(org.jooq.Param) RenderQuotedNames(org.jooq.conf.RenderQuotedNames) Configuration(org.jooq.Configuration) List(java.util.List) Pattern(java.util.regex.Pattern) RenderFormatting(org.jooq.conf.RenderFormatting) ArrayDeque(java.util.ArrayDeque) Query(org.jooq.Query) TRUE(java.lang.Boolean.TRUE) ScopeContent(org.jooq.impl.ScopeMarker.ScopeContent)

Aggregations

Param (org.jooq.Param)7 List (java.util.List)5 Configuration (org.jooq.Configuration)5 DSLContext (org.jooq.DSLContext)4 ArrayList (java.util.ArrayList)3 Field (org.jooq.Field)3 Preconditions.checkNotNull (com.google.common.base.Preconditions.checkNotNull)2 ImmutableSet (com.google.common.collect.ImmutableSet)2 SQLException (java.sql.SQLException)2 Instant (java.time.Instant)2 OffsetDateTime (java.time.OffsetDateTime)2 ArrayDeque (java.util.ArrayDeque)2 Arrays (java.util.Arrays)2 Deque (java.util.Deque)2 Constants (org.jooq.Constants)2 Table (org.jooq.Table)2 Settings (org.jooq.conf.Settings)2 SettingsTools.renderLocale (org.jooq.conf.SettingsTools.renderLocale)2 DataAccessException (org.jooq.exception.DataAccessException)2 JooqLogger (org.jooq.tools.JooqLogger)2