2021-08-29 14:41:41 +00:00
|
|
|
package sqlitedialect
|
|
|
|
|
|
|
|
import (
|
|
|
|
"database/sql"
|
2021-10-24 11:14:37 +00:00
|
|
|
"encoding/hex"
|
2021-08-29 14:41:41 +00:00
|
|
|
|
|
|
|
"github.com/uptrace/bun/dialect"
|
|
|
|
"github.com/uptrace/bun/dialect/feature"
|
|
|
|
"github.com/uptrace/bun/dialect/sqltype"
|
|
|
|
"github.com/uptrace/bun/schema"
|
|
|
|
)
|
|
|
|
|
|
|
|
type Dialect struct {
|
2021-10-24 11:14:37 +00:00
|
|
|
schema.BaseDialect
|
|
|
|
|
2021-08-29 14:41:41 +00:00
|
|
|
tables *schema.Tables
|
|
|
|
features feature.Feature
|
|
|
|
}
|
|
|
|
|
|
|
|
func New() *Dialect {
|
|
|
|
d := new(Dialect)
|
|
|
|
d.tables = schema.NewTables(d)
|
2021-09-10 12:42:14 +00:00
|
|
|
d.features = feature.CTE |
|
|
|
|
feature.Returning |
|
|
|
|
feature.InsertTableAlias |
|
2021-11-27 14:26:58 +00:00
|
|
|
feature.DeleteTableAlias |
|
|
|
|
feature.InsertOnConflict
|
2021-08-29 14:41:41 +00:00
|
|
|
return d
|
|
|
|
}
|
|
|
|
|
|
|
|
func (d *Dialect) Init(*sql.DB) {}
|
|
|
|
|
|
|
|
func (d *Dialect) Name() dialect.Name {
|
|
|
|
return dialect.SQLite
|
|
|
|
}
|
|
|
|
|
|
|
|
func (d *Dialect) Features() feature.Feature {
|
|
|
|
return d.features
|
|
|
|
}
|
|
|
|
|
|
|
|
func (d *Dialect) Tables() *schema.Tables {
|
|
|
|
return d.tables
|
|
|
|
}
|
|
|
|
|
|
|
|
func (d *Dialect) OnTable(table *schema.Table) {
|
|
|
|
for _, field := range table.FieldMap {
|
|
|
|
d.onField(field)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
func (d *Dialect) onField(field *schema.Field) {
|
2021-10-24 11:14:37 +00:00
|
|
|
field.DiscoveredSQLType = fieldSQLType(field)
|
2021-08-29 14:41:41 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
func (d *Dialect) IdentQuote() byte {
|
|
|
|
return '"'
|
|
|
|
}
|
|
|
|
|
2021-10-24 11:14:37 +00:00
|
|
|
func (d *Dialect) AppendBytes(b []byte, bs []byte) []byte {
|
|
|
|
if bs == nil {
|
|
|
|
return dialect.AppendNull(b)
|
2021-08-29 14:41:41 +00:00
|
|
|
}
|
|
|
|
|
2021-10-24 11:14:37 +00:00
|
|
|
b = append(b, `X'`...)
|
2021-08-29 14:41:41 +00:00
|
|
|
|
2021-10-24 11:14:37 +00:00
|
|
|
s := len(b)
|
|
|
|
b = append(b, make([]byte, hex.EncodedLen(len(bs)))...)
|
|
|
|
hex.Encode(b[s:], bs)
|
2021-08-29 14:41:41 +00:00
|
|
|
|
2021-10-24 11:14:37 +00:00
|
|
|
b = append(b, '\'')
|
2021-08-29 14:41:41 +00:00
|
|
|
|
2021-10-24 11:14:37 +00:00
|
|
|
return b
|
|
|
|
}
|
2021-08-29 14:41:41 +00:00
|
|
|
|
2021-10-24 11:14:37 +00:00
|
|
|
func fieldSQLType(field *schema.Field) string {
|
|
|
|
switch field.DiscoveredSQLType {
|
|
|
|
case sqltype.SmallInt, sqltype.BigInt:
|
|
|
|
// INTEGER PRIMARY KEY is an alias for the ROWID.
|
|
|
|
// It is safe to convert all ints to INTEGER, because SQLite types don't have size.
|
|
|
|
return sqltype.Integer
|
|
|
|
default:
|
|
|
|
return field.DiscoveredSQLType
|
2021-08-29 14:41:41 +00:00
|
|
|
}
|
|
|
|
}
|