Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
18 changes: 14 additions & 4 deletions index.js
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ const SPLIT_CHARS = '[^a-zA-Z_]'
const highlighters = [
{
name: 'keyword',
regex: new RegExp(`(?:^|${SPLIT_CHARS})(?:${keywords.join('|')})(?=${SPLIT_CHARS})`, 'g')
regex: new RegExp(`(?:^|${SPLIT_CHARS})(?:${keywords.join('|')})(?=${SPLIT_CHARS}|$)`, 'g')
},
{
name: 'special',
Expand Down Expand Up @@ -65,11 +65,21 @@ function highlight (sqlString, options) {

const sortedMatches = matches.slice().sort((a, b) => a.start - b.start)

// filter/exclude nested matches (matches within the last match)
let filteredMatches = []
let upperBound = 0
for (let i = 0; i < sortedMatches.length; i++) {
if (sortedMatches[i].start >= upperBound) {
filteredMatches.push(sortedMatches[i])
upperBound = sortedMatches[i].start + sortedMatches[i].length
}
}

let highlighted = ''

for (let i = 0; i < sortedMatches.length; i++) {
const match = sortedMatches[i]
const nextMatch = sortedMatches[i + 1]
for (let i = 0; i < filteredMatches.length; i++) {
const match = filteredMatches[i]
const nextMatch = filteredMatches[i + 1]

const stringMatch = sqlString.substr(match.start, match.length)

Expand Down
3 changes: 3 additions & 0 deletions test/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -8,3 +8,6 @@ const { highlight } = require('../index')
console.log(highlight("SELECT COUNT(id), COUNT(id), `id`, `username` FROM `users` WHERE `email` = 'test@example.com' AND `something` = 'oke' AND 1=1"))
console.log(highlight('SELECT "users".* FROM "users"'))
console.log(highlight(`select "users".* from "users" where ("username" = 'test' or "email" = 'test') and "is_admin" = true and "is_banned" = false limit 1`))

console.log(highlight("SELECT COUNT(id), COUNT(id), `id`, `username` FROM `users` WHERE `email` = 'test@example.com' AND `something` = 'oke-doke' AND true = true"))
console.log(highlight("SELECT COUNT(id), `id`, `username` FROM `users` WHERE `email` = 'test@example.com' AND (username in ( SELECT \"name\" from aTable)", {html: false} ))