tdb/constraint_notnull.go
2020-04-15 23:53:50 -05:00

53 lines
1.5 KiB
Go

package tdb
import (
"bytes"
"errors"
"fmt"
"git.keganmyers.com/terribleplan/tdb/stringy"
)
var nullishValues [][]byte = [][]byte{
[]byte(stringy.LiteralUintToString(uint64(0))),
[]byte(stringy.LiteralIntToString(int64(0))),
[]byte(""),
[]byte("nil"),
[]byte("<nil>"),
}
type notNullConstraint struct {
table *table
field dbField
}
func newNotNullConstraint(table *table, field dbField) (constraintish, error) {
if table == nil {
return nil, errors.New("[constraint.notnull] unable to create not-null without table")
}
return &notNullConstraint{
table: table,
field: field,
}, nil
}
func (c *notNullConstraint) validateRaw(tx *Tx, foreignKey []byte) error {
for _, nullishValue := range nullishValues {
if bytes.Equal(nullishValue, foreignKey) {
c.table.debugLogf("[constraint.notnull.validateRaw] violation: '%s'.'%s' is null-ish value '%s'", c.table.name, c.field.Name, nullishValue)
return fmt.Errorf("[constraint.notnull.validateRaw] violation: '%s'.'%s' is null-ish value '%s'", c.table.name, c.field.Name, nullishValue)
}
}
return nil
}
func (c *notNullConstraint) validate(tx *Tx, pv dbPtrValue) error {
c.table.debugLogf("[constraint.notnull.validate] validating not-null for '%s'.'%s'", c.table.name, c.field.Name)
if pv.dangerous_Field(c.field).IsZero() {
c.table.debugLogf("[constraint.notnull.validate] violation: '%s'.'%s' is zero value", c.table.name, c.field.Name)
return fmt.Errorf("[constraint.notnull.validate] violation: '%s'.'%s' is zero value", c.table.name, c.field.Name)
}
return nil
}