-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathts_type.go
84 lines (66 loc) · 1.71 KB
/
ts_type.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
package main
import (
"fmt"
"log"
"strings"
"github.com/stephen/sqlc-ts/internal/plugin"
"github.com/stephen/sqlc-ts/internal/sdk"
)
func tsTypecheckTemplate(req *plugin.CodeGenRequest, col *plugin.Column) string {
typ := sqliteType(req, col)
if typ == "unknown" {
return ""
}
cond := fmt.Sprintf(`typeof %% !== "%s"`, typ)
if !col.NotNull {
cond = fmt.Sprintf(`%s && %% !== null`, cond)
}
if col.IsArray {
cond = fmt.Sprintf(`!Array.isArray(%%) || %%.some(e => %s)`, strings.ReplaceAll(cond, "%%", "e"))
}
return cond
}
func tsType(req *plugin.CodeGenRequest, col *plugin.Column) string {
typ := sqliteType(req, col)
if typ == "unknown" {
return typ
}
if !col.NotNull {
typ = fmt.Sprintf("%s | null", typ)
}
if col.IsArray {
typ = fmt.Sprintf("%s[]", typ)
}
return typ
}
func sqliteType(req *plugin.CodeGenRequest, col *plugin.Column) string {
dt := strings.ToLower(sdk.DataType(col.Type))
switch dt {
case "int", "integer", "tinyint", "smallint", "mediumint", "bigint", "unsignedbigint", "int2", "int8", "numeric", "decimal", "real", "double", "doubleprecision", "float":
return "number"
case "blob":
return "Uint8Array"
case "boolean":
return "boolean"
case "date", "datetime", "timestamp":
return "Date"
case "any":
// XXX: is this right?
return "unknown"
}
switch {
case strings.HasPrefix(dt, "character"),
strings.HasPrefix(dt, "varchar"),
strings.HasPrefix(dt, "varyingcharacter"),
strings.HasPrefix(dt, "nchar"),
strings.HasPrefix(dt, "nativecharacter"),
strings.HasPrefix(dt, "nvarchar"),
dt == "text",
dt == "clob":
return "string"
default:
log.Printf("unknown SQLite type: %s\n", dt)
// XXX: is this right? or prefer any?
return "unknown"
}
}