2
0

sql.js 18 KB

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