1 CodeMirror.defineMode("sql", function(config, parserConfig) {
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};
13 function tokenBase(stream, state) {
14 var ch = stream.next();
16 // call hooks from the mime type
18 var result = hooks[ch](stream, state);
19 if (result !== false) return result;
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]+'/))) {
26 // ref: http://dev.mysql.com/doc/refman/5.5/en/hexadecimal-literals.html
28 } else if (support.binaryNumber == true &&
29 (((ch == "b" || ch == "B") && stream.match(/^'[01]+'/))
30 || (ch == "0" && stream.match(/^b[01]+/)))) {
32 // ref: http://dev.mysql.com/doc/refman/5.5/en/bit-field-literals.html
34 } else if (ch.charCodeAt(0) > 47 && ch.charCodeAt(0) < 58) {
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('.');
40 } else if (ch == "?" && (stream.eatSpace() || stream.eol() || stream.eat(";"))) {
43 } else if (ch == "'" || (ch == '"' && support.doubleQuote)) {
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
54 } else if (/^[\(\),\;\[\]]/.test(ch)) {
57 } else if (support.commentSlashSlash && ch == "/" && stream.eat("/")) {
61 } else if ((support.commentHash && ch == "#")
62 || (ch == "-" && stream.eat("-") && (!support.commentSpaceRequired || stream.eat(" ")))) {
64 // ref: https://kb.askmonty.org/en/comment-syntax/
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 == ".") {
74 if (support.zerolessFloat == true && stream.match(/^(?:\d+(?:e[+-]?\d+)?)/i)) {
78 // // ref: http://dev.mysql.com/doc/refman/5.6/en/identifier-qualifiers.html
79 if (support.ODBCdotTable == true && stream.match(/^[a-zA-Z_]+/)) {
82 } else if (operatorChars.test(ch)) {
84 stream.eatWhile(operatorChars);
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
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(/^( )+"[^"]*"/)))
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";
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;
115 escaped = !escaped && ch == "\\";
120 function tokenComment(stream, state) {
122 if (stream.skipTo("*")) {
124 if (stream.eat("/")) {
125 state.tokenize = tokenBase;
136 function pushContext(stream, state, type) {
139 indent: stream.indentation(),
140 col: stream.column(),
145 function popContext(state) {
146 state.indent = state.context.indent;
147 state.context = state.context.prev;
151 startState: function() {
152 return {tokenize: tokenBase, context: null};
155 token: function(stream, state) {
157 if (state.context && state.context.align == null)
158 state.context.align = false;
160 if (stream.eatSpace()) return null;
162 var style = state.tokenize(stream, state);
163 if (style == "comment") return style;
165 if (state.context && state.context.align == null)
166 state.context.align = true;
168 var tok = stream.current();
170 pushContext(stream, state, ")");
172 pushContext(stream, state, "]");
173 else if (state.context && state.context.type == tok)
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;
191 function hookIdentifier(stream) {
192 // MySQL/MariaDB identifiers
193 // ref: http://dev.mysql.com/doc/refman/5.6/en/identifier-qualifiers.html
195 while ((ch = stream.next()) != null) {
196 if (ch == "`" && !stream.eat("`")) return "variable-2";
202 function hookVar(stream) {
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\./);
213 if (stream.eat("'")) {
214 stream.match(/^.*'/);
216 } else if (stream.eat('"')) {
217 stream.match(/^.*"/);
219 } else if (stream.eat("`")) {
220 stream.match(/^.*`/);
222 } else if (stream.match(/^[0-9a-zA-Z$\.\_]+/)) {
228 // short client keyword token
229 function hookClient(stream) {
231 // ref: http://dev.mysql.com/doc/refman/5.5/en/null-values.html
232 if (stream.eat("N")) {
236 // ref: http://dev.mysql.com/doc/refman/5.5/en/mysql-commands.html
237 return stream.match(/^[a-zA-Z.#!?]/) ? "variable-2" : null;
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 ";
243 // turn a space-separated list into an array
245 var obj = {}, words = str.split(" ");
246 for (var i = 0; i < words.length; ++i) obj[words[i]] = true;
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", {
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")
261 CodeMirror.defineMIME("text/x-mysql", {
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"),
277 CodeMirror.defineMIME("text/x-mariadb", {
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"),
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", {
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: /^[<>=]/,
303 support: set("commentSlashSlash decimallessFloat"),
307 // this is based on Peter Raganitsch's 'plsql' mode
308 CodeMirror.defineMIME("text/x-plsql", {
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")
321 How Properties of Mime Types are used by SQL Mode
322 =================================================
325 A list of keywords you want to be highlighted.
327 A list of function names you want to be highlighted.
329 A list of builtin types you want to be highlighted (if you want types to be of class "builtin" instead of "keyword").
331 All characters that must be handled as operators.
333 Commands parsed and executed by the client (not the server).
335 A list of supported syntaxes which are not common, but are supported by more than 1 DBMS.
336 * ODBCdotTable: .tableName
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
345 Keywords that must be highlighted as atoms,. Some DBMS's support more atoms than others:
346 UNKNOWN, INFINITY, UNDERFLOW, NaN...
348 Used for date/time SQL standard syntax, because not all DBMS's support same temporal types.