Koha/koha-tmpl/intranet-tmpl/lib/codemirror/sql.js
Jacob O'Mara a3b2f42cc7
Bug 32613: Add autocomplete to SQL reports editor
This adds auto-complete for the sql reports editor codemirror instance.
To prevent a regression in syntax highlighting the overlay mode
'sqlPlaceholders' has been removed and replaced with a highlighting
engine that works correctly with the autocomplete engine.

Test Plan:
1. Navigate to reports and create a new sql report
2. Write an Sql query and observe that there is no autocomplete options
3. Apply patch
4. Write a new Sql query and observe that there are now auto-complete
   options that can be navigated through with the arrow keys and
   accepted with either tab or the enter keys.
5. Ensure that items bounded in << >> or [[ ]] are still syntax
   highlighted post-patch

Signed-off-by: Andrew Fuerste-Henry <andrewfh@dubcolib.org>
Signed-off-by: Nick Clemens <nick@bywatersolutions.com>
Signed-off-by: Tomas Cohen Arazi <tomascohen@theke.io>
2023-03-06 14:45:28 -03:00

368 lines
17 KiB
JavaScript

/* CodeMirror version: 5.40.2 */
// CodeMirror, copyright (c) by Marijn Haverbeke and others
// Distributed under an MIT license: https://codemirror.net/LICENSE
(function(mod) {
if (typeof exports == "object" && typeof module == "object") // CommonJS
mod(require("../../lib/codemirror"));
else if (typeof define == "function" && define.amd) // AMD
define(["../../lib/codemirror"], mod);
else // Plain browser env
mod(CodeMirror);
})(function(CodeMirror) {
"use strict";
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},
backslashStringEscapes = parserConfig.backslashStringEscapes !== false,
brackets = parserConfig.brackets || /^[\{}\(\)\[\]]/,
punctuation = parserConfig.punctuation || /^[;.,:]/
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 (support.hexNumber &&
((ch == "0" && stream.match(/^[xX][0-9a-fA-F]+/))
|| (ch == "x" || ch == "X") && stream.match(/^'[0-9a-fA-F]+'/))) {
// hex
// ref: http://dev.mysql.com/doc/refman/5.5/en/hexadecimal-literals.html
return "number";
} else if (support.binaryNumber &&
(((ch == "b" || ch == "B") && stream.match(/^'[01]+'/))
|| (ch == "0" && stream.match(/^b[01]+/)))) {
// bitstring
// ref: http://dev.mysql.com/doc/refman/5.5/en/bit-field-literals.html
return "number";
} else if (ch.charCodeAt(0) > 47 && ch.charCodeAt(0) < 58) {
// numbers
// ref: http://dev.mysql.com/doc/refman/5.5/en/number-literals.html
stream.match(/^[0-9]*(\.[0-9]+)?([eE][-+]?[0-9]+)?/);
support.decimallessFloat && stream.match(/^\.(?!\.)/);
return "number";
} else if (ch == "?" && (stream.eatSpace() || stream.eol() || stream.eat(";"))) {
// placeholders
return "variable-3";
} else if (ch == "'" || (ch == '"' && support.doubleQuote)) {
// strings
// ref: http://dev.mysql.com/doc/refman/5.5/en/string-literals.html
state.tokenize = tokenLiteral(ch);
return state.tokenize(stream, state);
} else if ((((support.nCharCast && (ch == "n" || ch == "N"))
|| (support.charsetCast && ch == "_" && stream.match(/[a-z][a-z0-9]*/i)))
&& (stream.peek() == "'" || stream.peek() == '"'))) {
// charset casting: _utf8'str', N'str', n'str'
// ref: http://dev.mysql.com/doc/refman/5.5/en/string-literals.html
return "keyword";
} else if (support.commentSlashSlash && ch == "/" && stream.eat("/")) {
// 1-line comment
stream.skipToEnd();
return "comment";
} else if ((support.commentHash && ch == "#")
|| (ch == "-" && stream.eat("-") && (!support.commentSpaceRequired || stream.eat(" ")))) {
// 1-line comments
// ref: https://kb.askmonty.org/en/comment-syntax/
stream.skipToEnd();
return "comment";
} else if (ch == "/" && stream.eat("*")) {
// multi-line comments
// ref: https://kb.askmonty.org/en/comment-syntax/
state.tokenize = tokenComment(1);
return state.tokenize(stream, state);
} else if (ch == ".") {
// .1 for 0.1
if (support.zerolessFloat && stream.match(/^(?:\d+(?:e[+-]?\d+)?)/i))
return "number";
if (stream.match(/^\.+/))
return null
// .table_name (ODBC)
// // ref: http://dev.mysql.com/doc/refman/5.6/en/identifier-qualifiers.html
if (support.ODBCdotTable && stream.match(/^[\w\d_]+/))
return "variable-2";
} else if (operatorChars.test(ch)) {
// operators
stream.eatWhile(operatorChars);
return "operator";
} else if (brackets.test(ch)) {
// brackets
stream.eatWhile(brackets);
return "bracket";
} else if (punctuation.test(ch)) {
// punctuation
stream.eatWhile(punctuation);
return "punctuation";
} else if (ch == '{' &&
(stream.match(/^( )*(d|D|t|T|ts|TS)( )*'[^']*'( )*}/) || stream.match(/^( )*(d|D|t|T|ts|TS)( )*"[^"]*"( )*}/))) {
// dates (weird ODBC syntax)
// ref: http://dev.mysql.com/doc/refman/5.5/en/date-and-time-literals.html
return "number";
} else {
stream.eatWhile(/^[_\w\d]/);
var word = stream.current().toLowerCase();
// dates (standard SQL syntax)
// ref: http://dev.mysql.com/doc/refman/5.5/en/date-and-time-literals.html
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";
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 = backslashStringEscapes && !escaped && ch == "\\";
}
return "string";
};
}
function tokenComment(depth) {
return function(stream, state) {
var m = stream.match(/^.*?(\/\*|\*\/)/)
if (!m) stream.skipToEnd()
else if (m[1] == "/*") state.tokenize = tokenComment(depth + 1)
else if (depth > 1) state.tokenize = tokenComment(depth - 1)
else state.tokenize = tokenBase
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 (state.tokenize == tokenBase && 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;
var closing = textAfter.charAt(0) == cx.type;
if (cx.align) return cx.col + (closing ? 0 : 1);
else return cx.indent + (closing ? 0 : config.indentUnit);
},
blockCommentStart: "/*",
blockCommentEnd: "*/",
lineComment: support.commentSlashSlash ? "//" : support.commentHash ? "#" : "--",
closeBrackets: "()[]{}''\"\"``"
};
});
(function() {
"use strict";
// `identifier`
function hookIdentifier(stream) {
// MySQL/MariaDB identifiers
// ref: http://dev.mysql.com/doc/refman/5.6/en/identifier-qualifiers.html
var ch;
while ((ch = stream.next()) != null) {
if (ch == "`" && !stream.eat("`")) return "variable-2";
}
stream.backUp(stream.current().length - 1);
return stream.eatWhile(/\w/) ? "variable-2" : null;
}
// "identifier"
function hookIdentifierDoublequote(stream) {
// Standard SQL /SQLite identifiers
// ref: http://web.archive.org/web/20160813185132/http://savage.net.au/SQL/sql-99.bnf.html#delimited%20identifier
// ref: http://sqlite.org/lang_keywords.html
var ch;
while ((ch = stream.next()) != null) {
if (ch == "\"" && !stream.eat("\"")) return "variable-2";
}
stream.backUp(stream.current().length - 1);
return stream.eatWhile(/\w/) ? "variable-2" : null;
}
// variable token
function hookVar(stream) {
// variables
// @@prefix.varName @varName
// varName can be quoted with ` or ' or "
// ref: http://dev.mysql.com/doc/refman/5.5/en/user-variables.html
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) {
// \N means NULL
// ref: http://dev.mysql.com/doc/refman/5.5/en/null-values.html
if (stream.eat("N")) {
return "atom";
}
// \g, etc
// ref: http://dev.mysql.com/doc/refman/5.5/en/mysql-commands.html
return stream.match(/^[a-zA-Z.#!?]/) ? "variable-2" : null;
}
// these keywords are used by all SQL dialects (however, a mode can still overwrite it)
var sqlKeywords = "alter and as asc between by count desc distinct from group having in into is join like not on or order select set table union values where limit ";
// turn a space-separated list into an array
function set(str) {
var obj = {}, words = str.split(" ");
for (var i = 0; i < words.length; ++i) obj[words[i]] = true;
return obj;
}
// A generic SQL Mode. It's not a standard, it just try to support what is generally supported
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 doubleQuote binaryNumber hexNumber")
});
CodeMirror.defineMIME("text/x-mssql", {
name: "sql",
client: set("$partition binary_checksum checksum connectionproperty context_info current_request_id error_line error_message error_number error_procedure error_severity error_state formatmessage get_filestream_transaction_context getansinull host_id host_name isnull isnumeric min_active_rowversion newid newsequentialid rowcount_big xact_state object_id"),
keywords: set(sqlKeywords + "begin trigger proc view index for add constraint key primary foreign collate clustered nonclustered declare exec go if use index holdlock nolock nowait paglock readcommitted readcommittedlock readpast readuncommitted repeatableread rowlock serializable snapshot tablock tablockx updlock with"),
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 "),
atoms: set("is not null like and or in left right between inner outer join all any some cross unpivot pivot exists"),
operatorChars: /^[*+\-%<>!=^\&|\/]/,
brackets: /^[\{}\(\)]/,
punctuation: /^[;.,:/]/,
backslashStringEscapes: false,
dateSQL: set("date datetimeoffset datetime2 smalldatetime datetime time"),
hooks: {
"@": hookVar
}
});
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 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 skewed sort sorted start statistics stored stratify struct table tables tablesample tblproperties temp temporary terminated then to touch transaction transactions transform true truncate unarchive unbounded uncache union unlock unset use using values view when where window 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"),
atoms: set("false true null"),
operatorChars: /^[*+\-%<>!=~&|^]/,
dateSQL: set("date time timestamp"),
support: set("ODBCdotTable doubleQuote zerolessFloat")
});
// Esper
CodeMirror.defineMIME("text/x-esper", {
name: "sql",
client: set("source"),
// http://www.espertech.com/esper/release-5.5.0/esper-reference/html/appendix_keywords.html
keywords: set("alter and as asc between by count desc distinct from group having in into is join like not on or order select set table union values where limit after all and as at asc avedev avg between by case cast coalesce count current_timestamp day days define desc distinct else end escape events every exists false first from full group having hour hours in inner instanceof into irstream is istream join last lastweekday left limit like max match_recognize matches median measures metadatasql min minute minutes msec millisecond milliseconds not null offset on or order outer output partition pattern prev prior regexp retain-union retain-intersection right rstream sec second seconds select set some snapshot sql stddev sum then true unidirectional until variable weekday when where window"),
builtin: {},
atoms: set("false true null"),
operatorChars: /^[*+\-%<>!=&|^\/#@?~]/,
dateSQL: set("time"),
support: set("decimallessFloat zerolessFloat binaryNumber hexNumber")
});
}());
});
/*
How Properties of Mime Types are used by SQL Mode
=================================================
keywords:
A list of keywords you want to be highlighted.
builtin:
A list of builtin types you want to be highlighted (if you want types to be of class "builtin" instead of "keyword").
operatorChars:
All characters that must be handled as operators.
client:
Commands parsed and executed by the client (not the server).
support:
A list of supported syntaxes which are not common, but are supported by more than 1 DBMS.
* ODBCdotTable: .tableName
* zerolessFloat: .1
* doubleQuote
* nCharCast: N'string'
* charsetCast: _utf8'string'
* commentHash: use # char for comments
* commentSlashSlash: use // for comments
* commentSpaceRequired: require a space after -- for comments
atoms:
Keywords that must be highlighted as atoms,. Some DBMS's support more atoms than others:
UNKNOWN, INFINITY, UNDERFLOW, NaN...
dateSQL:
Used for date/time SQL standard syntax, because not all DBMS's support same temporal types.
*/