Ejemplo n.º 1
0
 /**
  * Executes an arbitrary statement. If another result set exists for this statement, this will be
  * closed (even if this statement fails).
  *
  * <p>If the statement is a create or drop and does not throw an exception, the current
  * transaction (if any) is committed after executing the statement. If auto commit is on, and the
  * statement is not a select, this statement will be committed.
  *
  * @param sql the SQL statement to execute
  * @return true if a result set is available, false if not
  */
 public boolean execute(String sql) throws SQLException {
   try {
     int id = getNextId(TraceObject.RESULT_SET);
     if (isDebugEnabled()) {
       debugCodeCall("execute", sql);
     }
     checkClosedForWrite();
     closeOldResultSet();
     sql = conn.translateSQL(sql, escapeProcessing);
     CommandInterface command = conn.prepareCommand(sql, fetchSize);
     boolean returnsResultSet;
     synchronized (session) {
       setExecutingStatement(command);
       try {
         if (command.isQuery()) {
           returnsResultSet = true;
           boolean scrollable = resultSetType != ResultSet.TYPE_FORWARD_ONLY;
           boolean updatable = resultSetConcurrency == ResultSet.CONCUR_UPDATABLE;
           ResultInterface result = command.executeQuery(maxRows, scrollable);
           resultSet =
               new JdbcResultSet(conn, this, result, id, closedByResultSet, scrollable, updatable);
         } else {
           returnsResultSet = false;
           updateCount = command.executeUpdate();
         }
       } finally {
         setExecutingStatement(null);
       }
     }
     command.close();
     return returnsResultSet;
   } catch (Exception e) {
     throw logAndConvert(e);
   }
 }
Ejemplo n.º 2
0
 /**
  * Executes a query (select statement) and returns the result set. If another result set exists
  * for this statement, this will be closed (even if this statement fails).
  *
  * @param sql the SQL statement to execute
  * @return the result set
  */
 public ResultSet executeQuery(String sql) throws SQLException {
   try {
     int id = getNextId(TraceObject.RESULT_SET);
     if (isDebugEnabled()) {
       debugCodeAssign(
           "ResultSet", TraceObject.RESULT_SET, id, "executeQuery(" + quote(sql) + ")");
     }
     checkClosed();
     closeOldResultSet();
     sql = conn.translateSQL(sql, escapeProcessing);
     synchronized (session) {
       CommandInterface command = conn.prepareCommand(sql, fetchSize);
       ResultInterface result;
       boolean scrollable = resultSetType != ResultSet.TYPE_FORWARD_ONLY;
       boolean updatable = resultSetConcurrency == ResultSet.CONCUR_UPDATABLE;
       setExecutingStatement(command);
       try {
         result = command.executeQuery(maxRows, scrollable);
       } finally {
         setExecutingStatement(null);
       }
       command.close();
       resultSet =
           new JdbcResultSet(conn, this, result, id, closedByResultSet, scrollable, updatable);
     }
     return resultSet;
   } catch (Exception e) {
     throw logAndConvert(e);
   }
 }
Ejemplo n.º 3
0
 /**
  * INTERNAL. Set the statement that is currently running.
  *
  * @param c the command
  */
 protected void setExecutingStatement(CommandInterface c) {
   if (c == null) {
     conn.setExecutingStatement(null);
   } else {
     conn.setExecutingStatement(this);
     lastExecutedCommandType = c.getCommandType();
   }
   executingCommand = c;
 }
Ejemplo n.º 4
0
 /**
  * INTERNAL. Check if the statement is closed.
  *
  * @param write if the next operation is possibly writing
  * @return true if a reconnect was required
  * @throws SQLException if it is closed
  */
 protected boolean checkClosed(boolean write) throws SQLException {
   if (conn == null) {
     throw Message.getSQLException(ErrorCode.OBJECT_CLOSED);
   }
   conn.checkClosed(write);
   SessionInterface s = conn.getSession();
   if (s != session) {
     session = s;
     setTrace(session.getTrace());
     return true;
   }
   return false;
 }
Ejemplo n.º 5
0
 /**
  * Gets the current query timeout in seconds. This method will return 0 if no query timeout is
  * set. The result is rounded to the next second.
  *
  * @return the timeout in seconds
  * @throws SQLException if this object is closed
  */
 public int getQueryTimeout() throws SQLException {
   try {
     debugCodeCall("getQueryTimeout");
     checkClosed();
     return conn.getQueryTimeout();
   } catch (Exception e) {
     throw logAndConvert(e);
   }
 }
Ejemplo n.º 6
0
 private int executeUpdateInternal(String sql) throws SQLException {
   checkClosedForWrite();
   try {
     closeOldResultSet();
     sql = JdbcConnection.translateSQL(sql, escapeProcessing);
     CommandInterface command = conn.prepareCommand(sql, fetchSize);
     synchronized (session) {
       setExecutingStatement(command);
       try {
         updateCount = command.executeUpdate();
       } finally {
         setExecutingStatement(null);
       }
     }
     command.close();
     return updateCount;
   } finally {
     afterWriting();
   }
 }
Ejemplo n.º 7
0
 /**
  * Sets the current query timeout in seconds. Calling this method will commit an open transaction,
  * even if the value is the same as before. Changing the value will affect all statements of this
  * connection. This method does not commit a transaction, and rolling back a transaction does not
  * affect this setting.
  *
  * @param seconds the timeout in seconds - 0 means no timeout, values smaller 0 will throw an
  *     exception
  * @throws SQLException if this object is closed
  */
 public void setQueryTimeout(int seconds) throws SQLException {
   try {
     debugCodeCall("setQueryTimeout", seconds);
     checkClosed();
     if (seconds < 0) {
       throw Message.getInvalidValueException("" + seconds, "seconds");
     }
     conn.setQueryTimeout(seconds);
   } catch (Exception e) {
     throw logAndConvert(e);
   }
 }
Ejemplo n.º 8
0
 /**
  * Executes a statement (insert, update, delete, create, drop) and returns the update count. If
  * another result set exists for this statement, this will be closed (even if this statement
  * fails).
  *
  * <p>If the statement is a create or drop and does not throw an exception, the current
  * transaction (if any) is committed after executing the statement. If auto commit is on, this
  * statement will be committed.
  *
  * @param sql the SQL statement
  * @return the update count (number of row affected by an insert, update or delete, or 0 if no
  *     rows or the statement was a create, drop, commit or rollback)
  * @throws SQLException if a database error occurred or a select statement was executed
  */
 public int executeUpdate(String sql) throws SQLException {
   try {
     debugCodeCall("executeUpdate", sql);
     checkClosedForWrite();
     closeOldResultSet();
     sql = conn.translateSQL(sql, escapeProcessing);
     CommandInterface command = conn.prepareCommand(sql, fetchSize);
     synchronized (session) {
       setExecutingStatement(command);
       try {
         updateCount = command.executeUpdate();
       } finally {
         setExecutingStatement(null);
       }
     }
     command.close();
     return updateCount;
   } catch (Exception e) {
     throw logAndConvert(e);
   }
 }
Ejemplo n.º 9
0
 /**
  * Return a result set that contains the last generated auto-increment key for this connection, if
  * there was one. If no key was generated by the last modification statement, then an empty result
  * set is returned. The returned result set only contains the data for the very last row.
  *
  * @return the result set with one row and one column containing the key
  * @throws SQLException if this object is closed
  */
 public ResultSet getGeneratedKeys() throws SQLException {
   try {
     int id = getNextId(TraceObject.RESULT_SET);
     if (isDebugEnabled()) {
       debugCodeAssign("ResultSet", TraceObject.RESULT_SET, id, "getGeneratedKeys()");
     }
     checkClosed();
     return conn.getGeneratedKeys(this, id);
   } catch (Exception e) {
     throw logAndConvert(e);
   }
 }
Ejemplo n.º 10
0
 /**
  * Adds a statement to the batch.
  *
  * @param sql the SQL statement
  */
 public void addBatch(String sql) throws SQLException {
   try {
     debugCodeCall("addBatch", sql);
     checkClosed();
     sql = JdbcConnection.translateSQL(sql, escapeProcessing);
     if (batchCommands == null) {
       batchCommands = New.arrayList();
     }
     batchCommands.add(sql);
   } catch (Exception e) {
     throw logAndConvert(e);
   }
 }
Ejemplo n.º 11
0
 /**
  * Adds a statement to the batch.
  *
  * @param sql the SQL statement
  */
 public void addBatch(String sql) throws SQLException {
   try {
     debugCodeCall("addBatch", sql);
     checkClosed();
     sql = conn.translateSQL(sql, escapeProcessing);
     if (batchCommands == null) {
       batchCommands = ObjectArray.newInstance();
     }
     batchCommands.add(sql);
   } catch (Exception e) {
     throw logAndConvert(e);
   }
 }
Ejemplo n.º 12
0
 JdbcStatement(
     JdbcConnection conn,
     int id,
     int resultSetType,
     int resultSetConcurrency,
     boolean closeWithResultSet) {
   this.conn = conn;
   this.session = conn.getSession();
   setTrace(session.getTrace(), TraceObject.STATEMENT, id);
   this.resultSetType = resultSetType;
   this.resultSetConcurrency = resultSetConcurrency;
   this.closedByResultSet = closeWithResultSet;
 }
Ejemplo n.º 13
0
 /**
  * Return a result set that contains the last generated autoincrement key for this connection.
  *
  * @return the result set with one row and one column containing the key
  * @throws SQLException if this object is closed
  */
 public ResultSet getGeneratedKeys() throws SQLException {
   try {
     int id = getNextId(TraceObject.RESULT_SET);
     if (isDebugEnabled()) {
       debugCodeAssign("ResultSet", TraceObject.RESULT_SET, id, "getGeneratedKeys()");
     }
     checkClosed();
     ResultInterface result = conn.getGeneratedKeys();
     ResultSet rs = new JdbcResultSet(conn, this, result, id, false, true, false);
     return rs;
   } catch (Exception e) {
     throw logAndConvert(e);
   }
 }
Ejemplo n.º 14
0
 /**
  * Fills the Clob. This is only supported for new, empty Clob objects that were created with
  * Connection.createClob() or createNClob(). The position must be 1, meaning the whole Clob data
  * is set.
  *
  * @param pos where to start writing (the first character is at position 1)
  * @param str the string to add
  * @return the length of the added text
  */
 public int setString(long pos, String str) throws SQLException {
   try {
     if (isDebugEnabled()) {
       debugCode("setString(" + pos + ", " + quote(str) + ");");
     }
     checkClosed();
     if (pos != 1) {
       throw DbException.getInvalidValueException("pos", pos);
     } else if (str == null) {
       throw DbException.getInvalidValueException("str", str);
     }
     value = conn.createClob(new StringReader(str), -1);
     return str.length();
   } catch (Exception e) {
     throw logAndConvert(e);
   }
 }
Ejemplo n.º 15
0
  /**
   * @param conn Connection.
   * @param qry Query.
   * @param explain Explain.
   * @return Table.
   * @throws IgniteCheckedException
   */
  private GridMergeTable createMergeTable(
      JdbcConnection conn, GridCacheSqlQuery qry, boolean explain) throws IgniteCheckedException {
    try {
      Session ses = (Session) conn.getSession();

      CreateTableData data = new CreateTableData();

      data.tableName = "T___";
      data.schema = ses.getDatabase().getSchema(ses.getCurrentSchemaName());
      data.create = true;

      if (!explain) {
        LinkedHashMap<String, ?> colsMap = qry.columns();

        assert colsMap != null;

        ArrayList<Column> cols = new ArrayList<>(colsMap.size());

        for (Map.Entry<String, ?> e : colsMap.entrySet()) {
          String alias = e.getKey();
          GridSqlType t = (GridSqlType) e.getValue();

          assert !F.isEmpty(alias);

          Column c = new Column(alias, t.type(), t.precision(), t.scale(), t.displaySize());

          cols.add(c);
        }

        data.columns = cols;
      } else data.columns = planColumns();

      return new GridMergeTable(data, ctx);
    } catch (Exception e) {
      U.closeQuiet(conn);

      throw new IgniteCheckedException(e);
    }
  }
Ejemplo n.º 16
0
 /**
  * Do the search.
  *
  * @param conn the database connection
  * @param text the query
  * @param limit the limit
  * @param offset the offset
  * @param data whether the raw data should be returned
  * @return the result set
  */
 protected static ResultSet search(
     Connection conn, String text, int limit, int offset, boolean data) throws SQLException {
   SimpleResultSet result = createResultSet(data);
   if (conn.getMetaData().getURL().startsWith("jdbc:columnlist:")) {
     // this is just to query the result set columns
     return result;
   }
   if (text == null || text.trim().length() == 0) {
     return result;
   }
   try {
     IndexAccess access = getIndexAccess(conn);
     /*## LUCENE2 ##
     access.modifier.flush();
     String path = getIndexPath(conn);
     IndexReader reader = IndexReader.open(path);
     Analyzer analyzer = new StandardAnalyzer();
     Searcher searcher = new IndexSearcher(reader);
     QueryParser parser = new QueryParser(LUCENE_FIELD_DATA, analyzer);
     Query query = parser.parse(text);
     Hits hits = searcher.search(query);
     int max = hits.length();
     if (limit == 0) {
         limit = max;
     }
     for (int i = 0; i < limit && i + offset < max; i++) {
         Document doc = hits.doc(i + offset);
         float score = hits.score(i + offset);
     //*/
     // ## LUCENE3 ##
     // take a reference as the searcher may change
     Searcher searcher = access.searcher;
     // reuse the same analyzer; it's thread-safe;
     // also allows subclasses to control the analyzer used.
     Analyzer analyzer = access.writer.getAnalyzer();
     QueryParser parser = new QueryParser(Version.LUCENE_30, LUCENE_FIELD_DATA, analyzer);
     Query query = parser.parse(text);
     // Lucene 3 insists on a hard limit and will not provide
     // a total hits value. Take at least 100 which is
     // an optimal limit for Lucene as any more
     // will trigger writing results to disk.
     int maxResults = (limit == 0 ? 100 : limit) + offset;
     TopDocs docs = searcher.search(query, maxResults);
     if (limit == 0) {
       limit = docs.totalHits;
     }
     for (int i = 0, len = docs.scoreDocs.length;
         i < limit && i + offset < docs.totalHits && i + offset < len;
         i++) {
       ScoreDoc sd = docs.scoreDocs[i + offset];
       Document doc = searcher.doc(sd.doc);
       float score = sd.score;
       // */
       String q = doc.get(LUCENE_FIELD_QUERY);
       if (data) {
         int idx = q.indexOf(" WHERE ");
         JdbcConnection c = (JdbcConnection) conn;
         Session session = (Session) c.getSession();
         Parser p = new Parser(session);
         String tab = q.substring(0, idx);
         ExpressionColumn expr = (ExpressionColumn) p.parseExpression(tab);
         String schemaName = expr.getOriginalTableAliasName();
         String tableName = expr.getColumnName();
         q = q.substring(idx + " WHERE ".length());
         Object[][] columnData = parseKey(conn, q);
         result.addRow(schemaName, tableName, columnData[0], columnData[1], score);
       } else {
         result.addRow(q, score);
       }
     }
     /*## LUCENE2 ##
     // TODO keep it open if possible
     reader.close();
     //*/
   } catch (Exception e) {
     throw convertException(e);
   }
   return result;
 }
Ejemplo n.º 17
0
 /**
  * INTERNAL. Set the statement that is currently running.
  *
  * @param c the command
  */
 protected void setExecutingStatement(CommandInterface c) {
   conn.setExecutingStatement(c == null ? null : this);
   executingCommand = c;
 }
Ejemplo n.º 18
0
 /** INTERNAL */
 public JdbcClob(JdbcConnection conn, Value value, int id) {
   setTrace(conn.getSession().getTrace(), TraceObject.CLOB, id);
   this.conn = conn;
   this.value = value;
 }
Ejemplo n.º 19
0
 /** Called after each write operation. */
 void afterWriting() {
   if (conn != null) {
     conn.afterWriting();
   }
 }
Ejemplo n.º 20
0
 private void checkClosed() {
   conn.checkClosed();
   if (value == null) {
     throw DbException.get(ErrorCode.OBJECT_CLOSED);
   }
 }