Skip to content

Commit 73d5a07

Browse files
committed
Initial commit
0 parents  commit 73d5a07

File tree

7 files changed

+280
-0
lines changed

7 files changed

+280
-0
lines changed

.gitignore

Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
# Logs
2+
logs
3+
*.log
4+
5+
# Runtime data
6+
pids
7+
*.pid
8+
*.seed
9+
10+
# Directory for instrumented libs generated by jscoverage/JSCover
11+
lib-cov
12+
13+
# Coverage directory used by tools like istanbul
14+
coverage
15+
16+
# Grunt intermediate storage (http://gruntjs.com/creating-plugins#storing-task-files)
17+
.grunt
18+
19+
# node-waf configuration
20+
.lock-wscript
21+
22+
# Compiled binary addons (http://nodejs.org/api/addons.html)
23+
build/Release
24+
25+
# Dependency directory
26+
# https://www.npmjs.org/doc/misc/npm-faq.html#should-i-check-my-node_modules-folder-into-git
27+
node_modules
28+
29+
*.log

LICENSE

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
MIT License
2+
3+
Copyright (c) 2018 Malcolm Nihlén
4+
5+
Permission is hereby granted, free of charge, to any person obtaining a copy
6+
of this software and associated documentation files (the "Software"), to deal
7+
in the Software without restriction, including without limitation the rights
8+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9+
copies of the Software, and to permit persons to whom the Software is
10+
furnished to do so, subject to the following conditions:
11+
12+
The above copyright notice and this permission notice shall be included in all
13+
copies or substantial portions of the Software.
14+
15+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21+
SOFTWARE.

README.md

Lines changed: 104 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,104 @@
1+
# SQL syntax highlight
2+
> A simple and lightweight syntax highlighting library for SQL
3+
4+
[![NPM Version][npm-image]][npm-url]
5+
[![Downloads Stats][npm-downloads]][npm-url]
6+
7+
## What's it all about?
8+
SQL Highlight is a small package that highlights SQL queries. It can output to both the terminal with Unicode escape sequences, as well as to normal HTML
9+
10+
## Installation
11+
12+
Install via Yarn (recommended):
13+
```bash
14+
yarn add sql-highlight -D
15+
```
16+
Install via NPM:
17+
```bash
18+
npm install sql-highlight --save-dev
19+
```
20+
21+
## Usage
22+
Note that we're using ES6 import statements here. Usage with `require` works just as well.
23+
24+
**In its most basic form:**
25+
```javascript
26+
import Highlight from 'sql-highlight'
27+
const highlighter = new Highlight()
28+
29+
console.log(highlighter.highlight("SELECT `id`, `username` FROM `users` WHERE `email` = '[email protected]'"))
30+
```
31+
32+
**Output:**
33+
34+
![Screenshot 1](screenshot1.png)
35+
36+
**HTML mode:**
37+
38+
```javascript
39+
import Highlight from 'sql-highlight'
40+
const highlighter = new Highlight({
41+
html: true
42+
})
43+
44+
document.body.innerHTML += highlighter.highlight("SELECT `id`, `username` FROM `users` WHERE `email` = '[email protected]'"))
45+
```
46+
47+
**Output:**
48+
```html
49+
<span class="sql-hl-keyword">SELECT</span>
50+
<span class="sql-hl-string">`id`</span>
51+
<span class="sql-hl-special">,</span>
52+
<span class="sql-hl-string">`username`</span>
53+
<span class="sql-hl-keyword">FROM</span>
54+
<span class="sql-hl-string">`users`</span>
55+
<span class="sql-hl-keyword">WHERE</span>
56+
<span class="sql-hl-string">`email`</span>
57+
<span class="sql-hl-special">=</span>
58+
<span class="sql-hl-string">'[email protected]'</span>
59+
```
60+
61+
## Options
62+
Options may be passed to the constructor while instantiating the `Highlighter` class.
63+
64+
| Option | Value | Default | Description |
65+
| --- | --- | --- | --- |
66+
| html | `boolean` | `true` | Set to true to render HTML instead of Unicode.
67+
| classPrefix | `string` | `'sql-hl-'` | Prefix to prepend to classes for HTML span-tags. Is appended with entity name.
68+
| colors | `Object` | _See below_* | What color codes to use for Unicode rendering.
69+
70+
\* `colors` option default value
71+
```javascript
72+
{
73+
keyword: '\x1b[35m', // SQL reserved keywords
74+
function: '\x1b[31m', // Functions
75+
number: '\x1b[32m', // Numbers
76+
string: '\x1b[32m', // Strings
77+
special: '\x1b[33m', // Special characters
78+
bracket: '\x1b[33m' // Brackets (parentheses)
79+
}
80+
```
81+
82+
## Contributing
83+
84+
1. Fork it (<https://github.com/scriptcoded/sql-highlight/fork>)
85+
2. Create your feature branch (`git checkout -b feature/fooBar`)
86+
3. Commit your changes (`git commit -am 'Add some fooBar'`)
87+
4. Push to the branch (`git push origin feature/fooBar`)
88+
5. Create a new Pull Request
89+
90+
## Additional information
91+
92+
Malcolm Nihlén - [email protected]
93+
94+
Distributed under the MIT licence. See `LICENCE` for more information.
95+
96+
https://github.com/scriptcoded
97+
98+
## Disclaimer
99+
This was initially a fork from https://github.com/pomahtuk/sequilize-highlight. The repo wasn't being
100+
updated, NPM wasn't serving the latest version and there was a severe memory leak. Though the latest version now exists on NPM, issues still persist. This repo serves to address those problems, as well as providing a cleaner interface that's not bound to Sequelize.
101+
102+
[npm-image]: https://img.shields.io/npm/v/sql-highlight.svg
103+
[npm-url]: https://npmjs.org/package/sql-highlight
104+
[npm-downloads]: https://img.shields.io/npm/dm/sql-highlight.svg

index.js

Lines changed: 90 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,90 @@
1+
'use strict'
2+
3+
const defaultOptions = {
4+
html: false,
5+
classPrefix: 'sql-hl-',
6+
colors: {
7+
keyword: '\x1b[35m',
8+
function: '\x1b[31m',
9+
number: '\x1b[32m',
10+
string: '\x1b[32m',
11+
special: '\x1b[33m',
12+
bracket: '\x1b[33m'
13+
}
14+
}
15+
const keywordsUpper = [
16+
'PRAGMA', 'CREATE', 'EXISTS', 'INTEGER', 'PRIMARY', 'letCHAR',
17+
'DATETIME', 'NULL', 'REFERENCES', 'AND', 'AS', 'ASC', 'INDEX_LIST',
18+
'BETWEEN', 'BY', 'CASE', 'CURRENT_DATE', 'CURRENT_TIME', 'DELETE',
19+
'DESC', 'DISTINCT', 'EACH', 'ELSE', 'ELSEIF', 'FALSE', 'FOR', 'FROM',
20+
'GROUP', 'HAVING', 'IF', 'IN', 'INSERT', 'INTERVAL', 'INTO', 'IS',
21+
'JOIN', 'KEY', 'KEYS', 'LEFT', 'LIKE', 'LIMIT', 'MATCH', 'NOT',
22+
'ON', 'OPTION', 'OR', 'ORDER', 'OUT', 'OUTER', 'REPLACE', 'TINYINT',
23+
'RIGHT', 'SELECT', 'SET', 'TABLE', 'THEN', 'TO', 'TRUE', 'UPDATE',
24+
'VALUES', 'WHEN', 'WHERE', 'UNSIGNED', 'CASCADE', 'UNIQUE', 'DEFAULT',
25+
'ENGINE', 'TEXT', 'auto_increment', 'SHOW', 'INDEX'
26+
]
27+
let keywordsLower = keywordsUpper.map(value => value.toLowerCase())
28+
const keywords = [].concat(keywordsUpper, keywordsLower)
29+
30+
const clearStyle = '\x1b[0m'
31+
32+
module.exports = class Highlighter {
33+
constructor (_options) {
34+
this.options = Object.assign({}, defaultOptions, _options)
35+
36+
this.unicodePattern = `{0}$1${clearStyle}`
37+
this.htmlPattern = `<span class="${this.options.classPrefix}{0}">$1</span>`
38+
}
39+
40+
highlight (text) {
41+
let newText = text
42+
43+
let rules = {
44+
special: /(=|%|\/|\*|-|,|;|:|\+|<|>)/g,
45+
function: {
46+
match: /(\w*?)\(/g,
47+
pattern: '{0}('
48+
},
49+
number: /(\d+)/g,
50+
string: /(['`].*?['`])/g,
51+
bracket: /([()])/g
52+
}
53+
54+
// Remove 'Executing (default):' message
55+
newText = newText.replace(/Executing \(default\): /g, '')
56+
57+
for (let key in rules) {
58+
let rule = rules[key]
59+
let match = rule
60+
let pattern = '{0}'
61+
62+
if (typeof rule === 'function') {
63+
match = rule.match
64+
pattern = rule.pattern
65+
}
66+
67+
let replacer
68+
69+
if (!this.options.html) {
70+
replacer = this.unicodePattern.replace('{0}', this.options.colors[key])
71+
} else {
72+
replacer = this.htmlPattern.replace('{0}', key)
73+
}
74+
newText = newText.replace(match, pattern.replace('{0}', replacer))
75+
console.log(newText + '\n\n')
76+
}
77+
78+
let replacer = !this.options.html
79+
? this.unicodePattern.replace('{0}', this.options.colors.keyword)
80+
: this.htmlPattern.replace('{0}', 'keyword')
81+
82+
// Keywords
83+
for (let i = 0; i < keywords.length; i++) {
84+
let regEx = new RegExp(`\\b(${keywords[i]})\\b`, 'g')
85+
newText = newText.replace(regEx, replacer)
86+
}
87+
88+
return newText
89+
}
90+
}

package.json

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
{
2+
"name": "seq-highlight",
3+
"version": "2.1.0",
4+
"description": "A simple and lightweight syntax highlighting library for SQL",
5+
"main": "index.js",
6+
"repository": {
7+
"type": "git",
8+
"url": "https://github.com/scriptcoded/sql-highlight.git"
9+
},
10+
"scripts": {
11+
"test": "echo \"Error: no test specified\" && exit 1"
12+
},
13+
"keywords": [
14+
"sql",
15+
"syntax",
16+
"highlight",
17+
"highlighter"
18+
],
19+
"author": "Malcolm Nihlén <[email protected]>",
20+
"contributors": [
21+
"pomahtuk"
22+
],
23+
"license": "MIT"
24+
}

screenshot1.png

3.88 KB
Loading

test/index.js

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,12 @@
1+
/**
2+
* This is by no means a real unit test or anything like
3+
* that. It's just to see that it's working in the console.
4+
*/
5+
6+
const Highlighter = require('../index')
7+
8+
const highlighter = new Highlighter({
9+
html: true
10+
})
11+
12+
console.log(highlighter.highlight("SELECT `id`, `username` FROM `users` WHERE `email` = '[email protected]'"))

0 commit comments

Comments
 (0)