Skip to content

Is there any way to emulate UNNEST? #362

Answered by houten11
maxguuse asked this question in Q&A
Discussion options

You must be logged in to vote

You can't use []string as a parameter, you'll need to use string array that knows how to serialize to Postgres array type. For instance pq.StringArray

err := table.PollOptions.INSERT(
	table.PollOptions.Title,
	table.PollOptions.PollID,
).VALUES(
	postgres.Raw("UNNEST($1::varchar[]", map[string]any{
		"$1": pq.StringArray(pollOptions),
	}),
	pollID,
).RETURNING(
	table.PollOptions.AllColumns,
).QueryContext(ctx, db, dest)

Additionaly, you can define UNNEST function:

func UNNEST(arr []string) Expression {
	return Func("UNNEST", Raw("#1::varchar[]", map[string]any{
		"#1": pq.StringArray(arr),
	}))
}

and then write:

err := table.PollOptions.INSERT(
	table.PollOptions.Title,
	table.PollOptions.

Replies: 2 comments

Comment options

You must be logged in to vote
0 replies
Comment options

You must be logged in to vote
0 replies
Answer selected by maxguuse
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Category
Q&A
Labels
None yet
2 participants