| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311 |
- // Licensed to Cloudera, Inc. under one
- // or more contributor license agreements. See the NOTICE file
- // distributed with this work for additional information
- // regarding copyright ownership. Cloudera, Inc. licenses this file
- // to you under the Apache License, Version 2.0 (the
- // "License"); you may not use this file except in compliance
- // with the License. You may obtain a copy of the License at
- //
- // http://www.apache.org/licenses/LICENSE-2.0
- //
- // Unless required by applicable law or agreed to in writing, software
- // distributed under the License is distributed on an "AS IS" BASIS,
- // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- // See the License for the specific language governing permissions and
- // limitations under the License.
- CodeMirror.defineMode("sql", function (config, parserConfig) {
- "use strict";
- var client = parserConfig.client || {},
- atoms = parserConfig.atoms || {"false": true, "true": true, "null": true},
- builtin = parserConfig.builtin || {},
- keywords = parserConfig.keywords || {},
- operatorChars = parserConfig.operatorChars || /^[*+\-%<>!=&|~^]/,
- support = parserConfig.support || {},
- hooks = parserConfig.hooks || {},
- dateSQL = parserConfig.dateSQL || {"date": true, "time": true, "timestamp": true},
- functions = parserConfig.functions || {},
- analytics = parserConfig.analytics || {};
- function tokenBase(stream, state) {
- var ch = stream.next();
- // call hooks from the mime type
- if (hooks[ch]) {
- var result = hooks[ch](stream, state);
- if (result !== false) return result;
- }
- if ((ch == "0" && stream.match(/^[xX][0-9a-fA-F]+/))
- || (ch == "x" || ch == "X") && stream.match(/^'[0-9a-fA-F]+'/)) {
- // hex
- return "number";
- } else if (((ch == "b" || ch == "B") && stream.match(/^'[01]+'/))
- || (ch == "0" && stream.match(/^b[01]+/))) {
- // bitstring
- return "number";
- } else if (ch.charCodeAt(0) > 47 && ch.charCodeAt(0) < 58) {
- // numbers
- stream.match(/^[0-9]*\.?[0-9]+([eE][-+]?[0-9]+)?/);
- return "number";
- } else if (ch == "?" && (stream.eatSpace() || stream.eol() || stream.eat(";"))) {
- // placeholders
- return "variable-3";
- } else if (ch == '"' || ch == "'") {
- // strings
- state.tokenize = tokenLiteral(ch);
- return state.tokenize(stream, state);
- } else if (/^[\(\),\;\[\]]/.test(ch)) {
- // no highlightning
- return null;
- } else if (ch == "#" || (ch == "-" && stream.eat("-") && stream.eat(" "))) {
- // 1-line comments
- stream.skipToEnd();
- return "comment";
- } else if (ch == "/" && stream.eat("*")) {
- // multi-line comments
- state.tokenize = tokenComment;
- return state.tokenize(stream, state);
- } else if (ch == ".") {
- // .1 for 0.1
- if (stream.match(/^[0-9eE]+/) && support.zerolessFloat == true) {
- return "number";
- }
- // .table_name (ODBC)
- if (stream.match(/^[a-zA-Z_]+/) && support.ODBCdotTable == true) {
- return "variable-2";
- }
- } else if (operatorChars.test(ch)) {
- // operators
- stream.eatWhile(operatorChars);
- return null;
- } else if (ch == '{' &&
- (stream.match(/^( )*(d|D|t|T|ts|TS)( )*'[^']*'( )*}/) || stream.match(/^( )*(d|D|t|T|ts|TS)( )*"[^"]*"( )*}/))) {
- // dates (weird ODBC syntax)
- return "number";
- } else {
- stream.eatWhile(/^[_\w\d]/);
- var word = stream.current().toLowerCase();
- // dates (standard SQL syntax)
- if (dateSQL.hasOwnProperty(word) && (stream.match(/^( )+'[^']*'/) || stream.match(/^( )+"[^"]*"/)))
- return "number";
- if (atoms.hasOwnProperty(word)) return "atom";
- if (builtin.hasOwnProperty(word)) return "builtin";
- if (keywords.hasOwnProperty(word)) return "keyword";
- if (client.hasOwnProperty(word)) return "string-2";
- if (functions.hasOwnProperty(word)) return "functions";
- if (analytics.hasOwnProperty(word)) return "analytics";
- return null;
- }
- }
- // 'string', with char specified in quote escaped by '\'
- function tokenLiteral(quote) {
- return function (stream, state) {
- var escaped = false, ch;
- while ((ch = stream.next()) != null) {
- if (ch == quote && !escaped) {
- state.tokenize = tokenBase;
- break;
- }
- escaped = !escaped && ch == "\\";
- }
- return "string";
- };
- }
- function tokenComment(stream, state) {
- while (true) {
- if (stream.skipTo("*")) {
- stream.next();
- if (stream.eat("/")) {
- state.tokenize = tokenBase;
- break;
- }
- } else {
- stream.skipToEnd();
- break;
- }
- }
- return "comment";
- }
- function pushContext(stream, state, type) {
- state.context = {
- prev: state.context,
- indent: stream.indentation(),
- col: stream.column(),
- type: type
- };
- }
- function popContext(state) {
- state.indent = state.context.indent;
- state.context = state.context.prev;
- }
- return {
- startState: function () {
- return {tokenize: tokenBase, context: null};
- },
- token: function (stream, state) {
- if (stream.sol()) {
- if (state.context && state.context.align == null)
- state.context.align = false;
- }
- if (stream.eatSpace()) return null;
- var style = state.tokenize(stream, state);
- if (style == "comment") return style;
- if (state.context && state.context.align == null)
- state.context.align = true;
- var tok = stream.current();
- if (tok == "(")
- pushContext(stream, state, ")");
- else if (tok == "[")
- pushContext(stream, state, "]");
- else if (state.context && state.context.type == tok)
- popContext(state);
- return style;
- },
- indent: function (state, textAfter) {
- var cx = state.context;
- if (!cx) return CodeMirror.Pass;
- if (cx.align) return cx.col + (textAfter.charAt(0) == cx.type ? 0 : 1);
- else return cx.indent + config.indentUnit;
- }
- };
- });
- (function () {
- "use strict";
- // `identifier`
- function hookIdentifier(stream) {
- var escaped = false, ch;
- while ((ch = stream.next()) != null) {
- if (ch == "`" && !escaped) return "variable-2";
- escaped = !escaped && ch == "`";
- }
- return null;
- }
- // variable token
- function hookVar(stream) {
- // variables
- // @@ and prefix
- if (stream.eat("@")) {
- stream.match(/^session\./);
- stream.match(/^local\./);
- stream.match(/^global\./);
- }
- if (stream.eat("'")) {
- stream.match(/^.*'/);
- return "variable-2";
- } else if (stream.eat('"')) {
- stream.match(/^.*"/);
- return "variable-2";
- } else if (stream.eat("`")) {
- stream.match(/^.*`/);
- return "variable-2";
- } else if (stream.match(/^[0-9a-zA-Z$\.\_]+/)) {
- return "variable-2";
- }
- return null;
- };
- // short client keyword token
- function hookClient(stream) {
- // \g, etc
- return stream.match(/^[a-zA-Z]\b/) ? "variable-2" : null;
- }
- 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 ";
- function set(str) {
- var obj = {}, words = str.split(" ");
- for (var i = 0; i < words.length; ++i) obj[words[i]] = true;
- return obj;
- }
- CodeMirror.defineMIME("text/x-sql", {
- name: "sql",
- keywords: set(sqlKeywords + "begin"),
- 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"),
- atoms: set("false true null unknown"),
- operatorChars: /^[*+\-%<>!=]/,
- dateSQL: set("date time timestamp"),
- support: set("ODBCdotTable")
- });
- CodeMirror.defineMIME("text/x-mysql", {
- name: "sql",
- client: set("charset clear connect edit ego exit go help nopager notee nowarning pager print prompt quit rehash source status system tee"),
- 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 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 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 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"),
- 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"),
- atoms: set("false true null unknown"),
- operatorChars: /^[*+\-%<>!=&|^]/,
- dateSQL: set("date time timestamp"),
- support: set("ODBCdotTable zerolessFloat"),
- hooks: {
- "@": hookVar,
- "`": hookIdentifier,
- "\\": hookClient
- }
- });
- CodeMirror.defineMIME("text/x-mariadb", {
- name: "sql",
- client: set("charset clear connect edit ego exit go help nopager notee nowarning pager print prompt quit rehash source status system tee"),
- 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 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 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 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 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"),
- 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"),
- atoms: set("false true null unknown"),
- operatorChars: /^[*+\-%<>!=&|^]/,
- dateSQL: set("date time timestamp"),
- support: set("ODBCdotTable zerolessFloat"),
- hooks: {
- "@": hookVar,
- "`": hookIdentifier,
- "\\": hookClient
- }
- });
- // this is based on Peter Raganitsch's 'plsql' mode
- CodeMirror.defineMIME("text/x-plsql", {
- name: "sql",
- 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"),
- 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"),
- 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"),
- 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"),
- operatorChars: /^[*+\-%<>!=~]/,
- dateSQL: set("date time timestamp")
- });
- CodeMirror.defineMIME("text/x-hiveql", {
- name: "sql",
- keywords: set("add after all alter analyze and archive as asc between bucket buckets by cascade change cli cluster clustered coalesce collection column columns comment compute create cross data database databases dbproperties deferred delimited dependency desc describe directory disable distinct distribute dot drop enable escaped exists explain export extended external fields fileformat first format formatted from full function functions grant group having idxproperties if ignore import in index indexes inpath insert into is items join keys lateral left like limit lines load local location locks map mapjoin msck not of offline on option order out outer overwrite partition partitioned partitions percent privileges protection rebuild recordreader recover reduce regexp rename repair replace restrict revoke right rlike role row schema schemas select semi separated serde serdeproperties set show skewed sort sorted statistics stored sum table tables tablesample tblproperties temporary terminated to touch transform truncate unarchive union us user using view where with"),
- builtin: set("tinyint smallint int bigint boolean float double string binary timestamp decimal array map struct uniontype delimited serde sequencefile textfile rcfile inputformat outputformat"),
- functions: set("round floor ceil ceiling rand exp ln log10 log2 log pow power sqrt bin hex unhex conv abs pmod sin asin cos acos tan atan degrees radians positive negative sign e pi size map_keys map_values array_contains sort_array binary cast from_unixtime unix_timestamp to_date year month day hour minute second weekofyear datediff date_add date_sub from_utc_timestamp to_utc_timestamp ascii concat context_ngrams concat_ws find_in_set format_number get_json_object in_file instr length locate lower lcase lpad ltrim ngrams parse_url printf regexp_extract regexp_replace repeat reverse rpad rtrim sentences space split str_to_map substr substring translate trim upper ucase java_method reflect xpath xpath_short xpath_int xpath_long xpath_float xpath_double xpath_number xpath_string count sum avg min max variance var_samp stdev_pop stdev_samp covar_pop covar_samp corr percentile percentile_approx histogram_numeric collect_set inline explode json_tuple parse_url_tuple get_json_object"),
- atoms: set("false true null"),
- operatorChars: /^[*+\-%<>!=~&|^]/,
- dateSQL: set("date time timestamp"),
- support: set("ODBCdotTable zerolessFloat")
- });
- CodeMirror.defineMIME("text/x-impalaql", {
- name: "sql",
- keywords: set("add aggregate all and api_version as avro binary by cached case change char class close_fn column columns comment compute create cross data database databases decimal delimited describe distinct div drop else end escaped exists explain external false fields fileformat finalize_fn first format formatted from full function functions group having if init_fn inner inpath insert integer intermediate interval into invalidate join last left like limit lines load location merge_fn metadata not null nulls offset or order outer overwrite parquet partition partitioned partitions prepare_fn produced real refresh regexp rename replace returns right rlike row schema schemas select semi serdeproperties serialize_fn show stats stored straight_join symbol table tables tblproperties terminated then to true uncached union update_fn use using view when where with"),
- builtin: set("tinyint smallint int bigint boolean float double string timestamp parquetfile sequencefile textfile rcfile"),
- functions: set("abs acos ascii asin atan avg bin cast ceil ceiling coalesce concat concat_ws count conv cos date_add date_sub datediff day dayname dayofmonth dayofweek degrees e exp find_in_set floor fnv_hash from_unixtime from_utc_timestamp greatest group_concat hex hour if initcap instr isnull lcase least length ln locate log log10 log2 lower lpad ltrim max min minute month ndv negative now nvl parse_url pi pmod positive pow power quotient radians rand regexp_extract repeat reverse round rpad rtrim second sign sin space sqrt substr substring sum tan to_date to_utc_timestamp translate trim ucase unhex unix_timestamp upper user weekofyear year"),
- analytics: set("dense_rank first_value lag last_value lead over rank row_number window"),
- atoms: set("false true null"),
- operatorChars: /^[*+\-%<>!=~&|^]/,
- dateSQL: set("date datetime timestamp")
- });
- }());
|