Skip to content

sum in select result in model field type interface{} #1901

Open

Description

@sosolyht

Version

1.14.0

What happened?

Hello, I found an error while using sqlc and mysql

return value must be int64

but it's an interface .

need cast to int64

const totalVAT = `-- name: TotalVAT :one
SELECT sum(vat) as vatpence
FROM sales
`

func (q *Queries) TotalVAT(ctx context.Context) (interface{}, error) {
	row := q.db.QueryRowContext(ctx, totalVAT)
	var vatpence interface{}
	err := row.Scan(&vatpence)
	return vatpence, err
}

Relevant log output

No response

Database schema

CREATE TABLE sales (
  vat integer      NOT NULL
);

SQL queries

-- name: TotalVAT :one
SELECT sum(vat) as vatpence
FROM sales;

Configuration

No response

Playground URL

https://play.sqlc.dev/p/6552b583f39af63c0d407f76b62cafdfe471b130c76d9066b9843b8c20b8cd90

What operating system are you using?

macOS

What database engines are you using?

MySQL

What type of code are you generating?

Go

Activity

  1. added
    bugSomething isn't working
    triageNew issues that hasn't been reviewed
    on Oct 17, 2022
  2. brlala commented on Oct 18, 2022

    @brlala

    use this as a workaround

    SELECT sum(vat) :: integer as vatpence
    FROM sales
    
  3. sosolyht commented on Oct 20, 2022

    @sosolyht
    Author

    @brlala thank you, but this solution does not work with mysql

  4. sosolyht commented on Oct 27, 2022

    @sosolyht
    Author
    func convertInterfaceToInt64(t interface{}) (int64, error) {
    	switch t := t.(type) {
    	case int64:
    		return t, nil
    	case int:
    		return int64(t), nil
    	case string:
    		return strconv.ParseInt(t, 10, 64)
    	case []byte:
    		return strconv.ParseInt(string(t), 10, 64)
    	default:
    		return 0, fmt.Errorf("type %T not supported", t)
    	}
    }

    query is return from interface to byte type

    so we can solve this problem

  5. abh commented on Dec 19, 2022

    @abh

    Related to #1622

  6. andrewmbenton commented on Jan 3, 2024

    @andrewmbenton
    Member

    use this as a workaround

    SELECT sum(vat) :: integer as vatpence
    FROM sales
    

    As noted, this workaround doesn't work for MySQL. The following does work though:

    SELECT CAST(sum(vat) AS unsigned) vatpence
    FROM sales;

    https://play.sqlc.dev/p/a046db4043e5fb11a9135f6632d96bcd4506c754e9bab06b1706ef06c5ea6dc9

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions