Passes a connection from the connection pool so that we can call .run()
    on a query without an explicit connection
492772
def remodel_run(self, c=None, **global_optargs):
    

    if not c:
        with remodel.connection.get_conn() as conn:
            return run(self, conn, **global_optargs)
    else:
        return run(self, c, **global_optargs)
1069365
function Connection(socket, pool) {
    _classCallCheck(this, Connection);

    this.socket = socket;
    this.id = socket.id;
    this.pool = pool;
    this.incomingFilters = [];
  }
1178747
protected void internalReleaseConnection(ConnectionHandle connectionHandle) throws SQLException {
		if (!this.cachedPoolStrategy){
			connectionHandle.clearStatementCaches(false);
		}

		if (connectionHandle.getReplayLog() != null){
			connectionHandle.getReplayLog().clear();
			connectionHandle.recoveryResult.getReplaceTarget().clear();
		}

		if (connectionHandle.isExpired() || 
				(!this.poolShuttingDown 
						&& connectionHandle.isPossiblyBroken()
				&& !isConnectionHandleAlive(connectionHandle))){

            if (connectionHandle.isExpired()) {
                connectionHandle.internalClose();
            }

			ConnectionPartition connectionPartition = connectionHandle.getOriginatingPartition();
			postDestroyConnection(connectionHandle);

			maybeSignalForMoreConnections(connectionPartition);
			connectionHandle.clearStatementCaches(true);
			return; // don't place back in queue - connection is broken or expired.
		}


		connectionHandle.setConnectionLastUsedInMs(System.currentTimeMillis());
		if (!this.poolShuttingDown){
			putConnectionBackInPartition(connectionHandle);
		} else {
			connectionHandle.internalClose();
		}
	}
812956
async function runQuery(query, connection) {
  // Connection here doesn't actually matter.
  // Someday this mock could get fancy and change output based on some connection value
  // For now validate that it is getting passed
  const { maxRows } = connection;

  // To determine the content of this mock query, inspect values from comments
  // Example format
  // -- dimensions = department 10, color 10, product 10, orderdate|orderdatetime 500
  // -- measures = cost, revenue, profit, <anythingyouwant>
  // -- orderby = department asc, product desc
  // -- limit = 100
  const dimensions = [];
  const measures = [];
  const orderByFields = [];
  const orderByDirections = [];
  let limit;

  query
    .split('\n')
    .map(line => line.trim())
    .filter(line => line.startsWith('--'))
    .map(line => line.replace('--', ''))
    .forEach(line => {
      const [fieldType, fieldData] = line
        .split('=')
        .map(p => p.trim().toLowerCase());

      if (!fieldData) {
        return;
      }

      // fieldData is something like <fieldname> <direction>, <field2> <direction>
      // or 100
      fieldData
        .split(',')
        .map(p => p.trim())
        .forEach(part => {
          if (fieldType === 'limit') {
            limit = parseInt(part);
          } else if (fieldType === 'dimensions') {
            const [fieldName, numString] = part.split(' ').map(p => p.trim());
            if (!fieldValues[fieldName]) {
              throw new Error(
                `Unknown ${fieldName}. must be one of: ${Object.keys(
                  fieldValues
                ).join(', ')}`
              );
            }
            dimensions.push({
              name: fieldName,
              values: fieldValues[fieldName].slice(0, parseInt(numString))
            });
          } else if (fieldType === 'measures') {
            measures.push(part);
          } else if (fieldType === 'orderby') {
            const [fieldName, direction] = part.split(' ').map(p => p.trim());
            if (!direction) {
              throw new Error('direction required. Must be asc or desc');
            }
            orderByFields.push(fieldName);
            orderByDirections.push(direction);
          } else {
            throw new Error(
              `Unknown ${fieldType}. Must be dimensions, measures, orderby, or limit`
            );
          }
        });
    });

  if (!dimensions.length) {
    throw new Error('dimensions required');
  }

  // Assemble dimensions and things
  let rows = [];
  dimensions.forEach(dimension => {
    rows = cartesianify(rows, dimension);
  });

  if (measures.length) {
    rows.forEach(row => {
      measures.forEach(measure => {
        const date = row.orderdate || row.orderdatetime;
        if (date) {
          const doy = moment.utc(date).dayOfYear();
          row[measure] = 10 + Math.round(doy * Math.random());
        } else {
          row[measure] = Math.round(Math.random() * 1000);
        }
      });
    });
  }

  if (orderByFields.length) {
    rows = _.orderBy(rows, orderByFields, orderByDirections);
  }

  if (limit) {
    rows = rows.slice(0, limit);
  }

  return { rows: rows.slice(0, maxRows), incomplete: rows.length > maxRows };
}
745279
function runQuery(query, connection) {
  const { contactPoints, keyspace, maxRows } = connection;

  const client = new cassandra.Client({
    contactPoints: contactPoints.split(',').map(cp => cp.trim()),
    keyspace
  });

  return client
    .execute(query, [], { fetchSize: maxRows })
    .then(result => {
      shutdownClient(client);
      const incomplete = result.rows && result.rows.length === maxRows;
      return { rows: result.rows, incomplete };
    })
    .catch(error => {
      shutdownClient(client);
      throw error;
    });
}
871134
async def connect(self):
        '''
        '''
        assert not self.closed
        connection = await self._get()
        return PoolConnection(self, connection)
1163343
function runQuery(query, connection) {
  let incomplete = false;
  const rows = [];

  const drillConfig = {
    host: connection.host,
    port: connection.port,
    user: connection.username,
    password: connection.password,
    defaultSchema: connection.drillDefaultSchema,
    ssl: connection.ssl || false
  };
  const client = new drill.Client(drillConfig);

  return client.query(drillConfig, query).then(result => {
    if (!result) {
      throw new Error('No result returned');
    } else if (result.errorMessage && result.errorMessage.length > 0) {
      console.log('Error with query: ' + query);
      console.log(result.errorMessage);
      throw new Error(result.errorMessage.split('\n')[0]);
    }
    if (result.length > connection.maxRows) {
      incomplete = true;
      result['rows'] = result['rows'].slice(0, connection.maxRows);
    }
    for (let r = 0; r < result['rows'].length; r++) {
      const row = {};
      for (let c = 0; c < result['columns'].length; c++) {
        row[result['columns'][c]] = result['rows'][r][result['columns'][c]];
      }
      rows.push(row);
    }
    return { rows, incomplete };
  });
}
531007
@Override
	final public void run() {
		while(true) {
			try {
				try {
					sleep(delayTime);
				} catch(InterruptedException err) {
					logger.log(Level.WARNING, null, err);
				}
				long time = System.currentTimeMillis();
				List<C> connsToClose;
				synchronized(poolLock) {
					if(isClosed) return;
					// Find any connections that are available and been idle too long
					int maxIdle = maxIdleTime;
					connsToClose = new ArrayList<>(availableConnections.size());
					for(PooledConnection<C> availableConnection : availableConnections) {
						synchronized(availableConnection) {
							C conn = availableConnection.connection;
							if(conn!=null) {
								if(
									(time-availableConnection.releaseTime) > maxIdle // Idle too long
									|| (
										maxConnectionAge!=UNLIMITED_MAX_CONNECTION_AGE
										&& (
											availableConnection.createTime > time // System time reset?
											|| (time-availableConnection.createTime) >= maxConnectionAge // Max connection age reached
										)
									)
								) {
									availableConnection.connection = null;
									connsToClose.add(conn);
								}
							}
						}
					}
				}
				// Close all of the connections
				for(C conn : connsToClose) {
					try {
						close(conn);
					} catch(Exception err) {
						logger.log(Level.WARNING, null, err);
					}
				}
			} catch (ThreadDeath TD) {
				throw TD;
			} catch (Throwable T) {
				logger.logp(Level.SEVERE, AOPool.class.getName(), "run", null, T);
			}
		}
	}
316369
void connectionCloses(final Session connection) {
        synchronized (connections) {
            final ExecutorService executorService = connectionThreads.get(connection);
            if (executorService != null) {
                executorService.shutdownNow();
            }
            connectionThreads.remove(connection);
            connections.remove(connection);
        }
    }
1297904
function runQuery(query, connection) {
  const config = {
    user: connection.username,
    password: connection.password,
    connection_string: connection.connection_string
  };
  // TODO use connection pool
  // TODO handle connection.maxRows

  let cn = config.connection_string;

  // Not all drivers require auth
  if (config.user) {
    cn = cn + ';Uid=' + config.user;
  }
  if (config.password) {
    cn = cn + ';Pwd=' + config.password;
  }

  return openConnection(cn)
    .then(() => executeQuery(query))
    .then(queryResult => {
      odbc.close(); // TODO consider putting into finally()?
      return Promise.resolve({ rows: queryResult, incomplete: false });
    })
    .catch(function(e) {
      console.error(e, e.stack);
    });
}
1189373
def execute_query_return_result_proxy(query):
    
    context = query._compile_context()
    context.statement.use_labels = False
    if query._autoflush and not query._populate_existing:
        query.session._autoflush()

    conn = query._get_bind_args(
        context,
        query._connection_from_session,
        close_with_result=True)

    return conn.execute(context.statement, query._params)
228118
def run_to_queue(self, queue, conn, options=None, dsquery=None):
    """"""
    try:
      multiquery = self._maybe_multi_query()
      if multiquery is not None:
        yield multiquery.run_to_queue(queue, conn, options=options)
        return

      if dsquery is None:
        dsquery = self._get_query(conn)
      rpc = dsquery.run_async(conn, options)
      while rpc is not None:
        batch = yield rpc
        if (batch.skipped_results and
            datastore_query.FetchOptions.offset(options)):
          offset = options.offset - batch.skipped_results
          options = datastore_query.FetchOptions(offset=offset, config=options)
        rpc = batch.next_batch_async(options)
        for i, result in enumerate(batch.results):
          queue.putq((batch, i, result))
      queue.complete()

    except GeneratorExit:
      raise
    except Exception:
      if not queue.done():
        _, e, tb = sys.exc_info()
        queue.set_exception(e, tb)
      raise
6170
public static ResultSet callQuery(Connection conn, String sql, Object... params) throws SQLException {
		CallableStatement proc = null;
		try {
			proc = StatementUtil.prepareCall(conn, sql, params);
			return proc.executeQuery();
		} finally {
			DbUtil.close(proc);
		}
	}
790105
@Local
    @Override
    public <V> V directQuery(String sql, Function<ResultSet, V> handler) {
        final Connection conn = readPool.poll();
        try {
            if (logger.isLoggable(Level.FINEST)) logger.finest("direct query sql=" + sql);
            conn.setReadOnly(true);
            final Statement statement = conn.createStatement();
            //final PreparedStatement statement = conn.prepareStatement(sql, ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY);
            final ResultSet set = statement.executeQuery(sql);// ps.executeQuery();
            V rs = handler.apply(set);
            set.close();
            statement.close();
            return rs;
        } catch (Exception ex) {
            throw new RuntimeException(ex);
        } finally {
            if (conn != null) readPool.offerConnection(conn);
        }
    }
1269700
public Collector<T> getResults(Connection conn, DataObject object, Collector<T> collector) throws Exception {
        return executeSelect(conn, object, new ResultSetMapper<Collector<T>>(collector));
    }
1183139
function (connectionInfo, query, params) {
    var connection;

    // Connection validation
    if (typeof connectionInfo.host !== 'string' || connectionInfo.host.length === 0) {
        return respond({
            success: false,
            data: {
                err: 'Bad hostname provided.',
                query: query,
                connection: connectionInfo
            }
        });
    }
    if (typeof connectionInfo.user !== 'string' || connectionInfo.user.length === 0) {
        return respond({
            success: false,
            data: {
                err: 'Bad username provided.',
                query: query,
                connection: connectionInfo
            }
        });
    }

    if (typeof connectionInfo.password !== 'string') {
        return respond({
            success: false,
            data: {
                err: 'Bad password provided.',
                query: query,
                connection: connectionInfo
            }
        });
    }
    if (typeof connectionInfo.database !== 'string' || connectionInfo.database.length === 0) {
        return respond({
            success: false,
            data: {
                err: 'Bad database provided.',
                query: query,
                connection: connectionInfo
            }
        });
    }


    // Return if no sql query specified
    if (query.length === 0) {
        return respond({
            success: false,
            data: {
                err: 'No SQL query specified.'
            }
        });
    }

    // Create the connection to the database
    connection = mysql.createConnection(connectionInfo);

    // Connect to the database
    connection.connect();

    // Do the query
    connection.query(query, params, function (err, rows, fields) {
        // End the connection
        connection.end();

        // Return the error and stop
        if (err) {
            return respond({
                success: false,
                data: {
                    err: err,
                    query: query,
                    connection: connectionInfo
                }

            });
        }

        // Do the callback
        respond({
            success: true,
            data: {
                rows: rows,
                fields: fields
            }
        });
    });
}
277688
function runQuery(query, connection) {
  const incomplete = false;

  return new Promise((resolve, reject) => {
    const client = hdb.createClient({
      host: connection.host,
      port: connection.hanaport,
      database: connection.hanadatabase,
      user: connection.username,
      password: connection.password,
      schema: connection.hanaSchema
    });

    client.on('error', err => {
      console.error('Network connection error', err);
      return reject(err);
    });

    client.connect(err => {
      if (err) {
        console.error('Connect error', err);
        return reject(err);
      }
      return client.execute(query, function(err, rs) {
        let rows = [];

        if (err) {
          client.disconnect();
          return reject(err);
        }

        if (!rs) {
          client.disconnect();
          return resolve({ rows, incomplete });
        }

        if (!rs.createObjectStream) {
          // Could be row count or something
          client.disconnect();
          return resolve({ rows: [{ result: rs }], incomplete });
        }

        const stream = rs.createObjectStream();

        stream.on('data', data => {
          if (rows.length < connection.maxRows) {
            return rows.push(data);
          }
          client.disconnect();
          return resolve({ rows, incomplete: true });
        });

        stream.on('error', error => {
          client.disconnect();
          return reject(error);
        });

        stream.on('finish', () => {
          client.disconnect();
          return resolve({ rows, incomplete });
        });
      });
    });
  });
}