sql.js 33 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413
  1. // CodeMirror, copyright (c) by Marijn Haverbeke and others
  2. // Distributed under an MIT license: http://codemirror.net/LICENSE
  3. (function(mod) {
  4. if (typeof exports == "object" && typeof module == "object") // CommonJS
  5. mod(require("../../lib/codemirror"));
  6. else if (typeof define == "function" && define.amd) // AMD
  7. define(["../../lib/codemirror"], mod);
  8. else // Plain browser env
  9. mod(CodeMirror);
  10. })(function(CodeMirror) {
  11. "use strict";
  12. CodeMirror.defineMode("sql", function(config, parserConfig) {
  13. "use strict";
  14. var client = parserConfig.client || {},
  15. atoms = parserConfig.atoms || {"false": true, "true": true, "null": true},
  16. builtin = parserConfig.builtin || {},
  17. keywords = parserConfig.keywords || {},
  18. operatorChars = parserConfig.operatorChars || /^[*+\-%<>!=&|~^]/,
  19. support = parserConfig.support || {},
  20. hooks = parserConfig.hooks || {},
  21. dateSQL = parserConfig.dateSQL || {"date" : true, "time" : true, "timestamp" : true};
  22. function tokenBase(stream, state) {
  23. var ch = stream.next();
  24. // call hooks from the mime type
  25. if (hooks[ch]) {
  26. var result = hooks[ch](stream, state);
  27. if (result !== false) return result;
  28. }
  29. if (support.hexNumber == true &&
  30. ((ch == "0" && stream.match(/^[xX][0-9a-fA-F]+/))
  31. || (ch == "x" || ch == "X") && stream.match(/^'[0-9a-fA-F]+'/))) {
  32. // hex
  33. // ref: http://dev.mysql.com/doc/refman/5.5/en/hexadecimal-literals.html
  34. return "number";
  35. } else if (support.binaryNumber == true &&
  36. (((ch == "b" || ch == "B") && stream.match(/^'[01]+'/))
  37. || (ch == "0" && stream.match(/^b[01]+/)))) {
  38. // bitstring
  39. // ref: http://dev.mysql.com/doc/refman/5.5/en/bit-field-literals.html
  40. return "number";
  41. } else if (ch.charCodeAt(0) > 47 && ch.charCodeAt(0) < 58) {
  42. // numbers
  43. // ref: http://dev.mysql.com/doc/refman/5.5/en/number-literals.html
  44. stream.match(/^[0-9]*\.?[0-9]+([eE][-+]?[0-9]+)?/);
  45. support.decimallessFloat == true && stream.eat('.');
  46. return "number";
  47. } else if (ch == "?" && (stream.eatSpace() || stream.eol() || stream.eat(";"))) {
  48. // placeholders
  49. return "variable-3";
  50. } else if (ch == "'" || (ch == '"' && support.doubleQuote)) {
  51. // strings
  52. // ref: http://dev.mysql.com/doc/refman/5.5/en/string-literals.html
  53. state.tokenize = tokenLiteral(ch);
  54. return state.tokenize(stream, state);
  55. } else if ((((support.nCharCast == true && (ch == "n" || ch == "N"))
  56. || (support.charsetCast == true && ch == "_" && stream.match(/[a-z][a-z0-9]*/i)))
  57. && (stream.peek() == "'" || stream.peek() == '"'))) {
  58. // charset casting: _utf8'str', N'str', n'str'
  59. // ref: http://dev.mysql.com/doc/refman/5.5/en/string-literals.html
  60. return "keyword";
  61. } else if (/^[\(\),\;\[\]]/.test(ch)) {
  62. // no highlighting
  63. return null;
  64. } else if (support.commentSlashSlash && ch == "/" && stream.eat("/")) {
  65. // 1-line comment
  66. stream.skipToEnd();
  67. return "comment";
  68. } else if ((support.commentHash && ch == "#")
  69. || (ch == "-" && stream.eat("-") && (!support.commentSpaceRequired || stream.eat(" ")))) {
  70. // 1-line comments
  71. // ref: https://kb.askmonty.org/en/comment-syntax/
  72. stream.skipToEnd();
  73. return "comment";
  74. } else if (ch == "/" && stream.eat("*")) {
  75. // multi-line comments
  76. // ref: https://kb.askmonty.org/en/comment-syntax/
  77. state.tokenize = tokenComment;
  78. return state.tokenize(stream, state);
  79. } else if (ch == ".") {
  80. // .1 for 0.1
  81. if (support.zerolessFloat == true && stream.match(/^(?:\d+(?:e[+-]?\d+)?)/i)) {
  82. return "number";
  83. }
  84. // .table_name (ODBC)
  85. // // ref: http://dev.mysql.com/doc/refman/5.6/en/identifier-qualifiers.html
  86. if (support.ODBCdotTable == true && stream.match(/^[a-zA-Z_]+/)) {
  87. return "variable-2";
  88. }
  89. } else if (operatorChars.test(ch)) {
  90. // operators
  91. stream.eatWhile(operatorChars);
  92. return null;
  93. } else if (ch == '{' &&
  94. (stream.match(/^( )*(d|D|t|T|ts|TS)( )*'[^']*'( )*}/) || stream.match(/^( )*(d|D|t|T|ts|TS)( )*"[^"]*"( )*}/))) {
  95. // dates (weird ODBC syntax)
  96. // ref: http://dev.mysql.com/doc/refman/5.5/en/date-and-time-literals.html
  97. return "number";
  98. } else {
  99. stream.eatWhile(/^[_\w\d]/);
  100. var word = stream.current().toLowerCase();
  101. // dates (standard SQL syntax)
  102. // ref: http://dev.mysql.com/doc/refman/5.5/en/date-and-time-literals.html
  103. if (dateSQL.hasOwnProperty(word) && (stream.match(/^( )+'[^']*'/) || stream.match(/^( )+"[^"]*"/)))
  104. return "number";
  105. if (atoms.hasOwnProperty(word)) return "atom";
  106. if (builtin.hasOwnProperty(word)) return "builtin";
  107. if (keywords.hasOwnProperty(word)) return "keyword";
  108. if (client.hasOwnProperty(word)) return "string-2";
  109. return null;
  110. }
  111. }
  112. // 'string', with char specified in quote escaped by '\'
  113. function tokenLiteral(quote) {
  114. return function(stream, state) {
  115. var escaped = false, ch;
  116. while ((ch = stream.next()) != null) {
  117. if (ch == quote && !escaped) {
  118. state.tokenize = tokenBase;
  119. break;
  120. }
  121. escaped = !escaped && ch == "\\";
  122. }
  123. return "string";
  124. };
  125. }
  126. function tokenComment(stream, state) {
  127. while (true) {
  128. if (stream.skipTo("*")) {
  129. stream.next();
  130. if (stream.eat("/")) {
  131. state.tokenize = tokenBase;
  132. break;
  133. }
  134. } else {
  135. stream.skipToEnd();
  136. break;
  137. }
  138. }
  139. return "comment";
  140. }
  141. function pushContext(stream, state, type) {
  142. state.context = {
  143. prev: state.context,
  144. indent: stream.indentation(),
  145. col: stream.column(),
  146. type: type
  147. };
  148. }
  149. function popContext(state) {
  150. state.indent = state.context.indent;
  151. state.context = state.context.prev;
  152. }
  153. return {
  154. startState: function() {
  155. return {tokenize: tokenBase, context: null};
  156. },
  157. token: function(stream, state) {
  158. if (stream.sol()) {
  159. if (state.context && state.context.align == null)
  160. state.context.align = false;
  161. }
  162. if (stream.eatSpace()) return null;
  163. var style = state.tokenize(stream, state);
  164. if (style == "comment") return style;
  165. if (state.context && state.context.align == null)
  166. state.context.align = true;
  167. var tok = stream.current();
  168. if (tok == "(")
  169. pushContext(stream, state, ")");
  170. else if (tok == "[")
  171. pushContext(stream, state, "]");
  172. else if (state.context && state.context.type == tok)
  173. popContext(state);
  174. return style;
  175. },
  176. indent: function(state, textAfter) {
  177. var cx = state.context;
  178. if (!cx) return CodeMirror.Pass;
  179. var closing = textAfter.charAt(0) == cx.type;
  180. if (cx.align) return cx.col + (closing ? 0 : 1);
  181. else return cx.indent + (closing ? 0 : config.indentUnit);
  182. },
  183. blockCommentStart: "/*",
  184. blockCommentEnd: "*/",
  185. lineComment: support.commentSlashSlash ? "//" : support.commentHash ? "#" : null
  186. };
  187. });
  188. (function() {
  189. "use strict";
  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. stream.backUp(stream.current().length - 1);
  199. return stream.eatWhile(/\w/) ? "variable-2" : null;
  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. if (stream.eat("'")) {
  213. stream.match(/^.*'/);
  214. return "variable-2";
  215. } else if (stream.eat('"')) {
  216. stream.match(/^.*"/);
  217. return "variable-2";
  218. } else if (stream.eat("`")) {
  219. stream.match(/^.*`/);
  220. return "variable-2";
  221. } else if (stream.match(/^[0-9a-zA-Z$\.\_]+/)) {
  222. return "variable-2";
  223. }
  224. return null;
  225. };
  226. // short client keyword token
  227. function hookClient(stream) {
  228. // \N means NULL
  229. // ref: http://dev.mysql.com/doc/refman/5.5/en/null-values.html
  230. if (stream.eat("N")) {
  231. return "atom";
  232. }
  233. // \g, etc
  234. // ref: http://dev.mysql.com/doc/refman/5.5/en/mysql-commands.html
  235. return stream.match(/^[a-zA-Z.#!?]/) ? "variable-2" : null;
  236. }
  237. // these keywords are used by all SQL dialects (however, a mode can still overwrite it)
  238. var sqlKeywords = "alter and as asc between by count create delete desc distinct drop from group having in insert into is join like not on or order select set table union update values where limit ";
  239. // turn a space-separated list into an array
  240. function set(str) {
  241. var obj = {}, words = str.split(" ");
  242. for (var i = 0; i < words.length; ++i) obj[words[i]] = true;
  243. return obj;
  244. }
  245. // A generic SQL Mode. It's not a standard, it just try to support what is generally supported
  246. CodeMirror.defineMIME("text/x-sql", {
  247. name: "sql",
  248. keywords: set(sqlKeywords + "begin"),
  249. 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"),
  250. atoms: set("false true null unknown"),
  251. operatorChars: /^[*+\-%<>!=]/,
  252. dateSQL: set("date time timestamp"),
  253. support: set("ODBCdotTable doubleQuote binaryNumber hexNumber")
  254. });
  255. CodeMirror.defineMIME("text/x-mssql", {
  256. name: "sql",
  257. client: set("charset clear connect edit ego exit go help nopager notee nowarning pager print prompt quit rehash source status system tee"),
  258. keywords: set(sqlKeywords + "begin trigger proc view index for add constraint key primary foreign collate clustered nonclustered declare"),
  259. 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 "),
  260. atoms: set("false true null unknown"),
  261. operatorChars: /^[*+\-%<>!=]/,
  262. dateSQL: set("date datetimeoffset datetime2 smalldatetime datetime time"),
  263. hooks: {
  264. "@": hookVar
  265. }
  266. });
  267. CodeMirror.defineMIME("text/x-mysql", {
  268. name: "sql",
  269. client: set("charset clear connect edit ego exit go help nopager notee nowarning pager print prompt quit rehash source status system tee"),
  270. 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 group_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"),
  271. 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"),
  272. atoms: set("false true null unknown"),
  273. operatorChars: /^[*+\-%<>!=&|^]/,
  274. dateSQL: set("date time timestamp"),
  275. support: set("ODBCdotTable decimallessFloat zerolessFloat binaryNumber hexNumber doubleQuote nCharCast charsetCast commentHash commentSpaceRequired"),
  276. hooks: {
  277. "@": hookVar,
  278. "`": hookIdentifier,
  279. "\\": hookClient
  280. }
  281. });
  282. CodeMirror.defineMIME("text/x-mariadb", {
  283. name: "sql",
  284. client: set("charset clear connect edit ego exit go help nopager notee nowarning pager print prompt quit rehash source status system tee"),
  285. 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"),
  286. 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"),
  287. atoms: set("false true null unknown"),
  288. operatorChars: /^[*+\-%<>!=&|^]/,
  289. dateSQL: set("date time timestamp"),
  290. support: set("ODBCdotTable decimallessFloat zerolessFloat binaryNumber hexNumber doubleQuote nCharCast charsetCast commentHash commentSpaceRequired"),
  291. hooks: {
  292. "@": hookVar,
  293. "`": hookIdentifier,
  294. "\\": hookClient
  295. }
  296. });
  297. // the query language used by Apache Cassandra is called CQL, but this mime type
  298. // is called Cassandra to avoid confusion with Contextual Query Language
  299. CodeMirror.defineMIME("text/x-cassandra", {
  300. name: "sql",
  301. client: { },
  302. keywords: set("add all allow alter and any apply as asc authorize batch begin by clustering columnfamily compact consistency count create custom delete desc distinct drop each_quorum exists filtering from grant if in index insert into key keyspace keyspaces level limit local_one local_quorum modify nan norecursive nosuperuser not of on one order password permission permissions primary quorum rename revoke schema select set storage superuser table three to token truncate ttl two type unlogged update use user users using values where with writetime"),
  303. builtin: set("ascii bigint blob boolean counter decimal double float frozen inet int list map static text timestamp timeuuid tuple uuid varchar varint"),
  304. atoms: set("false true infinity NaN"),
  305. operatorChars: /^[<>=]/,
  306. dateSQL: { },
  307. support: set("commentSlashSlash decimallessFloat"),
  308. hooks: { }
  309. });
  310. // this is based on Peter Raganitsch's 'plsql' mode
  311. CodeMirror.defineMIME("text/x-plsql", {
  312. name: "sql",
  313. 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"),
  314. 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"),
  315. 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 length lengthb 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"),
  316. operatorChars: /^[*+\-%<>!=~]/,
  317. dateSQL: set("date time timestamp"),
  318. support: set("doubleQuote nCharCast zerolessFloat binaryNumber hexNumber")
  319. });
  320. // Created to support specific hive keywords
  321. CodeMirror.defineMIME("text/x-hive", {
  322. name: "sql",
  323. 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"),
  324. builtin: set("bool boolean long timestamp tinyint smallint bigint int float double date datetime unsigned string array struct map uniontype"),
  325. atoms: set("false true null unknown"),
  326. operatorChars: /^[*+\-%<>!=]/,
  327. dateSQL: set("date timestamp"),
  328. support: set("ODBCdotTable doubleQuote binaryNumber hexNumber")
  329. });
  330. CodeMirror.defineMIME("text/x-pgsql", {
  331. name: "sql",
  332. client: set("source"),
  333. // http://www.postgresql.org/docs/9.5/static/sql-keywords-appendix.html
  334. keywords: set(sqlKeywords + "a abort abs absent absolute access according action ada add admin after aggregate all allocate also always analyse analyze any are array array_agg array_max_cardinality asensitive assertion assignment asymmetric at atomic attribute attributes authorization avg backward base64 before begin begin_frame begin_partition bernoulli binary bit_length blob blocked bom both breadth c cache call called cardinality cascade cascaded case cast catalog catalog_name ceil ceiling chain characteristics characters character_length character_set_catalog character_set_name character_set_schema char_length check checkpoint class class_origin clob close cluster coalesce cobol collate collation collation_catalog collation_name collation_schema collect column columns column_name command_function command_function_code comment comments commit committed concurrently condition condition_number configuration conflict connect connection connection_name constraint constraints constraint_catalog constraint_name constraint_schema constructor contains content continue control conversion convert copy corr corresponding cost covar_pop covar_samp cross csv cube cume_dist current current_catalog current_date current_default_transform_group current_path current_role current_row current_schema current_time current_timestamp current_transform_group_for_type current_user cursor cursor_name cycle data database datalink datetime_interval_code datetime_interval_precision day db deallocate dec declare default defaults deferrable deferred defined definer degree delimiter delimiters dense_rank depth deref derived describe descriptor deterministic diagnostics dictionary disable discard disconnect dispatch dlnewcopy dlpreviouscopy dlurlcomplete dlurlcompleteonly dlurlcompletewrite dlurlpath dlurlpathonly dlurlpathwrite dlurlscheme dlurlserver dlvalue do document domain dynamic dynamic_function dynamic_function_code each element else empty enable encoding encrypted end end-exec end_frame end_partition enforced enum equals escape event every except exception exclude excluding exclusive exec execute exists exp explain expression extension external extract false family fetch file filter final first first_value flag float floor following for force foreign fortran forward found frame_row free freeze fs full function functions fusion g general generated get global go goto grant granted greatest grouping groups handler header hex hierarchy hold hour id identity if ignore ilike immediate immediately immutable implementation implicit import including increment indent index indexes indicator inherit inherits initially inline inner inout input insensitive instance instantiable instead integrity intersect intersection invoker isnull isolation k key key_member key_type label lag language large last last_value lateral lead leading leakproof least left length level library like_regex link listen ln load local localtime localtimestamp location locator lock locked logged lower m map mapping match matched materialized max maxvalue max_cardinality member merge message_length message_octet_length message_text method min minute minvalue mod mode modifies module month more move multiset mumps name names namespace national natural nchar nclob nesting new next nfc nfd nfkc nfkd nil no none normalize normalized nothing notify notnull nowait nth_value ntile null nullable nullif nulls number object occurrences_regex octets octet_length of off offset oids old only open operator option options ordering ordinality others out outer output over overlaps overlay overriding owned owner p pad parameter parameter_mode parameter_name parameter_ordinal_position parameter_specific_catalog parameter_specific_name parameter_specific_schema parser partial partition pascal passing passthrough password percent percentile_cont percentile_disc percent_rank period permission placing plans pli policy portion position position_regex power precedes preceding prepare prepared preserve primary prior privileges procedural procedure program public quote range rank read reads reassign recheck recovery recursive ref references referencing refresh regr_avgx regr_avgy regr_count regr_intercept regr_r2 regr_slope regr_sxx regr_sxy regr_syy reindex relative release rename repeatable replace replica requiring reset respect restart restore restrict result return returned_cardinality returned_length returned_octet_length returned_sqlstate returning returns revoke right role rollback rollup routine routine_catalog routine_name routine_schema row rows row_count row_number rule savepoint scale schema schema_name scope scope_catalog scope_name scope_schema scroll search second section security selective self sensitive sequence sequences serializable server server_name session session_user setof sets share show similar simple size skip snapshot some source space specific specifictype specific_name sql sqlcode sqlerror sqlexception sqlstate sqlwarning sqrt stable standalone start state statement static statistics stddev_pop stddev_samp stdin stdout storage strict strip structure style subclass_origin submultiset substring substring_regex succeeds sum symmetric sysid system system_time system_user t tables tablesample tablespace table_name temp template temporary then ties timezone_hour timezone_minute to token top_level_count trailing transaction transactions_committed transactions_rolled_back transaction_active transform transforms translate translate_regex translation treat trigger trigger_catalog trigger_name trigger_schema trim trim_array true truncate trusted type types uescape unbounded uncommitted under unencrypted unique unknown unlink unlisten unlogged unnamed unnest until untyped upper uri usage user user_defined_type_catalog user_defined_type_code user_defined_type_name user_defined_type_schema using vacuum valid validate validator value value_of varbinary variadic var_pop var_samp verbose version versioning view views volatile when whenever whitespace width_bucket window within work wrapper write xmlagg xmlattributes xmlbinary xmlcast xmlcomment xmlconcat xmldeclaration xmldocument xmlelement xmlexists xmlforest xmliterate xmlnamespaces xmlparse xmlpi xmlquery xmlroot xmlschema xmlserialize xmltable xmltext xmlvalidate year yes loop repeat"),
  335. // http://www.postgresql.org/docs/9.5/static/datatype.html
  336. builtin: set("bigint int8 bigserial serial8 bit varying varbit boolean bool box bytea character char varchar cidr circle date double precision float8 inet integer int int4 interval json jsonb line lseg macaddr money numeric decimal path pg_lsn point polygon real float4 smallint int2 smallserial serial2 serial serial4 text time without zone with timetz timestamp timestamptz tsquery tsvector txid_snapshot uuid xml"),
  337. atoms: set("false true null unknown"),
  338. operatorChars: /^[*+\-%<>!=&|^\/#@?~]/,
  339. dateSQL: set("date time timestamp"),
  340. support: set("ODBCdotTable decimallessFloat zerolessFloat binaryNumber hexNumber nCharCast charsetCast")
  341. });
  342. // Google's SQL-like query language, GQL
  343. CodeMirror.defineMIME("text/x-gql", {
  344. name: "sql",
  345. keywords: set("ancestor and asc by contains desc descendant distinct from group has in is limit offset on order select superset where"),
  346. atoms: set("false true"),
  347. builtin: set("blob datetime first key __key__ string integer double boolean null"),
  348. operatorChars: /^[*+\-%<>!=]/
  349. });
  350. }());
  351. });
  352. /*
  353. How Properties of Mime Types are used by SQL Mode
  354. =================================================
  355. keywords:
  356. A list of keywords you want to be highlighted.
  357. builtin:
  358. A list of builtin types you want to be highlighted (if you want types to be of class "builtin" instead of "keyword").
  359. operatorChars:
  360. All characters that must be handled as operators.
  361. client:
  362. Commands parsed and executed by the client (not the server).
  363. support:
  364. A list of supported syntaxes which are not common, but are supported by more than 1 DBMS.
  365. * ODBCdotTable: .tableName
  366. * zerolessFloat: .1
  367. * doubleQuote
  368. * nCharCast: N'string'
  369. * charsetCast: _utf8'string'
  370. * commentHash: use # char for comments
  371. * commentSlashSlash: use // for comments
  372. * commentSpaceRequired: require a space after -- for comments
  373. atoms:
  374. Keywords that must be highlighted as atoms,. Some DBMS's support more atoms than others:
  375. UNKNOWN, INFINITY, UNDERFLOW, NaN...
  376. dateSQL:
  377. Used for date/time SQL standard syntax, because not all DBMS's support same temporal types.
  378. */