sql.py 33 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832
  1. """
  2. pygments.lexers.sql
  3. ~~~~~~~~~~~~~~~~~~~
  4. Lexers for various SQL dialects and related interactive sessions.
  5. Postgres specific lexers:
  6. `PostgresLexer`
  7. A SQL lexer for the PostgreSQL dialect. Differences w.r.t. the SQL
  8. lexer are:
  9. - keywords and data types list parsed from the PG docs (run the
  10. `_postgres_builtins` module to update them);
  11. - Content of $-strings parsed using a specific lexer, e.g. the content
  12. of a PL/Python function is parsed using the Python lexer;
  13. - parse PG specific constructs: E-strings, $-strings, U&-strings,
  14. different operators and punctuation.
  15. `PlPgsqlLexer`
  16. A lexer for the PL/pgSQL language. Adds a few specific construct on
  17. top of the PG SQL lexer (such as <<label>>).
  18. `PostgresConsoleLexer`
  19. A lexer to highlight an interactive psql session:
  20. - identifies the prompt and does its best to detect the end of command
  21. in multiline statement where not all the lines are prefixed by a
  22. prompt, telling them apart from the output;
  23. - highlights errors in the output and notification levels;
  24. - handles psql backslash commands.
  25. The ``tests/examplefiles`` contains a few test files with data to be
  26. parsed by these lexers.
  27. :copyright: Copyright 2006-2021 by the Pygments team, see AUTHORS.
  28. :license: BSD, see LICENSE for details.
  29. """
  30. import re
  31. from pygments.lexer import Lexer, RegexLexer, do_insertions, bygroups, words
  32. from pygments.token import Punctuation, Whitespace, Text, Comment, Operator, \
  33. Keyword, Name, String, Number, Generic, Literal
  34. from pygments.lexers import get_lexer_by_name, ClassNotFound
  35. from pygments.lexers._postgres_builtins import KEYWORDS, DATATYPES, \
  36. PSEUDO_TYPES, PLPGSQL_KEYWORDS
  37. from pygments.lexers._mysql_builtins import \
  38. MYSQL_CONSTANTS, \
  39. MYSQL_DATATYPES, \
  40. MYSQL_FUNCTIONS, \
  41. MYSQL_KEYWORDS, \
  42. MYSQL_OPTIMIZER_HINTS
  43. from pygments.lexers import _tsql_builtins
  44. __all__ = ['PostgresLexer', 'PlPgsqlLexer', 'PostgresConsoleLexer',
  45. 'SqlLexer', 'TransactSqlLexer', 'MySqlLexer',
  46. 'SqliteConsoleLexer', 'RqlLexer']
  47. line_re = re.compile('.*?\n')
  48. language_re = re.compile(r"\s+LANGUAGE\s+'?(\w+)'?", re.IGNORECASE)
  49. do_re = re.compile(r'\bDO\b', re.IGNORECASE)
  50. # Regular expressions for analyse_text()
  51. name_between_bracket_re = re.compile(r'\[[a-zA-Z_]\w*\]')
  52. name_between_backtick_re = re.compile(r'`[a-zA-Z_]\w*`')
  53. tsql_go_re = re.compile(r'\bgo\b', re.IGNORECASE)
  54. tsql_declare_re = re.compile(r'\bdeclare\s+@', re.IGNORECASE)
  55. tsql_variable_re = re.compile(r'@[a-zA-Z_]\w*\b')
  56. def language_callback(lexer, match):
  57. """Parse the content of a $-string using a lexer
  58. The lexer is chosen looking for a nearby LANGUAGE or assumed as
  59. plpgsql if inside a DO statement and no LANGUAGE has been found.
  60. """
  61. lx = None
  62. m = language_re.match(lexer.text[match.end():match.end()+100])
  63. if m is not None:
  64. lx = lexer._get_lexer(m.group(1))
  65. else:
  66. m = list(language_re.finditer(
  67. lexer.text[max(0, match.start()-100):match.start()]))
  68. if m:
  69. lx = lexer._get_lexer(m[-1].group(1))
  70. else:
  71. m = list(do_re.finditer(
  72. lexer.text[max(0, match.start()-25):match.start()]))
  73. if m:
  74. lx = lexer._get_lexer('plpgsql')
  75. # 1 = $, 2 = delimiter, 3 = $
  76. yield (match.start(1), String, match.group(1))
  77. yield (match.start(2), String.Delimiter, match.group(2))
  78. yield (match.start(3), String, match.group(3))
  79. # 4 = string contents
  80. if lx:
  81. yield from lx.get_tokens_unprocessed(match.group(4))
  82. else:
  83. yield (match.start(4), String, match.group(4))
  84. # 5 = $, 6 = delimiter, 7 = $
  85. yield (match.start(5), String, match.group(5))
  86. yield (match.start(6), String.Delimiter, match.group(6))
  87. yield (match.start(7), String, match.group(7))
  88. class PostgresBase:
  89. """Base class for Postgres-related lexers.
  90. This is implemented as a mixin to avoid the Lexer metaclass kicking in.
  91. this way the different lexer don't have a common Lexer ancestor. If they
  92. had, _tokens could be created on this ancestor and not updated for the
  93. other classes, resulting e.g. in PL/pgSQL parsed as SQL. This shortcoming
  94. seem to suggest that regexp lexers are not really subclassable.
  95. """
  96. def get_tokens_unprocessed(self, text, *args):
  97. # Have a copy of the entire text to be used by `language_callback`.
  98. self.text = text
  99. yield from super().get_tokens_unprocessed(text, *args)
  100. def _get_lexer(self, lang):
  101. if lang.lower() == 'sql':
  102. return get_lexer_by_name('postgresql', **self.options)
  103. tries = [lang]
  104. if lang.startswith('pl'):
  105. tries.append(lang[2:])
  106. if lang.endswith('u'):
  107. tries.append(lang[:-1])
  108. if lang.startswith('pl') and lang.endswith('u'):
  109. tries.append(lang[2:-1])
  110. for lx in tries:
  111. try:
  112. return get_lexer_by_name(lx, **self.options)
  113. except ClassNotFound:
  114. pass
  115. else:
  116. # TODO: better logging
  117. # print >>sys.stderr, "language not found:", lang
  118. return None
  119. class PostgresLexer(PostgresBase, RegexLexer):
  120. """
  121. Lexer for the PostgreSQL dialect of SQL.
  122. .. versionadded:: 1.5
  123. """
  124. name = 'PostgreSQL SQL dialect'
  125. aliases = ['postgresql', 'postgres']
  126. mimetypes = ['text/x-postgresql']
  127. flags = re.IGNORECASE
  128. tokens = {
  129. 'root': [
  130. (r'\s+', Text),
  131. (r'--.*\n?', Comment.Single),
  132. (r'/\*', Comment.Multiline, 'multiline-comments'),
  133. (r'(' + '|'.join(s.replace(" ", r"\s+")
  134. for s in DATATYPES + PSEUDO_TYPES) + r')\b',
  135. Name.Builtin),
  136. (words(KEYWORDS, suffix=r'\b'), Keyword),
  137. (r'[+*/<>=~!@#%^&|`?-]+', Operator),
  138. (r'::', Operator), # cast
  139. (r'\$\d+', Name.Variable),
  140. (r'([0-9]*\.[0-9]*|[0-9]+)(e[+-]?[0-9]+)?', Number.Float),
  141. (r'[0-9]+', Number.Integer),
  142. (r"((?:E|U&)?)(')", bygroups(String.Affix, String.Single), 'string'),
  143. # quoted identifier
  144. (r'((?:U&)?)(")', bygroups(String.Affix, String.Name), 'quoted-ident'),
  145. (r'(?s)(\$)([^$]*)(\$)(.*?)(\$)(\2)(\$)', language_callback),
  146. (r'[a-z_]\w*', Name),
  147. # psql variable in SQL
  148. (r""":(['"]?)[a-z]\w*\b\1""", Name.Variable),
  149. (r'[;:()\[\]{},.]', Punctuation),
  150. ],
  151. 'multiline-comments': [
  152. (r'/\*', Comment.Multiline, 'multiline-comments'),
  153. (r'\*/', Comment.Multiline, '#pop'),
  154. (r'[^/*]+', Comment.Multiline),
  155. (r'[/*]', Comment.Multiline)
  156. ],
  157. 'string': [
  158. (r"[^']+", String.Single),
  159. (r"''", String.Single),
  160. (r"'", String.Single, '#pop'),
  161. ],
  162. 'quoted-ident': [
  163. (r'[^"]+', String.Name),
  164. (r'""', String.Name),
  165. (r'"', String.Name, '#pop'),
  166. ],
  167. }
  168. class PlPgsqlLexer(PostgresBase, RegexLexer):
  169. """
  170. Handle the extra syntax in Pl/pgSQL language.
  171. .. versionadded:: 1.5
  172. """
  173. name = 'PL/pgSQL'
  174. aliases = ['plpgsql']
  175. mimetypes = ['text/x-plpgsql']
  176. flags = re.IGNORECASE
  177. tokens = {k: l[:] for (k, l) in PostgresLexer.tokens.items()}
  178. # extend the keywords list
  179. for i, pattern in enumerate(tokens['root']):
  180. if pattern[1] == Keyword:
  181. tokens['root'][i] = (
  182. words(KEYWORDS + PLPGSQL_KEYWORDS, suffix=r'\b'),
  183. Keyword)
  184. del i
  185. break
  186. else:
  187. assert 0, "SQL keywords not found"
  188. # Add specific PL/pgSQL rules (before the SQL ones)
  189. tokens['root'][:0] = [
  190. (r'\%[a-z]\w*\b', Name.Builtin), # actually, a datatype
  191. (r':=', Operator),
  192. (r'\<\<[a-z]\w*\>\>', Name.Label),
  193. (r'\#[a-z]\w*\b', Keyword.Pseudo), # #variable_conflict
  194. ]
  195. class PsqlRegexLexer(PostgresBase, RegexLexer):
  196. """
  197. Extend the PostgresLexer adding support specific for psql commands.
  198. This is not a complete psql lexer yet as it lacks prompt support
  199. and output rendering.
  200. """
  201. name = 'PostgreSQL console - regexp based lexer'
  202. aliases = [] # not public
  203. flags = re.IGNORECASE
  204. tokens = {k: l[:] for (k, l) in PostgresLexer.tokens.items()}
  205. tokens['root'].append(
  206. (r'\\[^\s]+', Keyword.Pseudo, 'psql-command'))
  207. tokens['psql-command'] = [
  208. (r'\n', Text, 'root'),
  209. (r'\s+', Text),
  210. (r'\\[^\s]+', Keyword.Pseudo),
  211. (r""":(['"]?)[a-z]\w*\b\1""", Name.Variable),
  212. (r"'(''|[^'])*'", String.Single),
  213. (r"`([^`])*`", String.Backtick),
  214. (r"[^\s]+", String.Symbol),
  215. ]
  216. re_prompt = re.compile(r'^(\S.*?)??[=\-\(\$\'\"][#>]')
  217. re_psql_command = re.compile(r'\s*\\')
  218. re_end_command = re.compile(r';\s*(--.*?)?$')
  219. re_psql_command = re.compile(r'(\s*)(\\.+?)(\s+)$')
  220. re_error = re.compile(r'(ERROR|FATAL):')
  221. re_message = re.compile(
  222. r'((?:DEBUG|INFO|NOTICE|WARNING|ERROR|'
  223. r'FATAL|HINT|DETAIL|CONTEXT|LINE [0-9]+):)(.*?\n)')
  224. class lookahead:
  225. """Wrap an iterator and allow pushing back an item."""
  226. def __init__(self, x):
  227. self.iter = iter(x)
  228. self._nextitem = None
  229. def __iter__(self):
  230. return self
  231. def send(self, i):
  232. self._nextitem = i
  233. return i
  234. def __next__(self):
  235. if self._nextitem is not None:
  236. ni = self._nextitem
  237. self._nextitem = None
  238. return ni
  239. return next(self.iter)
  240. next = __next__
  241. class PostgresConsoleLexer(Lexer):
  242. """
  243. Lexer for psql sessions.
  244. .. versionadded:: 1.5
  245. """
  246. name = 'PostgreSQL console (psql)'
  247. aliases = ['psql', 'postgresql-console', 'postgres-console']
  248. mimetypes = ['text/x-postgresql-psql']
  249. def get_tokens_unprocessed(self, data):
  250. sql = PsqlRegexLexer(**self.options)
  251. lines = lookahead(line_re.findall(data))
  252. # prompt-output cycle
  253. while 1:
  254. # consume the lines of the command: start with an optional prompt
  255. # and continue until the end of command is detected
  256. curcode = ''
  257. insertions = []
  258. for line in lines:
  259. # Identify a shell prompt in case of psql commandline example
  260. if line.startswith('$') and not curcode:
  261. lexer = get_lexer_by_name('console', **self.options)
  262. yield from lexer.get_tokens_unprocessed(line)
  263. break
  264. # Identify a psql prompt
  265. mprompt = re_prompt.match(line)
  266. if mprompt is not None:
  267. insertions.append((len(curcode),
  268. [(0, Generic.Prompt, mprompt.group())]))
  269. curcode += line[len(mprompt.group()):]
  270. else:
  271. curcode += line
  272. # Check if this is the end of the command
  273. # TODO: better handle multiline comments at the end with
  274. # a lexer with an external state?
  275. if re_psql_command.match(curcode) \
  276. or re_end_command.search(curcode):
  277. break
  278. # Emit the combined stream of command and prompt(s)
  279. yield from do_insertions(insertions,
  280. sql.get_tokens_unprocessed(curcode))
  281. # Emit the output lines
  282. out_token = Generic.Output
  283. for line in lines:
  284. mprompt = re_prompt.match(line)
  285. if mprompt is not None:
  286. # push the line back to have it processed by the prompt
  287. lines.send(line)
  288. break
  289. mmsg = re_message.match(line)
  290. if mmsg is not None:
  291. if mmsg.group(1).startswith("ERROR") \
  292. or mmsg.group(1).startswith("FATAL"):
  293. out_token = Generic.Error
  294. yield (mmsg.start(1), Generic.Strong, mmsg.group(1))
  295. yield (mmsg.start(2), out_token, mmsg.group(2))
  296. else:
  297. yield (0, out_token, line)
  298. else:
  299. return
  300. class SqlLexer(RegexLexer):
  301. """
  302. Lexer for Structured Query Language. Currently, this lexer does
  303. not recognize any special syntax except ANSI SQL.
  304. """
  305. name = 'SQL'
  306. aliases = ['sql']
  307. filenames = ['*.sql']
  308. mimetypes = ['text/x-sql']
  309. flags = re.IGNORECASE
  310. tokens = {
  311. 'root': [
  312. (r'\s+', Text),
  313. (r'--.*\n?', Comment.Single),
  314. (r'/\*', Comment.Multiline, 'multiline-comments'),
  315. (words((
  316. 'ABORT', 'ABS', 'ABSOLUTE', 'ACCESS', 'ADA', 'ADD', 'ADMIN', 'AFTER',
  317. 'AGGREGATE', 'ALIAS', 'ALL', 'ALLOCATE', 'ALTER', 'ANALYSE', 'ANALYZE',
  318. 'AND', 'ANY', 'ARE', 'AS', 'ASC', 'ASENSITIVE', 'ASSERTION', 'ASSIGNMENT',
  319. 'ASYMMETRIC', 'AT', 'ATOMIC', 'AUTHORIZATION', 'AVG', 'BACKWARD',
  320. 'BEFORE', 'BEGIN', 'BETWEEN', 'BITVAR', 'BIT_LENGTH', 'BOTH', 'BREADTH',
  321. 'BY', 'C', 'CACHE', 'CALL', 'CALLED', 'CARDINALITY', 'CASCADE',
  322. 'CASCADED', 'CASE', 'CAST', 'CATALOG', 'CATALOG_NAME', 'CHAIN',
  323. 'CHARACTERISTICS', 'CHARACTER_LENGTH', 'CHARACTER_SET_CATALOG',
  324. 'CHARACTER_SET_NAME', 'CHARACTER_SET_SCHEMA', 'CHAR_LENGTH', 'CHECK',
  325. 'CHECKED', 'CHECKPOINT', 'CLASS', 'CLASS_ORIGIN', 'CLOB', 'CLOSE',
  326. 'CLUSTER', 'COALESCE', 'COBOL', 'COLLATE', 'COLLATION',
  327. 'COLLATION_CATALOG', 'COLLATION_NAME', 'COLLATION_SCHEMA', 'COLUMN',
  328. 'COLUMN_NAME', 'COMMAND_FUNCTION', 'COMMAND_FUNCTION_CODE', 'COMMENT',
  329. 'COMMIT', 'COMMITTED', 'COMPLETION', 'CONDITION_NUMBER', 'CONNECT',
  330. 'CONNECTION', 'CONNECTION_NAME', 'CONSTRAINT', 'CONSTRAINTS',
  331. 'CONSTRAINT_CATALOG', 'CONSTRAINT_NAME', 'CONSTRAINT_SCHEMA',
  332. 'CONSTRUCTOR', 'CONTAINS', 'CONTINUE', 'CONVERSION', 'CONVERT',
  333. 'COPY', 'CORRESPONDING', 'COUNT', 'CREATE', 'CREATEDB', 'CREATEUSER',
  334. 'CROSS', 'CUBE', 'CURRENT', 'CURRENT_DATE', 'CURRENT_PATH',
  335. 'CURRENT_ROLE', 'CURRENT_TIME', 'CURRENT_TIMESTAMP', 'CURRENT_USER',
  336. 'CURSOR', 'CURSOR_NAME', 'CYCLE', 'DATA', 'DATABASE',
  337. 'DATETIME_INTERVAL_CODE', 'DATETIME_INTERVAL_PRECISION', 'DAY',
  338. 'DEALLOCATE', 'DECLARE', 'DEFAULT', 'DEFAULTS', 'DEFERRABLE',
  339. 'DEFERRED', 'DEFINED', 'DEFINER', 'DELETE', 'DELIMITER', 'DELIMITERS',
  340. 'DEREF', 'DESC', 'DESCRIBE', 'DESCRIPTOR', 'DESTROY', 'DESTRUCTOR',
  341. 'DETERMINISTIC', 'DIAGNOSTICS', 'DICTIONARY', 'DISCONNECT', 'DISPATCH',
  342. 'DISTINCT', 'DO', 'DOMAIN', 'DROP', 'DYNAMIC', 'DYNAMIC_FUNCTION',
  343. 'DYNAMIC_FUNCTION_CODE', 'EACH', 'ELSE', 'ELSIF', 'ENCODING',
  344. 'ENCRYPTED', 'END', 'END-EXEC', 'EQUALS', 'ESCAPE', 'EVERY', 'EXCEPTION',
  345. 'EXCEPT', 'EXCLUDING', 'EXCLUSIVE', 'EXEC', 'EXECUTE', 'EXISTING',
  346. 'EXISTS', 'EXPLAIN', 'EXTERNAL', 'EXTRACT', 'FALSE', 'FETCH', 'FINAL',
  347. 'FIRST', 'FOR', 'FORCE', 'FOREIGN', 'FORTRAN', 'FORWARD', 'FOUND', 'FREE',
  348. 'FREEZE', 'FROM', 'FULL', 'FUNCTION', 'G', 'GENERAL', 'GENERATED', 'GET',
  349. 'GLOBAL', 'GO', 'GOTO', 'GRANT', 'GRANTED', 'GROUP', 'GROUPING',
  350. 'HANDLER', 'HAVING', 'HIERARCHY', 'HOLD', 'HOST', 'IDENTITY', 'IF',
  351. 'IGNORE', 'ILIKE', 'IMMEDIATE', 'IMMEDIATELY', 'IMMUTABLE', 'IMPLEMENTATION', 'IMPLICIT',
  352. 'IN', 'INCLUDING', 'INCREMENT', 'INDEX', 'INDITCATOR', 'INFIX',
  353. 'INHERITS', 'INITIALIZE', 'INITIALLY', 'INNER', 'INOUT', 'INPUT',
  354. 'INSENSITIVE', 'INSERT', 'INSTANTIABLE', 'INSTEAD', 'INTERSECT', 'INTO',
  355. 'INVOKER', 'IS', 'ISNULL', 'ISOLATION', 'ITERATE', 'JOIN', 'KEY',
  356. 'KEY_MEMBER', 'KEY_TYPE', 'LANCOMPILER', 'LANGUAGE', 'LARGE', 'LAST',
  357. 'LATERAL', 'LEADING', 'LEFT', 'LENGTH', 'LESS', 'LEVEL', 'LIKE', 'LIMIT',
  358. 'LISTEN', 'LOAD', 'LOCAL', 'LOCALTIME', 'LOCALTIMESTAMP', 'LOCATION',
  359. 'LOCATOR', 'LOCK', 'LOWER', 'MAP', 'MATCH', 'MAX', 'MAXVALUE',
  360. 'MESSAGE_LENGTH', 'MESSAGE_OCTET_LENGTH', 'MESSAGE_TEXT', 'METHOD', 'MIN',
  361. 'MINUTE', 'MINVALUE', 'MOD', 'MODE', 'MODIFIES', 'MODIFY', 'MONTH',
  362. 'MORE', 'MOVE', 'MUMPS', 'NAMES', 'NATIONAL', 'NATURAL', 'NCHAR', 'NCLOB',
  363. 'NEW', 'NEXT', 'NO', 'NOCREATEDB', 'NOCREATEUSER', 'NONE', 'NOT',
  364. 'NOTHING', 'NOTIFY', 'NOTNULL', 'NULL', 'NULLABLE', 'NULLIF', 'OBJECT',
  365. 'OCTET_LENGTH', 'OF', 'OFF', 'OFFSET', 'OIDS', 'OLD', 'ON', 'ONLY',
  366. 'OPEN', 'OPERATION', 'OPERATOR', 'OPTION', 'OPTIONS', 'OR', 'ORDER',
  367. 'ORDINALITY', 'OUT', 'OUTER', 'OUTPUT', 'OVERLAPS', 'OVERLAY',
  368. 'OVERRIDING', 'OWNER', 'PAD', 'PARAMETER', 'PARAMETERS', 'PARAMETER_MODE',
  369. 'PARAMETER_NAME', 'PARAMETER_ORDINAL_POSITION',
  370. 'PARAMETER_SPECIFIC_CATALOG', 'PARAMETER_SPECIFIC_NAME',
  371. 'PARAMETER_SPECIFIC_SCHEMA', 'PARTIAL', 'PASCAL', 'PENDANT', 'PERIOD', 'PLACING',
  372. 'PLI', 'POSITION', 'POSTFIX', 'PRECEEDS', 'PRECISION', 'PREFIX', 'PREORDER',
  373. 'PREPARE', 'PRESERVE', 'PRIMARY', 'PRIOR', 'PRIVILEGES', 'PROCEDURAL',
  374. 'PROCEDURE', 'PUBLIC', 'READ', 'READS', 'RECHECK', 'RECURSIVE', 'REF',
  375. 'REFERENCES', 'REFERENCING', 'REINDEX', 'RELATIVE', 'RENAME',
  376. 'REPEATABLE', 'REPLACE', 'RESET', 'RESTART', 'RESTRICT', 'RESULT',
  377. 'RETURN', 'RETURNED_LENGTH', 'RETURNED_OCTET_LENGTH', 'RETURNED_SQLSTATE',
  378. 'RETURNS', 'REVOKE', 'RIGHT', 'ROLE', 'ROLLBACK', 'ROLLUP', 'ROUTINE',
  379. 'ROUTINE_CATALOG', 'ROUTINE_NAME', 'ROUTINE_SCHEMA', 'ROW', 'ROWS',
  380. 'ROW_COUNT', 'RULE', 'SAVE_POINT', 'SCALE', 'SCHEMA', 'SCHEMA_NAME',
  381. 'SCOPE', 'SCROLL', 'SEARCH', 'SECOND', 'SECURITY', 'SELECT', 'SELF',
  382. 'SENSITIVE', 'SERIALIZABLE', 'SERVER_NAME', 'SESSION', 'SESSION_USER',
  383. 'SET', 'SETOF', 'SETS', 'SHARE', 'SHOW', 'SIMILAR', 'SIMPLE', 'SIZE',
  384. 'SOME', 'SOURCE', 'SPACE', 'SPECIFIC', 'SPECIFICTYPE', 'SPECIFIC_NAME',
  385. 'SQL', 'SQLCODE', 'SQLERROR', 'SQLEXCEPTION', 'SQLSTATE', 'SQLWARNINIG',
  386. 'STABLE', 'START', 'STATE', 'STATEMENT', 'STATIC', 'STATISTICS', 'STDIN',
  387. 'STDOUT', 'STORAGE', 'STRICT', 'STRUCTURE', 'STYPE', 'SUBCLASS_ORIGIN',
  388. 'SUBLIST', 'SUBSTRING', 'SUCCEEDS', 'SUM', 'SYMMETRIC', 'SYSID', 'SYSTEM',
  389. 'SYSTEM_USER', 'TABLE', 'TABLE_NAME', ' TEMP', 'TEMPLATE', 'TEMPORARY',
  390. 'TERMINATE', 'THAN', 'THEN', 'TIME', 'TIMESTAMP', 'TIMEZONE_HOUR',
  391. 'TIMEZONE_MINUTE', 'TO', 'TOAST', 'TRAILING', 'TRANSACTION',
  392. 'TRANSACTIONS_COMMITTED', 'TRANSACTIONS_ROLLED_BACK', 'TRANSACTION_ACTIVE',
  393. 'TRANSFORM', 'TRANSFORMS', 'TRANSLATE', 'TRANSLATION', 'TREAT', 'TRIGGER',
  394. 'TRIGGER_CATALOG', 'TRIGGER_NAME', 'TRIGGER_SCHEMA', 'TRIM', 'TRUE',
  395. 'TRUNCATE', 'TRUSTED', 'TYPE', 'UNCOMMITTED', 'UNDER', 'UNENCRYPTED',
  396. 'UNION', 'UNIQUE', 'UNKNOWN', 'UNLISTEN', 'UNNAMED', 'UNNEST', 'UNTIL',
  397. 'UPDATE', 'UPPER', 'USAGE', 'USER', 'USER_DEFINED_TYPE_CATALOG',
  398. 'USER_DEFINED_TYPE_NAME', 'USER_DEFINED_TYPE_SCHEMA', 'USING', 'VACUUM',
  399. 'VALID', 'VALIDATOR', 'VALUES', 'VARIABLE', 'VERBOSE',
  400. 'VERSION', 'VERSIONS', 'VERSIONING', 'VIEW',
  401. 'VOLATILE', 'WHEN', 'WHENEVER', 'WHERE', 'WITH', 'WITHOUT', 'WORK',
  402. 'WRITE', 'YEAR', 'ZONE'), suffix=r'\b'),
  403. Keyword),
  404. (words((
  405. 'ARRAY', 'BIGINT', 'BINARY', 'BIT', 'BLOB', 'BOOLEAN', 'CHAR',
  406. 'CHARACTER', 'DATE', 'DEC', 'DECIMAL', 'FLOAT', 'INT', 'INTEGER',
  407. 'INTERVAL', 'NUMBER', 'NUMERIC', 'REAL', 'SERIAL', 'SMALLINT',
  408. 'VARCHAR', 'VARYING', 'INT8', 'SERIAL8', 'TEXT'), suffix=r'\b'),
  409. Name.Builtin),
  410. (r'[+*/<>=~!@#%^&|`?-]', Operator),
  411. (r'[0-9]+', Number.Integer),
  412. # TODO: Backslash escapes?
  413. (r"'(''|[^'])*'", String.Single),
  414. (r'"(""|[^"])*"', String.Symbol), # not a real string literal in ANSI SQL
  415. (r'[a-z_][\w$]*', Name), # allow $s in strings for Oracle
  416. (r'[;:()\[\],.]', Punctuation)
  417. ],
  418. 'multiline-comments': [
  419. (r'/\*', Comment.Multiline, 'multiline-comments'),
  420. (r'\*/', Comment.Multiline, '#pop'),
  421. (r'[^/*]+', Comment.Multiline),
  422. (r'[/*]', Comment.Multiline)
  423. ]
  424. }
  425. class TransactSqlLexer(RegexLexer):
  426. """
  427. Transact-SQL (T-SQL) is Microsoft's and Sybase's proprietary extension to
  428. SQL.
  429. The list of keywords includes ODBC and keywords reserved for future use..
  430. """
  431. name = 'Transact-SQL'
  432. aliases = ['tsql', 't-sql']
  433. filenames = ['*.sql']
  434. mimetypes = ['text/x-tsql']
  435. # Use re.UNICODE to allow non ASCII letters in names.
  436. flags = re.IGNORECASE | re.UNICODE
  437. tokens = {
  438. 'root': [
  439. (r'\s+', Whitespace),
  440. (r'--.*?$\n?', Comment.Single),
  441. (r'/\*', Comment.Multiline, 'multiline-comments'),
  442. (words(_tsql_builtins.OPERATORS), Operator),
  443. (words(_tsql_builtins.OPERATOR_WORDS, suffix=r'\b'), Operator.Word),
  444. (words(_tsql_builtins.TYPES, suffix=r'\b'), Name.Class),
  445. (words(_tsql_builtins.FUNCTIONS, suffix=r'\b'), Name.Function),
  446. (r'(goto)(\s+)(\w+\b)', bygroups(Keyword, Whitespace, Name.Label)),
  447. (words(_tsql_builtins.KEYWORDS, suffix=r'\b'), Keyword),
  448. (r'(\[)([^]]+)(\])', bygroups(Operator, Name, Operator)),
  449. (r'0x[0-9a-f]+', Number.Hex),
  450. # Float variant 1, for example: 1., 1.e2, 1.2e3
  451. (r'[0-9]+\.[0-9]*(e[+-]?[0-9]+)?', Number.Float),
  452. # Float variant 2, for example: .1, .1e2
  453. (r'\.[0-9]+(e[+-]?[0-9]+)?', Number.Float),
  454. # Float variant 3, for example: 123e45
  455. (r'[0-9]+e[+-]?[0-9]+', Number.Float),
  456. (r'[0-9]+', Number.Integer),
  457. (r"'(''|[^'])*'", String.Single),
  458. (r'"(""|[^"])*"', String.Symbol),
  459. (r'[;(),.]', Punctuation),
  460. # Below we use \w even for the first "real" character because
  461. # tokens starting with a digit have already been recognized
  462. # as Number above.
  463. (r'@@\w+', Name.Builtin),
  464. (r'@\w+', Name.Variable),
  465. (r'(\w+)(:)', bygroups(Name.Label, Punctuation)),
  466. (r'#?#?\w+', Name), # names for temp tables and anything else
  467. (r'\?', Name.Variable.Magic), # parameter for prepared statements
  468. ],
  469. 'multiline-comments': [
  470. (r'/\*', Comment.Multiline, 'multiline-comments'),
  471. (r'\*/', Comment.Multiline, '#pop'),
  472. (r'[^/*]+', Comment.Multiline),
  473. (r'[/*]', Comment.Multiline)
  474. ]
  475. }
  476. def analyse_text(text):
  477. rating = 0
  478. if tsql_declare_re.search(text):
  479. # Found T-SQL variable declaration.
  480. rating = 1.0
  481. else:
  482. name_between_backtick_count = len(
  483. name_between_backtick_re.findall(text))
  484. name_between_bracket_count = len(
  485. name_between_bracket_re.findall(text))
  486. # We need to check if there are any names using
  487. # backticks or brackets, as otherwise both are 0
  488. # and 0 >= 2 * 0, so we would always assume it's true
  489. dialect_name_count = name_between_backtick_count + name_between_bracket_count
  490. if dialect_name_count >= 1 and \
  491. name_between_bracket_count >= 2 * name_between_backtick_count:
  492. # Found at least twice as many [name] as `name`.
  493. rating += 0.5
  494. elif name_between_bracket_count > name_between_backtick_count:
  495. rating += 0.2
  496. elif name_between_bracket_count > 0:
  497. rating += 0.1
  498. if tsql_variable_re.search(text) is not None:
  499. rating += 0.1
  500. if tsql_go_re.search(text) is not None:
  501. rating += 0.1
  502. return rating
  503. class MySqlLexer(RegexLexer):
  504. """The Oracle MySQL lexer.
  505. This lexer does not attempt to maintain strict compatibility with
  506. MariaDB syntax or keywords. Although MySQL and MariaDB's common code
  507. history suggests there may be significant overlap between the two,
  508. compatibility between the two is not a target for this lexer.
  509. """
  510. name = 'MySQL'
  511. aliases = ['mysql']
  512. mimetypes = ['text/x-mysql']
  513. flags = re.IGNORECASE
  514. tokens = {
  515. 'root': [
  516. (r'\s+', Text),
  517. # Comments
  518. (r'(?:#|--\s+).*', Comment.Single),
  519. (r'/\*\+', Comment.Special, 'optimizer-hints'),
  520. (r'/\*', Comment.Multiline, 'multiline-comment'),
  521. # Hexadecimal literals
  522. (r"x'([0-9a-f]{2})+'", Number.Hex), # MySQL requires paired hex characters in this form.
  523. (r'0x[0-9a-f]+', Number.Hex),
  524. # Binary literals
  525. (r"b'[01]+'", Number.Bin),
  526. (r'0b[01]+', Number.Bin),
  527. # Numeric literals
  528. (r'[0-9]+\.[0-9]*(e[+-]?[0-9]+)?', Number.Float), # Mandatory integer, optional fraction and exponent
  529. (r'[0-9]*\.[0-9]+(e[+-]?[0-9]+)?', Number.Float), # Mandatory fraction, optional integer and exponent
  530. (r'[0-9]+e[+-]?[0-9]+', Number.Float), # Exponents with integer significands are still floats
  531. (r'[0-9]+(?=[^0-9a-z$_\u0080-\uffff])', Number.Integer), # Integers that are not in a schema object name
  532. # Date literals
  533. (r"\{\s*d\s*(?P<quote>['\"])\s*\d{2}(\d{2})?.?\d{2}.?\d{2}\s*(?P=quote)\s*\}",
  534. Literal.Date),
  535. # Time literals
  536. (r"\{\s*t\s*(?P<quote>['\"])\s*(?:\d+\s+)?\d{1,2}.?\d{1,2}.?\d{1,2}(\.\d*)?\s*(?P=quote)\s*\}",
  537. Literal.Date),
  538. # Timestamp literals
  539. (
  540. r"\{\s*ts\s*(?P<quote>['\"])\s*"
  541. r"\d{2}(?:\d{2})?.?\d{2}.?\d{2}" # Date part
  542. r"\s+" # Whitespace between date and time
  543. r"\d{1,2}.?\d{1,2}.?\d{1,2}(\.\d*)?" # Time part
  544. r"\s*(?P=quote)\s*\}",
  545. Literal.Date
  546. ),
  547. # String literals
  548. (r"'", String.Single, 'single-quoted-string'),
  549. (r'"', String.Double, 'double-quoted-string'),
  550. # Variables
  551. (r'@@(?:global\.|persist\.|persist_only\.|session\.)?[a-z_]+', Name.Variable),
  552. (r'@[a-z0-9_$.]+', Name.Variable),
  553. (r"@'", Name.Variable, 'single-quoted-variable'),
  554. (r'@"', Name.Variable, 'double-quoted-variable'),
  555. (r"@`", Name.Variable, 'backtick-quoted-variable'),
  556. (r'\?', Name.Variable), # For demonstrating prepared statements
  557. # Operators
  558. (r'[!%&*+/:<=>^|~-]+', Operator),
  559. # Exceptions; these words tokenize differently in different contexts.
  560. (r'\b(set)(?!\s*\()', Keyword),
  561. (r'\b(character)(\s+)(set)\b', bygroups(Keyword, Text, Keyword)),
  562. # In all other known cases, "SET" is tokenized by MYSQL_DATATYPES.
  563. (words(MYSQL_CONSTANTS, prefix=r'\b', suffix=r'\b'), Name.Constant),
  564. (words(MYSQL_DATATYPES, prefix=r'\b', suffix=r'\b'), Keyword.Type),
  565. (words(MYSQL_KEYWORDS, prefix=r'\b', suffix=r'\b'), Keyword),
  566. (words(MYSQL_FUNCTIONS, prefix=r'\b', suffix=r'\b(\s*)(\()'),
  567. bygroups(Name.Function, Text, Punctuation)),
  568. # Schema object names
  569. #
  570. # Note: Although the first regex supports unquoted all-numeric
  571. # identifiers, this will not be a problem in practice because
  572. # numeric literals have already been handled above.
  573. #
  574. ('[0-9a-z$_\u0080-\uffff]+', Name),
  575. (r'`', Name.Quoted, 'schema-object-name'),
  576. # Punctuation
  577. (r'[(),.;]', Punctuation),
  578. ],
  579. # Multiline comment substates
  580. # ---------------------------
  581. 'optimizer-hints': [
  582. (r'[^*a-z]+', Comment.Special),
  583. (r'\*/', Comment.Special, '#pop'),
  584. (words(MYSQL_OPTIMIZER_HINTS, suffix=r'\b'), Comment.Preproc),
  585. ('[a-z]+', Comment.Special),
  586. (r'\*', Comment.Special),
  587. ],
  588. 'multiline-comment': [
  589. (r'[^*]+', Comment.Multiline),
  590. (r'\*/', Comment.Multiline, '#pop'),
  591. (r'\*', Comment.Multiline),
  592. ],
  593. # String substates
  594. # ----------------
  595. 'single-quoted-string': [
  596. (r"[^'\\]+", String.Single),
  597. (r"''", String.Escape),
  598. (r"""\\[0'"bnrtZ\\%_]""", String.Escape),
  599. (r"'", String.Single, '#pop'),
  600. ],
  601. 'double-quoted-string': [
  602. (r'[^"\\]+', String.Double),
  603. (r'""', String.Escape),
  604. (r"""\\[0'"bnrtZ\\%_]""", String.Escape),
  605. (r'"', String.Double, '#pop'),
  606. ],
  607. # Variable substates
  608. # ------------------
  609. 'single-quoted-variable': [
  610. (r"[^']+", Name.Variable),
  611. (r"''", Name.Variable),
  612. (r"'", Name.Variable, '#pop'),
  613. ],
  614. 'double-quoted-variable': [
  615. (r'[^"]+', Name.Variable),
  616. (r'""', Name.Variable),
  617. (r'"', Name.Variable, '#pop'),
  618. ],
  619. 'backtick-quoted-variable': [
  620. (r'[^`]+', Name.Variable),
  621. (r'``', Name.Variable),
  622. (r'`', Name.Variable, '#pop'),
  623. ],
  624. # Schema object name substates
  625. # ----------------------------
  626. #
  627. # "Name.Quoted" and "Name.Quoted.Escape" are non-standard but
  628. # formatters will style them as "Name" by default but add
  629. # additional styles based on the token name. This gives users
  630. # flexibility to add custom styles as desired.
  631. #
  632. 'schema-object-name': [
  633. (r'[^`]+', Name.Quoted),
  634. (r'``', Name.Quoted.Escape),
  635. (r'`', Name.Quoted, '#pop'),
  636. ],
  637. }
  638. def analyse_text(text):
  639. rating = 0
  640. name_between_backtick_count = len(
  641. name_between_backtick_re.findall(text))
  642. name_between_bracket_count = len(
  643. name_between_bracket_re.findall(text))
  644. # Same logic as above in the TSQL analysis
  645. dialect_name_count = name_between_backtick_count + name_between_bracket_count
  646. if dialect_name_count >= 1 and \
  647. name_between_backtick_count >= 2 * name_between_bracket_count:
  648. # Found at least twice as many `name` as [name].
  649. rating += 0.5
  650. elif name_between_backtick_count > name_between_bracket_count:
  651. rating += 0.2
  652. elif name_between_backtick_count > 0:
  653. rating += 0.1
  654. return rating
  655. class SqliteConsoleLexer(Lexer):
  656. """
  657. Lexer for example sessions using sqlite3.
  658. .. versionadded:: 0.11
  659. """
  660. name = 'sqlite3con'
  661. aliases = ['sqlite3']
  662. filenames = ['*.sqlite3-console']
  663. mimetypes = ['text/x-sqlite3-console']
  664. def get_tokens_unprocessed(self, data):
  665. sql = SqlLexer(**self.options)
  666. curcode = ''
  667. insertions = []
  668. for match in line_re.finditer(data):
  669. line = match.group()
  670. if line.startswith('sqlite> ') or line.startswith(' ...> '):
  671. insertions.append((len(curcode),
  672. [(0, Generic.Prompt, line[:8])]))
  673. curcode += line[8:]
  674. else:
  675. if curcode:
  676. yield from do_insertions(insertions,
  677. sql.get_tokens_unprocessed(curcode))
  678. curcode = ''
  679. insertions = []
  680. if line.startswith('SQL error: '):
  681. yield (match.start(), Generic.Traceback, line)
  682. else:
  683. yield (match.start(), Generic.Output, line)
  684. if curcode:
  685. yield from do_insertions(insertions,
  686. sql.get_tokens_unprocessed(curcode))
  687. class RqlLexer(RegexLexer):
  688. """
  689. Lexer for Relation Query Language.
  690. `RQL <http://www.logilab.org/project/rql>`_
  691. .. versionadded:: 2.0
  692. """
  693. name = 'RQL'
  694. aliases = ['rql']
  695. filenames = ['*.rql']
  696. mimetypes = ['text/x-rql']
  697. flags = re.IGNORECASE
  698. tokens = {
  699. 'root': [
  700. (r'\s+', Text),
  701. (r'(DELETE|SET|INSERT|UNION|DISTINCT|WITH|WHERE|BEING|OR'
  702. r'|AND|NOT|GROUPBY|HAVING|ORDERBY|ASC|DESC|LIMIT|OFFSET'
  703. r'|TODAY|NOW|TRUE|FALSE|NULL|EXISTS)\b', Keyword),
  704. (r'[+*/<>=%-]', Operator),
  705. (r'(Any|is|instance_of|CWEType|CWRelation)\b', Name.Builtin),
  706. (r'[0-9]+', Number.Integer),
  707. (r'[A-Z_]\w*\??', Name),
  708. (r"'(''|[^'])*'", String.Single),
  709. (r'"(""|[^"])*"', String.Single),
  710. (r'[;:()\[\],.]', Punctuation)
  711. ],
  712. }