[ Index ]

PHP Cross Reference of Joomla 4.2.2 documentation

title

Body

[close]

/media/vendor/codemirror/mode/sql/ -> sql.js (source)

   1  // CodeMirror, copyright (c) by Marijn Haverbeke and others
   2  // Distributed under an MIT license: https://codemirror.net/5/LICENSE
   3  
   4  (function(mod) {
   5    if (typeof exports == "object" && typeof module == "object") // CommonJS
   6      mod(require("../../lib/codemirror"));
   7    else if (typeof define == "function" && define.amd) // AMD
   8      define(["../../lib/codemirror"], mod);
   9    else // Plain browser env
  10      mod(CodeMirror);
  11  })(function(CodeMirror) {
  12  "use strict";
  13  
  14  CodeMirror.defineMode("sql", function(config, parserConfig) {
  15    var client         = parserConfig.client || {},
  16        atoms          = parserConfig.atoms || {"false": true, "true": true, "null": true},
  17        builtin        = parserConfig.builtin || set(defaultBuiltin),
  18        keywords       = parserConfig.keywords || set(sqlKeywords),
  19        operatorChars  = parserConfig.operatorChars || /^[*+\-%<>!=&|~^\/]/,
  20        support        = parserConfig.support || {},
  21        hooks          = parserConfig.hooks || {},
  22        dateSQL        = parserConfig.dateSQL || {"date" : true, "time" : true, "timestamp" : true},
  23        backslashStringEscapes = parserConfig.backslashStringEscapes !== false,
  24        brackets       = parserConfig.brackets || /^[\{}\(\)\[\]]/,
  25        punctuation    = parserConfig.punctuation || /^[;.,:]/
  26  
  27    function tokenBase(stream, state) {
  28      var ch = stream.next();
  29  
  30      // call hooks from the mime type
  31      if (hooks[ch]) {
  32        var result = hooks[ch](stream, state);
  33        if (result !== false) return result;
  34      }
  35  
  36      if (support.hexNumber &&
  37        ((ch == "0" && stream.match(/^[xX][0-9a-fA-F]+/))
  38        || (ch == "x" || ch == "X") && stream.match(/^'[0-9a-fA-F]+'/))) {
  39        // hex
  40        // ref: http://dev.mysql.com/doc/refman/5.5/en/hexadecimal-literals.html
  41        return "number";
  42      } else if (support.binaryNumber &&
  43        (((ch == "b" || ch == "B") && stream.match(/^'[01]+'/))
  44        || (ch == "0" && stream.match(/^b[01]+/)))) {
  45        // bitstring
  46        // ref: http://dev.mysql.com/doc/refman/5.5/en/bit-field-literals.html
  47        return "number";
  48      } else if (ch.charCodeAt(0) > 47 && ch.charCodeAt(0) < 58) {
  49        // numbers
  50        // ref: http://dev.mysql.com/doc/refman/5.5/en/number-literals.html
  51        stream.match(/^[0-9]*(\.[0-9]+)?([eE][-+]?[0-9]+)?/);
  52        support.decimallessFloat && stream.match(/^\.(?!\.)/);
  53        return "number";
  54      } else if (ch == "?" && (stream.eatSpace() || stream.eol() || stream.eat(";"))) {
  55        // placeholders
  56        return "variable-3";
  57      } else if (ch == "'" || (ch == '"' && support.doubleQuote)) {
  58        // strings
  59        // ref: http://dev.mysql.com/doc/refman/5.5/en/string-literals.html
  60        state.tokenize = tokenLiteral(ch);
  61        return state.tokenize(stream, state);
  62      } else if ((((support.nCharCast && (ch == "n" || ch == "N"))
  63          || (support.charsetCast && ch == "_" && stream.match(/[a-z][a-z0-9]*/i)))
  64          && (stream.peek() == "'" || stream.peek() == '"'))) {
  65        // charset casting: _utf8'str', N'str', n'str'
  66        // ref: http://dev.mysql.com/doc/refman/5.5/en/string-literals.html
  67        return "keyword";
  68      } else if (support.escapeConstant && (ch == "e" || ch == "E")
  69          && (stream.peek() == "'" || (stream.peek() == '"' && support.doubleQuote))) {
  70        // escape constant: E'str', e'str'
  71        // ref: https://www.postgresql.org/docs/current/sql-syntax-lexical.html#SQL-SYNTAX-STRINGS-ESCAPE
  72        state.tokenize = function(stream, state) {
  73          return (state.tokenize = tokenLiteral(stream.next(), true))(stream, state);
  74        }
  75        return "keyword";
  76      } else if (support.commentSlashSlash && ch == "/" && stream.eat("/")) {
  77        // 1-line comment
  78        stream.skipToEnd();
  79        return "comment";
  80      } else if ((support.commentHash && ch == "#")
  81          || (ch == "-" && stream.eat("-") && (!support.commentSpaceRequired || stream.eat(" ")))) {
  82        // 1-line comments
  83        // ref: https://kb.askmonty.org/en/comment-syntax/
  84        stream.skipToEnd();
  85        return "comment";
  86      } else if (ch == "/" && stream.eat("*")) {
  87        // multi-line comments
  88        // ref: https://kb.askmonty.org/en/comment-syntax/
  89        state.tokenize = tokenComment(1);
  90        return state.tokenize(stream, state);
  91      } else if (ch == ".") {
  92        // .1 for 0.1
  93        if (support.zerolessFloat && stream.match(/^(?:\d+(?:e[+-]?\d+)?)/i))
  94          return "number";
  95        if (stream.match(/^\.+/))
  96          return null
  97        // .table_name (ODBC)
  98        // // ref: http://dev.mysql.com/doc/refman/5.6/en/identifier-qualifiers.html
  99        if (support.ODBCdotTable && stream.match(/^[\w\d_$#]+/))
 100          return "variable-2";
 101      } else if (operatorChars.test(ch)) {
 102        // operators
 103        stream.eatWhile(operatorChars);
 104        return "operator";
 105      } else if (brackets.test(ch)) {
 106        // brackets
 107        return "bracket";
 108      } else if (punctuation.test(ch)) {
 109        // punctuation
 110        stream.eatWhile(punctuation);
 111        return "punctuation";
 112      } else if (ch == '{' &&
 113          (stream.match(/^( )*(d|D|t|T|ts|TS)( )*'[^']*'( )*}/) || stream.match(/^( )*(d|D|t|T|ts|TS)( )*"[^"]*"( )*}/))) {
 114        // dates (weird ODBC syntax)
 115        // ref: http://dev.mysql.com/doc/refman/5.5/en/date-and-time-literals.html
 116        return "number";
 117      } else {
 118        stream.eatWhile(/^[_\w\d]/);
 119        var word = stream.current().toLowerCase();
 120        // dates (standard SQL syntax)
 121        // ref: http://dev.mysql.com/doc/refman/5.5/en/date-and-time-literals.html
 122        if (dateSQL.hasOwnProperty(word) && (stream.match(/^( )+'[^']*'/) || stream.match(/^( )+"[^"]*"/)))
 123          return "number";
 124        if (atoms.hasOwnProperty(word)) return "atom";
 125        if (builtin.hasOwnProperty(word)) return "type";
 126        if (keywords.hasOwnProperty(word)) return "keyword";
 127        if (client.hasOwnProperty(word)) return "builtin";
 128        return null;
 129      }
 130    }
 131  
 132    // 'string', with char specified in quote escaped by '\'
 133    function tokenLiteral(quote, backslashEscapes) {
 134      return function(stream, state) {
 135        var escaped = false, ch;
 136        while ((ch = stream.next()) != null) {
 137          if (ch == quote && !escaped) {
 138            state.tokenize = tokenBase;
 139            break;
 140          }
 141          escaped = (backslashStringEscapes || backslashEscapes) && !escaped && ch == "\\";
 142        }
 143        return "string";
 144      };
 145    }
 146    function tokenComment(depth) {
 147      return function(stream, state) {
 148        var m = stream.match(/^.*?(\/\*|\*\/)/)
 149        if (!m) stream.skipToEnd()
 150        else if (m[1] == "/*") state.tokenize = tokenComment(depth + 1)
 151        else if (depth > 1) state.tokenize = tokenComment(depth - 1)
 152        else state.tokenize = tokenBase
 153        return "comment"
 154      }
 155    }
 156  
 157    function pushContext(stream, state, type) {
 158      state.context = {
 159        prev: state.context,
 160        indent: stream.indentation(),
 161        col: stream.column(),
 162        type: type
 163      };
 164    }
 165  
 166    function popContext(state) {
 167      state.indent = state.context.indent;
 168      state.context = state.context.prev;
 169    }
 170  
 171    return {
 172      startState: function() {
 173        return {tokenize: tokenBase, context: null};
 174      },
 175  
 176      token: function(stream, state) {
 177        if (stream.sol()) {
 178          if (state.context && state.context.align == null)
 179            state.context.align = false;
 180        }
 181        if (state.tokenize == tokenBase && stream.eatSpace()) return null;
 182  
 183        var style = state.tokenize(stream, state);
 184        if (style == "comment") return style;
 185  
 186        if (state.context && state.context.align == null)
 187          state.context.align = true;
 188  
 189        var tok = stream.current();
 190        if (tok == "(")
 191          pushContext(stream, state, ")");
 192        else if (tok == "[")
 193          pushContext(stream, state, "]");
 194        else if (state.context && state.context.type == tok)
 195          popContext(state);
 196        return style;
 197      },
 198  
 199      indent: function(state, textAfter) {
 200        var cx = state.context;
 201        if (!cx) return CodeMirror.Pass;
 202        var closing = textAfter.charAt(0) == cx.type;
 203        if (cx.align) return cx.col + (closing ? 0 : 1);
 204        else return cx.indent + (closing ? 0 : config.indentUnit);
 205      },
 206  
 207      blockCommentStart: "/*",
 208      blockCommentEnd: "*/",
 209      lineComment: support.commentSlashSlash ? "//" : support.commentHash ? "#" : "--",
 210      closeBrackets: "()[]{}''\"\"``"
 211    };
 212  });
 213  
 214    // `identifier`
 215    function hookIdentifier(stream) {
 216      // MySQL/MariaDB identifiers
 217      // ref: http://dev.mysql.com/doc/refman/5.6/en/identifier-qualifiers.html
 218      var ch;
 219      while ((ch = stream.next()) != null) {
 220        if (ch == "`" && !stream.eat("`")) return "variable-2";
 221      }
 222      stream.backUp(stream.current().length - 1);
 223      return stream.eatWhile(/\w/) ? "variable-2" : null;
 224    }
 225  
 226    // "identifier"
 227    function hookIdentifierDoublequote(stream) {
 228      // Standard SQL /SQLite identifiers
 229      // ref: http://web.archive.org/web/20160813185132/http://savage.net.au/SQL/sql-99.bnf.html#delimited%20identifier
 230      // ref: http://sqlite.org/lang_keywords.html
 231      var ch;
 232      while ((ch = stream.next()) != null) {
 233        if (ch == "\"" && !stream.eat("\"")) return "variable-2";
 234      }
 235      stream.backUp(stream.current().length - 1);
 236      return stream.eatWhile(/\w/) ? "variable-2" : null;
 237    }
 238  
 239    // variable token
 240    function hookVar(stream) {
 241      // variables
 242      // @@prefix.varName @varName
 243      // varName can be quoted with ` or ' or "
 244      // ref: http://dev.mysql.com/doc/refman/5.5/en/user-variables.html
 245      if (stream.eat("@")) {
 246        stream.match('session.');
 247        stream.match('local.');
 248        stream.match('global.');
 249      }
 250  
 251      if (stream.eat("'")) {
 252        stream.match(/^.*'/);
 253        return "variable-2";
 254      } else if (stream.eat('"')) {
 255        stream.match(/^.*"/);
 256        return "variable-2";
 257      } else if (stream.eat("`")) {
 258        stream.match(/^.*`/);
 259        return "variable-2";
 260      } else if (stream.match(/^[0-9a-zA-Z$\.\_]+/)) {
 261        return "variable-2";
 262      }
 263      return null;
 264    };
 265  
 266    // short client keyword token
 267    function hookClient(stream) {
 268      // \N means NULL
 269      // ref: http://dev.mysql.com/doc/refman/5.5/en/null-values.html
 270      if (stream.eat("N")) {
 271          return "atom";
 272      }
 273      // \g, etc
 274      // ref: http://dev.mysql.com/doc/refman/5.5/en/mysql-commands.html
 275      return stream.match(/^[a-zA-Z.#!?]/) ? "variable-2" : null;
 276    }
 277  
 278    // these keywords are used by all SQL dialects (however, a mode can still overwrite it)
 279    var sqlKeywords = "alter and as asc between by count create delete desc distinct drop from group having in insert into is join like not on or order select set table union update values where limit ";
 280  
 281    // turn a space-separated list into an array
 282    function set(str) {
 283      var obj = {}, words = str.split(" ");
 284      for (var i = 0; i < words.length; ++i) obj[words[i]] = true;
 285      return obj;
 286    }
 287  
 288    var defaultBuiltin = "bool boolean bit blob enum long longblob longtext medium mediumblob mediumint mediumtext time timestamp tinyblob tinyint tinytext text bigint int int1 int2 int3 int4 int8 integer float float4 float8 double char varbinary varchar varcharacter precision real date datetime year unsigned signed decimal numeric"
 289  
 290    // A generic SQL Mode. It's not a standard, it just try to support what is generally supported
 291    CodeMirror.defineMIME("text/x-sql", {
 292      name: "sql",
 293      keywords: set(sqlKeywords + "begin"),
 294      builtin: set(defaultBuiltin),
 295      atoms: set("false true null unknown"),
 296      dateSQL: set("date time timestamp"),
 297      support: set("ODBCdotTable doubleQuote binaryNumber hexNumber")
 298    });
 299  
 300    CodeMirror.defineMIME("text/x-mssql", {
 301      name: "sql",
 302      client: set("$partition binary_checksum checksum connectionproperty context_info current_request_id error_line error_message error_number error_procedure error_severity error_state formatmessage get_filestream_transaction_context getansinull host_id host_name isnull isnumeric min_active_rowversion newid newsequentialid rowcount_big xact_state object_id"),
 303      keywords: set(sqlKeywords + "begin trigger proc view index for add constraint key primary foreign collate clustered nonclustered declare exec go if use index holdlock nolock nowait paglock readcommitted readcommittedlock readpast readuncommitted repeatableread rowlock serializable snapshot tablock tablockx updlock with"),
 304      builtin: set("bigint numeric bit smallint decimal smallmoney int tinyint money float real char varchar text nchar nvarchar ntext binary varbinary image cursor timestamp hierarchyid uniqueidentifier sql_variant xml table "),
 305      atoms: set("is not null like and or in left right between inner outer join all any some cross unpivot pivot exists"),
 306      operatorChars: /^[*+\-%<>!=^\&|\/]/,
 307      brackets: /^[\{}\(\)]/,
 308      punctuation: /^[;.,:/]/,
 309      backslashStringEscapes: false,
 310      dateSQL: set("date datetimeoffset datetime2 smalldatetime datetime time"),
 311      hooks: {
 312        "@":   hookVar
 313      }
 314    });
 315  
 316    CodeMirror.defineMIME("text/x-mysql", {
 317      name: "sql",
 318      client: set("charset clear connect edit ego exit go help nopager notee nowarning pager print prompt quit rehash source status system tee"),
 319      keywords: set(sqlKeywords + "accessible action add after algorithm all analyze asensitive at authors auto_increment autocommit avg avg_row_length before binary binlog both btree cache call cascade cascaded case catalog_name chain change changed character check checkpoint checksum class_origin client_statistics close coalesce code collate collation collations column columns comment commit committed completion concurrent condition connection consistent constraint contains continue contributors convert cross current current_date current_time current_timestamp current_user cursor data database databases day_hour day_microsecond day_minute day_second deallocate dec declare default delay_key_write delayed delimiter des_key_file describe deterministic dev_pop dev_samp deviance diagnostics directory disable discard distinctrow div dual dumpfile each elseif enable enclosed end ends engine engines enum errors escape escaped even event events every execute exists exit explain extended fast fetch field fields first flush for force foreign found_rows full fulltext function general get global grant grants group group_concat handler hash help high_priority hosts hour_microsecond hour_minute hour_second if ignore ignore_server_ids import index index_statistics infile inner innodb inout insensitive insert_method install interval invoker isolation iterate key keys kill language last leading leave left level limit linear lines list load local localtime localtimestamp lock logs low_priority master master_heartbeat_period master_ssl_verify_server_cert masters match max max_rows maxvalue message_text middleint migrate min min_rows minute_microsecond minute_second mod mode modifies modify mutex mysql_errno natural next no no_write_to_binlog offline offset one online open optimize option optionally out outer outfile pack_keys parser partition partitions password phase plugin plugins prepare preserve prev primary privileges procedure processlist profile profiles purge query quick range read read_write reads real rebuild recover references regexp relaylog release remove rename reorganize repair repeatable replace require resignal restrict resume return returns revoke right rlike rollback rollup row row_format rtree savepoint schedule schema schema_name schemas second_microsecond security sensitive separator serializable server session share show signal slave slow smallint snapshot soname spatial specific sql sql_big_result sql_buffer_result sql_cache sql_calc_found_rows sql_no_cache sql_small_result sqlexception sqlstate sqlwarning ssl start starting starts status std stddev stddev_pop stddev_samp storage straight_join subclass_origin sum suspend table_name table_statistics tables tablespace temporary terminated to trailing transaction trigger triggers truncate uncommitted undo uninstall unique unlock upgrade usage use use_frm user user_resources user_statistics using utc_date utc_time utc_timestamp value variables varying view views warnings when while with work write xa xor year_month zerofill begin do then else loop repeat"),
 320      builtin: set("bool boolean bit blob decimal double float long longblob longtext medium mediumblob mediumint mediumtext time timestamp tinyblob tinyint tinytext text bigint int int1 int2 int3 int4 int8 integer float float4 float8 double char varbinary varchar varcharacter precision date datetime year unsigned signed numeric"),
 321      atoms: set("false true null unknown"),
 322      operatorChars: /^[*+\-%<>!=&|^]/,
 323      dateSQL: set("date time timestamp"),
 324      support: set("ODBCdotTable decimallessFloat zerolessFloat binaryNumber hexNumber doubleQuote nCharCast charsetCast commentHash commentSpaceRequired"),
 325      hooks: {
 326        "@":   hookVar,
 327        "`":   hookIdentifier,
 328        "\\":  hookClient
 329      }
 330    });
 331  
 332    CodeMirror.defineMIME("text/x-mariadb", {
 333      name: "sql",
 334      client: set("charset clear connect edit ego exit go help nopager notee nowarning pager print prompt quit rehash source status system tee"),
 335      keywords: set(sqlKeywords + "accessible action add after algorithm all always analyze asensitive at authors auto_increment autocommit avg avg_row_length before binary binlog both btree cache call cascade cascaded case catalog_name chain change changed character check checkpoint checksum class_origin client_statistics close coalesce code collate collation collations column columns comment commit committed completion concurrent condition connection consistent constraint contains continue contributors convert cross current current_date current_time current_timestamp current_user cursor data database databases day_hour day_microsecond day_minute day_second deallocate dec declare default delay_key_write delayed delimiter des_key_file describe deterministic dev_pop dev_samp deviance diagnostics directory disable discard distinctrow div dual dumpfile each elseif enable enclosed end ends engine engines enum errors escape escaped even event events every execute exists exit explain extended fast fetch field fields first flush for force foreign found_rows full fulltext function general generated get global grant grants group group_concat handler hard hash help high_priority hosts hour_microsecond hour_minute hour_second if ignore ignore_server_ids import index index_statistics infile inner innodb inout insensitive insert_method install interval invoker isolation iterate key keys kill language last leading leave left level limit linear lines list load local localtime localtimestamp lock logs low_priority master master_heartbeat_period master_ssl_verify_server_cert masters match max max_rows maxvalue message_text middleint migrate min min_rows minute_microsecond minute_second mod mode modifies modify mutex mysql_errno natural next no no_write_to_binlog offline offset one online open optimize option optionally out outer outfile pack_keys parser partition partitions password persistent phase plugin plugins prepare preserve prev primary privileges procedure processlist profile profiles purge query quick range read read_write reads real rebuild recover references regexp relaylog release remove rename reorganize repair repeatable replace require resignal restrict resume return returns revoke right rlike rollback rollup row row_format rtree savepoint schedule schema schema_name schemas second_microsecond security sensitive separator serializable server session share show shutdown signal slave slow smallint snapshot soft soname spatial specific sql sql_big_result sql_buffer_result sql_cache sql_calc_found_rows sql_no_cache sql_small_result sqlexception sqlstate sqlwarning ssl start starting starts status std stddev stddev_pop stddev_samp storage straight_join subclass_origin sum suspend table_name table_statistics tables tablespace temporary terminated to trailing transaction trigger triggers truncate uncommitted undo uninstall unique unlock upgrade usage use use_frm user user_resources user_statistics using utc_date utc_time utc_timestamp value variables varying view views virtual warnings when while with work write xa xor year_month zerofill begin do then else loop repeat"),
 336      builtin: set("bool boolean bit blob decimal double float long longblob longtext medium mediumblob mediumint mediumtext time timestamp tinyblob tinyint tinytext text bigint int int1 int2 int3 int4 int8 integer float float4 float8 double char varbinary varchar varcharacter precision date datetime year unsigned signed numeric"),
 337      atoms: set("false true null unknown"),
 338      operatorChars: /^[*+\-%<>!=&|^]/,
 339      dateSQL: set("date time timestamp"),
 340      support: set("ODBCdotTable decimallessFloat zerolessFloat binaryNumber hexNumber doubleQuote nCharCast charsetCast commentHash commentSpaceRequired"),
 341      hooks: {
 342        "@":   hookVar,
 343        "`":   hookIdentifier,
 344        "\\":  hookClient
 345      }
 346    });
 347  
 348    // provided by the phpLiteAdmin project - phpliteadmin.org
 349    CodeMirror.defineMIME("text/x-sqlite", {
 350      name: "sql",
 351      // commands of the official SQLite client, ref: https://www.sqlite.org/cli.html#dotcmd
 352      client: set("auth backup bail binary changes check clone databases dbinfo dump echo eqp exit explain fullschema headers help import imposter indexes iotrace limit lint load log mode nullvalue once open output print prompt quit read restore save scanstats schema separator session shell show stats system tables testcase timeout timer trace vfsinfo vfslist vfsname width"),
 353      // ref: http://sqlite.org/lang_keywords.html
 354      keywords: set(sqlKeywords + "abort action add after all analyze attach autoincrement before begin cascade case cast check collate column commit conflict constraint cross current_date current_time current_timestamp database default deferrable deferred detach each else end escape except exclusive exists explain fail for foreign full glob if ignore immediate index indexed initially inner instead intersect isnull key left limit match natural no notnull null of offset outer plan pragma primary query raise recursive references regexp reindex release rename replace restrict right rollback row savepoint temp temporary then to transaction trigger unique using vacuum view virtual when with without"),
 355      // SQLite is weakly typed, ref: http://sqlite.org/datatype3.html. This is just a list of some common types.
 356      builtin: set("bool boolean bit blob decimal double float long longblob longtext medium mediumblob mediumint mediumtext time timestamp tinyblob tinyint tinytext text clob bigint int int2 int8 integer float double char varchar date datetime year unsigned signed numeric real"),
 357      // ref: http://sqlite.org/syntax/literal-value.html
 358      atoms: set("null current_date current_time current_timestamp"),
 359      // ref: http://sqlite.org/lang_expr.html#binaryops
 360      operatorChars: /^[*+\-%<>!=&|/~]/,
 361      // SQLite is weakly typed, ref: http://sqlite.org/datatype3.html. This is just a list of some common types.
 362      dateSQL: set("date time timestamp datetime"),
 363      support: set("decimallessFloat zerolessFloat"),
 364      identifierQuote: "\"",  //ref: http://sqlite.org/lang_keywords.html
 365      hooks: {
 366        // bind-parameters ref:http://sqlite.org/lang_expr.html#varparam
 367        "@":   hookVar,
 368        ":":   hookVar,
 369        "?":   hookVar,
 370        "$":   hookVar,
 371        // The preferred way to escape Identifiers is using double quotes, ref: http://sqlite.org/lang_keywords.html
 372        "\"":   hookIdentifierDoublequote,
 373        // there is also support for backticks, ref: http://sqlite.org/lang_keywords.html
 374        "`":   hookIdentifier
 375      }
 376    });
 377  
 378    // the query language used by Apache Cassandra is called CQL, but this mime type
 379    // is called Cassandra to avoid confusion with Contextual Query Language
 380    CodeMirror.defineMIME("text/x-cassandra", {
 381      name: "sql",
 382      client: { },
 383      keywords: set("add all allow alter and any apply as asc authorize batch begin by clustering columnfamily compact consistency count create custom delete desc distinct drop each_quorum exists filtering from grant if in index insert into key keyspace keyspaces level limit local_one local_quorum modify nan norecursive nosuperuser not of on one order password permission permissions primary quorum rename revoke schema select set storage superuser table three to token truncate ttl two type unlogged update use user users using values where with writetime"),
 384      builtin: set("ascii bigint blob boolean counter decimal double float frozen inet int list map static text timestamp timeuuid tuple uuid varchar varint"),
 385      atoms: set("false true infinity NaN"),
 386      operatorChars: /^[<>=]/,
 387      dateSQL: { },
 388      support: set("commentSlashSlash decimallessFloat"),
 389      hooks: { }
 390    });
 391  
 392    // this is based on Peter Raganitsch's 'plsql' mode
 393    CodeMirror.defineMIME("text/x-plsql", {
 394      name:       "sql",
 395      client:     set("appinfo arraysize autocommit autoprint autorecovery autotrace blockterminator break btitle cmdsep colsep compatibility compute concat copycommit copytypecheck define describe echo editfile embedded escape exec execute feedback flagger flush heading headsep instance linesize lno loboffset logsource long longchunksize markup native newpage numformat numwidth pagesize pause pno recsep recsepchar release repfooter repheader serveroutput shiftinout show showmode size spool sqlblanklines sqlcase sqlcode sqlcontinue sqlnumber sqlpluscompatibility sqlprefix sqlprompt sqlterminator suffix tab term termout time timing trimout trimspool ttitle underline verify version wrap"),
 396      keywords:   set("abort accept access add all alter and any array arraylen as asc assert assign at attributes audit authorization avg base_table begin between binary_integer body boolean by case cast char char_base check close cluster clusters colauth column comment commit compress connect connected constant constraint crash create current currval cursor data_base database date dba deallocate debugoff debugon decimal declare default definition delay delete desc digits dispose distinct do drop else elseif elsif enable end entry escape exception exception_init exchange exclusive exists exit external fast fetch file for force form from function generic goto grant group having identified if immediate in increment index indexes indicator initial initrans insert interface intersect into is key level library like limited local lock log logging long loop master maxextents maxtrans member minextents minus mislabel mode modify multiset new next no noaudit nocompress nologging noparallel not nowait number_base object of off offline on online only open option or order out package parallel partition pctfree pctincrease pctused pls_integer positive positiven pragma primary prior private privileges procedure public raise range raw read rebuild record ref references refresh release rename replace resource restrict return returning returns reverse revoke rollback row rowid rowlabel rownum rows run savepoint schema segment select separate session set share snapshot some space split sql start statement storage subtype successful synonym tabauth table tables tablespace task terminate then to trigger truncate type union unique unlimited unrecoverable unusable update use using validate value values variable view views when whenever where while with work"),
 397      builtin:    set("abs acos add_months ascii asin atan atan2 average bfile bfilename bigserial bit blob ceil character chartorowid chr clob concat convert cos cosh count dec decode deref dual dump dup_val_on_index empty error exp false float floor found glb greatest hextoraw initcap instr instrb int integer isopen last_day least length lengthb ln lower lpad ltrim lub make_ref max min mlslabel mod months_between natural naturaln nchar nclob new_time next_day nextval nls_charset_decl_len nls_charset_id nls_charset_name nls_initcap nls_lower nls_sort nls_upper nlssort no_data_found notfound null number numeric nvarchar2 nvl others power rawtohex real reftohex round rowcount rowidtochar rowtype rpad rtrim serial sign signtype sin sinh smallint soundex sqlcode sqlerrm sqrt stddev string substr substrb sum sysdate tan tanh to_char text to_date to_label to_multi_byte to_number to_single_byte translate true trunc uid unlogged upper user userenv varchar varchar2 variance varying vsize xml"),
 398      operatorChars: /^[*\/+\-%<>!=~]/,
 399      dateSQL:    set("date time timestamp"),
 400      support:    set("doubleQuote nCharCast zerolessFloat binaryNumber hexNumber")
 401    });
 402  
 403    // Created to support specific hive keywords
 404    CodeMirror.defineMIME("text/x-hive", {
 405      name: "sql",
 406      keywords: set("select alter $elem$ $key$ $value$ add after all analyze and archive as asc before between binary both bucket buckets by cascade case cast change cluster clustered clusterstatus collection column columns comment compute concatenate continue create cross cursor data database databases dbproperties deferred delete delimited desc describe directory disable distinct distribute drop else enable end escaped exclusive exists explain export extended external fetch fields fileformat first format formatted from full function functions grant group having hold_ddltime idxproperties if import in index indexes inpath inputdriver inputformat insert intersect into is items join keys lateral left like limit lines load local location lock locks mapjoin materialized minus msck no_drop nocompress not of offline on option or order out outer outputdriver outputformat overwrite partition partitioned partitions percent plus preserve procedure purge range rcfile read readonly reads rebuild recordreader recordwriter recover reduce regexp rename repair replace restrict revoke right rlike row schema schemas semi sequencefile serde serdeproperties set shared show show_database sort sorted ssl statistics stored streamtable table tables tablesample tblproperties temporary terminated textfile then tmp to touch transform trigger unarchive undo union uniquejoin unlock update use using utc utc_tmestamp view when where while with admin authorization char compact compactions conf cube current current_date current_timestamp day decimal defined dependency directories elem_type exchange file following for grouping hour ignore inner interval jar less logical macro minute month more none noscan over owner partialscan preceding pretty principals protection reload rewrite role roles rollup rows second server sets skewed transactions truncate unbounded unset uri user values window year"),
 407      builtin: set("bool boolean long timestamp tinyint smallint bigint int float double date datetime unsigned string array struct map uniontype key_type utctimestamp value_type varchar"),
 408      atoms: set("false true null unknown"),
 409      operatorChars: /^[*+\-%<>!=]/,
 410      dateSQL: set("date timestamp"),
 411      support: set("ODBCdotTable doubleQuote binaryNumber hexNumber")
 412    });
 413  
 414    CodeMirror.defineMIME("text/x-pgsql", {
 415      name: "sql",
 416      client: set("source"),
 417      // For PostgreSQL - https://www.postgresql.org/docs/11/sql-keywords-appendix.html
 418      // For pl/pgsql lang - https://github.com/postgres/postgres/blob/REL_11_2/src/pl/plpgsql/src/pl_scanner.c
 419      keywords: set(sqlKeywords + "a abort abs absent absolute access according action ada add admin after aggregate alias all allocate also alter always analyse analyze and any are array array_agg array_max_cardinality as asc asensitive assert assertion assignment asymmetric at atomic attach attribute attributes authorization avg backward base64 before begin begin_frame begin_partition bernoulli between bigint binary bit bit_length blob blocked bom boolean both breadth by c cache call called cardinality cascade cascaded case cast catalog catalog_name ceil ceiling chain char char_length character character_length character_set_catalog character_set_name character_set_schema characteristics characters check checkpoint class class_origin clob close cluster coalesce cobol collate collation collation_catalog collation_name collation_schema collect column column_name columns command_function command_function_code comment comments commit committed concurrently condition condition_number configuration conflict connect connection connection_name constant constraint constraint_catalog constraint_name constraint_schema constraints constructor contains content continue control conversion convert copy corr corresponding cost count covar_pop covar_samp create cross csv cube cume_dist current current_catalog current_date current_default_transform_group current_path current_role current_row current_schema current_time current_timestamp current_transform_group_for_type current_user cursor cursor_name cycle data database datalink datatype date datetime_interval_code datetime_interval_precision day db deallocate debug dec decimal declare default defaults deferrable deferred defined definer degree delete delimiter delimiters dense_rank depends depth deref derived desc describe descriptor detach detail deterministic diagnostics dictionary disable discard disconnect dispatch distinct dlnewcopy dlpreviouscopy dlurlcomplete dlurlcompleteonly dlurlcompletewrite dlurlpath dlurlpathonly dlurlpathwrite dlurlscheme dlurlserver dlvalue do document domain double drop dump dynamic dynamic_function dynamic_function_code each element else elseif elsif empty enable encoding encrypted end end_frame end_partition endexec enforced enum equals errcode error escape event every except exception exclude excluding exclusive exec execute exists exit exp explain expression extension external extract false family fetch file filter final first first_value flag float floor following for force foreach foreign fortran forward found frame_row free freeze from fs full function functions fusion g general generated get global go goto grant granted greatest group grouping groups handler having header hex hierarchy hint hold hour id identity if ignore ilike immediate immediately immutable implementation implicit import in include including increment indent index indexes indicator info inherit inherits initially inline inner inout input insensitive insert instance instantiable instead int integer integrity intersect intersection interval into invoker is isnull isolation join k key key_member key_type label lag language large last last_value lateral lead leading leakproof least left length level library like like_regex limit link listen ln load local localtime localtimestamp location locator lock locked log logged loop lower m map mapping match matched materialized max max_cardinality maxvalue member merge message message_length message_octet_length message_text method min minute minvalue mod mode modifies module month more move multiset mumps name names namespace national natural nchar nclob nesting new next nfc nfd nfkc nfkd nil no none normalize normalized not nothing notice notify notnull nowait nth_value ntile null nullable nullif nulls number numeric object occurrences_regex octet_length octets of off offset oids old on only open operator option options or order ordering ordinality others out outer output over overlaps overlay overriding owned owner p pad parallel parameter parameter_mode parameter_name parameter_ordinal_position parameter_specific_catalog parameter_specific_name parameter_specific_schema parser partial partition pascal passing passthrough password path percent percent_rank percentile_cont percentile_disc perform period permission pg_context pg_datatype_name pg_exception_context pg_exception_detail pg_exception_hint placing plans pli policy portion position position_regex power precedes preceding precision prepare prepared preserve primary print_strict_params prior privileges procedural procedure procedures program public publication query quote raise range rank read reads real reassign recheck recovery recursive ref references referencing refresh regr_avgx regr_avgy regr_count regr_intercept regr_r2 regr_slope regr_sxx regr_sxy regr_syy reindex relative release rename repeatable replace replica requiring reset respect restart restore restrict result result_oid return returned_cardinality returned_length returned_octet_length returned_sqlstate returning returns reverse revoke right role rollback rollup routine routine_catalog routine_name routine_schema routines row row_count row_number rows rowtype rule savepoint scale schema schema_name schemas scope scope_catalog scope_name scope_schema scroll search second section security select selective self sensitive sequence sequences serializable server server_name session session_user set setof sets share show similar simple size skip slice smallint snapshot some source space specific specific_name specifictype sql sqlcode sqlerror sqlexception sqlstate sqlwarning sqrt stable stacked standalone start state statement static statistics stddev_pop stddev_samp stdin stdout storage strict strip structure style subclass_origin submultiset subscription substring substring_regex succeeds sum symmetric sysid system system_time system_user t table table_name tables tablesample tablespace temp template temporary text then ties time timestamp timezone_hour timezone_minute to token top_level_count trailing transaction transaction_active transactions_committed transactions_rolled_back transform transforms translate translate_regex translation treat trigger trigger_catalog trigger_name trigger_schema trim trim_array true truncate trusted type types uescape unbounded uncommitted under unencrypted union unique unknown unlink unlisten unlogged unnamed unnest until untyped update upper uri usage use_column use_variable user user_defined_type_catalog user_defined_type_code user_defined_type_name user_defined_type_schema using vacuum valid validate validator value value_of values var_pop var_samp varbinary varchar variable_conflict variadic varying verbose version versioning view views volatile warning when whenever where while whitespace width_bucket window with within without work wrapper write xml xmlagg xmlattributes xmlbinary xmlcast xmlcomment xmlconcat xmldeclaration xmldocument xmlelement xmlexists xmlforest xmliterate xmlnamespaces xmlparse xmlpi xmlquery xmlroot xmlschema xmlserialize xmltable xmltext xmlvalidate year yes zone"),
 420      // https://www.postgresql.org/docs/11/datatype.html
 421      builtin: set("bigint int8 bigserial serial8 bit varying varbit boolean bool box bytea character char varchar cidr circle date double precision float8 inet integer int int4 interval json jsonb line lseg macaddr macaddr8 money numeric decimal path pg_lsn point polygon real float4 smallint int2 smallserial serial2 serial serial4 text time without zone with timetz timestamp timestamptz tsquery tsvector txid_snapshot uuid xml"),
 422      atoms: set("false true null unknown"),
 423      operatorChars: /^[*\/+\-%<>!=&|^\/#@?~]/,
 424      backslashStringEscapes: false,
 425      dateSQL: set("date time timestamp"),
 426      support: set("ODBCdotTable decimallessFloat zerolessFloat binaryNumber hexNumber nCharCast charsetCast escapeConstant")
 427    });
 428  
 429    // Google's SQL-like query language, GQL
 430    CodeMirror.defineMIME("text/x-gql", {
 431      name: "sql",
 432      keywords: set("ancestor and asc by contains desc descendant distinct from group has in is limit offset on order select superset where"),
 433      atoms: set("false true"),
 434      builtin: set("blob datetime first key __key__ string integer double boolean null"),
 435      operatorChars: /^[*+\-%<>!=]/
 436    });
 437  
 438    // Greenplum
 439    CodeMirror.defineMIME("text/x-gpsql", {
 440      name: "sql",
 441      client: set("source"),
 442      //https://github.com/greenplum-db/gpdb/blob/master/src/include/parser/kwlist.h
 443      keywords: set("abort absolute access action active add admin after aggregate all also alter always analyse analyze and any array as asc assertion assignment asymmetric at authorization backward before begin between bigint binary bit boolean both by cache called cascade cascaded case cast chain char character characteristics check checkpoint class close cluster coalesce codegen collate column comment commit committed concurrency concurrently configuration connection constraint constraints contains content continue conversion copy cost cpu_rate_limit create createdb createexttable createrole createuser cross csv cube current current_catalog current_date current_role current_schema current_time current_timestamp current_user cursor cycle data database day deallocate dec decimal declare decode default defaults deferrable deferred definer delete delimiter delimiters deny desc dictionary disable discard distinct distributed do document domain double drop dxl each else enable encoding encrypted end enum errors escape every except exchange exclude excluding exclusive execute exists explain extension external extract false family fetch fields filespace fill filter first float following for force foreign format forward freeze from full function global grant granted greatest group group_id grouping handler hash having header hold host hour identity if ignore ilike immediate immutable implicit in including inclusive increment index indexes inherit inherits initially inline inner inout input insensitive insert instead int integer intersect interval into invoker is isnull isolation join key language large last leading least left level like limit list listen load local localtime localtimestamp location lock log login mapping master match maxvalue median merge minute minvalue missing mode modifies modify month move name names national natural nchar new newline next no nocreatedb nocreateexttable nocreaterole nocreateuser noinherit nologin none noovercommit nosuperuser not nothing notify notnull nowait null nullif nulls numeric object of off offset oids old on only operator option options or order ordered others out outer over overcommit overlaps overlay owned owner parser partial partition partitions passing password percent percentile_cont percentile_disc placing plans position preceding precision prepare prepared preserve primary prior privileges procedural procedure protocol queue quote randomly range read readable reads real reassign recheck recursive ref references reindex reject relative release rename repeatable replace replica reset resource restart restrict returning returns revoke right role rollback rollup rootpartition row rows rule savepoint scatter schema scroll search second security segment select sequence serializable session session_user set setof sets share show similar simple smallint some split sql stable standalone start statement statistics stdin stdout storage strict strip subpartition subpartitions substring superuser symmetric sysid system table tablespace temp template temporary text then threshold ties time timestamp to trailing transaction treat trigger trim true truncate trusted type unbounded uncommitted unencrypted union unique unknown unlisten until update user using vacuum valid validation validator value values varchar variadic varying verbose version view volatile web when where whitespace window with within without work writable write xml xmlattributes xmlconcat xmlelement xmlexists xmlforest xmlparse xmlpi xmlroot xmlserialize year yes zone"),
 444      builtin: set("bigint int8 bigserial serial8 bit varying varbit boolean bool box bytea character char varchar cidr circle date double precision float float8 inet integer int int4 interval json jsonb line lseg macaddr macaddr8 money numeric decimal path pg_lsn point polygon real float4 smallint int2 smallserial serial2 serial serial4 text time without zone with timetz timestamp timestamptz tsquery tsvector txid_snapshot uuid xml"),
 445      atoms: set("false true null unknown"),
 446      operatorChars: /^[*+\-%<>!=&|^\/#@?~]/,
 447      dateSQL: set("date time timestamp"),
 448      support: set("ODBCdotTable decimallessFloat zerolessFloat binaryNumber hexNumber nCharCast charsetCast")
 449    });
 450  
 451    // Spark SQL
 452    CodeMirror.defineMIME("text/x-sparksql", {
 453      name: "sql",
 454      keywords: set("add after all alter analyze and anti archive array as asc at between bucket buckets by cache cascade case cast change clear cluster clustered codegen collection column columns comment commit compact compactions compute concatenate cost create cross cube current current_date current_timestamp database databases data dbproperties defined delete delimited deny desc describe dfs directories distinct distribute drop else end escaped except exchange exists explain export extended external false fields fileformat first following for format formatted from full function functions global grant group grouping having if ignore import in index indexes inner inpath inputformat insert intersect interval into is items join keys last lateral lazy left like limit lines list load local location lock locks logical macro map minus msck natural no not null nulls of on optimize option options or order out outer outputformat over overwrite partition partitioned partitions percent preceding principals purge range recordreader recordwriter recover reduce refresh regexp rename repair replace reset restrict revoke right rlike role roles rollback rollup row rows schema schemas select semi separated serde serdeproperties set sets show skewed sort sorted start statistics stored stratify struct table tables tablesample tblproperties temp temporary terminated then to touch transaction transactions transform true truncate unarchive unbounded uncache union unlock unset use using values view when where window with"),
 455      builtin: set("abs acos acosh add_months aggregate and any approx_count_distinct approx_percentile array array_contains array_distinct array_except array_intersect array_join array_max array_min array_position array_remove array_repeat array_sort array_union arrays_overlap arrays_zip ascii asin asinh assert_true atan atan2 atanh avg base64 between bigint bin binary bit_and bit_count bit_get bit_length bit_or bit_xor bool_and bool_or boolean bround btrim cardinality case cast cbrt ceil ceiling char char_length character_length chr coalesce collect_list collect_set concat concat_ws conv corr cos cosh cot count count_if count_min_sketch covar_pop covar_samp crc32 cume_dist current_catalog current_database current_date current_timestamp current_timezone current_user date date_add date_format date_from_unix_date date_part date_sub date_trunc datediff day dayofmonth dayofweek dayofyear decimal decode degrees delimited dense_rank div double e element_at elt encode every exists exp explode explode_outer expm1 extract factorial filter find_in_set first first_value flatten float floor forall format_number format_string from_csv from_json from_unixtime from_utc_timestamp get_json_object getbit greatest grouping grouping_id hash hex hour hypot if ifnull in initcap inline inline_outer input_file_block_length input_file_block_start input_file_name inputformat instr int isnan isnotnull isnull java_method json_array_length json_object_keys json_tuple kurtosis lag last last_day last_value lcase lead least left length levenshtein like ln locate log log10 log1p log2 lower lpad ltrim make_date make_dt_interval make_interval make_timestamp make_ym_interval map map_concat map_entries map_filter map_from_arrays map_from_entries map_keys map_values map_zip_with max max_by md5 mean min min_by minute mod monotonically_increasing_id month months_between named_struct nanvl negative next_day not now nth_value ntile nullif nvl nvl2 octet_length or outputformat overlay parse_url percent_rank percentile percentile_approx pi pmod posexplode posexplode_outer position positive pow power printf quarter radians raise_error rand randn random rank rcfile reflect regexp regexp_extract regexp_extract_all regexp_like regexp_replace repeat replace reverse right rint rlike round row_number rpad rtrim schema_of_csv schema_of_json second sentences sequence sequencefile serde session_window sha sha1 sha2 shiftleft shiftright shiftrightunsigned shuffle sign signum sin sinh size skewness slice smallint some sort_array soundex space spark_partition_id split sqrt stack std stddev stddev_pop stddev_samp str_to_map string struct substr substring substring_index sum tan tanh textfile timestamp timestamp_micros timestamp_millis timestamp_seconds tinyint to_csv to_date to_json to_timestamp to_unix_timestamp to_utc_timestamp transform transform_keys transform_values translate trim trunc try_add try_divide typeof ucase unbase64 unhex uniontype unix_date unix_micros unix_millis unix_seconds unix_timestamp upper uuid var_pop var_samp variance version weekday weekofyear when width_bucket window xpath xpath_boolean xpath_double xpath_float xpath_int xpath_long xpath_number xpath_short xpath_string xxhash64 year zip_with"),
 456      atoms: set("false true null"),
 457      operatorChars: /^[*\/+\-%<>!=~&|^]/,
 458      dateSQL: set("date time timestamp"),
 459      support: set("ODBCdotTable doubleQuote zerolessFloat")
 460    });
 461  
 462    // Esper
 463    CodeMirror.defineMIME("text/x-esper", {
 464      name: "sql",
 465      client: set("source"),
 466      // http://www.espertech.com/esper/release-5.5.0/esper-reference/html/appendix_keywords.html
 467      keywords: set("alter and as asc between by count create delete desc distinct drop from group having in insert into is join like not on or order select set table union update values where limit after all and as at asc avedev avg between by case cast coalesce count create current_timestamp day days delete define desc distinct else end escape events every exists false first from full group having hour hours in inner insert instanceof into irstream is istream join last lastweekday left limit like max match_recognize matches median measures metadatasql min minute minutes msec millisecond milliseconds not null offset on or order outer output partition pattern prev prior regexp retain-union retain-intersection right rstream sec second seconds select set some snapshot sql stddev sum then true unidirectional until update variable weekday when where window"),
 468      builtin: {},
 469      atoms: set("false true null"),
 470      operatorChars: /^[*+\-%<>!=&|^\/#@?~]/,
 471      dateSQL: set("time"),
 472      support: set("decimallessFloat zerolessFloat binaryNumber hexNumber")
 473    });
 474  });
 475  
 476  /*
 477    How Properties of Mime Types are used by SQL Mode
 478    =================================================
 479  
 480    keywords:
 481      A list of keywords you want to be highlighted.
 482    builtin:
 483      A list of builtin types you want to be highlighted (if you want types to be of class "builtin" instead of "keyword").
 484    operatorChars:
 485      All characters that must be handled as operators.
 486    client:
 487      Commands parsed and executed by the client (not the server).
 488    support:
 489      A list of supported syntaxes which are not common, but are supported by more than 1 DBMS.
 490      * ODBCdotTable: .tableName
 491      * zerolessFloat: .1
 492      * doubleQuote
 493      * nCharCast: N'string'
 494      * charsetCast: _utf8'string'
 495      * commentHash: use # char for comments
 496      * commentSlashSlash: use // for comments
 497      * commentSpaceRequired: require a space after -- for comments
 498    atoms:
 499      Keywords that must be highlighted as atoms,. Some DBMS's support more atoms than others:
 500      UNKNOWN, INFINITY, UNDERFLOW, NaN...
 501    dateSQL:
 502      Used for date/time SQL standard syntax, because not all DBMS's support same temporal types.
 503  */


Generated: Wed Sep 7 05:41:13 2022 Chilli.vc Blog - For Webmaster,Blog-Writer,System Admin and Domainer