advsql/create_table.go

97 lines
1.8 KiB
Go
Raw Normal View History

package advsql
import (
"log"
"reflect"
"strings"
)
func (s *Store) createTable(structure *structure) error {
b := new(strings.Builder)
b.WriteString("CREATE TABLE ")
b.WriteString(structure.TypeName)
b.WriteString("(")
fieldAmount := len(structure.Fields)
for i, field := range structure.Fields {
b.WriteString(field.FieldName)
b.WriteString(" ")
b.WriteString(getTypeSpecForDB(field.FieldType))
if i < fieldAmount-1 {
b.WriteString(",")
}
}
b.WriteString(")")
log.Println("sql command: " + b.String())
_, err := s.db.Exec(b.String())
if err != nil {
return err
}
return nil
}
func getTypeSpecForDB(t reflect.Type) string {
noPtrType := t
dereferenced := false
// derefence all pointers recursively
for noPtrType.Kind() == reflect.Ptr {
noPtrType = t.Elem()
dereferenced = true
}
// actual data types
b := new(strings.Builder)
switch noPtrType.Kind() {
case reflect.Bool:
b.WriteString("INT")
case reflect.Int:
b.WriteString("BIGINT")
case reflect.Int8:
b.WriteString("TINYINT")
case reflect.Int16:
b.WriteString("SMALLINT")
case reflect.Int32:
b.WriteString("INT")
case reflect.Int64:
b.WriteString("BIGINT")
case reflect.Uint:
b.WriteString("BIGINT UNSIGNED")
case reflect.Uint8:
b.WriteString("TINYINT UNSIGNED")
case reflect.Uint16:
b.WriteString("SMALLINT UNSIGNED")
case reflect.Uint32:
b.WriteString("INT UNSIGNED")
case reflect.Uint64:
b.WriteString("BIGINT UNSIGNED")
case reflect.Float32:
b.WriteString("FLOAT")
case reflect.Float64:
b.WriteString("DOUBLE")
case reflect.String:
b.WriteString("TEXT")
case reflect.Ptr:
panic("something's broken. All pointers should have been dereferenced by now")
default:
panic("type spec for db not implemented yet: " + noPtrType.Kind().String())
}
if !dereferenced {
b.WriteString(" NOT NULL")
}
return b.String()
}