コード例 #1
0
        @Override
        public void executeStart(ExecuteContext ctx) {
            executeStart = ++callbackCount;
            checkBase(ctx);
            checkSQL(ctx, true);
            checkStatement(ctx, true);

            assertNull(ctx.resultSet());
            assertNull(ctx.record());
            assertNull(ctx.result());
        }
コード例 #2
0
ファイル: FieldTypeHelper.java プロジェクト: Arbonaut/jOOQ
  /** Workarounds for the unimplemented Postgres JDBC driver features */
  @SuppressWarnings("unchecked")
  private static <T> T pgGetArray(ExecuteContext ctx, Class<? extends T> type, int index)
      throws SQLException {

    ResultSet rs = ctx.resultSet();

    // Get the JDBC Array and check for null. If null, that's OK
    Array array = rs.getArray(index);
    if (array == null) {
      return null;
    }

    // Try fetching a Java Object[]. That's gonna work for non-UDT types
    try {
      return (T) convertArray(rs.getArray(index), (Class<? extends Object[]>) type);
    }

    // This might be a UDT (not implemented exception...)
    catch (Exception e) {
      List<Object> result = new ArrayList<Object>();

      // Try fetching the array as a JDBC ResultSet
      try {
        ctx.resultSet(array.getResultSet());
        while (ctx.resultSet().next()) {
          result.add(getFromResultSet(ctx, type.getComponentType(), 2));
        }
      }

      // That might fail too, then we don't know any further...
      catch (Exception fatal) {
        log.error("Cannot parse Postgres array: " + rs.getString(index));
        log.error(fatal);
        return null;
      } finally {
        ctx.resultSet(rs);
      }

      return (T) convertArray(result.toArray(), (Class<? extends Object[]>) type);
    }
  }
コード例 #3
0
        @Override
        public void renderStart(ExecuteContext ctx) {
            renderStart = ++callbackCount;
            checkBase(ctx);

            assertNull(ctx.batchSQL()[0]);
            assertNull(ctx.sql());
            assertNull(ctx.statement());
            assertNull(ctx.resultSet());
            assertNull(ctx.record());
            assertNull(ctx.result());
        }
コード例 #4
0
        @Override
        public void prepareEnd(ExecuteContext ctx) {
            prepareEnd = ++callbackCount;
            checkBase(ctx);
            checkSQL(ctx, true);

            checkStatement(ctx, false);
            // TODO Patch statement
            checkStatement(ctx, true);

            assertNull(ctx.resultSet());
            assertNull(ctx.record());
            assertNull(ctx.result());
        }
コード例 #5
0
        @Override
        public void renderEnd(ExecuteContext ctx) {
            renderEnd = ++callbackCount;
            checkBase(ctx);
            checkSQL(ctx, false);

            assertNull(ctx.statement());
            assertNull(ctx.resultSet());
            assertNull(ctx.record());
            assertNull(ctx.result());

            ctx.sql(ctx.sql().replaceFirst("(?i:from)", "as my_field from"));
            checkSQL(ctx, true);
        }
コード例 #6
0
        @SuppressWarnings("serial")
        private void checkBase(ExecuteContext ctx) {
            assertNull(ctx.query());
            assertNotNull(ctx.batchQueries());
            assertTrue(ctx.batchQueries()[0].toString().toLowerCase().contains("insert"));
            assertEquals(1, ctx.batchSQL().length);

            assertEquals("Bar", ctx.getData("Foo"));
            assertEquals("Baz", ctx.getData("Bar"));
            assertEquals(new HashMap<String, String>() {{
                put("Foo", "Bar");
                put("Bar", "Baz");
            }}, ctx.getData());

            assertNull(ctx.routine());
            assertNull(ctx.resultSet());
            assertNull(ctx.record());
            assertNull(ctx.result());

            assertEquals(ExecuteType.BATCH, ctx.type());
        }
コード例 #7
0
  @Override
  protected final int execute(ExecuteContext ctx, ExecuteListener listener) throws SQLException {
    Connection connection = ctx.getConnection();
    boolean autoCommit = false;

    // [#706] Postgres requires two separate queries running in the same
    // transaction to be executed when fetching refcursor types
    if (ctx.getDialect() == SQLDialect.POSTGRES && isSelectingRefCursor()) {
      autoCommit = connection.getAutoCommit();

      if (autoCommit) {
        if (log.isDebugEnabled()) log.debug("Unsetting auto-commit", false);

        connection.setAutoCommit(false);
      }
    }

    try {
      listener.executeStart(ctx);

      // JTDS doesn't seem to implement PreparedStatement.execute()
      // correctly, at least not for sp_help
      if (ctx.getDialect() == ASE) {
        ctx.resultSet(ctx.statement().executeQuery());
      }

      // [#1232] Avoid executeQuery() in order to handle queries that may
      // not return a ResultSet, e.g. SQLite's pragma foreign_key_list(table)
      else if (ctx.statement().execute()) {
        ctx.resultSet(ctx.statement().getResultSet());
      }

      listener.executeEnd(ctx);

      // Fetch a single result set
      if (!many) {
        if (ctx.resultSet() != null) {
          FieldList fields = new FieldList(getFields(ctx.resultSet().getMetaData()));
          cursor = new CursorImpl<R>(ctx, listener, fields, getRecordType());

          if (!lazy) {
            result = cursor.fetch();
            cursor = null;
          }
        } else {
          result = new ResultImpl<R>(ctx, new FieldList());
        }
      }

      // Fetch several result sets
      else {
        results = new ArrayList<Result<Record>>();
        boolean anyResults = false;

        while (ctx.resultSet() != null) {
          anyResults = true;

          FieldProvider fields = new MetaDataFieldProvider(ctx, ctx.resultSet().getMetaData());
          Cursor<Record> c = new CursorImpl<Record>(ctx, listener, fields, true);
          results.add(c.fetch());

          if (ctx.statement().getMoreResults()) {
            ctx.resultSet(ctx.statement().getResultSet());
          } else {
            ctx.resultSet(null);
          }
        }

        // Call this only when there was at least one ResultSet.
        // Otherwise, this call is not supported by ojdbc...
        if (anyResults) {
          ctx.statement().getMoreResults(Statement.CLOSE_ALL_RESULTS);
        }

        ctx.statement().close();
      }
    } finally {
      if (autoCommit) {
        if (log.isDebugEnabled()) log.debug("Resetting auto-commit", autoCommit);

        connection.setAutoCommit(autoCommit);
      }
    }

    return result != null ? result.size() : 0;
  }
コード例 #8
0
ファイル: AbstractStoreQuery.java プロジェクト: binque/jOOQ
  @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;
    }
  }
コード例 #9
0
ファイル: FieldTypeHelper.java プロジェクト: Arbonaut/jOOQ
  @SuppressWarnings("unchecked")
  private static <T> T getFromResultSet(ExecuteContext ctx, Class<? extends T> type, int index)
      throws SQLException {

    ResultSet rs = ctx.resultSet();

    if (type == Blob.class) {
      return (T) rs.getBlob(index);
    } else if (type == Boolean.class) {
      return (T) checkWasNull(rs, Boolean.valueOf(rs.getBoolean(index)));
    } else if (type == BigInteger.class) {
      // The SQLite JDBC driver doesn't support BigDecimals
      if (ctx.getDialect() == SQLDialect.SQLITE) {
        return Convert.convert(rs.getString(index), (Class<? extends T>) BigInteger.class);
      } else {
        BigDecimal result = rs.getBigDecimal(index);
        return (T) (result == null ? null : result.toBigInteger());
      }
    } else if (type == BigDecimal.class) {
      // The SQLite JDBC driver doesn't support BigDecimals
      if (ctx.getDialect() == SQLDialect.SQLITE) {
        return Convert.convert(rs.getString(index), (Class<? extends T>) BigDecimal.class);
      } else {
        return (T) rs.getBigDecimal(index);
      }
    } else if (type == Byte.class) {
      return (T) checkWasNull(rs, Byte.valueOf(rs.getByte(index)));
    } else if (type == byte[].class) {
      return (T) rs.getBytes(index);
    } else if (type == Clob.class) {
      return (T) rs.getClob(index);
    } else if (type == Date.class) {
      return (T) getDate(ctx.getDialect(), rs, index);
    } else if (type == Double.class) {
      return (T) checkWasNull(rs, Double.valueOf(rs.getDouble(index)));
    } else if (type == Float.class) {
      return (T) checkWasNull(rs, Float.valueOf(rs.getFloat(index)));
    } else if (type == Integer.class) {
      return (T) checkWasNull(rs, Integer.valueOf(rs.getInt(index)));
    } else if (type == Long.class) {
      return (T) checkWasNull(rs, Long.valueOf(rs.getLong(index)));
    } else if (type == Short.class) {
      return (T) checkWasNull(rs, Short.valueOf(rs.getShort(index)));
    } else if (type == String.class) {
      return (T) rs.getString(index);
    } else if (type == Time.class) {
      return (T) getTime(ctx.getDialect(), rs, index);
    } else if (type == Timestamp.class) {
      return (T) getTimestamp(ctx.getDialect(), rs, index);
    } else if (type == YearToMonth.class) {
      if (ctx.getDialect() == POSTGRES) {
        Object object = rs.getObject(index);
        return (T) (object == null ? null : PostgresUtils.toYearToMonth(object));
      } else {
        String string = rs.getString(index);
        return (T) (string == null ? null : YearToMonth.valueOf(string));
      }
    } else if (type == DayToSecond.class) {
      if (ctx.getDialect() == POSTGRES) {
        Object object = rs.getObject(index);
        return (T) (object == null ? null : PostgresUtils.toDayToSecond(object));
      } else {
        String string = rs.getString(index);
        return (T) (string == null ? null : DayToSecond.valueOf(string));
      }
    } else if (type == UByte.class) {
      String string = rs.getString(index);
      return (T) (string == null ? null : UByte.valueOf(string));
    } else if (type == UShort.class) {
      String string = rs.getString(index);
      return (T) (string == null ? null : UShort.valueOf(string));
    } else if (type == UInteger.class) {
      String string = rs.getString(index);
      return (T) (string == null ? null : UInteger.valueOf(string));
    } else if (type == ULong.class) {
      String string = rs.getString(index);
      return (T) (string == null ? null : ULong.valueOf(string));
    }

    // The type byte[] is handled earlier. byte[][] can be handled here
    else if (type.isArray()) {
      switch (ctx.getDialect()) {
        case POSTGRES:
          {
            return pgGetArray(ctx, type, index);
          }

        default:
          // Note: due to a HSQLDB bug, it is not recommended to call rs.getObject() here:
          // See https://sourceforge.net/tracker/?func=detail&aid=3181365&group_id=23316&atid=378131
          return (T) convertArray(rs.getArray(index), (Class<? extends Object[]>) type);
      }
    } else if (ArrayRecord.class.isAssignableFrom(type)) {
      return (T) getArrayRecord(ctx, rs.getArray(index), (Class<? extends ArrayRecord<?>>) type);
    } else if (EnumType.class.isAssignableFrom(type)) {
      return getEnumType(type, rs.getString(index));
    } else if (MasterDataType.class.isAssignableFrom(type)) {
      return (T) getMasterDataType(type, rs.getObject(index));
    } else if (UDTRecord.class.isAssignableFrom(type)) {
      switch (ctx.getDialect()) {
        case POSTGRES:
          return (T) pgNewUDTRecord(type, rs.getObject(index));
      }

      return (T) rs.getObject(index, DataTypes.udtRecords());
    } else if (Result.class.isAssignableFrom(type)) {
      ResultSet nested = (ResultSet) rs.getObject(index);
      return (T) getNewFactory(ctx).fetch(nested);
    } else {
      return (T) rs.getObject(index);
    }
  }
コード例 #10
0
 @SuppressWarnings("unused")
 private void checkResultSet(ExecuteContext ctx, boolean patched) {
     assertNotNull(ctx.resultSet());
 }