Fetch all existing BOs from storage, sorted by primary key(s) and return the result as a
stream.

@param conn
@return
@since 0.9.0
195588
protected Stream<T> getAllSorted(Connection conn) {
        return executeSelectAsStream(rowMapper, conn, true, calcSqlSelectAllSorted());
    }
1351971
public int[] insert(Connection conn, Entity... records) throws SQLException {
		checkConn(conn);
		if(ArrayUtil.isEmpty(records)){
			return new int[]{0};
		}
		
		//单条单独处理
		if(1 == records.length) {
			return new int[] { insert(conn, records[0])};
		}
		
		PreparedStatement ps = null;
		try {
			ps = dialect.psForInsertBatch(conn, records);
			return ps.executeBatch();
		} finally {
			DbUtil.close(ps);
		}
	}
199511
public final Cursor<T> select (Connection conn, String condition)
    {
        String query = "select " + listOfFields + " from " + name +
            " " + condition;
        return new Cursor<T>(this, conn, query);
    }
1193000
public M fetchOne(String... columns) {
		if (null == columns) {
			return this.fetchOne();
		}
		//from db
		if (!this.syncToRedis) {
			return this.findFirst(SqlpKit.selectOne(this, columns));
		}
		//from redis
		return this.fetchOneFromRedis(columns);
	}
207379
public List<Entity> findAll(Connection conn, String tableName) throws SQLException{
		return findAll(conn, Entity.create(tableName));
	}
749624
protected DaoResult update(Connection conn, T bo) {
        if (bo == null) {
            return new DaoResult(DaoOperationStatus.NOT_FOUND);
        }
        Savepoint savepoint = null;
        try {
            try {
                String[] bindColumns = ArrayUtils.addAll(rowMapper.getUpdateColumns(),
                        rowMapper.getPrimaryKeyColumns());
                String colChecksum = rowMapper.getChecksumColumn();
                if (!StringUtils.isBlank(colChecksum)) {
                    bindColumns = ArrayUtils.add(bindColumns, colChecksum);
                }
                savepoint = conn.getAutoCommit() ? null : conn.setSavepoint();
                int numRows = execute(conn, calcSqlUpdateOne(bo),
                        rowMapper.valuesForColumns(bo, bindColumns));
                DaoResult result = numRows > 0 ? new DaoResult(DaoOperationStatus.SUCCESSFUL, bo)
                        : new DaoResult(DaoOperationStatus.NOT_FOUND);
                if (numRows > 0) {
                    invalidateCache(bo, CacheInvalidationReason.UPDATE);
                }
                return result;
            } catch (DuplicatedValueException dke) {
                if (savepoint != null) {
                    conn.rollback(savepoint);
                }
                return new DaoResult(DaoOperationStatus.DUPLICATED_VALUE);
            }
        } catch (SQLException e) {
            throw new DaoException(e);
        }
    }
203690
public static Object convertBlob(Object blob, InputStream input) throws SQLException {
        return convertBlob(blob, toByteArray(input));
    }
1010630
private Map<byte[], byte[]> getColumns(Object connection, String hashKey, Map<byte[], byte[]> columns)
    {
        if (resource != null && resource.isActive())
        {
            // Why transaction API returns response in byte[] format/?
            Response response = ((Transaction) connection).hgetAll(getEncodedBytes(hashKey));
            ((RedisTransaction) resource).onExecute(((Transaction) connection));
            // ((Transaction) connection).exec();
            Map<String, String> cols = (Map<String, String>) response.get();
            connection = getConnection();

            if (cols != null)
            {
                for (String name : cols.keySet())
                {
                    columns.put(getEncodedBytes(name), getEncodedBytes(cols.get(name)));
                }
            }
        }
        else
        {
            columns = ((Jedis) connection).hgetAll(getEncodedBytes(hashKey));
        }
        return columns;
    }
69278
ColumnOrSuperColumn getColumn(ByteBuffer key, ColumnPath colPath) {
        m_logger.debug("Fetching {}.{}", new Object[]{Utils.toString(key), toString(colPath)});
        ColumnOrSuperColumn column = null;
        boolean bSuccess = false;
        for (int attempts = 1; !bSuccess; attempts++) {
            try {
                // Attempt to retrieve a slice list.
                Date startDate = new Date();
                column = m_client.get(key, colPath, ConsistencyLevel.ONE);
                timing("get", startDate);
                if (attempts > 1) {
                    m_logger.info("get() succeeded on attempt #{}", attempts);
                }
                bSuccess = true;
            } catch (NotFoundException ex) {
                return null;
            } catch (InvalidRequestException ex) {
                // No point in retrying this one.
                String errMsg = "get() failed for table: " + colPath.getColumn_family();
                m_bFailed = true;
                m_logger.error(errMsg, ex);
                throw new RuntimeException(errMsg, ex);
            } catch (Exception ex) {
                // Abort if all retries exceeded.
                if (attempts >= m_max_read_attempts) {
                    String errMsg = "All retries exceeded; abandoning get() for table: " +
                                    colPath.getColumn_family();
                    m_bFailed = true;
                    m_logger.error(errMsg, ex);
                    throw new RuntimeException(errMsg, ex);
                }
                
                // Report retry as a warning.
                m_logger.warn("get() attempt #{} failed: {}", attempts, ex);
                try {
                    Thread.sleep(attempts * m_retry_wait_millis);
                } catch (InterruptedException e1) {
                    // ignore
                }
                reconnect(ex);
            }
        }
        return column;
    }
678475
function(pool) {
    const conn = new Connection(options.connOptions);
    return conn
      .connect()
      .then(() => {
        if (pool.closed) {
          conn
            .end()
            .then(() => {})
            .catch(() => {});
          return Promise.reject(
            Errors.createError(
              'Cannot create new connection to pool, pool closed',
              true,
              null,
              '08S01',
              Errors.ER_ADD_CONNECTION_CLOSED_POOL,
              null
            )
          );
        }

        conn.releaseWithoutError = () => {
          conn.release().catch(() => {});
        };

        conn.forceEnd = conn.end;

        conn.release = () => {
          if (pool.closed) {
            pool._discardConnection(conn);
            return Promise.resolve();
          }
          if (options.noControlAfterUse) {
            pool._releaseConnection(conn);
            return Promise.resolve();
          }
          //if server permit it, reset the connection, or rollback only if not
          let revertFunction = conn.rollback;
          if (
            options.resetAfterUse &&
            ((conn.info.isMariaDB() && conn.info.hasMinVersion(10, 2, 4)) ||
              (!conn.info.isMariaDB() && conn.info.hasMinVersion(5, 7, 3)))
          ) {
            revertFunction = conn.reset;
          }

          return revertFunction()
            .then(() => {
              pool._releaseConnection(conn);
              return Promise.resolve();
            })
            .catch(err => {
              //uncertain connection state.
              // discard it
              pool._discardConnection(conn);
              return Promise.resolve();
            });
        };
        conn.end = conn.release;
        return Promise.resolve(conn);
      })
      .catch(err => {
        return Promise.reject(err);
      });
  }
1155496
function(conn) {
    var coll = CollMethods.Instance(dbLit, conn);
    var dbMethods = DBMethods(dbLit, conn);
    var dbMethodKeys = Object.keys(dbMethods);

    return {
      getOwnPropertyNames: function() {
        conn.db.collectionNames(conn.flow.add());

        return conn.flow.wait().map(function(obj) {
          var collName = obj.name;
          return collName.substr(collName.indexOf('.') + 1);
        }).concat(dbMethodKeys.map(function(methodName) {
          return util.format('%s(', methodName);
        }));
      },
      getOwnPropertyDescriptor: function(proxy, collectionName) {
        return {
          writable: false,
          enumerable: false,
          configurable: true
        };
      },
      getPropertyDescriptor: function(proxy, collectionName) {
        return this.getOwnPropertyDescriptor(proxy, collectionName);
      },
      get: function(proxy, op1) {
        if (op1 === 'getConn') {
          return function() { return conn; };
        } else if (op1 === '_name') {
          return conn.db.databaseName;
        } else if (op1 === 'toString') {
          return function() { return conn.db.databaseName; };
        }

        if (dbMethodKeys.indexOf(op1) !== -1) {
          return dbMethods[op1];
        }

        var collOps = coll(op1);
        var collOpKeys = Object.keys(collOps);
        var _this = this;
        return Proxy.create({
          getOwnPropertyNames: function() {
            var collNames = _this.getOwnPropertyNames();
            var matchColls = collNames.filter(function(collName) {
              return collName !== op1 &&
                collName.indexOf(op1) !== -1;
            }).map(function(collName) {
              var ext = collName.substr(collName.indexOf('.') + 1);
              var subExt = ext.indexOf(op1);
              if (subExt != -1) {
                return '';
              }
              return ext;
            }).filter(function(collName) {
              return collName.length;
            });
            if (matchColls.length) {
              return matchColls;
            }
            return collOpKeys.map(function(collOpKey) {
              return util.format('%s(', collOpKey);
            });
          },
          getOwnPropertyDescriptor: function(proxy, op) {
            return _this.getOwnPropertyDescriptor(proxy, op);
          },
          getPropertyDescriptor: function(proxy, op) {
            return _this.getPropertyDescriptor(proxy, op);
          },
          get: function(proxy, op2) {
            if (collOpKeys.indexOf(op2) !== -1) {
              return collOps[op2];
            }
            return _this.get(proxy, op1 + '.' + op2);
          }
        });
      }
    };
  }
1075120
public Object javaToSql(Object source)
    {
        if (source == null)
            return null;
        try
        {
            ByteArrayOutputStream bao = new ByteArrayOutputStream();
            GZIPOutputStream gos = new GZIPOutputStream(bao);
            ObjectOutputStream oos = new ObjectOutputStream(gos);
            oos.writeObject(source);
            oos.close();
            gos.close();
            bao.close();
            byte[] result = bao.toByteArray();
            return result;
        }
        catch (Throwable t)
        {
            throw new ConversionException(t);
        }
    }
1302562
public List fetchDatas(QueryConditonDatakey qcdk) {
		Debug.logVerbose("[JdonFramework]--> fetch the primary key collection, sql sentence: " + qcdk.getSQlKey(), module);
		Connection c = null;
		PreparedStatement ps = null;
		ResultSet rs = null;

		int blockStart = qcdk.getBlockStart();
		int blockSize = qcdk.getBlockSize();
		Debug.logVerbose("[JdonFramework]--> blockStart=" + blockStart + " blockSize=" + blockSize, module);
		List items = new ArrayList(blockSize);
		try {
			c = dataSource.getConnection();

			DbUtil.testConnection(c);
			ps = c.prepareStatement(qcdk.getSqlquery(), ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY);

			jdbcUtil.setQueryParams(qcdk.getQueryParams(), ps);

			rs = ps.executeQuery();
			if (DbUtil.supportsFetchSize)
				rs.setFetchSize(blockSize);
			// Many JDBC drivers don't implement scrollable cursors the real
			// way, but instead load all results into memory. Looping through
			// the results ourselves is more efficient.
			for (int i = 0; i < blockStart; i++) {
				if (!rs.next())
					break;
			}
			blockSize++;
			while (rs.next() && (--blockSize > 0)) {
				Object result = rs.getObject(1);
				Debug.logVerbose("[JdonFramework]--> found a primary key = " + result + ",  type:" + result.getClass().getName(), module);
				items.add(result);
			}

			Debug.logVerbose("[JdonFramework]--> get a result succefully ..", module);
		} catch (SQLException se) {
			Debug.logError(se, module);

		} catch (Exception ex) {
			Debug.logError(ex, module);

		} finally {
			if (rs != null)
				try {
					rs.close();
				} catch (SQLException quiet) {
				}
			if (ps != null)
				try {
					ps.close();
				} catch (SQLException quiet) {
				}
			if (c != null)
				try {
					c.close();
				} catch (SQLException quiet) {
				}
		}
		return items;

	}
368113
public static int[] executeBatch(Connection conn, String... sqls) throws SQLException {
		return executeBatch(conn, new ArrayIter<String>(sqls));
	}
608208
@Override
    public InputStream getBinaryStream(int columnIndex) throws SQLException {
        checkColumnBounds(columnIndex);
        try {
            return new ByteArrayInputStream(
                    table.getStringAsBytes(columnIndex - 1));
        } catch (Exception x) {
            throw SQLError.get(x);
        }
    }
1351612
function(conn) {
  this._conn = conn;
  this._logger = conn._logger;
  var delegates = [
    "query",
    "queryMore",
    "create",
    "insert",
    "retrieve",
    "update",
    "upsert",
    "del",
    "delete",
    "destroy",
    "describe",
    "describeGlobal",
    "sobject"
  ];
  delegates.forEach(function(method) {
    this[method] = conn.constructor.prototype[method];
  }, this);

  this.cache = new Cache();

  var cacheOptions = {
    key: function(type) { return type ? "describe." + type : "describe"; }
  };
  this.describe$ = this.cache.makeCacheable(this.describe, this, cacheOptions);
  this.describe = this.cache.makeResponseCacheable(this.describe, this, cacheOptions);
  this.describeSObject$ = this.describe$;
  this.describeSObject = this.describe;

  cacheOptions = { key: 'describeGlobal' };
  this.describeGlobal$ = this.cache.makeCacheable(this.describeGlobal, this, cacheOptions);
  this.describeGlobal = this.cache.makeResponseCacheable(this.describeGlobal, this, cacheOptions);

  this.initialize();
}
1207748
public static Long executeForGeneratedKey(Connection conn, String sql, Object... params) throws SQLException {
		PreparedStatement ps = null;
		ResultSet rs = null;
		try {
			ps = StatementUtil.prepareStatement(conn, sql, params);
			ps.executeUpdate();
			rs = ps.getGeneratedKeys();
			if (rs != null && rs.next()) {
				try {
					return rs.getLong(1);
				} catch (SQLException e) {
					// 可能会出现没有主键返回的情况
				}
			}
			return null;
		} finally {
			DbUtil.close(ps);
			DbUtil.close(rs);
		}
	}