Client supplied raw DMQL, ensure quote wrap.
430301
def dmql(query):
        """"""
        if isinstance(query, dict):
            raise ValueError("You supplied a dictionary to the dmql_query parameter, but a string is required."
                                " Did you mean to pass this to the search_filter parameter? ")

        # automatically surround the given query with parentheses if it doesn't have them already
        if len(query) > 0 and query != "*" and query[0] != '(' and query[-1] != ')':
            query = '({})'.format(query)
        return query
310624
def _get_query(self, callback, schema, query=None, *args, **kwargs):
        """"""
        if not query: query = Query()

        ret = None
        with self.connection(**kwargs) as connection:
            kwargs['connection'] = connection
            try:
                if connection.in_transaction():
                    # we wrap SELECT queries in a transaction if we are in a transaction because
                    # it could cause data loss if it failed by causing the db to discard
                    # anything in the current transaction if the query isn't wrapped,
                    # go ahead, ask me how I know this
                    with self.transaction(**kwargs):
                        ret = callback(schema, query, *args, **kwargs)

                else:
                    ret = callback(schema, query, *args, **kwargs)

            except Exception as e:
                exc_info = sys.exc_info()
                if self.handle_error(schema, e, **kwargs):
                    ret = callback(schema, query, *args, **kwargs)
                else:
                    self.raise_error(e, exc_info)

        return ret
1126023
function quotedPair() {
        var qp = wrap('quoted-pair',
        or(
            and(literal('\\'), or(vchar, wsp)),
            obsQP
        )());
        if (qp === null) { return null; }
        // a quoted pair will be two characters, and the "\" character
        // should be semantically "invisible" (RFC 5322 3.2.1)
        qp.semantic = qp.semantic[1];
        return qp;
    }
832644
function wrap(field, type, packet, encoding) {
    return {
      type: type,
      length: field.columnLength,
      db: field.schema,
      table: field.table,
      name: field.name,
      string: function() {
        return packet.readLengthCodedString(encoding);
      },
      buffer: function() {
        return packet.readLengthCodedBuffer();
      },
      geometry: function() {
        return packet.parseGeometryValue();
      }
    };
  }
289426
def any2sql(func, definition_dict=None, **definition_kwargs):
    
    if definition_dict and definition_kwargs:
        raise InputError("Cannot process dict and kwargs input at the same time")

    definition = load_input(definition_dict or definition_kwargs)

    if definition.get('returning', '') == '*':
        definition['returning'] = mosql_raw('*')

    try:
        result = func(**definition)
    except (TypeError, AttributeError) as exc:
        raise ClauseError("Clause definition error: %s" % str(exc)) from exc
    except Exception as exc:
        import json2sql.errors as json2sql_errors

        if exc.__class__.__name__ not in json2sql_errors.__dict__.keys():
            raise json2sql_errors.Json2SqlInternalError("Unhandled error: %s" % str(exc)) from exc
        raise

    return result
268358
def create_aql_text(*args):
        
        aql_query_text = ""
        for arg in args:
            if isinstance(arg, dict):
                arg = "({})".format(json.dumps(arg))
            elif isinstance(arg, list):
                arg = "({})".format(json.dumps(arg)).replace("[", "").replace("]", "")
            aql_query_text += arg
        return aql_query_text
1223762
def as_cql_query(self, formatted=False):
        
        sep = '\n    ' if formatted else ' '
        keyspace = protect_name(self.keyspace_name)
        name = protect_name(self.name)

        selected_cols = '*' if self.include_all_columns else ', '.join(protect_name(col.name) for col in self.columns.values())
        base_table = protect_name(self.base_table_name)
        where_clause = self.where_clause

        part_key = ', '.join(protect_name(col.name) for col in self.partition_key)
        if len(self.partition_key) > 1:
            pk = "((%s)" % part_key
        else:
            pk = "(%s" % part_key
        if self.clustering_key:
            pk += ", %s" % ', '.join(protect_name(col.name) for col in self.clustering_key)
        pk += ")"

        properties = TableMetadataV3._property_string(formatted, self.clustering_key, self.options)

        ret = ("CREATE MATERIALIZED VIEW %(keyspace)s.%(name)s AS%(sep)s"
               "SELECT %(selected_cols)s%(sep)s"
               "FROM %(keyspace)s.%(base_table)s%(sep)s"
               "WHERE %(where_clause)s%(sep)s"
               "PRIMARY KEY %(pk)s%(sep)s"
               "WITH %(properties)s") % locals()

        if self.extensions:
            registry = _RegisteredExtensionType._extension_registry
            for k in six.viewkeys(registry) & self.extensions:  # no viewkeys on OrderedMapSerializeKey
                ext = registry[k]
                cql = ext.after_table_cql(self, k, self.extensions[k])
                if cql:
                    ret += "\n\n%s" % (cql,)
        return ret
3977
protected void validateSqlString(String originalSql) {
        if (originalSql == null) {
            throw new IllegalArgumentException(ERROR_SQL_QUERY_NULL);
        }
        if (processor.hasUnnamedParameters(originalSql) == true) {
            throw new IllegalArgumentException(ERROR_FOUND_UNNAMED_PARAMETER);
        }
    }
1081793
function quote($filter = array(), $join = " AND ") {
		$QUOTE_CHAR = defined('DB::USE_ANSI_SQL') ? '"' : '';

		$string = '';
		$sep = '';

		foreach ($filter as $field => $value) {
			// first break the field up into its two components
			$operator = '';
			if (is_string($field)) {
				list($field, $operator) = explode(' ', trim($field));
			}

			if (is_array($value)) {
				// quote each individual one into a string
				$ins = '';
				$insep = '';
				foreach ($value as $v) {
					$ins .= $insep . Convert::raw2sql($v);
					$insep = ',';
				}
				$value = '('.$ins.')';
			} else if (is_null($value)) {
				$value = 'NULL';
			} else if (is_string($field)) {
				$value = "'" . Convert::raw2sql($value) . "'";
			}

			if (strpos($field, '.')) {
				list($tb, $fl) = explode('.', $field);
				$string .= $sep . $QUOTE_CHAR . $tb . $QUOTE_CHAR . '.' . $QUOTE_CHAR . $fl . $QUOTE_CHAR . " $operator " . $value;
			} else {
				if (is_numeric($field)) {
					$string .= $sep . $value;
				} else {
					$string .= $sep . $QUOTE_CHAR . $field . $QUOTE_CHAR . " $operator " . $value;
				}
			}

			$sep = $join;
		}

		return $string;
	}
246696
def mark_quoted_strings(sql):
    
    # pattern of a string parameter (pm), a char escaped by backslash (bs)
    # out_pattern: characters valid in SOQL
    pm_pattern = re.compile(r"'[^\\']*(?:\\[\\'][^\\']*)*'")
    bs_pattern = re.compile(r"\\([\\'])")
    out_pattern = re.compile(r"^(?:[-!()*+,.:<=>\w\s|%s])*$")
    missing_apostrophe = "invalid character in SOQL or a missing apostrophe"
    start = 0
    out = []
    params = []
    for match in pm_pattern.finditer(sql):
        out.append(sql[start:match.start()])
        assert out_pattern.match(sql[start:match.start()]), missing_apostrophe
        params.append(bs_pattern.sub('\\1', sql[match.start() + 1:match.end() - 1]))
        start = match.end()
    out.append(sql[start:])
    assert out_pattern.match(sql[start:]), missing_apostrophe
    return '@'.join(out), params
1352963
function toSQL() {
    if (this._cached) {
      return this._cached;
    }
    if (Array.isArray(this.bindings)) {
      this._cached = replaceRawArrBindings(this);
    } else if (this.bindings && typeof this.bindings === 'object') {
      this._cached = replaceKeyBindings(this);
    } else {
      this._cached = {
        method: 'raw',
        sql: this.sql,
        bindings: this.bindings
      };
    }
    if (this._wrappedBefore) {
      this._cached.sql = this._wrappedBefore + this._cached.sql;
    }
    if (this._wrappedAfter) {
      this._cached.sql = this._cached.sql + this._wrappedAfter;
    }
    this._cached.options = assign({}, this._options);
    return this._cached;
  }
433836
def _quote_query(query):
    """"""
    return "&".join("%s=%s" % (
        k, urllib_quote(
            unicode(query[k]).encode('utf-8'), safe='~'))
            for k in sorted(query))
865060
function MySQL(client, conSettings) {
    'use strict';
    this.name = 'mysql';
    this._models = {};
    this.log = console.log;
    this.client = client;
    this.settings = conSettings;
}
726628
def validateAQLQuery(self, query, bindVars = None, options = None) :
        ""
        if bindVars is None :
            bindVars = {}
        if options is None :
            options = {}
        payload = {'query' : query, 'bindVars' : bindVars, 'options' : options}
        r = self.connection.session.post(self.cursorsURL, data = json.dumps(payload, default=str))
        data = r.json()
        if r.status_code == 201 and not data["error"] :
            return data
        else :
            raise AQLQueryError(data["errorMessage"], query, data)
1296537
def _raw_sql(self, values):
        """"""
        if isinstance(self.model._meta.pk, CharField):
            when_clauses = " ".join(
                [self._when("'{}'".format(x), y) for (x, y) in values]
            )
        else:
            when_clauses = " ".join([self._when(x, y) for (x, y) in values])
        table_name = self.model._meta.db_table
        primary_key = self.model._meta.pk.column
        return 'SELECT CASE {}."{}" {} ELSE 0 END'.format(
            table_name, primary_key, when_clauses
        )
20885
def __build_raw_query(self, routine, parameters):
        

        parameter_names = []
        replacements = {}

        for i, value in enumerate(parameters):
            name = 'arg' + str(i)

            parameter_names.append(name)
            replacements[name] = value

        parameter_phrase = ', '.join([('%(' + p + ')s') for p in parameter_names])

        query = "CALL " + routine + "(" + parameter_phrase + ")"
        return (query, replacements)
734365
function Query(client, rawQuery) {
  if (client) {
    /**
     * If set, query is attached to given client instance
     *
     * @private
     * @type {Druid|Client}
     */
    this.client = client
  }


  /**
   * Actual query object
   *
   * @private
   */
  this._query = {
    queryType: this._queryType
  }

  if (rawQuery) {
    // we do not want to change query type, aren't we?
    this._queryType && delete rawQuery.queryType

    assign(this._query, rawQuery)
  }
}