For queries like http://localhost/NorthWind.svc/Orders(10643)/Customer
491391
public function getRelatedResourceReference(
        ResourceSet $sourceResourceSet,
        $sourceEntityInstance,
        ResourceSet $targetResourceSet,
        ResourceProperty $targetProperty
    ) {
        $entityClassName = $targetResourceSet->getResourceType()->getInstanceType()->name;
        $entityName = $this->getEntityName($entityClassName);
        $fieldName = $this->getTableName($entityName) . '_id';

        return $this->getResource($targetResourceSet, null, [
            'id' => $sourceEntityInstance->$fieldName
        ]);
    }
1303170
function QueryWhere(data)
{
	//Initialize the string
	var sql = '';

	//Check the type
	if(typeof data === 'string')
	{
		//Return the where
		return data;
	}

	//Get all data
	for(var key in data)
	{
		//Save data value
		var value = data[key];

		//Check the data type
		if(typeof value === 'string' || value instanceof String)
		{
			//Add the quotes
			value = '"' + value + '"';
		}

		//Check if is necessary add the AND
		if(sql !== '')
		{
			//Add the AND
			sql = sql + ' AND ';
		}

		//Add the key=value
		sql = sql + key + '=' + value;
	}

	//Return the string
	return sql;
}
29405
def query_conditions(query)
      if query.limit || query.links.any?
        query.to_subquery
      else
        query.conditions
      end
    end
547448
public function performsql()
    {
        $oAuthUser = oxNew(\OxidEsales\Eshop\Application\Model\User::class);
        $oAuthUser->loadAdminUser();
        if ($oAuthUser->oxuser__oxrights->value === "malladmin") {
            $sUpdateSQL = \OxidEsales\Eshop\Core\Registry::getConfig()->getRequestParameter("updatesql");
            $sUpdateSQLFile = $this->_processFiles();

            if ($sUpdateSQLFile && strlen($sUpdateSQLFile) > 0) {
                if (isset($sUpdateSQL) && strlen($sUpdateSQL)) {
                    $sUpdateSQL .= ";\r\n" . $sUpdateSQLFile;
                } else {
                    $sUpdateSQL = $sUpdateSQLFile;
                }
            }

            $sUpdateSQL = trim(stripslashes($sUpdateSQL));
            $oStr = getStr();
            $iLen = $oStr->strlen($sUpdateSQL);
            if ($this->_prepareSQL($sUpdateSQL, $iLen)) {
                $aQueries = $this->aSQLs;
                $this->_aViewData["aQueries"] = [];
                $aPassedQueries = [];
                $aQAffectedRows = [];
                $aQErrorMessages = [];
                $aQErrorNumbers = [];

                if (!empty($aQueries) && is_array($aQueries)) {
                    $blStop = false;
                    $oDB = \OxidEsales\Eshop\Core\DatabaseProvider::getDb();
                    $iQueriesCounter = 0;
                    for ($i = 0; $i < count($aQueries); $i++) {
                        $sUpdateSQL = $aQueries[$i];
                        $sUpdateSQL = trim($sUpdateSQL);

                        if ($oStr->strlen($sUpdateSQL) > 0) {
                            $aPassedQueries[$iQueriesCounter] = nl2br(\OxidEsales\Eshop\Core\Str::getStr()->htmlentities($sUpdateSQL));
                            if ($oStr->strlen($aPassedQueries[$iQueriesCounter]) > 200) {
                                $aPassedQueries[$iQueriesCounter] = $oStr->substr($aPassedQueries[$iQueriesCounter], 0, 200) . "...";
                            }

                            while ($sUpdateSQL[$oStr->strlen($sUpdateSQL) - 1] == ";") {
                                $sUpdateSQL = $oStr->substr($sUpdateSQL, 0, ($oStr->strlen($sUpdateSQL) - 1));
                            }

                            $aQAffectedRows [$iQueriesCounter] = null;
                            $aQErrorMessages[$iQueriesCounter] = null;
                            $aQErrorNumbers [$iQueriesCounter] = null;

                            try {
                                $aQAffectedRows[$iQueriesCounter] = $oDB->execute($sUpdateSQL);
                            } catch (Exception $exception) {
                                // Report errors
                                $aQErrorMessages[$iQueriesCounter] = \OxidEsales\Eshop\Core\Str::getStr()->htmlentities($exception->getMessage());
                                $aQErrorNumbers[$iQueriesCounter] = \OxidEsales\Eshop\Core\Str::getStr()->htmlentities($exception->getCode());
                                // Trigger breaking the loop
                                $blStop = true;
                            }

                            $iQueriesCounter++;

                            // stopping on first error..
                            if ($blStop) {
                                break;
                            }
                        }
                    }
                }
                $this->_aViewData["aQueries"] = $aPassedQueries;
                $this->_aViewData["aAffectedRows"] = $aQAffectedRows;
                $this->_aViewData["aErrorMessages"] = $aQErrorMessages;
                $this->_aViewData["aErrorNumbers"] = $aQErrorNumbers;
            }
            $this->_iDefEdit = 1;
        }
    }
905974
function query(queryString, args, callback) {
  getClient(function (err, client) {
    if (err) { callback(err); }

    if (!client) {
      callback('Could not connect to the database');
    }
    else {
      runQuery(client, queryString, args, callback);
    }
  });
}
1244909
def query(query_str)
      # puts "conent #{content}"
      res = conn.post '/query/', {query: query_str, time: Time.now.to_i}.to_json do |req|
        req.headers['Content-Type'] = 'application/json'
        req.headers['X-Requested-With'] = 'XMLHttpRequest'
        req['Cookie'] = "csrftoken=#{csrf_token}"
        req.headers['X-CSRFToken'] = csrf_token
      end
      JSON.parse(res.body)
   end
1145663
def query(action=None,
          command=None,
          args=None,
          method='GET',
          location=None,
          data=None):
    '''
    
    '''
    user = config.get_cloud_config_value(
        'user', get_configured_provider(), __opts__, search_global=False
    )

    if not user:
        log.error('username is required for Joyent API requests. Please set one in your provider configuration')

    password = config.get_cloud_config_value(
        'password', get_configured_provider(), __opts__,
        search_global=False
    )

    verify_ssl = config.get_cloud_config_value(
        'verify_ssl', get_configured_provider(), __opts__,
        search_global=False, default=True
    )

    ssh_keyfile = config.get_cloud_config_value(
        'private_key', get_configured_provider(), __opts__,
        search_global=False, default=True
    )

    if not ssh_keyfile:
        log.error('ssh_keyfile is required for Joyent API requests.  Please set one in your provider configuration')

    ssh_keyname = config.get_cloud_config_value(
        'keyname', get_configured_provider(), __opts__,
        search_global=False, default=True
    )

    if not ssh_keyname:
        log.error('ssh_keyname is required for Joyent API requests.  Please set one in your provider configuration')

    if not location:
        location = get_location()

    api_host_suffix = config.get_cloud_config_value(
        'api_host_suffix', get_configured_provider(), __opts__,
        search_global=False, default=JOYENT_API_HOST_SUFFIX
    )

    path = get_location_path(location=location, api_host_suffix=api_host_suffix)

    if action:
        path += action

    if command:
        path += '/{0}'.format(command)

    log.debug('User: \'%s\' on PATH: %s', user, path)

    if (not user) or (not ssh_keyfile) or (not ssh_keyname) or (not location):
        return None

    timenow = datetime.datetime.utcnow()
    timestamp = timenow.strftime('%a, %d %b %Y %H:%M:%S %Z').strip()
    rsa_key = salt.crypt.get_rsa_key(ssh_keyfile, None)
    if HAS_M2:
        md = EVP.MessageDigest('sha256')
        md.update(timestamp.encode(__salt_system_encoding__))
        digest = md.final()
        signed = rsa_key.sign(digest, algo='sha256')
    else:
        rsa_ = PKCS1_v1_5.new(rsa_key)
        hash_ = SHA256.new()
        hash_.update(timestamp.encode(__salt_system_encoding__))
        signed = rsa_.sign(hash_)
    signed = base64.b64encode(signed)
    user_arr = user.split('/')
    if len(user_arr) == 1:
        keyid = '/{0}/keys/{1}'.format(user_arr[0], ssh_keyname)
    elif len(user_arr) == 2:
        keyid = '/{0}/users/{1}/keys/{2}'.format(user_arr[0], user_arr[1], ssh_keyname)
    else:
        log.error('Malformed user string')

    headers = {
        'Content-Type': 'application/json',
        'Accept': 'application/json',
        'X-Api-Version': JOYENT_API_VERSION,
        'Date': timestamp,
        'Authorization': 'Signature keyId="{0}",algorithm="rsa-sha256" {1}'.format(
            keyid,
            signed.decode(__salt_system_encoding__)
        ),
    }

    if not isinstance(args, dict):
        args = {}

    # post form data
    if not data:
        data = salt.utils.json.dumps({})

    return_content = None
    result = salt.utils.http.query(
        path,
        method,
        params=args,
        header_dict=headers,
        data=data,
        decode=False,
        text=True,
        status=True,
        headers=True,
        verify_ssl=verify_ssl,
        opts=__opts__,
    )
    log.debug('Joyent Response Status Code: %s', result['status'])
    if 'headers' not in result:
        return [result['status'], result['error']]

    if 'Content-Length' in result['headers']:
        content = result['text']
        return_content = salt.utils.yaml.safe_load(content)

    return [result['status'], return_content]
1370794
public function httpQuery()
    {

        //echo ini_get('allow_url_fopen');
        //if (ini_get('allow_url_fopen'))
        $lines = @file($this->query['server']);

        if (!$lines) {
            return false;
        }

        $output = '';
        $pre = '';

        while (list($key, $val) = each($lines)) {
            $val = trim($val);

            $pos = strpos(strtoupper($val), '<PRE>');
            if ($pos !== false) {
                $pre = "\n";
                $output .= substr($val, 0, $pos) . "\n";
                $val = substr($val, $pos + 5);
            }
            $pos = strpos(strtoupper($val), '</PRE>');
            if ($pos !== false) {
                $pre = '';
                $output .= substr($val, 0, $pos) . "\n";
                $val = substr($val, $pos + 6);
            }
            $output .= $val . $pre;
        }

        $search = array(
            '<BR>', '<P>', '</TITLE>',
            '</H1>', '</H2>', '</H3>',
            '<br>', '<p>', '</title>',
            '</h1>', '</h2>', '</h3>');

        $output = str_replace($search, "\n", $output);
        $output = str_replace('<TD', ' <td', $output);
        $output = str_replace('<td', ' <td', $output);
        $output = str_replace('<tr', "\n<tr", $output);
        $output = str_replace('<TR', "\n<tr", $output);
        $output = str_replace('&nbsp;', ' ', $output);
        $output = strip_tags($output);
        $output = explode("\n", $output);

        $rawdata = array();
        $null = 0;

        while (list($key, $val) = each($output)) {
            $val = trim($val);
            if ($val == '') {
                if (++$null > 2) {
                    continue;
                }
            } else {
                $null = 0;
            }
            $rawdata[] = $val;
        }
        return $rawdata;
    }
179273
def list_customers(self, params=None):
        """"""
        request = self._get('customers', params)
        return self.responder(request)
1329655
@Override
    public ClientResponse doHandle(ClientRequest cr) {
        UriBuilder newUri = UriBuilder.fromUri(cr.getURI());
        String currentQuery = cr.getURI().getRawQuery();
        if (currentQuery == null) {
            currentQuery = "";
        } else if (currentQuery.length() > 0) {
            currentQuery += "&";
        }
        currentQuery += "api-version=2016-05-31&" + sasToken;

        newUri.replaceQuery(currentQuery);
        cr.setURI(newUri.build());

        return getNext().handle(cr);
    }
883048
private function getAllUrlAliasesQuery(): string
    {
        $existingAliasesQueryBuilder = $this->connection->createQueryBuilder();
        $innerQueryBuilder = $this->connection->createQueryBuilder();

        return $existingAliasesQueryBuilder
            ->select('tmp.id')
            ->from(
                // nest subquery to avoid same-table update error
                '(' . $innerQueryBuilder->select('id')->from($this->table)->getSQL() . ')',
                'tmp'
            )
            ->getSQL();
    }
810126
public function pathAndQuery()
    {
        $query = Request::getQueryString();
        $path = ltrim(Request::path(), '/'); // ltrim fixes homepage
        return $query ? $path.'?'.$query : $path;
    }
514002
function beforeList (controller, args, fields, title, form, links, defaultQueryArgs) {
    // get model from controller
    var model = controller.model
    // set limit
    var limit = args.limit || controller.defaultLimit
    var offset = args.offset || 0
    // set to true to show clear option for filters/sort
    var clear = false
    // set minimum limit to 2
    if (limit < 2) {
        limit = 2
    }
    // build arguments for query
    var query = {
        session: args.session,
    }
    // if query args are passed use them
    if (defined(defaultQueryArgs)) {
        _.merge(query, defaultQueryArgs)
    }
    // add order if set
    if (defined(args.orderColumn)) {
        query.order = [args.orderColumn]
        // if custom order is set add clear option
        clear = true
        // add direction if set
        if (defined(args.orderDirection)) {
            query.order.push(args.orderDirection)
        }
    }
    // add where if set
    if (defined(args.where)) {
        query.where = JSON.parse(args.where)
    }
    // included deleted records
    if (defined(args.deleted)) {
        // create where query if not set
        if (!defined(query.where)) {
            query.where = {}
        }
        // include deleted records - if argument is only then only deleted
        query.where.isDeleted = args.deleted === 'only'
            ? true: null
    }
    // add extra columns as query param options
    _.each(model.extraColumns, (spec, name) => {
        // if param is set in args add to where query
        if (typeof args[name] === 'string') {
            // create where query if not set
            if (!defined(query.where)) {
                query.where = {}
            }
            // if query is quoted then do exact match
            var queryArg = args[name].charAt(0) === '"' && args[name].charAt(args[name].length - 1) === '"'
                // strip leading and trailing quotes
                ? args[name].substr(1, args[name].length - 2)
                // add wildcards to string
                : `%${args[name]}%`
            // set like query
            query.where[name] = {like: queryArg}
            // if filter is set add clear option
            clear = true
            // and param to sort links
            _.each(fields, field => {
                if (field.orderAscUrl) {
                    field.orderAscUrl += '&'+name+'='+args[name]
                }
                if (field.orderDescUrl) {
                    field.orderDescUrl += '&'+name+'='+args[name]
                }
            })
        }
    })
    // if originalId set add to query
    if (args.originalId) {
        // create where query if not set
        if (!query.where) {
            query.where = {}
        }
        // set originalId in query
        query.where.originalId = {eq: args.originalId}
    }
    // do database query
    return model.query(query)
    // prepare args for primary method
    .then(result => {
        // remove session from query args for presentation
        delete query.session
        // fetch records
        return result.fetch(limit, offset)
        // resolve with result and record data
        .then(records => {
            // add actions to records
            _.each(records, record => {
                buildActions(controller, record)
            })
            // return data that will be merged into args for primary method
            return {
                clear: clear,
                fields: fields,
                form: form,
                links: links,
                query: query,
                records: records,
                result: {
                    length: result.length,
                },
                title: title,
            }
        })
    })
}
458083
public com.riversoft.weixin.pay.payment.bean.OrderQueryResponse query(com.riversoft.weixin.pay.payment.bean.OrderQueryRequest orderQueryRequest) {
        OrderQueryRequestWrapper wrapper = new OrderQueryRequestWrapper();
        wrapper.setRequest(orderQueryRequest);
        setBaseSettings(wrapper);
        SortedMap<String, Object> queryRequestMap = JsonMapper.nonEmptyMapper().getMapper().convertValue(wrapper, SortedMap.class);
        sign(wrapper, queryRequestMap);

        String url = WxEndpoint.get("url.pay.payment.order.query");
        try {
            String xml = XmlObjectMapper.nonEmptyMapper().toXml(wrapper);
            logger.info("支付 query order request: {}", xml);
            String response = wxSslClient.post(url, xml);
            logger.info("支付 query order response: {}", response);

            OrderQueryResponseWrapper responseWrapper = XmlObjectMapper.defaultMapper().fromXml(response, OrderQueryResponseWrapper.class);
            return responseWrapper.getResponse();
        } catch (Exception e) {
            throw new WxRuntimeException(999, "query order failed:" + e.getMessage());
        }

    }
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
            }
        });
    });
}
1114968
function (path, query, cb) {
    var httpMethod = 'get',
        config = User.datastore.config,
        endpoint = url.format({
                    host: config.host,
                    pathname: path,
                    protocol: config.protocol,
                    query: query
                  }),
        req = request[httpMethod](endpoint);
    req.end(cb);
  }
711721
def query(conn_type, option, post_data=None):
    '''
    
    '''
    if ticket is None or csrf is None or url is None:
        log.debug('Not authenticated yet, doing that now..')
        _authenticate()

    full_url = 'https://{0}:{1}/api2/json/{2}'.format(url, port, option)

    log.debug('%s: %s (%s)', conn_type, full_url, post_data)

    httpheaders = {'Accept': 'application/json',
                   'Content-Type': 'application/x-www-form-urlencoded',
                   'User-Agent': 'salt-cloud-proxmox'}

    if conn_type == 'post':
        httpheaders['CSRFPreventionToken'] = csrf
        response = requests.post(full_url, verify=verify_ssl,
                                 data=post_data,
                                 cookies=ticket,
                                 headers=httpheaders)
    elif conn_type == 'put':
        httpheaders['CSRFPreventionToken'] = csrf
        response = requests.put(full_url, verify=verify_ssl,
                                data=post_data,
                                cookies=ticket,
                                headers=httpheaders)
    elif conn_type == 'delete':
        httpheaders['CSRFPreventionToken'] = csrf
        response = requests.delete(full_url, verify=verify_ssl,
                                   data=post_data,
                                   cookies=ticket,
                                   headers=httpheaders)
    elif conn_type == 'get':
        response = requests.get(full_url, verify=verify_ssl,
                                cookies=ticket)

    response.raise_for_status()

    try:
        returned_data = response.json()
        if 'data' not in returned_data:
            raise SaltCloudExecutionFailure
        return returned_data['data']
    except Exception:
        log.error('Error in trying to process JSON')
        log.error(response)