// Copyright 2023 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 functions import ( "math" "github.com/cockroachdb/apd/v3" "github.com/dolthub/go-mysql-server/sql" "github.com/dolthub/doltgresql/server/functions/framework" pgtypes "github.com/dolthub/doltgresql/server/types" ) // initRound registers the functions to the catalog. func initRound() { framework.RegisterFunction(round_float64) framework.RegisterFunction(round_numeric) framework.RegisterFunction(round_numeric_int64) } // round_float64 represents the PostgreSQL function of the same name, taking the same parameters. var round_float64 = framework.Function1{ Name: "round", Return: pgtypes.Float64, Parameters: [1]*pgtypes.DoltgresType{pgtypes.Float64}, Strict: true, Callable: func(ctx *sql.Context, _ [2]*pgtypes.DoltgresType, val any) (any, error) { return math.RoundToEven(val.(float64)), nil }, } // round_numeric represents the PostgreSQL function of the same name, taking the same parameters. var round_numeric = framework.Function1{ Name: "round", Return: pgtypes.Numeric, Parameters: [1]*pgtypes.DoltgresType{pgtypes.Numeric}, Strict: true, Callable: func(ctx *sql.Context, _ [2]*pgtypes.DoltgresType, val any) (any, error) { dec := val.(*apd.Decimal) p := dec.NumDigits() if dec.Exponent > 0 { p += int64(dec.Exponent) } res := new(apd.Decimal) _, err := sql.DecimalCtx.WithPrecision(uint32(p)).Round(res, dec) if err != nil { return nil, err } return sql.DecimalRound(res, 0) }, } // round_numeric_int64 represents the PostgreSQL function of the same name, taking the same parameters. var round_numeric_int64 = framework.Function2{ Name: "round", Return: pgtypes.Numeric, Parameters: [2]*pgtypes.DoltgresType{pgtypes.Numeric, pgtypes.Int64}, Strict: true, Callable: func(ctx *sql.Context, _ [3]*pgtypes.DoltgresType, val1 any, val2 any) (any, error) { dec := val1.(*apd.Decimal) places := val2.(int64) p := dec.NumDigits() if dec.Exponent > 0 { p += int64(dec.Exponent) } res := new(apd.Decimal) _, err := sql.DecimalCtx.WithPrecision(uint32(p)).Round(res, dec) if err != nil { return nil, err } return sql.DecimalRound(res, int32(places)) }, }