Skip to content

Commit 1057d70

Browse files
committed
support double quoted strings and quote escaping
1 parent e62fc8b commit 1057d70

File tree

4 files changed

+33
-6
lines changed

4 files changed

+33
-6
lines changed

lib/grammar.coffee

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -128,7 +128,8 @@ grammar =
128128
]
129129

130130
String: [
131-
o 'STRING', -> new StringValue($1)
131+
o 'STRING', -> new StringValue($1, "'")
132+
o 'DBLSTRING', -> new StringValue($1, '"')
132133
]
133134

134135
Literal: [

lib/lexer.coffee

Lines changed: 8 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -85,8 +85,12 @@ class Lexer
8585
seperatorToken: -> @tokenizeFromRegex('SEPARATOR', SEPARATOR)
8686
literalToken: -> @tokenizeFromRegex('LITERAL', LITERAL, 1, 0)
8787
numberToken: -> @tokenizeFromRegex('NUMBER', NUMBER)
88-
stringToken: -> @tokenizeFromRegex('STRING', STRING, 1, 0)
89-
parensToken: ->
88+
stringToken: ->
89+
@tokenizeFromRegex('STRING', STRING, 1, 0) ||
90+
@tokenizeFromRegex('DBLSTRING', DBLSTRING, 1, 0)
91+
92+
93+
parensToken: ->
9094
@tokenizeFromRegex('LEFT_PAREN', /^\(/,) or
9195
@tokenizeFromRegex('RIGHT_PAREN', /^\)/,)
9296

@@ -121,7 +125,8 @@ class Lexer
121125
WHITESPACE = /^[ \n\r]+/
122126
LITERAL = /^`?([a-z_][a-z0-9_]{0,})`?/i
123127
NUMBER = /^[0-9]+(\.[0-9]+)?/
124-
STRING = /^'(.*?)'/
128+
STRING = /^'([^\\']*(?:\\.[^\\']*)*)'/
129+
DBLSTRING = /^"([^\\"]*(?:\\.[^\\"]*)*)"/
125130

126131

127132

lib/nodes.coffee

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -46,8 +46,8 @@ exports.LiteralValue = class LiteralValue
4646
toString: -> "`#{@values.join('.')}`"
4747

4848
exports.StringValue = class StringValue
49-
constructor: (@value) -> null
50-
toString: -> "'#{@value}'"
49+
constructor: (@value, @quoteType="''") -> null
50+
toString: -> "#{@quoteType}#{@value}#{@quoteType}"
5151

5252
exports.NumberValue = class LiteralValue
5353
constructor: (value) -> @value = Number(value)

test/grammar.spec.coffee

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -186,3 +186,24 @@ describe "SQL Grammer", ->
186186
JOIN `c`
187187
ON (`a.id` = `c.id`)
188188
"""
189+
190+
it "doesn't choke on escaped quotes", ->
191+
parse("select * from a where foo = 'I\\'m'").toString().should.eql """
192+
SELECT *
193+
FROM `a`
194+
WHERE (`foo` = 'I\\'m')
195+
"""
196+
197+
it "allows using double quotes", ->
198+
parse('select * from a where foo = "a"').toString().should.eql """
199+
SELECT *
200+
FROM `a`
201+
WHERE (`foo` = "a")
202+
"""
203+
204+
it "allows nesting different quote styles", ->
205+
parse("""select * from a where foo = "I'm" """).toString().should.eql """
206+
SELECT *
207+
FROM `a`
208+
WHERE (`foo` = "I'm")
209+
"""

0 commit comments

Comments
 (0)