Fixed time zone calculation issue
[GitHub/WoltLab/WCF.git] / wcfsetup / install / files / js / 3rdParty / codemirror / 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 ((ch == "0" && stream.match(/^[xX][0-9a-fA-F]+/))
23 || (ch == "x" || ch == "X") && stream.match(/^'[0-9a-fA-F]+'/)) {
24 // hex
25 return "number";
26 } else if (((ch == "b" || ch == "B") && stream.match(/^'[01]+'/))
27 || (ch == "0" && stream.match(/^b[01]+/))) {
28 // bitstring
29 return "number";
30 } else if (ch.charCodeAt(0) > 47 && ch.charCodeAt(0) < 58) {
31 // numbers
32 stream.match(/^[0-9]*\.?[0-9]+([eE][-+]?[0-9]+)?/);
33 return "number";
34 } else if (ch == "?" && (stream.eatSpace() || stream.eol() || stream.eat(";"))) {
35 // placeholders
36 return "variable-3";
37 } else if (ch == '"' || ch == "'") {
38 // strings
39 state.tokenize = tokenLiteral(ch);
40 return state.tokenize(stream, state);
41 } else if (/^[\(\),\;\[\]]/.test(ch)) {
42 // no highlightning
43 return null;
44 } else if (ch == "#" || (ch == "-" && stream.eat("-") && stream.eat(" "))) {
45 // 1-line comments
46 stream.skipToEnd();
47 return "comment";
48 } else if (ch == "/" && stream.eat("*")) {
49 // multi-line comments
50 state.tokenize = tokenComment;
51 return state.tokenize(stream, state);
52 } else if (ch == ".") {
53 // .1 for 0.1
54 if (support.zerolessFloat == true && stream.match(/^(?:\d+(?:e\d*)?|\d*e\d+)/i)) {
55 return "number";
56 }
57 // .table_name (ODBC)
58 if (stream.match(/^[a-zA-Z_]+/) && support.ODBCdotTable == true) {
59 return "variable-2";
60 }
61 } else if (operatorChars.test(ch)) {
62 // operators
63 stream.eatWhile(operatorChars);
64 return null;
65 } else if (ch == '{' &&
66 (stream.match(/^( )*(d|D|t|T|ts|TS)( )*'[^']*'( )*}/) || stream.match(/^( )*(d|D|t|T|ts|TS)( )*"[^"]*"( )*}/))) {
67 // dates (weird ODBC syntax)
68 return "number";
69 } else {
70 stream.eatWhile(/^[_\w\d]/);
71 var word = stream.current().toLowerCase();
72 // dates (standard SQL syntax)
73 if (dateSQL.hasOwnProperty(word) && (stream.match(/^( )+'[^']*'/) || stream.match(/^( )+"[^"]*"/)))
74 return "number";
75 if (atoms.hasOwnProperty(word)) return "atom";
76 if (builtin.hasOwnProperty(word)) return "builtin";
77 if (keywords.hasOwnProperty(word)) return "keyword";
78 if (client.hasOwnProperty(word)) return "string-2";
79 return null;
80 }
81 }
82
83 // 'string', with char specified in quote escaped by '\'
84 function tokenLiteral(quote) {
85 return function(stream, state) {
86 var escaped = false, ch;
87 while ((ch = stream.next()) != null) {
88 if (ch == quote && !escaped) {
89 state.tokenize = tokenBase;
90 break;
91 }
92 escaped = !escaped && ch == "\\";
93 }
94 return "string";
95 };
96 }
97 function tokenComment(stream, state) {
98 while (true) {
99 if (stream.skipTo("*")) {
100 stream.next();
101 if (stream.eat("/")) {
102 state.tokenize = tokenBase;
103 break;
104 }
105 } else {
106 stream.skipToEnd();
107 break;
108 }
109 }
110 return "comment";
111 }
112
113 function pushContext(stream, state, type) {
114 state.context = {
115 prev: state.context,
116 indent: stream.indentation(),
117 col: stream.column(),
118 type: type
119 };
120 }
121
122 function popContext(state) {
123 state.indent = state.context.indent;
124 state.context = state.context.prev;
125 }
126
127 return {
128 startState: function() {
129 return {tokenize: tokenBase, context: null};
130 },
131
132 token: function(stream, state) {
133 if (stream.sol()) {
134 if (state.context && state.context.align == null)
135 state.context.align = false;
136 }
137 if (stream.eatSpace()) return null;
138
139 var style = state.tokenize(stream, state);
140 if (style == "comment") return style;
141
142 if (state.context && state.context.align == null)
143 state.context.align = true;
144
145 var tok = stream.current();
146 if (tok == "(")
147 pushContext(stream, state, ")");
148 else if (tok == "[")
149 pushContext(stream, state, "]");
150 else if (state.context && state.context.type == tok)
151 popContext(state);
152 return style;
153 },
154
155 indent: function(state, textAfter) {
156 var cx = state.context;
157 if (!cx) return CodeMirror.Pass;
158 if (cx.align) return cx.col + (textAfter.charAt(0) == cx.type ? 0 : 1);
159 else return cx.indent + config.indentUnit;
160 }
161 };
162 });
163
164 (function() {
165 "use strict";
166
167 // `identifier`
168 function hookIdentifier(stream) {
169 var ch;
170 while ((ch = stream.next()) != null) {
171 if (ch == "`" && !stream.eat("`")) return "variable-2";
172 }
173 return null;
174 }
175
176 // variable token
177 function hookVar(stream) {
178 // variables
179 // @@ and prefix
180 if (stream.eat("@")) {
181 stream.match(/^session\./);
182 stream.match(/^local\./);
183 stream.match(/^global\./);
184 }
185
186 if (stream.eat("'")) {
187 stream.match(/^.*'/);
188 return "variable-2";
189 } else if (stream.eat('"')) {
190 stream.match(/^.*"/);
191 return "variable-2";
192 } else if (stream.eat("`")) {
193 stream.match(/^.*`/);
194 return "variable-2";
195 } else if (stream.match(/^[0-9a-zA-Z$\.\_]+/)) {
196 return "variable-2";
197 }
198 return null;
199 };
200
201 // short client keyword token
202 function hookClient(stream) {
203 // \g, etc
204 return stream.match(/^[a-zA-Z]\b/) ? "variable-2" : null;
205 }
206
207 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 ";
208
209 function set(str) {
210 var obj = {}, words = str.split(" ");
211 for (var i = 0; i < words.length; ++i) obj[words[i]] = true;
212 return obj;
213 }
214
215 CodeMirror.defineMIME("text/x-sql", {
216 name: "sql",
217 keywords: set(sqlKeywords + "begin"),
218 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"),
219 atoms: set("false true null unknown"),
220 operatorChars: /^[*+\-%<>!=]/,
221 dateSQL: set("date time timestamp"),
222 support: set("ODBCdotTable")
223 });
224
225 CodeMirror.defineMIME("text/x-mysql", {
226 name: "sql",
227 client: set("charset clear connect edit ego exit go help nopager notee nowarning pager print prompt quit rehash source status system tee"),
228 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"),
229 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"),
230 atoms: set("false true null unknown"),
231 operatorChars: /^[*+\-%<>!=&|^]/,
232 dateSQL: set("date time timestamp"),
233 support: set("ODBCdotTable zerolessFloat"),
234 hooks: {
235 "@": hookVar,
236 "`": hookIdentifier,
237 "\\": hookClient
238 }
239 });
240
241 CodeMirror.defineMIME("text/x-mariadb", {
242 name: "sql",
243 client: set("charset clear connect edit ego exit go help nopager notee nowarning pager print prompt quit rehash source status system tee"),
244 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"),
245 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"),
246 atoms: set("false true null unknown"),
247 operatorChars: /^[*+\-%<>!=&|^]/,
248 dateSQL: set("date time timestamp"),
249 support: set("ODBCdotTable zerolessFloat"),
250 hooks: {
251 "@": hookVar,
252 "`": hookIdentifier,
253 "\\": hookClient
254 }
255 });
256
257 // this is based on Peter Raganitsch's 'plsql' mode
258 CodeMirror.defineMIME("text/x-plsql", {
259 name: "sql",
260 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"),
261 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"),
262 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"),
263 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"),
264 operatorChars: /^[*+\-%<>!=~]/,
265 dateSQL: set("date time timestamp")
266 });
267 }());