Check if is a reserved word of any database
320741
public static boolean isReservedWord(String word) {
		return !StrUtils.isEmpty(word) && RESERVED_WORDS.containsKey(word.toUpperCase());
	}
943308
def rewrite_reserved_words(func):
    
    @partial_safe_wraps(func)
    def inner(*args, **kwargs):
        for word in RESERVED_WORDS:
            key = "{0}_".format(word)
            if key in kwargs:
                kwargs[word] = kwargs.pop(key)
        return func(*args, **kwargs)
    return inner
193850
function constainRestrictedWords(text) {
	var i,
		restictedWords = ['today', 'tomorrow', 'yesterday', 'tonight'];

	text = text.toLowerCase();
	i = restictedWords.length;
	while (i--) {
		if (text.indexOf(restictedWords[i]) > -1) {
			return true;
		}
	}
	return false;
}
744104
def db_check( block_id, opcode, op, txid, vtxindex, checked, db_state=None ):
   
   print "\nreference implementation of db_check\n"
   return False
1093009
def CheckBlobsExist(self, blob_ids, cursor=None):
    """"""
    if not blob_ids:
      return {}

    exists = {blob_id: False for blob_id in blob_ids}
    query = ("SELECT blob_id "
             "FROM blobs "
             "FORCE INDEX (PRIMARY) "
             "WHERE blob_id IN {}".format(
                 mysql_utils.Placeholders(len(blob_ids))))
    cursor.execute(query, [blob_id.AsBytes() for blob_id in blob_ids])
    for blob_id, in cursor.fetchall():
      exists[rdf_objects.BlobID.FromBytes(blob_id)] = True
    return exists
1265974
def _CheckCollation(cursor):
  """"""

  # Do not fail for wrong collation, because changing it is harder than changing
  # the character set. Some providers only allow changing character set and then
  # use the default collation. Also, misconfigured collation is not expected to
  # have major negative impacts, since it only affects string sort order for
  # some locales.

  cur_collation_connection = _ReadVariable("collation_connection", cursor)
  if cur_collation_connection != COLLATION:
    logging.warning("Require MySQL collation_connection of %s, got %s.",
                    COLLATION, cur_collation_connection)

  cur_collation_database = _ReadVariable("collation_database", cursor)
  if cur_collation_database != COLLATION:
    logging.warning(
        "Require MySQL collation_database of %s, got %s."
        " To create your database, use: %s", COLLATION, cur_collation_database,
        CREATE_DATABASE_QUERY)
477287
def validate_db(sqlalchemy_bind, is_enabled=ENABLE_DB):
    
    def decorator(func):
        @wraps(func)
        def wrapper(*args, **kwargs):
            def is_db_responsive():
                try:
                    sqlalchemy_bind.session.query('1').first_or_404()
                except:
                    return False
                else:
                    return True
            if is_enabled and is_db_responsive():
                return func(*args, **kwargs)
            else:
                abort(HTTP_CODES.UNAUTHORIZED)
        return wrapper
    return decorator
1339304
static String getEmptyTableSQL(String database, String table) {
        String safeDeleteSQL = "SELECT IF( \n" +
                 "(SELECT COUNT(1) as table_exists FROM information_schema.tables \n" +
                    "WHERE table_schema='" + database + "' AND table_name='" + table + "') > 1, \n" +
                 "'DELETE FROM " + table + "', \n" +
                 "'SELECT 1') INTO @DeleteSQL; \n" +
                "PREPARE stmt FROM @DeleteSQL; \n" +
                "EXECUTE stmt; DEALLOCATE PREPARE stmt; \n";

        return  "\n" + MysqlBaseService.SQL_START_PATTERN + "\n" +
                    safeDeleteSQL + "\n" +
                "\n" + MysqlBaseService.SQL_END_PATTERN + "\n";
    }
260156
def has_word ():
    """"""
    if not has_win32com:
        return False
    try:
        import _winreg as winreg
    except ImportError:
        import winreg
    try:
        key = winreg.OpenKey(winreg.HKEY_CLASSES_ROOT, "Word.Application")
        winreg.CloseKey(key)
        return True
    except (EnvironmentError, ImportError):
        pass
    return False
1282884
def _select(self, tree, allow_select_scan):
        
        tablename = tree.table
        desc = self.describe(tablename, require=True)
        kwargs = {}
        if tree.consistent:
            kwargs["consistent"] = True

        visitor = Visitor(self.reserved_words)

        selection = SelectionExpression.from_selection(tree.attrs)
        if selection.is_count:
            kwargs["select"] = "COUNT"

        if tree.keys_in:
            if tree.limit:
                raise SyntaxError("Cannot use LIMIT with KEYS IN")
            elif tree.using:
                raise SyntaxError("Cannot use USING with KEYS IN")
            elif tree.order:
                raise SyntaxError("Cannot use DESC/ASC with KEYS IN")
            elif tree.where:
                raise SyntaxError("Cannot use WHERE with KEYS IN")
            keys = list(self._iter_where_in(tree))
            kwargs["attributes"] = selection.build(visitor)
            kwargs["alias"] = visitor.attribute_names
            return self.connection.batch_get(tablename, keys=keys, **kwargs)

        if tree.limit:
            if tree.scan_limit:
                kwargs["limit"] = Limit(
                    scan_limit=resolve(tree.scan_limit[2]),
                    item_limit=resolve(tree.limit[1]),
                    strict=True,
                )
            else:
                kwargs["limit"] = Limit(item_limit=resolve(tree.limit[1]), strict=True)
        elif tree.scan_limit:
            kwargs["limit"] = Limit(scan_limit=resolve(tree.scan_limit[2]))

        (action, query_kwargs, index) = self._build_query(desc, tree, visitor)
        if action == "scan" and not allow_select_scan:
            raise SyntaxError(
                "No index found for query. Please use a SCAN query, or "
                "set allow_select_scan=True\nopt allow_select_scan true"
            )
        order_by = None
        if tree.order_by:
            order_by = tree.order_by[0]
        reverse = tree.order == "DESC"
        if tree.order:
            if action == "scan" and not tree.order_by:
                raise SyntaxError(
                    "No index found for query, "
                    "cannot use ASC or DESC without "
                    "ORDER BY <field>"
                )
            if action == "query":
                if order_by is None or order_by == index.range_key:
                    kwargs["desc"] = reverse

        kwargs.update(query_kwargs)

        # This is a special case for when we're querying an index and selecting
        # fields that aren't projected into the index.
        # We will change the query to only fetch the primary keys, and then
        # fill in the selected attributes after the fact.
        fetch_attrs_after = False
        if index is not None and not index.projects_all_attributes(
            selection.all_fields
        ):
            kwargs["attributes"] = [
                visitor.get_field(a) for a in desc.primary_key_attributes
            ]
            fetch_attrs_after = True
        else:
            kwargs["attributes"] = selection.build(visitor)
        kwargs["expr_values"] = visitor.expression_values
        kwargs["alias"] = visitor.attribute_names

        method = getattr(self.connection, action + "2")
        result = method(tablename, **kwargs)

        # If the queried index didn't project the selected attributes, we need
        # to do a BatchGetItem to fetch all the data.
        if fetch_attrs_after:
            if not isinstance(result, list):
                result = list(result)
            # If no results, no need to batch_get
            if not result:
                return result
            visitor = Visitor(self.reserved_words)
            kwargs = {"keys": [desc.primary_key(item) for item in result]}
            kwargs["attributes"] = selection.build(visitor)
            kwargs["alias"] = visitor.attribute_names
            result = self.connection.batch_get(tablename, **kwargs)

        def order(items):
            """ Sort the items by the specified keys """
            if order_by is None:
                return items
            if index is None or order_by != index.range_key:
                if not isinstance(items, list):
                    items = list(items)
                items.sort(key=lambda x: x.get(order_by), reverse=reverse)
            return items

        # Save the data to a file
        if tree.save_file:
            if selection.is_count:
                raise Exception("Cannot use count(*) with SAVE")
            count = 0
            result = order(selection.convert(item, True) for item in result)
            filename = tree.save_file[0]
            if filename[0] in ['"', "'"]:
                filename = unwrap(filename)
            # If it's still an iterator, convert to a list so we can iterate
            # multiple times.
            if not isinstance(result, list):
                result = list(result)
            remainder, ext = os.path.splitext(filename)
            if ext.lower() in [".gz", ".gzip"]:
                ext = os.path.splitext(remainder)[1]
                opened = gzip.open(filename, "wb")
            else:
                opened = open(filename, "wb")
            if ext.lower() == ".csv":
                if selection.all_keys:
                    headers = selection.all_keys
                else:
                    # Have to do this to get all the headers :(
                    result = list(result)
                    all_headers = set()
                    for item in result:
                        all_headers.update(item.keys())
                    headers = list(all_headers)
                with opened as ofile:
                    writer = csv.DictWriter(
                        ofile, fieldnames=headers, extrasaction="ignore"
                    )
                    writer.writeheader()
                    for item in result:
                        count += 1
                        writer.writerow(item)
            elif ext.lower() == ".json":
                with opened as ofile:
                    for item in result:
                        count += 1
                        ofile.write(self._encoder.encode(item))
                        ofile.write("\n")
            else:
                with opened as ofile:
                    for item in result:
                        count += 1
                        pickle.dump(item, ofile)
            return count
        elif not selection.is_count:
            result = order(selection.convert(item) for item in result)

        return result
302669
def get_sql(self):
        """"""
        test_method = [
            self.is_time,
            self.is_date,
            self.is_datetime,
            self.is_decimal,
            self.is_year,
            self.is_tinyint,
            self.is_smallint,
            self.is_mediumint,
            self.is_int,
            self.is_bigint,
            self.is_tinytext,
            self.is_varchar,
            self.is_mediumtext,
            self.is_longtext,
        ]
        # Loop through test methods until a test returns True
        for method in test_method:
            if method():
                return self.sql
811754
def available(self):
        '''  '''
        return self.db_name in map(
            lambda x: x['name'], self._db.get_database_list()
        )
39547
function validateCommonReservedWords(name){
  // Using regular expressions to find string literals can often have a
  // negative effect on performance.
  if (name ==='break') { return false; }
  if (name === 'case') { return false; }
  if (name === 'catch') { return false; }
  if (name === 'continue') { return false; }
  if (name === 'debugger') { return false; }
  if (name === 'default') { return false; }
  if (name === 'delete') { return false; }
  if (name === 'do') { return false; }
  if (name === 'else') { return false; }
  if (name === 'finally') { return false; }
  if (name === 'for') { return false; }
  if (name === 'function') { return false; }
  if (name === 'if') { return false; }
  if (name === 'in') { return false; }
  if (name === 'instanceof') { return false; }
  if (name === 'new') { return false; }
  if (name === 'return') { return false; }
  if (name === 'switch') { return false; }
  if (name === 'this') { return false; }
  if (name === 'throw') { return false; }
  if (name === 'try') { return false; }
  if (name === 'typeof') { return false; }
  if (name === 'var') { return false; }
  if (name === 'void') { return false; }
  if (name === 'while') { return false; }
  if (name === 'with') { return false; }
  if (name === 'class') { return false; }
  if (name === 'const') { return false; }
  if (name === 'export') { return false; }
  if (name === 'extends') { return false; }
  if (name === 'import') { return false; }
  if (name === 'super') { return false; }
  if (name === 'implements') { return false; }
  if (name === 'interface') { return false; }
  if (name === 'let') { return false; }
  if (name === 'package') { return false; }
  if (name === 'private') { return false; }
  if (name === 'protected') { return false; }
  if (name === 'public') { return false; }
  if (name === 'static') { return false; }
  if (name === 'yield') { return false; }
  if (name === 'null') { return false; }
  if (name === 'true') { return false; }
  if (name === 'false') { return false; }
  if (name === 'NaN') { return false; }
  if (name === 'Infinity') { return false; }
  if (name === 'undefined') { return false; }

  return true;
}
697434
public function formatSQL($sql = '')
    {
        // Reserved SQL Keywords Data
        $reserveSqlKey = 'select|insert|update|delete|truncate|drop|create|add|except|percent|all|exec|plan|alter|execute|precision|and|exists|primary|any|exit|print|as|fetch|proc|asc|file|procedure|authorization|fillfactor|public|backup|for|raiserror|begin|foreign|read|between|freetext|readtext|break|freetexttable|reconfigure|browse|from|references|bulk|full|replication|by|function|restore|cascade|goto|restrict|case|grant|return|check|group|revoke|checkpoint|having|right|close|holdlock|rollback|clustered|identity|rowcount|coalesce|identity_insert|rowguidcol|collate|identitycol|rule|column|if|save|commit|in|schema|compute|index|select|constraint|inner|session_user|contains|insert|set|containstable|intersect|setuser|continue|into|shutdown|convert|is|some|create|join|statistics|cross|key|system_user|current|kill|table|current_date|left|textsize|current_time|like|then|current_timestamp|lineno|to|current_user|load|top|cursor|national|tran|database|nocheck|transaction|dbcc|nonclustered|trigger|deallocate|not|truncate|declare|null|tsequal|default|nullif|union|delete|of|unique|deny|off|update|desc|offsets|updatetext|disk|on|use|distinct|open|user|distributed|opendatasource|values|double|openquery|varying|drop|openrowset|view|dummy|openxml|waitfor|dump|option|when|else|or|where|end|order|while|errlvl|outer|with|escape|over|writetext|absolute|overlaps|action|pad|ada|partial|external|pascal|extract|position|allocate|false|prepare|first|preserve|float|are|prior|privileges|fortran|assertion|found|at|real|avg|get|global|relative|go|bit|bit_length|both|rows|hour|cascaded|scroll|immediate|second|cast|section|catalog|include|char|session|char_length|indicator|character|initially|character_length|size|input|smallint|insensitive|space|int|sql|collation|integer|sqlca|sqlcode|interval|sqlerror|connect|sqlstate|connection|sqlwarning|isolation|substring|constraints|sum|language|corresponding|last|temporary|count|leading|time|level|timestamp|timezone_hour|local|timezone_minute|lower|match|trailing|max|min|translate|date|minute|translation|day|module|trim|month|true|dec|names|decimal|natural|unknown|nchar|deferrable|next|upper|deferred|no|usage|none|using|describe|value|descriptor|diagnostics|numeric|varchar|disconnect|octet_length|domain|only|whenever|work|end-exec|write|year|output|zone|exception|free|admin|general|after|reads|aggregate|alias|recursive|grouping|ref|host|referencing|array|ignore|result|returns|before|role|binary|initialize|rollup|routine|blob|inout|row|boolean|savepoint|breadth|call|scope|search|iterate|large|sequence|class|lateral|sets|clob|less|completion|limit|specific|specifictype|localtime|constructor|localtimestamp|sqlexception|locator|cube|map|current_path|start|current_role|state|cycle|modifies|statement|data|modify|static|structure|terminate|than|nclob|depth|new|deref|destroy|treat|destructor|object|deterministic|old|under|dictionary|operation|unnest|ordinality|out|dynamic|each|parameter|variable|equals|parameters|every|without|path|postfix|prefix|preorder';
        // convert in array
        $list = explode('|', $reserveSqlKey);
        foreach ($list as &$verb) {
            $verb = '/\b' . preg_quote($verb, '/') . '\b/';
        }
        $regex_sign = ['/\b', '\b/'];
        // replace matching words
        return str_replace(
            $regex_sign,
            '',
            preg_replace(
                $list,
                array_map(
                    [
                        $this,
                        'highlight_sql',
                    ],
                    $list
                ),
                strtolower($sql)
            )
        );
    }
892885
def present(name, character_set=None, collate=None, **connection_args):
    '''
    
    '''
    ret = {'name': name,
           'changes': {},
           'result': True,
           'comment': 'Database {0} is already present'.format(name)}
    # check if database exists
    existing = __salt__['mysql.db_get'](name, **connection_args)
    if existing:
        alter = False
        if character_set and character_set != existing.get('character_set'):
            log.debug('character set differes from %s : %s',
                      character_set, existing.get('character_set'))
            alter = True
        if collate and collate != existing.get('collate'):
            log.debug('collate set differs from %s : %s',
                      collate, existing.get('collate'))
            alter = True
        if alter:
            __salt__['mysql.alter_db'](
                name, character_set=character_set, collate=collate,
                **connection_args)
        current = __salt__['mysql.db_get'](name, **connection_args)
        if existing.get('collate', None) != current.get('collate', None):
            ret['changes'].update({'collate': {
                'before': existing.get('collate', None),
                'now': current.get('collate', None)}})
        if existing.get('character_set', None) != current.get('character_set', None):
            ret['changes'].update({'character_set': {
                'before': existing.get('character_set', None),
                'now': current.get('character_set', None)}})
        return ret
    else:
        err = _get_mysql_error()
        if err is not None:
            ret['comment'] = err
            ret['result'] = False
            return ret

    if __opts__['test']:
        ret['result'] = None
        ret['comment'] = ('Database {0} is not present and needs to be created'
                ).format(name)
        return ret
    # The database is not present, make it!
    if __salt__['mysql.db_create'](
            name, character_set=character_set, collate=collate,
            **connection_args):
        ret['comment'] = 'The database {0} has been created'.format(name)
        ret['changes'][name] = 'Present'
    else:
        ret['comment'] = 'Failed to create database {0}'.format(name)
        err = _get_mysql_error()
        if err is not None:
            ret['comment'] += ' ({0})'.format(err)
        ret['result'] = False

    return ret
550367
@Override
    public void check(Connection conn, String scName, Collection<String> tbNames) throws IllegalMetaDataException {
        if (scName == null) {
            throw new IllegalArgumentException("[Check MetaData Failed] parameter 'scName' can't be null");
        }
        if (tbNames == null || tbNames.isEmpty()) {
            throw new IllegalArgumentException("[Check MetaData Failed] parameter 'tbNames' can't be empty");
        }
        try {
            Set<String> set = getAllTables(conn, scName);
            if (set == null || set.isEmpty()) {
                throw new IllegalMetaDataException(
                                                   "[Check MetaData Failed] Schema:'"
                                                           + scName
                                                           + "' has nothing tables. but in your configuration it requires table:"
                                                           + DDRJSONUtils.toJSONString(tbNames));
            }
            for (String tbName : tbNames) {
                if (!set.contains(tbName)) {
                    throw new IllegalMetaDataException("[Check MetaData Failed] Schema:'" + scName
                                                       + "' only has tables:" + DDRJSONUtils.toJSONString(set)
                                                       + ", but in your configuration it requires table:" + tbName);
                }
            }
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }
105684
def _check_database_id(database_id):
    
    if database_id != u"":
        msg = _DATABASE_ID_TEMPLATE.format(database_id)
        raise ValueError(msg)