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

How does this work for bulk operations? #216

Closed
matheuscscp opened this issue Dec 25, 2019 · 5 comments
Closed

How does this work for bulk operations? #216

matheuscscp opened this issue Dec 25, 2019 · 5 comments
Labels
duplicate This issue or pull request already exists

Comments

@matheuscscp
Copy link

Imagine my program receives a list of Book unique keys, and it needs to return the list of these Books. The query would be something like this:

SELECT * FROM books WHERE key IN ('key1', ..., 'keyN');

How would I use sqlc for that?

@kyleconroy kyleconroy added the duplicate This issue or pull request already exists label Dec 25, 2019
@kyleconroy
Copy link
Collaborator

kyleconroy commented Dec 25, 2019

You're in luck! sqlc already supports this using ANY. The following SQL:

-- name: GetBulkBooks :many
SELECT * FROM books
WHERE key = ANY($1::text[]);

generate this method signature

func (q *Queries) GetBulkBooks(ctx context.Context, keys []string) ([]Book, error) {
  ...
}

Duplicate of #167

@matheuscscp
Copy link
Author

Sorry for not being specific enough: What about bulk inserts?

@kyleconroy
Copy link
Collaborator

There are a few ways to do bulk inserts in Go. This article from 2017 goes into two approaches. The first approach, insering multiple records inside a transaction, can be used today with sqlc.

-- name: InsertBook :exec
INSERT INTO books (key, title) VALUES ($1, $2)

However, this isn't really a true bulk insert. You can insert multiple records in a single query:

-- name: BulkInsert :exec
INSERT INTO books (key, title) VALUES
    ($1, $2),
    ($3, $4),
    ($5, $6)

This approach can't support a dynamic number of records.

The suggested approach is to use COPY (see this excellent StackOverflow answer). lib/pq has special support for this use case. I've opened up #218 for the feature.

@BienTrinh
Copy link

It does not work on MySQL. My table and schema below:
schema:
CREATE TABLE pkg (
id text NOT NULL,
vic VARCHAR(50) NOT NULL,
kim text NOT NULL,
order INTEGER NOT NULL,
PRIMARY KEY (id)
);
/* name: GetPkgID :many */
SELECT id,vic,kim FROM pkg WHERE vic = ANY($1::int[]) AND shop_id = ?;

sqlc generate
sql/query/pkg.sql:2:67: syntax error at or near "$"
sql/query/pkg.sql:2:76: syntax error at or near "]"

@kyleconroy
Copy link
Collaborator

MySQL does not support arrays so it's not expected for this to work. I've opened #695 to track this issue.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
duplicate This issue or pull request already exists
Projects
None yet
Development

No branches or pull requests

3 participants