Search in sources :

Example 6 with Configuration

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

the class MockResultSetMetaData method getSchemaName.

@Override
public String getSchemaName(int column) throws SQLException {
    rs.checkNotClosed();
    Field<?> field = rs.result.field(column - 1);
    if (field instanceof TableField) {
        Table<?> table = ((TableField<?, ?>) field).getTable();
        if (table != null) {
            Schema schema = table.getSchema();
            if (schema != null) {
                Configuration configuration = ((AttachableInternal) rs.result).configuration();
                Schema mapped = null;
                if (configuration != null) {
                    mapped = DSL.using(configuration).map(schema);
                }
                if (mapped != null) {
                    return mapped.getName();
                } else {
                    return schema.getName();
                }
            }
        }
    }
    // By default, no schema is available
    return "";
}
Also used : Configuration(org.jooq.Configuration) Schema(org.jooq.Schema) TableField(org.jooq.TableField) AttachableInternal(org.jooq.AttachableInternal)

Example 7 with Configuration

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

the class JavaGenerator method generateDao.

protected void generateDao(TableDefinition table, JavaWriter out) {
    UniqueKeyDefinition key = table.getPrimaryKey();
    if (key == null) {
        log.info("Skipping DAO generation", out.file().getName());
        return;
    }
    final String className = getStrategy().getJavaClassName(table, Mode.DAO);
    final List<String> interfaces = out.ref(getStrategy().getJavaClassImplements(table, Mode.DAO));
    final String tableRecord = out.ref(getStrategy().getFullJavaClassName(table, Mode.RECORD));
    final String daoImpl = out.ref(DAOImpl.class);
    final String tableIdentifier = out.ref(getStrategy().getFullJavaIdentifier(table), 2);
    String tType = (scala ? "Unit" : "Void");
    String pType = out.ref(getStrategy().getFullJavaClassName(table, Mode.POJO));
    List<ColumnDefinition> keyColumns = key.getKeyColumns();
    if (keyColumns.size() == 1) {
        tType = getJavaType(keyColumns.get(0).getType());
    } else if (keyColumns.size() <= Constants.MAX_ROW_DEGREE) {
        String generics = "";
        String separator = "";
        for (ColumnDefinition column : keyColumns) {
            generics += separator + out.ref(getJavaType(column.getType()));
            separator = ", ";
        }
        if (scala)
            tType = Record.class.getName() + keyColumns.size() + "[" + generics + "]";
        else
            tType = Record.class.getName() + keyColumns.size() + "<" + generics + ">";
    } else {
        tType = Record.class.getName();
    }
    tType = out.ref(tType);
    printPackage(out, table, Mode.DAO);
    generateDaoClassJavadoc(table, out);
    printClassAnnotations(out, table.getSchema());
    if (generateSpringAnnotations())
        out.println("@%s", out.ref("org.springframework.stereotype.Repository"));
    if (scala)
        out.println("class %s(configuration : %s) extends %s[%s, %s, %s](%s, classOf[%s], configuration)[[before= with ][separator= with ][%s]] {", className, Configuration.class, daoImpl, tableRecord, pType, tType, tableIdentifier, pType, interfaces);
    else
        out.println("public class %s extends %s<%s, %s, %s>[[before= implements ][%s]] {", className, daoImpl, tableRecord, pType, tType, interfaces);
    // Default constructor
    // -------------------
    out.tab(1).javadoc("Create a new %s without any configuration", className);
    if (scala) {
        out.tab(1).println("def this() = {");
        out.tab(2).println("this(null)");
        out.tab(1).println("}");
    } else {
        out.tab(1).println("public %s() {", className);
        out.tab(2).println("super(%s, %s.class);", tableIdentifier, pType);
        out.tab(1).println("}");
    }
    if (scala) {
    } else {
        out.tab(1).javadoc("Create a new %s with an attached configuration", className);
        if (generateSpringAnnotations())
            out.tab(1).println("@%s", out.ref("org.springframework.beans.factory.annotation.Autowired"));
        out.tab(1).println("public %s(%s configuration) {", className, Configuration.class);
        out.tab(2).println("super(%s, %s.class, configuration);", tableIdentifier, pType);
        out.tab(1).println("}");
    }
    // -------------------------------
    if (scala) {
        out.println();
        out.tab(1).println("override protected def getId(o : %s) : %s = {", pType, tType);
    } else {
        out.tab(1).overrideInherit();
        out.tab(1).println("protected %s getId(%s object) {", tType, pType);
    }
    if (keyColumns.size() == 1) {
        if (scala)
            out.tab(2).println("o.%s", getStrategy().getJavaGetterName(keyColumns.get(0), Mode.POJO));
        else
            out.tab(2).println("return object.%s();", getStrategy().getJavaGetterName(keyColumns.get(0), Mode.POJO));
    } else // [#2574] This should be replaced by a call to a method on the target table's Key type
    {
        String params = "";
        String separator = "";
        for (ColumnDefinition column : keyColumns) {
            if (scala)
                params += separator + "o." + getStrategy().getJavaGetterName(column, Mode.POJO);
            else
                params += separator + "object." + getStrategy().getJavaGetterName(column, Mode.POJO) + "()";
            separator = ", ";
        }
        if (scala)
            out.tab(2).println("compositeKeyRecord(%s)", params);
        else
            out.tab(2).println("return compositeKeyRecord(%s);", params);
    }
    out.tab(1).println("}");
    for (ColumnDefinition column : table.getColumns()) {
        final String colName = column.getOutputName();
        final String colClass = getStrategy().getJavaClassName(column);
        final String colType = out.ref(getJavaType(column.getType()));
        final String colIdentifier = out.ref(getStrategy().getFullJavaIdentifier(column), colRefSegments(column));
        // fetchBy[Column]([T]...)
        // -----------------------
        out.tab(1).javadoc("Fetch records that have <code>%s IN (values)</code>", colName);
        if (scala) {
            out.tab(1).println("def fetchBy%s(values : %s*) : %s[%s] = {", colClass, colType, List.class, pType);
            out.tab(2).println("fetch(%s, values:_*)", colIdentifier);
            out.tab(1).println("}");
        } else {
            out.tab(1).println("public %s<%s> fetchBy%s(%s... values) {", List.class, pType, colClass, colType);
            out.tab(2).println("return fetch(%s, values);", colIdentifier);
            out.tab(1).println("}");
        }
        // -----------------------
        ukLoop: for (UniqueKeyDefinition uk : column.getUniqueKeys()) {
            // If column is part of a single-column unique key...
            if (uk.getKeyColumns().size() == 1 && uk.getKeyColumns().get(0).equals(column)) {
                out.tab(1).javadoc("Fetch a unique record that has <code>%s = value</code>", colName);
                if (scala) {
                    out.tab(1).println("def fetchOneBy%s(value : %s) : %s = {", colClass, colType, pType);
                    out.tab(2).println("fetchOne(%s, value)", colIdentifier);
                    out.tab(1).println("}");
                } else {
                    out.tab(1).println("public %s fetchOneBy%s(%s value) {", pType, colClass, colType);
                    out.tab(2).println("return fetchOne(%s, value);", colIdentifier);
                    out.tab(1).println("}");
                }
                break ukLoop;
            }
        }
    }
    generateDaoClassFooter(table, out);
    out.println("}");
}
Also used : Configuration(org.jooq.Configuration) Record(org.jooq.Record) StringUtils.defaultString(org.jooq.tools.StringUtils.defaultString)

Example 8 with Configuration

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

the class SakilaReportService method initDB.

private static void initDB() throws Exception {
    final Properties properties = new Properties();
    properties.load(SakilaReportService.class.getResourceAsStream("/config.properties"));
    Class.forName(properties.getProperty("db.driver"));
    HikariDataSource ds = new HikariDataSource();
    ds.setJdbcUrl(properties.getProperty("db.url"));
    ds.setUsername(properties.getProperty("db.username"));
    ds.setPassword(properties.getProperty("db.password"));
    // Some nice debug logging of formatted queries and the first 5 rows in each result set.
    dsl = DSL.using(new DefaultConfiguration().set(ds).set(DefaultExecuteListenerProvider.providers(new DefaultExecuteListener() {

        @Override
        public void executeEnd(ExecuteContext ctx) {
            Configuration config = ctx.configuration().derive();
            config.settings().setRenderFormatted(true);
            log.info("\n" + DSL.using(config).renderInlined(ctx.query()));
        }

        @Override
        public void fetchEnd(ExecuteContext ctx) {
            log.info("\n" + ctx.result().format(5));
        }
    })));
}
Also used : DefaultExecuteListener(org.jooq.impl.DefaultExecuteListener) HikariDataSource(com.zaxxer.hikari.HikariDataSource) DefaultConfiguration(org.jooq.impl.DefaultConfiguration) Configuration(org.jooq.Configuration) ExecuteContext(org.jooq.ExecuteContext) DefaultConfiguration(org.jooq.impl.DefaultConfiguration) Properties(java.util.Properties)

Example 9 with Configuration

use of org.jooq.Configuration 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 10 with Configuration

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

the class JavaGenerator method printConvenienceMethodFunction.

protected void printConvenienceMethodFunction(JavaWriter out, RoutineDefinition function, boolean instance) {
    // [#281] - Java can't handle more than 255 method parameters
    if (function.getInParameters().size() > 254) {
        log.warn("Too many parameters", "Function " + function + " has more than 254 in parameters. Skipping generation of convenience method.");
        return;
    }
    final String className = out.ref(getStrategy().getFullJavaClassName(function));
    final String functionName = function.getQualifiedOutputName();
    final String functionType = out.ref(getJavaType(function.getReturnType()));
    final String methodName = getStrategy().getJavaMethodName(function, Mode.DEFAULT);
    // [#3456] Local variables should not collide with actual function arguments
    final String configurationArgument = disambiguateJavaMemberName(function.getInParameters(), "configuration");
    final String localVar = disambiguateJavaMemberName(function.getInParameters(), "f");
    out.tab(1).javadoc("Call <code>%s</code>", functionName);
    if (scala)
        out.tab(1).print("def %s(", methodName);
    else
        out.tab(1).print("public %s%s %s(", !instance ? "static " : "", functionType, methodName);
    String glue = "";
    if (!instance) {
        if (scala)
            out.print("%s : %s", configurationArgument, Configuration.class);
        else
            out.print("%s %s", Configuration.class, configurationArgument);
        glue = ", ";
    }
    for (ParameterDefinition parameter : function.getInParameters()) {
        // Skip SELF parameter
        if (instance && parameter.equals(function.getInParameters().get(0))) {
            continue;
        }
        final String paramType = refNumberType(out, parameter.getType());
        final String paramMember = getStrategy().getJavaMemberName(parameter);
        if (scala)
            out.print("%s%s : %s", glue, paramMember, paramType);
        else
            out.print("%s%s %s", glue, paramType, paramMember);
        glue = ", ";
    }
    if (scala) {
        out.println(") : %s = {", functionType);
        out.tab(2).println("val %s = new %s()", localVar, className);
    } else {
        out.println(") {");
        out.tab(2).println("%s %s = new %s();", className, localVar, className);
    }
    for (ParameterDefinition parameter : function.getInParameters()) {
        final String paramSetter = getStrategy().getJavaSetterName(parameter, Mode.DEFAULT);
        final String paramMember = (instance && parameter.equals(function.getInParameters().get(0))) ? "this" : getStrategy().getJavaMemberName(parameter);
        if (scala)
            out.tab(2).println("%s.%s(%s)", localVar, paramSetter, paramMember);
        else
            out.tab(2).println("%s.%s(%s);", localVar, paramSetter, paramMember);
    }
    out.println();
    if (scala)
        out.tab(2).println("%s.execute(%s)", localVar, instance ? "configuration()" : configurationArgument);
    else
        out.tab(2).println("%s.execute(%s);", localVar, instance ? "configuration()" : configurationArgument);
    if (scala)
        out.tab(2).println("%s.getReturnValue", localVar);
    else
        out.tab(2).println("return %s.getReturnValue();", localVar);
    out.tab(1).println("}");
}
Also used : Configuration(org.jooq.Configuration) StringUtils.defaultString(org.jooq.tools.StringUtils.defaultString)

Aggregations

Configuration (org.jooq.Configuration)21 AttachableInternal (org.jooq.AttachableInternal)4 StringUtils.defaultString (org.jooq.tools.StringUtils.defaultString)4 OffsetDateTime (java.time.OffsetDateTime)3 ArrayList (java.util.ArrayList)3 List (java.util.List)3 ExecuteContext (org.jooq.ExecuteContext)3 Query (org.jooq.Query)3 BigDecimal (java.math.BigDecimal)2 BigInteger (java.math.BigInteger)2 Date (java.sql.Date)2 Time (java.sql.Time)2 LocalDate (java.time.LocalDate)2 LocalDateTime (java.time.LocalDateTime)2 LocalTime (java.time.LocalTime)2 OffsetTime (java.time.OffsetTime)2 SQLDialect (org.jooq.SQLDialect)2 DefaultExecuteContext.localConfiguration (org.jooq.impl.DefaultExecuteContext.localConfiguration)2 Preconditions.checkNotNull (com.google.common.base.Preconditions.checkNotNull)1 ImmutableSet (com.google.common.collect.ImmutableSet)1