Query

Runs a SQL query against the database using Oriento's query method
Will attempt to convert @rid's into ids.

@param {Object} connection
@param {Object} collection
@param {String} query
@param {String} options
@param {Object} cb
429863
function(connection, collection, query, options, cb) {
      return connections[connection].query(query, options, cb);
    }
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 });
        });
      });
    });
  });
}
94163
def execute_query(self, query, session):
		'''  '''
		self.auto_ensure_indexes(query.type)

		kwargs = dict()
		if query._get_fields():
			if PYMONGO_3: # pragma: nocover
				kwargs['projection'] = query._fields_expression()
			else: # pragma: nocover
				kwargs['fields'] = query._fields_expression()

		collection = self.db[query.type.get_collection_name()]
		
		if query._search:
			index_fields = query._createIndex
			if index_fields:
				# create new index
				if type(index_fields) is list:
					index_list = []
					for field in index_fields:
						index_list.append ((field, pymongo.TEXT))
					collection.create_index(index_list, name='search_index', default_language='english')
				else:
					raise InvalidConfigException()
			cursor = collection.find(query.query, {'__index_score': {'$meta': "textScore"}}, **kwargs)
			cursor.sort([('__index_score', {'$meta': 'textScore'})])
		elif query._rawquery:
			if query._query_type=='aggregate':
				cursor = collection.aggregate(query.query, cursor={}, **kwargs)
			elif query._query_type=='map_reduce':
				cursor = collection.map_reduce( query._mapreduce_mapper, query._mapreduce_reducer, query._mapreduce_key, query=query._mapreduce_query)
		else:
			cursor = collection.find(query.query, **kwargs)

		if query._sort:
			cursor.sort(query._sort)
		elif query.type.config_default_sort:
			cursor.sort(query.type.config_default_sort)
		if query.hints:
			cursor.hint(query.hints)
		if query._get_limit() is not None:
			cursor.limit(query._get_limit())
		if query._get_skip() is not None:
			cursor.skip(query._get_skip())
		return QueryResult(session, cursor, query.type, raw_output=query._raw_output, fields=query._get_fields())
201266
function all(options, cb) {
  var q
    , page = Number(options.page) || 1
    , limit = Number(options.limit) || conf.objects_by_page
    , offset = (page - 1) * limit;

  count(function(err, count) {
    if(err) { return cb(err); }

    q = select('LEFT JOIN');
    q += ' LIMIT ' + limit + ' OFFSET ' + offset;

    db.getClient(function(err, client, done) {
      client.query(q, function(err, r) {
        if(err) {
          cb(err);
          done(err);
        } else {
          cb(null, {
            rows: r.rows,
            count: count,
            limit: limit,
            offset: offset,
            page: page
          });
          done();
        }
      });
    });
  });
}
148680
function (query, options) {
            options.$itemsCount = undefined;

            var collection = new this.factory(null, options);
            collection.$context = this.$context;

            return collection;
        }
410173
def no_sql_connection(options={}, &block)
      @no_sql_connection ||= Mongify::Database::NoSqlConnection.new(options)
      @no_sql_connection.instance_exec(&block) if block_given?
      @no_sql_connection
    end
321188
def query(database, query, **client_args):
    '''
    
    '''
    client = _client(**client_args)
    _result = client.query(query, database=database)

    if isinstance(_result, collections.Sequence):
        return [_pull_query_results(_query_result) for _query_result in _result if _query_result]
    return [_pull_query_results(_result) if _result else {}]
95097
protected function run($query, $bindings, Closure $callback) {
        $start = microtime(true);

        // To execute the statement, we'll simply call the callback, which will actually
        // run the Cypher against the Orientdb connection. Then we can calculate the time it
        // took to execute and log the query Cypher, bindings and time in our memory.
        try {
            $result = $callback($this, $query, $bindings);
        }

        // If an exception occurs when attempting to run a query, we'll format the error
        // message to include the bindings with Cypher, which will make this exception a
        // lot more helpful to the developer instead of just the database's errors.
        catch (\Exception $e) {
            throw new QueryException($query, $bindings, $e);
        }

        // Once we have run the query we will calculate the time that it took to run and
        // then log the query, bindings, and execution time so we will report them on
        // the event that the developer needs them. We'll log time in milliseconds.
        $time = $this->getElapsedTime($start);

        $this->logQuery($query, $bindings, $time);

        return $result;
    }
1175009
function runQuery(query, connection) {
  const myConnection = mysql.createConnection({
    multipleStatements: true,
    host: connection.host,
    port: connection.port ? connection.port : 3306,
    user: connection.username,
    password: connection.password,
    database: connection.database,
    insecureAuth: connection.mysqlInsecureAuth,
    timezone: 'Z',
    supportBigNumbers: true
  });

  return new Promise((resolve, reject) => {
    let incomplete = false;
    const rows = [];

    myConnection.connect(err => {
      if (err) {
        return reject(err);
      }
      let queryError;
      let resultsSent = false;

      function continueOn() {
        if (!resultsSent) {
          resultsSent = true;
          if (queryError) {
            return reject(queryError);
          }
          return resolve({ rows, incomplete });
        }
      }

      const myQuery = myConnection.query(query);
      myQuery
        .on('error', function(err) {
          // Handle error,
          // an 'end' event will be emitted after this as well
          // so we'll call the callback there.
          queryError = err;
        })
        .on('result', function(row) {
          // If we haven't hit the max yet add row to results
          if (rows.length < connection.maxRows) {
            return rows.push(row);
          }

          // Too many rows
          incomplete = true;

          // Stop the query stream
          myConnection.pause();

          // Destroy the underlying connection
          // Calling end() will wait and eventually time out
          myConnection.destroy();
          continueOn();
        })
        .on('end', function() {
          // all rows have been received
          // This will not fire if we end the connection early
          // myConnection.end()
          // myConnection.destroy()
          myConnection.end(error => {
            if (error) {
              console.error('Error ending MySQL connection', error);
            }
            continueOn();
          });
        });
    });
  });
}
678094
function query (query, params, options, session) {
    // require string for query
    if (typeof query !== 'string') {
        throw new Error('query error: query must be string')
    }
    // validate optional args - create objects if not passed in
    options = requireValidOptionalObject(options)
    params = requireValidOptionalObject(params)
    session = requireValidOptionalObject(session)
    // if the no insert flag is set then do not run insert queries
    if (session.noInsert && query.match(/^\s*INSERT/i)) {
        return Promise.resolve()
    }
    // get unique if for query
    var dbQueryId = randomUniqueId()
    // log query start
    this.logQuery(query, params, options, session, dbQueryId)
    // perform query using promisified interface
    return this.client.queryPromise(query, params, options)
    // success
    .then(res => {
        // perform formatting on response data
        formatResponse(res)
        // log response
        this.logQueryResponse(dbQueryId, options, res)
        // resolve with response data
        return res
    })
    // error
    .catch(err => {
        // log error
        this.logQueryError(dbQueryId, options, err)
        // reject with error
        return Promise.reject(err)
    })
}
605564
function ResultSet(conn, query, values, options, rs) {
  this.query = query;
  this.metadata = rs.metadata;
  this.rows = rs.rows;
  this._conn = conn;
  this._values = values;
  this._options = options;
}
728311
function(cb) {

            var collection = connectionObject.collections[collectionName];
            if (!collection) return cb(Errors.CollectionNotRegistered);

            collection.dropTable(function(err) {
              // ignore "table does not exist" error
              if (err && err.code === 8704) return cb();
              if (err) return cb(err);
              cb();
            });
          }
441147
public <T> T execute(final String query, final Object connection,
        final List<KunderaQuery.BindParameter> parameters) {
        throw new KunderaException("not implemented");
    }
898471
public List<Entity> query(Query query, FetchOptions options) {
		return datastore.prepare(query).asList(options);
	}
1034251
function(query) {
	//	console.log(query);
	// Loop over all sources
	// Todo: make this loop smaller and more graspable
	for (var k = 0, klen = query.sources.length; k < klen; k++) {
		var source = query.sources[k];
		delete source.ix;
		// If there is indexation rule
		//console.log('preIndex', source);
		//console.log(source);
		if (k > 0 && source.optimization == 'ix' && source.onleftfn && source.onrightfn) {
			// If there is no table.indices - create it
			if (source.databaseid && alasql.databases[source.databaseid].tables[source.tableid]) {
				if (!alasql.databases[source.databaseid].tables[source.tableid].indices)
					query.database.tables[source.tableid].indices = {};
				// Check if index already exists
				var ixx =
					alasql.databases[source.databaseid].tables[source.tableid].indices[
						hash(source.onrightfns + '`' + source.srcwherefns)
					];
				if (!alasql.databases[source.databaseid].tables[source.tableid].dirty && ixx) {
					source.ix = ixx;
				}
			}

			if (!source.ix) {
				source.ix = {};
				// Walking over source data
				var scope = {};
				var i = 0;
				var ilen = source.data.length;
				var dataw;
				//				while(source.getfn i<ilen) {

				while (
					(dataw = source.data[i]) ||
					(source.getfn && (dataw = source.getfn(i))) ||
					i < ilen
				) {
					if (source.getfn && !source.dontcache) source.data[i] = dataw;
					//					scope[tableid] = dataw;

					//				for(var i=0, ilen=source.data.length; i<ilen; i++) {
					// Prepare scope for indexation
					scope[source.alias || source.tableid] = dataw;

					// Check if it apply to where function
					if (source.srcwherefn(scope, query.params, alasql)) {
						// Create index entry for each address
						var addr = source.onrightfn(scope, query.params, alasql);
						var group = source.ix[addr];
						if (!group) {
							group = source.ix[addr] = [];
						}
						group.push(dataw);
					}
					i++;
				}

				if (
					source.databaseid &&
					alasql.databases[source.databaseid].tables[source.tableid]
				) {
					// Save index to original table
					alasql.databases[source.databaseid].tables[source.tableid].indices[
						hash(source.onrightfns + '`' + source.srcwherefns)
					] =
						source.ix;
				}
			}
			//console.log(38,274,source.ix);

			// Optimization for WHERE column = expression
		} else if (source.wxleftfn) {
			if (!alasql.databases[source.databaseid].engineid) {
				// Check if index exists
				ixx =
					alasql.databases[source.databaseid].tables[source.tableid].indices[
						hash(source.wxleftfns + '`')
					];
			}
			if (!alasql.databases[source.databaseid].tables[source.tableid].dirty && ixx) {
				// Use old index if exists
				source.ix = ixx;
				// Reduce data (apply filter)
				source.data = source.ix[source.wxrightfn(null, query.params, alasql)];
			} else {
				// Create new index
				source.ix = {};
				// Prepare scope
				scope = {};
				// Walking on each source line
				i = 0;
				ilen = source.data.length;
				dataw;
				//				while(source.getfn i<ilen) {

				while (
					(dataw = source.data[i]) ||
					(source.getfn && (dataw = source.getfn(i))) ||
					i < ilen
				) {
					if (source.getfn && !source.dontcache) source.data[i] = dataw;
					//					for(var i=0, ilen=source.data.length; i<ilen; i++) {
					scope[source.alias || source.tableid] = source.data[i];
					// Create index entry
					addr = source.wxleftfn(scope, query.params, alasql);
					group = source.ix[addr];
					if (!group) {
						group = source.ix[addr] = [];
					}
					group.push(source.data[i]);
					i++;
				}
				//					query.database.tables[source.tableid].indices[hash(source.wxleftfns+'`'+source.onwherefns)] = source.ix;
				if (!alasql.databases[source.databaseid].engineid) {
					alasql.databases[source.databaseid].tables[source.tableid].indices[
						hash(source.wxleftfns + '`')
					] =
						source.ix;
				}
			}
			// Apply where filter to reduces rows
			if (source.srcwherefns) {
				if (source.data) {
					scope = {};
					source.data = source.data.filter(function(r) {
						scope[source.alias] = r;
						return source.srcwherefn(scope, query.params, alasql);
					});
				} else {
					source.data = [];
				}
			}
			//			}
			// If there is no any optimization than apply srcwhere filter
		} else if (source.srcwherefns && !source.dontcache) {
			if (source.data) {
				var scope = {};
				// TODO!!!!! Data as Function

				source.data = source.data.filter(function(r) {
					scope[source.alias] = r;
					//					console.log(288,source);
					return source.srcwherefn(scope, query.params, alasql);
				});

				scope = {};
				i = 0;
				ilen = source.data.length;
				//var dataw;
				var res = [];
				//				while(source.getfn i<ilen) {

				while (
					(dataw = source.data[i]) ||
					(source.getfn && (dataw = source.getfn(i))) ||
					i < ilen
				) {
					if (source.getfn && !source.dontcache) source.data[i] = dataw;
					scope[source.alias] = dataw;
					if (source.srcwherefn(scope, query.params, alasql)) res.push(dataw);
					i++;
				}
				source.data = res;
			} else {
				source.data = [];
			}
		}
		// Change this to another place (this is a wrong)
		if (source.databaseid && alasql.databases[source.databaseid].tables[source.tableid]) {
			//query.database.tables[source.tableid].dirty = false;
		} else {
			// this is a subquery?
		}
	}
}
570871
function query (args) {
    // get relation
    var relation = this.model.relation(args.relation)
    // delete relation name from args so it wont pass to query
    delete args.relation
    // build query args
    var queryArgs = {
        session: args.session || this.session,
        where: { relation: { name: this.model.name } },
    }
    // relation is via a linking table
    if (relation.via) {
        // query by current records ids
        queryArgs.where.relation[relation.viaModelIdColumn] = this[this.model.defaultColumns[relation.modelIdColumn]]
    }
    // relation is direct
    else {
        // query by current records ids
        queryArgs.where.relation[relation.relationIdColumn] = this[this.model.defaultColumns[relation.modelIdColumn]]
    }
    // merge args
    _.merge(queryArgs, args)
    // do query on related model
    return relation.model.query(queryArgs)
}
384557
function(connection, collection, definition, cb) {
      log.debug('define:', collection);

      // Create the collection and indexes
      connections[connection].createCollection(collection, definition, cb);
    }