Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

spanner: support scanning into slice of structs []Entry #11090

Open
egonelbre opened this issue Nov 6, 2024 · 0 comments
Open

spanner: support scanning into slice of structs []Entry #11090

egonelbre opened this issue Nov 6, 2024 · 0 comments
Assignees
Labels
api: spanner Issues related to the Spanner API. triage me I really want to be triaged.

Comments

@egonelbre
Copy link
Contributor

egonelbre commented Nov 6, 2024

Is your feature request related to a problem? Please describe.

Currently it's possibly to scan into a slice of pointers to structs, however not to a slice of structs:

client, err := spanner.NewClient(ctx, "projects/"+ProjectID+"/instances/"+InstanceID+"/databases/"+DatabaseName)
if err != nil {
	panic(err)
}
defer client.Close()

type Entry struct {
	Name  string
	Value int64
}

input := []Entry{
	{Name: "Hello", Value: 1000},
	{Name: "World", Value: 2000},
}

rows := client.ReadOnlyTransaction().Query(ctx, spanner.Statement{
	SQL: `SELECT ARRAY(SELECT AS STRUCT Name, Value FROM UNNEST(@input)) AS entries`,
	Params: map[string]any{
		"input": input,
	},
})
err = rows.Do(func(row *spanner.Row) error {
	var output []Entry
	if err := row.Columns(&output); err != nil {
		return err
	}
	for _, entry := range output {
		fmt.Println(entry)
	}
	return nil
})
fmt.Fprintln(os.Stderr, err)

Fails with:

spanner: code = "InvalidArgument", desc = "failed to decode column 0, error = <the container is not a slice of struct pointers: spanner: code = \"InvalidArgument\", desc = \"type *[]main.Entry cannot be used for decoding ARRAY[STRUCT]\">"

Describe the solution you'd like

I would like that using the following would work:

	var output []Entry
	if err := row.Columns(&output); err != nil {
		fmt.Fprintln(os.Stderr, err)
	}

Describe alternatives you've considered

It is possible to use:

	var output []*Entry
	if err := row.Columns(&output); err != nil {
		fmt.Fprintln(os.Stderr, err)
	}

And then later copy all the scanned values to a []Entry afterwards, however it does add more unnecessary code and it might allocate more.

@egonelbre egonelbre added the triage me I really want to be triaged. label Nov 6, 2024
@product-auto-label product-auto-label bot added the api: spanner Issues related to the Spanner API. label Nov 6, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
api: spanner Issues related to the Spanner API. triage me I really want to be triaged.
Projects
None yet
Development

No branches or pull requests

2 participants