Fix: merge conflict
[myslice.git] / third-party / codemirror-3.15 / mode / sql / sql.js
1 CodeMirror.defineMode("sql", function(config, parserConfig) {
2   "use strict";
3
4   var client         = parserConfig.client || {},
5       atoms          = parserConfig.atoms || {"false": true, "true": true, "null": true},
6       builtin        = parserConfig.builtin || {},
7       keywords       = parserConfig.keywords || {},
8       operatorChars  = parserConfig.operatorChars || /^[*+\-%<>!=&|~^]/,
9       support        = parserConfig.support || {},
10       hooks          = parserConfig.hooks || {},
11       dateSQL        = parserConfig.dateSQL || {"date" : true, "time" : true, "timestamp" : true};
12
13   function tokenBase(stream, state) {
14     var ch = stream.next();
15
16     // call hooks from the mime type
17     if (hooks[ch]) {
18       var result = hooks[ch](stream, state);
19       if (result !== false) return result;
20     }
21
22     if (support.hexNumber == true &&
23       ((ch == "0" && stream.match(/^[xX][0-9a-fA-F]+/))
24       || (ch == "x" || ch == "X") && stream.match(/^'[0-9a-fA-F]+'/))) {
25       // hex
26       // ref: http://dev.mysql.com/doc/refman/5.5/en/hexadecimal-literals.html
27       return "number";
28     } else if (support.binaryNumber == true &&
29       (((ch == "b" || ch == "B") && stream.match(/^'[01]+'/))
30       || (ch == "0" && stream.match(/^b[01]+/)))) {
31       // bitstring
32       // ref: http://dev.mysql.com/doc/refman/5.5/en/bit-field-literals.html
33       return "number";
34     } else if (ch.charCodeAt(0) > 47 && ch.charCodeAt(0) < 58) {
35       // numbers
36       // ref: http://dev.mysql.com/doc/refman/5.5/en/number-literals.html
37           stream.match(/^[0-9]*\.?[0-9]+([eE][-+]?[0-9]+)?/);
38       support.decimallessFloat == true && stream.eat('.');
39       return "number";
40     } else if (ch == "?" && (stream.eatSpace() || stream.eol() || stream.eat(";"))) {
41       // placeholders
42       return "variable-3";
43     } else if (ch == "'" || (ch == '"' && support.doubleQuote)) {
44       // strings
45       // ref: http://dev.mysql.com/doc/refman/5.5/en/string-literals.html
46       state.tokenize = tokenLiteral(ch);
47       return state.tokenize(stream, state);
48     } else if ((((support.nCharCast == true && (ch == "n" || ch == "N"))
49         || (support.charsetCast == true && ch == "_" && stream.match(/[a-z][a-z0-9]*/i)))
50         && (stream.peek() == "'" || stream.peek() == '"'))) {
51       // charset casting: _utf8'str', N'str', n'str'
52       // ref: http://dev.mysql.com/doc/refman/5.5/en/string-literals.html
53       return "keyword";
54     } else if (/^[\(\),\;\[\]]/.test(ch)) {
55       // no highlightning
56       return null;
57     } else if (support.commentSlashSlash && ch == "/" && stream.eat("/")) {
58       // 1-line comment
59       stream.skipToEnd();
60       return "comment";
61     } else if ((support.commentHash && ch == "#")
62         || (ch == "-" && stream.eat("-") && (!support.commentSpaceRequired || stream.eat(" ")))) {
63       // 1-line comments
64       // ref: https://kb.askmonty.org/en/comment-syntax/
65       stream.skipToEnd();
66       return "comment";
67     } else if (ch == "/" && stream.eat("*")) {
68       // multi-line comments
69       // ref: https://kb.askmonty.org/en/comment-syntax/
70       state.tokenize = tokenComment;
71       return state.tokenize(stream, state);
72     } else if (ch == ".") {
73       // .1 for 0.1
74       if (support.zerolessFloat == true && stream.match(/^(?:\d+(?:e[+-]?\d+)?)/i)) {
75         return "number";
76       }
77       // .table_name (ODBC)
78       // // ref: http://dev.mysql.com/doc/refman/5.6/en/identifier-qualifiers.html
79       if (support.ODBCdotTable == true && stream.match(/^[a-zA-Z_]+/)) {
80         return "variable-2";
81       }
82     } else if (operatorChars.test(ch)) {
83       // operators
84       stream.eatWhile(operatorChars);
85       return null;
86     } else if (ch == '{' &&
87         (stream.match(/^( )*(d|D|t|T|ts|TS)( )*'[^']*'( )*}/) || stream.match(/^( )*(d|D|t|T|ts|TS)( )*"[^"]*"( )*}/))) {
88       // dates (weird ODBC syntax)
89       // ref: http://dev.mysql.com/doc/refman/5.5/en/date-and-time-literals.html
90       return "number";
91     } else {
92       stream.eatWhile(/^[_\w\d]/);
93       var word = stream.current().toLowerCase();
94       // dates (standard SQL syntax)
95       // ref: http://dev.mysql.com/doc/refman/5.5/en/date-and-time-literals.html
96       if (dateSQL.hasOwnProperty(word) && (stream.match(/^( )+'[^']*'/) || stream.match(/^( )+"[^"]*"/)))
97         return "number";
98       if (atoms.hasOwnProperty(word)) return "atom";
99       if (builtin.hasOwnProperty(word)) return "builtin";
100       if (keywords.hasOwnProperty(word)) return "keyword";
101       if (client.hasOwnProperty(word)) return "string-2";
102       return null;
103     }
104   }
105
106   // 'string', with char specified in quote escaped by '\'
107   function tokenLiteral(quote) {
108     return function(stream, state) {
109       var escaped = false, ch;
110       while ((ch = stream.next()) != null) {
111         if (ch == quote && !escaped) {
112           state.tokenize = tokenBase;
113           break;
114         }
115         escaped = !escaped && ch == "\\";
116       }
117       return "string";
118     };
119   }
120   function tokenComment(stream, state) {
121     while (true) {
122       if (stream.skipTo("*")) {
123         stream.next();
124         if (stream.eat("/")) {
125           state.tokenize = tokenBase;
126           break;
127         }
128       } else {
129         stream.skipToEnd();
130         break;
131       }
132     }
133     return "comment";
134   }
135
136   function pushContext(stream, state, type) {
137     state.context = {
138       prev: state.context,
139       indent: stream.indentation(),
140       col: stream.column(),
141       type: type
142     };
143   }
144
145   function popContext(state) {
146     state.indent = state.context.indent;
147     state.context = state.context.prev;
148   }
149
150   return {
151     startState: function() {
152       return {tokenize: tokenBase, context: null};
153     },
154
155     token: function(stream, state) {
156       if (stream.sol()) {
157         if (state.context && state.context.align == null)
158           state.context.align = false;
159       }
160       if (stream.eatSpace()) return null;
161
162       var style = state.tokenize(stream, state);
163       if (style == "comment") return style;
164
165       if (state.context && state.context.align == null)
166         state.context.align = true;
167
168       var tok = stream.current();
169       if (tok == "(")
170         pushContext(stream, state, ")");
171       else if (tok == "[")
172         pushContext(stream, state, "]");
173       else if (state.context && state.context.type == tok)
174         popContext(state);
175       return style;
176     },
177
178     indent: function(state, textAfter) {
179       var cx = state.context;
180       if (!cx) return CodeMirror.Pass;
181       if (cx.align) return cx.col + (textAfter.charAt(0) == cx.type ? 0 : 1);
182       else return cx.indent + config.indentUnit;
183     }
184   };
185 });
186
187 (function() {
188   "use strict";
189
190   // `identifier`
191   function hookIdentifier(stream) {
192     // MySQL/MariaDB identifiers
193     // ref: http://dev.mysql.com/doc/refman/5.6/en/identifier-qualifiers.html
194     var ch;
195     while ((ch = stream.next()) != null) {
196       if (ch == "`" && !stream.eat("`")) return "variable-2";
197     }
198     return null;
199   }
200
201   // variable token
202   function hookVar(stream) {
203     // variables
204     // @@prefix.varName @varName
205     // varName can be quoted with ` or ' or "
206     // ref: http://dev.mysql.com/doc/refman/5.5/en/user-variables.html
207     if (stream.eat("@")) {
208       stream.match(/^session\./);
209       stream.match(/^local\./);
210       stream.match(/^global\./);
211     }
212
213     if (stream.eat("'")) {
214       stream.match(/^.*'/);
215       return "variable-2";
216     } else if (stream.eat('"')) {
217       stream.match(/^.*"/);
218       return "variable-2";
219     } else if (stream.eat("`")) {
220       stream.match(/^.*`/);
221       return "variable-2";
222     } else if (stream.match(/^[0-9a-zA-Z$\.\_]+/)) {
223       return "variable-2";
224     }
225     return null;
226   };
227
228   // short client keyword token
229   function hookClient(stream) {
230     // \N means NULL
231     // ref: http://dev.mysql.com/doc/refman/5.5/en/null-values.html
232     if (stream.eat("N")) {
233         return "atom";
234     }
235     // \g, etc
236     // ref: http://dev.mysql.com/doc/refman/5.5/en/mysql-commands.html
237     return stream.match(/^[a-zA-Z.#!?]/) ? "variable-2" : null;
238   }
239
240   // these keywords are used by all SQL dialects (however, a mode can still overwrite it)
241   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 ";
242
243   // turn a space-separated list into an array
244   function set(str) {
245     var obj = {}, words = str.split(" ");
246     for (var i = 0; i < words.length; ++i) obj[words[i]] = true;
247     return obj;
248   }
249
250   // A generic SQL Mode. It's not a standard, it just try to support what is generally supported
251   CodeMirror.defineMIME("text/x-sql", {
252     name: "sql",
253     keywords: set(sqlKeywords + "begin"),
254     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"),
255     atoms: set("false true null unknown"),
256     operatorChars: /^[*+\-%<>!=]/,
257     dateSQL: set("date time timestamp"),
258     support: set("ODBCdotTable doubleQuote binaryNumber hexNumber")
259   });
260
261   CodeMirror.defineMIME("text/x-mysql", {
262     name: "sql",
263     client: set("charset clear connect edit ego exit go help nopager notee nowarning pager print prompt quit rehash source status system tee"),
264     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_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 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 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"),
265     builtin: set("bool boolean bit blob decimal double enum 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"),
266     atoms: set("false true null unknown"),
267     operatorChars: /^[*+\-%<>!=&|^]/,
268     dateSQL: set("date time timestamp"),
269     support: set("ODBCdotTable decimallessFloat zerolessFloat binaryNumber hexNumber doubleQuote nCharCast charsetCast commentHash commentSpaceRequired"),
270     hooks: {
271       "@":   hookVar,
272       "`":   hookIdentifier,
273       "\\":  hookClient
274     }
275   });
276
277   CodeMirror.defineMIME("text/x-mariadb", {
278     name: "sql",
279     client: set("charset clear connect edit ego exit go help nopager notee nowarning pager print prompt quit rehash source status system tee"),
280     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_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 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 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 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"),
281     builtin: set("bool boolean bit blob decimal double enum 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"),
282     atoms: set("false true null unknown"),
283     operatorChars: /^[*+\-%<>!=&|^]/,
284     dateSQL: set("date time timestamp"),
285     support: set("ODBCdotTable decimallessFloat zerolessFloat binaryNumber hexNumber doubleQuote nCharCast charsetCast commentHash commentSpaceRequired"),
286     hooks: {
287       "@":   hookVar,
288       "`":   hookIdentifier,
289       "\\":  hookClient
290     }
291   });
292
293   // the query language used by Apache Cassandra is called CQL, but this mime type
294   // is called Cassandra to avoid confusion with Contextual Query Language
295   CodeMirror.defineMIME("text/x-cassandra", {
296     name: "sql",
297     client: { },
298     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"),
299     builtin: set("ascii bigint blob boolean counter decimal double float int text timestamp uuid varchar varint"),
300     atoms: set("false true"),
301     operatorChars: /^[<>=]/,
302     dateSQL: { },
303     support: set("commentSlashSlash decimallessFloat"),
304     hooks: { }
305   });
306
307   // this is based on Peter Raganitsch's 'plsql' mode
308   CodeMirror.defineMIME("text/x-plsql", {
309     name:       "sql",
310     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"),
311     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 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 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"),
312     functions:  set("abs acos add_months ascii asin atan atan2 average bfilename ceil chartorowid chr concat convert cos cosh count decode deref dual dump dup_val_on_index empty error exp false floor found glb greatest hextoraw initcap instr instrb isopen last_day least lenght lenghtb ln lower lpad ltrim lub make_ref max min mod months_between 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 nvl others power rawtohex reftohex round rowcount rowidtochar rpad rtrim sign sin sinh soundex sqlcode sqlerrm sqrt stddev substr substrb sum sysdate tan tanh to_char to_date to_label to_multi_byte to_number to_single_byte translate true trunc uid upper user userenv variance vsize"),
313     builtin:    set("bfile blob character clob dec float int integer mlslabel natural naturaln nchar nclob number numeric nvarchar2 real rowtype signtype smallint string varchar varchar2"),
314     operatorChars: /^[*+\-%<>!=~]/,
315     dateSQL:    set("date time timestamp"),
316     support:    set("doubleQuote nCharCast zerolessFloat binaryNumber hexNumber")
317   });
318 }());
319
320 /*
321   How Properties of Mime Types are used by SQL Mode
322   =================================================
323
324   keywords:
325     A list of keywords you want to be highlighted.
326   functions:
327     A list of function names you want to be highlighted.
328   builtin:
329     A list of builtin types you want to be highlighted (if you want types to be of class "builtin" instead of "keyword").
330   operatorChars:
331     All characters that must be handled as operators.
332   client:
333     Commands parsed and executed by the client (not the server).
334   support:
335     A list of supported syntaxes which are not common, but are supported by more than 1 DBMS.
336     * ODBCdotTable: .tableName
337     * zerolessFloat: .1
338     * doubleQuote
339     * nCharCast: N'string'
340     * charsetCast: _utf8'string'
341     * commentHash: use # char for comments
342     * commentSlashSlash: use // for comments
343     * commentSpaceRequired: require a space after -- for comments
344   atoms:
345     Keywords that must be highlighted as atoms,. Some DBMS's support more atoms than others:
346     UNKNOWN, INFINITY, UNDERFLOW, NaN...
347   dateSQL:
348     Used for date/time SQL standard syntax, because not all DBMS's support same temporal types.
349 */