@Test public void run() throws SQLException { Connection connection = connection(); Tools.title("Distinguishing between static and prepared statements with JDBC"); // 1% of the time try (Statement stmt = connection.createStatement()) { stmt.execute("SELECT * FROM AUTHOR"); } // 99% of the time try (PreparedStatement stmt = connection.prepareStatement("SELECT * FROM AUTHOR")) { stmt.execute(); } Tools.title("Distinguishing between static and prepared statements with jOOQ"); // 1% of the time System.out.println( DSL.using(connection, new Settings().withStatementType(StatementType.STATIC_STATEMENT)) .fetch("SELECT * FROM AUTHOR")); // 99% of the time System.out.println(DSL.using(connection).fetch("SELECT * FROM AUTHOR")); }
@Override public boolean isProjectOwner( long projectId, Long usingAccount, boolean isAdmin, Set<Identity> identities) { if (identities == null) { return false; } if (isAdmin) { return true; } if (usingAccount != null && usingAccount.equals(projectId)) { return false; } Set<ProjectMemberRecord> projectMembers = new HashSet<>(); Condition allMembers = DSL.falseCondition(); for (Identity id : identities) { allMembers = allMembers.or( PROJECT_MEMBER .EXTERNAL_ID .eq(id.getExternalId()) .and(PROJECT_MEMBER.EXTERNAL_ID_TYPE.eq(id.getExternalIdType())) .and(PROJECT_MEMBER.ROLE.eq(ProjectConstants.OWNER)) .and(PROJECT_MEMBER.PROJECT_ID.eq(projectId)) .and(PROJECT_MEMBER.STATE.eq(CommonStatesConstants.ACTIVE)) .and(PROJECT_MEMBER.REMOVED.isNull())); } projectMembers.addAll(create().selectFrom(PROJECT_MEMBER).where(allMembers).fetch()); return !projectMembers.isEmpty(); }
@SuppressFBWarnings("SQL_NONCONSTANT_STRING_PASSED_TO_EXECUTE") public static void execute( Configuration jooqConf, IndexStorage.CollectionSchema colSchema, @Nonnull DatabaseInterface databaseInterface) { ConnectionProvider provider = jooqConf.connectionProvider(); Connection connection = provider.acquire(); Statement st = null; try { st = connection.createStatement(); st.executeUpdate(databaseInterface.dropSchemaStatement(colSchema.getName())); DSLContext dsl = DSL.using(jooqConf); int deleted = dsl.deleteFrom(CollectionsTable.COLLECTIONS) .where(CollectionsTable.COLLECTIONS.NAME.eq(colSchema.getCollection())) .execute(); assert deleted == 1; } catch (SQLException ex) { throw new ToroImplementationException(ex); } finally { AutoCloser.close(st); } }
protected Condition vnetCondition(Long vnetId) { if (vnetId == null) { return DSL.trueCondition(); } return VNET.ID.eq(vnetId); }
@Override public Object map(R record) { AbstractRecord copy = (AbstractRecord) DSL.using(configuration).newRecord(f); for (int i = 0; i < f.length; i++) if (f[i] != null) copy.setValue(i, record.getValue(i)); return d.map(record); }
private static SelectConditionStep<Record1<Integer>> countSensorData(Field<Integer> datasetId) { return DSL.selectCount() .from(SENSORED_DATA) .join(DATA) .on(SENSORED_DATA.DATA.eq(DATA.ID)) // sensored_data -> data .where(DATA.DATASET_ID.eq(datasetId)) .and(isIncludedAndNotHidden(DATA)); }
private static SelectConditionStep<Record1<Integer>> countLayerData(Field<Integer> datasetId) { return DSL.selectCount() .from(LAYER) .join(DATA) .on(LAYER.DATA.eq(DATA.ID)) // layer -> data .where(DATA.DATASET_ID.eq(datasetId)) .and(isIncludedAndNotHidden(DATA)); }
private static SelectConditionStep<Record1<Integer>> countDataOfType( Field<Integer> datasetId, String type) { return DSL.selectCount() .from(DATA) .where(DATA.DATASET_ID.eq(datasetId)) .and(isIncludedAndNotHidden(DATA)) .and(DATA.TYPE.eq(type)); }
@Override final Field<BigDecimal> getFunction0(Configuration configuration) { switch (configuration.dialect().family()) { case ASE: case CUBRID: case HSQLDB: case INGRES: case MARIADB: case MYSQL: case POSTGRES: case SQLSERVER: case SYBASE: return DSL.exp(argument.mul(two())).sub(one()).div(DSL.exp(argument.mul(two())).add(one())); default: return function("tanh", SQLDataType.NUMERIC, argument); } }
/** * returns all the open Calibrations needed from the worker * * @param experimentID the experiment * @param platformID the id of the platform * @param worker the worker * @return a map where the keys are the detailed population the worker may belong to and the * values are the answerOptions */ public Map<CalibrationRecord, Result<CalibrationAnswerOptionRecord>> getCalibrations( int experimentID, String platformID, int worker) { SelectConditionStep<Record1<Integer>> alreadyAnsweredCalibrations = DSL.select(CALIBRATION_ANSWER_OPTION.CALIBRATION) .from(Tables.CALIBRATION_ANSWER_OPTION) .join(Tables.CALIBRATION_RESULT) .onKey() .where(Tables.CALIBRATION_RESULT.WORKER.eq(worker)); Map<CalibrationRecord, Result<Record>> calibrationAndAnswers = create .select(CALIBRATION.fields()) .select(CALIBRATION_ANSWER_OPTION.fields()) .from(Tables.CALIBRATION_ANSWER_OPTION) .join(Tables.CALIBRATION) .onKey() // we want all the calibrations .where( CALIBRATION.ID_CALIBRATION.in( // which belong to the chosen answer-option DSL.select(CALIBRATION_ANSWER_OPTION.CALIBRATION) .from(CALIBRATION_ANSWER_OPTION) .where( CALIBRATION_ANSWER_OPTION.ID_CALIBRATION_ANSWER_OPTION.in( // from the experiment DSL.select(EXPERIMENTS_CALIBRATION.ANSWER) .from(EXPERIMENTS_CALIBRATION) .where( EXPERIMENTS_CALIBRATION.EXPERIMENTS_PLATFORM.eq( // from the platform DSL.select(EXPERIMENTS_PLATFORM.IDEXPERIMENTS_PLATFORMS) .from(EXPERIMENTS_PLATFORM) .where( EXPERIMENTS_PLATFORM.EXPERIMENT.eq( experimentID)) .and( EXPERIMENTS_PLATFORM.PLATFORM.eq( platformID)))))))) .and(Tables.CALIBRATION.ID_CALIBRATION.notIn(alreadyAnsweredCalibrations)) .fetchGroups(Tables.CALIBRATION); return mapMap( calibrationAndAnswers, result -> result.into(Tables.CALIBRATION_ANSWER_OPTION.asTable())); }
@SuppressWarnings("unchecked") @Override final Field<T> getFunction0(Configuration configuration) { // In any dialect, a single argument is always the greatest if (getArguments().length == 1) { return (Field<T>) getArguments()[0]; } switch (configuration.dialect()) { // This implementation has O(2^n) complexity. Better implementations // are very welcome // [#1049] TODO Fix this! case ASE: case DERBY: case SQLSERVER: case SYBASE: { Field<T> first = (Field<T>) getArguments()[0]; Field<T> other = (Field<T>) getArguments()[1]; if (getArguments().length > 2) { Field<?>[] remaining = new Field[getArguments().length - 2]; System.arraycopy(getArguments(), 2, remaining, 0, remaining.length); return DSL.decode() .when(first.greaterThan(other), DSL.greatest(first, remaining)) .otherwise(DSL.greatest(other, remaining)); } else { return DSL.decode().when(first.greaterThan(other), first).otherwise(other); } } case FIREBIRD: return function("maxvalue", getDataType(), getArguments()); case SQLITE: return function("max", getDataType(), getArguments()); default: return function("greatest", getDataType(), getArguments()); } }
/** * returns whether the worker already has submitted the wrong calibrations * * @param experimentID the current experiment * @param platformID the platform the worker is working on * @param worker the worker to check for * @return true if the worker is already belonging to the wrong population, false if not */ public boolean hasSubmittedWrongCalibrations(int experimentID, String platformID, int worker) { SelectConditionStep<Record1<Integer>> getCalibrationForExperiment = DSL.select(CALIBRATION_ANSWER_OPTION.CALIBRATION) .from(CALIBRATION_ANSWER_OPTION) .where( CALIBRATION_ANSWER_OPTION.ID_CALIBRATION_ANSWER_OPTION.eq( EXPERIMENTS_CALIBRATION.ANSWER)); SelectConditionStep<Record1<Integer>> getExperimentPlatformIds = DSL.select(EXPERIMENTS_PLATFORM.IDEXPERIMENTS_PLATFORMS) .from(EXPERIMENTS_PLATFORM) .where(EXPERIMENTS_PLATFORM.EXPERIMENT.eq(experimentID)) .and(EXPERIMENTS_PLATFORM.PLATFORM.eq(platformID)); return create.fetchExists( DSL.select() .from(CALIBRATION_ANSWER_OPTION) .innerJoin(CALIBRATION_RESULT) .onKey() .innerJoin(EXPERIMENTS_CALIBRATION) .on( EXPERIMENTS_CALIBRATION .EXPERIMENTS_PLATFORM .in(getExperimentPlatformIds) .and(CALIBRATION_ANSWER_OPTION.CALIBRATION.eq(getCalibrationForExperiment)) .and( EXPERIMENTS_CALIBRATION .NOT .eq(true) .and( EXPERIMENTS_CALIBRATION.ANSWER.eq( CALIBRATION_ANSWER_OPTION.ID_CALIBRATION_ANSWER_OPTION)) .or( EXPERIMENTS_CALIBRATION .NOT .eq(false) .and( EXPERIMENTS_CALIBRATION.ANSWER.notEqual( CALIBRATION_ANSWER_OPTION .ID_CALIBRATION_ANSWER_OPTION))))) .where(CALIBRATION_RESULT.WORKER.eq(worker))); }
/** {@inheritDoc} */ @Override public org.jooq.Row6< java.lang.Integer, java.lang.String, java.lang.String, java.lang.Byte, java.lang.Short, java.sql.Timestamp> fieldsRow() { return org.jooq.impl.DSL.row(field1(), field2(), field3(), field4(), field5(), field6()); }
private void connect() { try { Class.forName("org.sqlite.JDBC"); conn = DriverManager.getConnection(url); dsl = DSL.using(conn, SQLDialect.SQLITE); } catch (ClassNotFoundException ex) { } catch (SQLException ex) { } }
/** {@inheritDoc} */ @Override public org.jooq.Row6< java.lang.Integer, java.lang.String, java.lang.String, java.lang.Byte, java.lang.Short, java.sql.Timestamp> valuesRow() { return org.jooq.impl.DSL.row(value1(), value2(), value3(), value4(), value5(), value6()); }
@Override public List<Account> getAccessibleProjects( Set<Identity> identities, boolean isAdmin, Long usingAccount) { List<Account> projects = new ArrayList<>(); if (identities == null) { return projects; } if (isAdmin) { projects.addAll( create() .selectFrom(ACCOUNT) .where(ACCOUNT.KIND.eq(ProjectConstants.TYPE).and(ACCOUNT.REMOVED.isNull())) .orderBy(ACCOUNT.ID.asc()) .fetch()); return projects; } if (usingAccount != null) { Account project = getAccountById(usingAccount); if (project != null && project.getKind().equalsIgnoreCase(ProjectConstants.TYPE)) { projects.add(project); return projects; } } // DSL.falseCondition is created so that we can dynamically build a or // Condition without caring what the external Ids are and still make one // Database call. Condition allMembers = DSL.falseCondition(); for (Identity id : identities) { allMembers = allMembers.or( PROJECT_MEMBER .EXTERNAL_ID .eq(id.getExternalId()) .and(PROJECT_MEMBER.EXTERNAL_ID_TYPE.eq(id.getExternalIdType())) .and(PROJECT_MEMBER.REMOVED.isNull()) .and(PROJECT_MEMBER.STATE.eq(CommonStatesConstants.ACTIVE))); } SelectQuery<Record> query = create().selectQuery(); query.addFrom(ACCOUNT); query.addJoin(PROJECT_MEMBER, PROJECT_MEMBER.PROJECT_ID.equal(ACCOUNT.ID)); query.addConditions(allMembers); query.setDistinct(true); projects.addAll(query.fetchInto(ACCOUNT)); Map<Long, Account> returnProjects = new HashMap<>(); for (Account project : projects) { returnProjects.put(project.getId(), project); } projects = new ArrayList<>(); projects.addAll(returnProjects.values()); return projects; }
@SuppressWarnings("unchecked") @Override final Field<T> getFunction0(Configuration configuration) { // In any dialect, a single argument is always the least if (getArguments().length == 1) { return (Field<T>) getArguments()[0]; } switch (configuration.family()) { // This implementation has O(2^n) complexity. Better implementations // are very welcome case DERBY: { Field<T> first = (Field<T>) getArguments()[0]; Field<T> other = (Field<T>) getArguments()[1]; if (getArguments().length > 2) { Field<?>[] remaining = new Field<?>[getArguments().length - 2]; System.arraycopy(getArguments(), 2, remaining, 0, remaining.length); return DSL.when(first.lessThan(other), DSL.least(first, remaining)) .otherwise(DSL.least(other, remaining)); } else { return DSL.when(first.lessThan(other), first).otherwise(other); } } case FIREBIRD: return function("minvalue", getDataType(), getArguments()); case SQLITE: return function("min", getDataType(), getArguments()); default: return function("least", getDataType(), getArguments()); } }
@Override public void deleteChargePoint(int chargeBoxPk) { ctx.transaction( configuration -> { DSLContext ctx = DSL.using(configuration); try { addressRepository.delete(ctx, selectAddressId(chargeBoxPk)); deleteChargePointInternal(ctx, chargeBoxPk); } catch (DataAccessException e) { throw new SteveException("Failed to delete the charge point", e); } }); }
@Override public int addChargePoint(ChargePointForm form) { return ctx.transactionResult( configuration -> { DSLContext ctx = DSL.using(configuration); try { Integer addressId = addressRepository.updateOrInsert(ctx, form.getAddress()); return addChargePointInternal(ctx, form, addressId); } catch (DataAccessException e) { throw new SteveException( "Failed to add the charge point with chargeBoxId '%s'", form.getChargeBoxId(), e); } }); }
public static void main(String[] args) throws IOException, SQLException { ResourceLoader loader = Hsqldb.keggReactionLoader(); loader.addLocation("kegg.reaction", new SystemLocation("/databases/kegg/ligand/reaction")); if (loader.canBackup()) loader.backup(); long t0 = System.nanoTime(); loader.update(); long t1 = System.nanoTime(); System.out.println(TimeUnit.NANOSECONDS.toMillis(t1 - t0) + " ms"); Connection connection = Hsqldb.keggReactionConnection().getConnection(); DSLContext context = DSL.using(connection, HSQLDB); System.out.println(context.select().from(REACTION).fetch()); System.out.println(context.select().from(COMPOUND).fetch()); System.out.println(context.select().from(REACTANT).fetch()); System.out.println(context.select().from(PRODUCT).fetch()); connection.close(); }
@Before public void setUp() { String userName = "******"; String password = "******"; String url = "jdbc:mysql://localhost:3306/library"; // Connection is the only JDBC resource that we need // PreparedStatement and ResultSet are handled by jOOQ, internally try { conn = DriverManager.getConnection(url, userName, password); if (create == null) create = DSL.using(conn, SQLDialect.MYSQL); } // For the sake of this tutorial, let's keep exception handling simple catch (Exception e) { e.printStackTrace(); } }
public List<? extends ProjectMember> getProjectMembersByIdentity( long projectId, Set<Identity> identities) { Condition allMembers = DSL.falseCondition(); for (Identity identity : identities) { allMembers = allMembers.or( PROJECT_MEMBER .EXTERNAL_ID .eq(identity.getExternalId()) .and(PROJECT_MEMBER.EXTERNAL_ID_TYPE.eq(identity.getExternalIdType())) .and(PROJECT_MEMBER.REMOVED.isNull()) .and(PROJECT_MEMBER.STATE.eq(CommonStatesConstants.ACTIVE)) .and(PROJECT_MEMBER.PROJECT_ID.eq(projectId))); } SelectQuery<Record> query = create().selectQuery(); query.addFrom(PROJECT_MEMBER); query.addConditions(allMembers); query.setDistinct(true); return query.fetchInto(PROJECT_MEMBER); }
@Override final Field<T> getFunction0(Configuration configuration) { switch (configuration.family()) { case H2: case HSQLDB: return field("{nvl}({0}, {1})", getDataType(), arg1, arg2); case DERBY: case POSTGRES: return field("{coalesce}({0}, {1})", getDataType(), arg1, arg2); case MARIADB: case MYSQL: case SQLITE: return field("{ifnull}({0}, {1})", getDataType(), arg1, arg2); default: return DSL.when(arg1.isNotNull(), arg1).otherwise(arg2); } }
@Override public List<ConnectorStatus> getChargePointConnectorStatus() { // Prepare for the inner select of the second join Field<Integer> t1Pk = CONNECTOR_STATUS.CONNECTOR_PK.as("t1_pk"); Field<DateTime> t1Max = DSL.max(CONNECTOR_STATUS.STATUS_TIMESTAMP).as("t1_max"); TableLike<?> t1 = ctx.select(t1Pk, t1Max) .from(CONNECTOR_STATUS) .groupBy(CONNECTOR_STATUS.CONNECTOR_PK) .asTable("t1"); return ctx.select( CHARGE_BOX.CHARGE_BOX_PK, CONNECTOR.CHARGE_BOX_ID, CONNECTOR.CONNECTOR_ID, CONNECTOR_STATUS.STATUS_TIMESTAMP, CONNECTOR_STATUS.STATUS, CONNECTOR_STATUS.ERROR_CODE) .from(CONNECTOR_STATUS) .join(CONNECTOR) .onKey() .join(CHARGE_BOX) .on(CHARGE_BOX.CHARGE_BOX_ID.eq(CONNECTOR.CHARGE_BOX_ID)) .join(t1) .on(CONNECTOR_STATUS.CONNECTOR_PK.equal(t1.field(t1Pk))) .and(CONNECTOR_STATUS.STATUS_TIMESTAMP.equal(t1.field(t1Max))) .orderBy(CONNECTOR_STATUS.STATUS_TIMESTAMP.desc()) .fetch() .map( r -> ConnectorStatus.builder() .chargeBoxPk(r.value1()) .chargeBoxId(r.value2()) .connectorId(r.value3()) .timeStamp(DateTimeUtils.humanize(r.value4())) .status(r.value5()) .errorCode(r.value6()) .build()); }
@Override final Field<String> getFunction0(Configuration configuration) { switch (configuration.family()) { // This beautiful expression was contributed by "Ludo", here: // http://stackoverflow.com/questions/6576343/how-to-simulate-lpad-rpad-with-sqlite case SQLITE: { return DSL.field( "{0} || substr(" + "replace(" + "replace(" + "substr(" + "quote(" + "zeroblob((({1} - length({0}) - 1 + length({2})) / length({2}) + 1) / 2)" + "), 3" + "), '\''', ''" + "), '0', {2}" + "), 1, ({1} - length({0}))" + ")", String.class, field, length, character); } // According to the Firebird documentation, LPAD outcomes should be // cast to truncate large results... case FIREBIRD: { return field( "cast(rpad({0}, {1}, {2}) as varchar(4000))", SQLDataType.VARCHAR, field, length, character); } default: { return function("rpad", SQLDataType.VARCHAR, field, length, character); } } }
/** {@inheritDoc} */ @Override public org.jooq.Row16< java.lang.Integer, java.lang.Integer, java.lang.String, java.lang.String, java.lang.String, java.lang.String, java.lang.String, java.lang.String, java.lang.String, java.lang.String, java.lang.String, java.lang.String, java.lang.String, java.lang.String, java.lang.String, java.sql.Timestamp> valuesRow() { return org.jooq.impl.DSL.row( value1(), value2(), value3(), value4(), value5(), value6(), value7(), value8(), value9(), value10(), value11(), value12(), value13(), value14(), value15(), value16()); }
/** {@inheritDoc} */ @Override public org.jooq.Row16< java.lang.Integer, java.lang.Integer, java.lang.String, java.lang.String, java.lang.String, java.lang.String, java.lang.String, java.lang.String, java.lang.String, java.lang.String, java.lang.String, java.lang.String, java.lang.String, java.lang.String, java.lang.String, java.sql.Timestamp> fieldsRow() { return org.jooq.impl.DSL.row( field1(), field2(), field3(), field4(), field5(), field6(), field7(), field8(), field9(), field10(), field11(), field12(), field13(), field14(), field15(), field16()); }
@Override public DSLContext get() { Configuration configuration = new DefaultConfiguration().set(ultm.getManagedDataSource()).set(SQLDialect.POSTGRES); return DSL.using(configuration); }
@Override protected DSLContext create0() { return DSL.using(getConnection(), SQLDialect.MYSQL); }
/** This class is generated by jOOQ. */ @Generated( value = {"http://www.jooq.org", "jOOQ version:3.8.4"}, comments = "This class is generated by jOOQ") @SuppressWarnings({"all", "unchecked", "rawtypes"}) public class Supplier extends TableImpl<SupplierRecord> { private static final long serialVersionUID = 145075241; /** The reference instance of <code>warehouse.Supplier</code> */ public static final Supplier SUPPLIER = new Supplier(); /** The class holding records for this type */ @Override public Class<SupplierRecord> getRecordType() { return SupplierRecord.class; } /** The column <code>warehouse.Supplier.id</code>. */ public final TableField<SupplierRecord, Long> ID = createField("id", org.jooq.impl.SQLDataType.BIGINT.nullable(false), this, ""); /** The column <code>warehouse.Supplier.code</code>. */ public final TableField<SupplierRecord, String> CODE = createField("code", org.jooq.impl.SQLDataType.VARCHAR.length(255).nullable(false), this, ""); /** The column <code>warehouse.Supplier.name</code>. */ public final TableField<SupplierRecord, String> NAME = createField("name", org.jooq.impl.SQLDataType.VARCHAR.length(255).nullable(false), this, ""); /** The column <code>warehouse.Supplier.dateCreated</code>. */ public final TableField<SupplierRecord, Timestamp> DATECREATED = createField( "dateCreated", org.jooq.impl.SQLDataType.TIMESTAMP .nullable(false) .defaultValue( org.jooq.impl.DSL.inline( "CURRENT_TIMESTAMP", org.jooq.impl.SQLDataType.TIMESTAMP)), this, ""); /** Create a <code>warehouse.Supplier</code> table reference */ public Supplier() { this("Supplier", null); } /** Create an aliased <code>warehouse.Supplier</code> table reference */ public Supplier(String alias) { this(alias, SUPPLIER); } private Supplier(String alias, Table<SupplierRecord> aliased) { this(alias, aliased, null); } private Supplier(String alias, Table<SupplierRecord> aliased, Field<?>[] parameters) { super(alias, null, aliased, parameters, ""); } /** {@inheritDoc} */ @Override public Schema getSchema() { return warehouse.WAREHOUSE; } /** {@inheritDoc} */ @Override public Identity<SupplierRecord, Long> getIdentity() { return Keys.IDENTITY_SUPPLIER; } /** {@inheritDoc} */ @Override public UniqueKey<SupplierRecord> getPrimaryKey() { return Keys.KEY_SUPPLIER_PRIMARY; } /** {@inheritDoc} */ @Override public List<UniqueKey<SupplierRecord>> getKeys() { return Arrays.<UniqueKey<SupplierRecord>>asList( Keys.KEY_SUPPLIER_PRIMARY, Keys.KEY_SUPPLIER_CODE); } /** {@inheritDoc} */ @Override public Supplier as(String alias) { return new Supplier(alias, this); } /** Rename this table */ public Supplier rename(String name) { return new Supplier(name, null); } }