Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 3 additions & 1 deletion server/analyzer/init.go
Original file line number Diff line number Diff line change
Expand Up @@ -48,14 +48,16 @@ const (
ruleId_ValidateCreateTable // validateCreateTable
ruleId_ValidateCreateSchema // validateCreateSchema
ruleId_ResolveAlterColumn // resolveAlterColumn
ruleId_ValidateCreateFunction
ruleId_ValidateCreateFunction // validateCreateFunction
ruleId_ResolveValuesTypes // resolveValuesTypes
)

// Init adds additional rules to the analyzer to handle Doltgres-specific functionality.
func Init() {
analyzer.AlwaysBeforeDefault = append(analyzer.AlwaysBeforeDefault,
analyzer.Rule{Id: ruleId_ResolveType, Apply: ResolveType},
analyzer.Rule{Id: ruleId_TypeSanitizer, Apply: TypeSanitizer},
analyzer.Rule{Id: ruleId_ResolveValuesTypes, Apply: ResolveValuesTypes},
analyzer.Rule{Id: ruleId_GenerateForeignKeyName, Apply: generateForeignKeyName},
analyzer.Rule{Id: ruleId_AddDomainConstraints, Apply: AddDomainConstraints},
analyzer.Rule{Id: ruleId_ValidateColumnDefaults, Apply: ValidateColumnDefaults},
Expand Down
178 changes: 178 additions & 0 deletions server/analyzer/resolve_values_types.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,178 @@
// Copyright 2026 Dolthub, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

package analyzer

import (
"github.com/cockroachdb/errors"
"github.com/dolthub/go-mysql-server/sql"
"github.com/dolthub/go-mysql-server/sql/analyzer"
"github.com/dolthub/go-mysql-server/sql/expression"
"github.com/dolthub/go-mysql-server/sql/plan"
"github.com/dolthub/go-mysql-server/sql/transform"

pgtransform "github.com/dolthub/doltgresql/server/transform"

pgexprs "github.com/dolthub/doltgresql/server/expression"
"github.com/dolthub/doltgresql/server/functions/framework"
pgtypes "github.com/dolthub/doltgresql/server/types"
)

// ResolveValuesTypes determines the common type for each column in a VALUES clause
// by examining all rows, following PostgreSQL's type resolution rules.
// This ensures VALUES(1),(2.01),(3) correctly infers numeric type, not integer.
func ResolveValuesTypes(ctx *sql.Context, a *analyzer.Analyzer, node sql.Node, scope *plan.Scope, selector analyzer.RuleSelector, qFlags *sql.QueryFlags) (sql.Node, transform.TreeIdentity, error) {
// Track which VDTs we transform so we can update GetField nodes
transformedVDTs := make(map[sql.TableId]sql.Schema)
// First we transform VDTs and record their new schemas
node, same, err := transform.NodeWithOpaque(node, func(n sql.Node) (sql.Node, transform.TreeIdentity, error) {
newNode, same, err := transformValuesNode(n)
if err != nil {
return nil, same, err
}
if !same {
if vdt, ok := newNode.(*plan.ValueDerivedTable); ok {
transformedVDTs[vdt.Id()] = vdt.Schema()
}
}
return newNode, same, err
})
if err != nil {
return nil, transform.SameTree, err
}

// Next we update all GetField expressions that refer to a transformed VDT
if len(transformedVDTs) > 0 {
node, _, err = pgtransform.NodeExprsWithOpaque(node, func(expr sql.Expression) (sql.Expression, transform.TreeIdentity, error) {
gf, ok := expr.(*expression.GetField)
if !ok {
return expr, transform.SameTree, nil
}
newSch, ok := transformedVDTs[gf.TableId()]
if !ok {
return expr, transform.SameTree, nil
}

// GetField indices are 1-based in GMS planbuilder, so subtract 1 for schema access
schemaIdx := gf.Index() - 1
if schemaIdx < 0 || schemaIdx >= len(newSch) {
return nil, transform.NewTree, errors.Newf("GetField `%s` on table `%s` uses invalid index `%d`",
gf.Name(), gf.Table(), gf.Index())
}

newType := newSch[schemaIdx].Type
if gf.Type() == newType {
return expr, transform.SameTree, nil
}

// Create a new expression with the updated type
newGf := expression.NewGetFieldWithTable(
gf.Index(),
int(gf.TableId()),
newType,
gf.Database(),
gf.Table(),
gf.Name(),
gf.IsNullable(),
)
return newGf, transform.NewTree, nil
})
if err != nil {
return nil, transform.SameTree, err
}
}

return node, same, nil
}

// transformValuesNode transforms a plan.Values or plan.ValueDerivedTable node to use common types
func transformValuesNode(n sql.Node) (sql.Node, transform.TreeIdentity, error) {
var values *plan.Values
var expressionerNode sql.Expressioner
switch v := n.(type) {
case *plan.ValueDerivedTable:
values = v.Values
expressionerNode = v
case *plan.Values:
values = v
expressionerNode = v
default:
return n, transform.SameTree, nil
}

// Skip if no rows or single row (nothing to unify)
if len(values.ExpressionTuples) <= 1 {
return n, transform.SameTree, nil
}
numCols := len(values.ExpressionTuples[0])
for i := 1; i < len(values.ExpressionTuples); i++ {
if len(values.ExpressionTuples[i]) != numCols {
return nil, transform.NewTree, errors.New("VALUES lists must all be the same length")
}
}
if numCols == 0 {
return n, transform.SameTree, nil
}

// Collect types for each column across all rows
columnTypes := make([][]*pgtypes.DoltgresType, numCols)
for colIdx := 0; colIdx < numCols; colIdx++ {
columnTypes[colIdx] = make([]*pgtypes.DoltgresType, len(values.ExpressionTuples))
for rowIdx, row := range values.ExpressionTuples {
exprType := row[colIdx].Type()
if exprType == nil {
columnTypes[colIdx][rowIdx] = pgtypes.Unknown
} else if pgType, ok := exprType.(*pgtypes.DoltgresType); ok {
columnTypes[colIdx][rowIdx] = pgType
} else {
return n, transform.NewTree, errors.New("VALUES cannot use GMS types")

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@Hydrocharged did mean to do nil for this sql.Node return given we are returning an error here?

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It doesn't make too big of a difference. For the sake of consistency we usually return nil, but we don't check the node itself (it's ignored) if an error is returned.

}
}
}

// Find common type for each column
var newTuples [][]sql.Expression
for colIdx := 0; colIdx < numCols; colIdx++ {
commonType, requiresCasts, err := framework.FindCommonType(columnTypes[colIdx])
if err != nil {
return nil, transform.NewTree, err
}
// If we require any casts, then we'll add casting to all expressions in the list
if requiresCasts {
if len(newTuples) == 0 {
newTuples = make([][]sql.Expression, len(values.ExpressionTuples))
copy(newTuples, values.ExpressionTuples)
}
for rowIdx := 0; rowIdx < len(newTuples); rowIdx++ {
newTuples[rowIdx][colIdx] = pgexprs.NewImplicitCast(
newTuples[rowIdx][colIdx], columnTypes[colIdx][rowIdx], commonType)
}
}
}
// If we didn't require any casts, then we can simply return our old node
if len(newTuples) == 0 {
return n, transform.SameTree, nil
}

// Flatten the new tuples into a single expression slice for WithExpressions
var flatExprs []sql.Expression
for _, row := range newTuples {
flatExprs = append(flatExprs, row...)
}
newNode, err := expressionerNode.WithExpressions(flatExprs...)
if err != nil {
return nil, transform.NewTree, err
}
return newNode, transform.NewTree, nil
}
8 changes: 2 additions & 6 deletions server/expression/array.go
Original file line number Diff line number Diff line change
Expand Up @@ -82,11 +82,7 @@ func (array *Array) Eval(ctx *sql.Context, row sql.Row) (any, error) {
// We always cast the element, as there may be parameter restrictions in place
castFunc := framework.GetImplicitCast(doltgresType, resultTyp)
if castFunc == nil {
if doltgresType.ID == pgtypes.Unknown.ID {
castFunc = framework.UnknownLiteralCast
} else {
return nil, errors.Errorf("cannot find cast function from %s to %s", doltgresType.String(), resultTyp.String())
}
return nil, errors.Errorf("cannot find cast function from %s to %s", doltgresType.String(), resultTyp.String())
}

values[i], err = castFunc(ctx, val, resultTyp)
Expand Down Expand Up @@ -175,7 +171,7 @@ func (array *Array) getTargetType(children ...sql.Expression) (*pgtypes.Doltgres
childrenTypes = append(childrenTypes, childType)
}
}
targetType, err := framework.FindCommonType(childrenTypes)
targetType, _, err := framework.FindCommonType(childrenTypes)
if err != nil {
return nil, errors.Errorf("ARRAY %s", err.Error())
}
Expand Down
8 changes: 2 additions & 6 deletions server/expression/assignment_cast.go
Original file line number Diff line number Diff line change
Expand Up @@ -56,12 +56,8 @@ func (ac *AssignmentCast) Eval(ctx *sql.Context, row sql.Row) (any, error) {
}
castFunc := framework.GetAssignmentCast(ac.fromType, ac.toType)
if castFunc == nil {
if ac.fromType.ID == pgtypes.Unknown.ID {
castFunc = framework.UnknownLiteralCast
} else {
return nil, errors.Errorf("ASSIGNMENT_CAST: target is of type %s but expression is of type %s: %s",
ac.toType.String(), ac.fromType.String(), ac.expr.String())
}
return nil, errors.Errorf("ASSIGNMENT_CAST: target is of type %s but expression is of type %s: %s",
ac.toType.String(), ac.fromType.String(), ac.expr.String())
}
return castFunc(ctx, val, ac.toType)
}
Expand Down
4 changes: 1 addition & 3 deletions server/expression/explicit_cast.go
Original file line number Diff line number Diff line change
Expand Up @@ -97,9 +97,7 @@ func (c *ExplicitCast) Eval(ctx *sql.Context, row sql.Row) (any, error) {
baseCastToType := checkForDomainType(c.castToType)
castFunction := framework.GetExplicitCast(fromType, baseCastToType)
if castFunction == nil {
if fromType.ID == pgtypes.Unknown.ID {
castFunction = framework.UnknownLiteralCast
} else if fromType.IsRecordType() && c.castToType.IsCompositeType() { // TODO: should this only be in explicit, or assignment and implicit too?
if fromType.IsRecordType() && c.castToType.IsCompositeType() { // TODO: should this only be in explicit, or assignment and implicit too?
// Casting to a record type will always work for any composite type.
// TODO: is the above statement true for all cases?
// When casting to a composite type, then we must match the arity and have valid casts for every position.
Expand Down
12 changes: 12 additions & 0 deletions server/functions/framework/cast.go
Original file line number Diff line number Diff line change
Expand Up @@ -159,6 +159,10 @@ func GetExplicitCast(fromType *pgtypes.DoltgresType, toType *pgtypes.DoltgresTyp
return targetType.IoInput(ctx, str)
}
}
// It is always valid to convert from the `unknown` type
if fromType.ID == pgtypes.Unknown.ID {
return UnknownLiteralCast
}
return nil
}

Expand Down Expand Up @@ -187,6 +191,10 @@ func GetAssignmentCast(fromType *pgtypes.DoltgresType, toType *pgtypes.DoltgresT
return targetType.IoInput(ctx, str)
}
}
// It is always valid to convert from the `unknown` type
if fromType.ID == pgtypes.Unknown.ID {
return UnknownLiteralCast
}
return nil
}

Expand All @@ -200,6 +208,10 @@ func GetImplicitCast(fromType *pgtypes.DoltgresType, toType *pgtypes.DoltgresTyp
if cast := getSizingOrIdentityCast(fromType, toType, false); cast != nil {
return cast
}
// It is always valid to convert from the `unknown` type
if fromType.ID == pgtypes.Unknown.ID {
return UnknownLiteralCast
}
return nil
}

Expand Down
50 changes: 30 additions & 20 deletions server/functions/framework/common_type.go
Original file line number Diff line number Diff line change
Expand Up @@ -20,52 +20,62 @@ import (
pgtypes "github.com/dolthub/doltgresql/server/types"
)

// FindCommonType returns the common type that given types can convert to.
// FindCommonType returns the common type that given types can convert to. Returns false if no implicit casts are needed
// to resolve the given types as the returned common type.
// https://www.postgresql.org/docs/15/typeconv-union-case.html
func FindCommonType(types []*pgtypes.DoltgresType) (*pgtypes.DoltgresType, error) {
var candidateType = pgtypes.Unknown
var fail = false
func FindCommonType(types []*pgtypes.DoltgresType) (_ *pgtypes.DoltgresType, requiresCasts bool, err error) {
candidateType := pgtypes.Unknown
differentTypes := false
for _, typ := range types {
if typ.ID == candidateType.ID {
continue
} else if candidateType.ID == pgtypes.Unknown.ID {
candidateType = typ
} else {
candidateType = pgtypes.Unknown
fail = true
differentTypes = true
}
}
if !fail {
if !differentTypes {
if candidateType.ID == pgtypes.Unknown.ID {
return pgtypes.Text, nil
// We require implicit casts from `unknown` to `text`
return pgtypes.Text, true, nil
}
return candidateType, nil
return candidateType, false, nil
}
// We have different types if we've made it this far, so we're guaranteed to require implicit casts
requiresCasts = true
for _, typ := range types {
if candidateType.ID == pgtypes.Unknown.ID {
candidateType = typ
}
if typ.ID != pgtypes.Unknown.ID && candidateType.TypCategory != typ.TypCategory {
return nil, errors.Errorf("types %s and %s cannot be matched", candidateType.String(), typ.String())
return nil, false, errors.Errorf("types %s and %s cannot be matched", candidateType.String(), typ.String())
}
}

var preferredTypeFound = false
// Attempt to find the most general type (or the preferred type in the type category)
for _, typ := range types {
if typ.ID == pgtypes.Unknown.ID {
if typ.ID == pgtypes.Unknown.ID || typ.ID == candidateType.ID {
continue
} else if GetImplicitCast(typ, candidateType) != nil {
// typ can convert to the candidate type, so the candidate type is at least as general
continue
} else if GetImplicitCast(candidateType, typ) == nil {
return nil, errors.Errorf("cannot find implicit cast function from %s to %s", candidateType.String(), typ.String())
} else if !preferredTypeFound {
} else if GetImplicitCast(candidateType, typ) != nil {
// the candidate type can convert to typ, but not vice versa, so typ is likely more general
candidateType = typ
if candidateType.IsPreferred {
candidateType = typ
preferredTypeFound = true
// We stop considering more types once we've found a preferred type
break
}
} else {
return nil, errors.Errorf("found another preferred candidate type")
}
}
return candidateType, nil
// Verify that all types have an implicit conversion to the candidate type
for _, typ := range types {
if typ.ID == pgtypes.Unknown.ID || typ.ID == candidateType.ID {
continue
} else if GetImplicitCast(typ, candidateType) == nil {
return nil, false, errors.Errorf("cannot find implicit cast function from %s to %s", candidateType.String(), typ.String())
}
}
return candidateType, requiresCasts, nil
}
8 changes: 2 additions & 6 deletions server/functions/framework/compiled_function.go
Original file line number Diff line number Diff line change
Expand Up @@ -582,12 +582,8 @@ func (c *CompiledFunction) typeCompatibleOverloads(fnOverloads []Overload, argTy
polymorphicTargets = append(polymorphicTargets, argTypes[i])
} else {
if overloadCasts[i] = GetImplicitCast(argTypes[i], paramType); overloadCasts[i] == nil {
if argTypes[i].ID == pgtypes.Unknown.ID {
overloadCasts[i] = UnknownLiteralCast
} else {
isConvertible = false
break
}
isConvertible = false
break
}
}
}
Expand Down
Loading