Skip to content

Commit 2861faa

Browse files
EliSauderCopilot
andcommitted
fix(mssql): type an N'...' literal as nvarchar
A Unicode string literal was typed as a varchar, as any string literal is. N'...' is now an nvarchar as long as the string, as SQL Server types it. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
1 parent 2420922 commit 2861faa

5 files changed

Lines changed: 74 additions & 1 deletion

File tree

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
{
2+
"command": "analyze",
3+
"args": ["--dialect", "mssql", "--schema", "schema.sql", "query.sql"],
4+
"contexts": ["base"]
5+
}
Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
-- name: Literals :many
2+
SELECT N'hello' AS a1, N'' AS a2, 'hi' AS a3, a + N'xy' AS a4 FROM p WHERE a LIKE N'%x%' AND b = @b;
Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
CREATE TABLE p (a NVARCHAR(10) NOT NULL, b NVARCHAR(20) NOT NULL, c VARCHAR(5) NOT NULL, d DECIMAL(10,2) NOT NULL, e DECIMAL(5,3) NOT NULL, i INT NOT NULL);
Lines changed: 59 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,59 @@
1+
[
2+
{
3+
"name": "Literals",
4+
"cmd": ":many",
5+
"columns": [
6+
{
7+
"name": "a1",
8+
"type": {
9+
"name": "nvarchar",
10+
"args": [
11+
{
12+
"int": 5
13+
}
14+
]
15+
}
16+
},
17+
{
18+
"name": "a2",
19+
"type": {
20+
"name": "nvarchar",
21+
"args": [
22+
{
23+
"int": 1
24+
}
25+
]
26+
}
27+
},
28+
{
29+
"name": "a3",
30+
"type": {
31+
"name": "varchar"
32+
}
33+
},
34+
{
35+
"name": "a4",
36+
"type": {
37+
"name": "nvarchar"
38+
}
39+
}
40+
],
41+
"params": [
42+
{
43+
"number": 1,
44+
"column": {
45+
"name": "b",
46+
"type": {
47+
"name": "nvarchar",
48+
"args": [
49+
{
50+
"int": 20
51+
}
52+
]
53+
},
54+
"table": "p"
55+
}
56+
}
57+
]
58+
}
59+
]

‎internal/engine/mssql/convert.go‎

Lines changed: 7 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@ package mssql
33
import (
44
"strconv"
55
"strings"
6+
"unicode/utf16"
67

78
tsql "github.com/sqlc-dev/teesql/ast"
89

@@ -800,10 +801,15 @@ func (c *cc) convertScalarExpression(expr tsql.ScalarExpression) ast.Node {
800801
Location: c.loc(e),
801802
}
802803
case *tsql.StringLiteral:
803-
return &ast.A_Const{
804+
lit := &ast.A_Const{
804805
Val: &ast.String{Str: e.Value},
805806
Location: c.loc(e),
806807
}
808+
// N'...' is an nvarchar as long as the string, and at least 1.
809+
if e.IsNational {
810+
return &ast.TypeCast{Arg: lit, TypeName: typeName("nvarchar", max(1, int64(len(utf16.Encode([]rune(e.Value)))))), Location: c.loc(e)}
811+
}
812+
return lit
807813
case *tsql.NullLiteral:
808814
return &ast.A_Const{
809815
Val: &ast.Null{},

0 commit comments

Comments
 (0)