View | Details | Raw Unified | Return to bug 20260
Collapse All | Expand All

(-)a/koha-tmpl/intranet-tmpl/lib/codemirror/sql.js (+501 lines)
Line 0 Link Here
1
/* CodeMirror version: 5.40.2 */
2
// CodeMirror, copyright (c) by Marijn Haverbeke and others
3
// Distributed under an MIT license: https://codemirror.net/LICENSE
4
5
(function(mod) {
6
  if (typeof exports == "object" && typeof module == "object") // CommonJS
7
    mod(require("../../lib/codemirror"));
8
  else if (typeof define == "function" && define.amd) // AMD
9
    define(["../../lib/codemirror"], mod);
10
  else // Plain browser env
11
    mod(CodeMirror);
12
})(function(CodeMirror) {
13
"use strict";
14
15
CodeMirror.defineMode("sql", function(config, parserConfig) {
16
  "use strict";
17
18
  var client         = parserConfig.client || {},
19
      atoms          = parserConfig.atoms || {"false": true, "true": true, "null": true},
20
      builtin        = parserConfig.builtin || {},
21
      keywords       = parserConfig.keywords || {},
22
      operatorChars  = parserConfig.operatorChars || /^[*+\-%<>!=&|~^]/,
23
      support        = parserConfig.support || {},
24
      hooks          = parserConfig.hooks || {},
25
      dateSQL        = parserConfig.dateSQL || {"date" : true, "time" : true, "timestamp" : true},
26
      backslashStringEscapes = parserConfig.backslashStringEscapes !== false,
27
      brackets       = parserConfig.brackets || /^[\{}\(\)\[\]]/,
28
      punctuation    = parserConfig.punctuation || /^[;.,:]/
29
30
  function tokenBase(stream, state) {
31
    var ch = stream.next();
32
33
    // call hooks from the mime type
34
    if (hooks[ch]) {
35
      var result = hooks[ch](stream, state);
36
      if (result !== false) return result;
37
    }
38
39
    if (support.hexNumber &&
40
      ((ch == "0" && stream.match(/^[xX][0-9a-fA-F]+/))
41
      || (ch == "x" || ch == "X") && stream.match(/^'[0-9a-fA-F]+'/))) {
42
      // hex
43
      // ref: http://dev.mysql.com/doc/refman/5.5/en/hexadecimal-literals.html
44
      return "number";
45
    } else if (support.binaryNumber &&
46
      (((ch == "b" || ch == "B") && stream.match(/^'[01]+'/))
47
      || (ch == "0" && stream.match(/^b[01]+/)))) {
48
      // bitstring
49
      // ref: http://dev.mysql.com/doc/refman/5.5/en/bit-field-literals.html
50
      return "number";
51
    } else if (ch.charCodeAt(0) > 47 && ch.charCodeAt(0) < 58) {
52
      // numbers
53
      // ref: http://dev.mysql.com/doc/refman/5.5/en/number-literals.html
54
      stream.match(/^[0-9]*(\.[0-9]+)?([eE][-+]?[0-9]+)?/);
55
      support.decimallessFloat && stream.match(/^\.(?!\.)/);
56
      return "number";
57
    } else if (ch == "?" && (stream.eatSpace() || stream.eol() || stream.eat(";"))) {
58
      // placeholders
59
      return "variable-3";
60
    } else if (ch == "'" || (ch == '"' && support.doubleQuote)) {
61
      // strings
62
      // ref: http://dev.mysql.com/doc/refman/5.5/en/string-literals.html
63
      state.tokenize = tokenLiteral(ch);
64
      return state.tokenize(stream, state);
65
    } else if ((((support.nCharCast && (ch == "n" || ch == "N"))
66
        || (support.charsetCast && ch == "_" && stream.match(/[a-z][a-z0-9]*/i)))
67
        && (stream.peek() == "'" || stream.peek() == '"'))) {
68
      // charset casting: _utf8'str', N'str', n'str'
69
      // ref: http://dev.mysql.com/doc/refman/5.5/en/string-literals.html
70
      return "keyword";
71
    } else if (support.commentSlashSlash && ch == "/" && stream.eat("/")) {
72
      // 1-line comment
73
      stream.skipToEnd();
74
      return "comment";
75
    } else if ((support.commentHash && ch == "#")
76
        || (ch == "-" && stream.eat("-") && (!support.commentSpaceRequired || stream.eat(" ")))) {
77
      // 1-line comments
78
      // ref: https://kb.askmonty.org/en/comment-syntax/
79
      stream.skipToEnd();
80
      return "comment";
81
    } else if (ch == "/" && stream.eat("*")) {
82
      // multi-line comments
83
      // ref: https://kb.askmonty.org/en/comment-syntax/
84
      state.tokenize = tokenComment(1);
85
      return state.tokenize(stream, state);
86
    } else if (ch == ".") {
87
      // .1 for 0.1
88
      if (support.zerolessFloat && stream.match(/^(?:\d+(?:e[+-]?\d+)?)/i))
89
        return "number";
90
      if (stream.match(/^\.+/))
91
        return null
92
      // .table_name (ODBC)
93
      // // ref: http://dev.mysql.com/doc/refman/5.6/en/identifier-qualifiers.html
94
      if (support.ODBCdotTable && stream.match(/^[\w\d_]+/))
95
        return "variable-2";
96
    } else if (operatorChars.test(ch)) {
97
      // operators
98
      stream.eatWhile(operatorChars);
99
      return "operator";
100
    } else if (brackets.test(ch)) {
101
      // brackets
102
      stream.eatWhile(brackets);
103
      return "bracket";
104
    } else if (punctuation.test(ch)) {
105
      // punctuation
106
      stream.eatWhile(punctuation);
107
      return "punctuation";
108
    } else if (ch == '{' &&
109
        (stream.match(/^( )*(d|D|t|T|ts|TS)( )*'[^']*'( )*}/) || stream.match(/^( )*(d|D|t|T|ts|TS)( )*"[^"]*"( )*}/))) {
110
      // dates (weird ODBC syntax)
111
      // ref: http://dev.mysql.com/doc/refman/5.5/en/date-and-time-literals.html
112
      return "number";
113
    } else {
114
      stream.eatWhile(/^[_\w\d]/);
115
      var word = stream.current().toLowerCase();
116
      // dates (standard SQL syntax)
117
      // ref: http://dev.mysql.com/doc/refman/5.5/en/date-and-time-literals.html
118
      if (dateSQL.hasOwnProperty(word) && (stream.match(/^( )+'[^']*'/) || stream.match(/^( )+"[^"]*"/)))
119
        return "number";
120
      if (atoms.hasOwnProperty(word)) return "atom";
121
      if (builtin.hasOwnProperty(word)) return "builtin";
122
      if (keywords.hasOwnProperty(word)) return "keyword";
123
      if (client.hasOwnProperty(word)) return "string-2";
124
      return null;
125
    }
126
  }
127
128
  // 'string', with char specified in quote escaped by '\'
129
  function tokenLiteral(quote) {
130
    return function(stream, state) {
131
      var escaped = false, ch;
132
      while ((ch = stream.next()) != null) {
133
        if (ch == quote && !escaped) {
134
          state.tokenize = tokenBase;
135
          break;
136
        }
137
        escaped = backslashStringEscapes && !escaped && ch == "\\";
138
      }
139
      return "string";
140
    };
141
  }
142
  function tokenComment(depth) {
143
    return function(stream, state) {
144
      var m = stream.match(/^.*?(\/\*|\*\/)/)
145
      if (!m) stream.skipToEnd()
146
      else if (m[1] == "/*") state.tokenize = tokenComment(depth + 1)
147
      else if (depth > 1) state.tokenize = tokenComment(depth - 1)
148
      else state.tokenize = tokenBase
149
      return "comment"
150
    }
151
  }
152
153
  function pushContext(stream, state, type) {
154
    state.context = {
155
      prev: state.context,
156
      indent: stream.indentation(),
157
      col: stream.column(),
158
      type: type
159
    };
160
  }
161
162
  function popContext(state) {
163
    state.indent = state.context.indent;
164
    state.context = state.context.prev;
165
  }
166
167
  return {
168
    startState: function() {
169
      return {tokenize: tokenBase, context: null};
170
    },
171
172
    token: function(stream, state) {
173
      if (stream.sol()) {
174
        if (state.context && state.context.align == null)
175
          state.context.align = false;
176
      }
177
      if (state.tokenize == tokenBase && stream.eatSpace()) return null;
178
179
      var style = state.tokenize(stream, state);
180
      if (style == "comment") return style;
181
182
      if (state.context && state.context.align == null)
183
        state.context.align = true;
184
185
      var tok = stream.current();
186
      if (tok == "(")
187
        pushContext(stream, state, ")");
188
      else if (tok == "[")
189
        pushContext(stream, state, "]");
190
      else if (state.context && state.context.type == tok)
191
        popContext(state);
192
      return style;
193
    },
194
195
    indent: function(state, textAfter) {
196
      var cx = state.context;
197
      if (!cx) return CodeMirror.Pass;
198
      var closing = textAfter.charAt(0) == cx.type;
199
      if (cx.align) return cx.col + (closing ? 0 : 1);
200
      else return cx.indent + (closing ? 0 : config.indentUnit);
201
    },
202
203
    blockCommentStart: "/*",
204
    blockCommentEnd: "*/",
205
    lineComment: support.commentSlashSlash ? "//" : support.commentHash ? "#" : "--",
206
    closeBrackets: "()[]{}''\"\"``"
207
  };
208
});
209
210
(function() {
211
  "use strict";
212
213
  // `identifier`
214
  function hookIdentifier(stream) {
215
    // MySQL/MariaDB identifiers
216
    // ref: http://dev.mysql.com/doc/refman/5.6/en/identifier-qualifiers.html
217
    var ch;
218
    while ((ch = stream.next()) != null) {
219
      if (ch == "`" && !stream.eat("`")) return "variable-2";
220
    }
221
    stream.backUp(stream.current().length - 1);
222
    return stream.eatWhile(/\w/) ? "variable-2" : null;
223
  }
224
225
  // "identifier"
226
  function hookIdentifierDoublequote(stream) {
227
    // Standard SQL /SQLite identifiers
228
    // ref: http://web.archive.org/web/20160813185132/http://savage.net.au/SQL/sql-99.bnf.html#delimited%20identifier
229
    // ref: http://sqlite.org/lang_keywords.html
230
    var ch;
231
    while ((ch = stream.next()) != null) {
232
      if (ch == "\"" && !stream.eat("\"")) return "variable-2";
233
    }
234
    stream.backUp(stream.current().length - 1);
235
    return stream.eatWhile(/\w/) ? "variable-2" : null;
236
  }
237
238
  // variable token
239
  function hookVar(stream) {
240
    // variables
241
    // @@prefix.varName @varName
242
    // varName can be quoted with ` or ' or "
243
    // ref: http://dev.mysql.com/doc/refman/5.5/en/user-variables.html
244
    if (stream.eat("@")) {
245
      stream.match(/^session\./);
246
      stream.match(/^local\./);
247
      stream.match(/^global\./);
248
    }
249
250
    if (stream.eat("'")) {
251
      stream.match(/^.*'/);
252
      return "variable-2";
253
    } else if (stream.eat('"')) {
254
      stream.match(/^.*"/);
255
      return "variable-2";
256
    } else if (stream.eat("`")) {
257
      stream.match(/^.*`/);
258
      return "variable-2";
259
    } else if (stream.match(/^[0-9a-zA-Z$\.\_]+/)) {
260
      return "variable-2";
261
    }
262
    return null;
263
  };
264
265
  // short client keyword token
266
  function hookClient(stream) {
267
    // \N means NULL
268
    // ref: http://dev.mysql.com/doc/refman/5.5/en/null-values.html
269
    if (stream.eat("N")) {
270
        return "atom";
271
    }
272
    // \g, etc
273
    // ref: http://dev.mysql.com/doc/refman/5.5/en/mysql-commands.html
274
    return stream.match(/^[a-zA-Z.#!?]/) ? "variable-2" : null;
275
  }
276
277
  // these keywords are used by all SQL dialects (however, a mode can still overwrite it)
278
  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 ";
279
280
  // turn a space-separated list into an array
281
  function set(str) {
282
    var obj = {}, words = str.split(" ");
283
    for (var i = 0; i < words.length; ++i) obj[words[i]] = true;
284
    return obj;
285
  }
286
287
  // A generic SQL Mode. It's not a standard, it just try to support what is generally supported
288
  CodeMirror.defineMIME("text/x-sql", {
289
    name: "sql",
290
    keywords: set(sqlKeywords + "begin"),
291
    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"),
292
    atoms: set("false true null unknown"),
293
    operatorChars: /^[*+\-%<>!=]/,
294
    dateSQL: set("date time timestamp"),
295
    support: set("ODBCdotTable doubleQuote binaryNumber hexNumber")
296
  });
297
298
  CodeMirror.defineMIME("text/x-mssql", {
299
    name: "sql",
300
    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"),
301
    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"),
302
    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 "),
303
    atoms: set("is not null like and or in left right between inner outer join all any some cross unpivot pivot exists"),
304
    operatorChars: /^[*+\-%<>!=^\&|\/]/,
305
    brackets: /^[\{}\(\)]/,
306
    punctuation: /^[;.,:/]/,
307
    backslashStringEscapes: false,
308
    dateSQL: set("date datetimeoffset datetime2 smalldatetime datetime time"),
309
    hooks: {
310
      "@":   hookVar
311
    }
312
  });
313
314
  CodeMirror.defineMIME("text/x-mysql", {
315
    name: "sql",
316
    client: set("charset clear connect edit ego exit go help nopager notee nowarning pager print prompt quit rehash source status system tee"),
317
    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"),
318
    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"),
319
    atoms: set("false true null unknown"),
320
    operatorChars: /^[*+\-%<>!=&|^]/,
321
    dateSQL: set("date time timestamp"),
322
    support: set("ODBCdotTable decimallessFloat zerolessFloat binaryNumber hexNumber doubleQuote nCharCast charsetCast commentHash commentSpaceRequired"),
323
    hooks: {
324
      "@":   hookVar,
325
      "`":   hookIdentifier,
326
      "\\":  hookClient
327
    }
328
  });
329
330
  CodeMirror.defineMIME("text/x-mariadb", {
331
    name: "sql",
332
    client: set("charset clear connect edit ego exit go help nopager notee nowarning pager print prompt quit rehash source status system tee"),
333
    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"),
334
    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"),
335
    atoms: set("false true null unknown"),
336
    operatorChars: /^[*+\-%<>!=&|^]/,
337
    dateSQL: set("date time timestamp"),
338
    support: set("ODBCdotTable decimallessFloat zerolessFloat binaryNumber hexNumber doubleQuote nCharCast charsetCast commentHash commentSpaceRequired"),
339
    hooks: {
340
      "@":   hookVar,
341
      "`":   hookIdentifier,
342
      "\\":  hookClient
343
    }
344
  });
345
346
  // provided by the phpLiteAdmin project - phpliteadmin.org
347
  CodeMirror.defineMIME("text/x-sqlite", {
348
    name: "sql",
349
    // commands of the official SQLite client, ref: https://www.sqlite.org/cli.html#dotcmd
350
    client: set("auth backup bail binary changes check clone databases dbinfo dump echo eqp exit explain fullschema headers help import imposter indexes iotrace limit lint load log mode nullvalue once open output print prompt quit read restore save scanstats schema separator session shell show stats system tables testcase timeout timer trace vfsinfo vfslist vfsname width"),
351
    // ref: http://sqlite.org/lang_keywords.html
352
    keywords: set(sqlKeywords + "abort action add after all analyze attach autoincrement before begin cascade case cast check collate column commit conflict constraint cross current_date current_time current_timestamp database default deferrable deferred detach each else end escape except exclusive exists explain fail for foreign full glob if ignore immediate index indexed initially inner instead intersect isnull key left limit match natural no notnull null of offset outer plan pragma primary query raise recursive references regexp reindex release rename replace restrict right rollback row savepoint temp temporary then to transaction trigger unique using vacuum view virtual when with without"),
353
    // SQLite is weakly typed, ref: http://sqlite.org/datatype3.html. This is just a list of some common types.
354
    builtin: set("bool boolean bit blob decimal double float long longblob longtext medium mediumblob mediumint mediumtext time timestamp tinyblob tinyint tinytext text clob bigint int int2 int8 integer float double char varchar date datetime year unsigned signed numeric real"),
355
    // ref: http://sqlite.org/syntax/literal-value.html
356
    atoms: set("null current_date current_time current_timestamp"),
357
    // ref: http://sqlite.org/lang_expr.html#binaryops
358
    operatorChars: /^[*+\-%<>!=&|/~]/,
359
    // SQLite is weakly typed, ref: http://sqlite.org/datatype3.html. This is just a list of some common types.
360
    dateSQL: set("date time timestamp datetime"),
361
    support: set("decimallessFloat zerolessFloat"),
362
    identifierQuote: "\"",  //ref: http://sqlite.org/lang_keywords.html
363
    hooks: {
364
      // bind-parameters ref:http://sqlite.org/lang_expr.html#varparam
365
      "@":   hookVar,
366
      ":":   hookVar,
367
      "?":   hookVar,
368
      "$":   hookVar,
369
      // The preferred way to escape Identifiers is using double quotes, ref: http://sqlite.org/lang_keywords.html
370
      "\"":   hookIdentifierDoublequote,
371
      // there is also support for backtics, ref: http://sqlite.org/lang_keywords.html
372
      "`":   hookIdentifier
373
    }
374
  });
375
376
  // the query language used by Apache Cassandra is called CQL, but this mime type
377
  // is called Cassandra to avoid confusion with Contextual Query Language
378
  CodeMirror.defineMIME("text/x-cassandra", {
379
    name: "sql",
380
    client: { },
381
    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"),
382
    builtin: set("ascii bigint blob boolean counter decimal double float frozen inet int list map static text timestamp timeuuid tuple uuid varchar varint"),
383
    atoms: set("false true infinity NaN"),
384
    operatorChars: /^[<>=]/,
385
    dateSQL: { },
386
    support: set("commentSlashSlash decimallessFloat"),
387
    hooks: { }
388
  });
389
390
  // this is based on Peter Raganitsch's 'plsql' mode
391
  CodeMirror.defineMIME("text/x-plsql", {
392
    name:       "sql",
393
    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"),
394
    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"),
395
    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"),
396
    operatorChars: /^[*+\-%<>!=~]/,
397
    dateSQL:    set("date time timestamp"),
398
    support:    set("doubleQuote nCharCast zerolessFloat binaryNumber hexNumber")
399
  });
400
401
  // Created to support specific hive keywords
402
  CodeMirror.defineMIME("text/x-hive", {
403
    name: "sql",
404
    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"),
405
    builtin: set("bool boolean long timestamp tinyint smallint bigint int float double date datetime unsigned string array struct map uniontype"),
406
    atoms: set("false true null unknown"),
407
    operatorChars: /^[*+\-%<>!=]/,
408
    dateSQL: set("date timestamp"),
409
    support: set("ODBCdotTable doubleQuote binaryNumber hexNumber")
410
  });
411
412
  CodeMirror.defineMIME("text/x-pgsql", {
413
    name: "sql",
414
    client: set("source"),
415
    // https://www.postgresql.org/docs/10/static/sql-keywords-appendix.html
416
    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 lc_collate lc_ctype 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 parallel 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 restricted 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 attach path depends detach zone"),
417
    // https://www.postgresql.org/docs/10/static/datatype.html
418
    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 macaddr8 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"),
419
    atoms: set("false true null unknown"),
420
    operatorChars: /^[*+\-%<>!=&|^\/#@?~]/,
421
    dateSQL: set("date time timestamp"),
422
    support: set("ODBCdotTable decimallessFloat zerolessFloat binaryNumber hexNumber nCharCast charsetCast")
423
  });
424
425
  // Google's SQL-like query language, GQL
426
  CodeMirror.defineMIME("text/x-gql", {
427
    name: "sql",
428
    keywords: set("ancestor and asc by contains desc descendant distinct from group has in is limit offset on order select superset where"),
429
    atoms: set("false true"),
430
    builtin: set("blob datetime first key __key__ string integer double boolean null"),
431
    operatorChars: /^[*+\-%<>!=]/
432
  });
433
434
  // Greenplum
435
  CodeMirror.defineMIME("text/x-gpsql", {
436
    name: "sql",
437
    client: set("source"),
438
    //https://github.com/greenplum-db/gpdb/blob/master/src/include/parser/kwlist.h
439
    keywords: set("abort absolute access action active add admin after aggregate all also alter always analyse analyze and any array as asc assertion assignment asymmetric at authorization backward before begin between bigint binary bit boolean both by cache called cascade cascaded case cast chain char character characteristics check checkpoint class close cluster coalesce codegen collate column comment commit committed concurrency concurrently configuration connection constraint constraints contains content continue conversion copy cost cpu_rate_limit create createdb createexttable createrole createuser cross csv cube current current_catalog current_date current_role current_schema current_time current_timestamp current_user cursor cycle data database day deallocate dec decimal declare decode default defaults deferrable deferred definer delete delimiter delimiters deny desc dictionary disable discard distinct distributed do document domain double drop dxl each else enable encoding encrypted end enum errors escape every except exchange exclude excluding exclusive execute exists explain extension external extract false family fetch fields filespace fill filter first float following for force foreign format forward freeze from full function global grant granted greatest group group_id grouping handler hash having header hold host hour identity if ignore ilike immediate immutable implicit in including inclusive increment index indexes inherit inherits initially inline inner inout input insensitive insert instead int integer intersect interval into invoker is isnull isolation join key language large last leading least left level like limit list listen load local localtime localtimestamp location lock log login mapping master match maxvalue median merge minute minvalue missing mode modifies modify month move name names national natural nchar new newline next no nocreatedb nocreateexttable nocreaterole nocreateuser noinherit nologin none noovercommit nosuperuser not nothing notify notnull nowait null nullif nulls numeric object of off offset oids old on only operator option options or order ordered others out outer over overcommit overlaps overlay owned owner parser partial partition partitions passing password percent percentile_cont percentile_disc placing plans position preceding precision prepare prepared preserve primary prior privileges procedural procedure protocol queue quote randomly range read readable reads real reassign recheck recursive ref references reindex reject relative release rename repeatable replace replica reset resource restart restrict returning returns revoke right role rollback rollup rootpartition row rows rule savepoint scatter schema scroll search second security segment select sequence serializable session session_user set setof sets share show similar simple smallint some split sql stable standalone start statement statistics stdin stdout storage strict strip subpartition subpartitions substring superuser symmetric sysid system table tablespace temp template temporary text then threshold ties time timestamp to trailing transaction treat trigger trim true truncate trusted type unbounded uncommitted unencrypted union unique unknown unlisten until update user using vacuum valid validation validator value values varchar variadic varying verbose version view volatile web when where whitespace window with within without work writable write xml xmlattributes xmlconcat xmlelement xmlexists xmlforest xmlparse xmlpi xmlroot xmlserialize year yes zone"),
440
    builtin: set("bigint int8 bigserial serial8 bit varying varbit boolean bool box bytea character char varchar cidr circle date double precision float float8 inet integer int int4 interval json jsonb line lseg macaddr macaddr8 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"),
441
    atoms: set("false true null unknown"),
442
    operatorChars: /^[*+\-%<>!=&|^\/#@?~]/,
443
    dateSQL: set("date time timestamp"),
444
    support: set("ODBCdotTable decimallessFloat zerolessFloat binaryNumber hexNumber nCharCast charsetCast")
445
  });
446
447
  // Spark SQL
448
  CodeMirror.defineMIME("text/x-sparksql", {
449
    name: "sql",
450
    keywords: set("add after all alter analyze and anti archive array as asc at between bucket buckets by cache cascade case cast change clear cluster clustered codegen collection column columns comment commit compact compactions compute concatenate cost create cross cube current current_date current_timestamp database databases datata dbproperties defined delete delimited deny desc describe dfs directories distinct distribute drop else end escaped except exchange exists explain export extended external false fields fileformat first following for format formatted from full function functions global grant group grouping having if ignore import in index indexes inner inpath inputformat insert intersect interval into is items join keys last lateral lazy left like limit lines list load local location lock locks logical macro map minus msck natural no not null nulls of on optimize option options or order out outer outputformat over overwrite partition partitioned partitions percent preceding principals purge range recordreader recordwriter recover reduce refresh regexp rename repair replace reset restrict revoke right rlike role roles rollback rollup row rows schema schemas select semi separated serde serdeproperties set sets show 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"),
451
    builtin: set("tinyint smallint int bigint boolean float double string binary timestamp decimal array map struct uniontype delimited serde sequencefile textfile rcfile inputformat outputformat"),
452
    atoms: set("false true null"),
453
    operatorChars: /^[*+\-%<>!=~&|^]/,
454
    dateSQL: set("date time timestamp"),
455
    support: set("ODBCdotTable doubleQuote zerolessFloat")
456
  });
457
458
  // Esper
459
  CodeMirror.defineMIME("text/x-esper", {
460
    name: "sql",
461
    client: set("source"),
462
    // http://www.espertech.com/esper/release-5.5.0/esper-reference/html/appendix_keywords.html
463
    keywords: set("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 after all and as at asc avedev avg between by case cast coalesce count create current_timestamp day days delete define desc distinct else end escape events every exists false first from full group having hour hours in inner insert 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 update variable weekday when where window"),
464
    builtin: {},
465
    atoms: set("false true null"),
466
    operatorChars: /^[*+\-%<>!=&|^\/#@?~]/,
467
    dateSQL: set("time"),
468
    support: set("decimallessFloat zerolessFloat binaryNumber hexNumber")
469
  });
470
}());
471
472
});
473
474
/*
475
  How Properties of Mime Types are used by SQL Mode
476
  =================================================
477
478
  keywords:
479
    A list of keywords you want to be highlighted.
480
  builtin:
481
    A list of builtin types you want to be highlighted (if you want types to be of class "builtin" instead of "keyword").
482
  operatorChars:
483
    All characters that must be handled as operators.
484
  client:
485
    Commands parsed and executed by the client (not the server).
486
  support:
487
    A list of supported syntaxes which are not common, but are supported by more than 1 DBMS.
488
    * ODBCdotTable: .tableName
489
    * zerolessFloat: .1
490
    * doubleQuote
491
    * nCharCast: N'string'
492
    * charsetCast: _utf8'string'
493
    * commentHash: use # char for comments
494
    * commentSlashSlash: use // for comments
495
    * commentSpaceRequired: require a space after -- for comments
496
  atoms:
497
    Keywords that must be highlighted as atoms,. Some DBMS's support more atoms than others:
498
    UNKNOWN, INFINITY, UNDERFLOW, NaN...
499
  dateSQL:
500
    Used for date/time SQL standard syntax, because not all DBMS's support same temporal types.
501
*/
(-)a/koha-tmpl/intranet-tmpl/lib/codemirror/sql.min.js (+2 lines)
Line 0 Link Here
1
/* CodeMirror version: 5.40.2 */
2
!function(e){"object"==typeof exports&&"object"==typeof module?e(require("../../lib/codemirror")):"function"==typeof define&&define.amd?define(["../../lib/codemirror"],e):e(CodeMirror)}(function(e){"use strict";e.defineMode("sql",function(t,r){var a=r.client||{},i=r.atoms||{false:!0,true:!0,null:!0},n=r.builtin||{},o=r.keywords||{},s=r.operatorChars||/^[*+\-%<>!=&|~^]/,l=r.support||{},c=r.hooks||{},u=r.dateSQL||{date:!0,time:!0,timestamp:!0},d=!1!==r.backslashStringEscapes,m=r.brackets||/^[\{}\(\)\[\]]/,p=r.punctuation||/^[;.,:]/;function b(e,t){var r,g=e.next();if(c[g]){var h=c[g](e,t);if(!1!==h)return h}if(l.hexNumber&&("0"==g&&e.match(/^[xX][0-9a-fA-F]+/)||("x"==g||"X"==g)&&e.match(/^'[0-9a-fA-F]+'/)))return"number";if(l.binaryNumber&&(("b"==g||"B"==g)&&e.match(/^'[01]+'/)||"0"==g&&e.match(/^b[01]+/)))return"number";if(g.charCodeAt(0)>47&&g.charCodeAt(0)<58)return e.match(/^[0-9]*(\.[0-9]+)?([eE][-+]?[0-9]+)?/),l.decimallessFloat&&e.match(/^\.(?!\.)/),"number";if("?"==g&&(e.eatSpace()||e.eol()||e.eat(";")))return"variable-3";if("'"==g||'"'==g&&l.doubleQuote)return t.tokenize=(r=g,function(e,t){for(var a,i=!1;null!=(a=e.next());){if(a==r&&!i){t.tokenize=b;break}i=d&&!i&&"\\"==a}return"string"}),t.tokenize(e,t);if((l.nCharCast&&("n"==g||"N"==g)||l.charsetCast&&"_"==g&&e.match(/[a-z][a-z0-9]*/i))&&("'"==e.peek()||'"'==e.peek()))return"keyword";if(l.commentSlashSlash&&"/"==g&&e.eat("/"))return e.skipToEnd(),"comment";if(l.commentHash&&"#"==g||"-"==g&&e.eat("-")&&(!l.commentSpaceRequired||e.eat(" ")))return e.skipToEnd(),"comment";if("/"==g&&e.eat("*"))return t.tokenize=function e(t){return function(r,a){var i=r.match(/^.*?(\/\*|\*\/)/);return i?"/*"==i[1]?a.tokenize=e(t+1):a.tokenize=t>1?e(t-1):b:r.skipToEnd(),"comment"}}(1),t.tokenize(e,t);if("."!=g){if(s.test(g))return e.eatWhile(s),"operator";if(m.test(g))return e.eatWhile(m),"bracket";if(p.test(g))return e.eatWhile(p),"punctuation";if("{"==g&&(e.match(/^( )*(d|D|t|T|ts|TS)( )*'[^']*'( )*}/)||e.match(/^( )*(d|D|t|T|ts|TS)( )*"[^"]*"( )*}/)))return"number";e.eatWhile(/^[_\w\d]/);var f=e.current().toLowerCase();return u.hasOwnProperty(f)&&(e.match(/^( )+'[^']*'/)||e.match(/^( )+"[^"]*"/))?"number":i.hasOwnProperty(f)?"atom":n.hasOwnProperty(f)?"builtin":o.hasOwnProperty(f)?"keyword":a.hasOwnProperty(f)?"string-2":null}return l.zerolessFloat&&e.match(/^(?:\d+(?:e[+-]?\d+)?)/i)?"number":e.match(/^\.+/)?null:l.ODBCdotTable&&e.match(/^[\w\d_]+/)?"variable-2":void 0}function g(e,t,r){t.context={prev:t.context,indent:e.indentation(),col:e.column(),type:r}}return{startState:function(){return{tokenize:b,context:null}},token:function(e,t){if(e.sol()&&t.context&&null==t.context.align&&(t.context.align=!1),t.tokenize==b&&e.eatSpace())return null;var r=t.tokenize(e,t);if("comment"==r)return r;t.context&&null==t.context.align&&(t.context.align=!0);var a,i=e.current();return"("==i?g(e,t,")"):"["==i?g(e,t,"]"):t.context&&t.context.type==i&&((a=t).indent=a.context.indent,a.context=a.context.prev),r},indent:function(r,a){var i=r.context;if(!i)return e.Pass;var n=a.charAt(0)==i.type;return i.align?i.col+(n?0:1):i.indent+(n?0:t.indentUnit)},blockCommentStart:"/*",blockCommentEnd:"*/",lineComment:l.commentSlashSlash?"//":l.commentHash?"#":"--",closeBrackets:"()[]{}''\"\"``"}}),function(){function t(e){for(var t;null!=(t=e.next());)if("`"==t&&!e.eat("`"))return"variable-2";return e.backUp(e.current().length-1),e.eatWhile(/\w/)?"variable-2":null}function r(e){return e.eat("@")&&(e.match(/^session\./),e.match(/^local\./),e.match(/^global\./)),e.eat("'")?(e.match(/^.*'/),"variable-2"):e.eat('"')?(e.match(/^.*"/),"variable-2"):e.eat("`")?(e.match(/^.*`/),"variable-2"):e.match(/^[0-9a-zA-Z$\.\_]+/)?"variable-2":null}function a(e){return e.eat("N")?"atom":e.match(/^[a-zA-Z.#!?]/)?"variable-2":null}var i="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 ";function n(e){for(var t={},r=e.split(" "),a=0;a<r.length;++a)t[r[a]]=!0;return t}e.defineMIME("text/x-sql",{name:"sql",keywords:n(i+"begin"),builtin:n("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:n("false true null unknown"),operatorChars:/^[*+\-%<>!=]/,dateSQL:n("date time timestamp"),support:n("ODBCdotTable doubleQuote binaryNumber hexNumber")}),e.defineMIME("text/x-mssql",{name:"sql",client:n("$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:n(i+"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:n("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:n("is not null like and or in left right between inner outer join all any some cross unpivot pivot exists"),operatorChars:/^[*+\-%<>!=^\&|\/]/,brackets:/^[\{}\(\)]/,punctuation:/^[;.,:/]/,backslashStringEscapes:!1,dateSQL:n("date datetimeoffset datetime2 smalldatetime datetime time"),hooks:{"@":r}}),e.defineMIME("text/x-mysql",{name:"sql",client:n("charset clear connect edit ego exit go help nopager notee nowarning pager print prompt quit rehash source status system tee"),keywords:n(i+"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"),builtin:n("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"),atoms:n("false true null unknown"),operatorChars:/^[*+\-%<>!=&|^]/,dateSQL:n("date time timestamp"),support:n("ODBCdotTable decimallessFloat zerolessFloat binaryNumber hexNumber doubleQuote nCharCast charsetCast commentHash commentSpaceRequired"),hooks:{"@":r,"`":t,"\\":a}}),e.defineMIME("text/x-mariadb",{name:"sql",client:n("charset clear connect edit ego exit go help nopager notee nowarning pager print prompt quit rehash source status system tee"),keywords:n(i+"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"),builtin:n("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"),atoms:n("false true null unknown"),operatorChars:/^[*+\-%<>!=&|^]/,dateSQL:n("date time timestamp"),support:n("ODBCdotTable decimallessFloat zerolessFloat binaryNumber hexNumber doubleQuote nCharCast charsetCast commentHash commentSpaceRequired"),hooks:{"@":r,"`":t,"\\":a}}),e.defineMIME("text/x-sqlite",{name:"sql",client:n("auth backup bail binary changes check clone databases dbinfo dump echo eqp exit explain fullschema headers help import imposter indexes iotrace limit lint load log mode nullvalue once open output print prompt quit read restore save scanstats schema separator session shell show stats system tables testcase timeout timer trace vfsinfo vfslist vfsname width"),keywords:n(i+"abort action add after all analyze attach autoincrement before begin cascade case cast check collate column commit conflict constraint cross current_date current_time current_timestamp database default deferrable deferred detach each else end escape except exclusive exists explain fail for foreign full glob if ignore immediate index indexed initially inner instead intersect isnull key left limit match natural no notnull null of offset outer plan pragma primary query raise recursive references regexp reindex release rename replace restrict right rollback row savepoint temp temporary then to transaction trigger unique using vacuum view virtual when with without"),builtin:n("bool boolean bit blob decimal double float long longblob longtext medium mediumblob mediumint mediumtext time timestamp tinyblob tinyint tinytext text clob bigint int int2 int8 integer float double char varchar date datetime year unsigned signed numeric real"),atoms:n("null current_date current_time current_timestamp"),operatorChars:/^[*+\-%<>!=&|/~]/,dateSQL:n("date time timestamp datetime"),support:n("decimallessFloat zerolessFloat"),identifierQuote:'"',hooks:{"@":r,":":r,"?":r,$:r,'"':function(e){for(var t;null!=(t=e.next());)if('"'==t&&!e.eat('"'))return"variable-2";return e.backUp(e.current().length-1),e.eatWhile(/\w/)?"variable-2":null},"`":t}}),e.defineMIME("text/x-cassandra",{name:"sql",client:{},keywords:n("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"),builtin:n("ascii bigint blob boolean counter decimal double float frozen inet int list map static text timestamp timeuuid tuple uuid varchar varint"),atoms:n("false true infinity NaN"),operatorChars:/^[<>=]/,dateSQL:{},support:n("commentSlashSlash decimallessFloat"),hooks:{}}),e.defineMIME("text/x-plsql",{name:"sql",client:n("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:n("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"),builtin:n("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"),operatorChars:/^[*+\-%<>!=~]/,dateSQL:n("date time timestamp"),support:n("doubleQuote nCharCast zerolessFloat binaryNumber hexNumber")}),e.defineMIME("text/x-hive",{name:"sql",keywords:n("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"),builtin:n("bool boolean long timestamp tinyint smallint bigint int float double date datetime unsigned string array struct map uniontype"),atoms:n("false true null unknown"),operatorChars:/^[*+\-%<>!=]/,dateSQL:n("date timestamp"),support:n("ODBCdotTable doubleQuote binaryNumber hexNumber")}),e.defineMIME("text/x-pgsql",{name:"sql",client:n("source"),keywords:n(i+"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 lc_collate lc_ctype 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 parallel 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 restricted 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 attach path depends detach zone"),builtin:n("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 macaddr8 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"),atoms:n("false true null unknown"),operatorChars:/^[*+\-%<>!=&|^\/#@?~]/,dateSQL:n("date time timestamp"),support:n("ODBCdotTable decimallessFloat zerolessFloat binaryNumber hexNumber nCharCast charsetCast")}),e.defineMIME("text/x-gql",{name:"sql",keywords:n("ancestor and asc by contains desc descendant distinct from group has in is limit offset on order select superset where"),atoms:n("false true"),builtin:n("blob datetime first key __key__ string integer double boolean null"),operatorChars:/^[*+\-%<>!=]/}),e.defineMIME("text/x-gpsql",{name:"sql",client:n("source"),keywords:n("abort absolute access action active add admin after aggregate all also alter always analyse analyze and any array as asc assertion assignment asymmetric at authorization backward before begin between bigint binary bit boolean both by cache called cascade cascaded case cast chain char character characteristics check checkpoint class close cluster coalesce codegen collate column comment commit committed concurrency concurrently configuration connection constraint constraints contains content continue conversion copy cost cpu_rate_limit create createdb createexttable createrole createuser cross csv cube current current_catalog current_date current_role current_schema current_time current_timestamp current_user cursor cycle data database day deallocate dec decimal declare decode default defaults deferrable deferred definer delete delimiter delimiters deny desc dictionary disable discard distinct distributed do document domain double drop dxl each else enable encoding encrypted end enum errors escape every except exchange exclude excluding exclusive execute exists explain extension external extract false family fetch fields filespace fill filter first float following for force foreign format forward freeze from full function global grant granted greatest group group_id grouping handler hash having header hold host hour identity if ignore ilike immediate immutable implicit in including inclusive increment index indexes inherit inherits initially inline inner inout input insensitive insert instead int integer intersect interval into invoker is isnull isolation join key language large last leading least left level like limit list listen load local localtime localtimestamp location lock log login mapping master match maxvalue median merge minute minvalue missing mode modifies modify month move name names national natural nchar new newline next no nocreatedb nocreateexttable nocreaterole nocreateuser noinherit nologin none noovercommit nosuperuser not nothing notify notnull nowait null nullif nulls numeric object of off offset oids old on only operator option options or order ordered others out outer over overcommit overlaps overlay owned owner parser partial partition partitions passing password percent percentile_cont percentile_disc placing plans position preceding precision prepare prepared preserve primary prior privileges procedural procedure protocol queue quote randomly range read readable reads real reassign recheck recursive ref references reindex reject relative release rename repeatable replace replica reset resource restart restrict returning returns revoke right role rollback rollup rootpartition row rows rule savepoint scatter schema scroll search second security segment select sequence serializable session session_user set setof sets share show similar simple smallint some split sql stable standalone start statement statistics stdin stdout storage strict strip subpartition subpartitions substring superuser symmetric sysid system table tablespace temp template temporary text then threshold ties time timestamp to trailing transaction treat trigger trim true truncate trusted type unbounded uncommitted unencrypted union unique unknown unlisten until update user using vacuum valid validation validator value values varchar variadic varying verbose version view volatile web when where whitespace window with within without work writable write xml xmlattributes xmlconcat xmlelement xmlexists xmlforest xmlparse xmlpi xmlroot xmlserialize year yes zone"),builtin:n("bigint int8 bigserial serial8 bit varying varbit boolean bool box bytea character char varchar cidr circle date double precision float float8 inet integer int int4 interval json jsonb line lseg macaddr macaddr8 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"),atoms:n("false true null unknown"),operatorChars:/^[*+\-%<>!=&|^\/#@?~]/,dateSQL:n("date time timestamp"),support:n("ODBCdotTable decimallessFloat zerolessFloat binaryNumber hexNumber nCharCast charsetCast")}),e.defineMIME("text/x-sparksql",{name:"sql",keywords:n("add after all alter analyze and anti archive array as asc at between bucket buckets by cache cascade case cast change clear cluster clustered codegen collection column columns comment commit compact compactions compute concatenate cost create cross cube current current_date current_timestamp database databases datata dbproperties defined delete delimited deny desc describe dfs directories distinct distribute drop else end escaped except exchange exists explain export extended external false fields fileformat first following for format formatted from full function functions global grant group grouping having if ignore import in index indexes inner inpath inputformat insert intersect interval into is items join keys last lateral lazy left like limit lines list load local location lock locks logical macro map minus msck natural no not null nulls of on optimize option options or order out outer outputformat over overwrite partition partitioned partitions percent preceding principals purge range recordreader recordwriter recover reduce refresh regexp rename repair replace reset restrict revoke right rlike role roles rollback rollup row rows schema schemas select semi separated serde serdeproperties set sets show 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:n("tinyint smallint int bigint boolean float double string binary timestamp decimal array map struct uniontype delimited serde sequencefile textfile rcfile inputformat outputformat"),atoms:n("false true null"),operatorChars:/^[*+\-%<>!=~&|^]/,dateSQL:n("date time timestamp"),support:n("ODBCdotTable doubleQuote zerolessFloat")}),e.defineMIME("text/x-esper",{name:"sql",client:n("source"),keywords:n("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 after all and as at asc avedev avg between by case cast coalesce count create current_timestamp day days delete define desc distinct else end escape events every exists false first from full group having hour hours in inner insert 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 update variable weekday when where window"),builtin:{},atoms:n("false true null"),operatorChars:/^[*+\-%<>!=&|^\/#@?~]/,dateSQL:n("time"),support:n("decimallessFloat zerolessFloat binaryNumber hexNumber")})}()});
(-)a/koha-tmpl/intranet-tmpl/prog/en/modules/reports/guided_reports_start.tt (-9 / +32 lines)
Lines 34-44 Link Here
34
[%- END -%]</title>
34
[%- END -%]</title>
35
35
36
[% INCLUDE 'doc-head-close.inc' %]
36
[% INCLUDE 'doc-head-close.inc' %]
37
[% Asset.css("lib/codemirror/codemirror.css") | $raw %]
38
<style>
39
.CodeMirror {
40
    resize:  vertical;
41
}
42
</style>
37
[% IF ( saved1 ) %]
43
[% IF ( saved1 ) %]
38
    [% Asset.css("css/reports.css") | $raw %]
44
    [% Asset.css("css/reports.css") | $raw %]
39
    [% Asset.css("css/datatables.css") | $raw %]
45
    [% Asset.css("css/datatables.css") | $raw %]
40
[% END %]
46
[% END %]
41
[% Asset.css("../lib/d3c3/c3.min.css") | $raw %]
47
[% Asset.css("lib/d3c3/c3.min.css") | $raw %]
42
</head>
48
</head>
43
49
44
<body id="rep_guided_reports_start" class="rep">
50
<body id="rep_guided_reports_start" class="rep">
Lines 379-384 canned reports and writing custom SQL reports.</p> Link Here
379
    <input type="submit" name="submit" value="Next &gt;&gt;" />
385
    <input type="submit" name="submit" value="Next &gt;&gt;" />
380
</fieldset>
386
</fieldset>
381
</form>
387
</form>
388
382
[% END %]
389
[% END %]
383
390
384
[% IF ( build3 ) %]
391
[% IF ( build3 ) %]
Lines 751-761 canned reports and writing custom SQL reports.</p> Link Here
751
[% END %]
758
[% END %]
752
759
753
[% IF ( create ) %]
760
[% IF ( create ) %]
754
<script type="text/javascript">
755
$(document).ready(function() {
756
    load_group_subgroups();
757
});
758
</script>
759
<form action="/cgi-bin/koha/reports/guided_reports.pl" method="post" class="validated">
761
<form action="/cgi-bin/koha/reports/guided_reports.pl" method="post" class="validated">
760
<fieldset class="rows">
762
<fieldset class="rows">
761
<legend>Create report from SQL</legend>
763
<legend>Create report from SQL</legend>
Lines 936-948 $(document).ready(function() { Link Here
936
938
937
[% MACRO jsinclude BLOCK %]
939
[% MACRO jsinclude BLOCK %]
938
    [% Asset.js("js/charts.js") | $raw %]
940
    [% Asset.js("js/charts.js") | $raw %]
939
    [% Asset.js("../lib/d3c3/d3.min.js") | $raw %]
941
    [% Asset.js("lib/d3c3/d3.min.js") | $raw %]
940
    [% Asset.js("../lib/d3c3/c3.min.js") | $raw %]
942
    [% Asset.js("lib/d3c3/c3.min.js") | $raw %]
941
    [% INCLUDE 'calendar.inc' %]
943
    [% INCLUDE 'calendar.inc' %]
942
    [% IF ( saved1 ) %]
944
    [% IF ( saved1 ) %]
943
        [% INCLUDE 'datatables.inc' %]
945
        [% INCLUDE 'datatables.inc' %]
944
        [% INCLUDE 'columns_settings.inc' %]
946
        [% INCLUDE 'columns_settings.inc' %]
945
    [% END %]
947
    [% END %]
948
    [% Asset.js( "lib/codemirror/codemirror-compressed.js" ) | $raw %]
949
    [% Asset.js( "lib/codemirror/sql.min.js" ) | $raw %]
946
    <script>
950
    <script>
947
951
948
        function hide_bar_element() {
952
        function hide_bar_element() {
Lines 985-990 $(document).ready(function() { Link Here
985
            [% END %]
989
            [% END %]
986
        [% END %]
990
        [% END %]
987
991
992
        [% IF ( create || editsql || save ) %]
993
            var editor = CodeMirror.fromTextArea(sql, {
994
                lineNumbers: true,
995
                mode: "text/x-sql",
996
                lineWrapping: true
997
            });
998
        [% END %]
999
1000
        [% IF ( showsql ) %]
1001
            var editor = CodeMirror.fromTextArea(sql, {
1002
                lineNumbers: false,
1003
                mode: "text/x-sql",
1004
                lineWrapping: true,
1005
                readOnly: true
1006
            });
1007
        [% END %]
1008
988
        function load_group_subgroups () {
1009
        function load_group_subgroups () {
989
            var group = $("#group_select").val();
1010
            var group = $("#group_select").val();
990
            var sg = $("#subgroup");
1011
            var sg = $("#subgroup");
Lines 1107-1112 $(document).ready(function() { Link Here
1107
                    $("html, body").animate({ scrollTop: $(document).height() }, "slow");
1128
                    $("html, body").animate({ scrollTop: $(document).height() }, "slow");
1108
                });
1129
                });
1109
            [% END %]
1130
            [% END %]
1131
            [% IF ( create ) %]
1132
                load_group_subgroups();
1133
            [% END %]
1110
1134
1111
            $('[data-toggle="tooltip"]').tooltip();
1135
            $('[data-toggle="tooltip"]').tooltip();
1112
            var columns_settings = [% ColumnsSettings.GetColumns( 'reports', 'saved-sql', 'table_reports', 'json' ) | $raw %];
1136
            var columns_settings = [% ColumnsSettings.GetColumns( 'reports', 'saved-sql', 'table_reports', 'json' ) | $raw %];
1113
- 

Return to bug 20260