@Override
 public List<NewsSource> getAllNewsSources(int userId) {
   return dsl.select(
           count(SUBSCRIPTIONS.NEWS_SOURCE_ID),
           NEWS_SOURCES.ID,
           NEWS_SOURCES.NAME,
           NEWS_SOURCES.RECIPE_FILE,
           NEWS_SOURCES.DESCRIPTION,
           NEWS_SOURCES.LANGUAGE,
           NEWS_SOURCES.CONTENT_DAYS,
           NEWS_SOURCES.CATEGORY_1)
       .from(
           NEWS_SOURCES
               .leftOuterJoin(SUBSCRIPTIONS)
               .on(
                   NEWS_SOURCES
                       .ID
                       .eq(SUBSCRIPTIONS.NEWS_SOURCE_ID)
                       .and(SUBSCRIPTIONS.USER_ID.eq(userId))))
       .groupBy(NEWS_SOURCES.ID)
       .fetch()
       .map(
           record -> {
             return new NewsSource(
                 record.getValue(NEWS_SOURCES.ID),
                 record.getValue(NEWS_SOURCES.NAME),
                 record.getValue(NEWS_SOURCES.RECIPE_FILE),
                 record.getValue(NEWS_SOURCES.CATEGORY_1),
                 record.getValue(NEWS_SOURCES.LANGUAGE),
                 record.getValue(NEWS_SOURCES.DESCRIPTION),
                 record.getValue(NEWS_SOURCES.CONTENT_DAYS),
                 record.getValue(0, Integer.class) != 0);
           });
 }
 @Override
 public Map<String, Integer> getChargeBoxIdPkPair(List<String> chargeBoxIdList) {
   return ctx.select(CHARGE_BOX.CHARGE_BOX_ID, CHARGE_BOX.CHARGE_BOX_PK)
       .from(CHARGE_BOX)
       .where(CHARGE_BOX.CHARGE_BOX_ID.in(chargeBoxIdList))
       .fetchMap(CHARGE_BOX.CHARGE_BOX_ID, CHARGE_BOX.CHARGE_BOX_PK);
 }
  public String getJsonWebToken(String username) {
    AdminUser a = AdminUser.ADMIN_USER;
    AuthCredential ac = AuthCredential.AUTH_CREDENTIAL;
    Company c = Company.COMPANY;
    Record3<Integer, Integer, String> rs =
        context
            .select(a.ID, c.ID, ac.JWT_TOKEN)
            .from(a)
            .join(c)
            .on(a.COMPANY_ID.equal(c.ID))
            .join(ac)
            .on(a.USERNAME.equal(a.USERNAME))
            .where(a.USERNAME.equal(username))
            .fetchOne();
    if (rs == null) {
      return null;
    }

    Map<String, Object> claims = new HashMap<>();
    claims.put("username", username);
    claims.put("userId", rs.value1());
    claims.put("companyId", rs.value2());
    Map<String, Object> headers = new HashMap<>();
    AuthSigningKeyResolver.KeyDTO key = signingKeyResolver.getRandomKey();
    headers.put("kid", key.getKeyId());
    return Jwts.builder()
        .setSubject(username)
        .setIssuedAt(new Date())
        .setHeader(headers)
        .setClaims(claims)
        .signWith(key.getAlgo(), key.getKey())
        .compact();
  }
 @Override
 public List<Integer> getConnectorIds(String chargeBoxId) {
   return ctx.select(CONNECTOR.CONNECTOR_ID)
       .from(CONNECTOR)
       .where(CONNECTOR.CHARGE_BOX_ID.equal(chargeBoxId))
       .fetch(CONNECTOR.CONNECTOR_ID);
 }
 public List<Customer> findAll() {
   return dslContext
       .select()
       .from(CUSTOMERS)
       .orderBy(CUSTOMERS.FIRST_NAME.asc())
       .fetchInto(Customer.class);
 }
 @Override
 public BookModel selectBook(int id) {
   return create
       .select(
           BOOK.ID_BOOK,
           BOOK.TITLE,
           BOOK.SHORT_DESCRIPTION,
           BOOK.DATE_PUBLISH,
           PostgresDSL.arrayAgg(
                   concat(
                       AUTHOR.ID_AUTHOR,
                       val(","),
                       AUTHOR.FIRST_NAME,
                       val(","),
                       AUTHOR.SECOND_NAME))
               .as("authors"))
       .from(AUTHOR)
       .join(AUTHOR_BOOK)
       .on(AUTHOR_BOOK.ID_AUTHOR.equal(AUTHOR.ID_AUTHOR))
       .join(BOOK)
       .on(BOOK.ID_BOOK.equal(AUTHOR_BOOK.ID_BOOK))
       .where(BOOK.STATUS.equal(true))
       .and(BOOK.ID_BOOK.equal(id))
       .groupBy(BOOK.ID_BOOK)
       .fetchOneInto(BookModel.class);
 }
Beispiel #7
0
  private void testPostgresEnumArrayCRUD0(DSLContext create) throws Exception {
    jOOQAbstractTest.reset = false;

    TArrays a = T_ARRAYS;

    assertEquals(
        4,
        create
            .insertInto(a, a.ID, a.ENUM_ARRAY)
            .values(11, null)
            .values(12, new UCountry[0])
            .values(13, new UCountry[] {null})
            .values(14, new UCountry[] {UCountry.Brazil})
            .execute());

    List<UCountry[]> countries =
        create.select(a.ENUM_ARRAY).from(a).where(a.ID.gt(10)).orderBy(a.ID).fetch(a.ENUM_ARRAY);

    assertNull(countries.get(0));
    assertEquals(0, countries.get(1).length);
    assertEquals(1, countries.get(2).length);
    assertNull(countries.get(2)[0]);
    assertEquals(1, countries.get(3).length);
    assertEquals(UCountry.Brazil, countries.get(3)[0]);
  }
  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();
  }
 @Override
 public List<String> getRecipesForToday() {
   String dayOfWeek = getDayAsRegex();
   return dsl.select(NEWS_SOURCES.RECIPE_FILE)
       .from(NEWS_SOURCES)
       .where(NEWS_SOURCES.CONTENT_DAYS.like(dayOfWeek))
       .fetch()
       .map(x -> x.getValue(0, String.class));
 }
 @Override
 public List<Integer> getActiveTransactionIds(String chargeBoxId) {
   return ctx.select(TRANSACTION.TRANSACTION_PK)
       .from(TRANSACTION)
       .join(CONNECTOR)
       .on(TRANSACTION.CONNECTOR_PK.equal(CONNECTOR.CONNECTOR_PK))
       .and(CONNECTOR.CHARGE_BOX_ID.equal(chargeBoxId))
       .where(TRANSACTION.STOP_TIMESTAMP.isNull())
       .fetch(TRANSACTION.TRANSACTION_PK);
 }
  @Override
  public List<ChargePointSelect> getChargePointSelect(OcppProtocol protocol) {
    final OcppTransport transport = protocol.getTransport();

    return ctx.select(CHARGE_BOX.CHARGE_BOX_ID, CHARGE_BOX.ENDPOINT_ADDRESS)
        .from(CHARGE_BOX)
        .where(CHARGE_BOX.OCPP_PROTOCOL.equal(protocol.getCompositeValue()))
        .and(CHARGE_BOX.ENDPOINT_ADDRESS.isNotNull())
        .fetch()
        .map(r -> new ChargePointSelect(transport, r.value1(), r.value2()));
  }
  @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
 public List<Book> selectBooksByIdAuthor(int idAuthor) {
   return create
       .select()
       .from(BOOK)
       .join(AUTHOR_BOOK)
       .on(BOOK.ID_BOOK.equal(AUTHOR_BOOK.ID_BOOK))
       .join(AUTHOR)
       .on(AUTHOR.ID_AUTHOR.equal(AUTHOR_BOOK.ID_AUTHOR))
       .where(AUTHOR.ID_AUTHOR.equal(idAuthor))
       .and(BOOK.STATUS.equal(true))
       .fetchInto(Book.class);
 }
 @Override
 public List<MailTask> getMailTasksForToday() {
   String dayOfWeek = getDayAsRegex();
   return dsl.select(NEWS_SOURCES.RECIPE_FILE, USERS.KINDLE_EMAIL)
       .from(
           NEWS_SOURCES
               .join(SUBSCRIPTIONS)
               .on(SUBSCRIPTIONS.NEWS_SOURCE_ID.eq(NEWS_SOURCES.ID))
               .join(USERS)
               .on(SUBSCRIPTIONS.USER_ID.eq(USERS.ID)))
       .where(NEWS_SOURCES.CONTENT_DAYS.like(dayOfWeek))
       .fetch()
       .map(
           x ->
               new MailTask(
                   x.getValue(USERS.KINDLE_EMAIL, String.class),
                   x.getValue(NEWS_SOURCES.RECIPE_FILE, String.class)));
 }
 @Override
 public void updateBook(BookModel bookModel) {
   create
       .update(BOOK)
       .set(BOOK.TITLE, bookModel.getTitle())
       .set(BOOK.DATE_PUBLISH, bookModel.getDatePublish())
       .set(BOOK.SHORT_DESCRIPTION, bookModel.getShortDescription())
       .where(BOOK.ID_BOOK.equal(bookModel.getIdBook()))
       .execute();
   List<Integer> existsAuthors =
       create
           .select(AUTHOR_BOOK.ID_AUTHOR)
           .from(AUTHOR_BOOK)
           .where(AUTHOR_BOOK.ID_BOOK.equal(bookModel.getIdBook()))
           .fetchInto(Integer.class);
   logger.debug("Existing authors: " + existsAuthors);
   List<Integer> newAuthors = new ArrayList<>();
   List<Integer> authors = new ArrayList<>();
   /** */
   for (String idAuthor : bookModel.getAuthors()) {
     int id = Integer.valueOf(idAuthor);
     authors.add(id);
     if (!existsAuthors.contains(id)) {
       newAuthors.add(id);
     }
   }
   existsAuthors.removeAll(authors);
   logger.debug("New authors: " + newAuthors);
   if (!newAuthors.isEmpty()) {
     InsertValuesStep2<AuthorBookRecord, Integer, Integer> insertStep =
         create.insertInto(AUTHOR_BOOK, AUTHOR_BOOK.ID_AUTHOR, AUTHOR_BOOK.ID_BOOK);
     InsertValuesStep2<AuthorBookRecord, Integer, Integer> valuesStep = null;
     for (Integer idAuthor : newAuthors) {
       valuesStep = insertStep.values(idAuthor, bookModel.getIdBook());
     }
     valuesStep.execute();
   }
   logger.debug("Old authors: " + existsAuthors);
   if (!existsAuthors.isEmpty()) {
     create.delete(AUTHOR_BOOK).where(AUTHOR_BOOK.ID_AUTHOR.in(existsAuthors)).execute();
   }
 }
 @Override
 public List<BookModel> selectAll() {
   List<BookModel> books =
       create
           .select(
               BOOK.ID_BOOK,
               BOOK.TITLE,
               BOOK.SHORT_DESCRIPTION,
               BOOK.DATE_PUBLISH,
               PostgresDSL.arrayAgg(concat(AUTHOR.FIRST_NAME, val(" "), AUTHOR.SECOND_NAME))
                   .as("authors"))
           .from(AUTHOR)
           .join(AUTHOR_BOOK)
           .on(AUTHOR_BOOK.ID_AUTHOR.equal(AUTHOR.ID_AUTHOR))
           .join(BOOK)
           .on(BOOK.ID_BOOK.equal(AUTHOR_BOOK.ID_BOOK))
           .where(BOOK.STATUS.equal(true))
           .groupBy(BOOK.ID_BOOK)
           .fetchInto(BookModel.class);
   logger.debug("Books: " + books);
   return books;
 }
 public static Msg<List<Addresslibrary>> getAddress(Context context, String userid, Integer type) {
   DSLContext dSLContext = context.getJc().getDefaultClient().getContext();
   Msg<List<Addresslibrary>> msg = new Msg<List<Addresslibrary>>();
   List<Addresslibrary> al =
       dSLContext
           .select()
           .from(ADDRESSLIBRARY)
           .where(
               ADDRESSLIBRARY
                   .USERID
                   .eq(userid)
                   .and(ADDRESSLIBRARY.TYPE.eq(type))
                   .and(ADDRESSLIBRARY.ISDEL.eq(0).or(ADDRESSLIBRARY.ISDEL.isNull())))
           .orderBy(ADDRESSLIBRARY.TEL.asc())
           .fetchInto(Addresslibrary.class);
   if (al.size() >= 1) {
     msg.setResult(true);
     msg.setValue(al);
   } else {
     msg.setResult(false);
   }
   return msg;
 }
 public static Msg<Addresslibrary> getDefaultSender(
     Context context, String userid, Integer isdefault) {
   DSLContext dSLContext = context.getJc().getDefaultClient().getContext();
   Msg<Addresslibrary> msg = new Msg<Addresslibrary>();
   List<Addresslibrary> al =
       dSLContext
           .select()
           .from(ADDRESSLIBRARY)
           .where(
               ADDRESSLIBRARY
                   .USERID
                   .eq(userid)
                   .and(ADDRESSLIBRARY.TYPE.eq(1))
                   .and(ADDRESSLIBRARY.ISDEFAULT.eq(1))
                   .and(ADDRESSLIBRARY.ISDEL.eq(0)))
           .fetchInto(Addresslibrary.class);
   if (al.size() >= 1) {
     msg.setResult(true);
     msg.setValue(al.get(0));
   } else {
     msg.setResult(false);
   }
   return msg;
 }
Beispiel #19
0
  @Override
  protected void doInitialize(Border layout) {
    add(layout);

    DSLContext context = Spring.getBean(DSLContext.class);
    MenuTable menuTable = Tables.MENU.as("menuTable");
    SectionTable sectionTable = Tables.SECTION.as("sectionTable");

    this.form = new Form<>("form");
    layout.add(this.form);

    this.orderField = new TextField<>("orderField", new PropertyModel<>(this, "order"));
    this.orderField.setRequired(true);
    this.form.add(this.orderField);
    this.orderFeedback = new TextFeedbackPanel("orderFeedback", this.orderField);
    this.form.add(this.orderFeedback);

    this.titleField = new TextField<>("titleField", new PropertyModel<>(this, "title"));
    this.titleField.setRequired(true);
    this.form.add(this.titleField);
    this.titleFeedback = new TextFeedbackPanel("titleFeedback", this.titleField);
    this.form.add(this.titleFeedback);

    this.iconField = new TextField<>("iconField", new PropertyModel<>(this, "icon"));
    this.iconField.setRequired(true);
    this.form.add(this.iconField);
    this.iconFeedback = new TextFeedbackPanel("iconFeedback", this.iconField);
    this.form.add(this.iconFeedback);

    this.menuParents = context.select(menuTable.fields()).from(menuTable).fetchInto(MenuPojo.class);
    this.parentField =
        new DropDownChoice<>(
            "parentField",
            new PropertyModel<>(this, "menuParent"),
            new PropertyModel<>(this, "menuParents"),
            new MenuChoiceRenderer());
    this.parentField.setNullValid(true);
    this.form.add(this.parentField);
    this.parentFeedback = new TextFeedbackPanel("parentFeedback", this.parentField);
    this.form.add(this.parentFeedback);

    this.sections =
        context.select(sectionTable.fields()).from(sectionTable).fetchInto(SectionPojo.class);
    this.sectionField =
        new DropDownChoice<>(
            "sectionField",
            new PropertyModel<>(this, "section"),
            new PropertyModel<>(this, "sections"),
            new SectionChoiceRenderer());
    this.sectionField.setNullValid(true);
    this.form.add(this.sectionField);
    this.sectionFeedback = new TextFeedbackPanel("sectionFeedback", this.sectionField);
    this.form.add(this.sectionFeedback);

    this.saveButton = new Button("saveButton");
    this.saveButton.setOnSubmit(this::saveButtonOnSubmit);
    this.form.add(this.saveButton);

    this.closeButton = new BookmarkablePageLink<>("closeButton", MenuBrowsePage.class);
    this.form.add(this.closeButton);

    this.form.add(new MenuFormValidator(this.parentField, this.sectionField));
  }
  @Override
  public void update() throws IOException {
    ResourceFileLocation location = getLocation("KEGG Reaction");
    HSQLDBLocation connection = connection();
    try {
      Hsqldb.createReactionSchema(connection.getConnection());
      DSLContext create = DSL.using(connection.getConnection(), HSQLDB);

      Set<String> compoundIds = Sets.newHashSetWithExpectedSize(10000);

      InsertValuesStep2<?, String, String> reactionInsert =
          create.insertInto(REACTION, REACTION.ACCESSION, REACTION.EC);
      InsertValuesStep1<?, String> compoundInsert = create.insertInto(COMPOUND, COMPOUND.ACCESSION);

      List<String[]> reactants = new ArrayList<String[]>(10000);
      List<String[]> products = new ArrayList<String[]>(10000);

      KEGGReactionParser parser =
          new KEGGReactionParser(
              location.open(), KEGGField.ENTRY, KEGGField.EQUATION, KEGGField.ENZYME);
      Map<KEGGField, StringBuilder> entry;
      while ((entry = parser.readNext()) != null) {

        if (isCancelled()) break;

        String equation = entry.get(KEGGField.EQUATION).toString();
        String ec =
            entry.containsKey(KEGGField.ENZYME)
                ? entry.get(KEGGField.ENZYME).toString().trim()
                : "";
        String[] sides = equation.split("<=>");

        String[][] left = getParticipants(sides[0]);
        String[][] right = getParticipants(sides[1]);

        Matcher matcher = ACCESSION.matcher(entry.get(KEGGField.ENTRY).toString());

        if (!ec.isEmpty()) ec = ec.split("\\s+")[0].trim();

        if (matcher.find()) {
          String accession = matcher.group(1);
          reactionInsert.values(accession, ec);

          for (String[] participant : left) {
            String cid = participant[1];
            if (compoundIds.add(cid)) compoundInsert.values(cid);
            participant = Arrays.copyOf(participant, 3);
            participant[2] = accession;
            reactants.add(participant);
          }
          for (String[] participant : right) {
            String cid = participant[1];
            if (compoundIds.add(cid)) compoundInsert.values(cid);
            participant = Arrays.copyOf(participant, 3);
            participant[2] = accession;
            products.add(participant);
          }
        }
      }

      // do the inserts
      fireProgressUpdate("inserting reactions and compounds");
      reactionInsert.execute();
      compoundInsert.execute();

      fireProgressUpdate("inserting reaction relations");

      for (int i = 0, end = reactants.size() - 1; i <= end; i++) {

        String[] participant = reactants.get(i);
        double coef = Double.parseDouble(participant[0]);
        String cid = participant[1];
        String acc = participant[2];
        create
            .insertInto(REACTANT)
            .set(REACTANT.COEFFICIENT, coef)
            .set(
                REACTANT.COMPOUND_ID,
                create.select(COMPOUND.ID).from(COMPOUND).where(COMPOUND.ACCESSION.eq(cid)))
            .set(
                REACTANT.REACTION_ID,
                create.select(REACTION.ID).from(REACTION).where(REACTION.ACCESSION.eq(acc)))
            .execute();
      }

      for (int i = 0, end = products.size() - 1; i <= end; i++) {

        String[] participant = products.get(i);
        double coef = Double.parseDouble(participant[0]);
        String cid = participant[1];
        String acc = participant[2];
        create
            .insertInto(PRODUCT)
            .set(PRODUCT.COEFFICIENT, coef)
            .set(
                PRODUCT.COMPOUND_ID,
                create.select(COMPOUND.ID).from(COMPOUND).where(COMPOUND.ACCESSION.eq(cid)))
            .set(
                PRODUCT.REACTION_ID,
                create.select(REACTION.ID).from(REACTION).where(REACTION.ACCESSION.eq(acc)))
            .execute();
      }

    } catch (SQLException e) {
      throw new IOException(e);
    } finally {
      location.close();
      try {
        connection.commit();
      } catch (SQLException e) {
        System.err.println(e.getMessage());
      } finally {
        try {
          connection.close();
        } catch (SQLException e) {
        }
      }
    }
  }
Beispiel #21
0
  @Override
  protected final int execute(ExecuteContext ctx, ExecuteListener listener) throws SQLException {
    if (returning.isEmpty()) {
      return super.execute(ctx, listener);
    } else {
      int result = 1;
      ResultSet rs;
      switch (ctx.configuration().dialect()) {

          // SQLite can select _rowid_ after the insert
        case SQLITE:
          {
            listener.executeStart(ctx);
            result = ctx.statement().executeUpdate();
            listener.executeEnd(ctx);

            DSLContext create =
                DSL.using(ctx.connection(), SQLDialect.SQLITE, ctx.configuration().settings());
            returned =
                create
                    .select(returning)
                    .from(getInto())
                    .where(rowid().equal(rowid().getDataType().convert(create.lastID())))
                    .fetchInto(getInto());

            return result;
          }

          // Sybase can select @@identity after the insert
          // TODO [#832] Fix this. This might be a driver issue. JDBC
          // Generated keys don't work with jconn3, but they seem to work
          // with jTDS (which is used for Sybase ASE integration)
        case CUBRID:
        case SYBASE:
          {
            listener.executeStart(ctx);
            result = ctx.statement().executeUpdate();
            listener.executeEnd(ctx);

            selectReturning(ctx.configuration(), create(ctx.configuration()).lastID());
            return result;
          }

          // Some dialects can only retrieve "identity" (AUTO_INCREMENT) values
          // Additional values have to be fetched explicitly
          // [#1260] TODO CUBRID supports this, but there's a JDBC bug
        case ASE:
        case DERBY:
        case H2:
        case INGRES:
        case MYSQL:
        case SQLSERVER:
          {
            listener.executeStart(ctx);
            result = ctx.statement().executeUpdate();
            listener.executeEnd(ctx);

            rs = ctx.statement().getGeneratedKeys();

            try {
              List<Object> list = new ArrayList<Object>();

              // Some JDBC drivers seem to illegally return null
              // from getGeneratedKeys() sometimes
              if (rs != null) {
                while (rs.next()) {
                  list.add(rs.getObject(1));
                }
              }

              selectReturning(ctx.configuration(), list.toArray());
              return result;
            } finally {
              JDBCUtils.safeClose(rs);
            }
          }

          // Firebird and Postgres can execute the INSERT .. RETURNING
          // clause like a select clause. JDBC support is not implemented
          // in the Postgres JDBC driver
        case FIREBIRD:
        case POSTGRES:
          {
            listener.executeStart(ctx);
            rs = ctx.statement().executeQuery();
            listener.executeEnd(ctx);

            break;
          }

          // These dialects have full JDBC support
        case DB2:
        case HSQLDB:
        case ORACLE:
        default:
          {
            listener.executeStart(ctx);
            result = ctx.statement().executeUpdate();
            listener.executeEnd(ctx);

            rs = ctx.statement().getGeneratedKeys();
            break;
          }
      }

      ExecuteContext ctx2 = new DefaultExecuteContext(ctx.configuration());
      ExecuteListener listener2 = new ExecuteListeners(ctx2);

      ctx2.resultSet(rs);
      returned =
          new CursorImpl<R>(ctx2, listener2, fieldArray(returning), null, true, false)
              .fetch()
              .into(getInto());
      return result;
    }
  }
Beispiel #22
0
    @Test
    public void testCustomSQL() throws Exception {
        final Field<Integer> IDx2 = new CustomField<Integer>(TBook_ID().getName(), TBook_ID().getDataType()) {
            private static final long serialVersionUID = 1L;

            @Override
            public void toSQL(RenderContext context) {
                context.configuration().data("Foo-Field", "Baz");

                if (context.inline()) {
                    context.sql(TBook_ID().getName() + " * 2");
                }

                // Firebird is the only dialect that cannot handle type inferral
                // When multiplying an INT by a bind value
                else if (context.configuration().dialect() == FIREBIRD) {
                    context.sql(TBook_ID().getName() + " * cast (? as int)");
                }
                else {
                    context.sql(TBook_ID().getName() + " * ?");
                }
            }

            @Override
            public void bind(BindContext context) {
                try {
                    context.statement().setInt(context.nextIndex(), 2);
                }
                catch (SQLException e) {
                    throw translate(null, e);
                }
            }
        };

        Condition c = new CustomCondition() {
            private static final long serialVersionUID = -629253722638033620L;

            @Override
            public void toSQL(RenderContext context) {
                context.configuration().data("Foo-Condition", "Baz");

                context.sql(IDx2);
                context.sql(" > ");

                if (context.inline()) {
                    context.sql("3");
                }
                else {
                    context.sql("?");
                }
            }

            @Override
            public void bind(BindContext context) {
                try {
                    context.bind(IDx2);
                    context.statement().setInt(context.nextIndex(), 3);
                }
                catch (SQLException e) {
                    throw translate(null, e);
                }
            }
        };

        // [#1169] Some additional checks to see if custom data is correctly
        // passed on to custom QueryParts
        DSLContext create = create();
        create.configuration().data("Foo-Field", "Bar");
        create.configuration().data("Foo-Condition", "Bar");

        Result<Record2<Integer, Integer>> result = create
            .select(TBook_ID(), IDx2)
            .from(TBook())
            .where(c)
            .orderBy(IDx2)
            .fetch();

        assertEquals(3, result.size());
        assertEquals(Integer.valueOf(2), result.getValue(0, TBook_ID()));
        assertEquals(Integer.valueOf(3), result.getValue(1, TBook_ID()));
        assertEquals(Integer.valueOf(4), result.getValue(2, TBook_ID()));

        assertEquals(Integer.valueOf(4), result.getValue(0, IDx2));
        assertEquals(Integer.valueOf(6), result.getValue(1, IDx2));
        assertEquals(Integer.valueOf(8), result.getValue(2, IDx2));

        // [#1169] Check again
        assertEquals("Baz", create.configuration().data("Foo-Field"));
        assertEquals("Baz", create.configuration().data("Foo-Condition"));
    }
 private SelectConditionStep<Record1<Integer>> selectAddressId(int chargeBoxPk) {
   return ctx.select(CHARGE_BOX.ADDRESS_PK)
       .from(CHARGE_BOX)
       .where(CHARGE_BOX.CHARGE_BOX_PK.eq(chargeBoxPk));
 }
 @Override
 public List<String> getChargeBoxIds() {
   return ctx.select(CHARGE_BOX.CHARGE_BOX_ID).from(CHARGE_BOX).fetch(CHARGE_BOX.CHARGE_BOX_ID);
 }