private function to execute a query
487908
function(query, data, successCallback, failureCallback) {
			if(typeof successCallback != "function") successCallback = function(){};
			if(typeof failureCallback != "function") failureCallback = function(){ return _throw(new jSQL_Error("0054")); };

			var i, l, remaining;

			if(!Array.isArray(data[0])) data = [data];
			remaining = data.length;
			var innerSuccessCallback = function(tx, rs) {
				var i, l, output = [];
				remaining = remaining - 1;
				if (!remaining) {
					for (i = 0, l = rs.rows.length; i < l; i = i + 1){
						var j = rs.rows.item(i).json;
						//j = JSON.parse(j);
						output.push(j);
					}
					successCallback(output);
				}
			};
			self.db.transaction(function (tx) {
				for (i = 0, l = data.length; i < l; i = i + 1) {
					tx.executeSql(query, data[i], innerSuccessCallback, failureCallback);
				}
			});
		}
1105512
function executeRelatedResultWithQuery (result, relatedName) {
    // get custom args for related model query
    var relatedArgs = this.args.with[relatedName]
    // get relation
    var relation = this.model.relation(relatedName)
    // build query args
    var queryArgs = {
        all: true,
        allow: this.args.allow,
        session: this.session,
        where: { relation: { name: this.model.name } },
    }
    // relation is via a linking table
    if (relation.via) {
        queryArgs.where.relation[relation.viaModelIdColumn] = result[relation.modelIdColumn] || result[model.defaultColumns[relation.modelIdColumn]]
    }
    // relation is direct
    else {
        queryArgs.where.relation[relation.relationIdColumn] = result[relation.modelIdColumn] || result[model.defaultColumns[relation.modelIdColumn]]
    }
    // merge args
    if (typeof relatedArgs === 'object') {
        _.merge(queryArgs, relatedArgs)
    }
    // do query on related model
    return relation.model.query(queryArgs)
    // merge related records once loaded
    .then(results => {
        result._related[relatedName] = results
    })
}
365631
function query (query) {
    // if cache is not connected immediately execute query and do not cache
    if (!this.redis.connected) {
        debug(`cache:${this.model.name}:false:redis:disconnected`)
        return query.executeQuery()
    }
    // build args for cache query instance
    var cacheQueryArgs = {
        cache: this,
        query: query,
    }
    // cache query object
    var cacheQuery
    // if query has views then cache after views are applied
    if (defined(query.modelViewEngine)) {
        // view query where underlying query is by id
        if (query.select.isSelectById) {
            // collection view is being applied
            if (query.modelViewEngine.hasCollection) {
                debug('cache:${this.model.name}:view:id:collection:true')
                // build cache query object
                cacheQuery = new ImmutableCoreModelCacheQueryViewIdCollection(cacheQueryArgs)
            }
            // only record view(s) being applied
            else {
                debug(`cache:${this.model.name}:view:id:record:true`)
                // build cache query object
                cacheQuery = new ImmutableCoreModelCacheQueryViewIdRecord(cacheQueryArgs)
            }
        }
        // view query where underlying query is select
        else if (query.select.isSelectOnlyIds && defined(query.model.columns.n)) {
            // if collection view is applied then cache result - if only
            // record view(s) are applied they are cached by id queries
            if (query.modelViewEngine.hasCollection) {
                debug(`cache:${this.model.name}:view:select:collection:true`)
                // build cache query object
                cacheQuery = new ImmutableCoreModelCacheQueryViewSelectCollection(cacheQueryArgs)
            }
        }
    }
    // if query is select by id then cache result
    else if (query.select.isSelectById) {
        debug(`cache:${this.model.name}:id:true`)
        // build cache query object
        cacheQuery = new ImmutableCoreModelCacheQueryId(cacheQueryArgs)
    }
    // if query has views then cache after views are applied
    else if (query.select.isSelectOnlyIds && defined(query.model.columns.n)) {
        debug(`cache:${this.model.name}:select:true`)
        // build cache query object
        cacheQuery = new ImmutableCoreModelCacheQuerySelect(cacheQueryArgs)
    }
    // execute cache query if available
    if (defined(cacheQuery)) {
        return cacheQuery.cacheQuery()
    }
    // execute original query uncached
    else {
        debug(`cache:${this.model.name}:false:unsupported`)
        return query.executeQuery()
    }
}
697472
function runQuery(query, connection) {
  const params = {
    host: connection.host,
    port: connection.port ? connection.port : 5433,
    user: connection.username,
    password: connection.password,
    database: connection.database
  };

  return new Promise((resolve, reject) => {
    const client = vertica.connect(params, function(err) {
      if (err) {
        client.disconnect();
        return reject(err);
      }

      let incomplete = false;
      const rows = [];
      let finished = false;
      let columnNames = [];

      const verticaQuery = client.query(query);

      verticaQuery.on('fields', fields => {
        columnNames = fields.map(field => field.name);
      });

      verticaQuery.on('row', function(row) {
        if (rows.length < connection.maxRows) {
          const resultRow = {};
          row.forEach((value, index) => {
            resultRow[columnNames[index]] = value;
          });
          return rows.push(resultRow);
        }
        if (!finished) {
          finished = true;
          client.disconnect();
          incomplete = true;
          return resolve({ rows, incomplete });
        }
      });

      verticaQuery.on('end', function() {
        if (!finished) {
          finished = true;
          client.disconnect();
          return resolve({ rows, incomplete });
        }
      });

      verticaQuery.on('error', function(err) {
        if (!finished) {
          finished = true;
          client.disconnect();
          return reject(err);
        }
      });
    });
  });
}
1037099
public function query($query) {
		$args = func_get_args();
		$query = array_shift($args);
		return $this->execute($query, $args);
	}
559940
function runQuery(query, connection) {
  const pgConfig = {
    user: connection.username,
    password: connection.password,
    database: connection.database,
    host: connection.host,
    ssl: connection.postgresSsl,
    stream: createSocksConnection(connection)
  };
  // TODO cache key/cert values
  if (connection.postgresKey && connection.postgresCert) {
    pgConfig.ssl = {
      key: fs.readFileSync(connection.postgresKey),
      cert: fs.readFileSync(connection.postgresCert)
    };
    if (connection.postgresCA) {
      pgConfig.ssl['ca'] = fs.readFileSync(connection.postgresCA);
    }
  }
  if (connection.port) pgConfig.port = connection.port;

  return new Promise((resolve, reject) => {
    const client = new pg.Client(pgConfig);
    client.connect(err => {
      if (err) {
        client.end();
        return reject(err);
      }
      const cursor = client.query(new PgCursor(query));
      return cursor.read(connection.maxRows + 1, (err, rows) => {
        if (err) {
          // pg_cursor can't handle multi-statements at the moment
          // as a work around we'll retry the query the old way, but we lose the maxRows protection
          return client.query(query, (err, result) => {
            client.end();
            if (err) {
              return reject(err);
            }
            return resolve({ rows: result.rows });
          });
        }
        let incomplete = false;
        if (rows.length === connection.maxRows + 1) {
          incomplete = true;
          rows.pop(); // get rid of that extra record. we only get 1 more than the max to see if there would have been more...
        }
        if (err) {
          reject(err);
        } else {
          resolve({ rows, incomplete });
        }
        cursor.close(err => {
          if (err) {
            console.log('error closing pg-cursor:');
            console.log(err);
          }
          // Calling end() without setImmediate causes error within node-pg
          setImmediate(() => {
            client.end(error => {
              if (error) {
                console.error(error);
              }
            });
          });
        });
      });
    });
  });
}
240534
function Query(server, query, options, token) {
  this.server = server;
  this.query = query;
  // Used to track the presence of r.args (workaround)
  this.originalQuery = util.deepCopy(query);
  this.options = {};
  this.context = {};
  this.frames = [];
  this.nowValue = ReqlDate.now();
  this.complete = false;
  this.token = token;

}
592834
def query(sql, *args, &block)
      fetched = nil
      execute do |dbh|
        result = dbh.execute(sql, *args)
        if block_given? then
          result.each(&block)
        else
          fetched = result.fetch(:all)
        end
        result.finish
      end
      fetched
    end
513661
function (query, params, stringifier) {
    if (!query || !query.length || !params) {
      return query;
    }
    if (!stringifier) {
      stringifier = function (a) {return a.toString()};
    }
    var parts = [];
    var isLiteral = false;
    var lastIndex = 0;
    var paramsCounter = 0;
    for (var i = 0; i < query.length; i++) {
      var char = query.charAt(i);
      if (char === "'" && query.charAt(i-1) !== '\\') {
        //opening or closing quotes in a literal value of the query
        isLiteral = !isLiteral;
      }
      if (!isLiteral && char === '?') {
        //is a placeholder
        parts.push(query.substring(lastIndex, i));
        parts.push(stringifier(params[paramsCounter++]));
        lastIndex = i+1;
      }
    }
    parts.push(query.substring(lastIndex));
    return parts.join('');
  }
1277769
public function execute($query = null, array $params = []) : object
    {
        // When using one argument and its array, assume its $params
        if (is_array($query)) {
            $params = $query;
            $query = null;
        }

        if (!$query) {
            $query = $this->getSQL();
        }

        return parent::execute($query, $params);
    }
638369
function execute(req, res) {
  //console.dir(req.args);
  var hmap = req.db.getKey(req.args[0], req);
  if(hmap === undefined) {
    return res.send(null, [0, []]);
  }
  //console.dir(hmap.getKeys())
  var scanner = new Scanner(
    hmap.getKeys(),
    req.info.cursor,
    req.info.pattern,
    req.info.count,
    hmap.data);

  scanner.scan(req, res);
}
1185724
def perform_query(self, query, **params):
        """"""
        try:
            return self.engine.execute(query, params)
        except:
            print("Error with query: {}".format(query))
            raise
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 };
}
334486
public function query($query, $params = []) {
		$statement = $this->get_statement($query, $params);
		$statement->execute();
	}
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 };
  });
}
681960
private ResultSet executeQuery(Query query, String tableName, Object... values) {
        m_logger.debug("Executing statement {} on table {}.{}; total params={}",
                       new Object[]{query, m_keyspace, tableName, values.length});
        try {
            PreparedStatement prepState = getPreparedQuery(query, tableName);
            BoundStatement boundState = prepState.bind(values);
            return m_session.execute(boundState);
        } catch (Exception e) {
            String params = "[" + Utils.concatenate(Arrays.asList(values), ",") + "]";
            m_logger.error("Query failed: query={}, keyspace={}, table={}, params={}; error: {}",
                           query, m_keyspace, tableName, params, e);
            throw e;
        }
    }
2020
function execute () {
    // check access and set access params
    this.accessControl()
    // build select
    this.select = sql.select(this.model, this.args)
    // debug
    debug(this.select.sql, this.select.params)
    // do query
    defined(this.model.cache)
        && this.args.cache !== false
        && (!this.modelViewEngine || this.modelViewEngine.cache !== false)
        ? this.executeQueryCached()
        : this.executeQueryDirect()
    // add queries for related records if any
    this.executeRelated()
    // build result
    return this.result()
}