Passed
Push — master ( 3324e2...2ba76b )
by Ralf
13:44
created

sql.js ➔ tokenBase   F

Complexity

Conditions 28

Size

Total Lines 92
Code Lines 59

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
eloc 59
c 0
b 0
f 0
dl 0
loc 92
rs 0
cc 28

How to fix   Long Method    Complexity   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

Complexity

Complex classes like sql.js ➔ tokenBase often do a lot of different things. To break such a class down, we need to identify a cohesive component within that class. A common approach to find such a component is to look for fields/methods that share the same prefixes, or suffixes.

Once you have determined the fields that belong together, you can apply the Extract Class refactoring. If the component makes sense as a sub-class, Extract Subclass is also a candidate, and is often faster.

1
// CodeMirror, copyright (c) by Marijn Haverbeke and others
2
// Distributed under an MIT license: http://codemirror.net/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
0 ignored issues
show
Bug introduced by
The variable define seems to be never declared. If this is a global, consider adding a /** global: define */ comment.

This checks looks for references to variables that have not been declared. This is most likey a typographical error or a variable has been renamed.

To learn more about declaring variables in Javascript, see the MDN.

Loading history...
8
    define(["../../lib/codemirror"], mod);
9
  else // Plain browser env
10
    mod(CodeMirror);
0 ignored issues
show
Bug introduced by
The variable CodeMirror seems to be never declared. If this is a global, consider adding a /** global: CodeMirror */ comment.

This checks looks for references to variables that have not been declared. This is most likey a typographical error or a variable has been renamed.

To learn more about declaring variables in Javascript, see the MDN.

Loading history...
11
})(function(CodeMirror) {
12
"use strict";
13
14
CodeMirror.defineMode("sql", function(config, parserConfig) {
15
  "use strict";
16
17
  var client         = parserConfig.client || {},
18
      atoms          = parserConfig.atoms || {"false": true, "true": true, "null": true},
19
      builtin        = parserConfig.builtin || {},
20
      keywords       = parserConfig.keywords || {},
21
      operatorChars  = parserConfig.operatorChars || /^[*+\-%<>!=&|~^]/,
22
      support        = parserConfig.support || {},
23
      hooks          = parserConfig.hooks || {},
24
      dateSQL        = parserConfig.dateSQL || {"date" : true, "time" : true, "timestamp" : true};
25
26
  function tokenBase(stream, state) {
27
    var ch = stream.next();
28
29
    // call hooks from the mime type
30
    if (hooks[ch]) {
31
      var result = hooks[ch](stream, state);
32
      if (result !== false) return result;
33
    }
34
35
    if (support.hexNumber == true &&
0 ignored issues
show
Best Practice introduced by
Comparing support.hexNumber to true using the == operator is not safe. Consider using === instead.
Loading history...
36
      ((ch == "0" && stream.match(/^[xX][0-9a-fA-F]+/))
37
      || (ch == "x" || ch == "X") && stream.match(/^'[0-9a-fA-F]+'/))) {
38
      // hex
39
      // ref: http://dev.mysql.com/doc/refman/5.5/en/hexadecimal-literals.html
40
      return "number";
41
    } else if (support.binaryNumber == true &&
0 ignored issues
show
Best Practice introduced by
Comparing support.binaryNumber to true using the == operator is not safe. Consider using === instead.
Loading history...
42
      (((ch == "b" || ch == "B") && stream.match(/^'[01]+'/))
43
      || (ch == "0" && stream.match(/^b[01]+/)))) {
44
      // bitstring
45
      // ref: http://dev.mysql.com/doc/refman/5.5/en/bit-field-literals.html
46
      return "number";
47
    } else if (ch.charCodeAt(0) > 47 && ch.charCodeAt(0) < 58) {
48
      // numbers
49
      // ref: http://dev.mysql.com/doc/refman/5.5/en/number-literals.html
50
          stream.match(/^[0-9]*\.?[0-9]+([eE][-+]?[0-9]+)?/);
51
      support.decimallessFloat == true && stream.eat('.');
0 ignored issues
show
Best Practice introduced by
Comparing support.decimallessFloat to true using the == operator is not safe. Consider using === instead.
Loading history...
52
      return "number";
53
    } else if (ch == "?" && (stream.eatSpace() || stream.eol() || stream.eat(";"))) {
54
      // placeholders
55
      return "variable-3";
56
    } else if (ch == "'" || (ch == '"' && support.doubleQuote)) {
57
      // strings
58
      // ref: http://dev.mysql.com/doc/refman/5.5/en/string-literals.html
59
      state.tokenize = tokenLiteral(ch);
60
      return state.tokenize(stream, state);
61
    } else if ((((support.nCharCast == true && (ch == "n" || ch == "N"))
0 ignored issues
show
Best Practice introduced by
Comparing support.nCharCast to true using the == operator is not safe. Consider using === instead.
Loading history...
62
        || (support.charsetCast == true && ch == "_" && stream.match(/[a-z][a-z0-9]*/i)))
0 ignored issues
show
Best Practice introduced by
Comparing support.charsetCast to true using the == operator is not safe. Consider using === instead.
Loading history...
63
        && (stream.peek() == "'" || stream.peek() == '"'))) {
64
      // charset casting: _utf8'str', N'str', n'str'
65
      // ref: http://dev.mysql.com/doc/refman/5.5/en/string-literals.html
66
      return "keyword";
67
    } else if (/^[\(\),\;\[\]]/.test(ch)) {
68
      // no highlightning
69
      return null;
70
    } else if (support.commentSlashSlash && ch == "/" && stream.eat("/")) {
71
      // 1-line comment
72
      stream.skipToEnd();
73
      return "comment";
74
    } else if ((support.commentHash && ch == "#")
75
        || (ch == "-" && stream.eat("-") && (!support.commentSpaceRequired || stream.eat(" ")))) {
76
      // 1-line comments
77
      // ref: https://kb.askmonty.org/en/comment-syntax/
78
      stream.skipToEnd();
79
      return "comment";
80
    } else if (ch == "/" && stream.eat("*")) {
81
      // multi-line comments
82
      // ref: https://kb.askmonty.org/en/comment-syntax/
83
      state.tokenize = tokenComment;
84
      return state.tokenize(stream, state);
85
    } else if (ch == ".") {
86
      // .1 for 0.1
87
      if (support.zerolessFloat == true && stream.match(/^(?:\d+(?:e[+-]?\d+)?)/i)) {
0 ignored issues
show
Best Practice introduced by
Comparing support.zerolessFloat to true using the == operator is not safe. Consider using === instead.
Loading history...
88
        return "number";
89
      }
90
      // .table_name (ODBC)
91
      // // ref: http://dev.mysql.com/doc/refman/5.6/en/identifier-qualifiers.html
92
      if (support.ODBCdotTable == true && stream.match(/^[a-zA-Z_]+/)) {
0 ignored issues
show
Complexity Best Practice introduced by
There is no return statement if support.ODBCdotTable == ...ream.match(^[a-zA-Z_]+) is false. Are you sure this is correct? If so, consider adding return; explicitly.

This check looks for functions where a return statement is found in some execution paths, but not in all.

Consider this little piece of code

function isBig(a) {
    if (a > 5000) {
        return "yes";
    }
}

console.log(isBig(5001)); //returns yes
console.log(isBig(42)); //returns undefined

The function isBig will only return a specific value when its parameter is bigger than 5000. In any other case, it will implicitly return undefined.

This behaviour may not be what you had intended. In any case, you can add a return undefined to the other execution path to make the return value explicit.

Loading history...
Best Practice introduced by
Comparing support.ODBCdotTable to true using the == operator is not safe. Consider using === instead.
Loading history...
93
        return "variable-2";
94
      }
95
    } else if (operatorChars.test(ch)) {
96
      // operators
97
      stream.eatWhile(operatorChars);
98
      return null;
99
    } else if (ch == '{' &&
100
        (stream.match(/^( )*(d|D|t|T|ts|TS)( )*'[^']*'( )*}/) || stream.match(/^( )*(d|D|t|T|ts|TS)( )*"[^"]*"( )*}/))) {
101
      // dates (weird ODBC syntax)
102
      // ref: http://dev.mysql.com/doc/refman/5.5/en/date-and-time-literals.html
103
      return "number";
104
    } else {
105
      stream.eatWhile(/^[_\w\d]/);
106
      var word = stream.current().toLowerCase();
107
      // dates (standard SQL syntax)
108
      // ref: http://dev.mysql.com/doc/refman/5.5/en/date-and-time-literals.html
109
      if (dateSQL.hasOwnProperty(word) && (stream.match(/^( )+'[^']*'/) || stream.match(/^( )+"[^"]*"/)))
110
        return "number";
111
      if (atoms.hasOwnProperty(word)) return "atom";
112
      if (builtin.hasOwnProperty(word)) return "builtin";
113
      if (keywords.hasOwnProperty(word)) return "keyword";
114
      if (client.hasOwnProperty(word)) return "string-2";
115
      return null;
116
    }
117
  }
118
119
  // 'string', with char specified in quote escaped by '\'
120
  function tokenLiteral(quote) {
121
    return function(stream, state) {
122
      var escaped = false, ch;
123
      while ((ch = stream.next()) != null) {
0 ignored issues
show
Best Practice introduced by
Comparing ch = stream.next() to null using the != operator is not safe. Consider using !== instead.
Loading history...
124
        if (ch == quote && !escaped) {
125
          state.tokenize = tokenBase;
126
          break;
127
        }
128
        escaped = !escaped && ch == "\\";
129
      }
130
      return "string";
131
    };
132
  }
133
  function tokenComment(stream, state) {
134
    while (true) {
135
      if (stream.skipTo("*")) {
136
        stream.next();
137
        if (stream.eat("/")) {
138
          state.tokenize = tokenBase;
139
          break;
140
        }
141
      } else {
142
        stream.skipToEnd();
143
        break;
144
      }
145
    }
146
    return "comment";
147
  }
148
149
  function pushContext(stream, state, type) {
150
    state.context = {
151
      prev: state.context,
152
      indent: stream.indentation(),
153
      col: stream.column(),
154
      type: type
155
    };
156
  }
157
158
  function popContext(state) {
159
    state.indent = state.context.indent;
160
    state.context = state.context.prev;
161
  }
162
163
  return {
164
    startState: function() {
165
      return {tokenize: tokenBase, context: null};
166
    },
167
168
    token: function(stream, state) {
169
      if (stream.sol()) {
170
        if (state.context && state.context.align == null)
0 ignored issues
show
Best Practice introduced by
Comparing state.context.align to null using the == operator is not safe. Consider using === instead.
Loading history...
171
          state.context.align = false;
172
      }
173
      if (stream.eatSpace()) return null;
174
175
      var style = state.tokenize(stream, state);
176
      if (style == "comment") return style;
177
178
      if (state.context && state.context.align == null)
179
        state.context.align = true;
180
181
      var tok = stream.current();
182
      if (tok == "(")
183
        pushContext(stream, state, ")");
184
      else if (tok == "[")
185
        pushContext(stream, state, "]");
186
      else if (state.context && state.context.type == tok)
187
        popContext(state);
188
      return style;
189
    },
190
191
    indent: function(state, textAfter) {
192
      var cx = state.context;
193
      if (!cx) return CodeMirror.Pass;
194
      var closing = textAfter.charAt(0) == cx.type;
195
      if (cx.align) return cx.col + (closing ? 0 : 1);
196
      else return cx.indent + (closing ? 0 : config.indentUnit);
0 ignored issues
show
Comprehensibility introduced by
else is not necessary here since all if branches return, consider removing it to reduce nesting and make code more readable.
Loading history...
197
    },
198
199
    blockCommentStart: "/*",
200
    blockCommentEnd: "*/",
201
    lineComment: support.commentSlashSlash ? "//" : support.commentHash ? "#" : null
202
  };
203
});
204
205
(function() {
206
  "use strict";
207
208
  // `identifier`
209
  function hookIdentifier(stream) {
210
    // MySQL/MariaDB identifiers
211
    // ref: http://dev.mysql.com/doc/refman/5.6/en/identifier-qualifiers.html
212
    var ch;
213
    while ((ch = stream.next()) != null) {
0 ignored issues
show
Best Practice introduced by
Comparing ch = stream.next() to null using the != operator is not safe. Consider using !== instead.
Loading history...
214
      if (ch == "`" && !stream.eat("`")) return "variable-2";
215
    }
216
    stream.backUp(stream.current().length - 1);
217
    return stream.eatWhile(/\w/) ? "variable-2" : null;
218
  }
219
220
  // variable token
221
  function hookVar(stream) {
222
    // variables
223
    // @@prefix.varName @varName
224
    // varName can be quoted with ` or ' or "
225
    // ref: http://dev.mysql.com/doc/refman/5.5/en/user-variables.html
226
    if (stream.eat("@")) {
227
      stream.match(/^session\./);
228
      stream.match(/^local\./);
229
      stream.match(/^global\./);
230
    }
231
232
    if (stream.eat("'")) {
233
      stream.match(/^.*'/);
234
      return "variable-2";
235
    } else if (stream.eat('"')) {
236
      stream.match(/^.*"/);
237
      return "variable-2";
238
    } else if (stream.eat("`")) {
239
      stream.match(/^.*`/);
240
      return "variable-2";
241
    } else if (stream.match(/^[0-9a-zA-Z$\.\_]+/)) {
242
      return "variable-2";
243
    }
244
    return null;
245
  };
246
247
  // short client keyword token
248
  function hookClient(stream) {
249
    // \N means NULL
250
    // ref: http://dev.mysql.com/doc/refman/5.5/en/null-values.html
251
    if (stream.eat("N")) {
252
        return "atom";
253
    }
254
    // \g, etc
255
    // ref: http://dev.mysql.com/doc/refman/5.5/en/mysql-commands.html
256
    return stream.match(/^[a-zA-Z.#!?]/) ? "variable-2" : null;
257
  }
258
259
  // these keywords are used by all SQL dialects (however, a mode can still overwrite it)
260
  var sqlKeywords = "alter and as asc between by count create delete desc distinct drop from having in insert into is join like not on or order select set table union update values where ";
261
262
  // turn a space-separated list into an array
263
  function set(str) {
264
    var obj = {}, words = str.split(" ");
265
    for (var i = 0; i < words.length; ++i) obj[words[i]] = true;
266
    return obj;
267
  }
268
269
  // A generic SQL Mode. It's not a standard, it just try to support what is generally supported
270
  CodeMirror.defineMIME("text/x-sql", {
271
    name: "sql",
272
    keywords: set(sqlKeywords + "begin"),
273
    builtin: set("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"),
274
    atoms: set("false true null unknown"),
275
    operatorChars: /^[*+\-%<>!=]/,
276
    dateSQL: set("date time timestamp"),
277
    support: set("ODBCdotTable doubleQuote binaryNumber hexNumber")
278
  });
279
280
  CodeMirror.defineMIME("text/x-mssql", {
281
    name: "sql",
282
    client: set("charset clear connect edit ego exit go help nopager notee nowarning pager print prompt quit rehash source status system tee"),
283
    keywords: set(sqlKeywords + "begin trigger proc view index for add constraint key primary foreign collate clustered nonclustered"),
284
    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 "),
285
    atoms: set("false true null unknown"),
286
    operatorChars: /^[*+\-%<>!=]/,
287
    dateSQL: set("date datetimeoffset datetime2 smalldatetime datetime time"),
288
    hooks: {
289
      "@":   hookVar
290
    }
291
  });
292
293
  CodeMirror.defineMIME("text/x-mysql", {
294
    name: "sql",
295
    client: set("charset clear connect edit ego exit go help nopager notee nowarning pager print prompt quit rehash source status system tee"),
296
    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 groupby_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"),
297
    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"),
298
    atoms: set("false true null unknown"),
299
    operatorChars: /^[*+\-%<>!=&|^]/,
300
    dateSQL: set("date time timestamp"),
301
    support: set("ODBCdotTable decimallessFloat zerolessFloat binaryNumber hexNumber doubleQuote nCharCast charsetCast commentHash commentSpaceRequired"),
302
    hooks: {
303
      "@":   hookVar,
304
      "`":   hookIdentifier,
305
      "\\":  hookClient
306
    }
307
  });
308
309
  CodeMirror.defineMIME("text/x-mariadb", {
310
    name: "sql",
311
    client: set("charset clear connect edit ego exit go help nopager notee nowarning pager print prompt quit rehash source status system tee"),
312
    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 groupby_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"),
313
    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"),
314
    atoms: set("false true null unknown"),
315
    operatorChars: /^[*+\-%<>!=&|^]/,
316
    dateSQL: set("date time timestamp"),
317
    support: set("ODBCdotTable decimallessFloat zerolessFloat binaryNumber hexNumber doubleQuote nCharCast charsetCast commentHash commentSpaceRequired"),
318
    hooks: {
319
      "@":   hookVar,
320
      "`":   hookIdentifier,
321
      "\\":  hookClient
322
    }
323
  });
324
325
  // the query language used by Apache Cassandra is called CQL, but this mime type
326
  // is called Cassandra to avoid confusion with Contextual Query Language
327
  CodeMirror.defineMIME("text/x-cassandra", {
328
    name: "sql",
329
    client: { },
330
    keywords: set("use select from using consistency where limit first reversed first and in insert into values using consistency ttl update set delete truncate begin batch apply create keyspace with columnfamily primary key index on drop alter type add any one quorum all local_quorum each_quorum"),
331
    builtin: set("ascii bigint blob boolean counter decimal double float int text timestamp uuid varchar varint"),
332
    atoms: set("false true"),
333
    operatorChars: /^[<>=]/,
334
    dateSQL: { },
335
    support: set("commentSlashSlash decimallessFloat"),
336
    hooks: { }
337
  });
338
339
  // this is based on Peter Raganitsch's 'plsql' mode
340
  CodeMirror.defineMIME("text/x-plsql", {
341
    name:       "sql",
342
    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"),
343
    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"),
344
    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 lenght lenghtb 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"),
345
    operatorChars: /^[*+\-%<>!=~]/,
346
    dateSQL:    set("date time timestamp"),
347
    support:    set("doubleQuote nCharCast zerolessFloat binaryNumber hexNumber")
348
  });
349
350
  // Created to support specific hive keywords
351
  CodeMirror.defineMIME("text/x-hive", {
352
    name: "sql",
353
    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 false 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 true unarchive undo union uniquejoin unlock update use using utc utc_tmestamp view when where while with"),
354
    builtin: set("bool boolean long timestamp tinyint smallint bigint int float double date datetime unsigned string array struct map uniontype"),
355
    atoms: set("false true null unknown"),
356
    operatorChars: /^[*+\-%<>!=]/,
357
    dateSQL: set("date timestamp"),
358
    support: set("ODBCdotTable doubleQuote binaryNumber hexNumber")
359
  });
360
}());
361
362
});
363
364
/*
365
  How Properties of Mime Types are used by SQL Mode
366
  =================================================
367
368
  keywords:
369
    A list of keywords you want to be highlighted.
370
  builtin:
371
    A list of builtin types you want to be highlighted (if you want types to be of class "builtin" instead of "keyword").
372
  operatorChars:
373
    All characters that must be handled as operators.
374
  client:
375
    Commands parsed and executed by the client (not the server).
376
  support:
377
    A list of supported syntaxes which are not common, but are supported by more than 1 DBMS.
378
    * ODBCdotTable: .tableName
379
    * zerolessFloat: .1
380
    * doubleQuote
381
    * nCharCast: N'string'
382
    * charsetCast: _utf8'string'
383
    * commentHash: use # char for comments
384
    * commentSlashSlash: use // for comments
385
    * commentSpaceRequired: require a space after -- for comments
386
  atoms:
387
    Keywords that must be highlighted as atoms,. Some DBMS's support more atoms than others:
388
    UNKNOWN, INFINITY, UNDERFLOW, NaN...
389
  dateSQL:
390
    Used for date/time SQL standard syntax, because not all DBMS's support same temporal types.
391
*/
392