Skip to content

Use ON CONFLICT DO UPDATE instead of rewriting it manually #719

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

Closed
jyn514 opened this issue Apr 15, 2020 · 0 comments · Fixed by #744
Closed

Use ON CONFLICT DO UPDATE instead of rewriting it manually #719

jyn514 opened this issue Apr 15, 2020 · 0 comments · Fixed by #744
Labels
E-easy Effort: Should be easy to implement and would make a good first PR mentor This has instructions for getting started

Comments

@jyn514
Copy link
Member

jyn514 commented Apr 15, 2020

@pietroalbini pointed out in #643 (comment) that code that looks like

            // check if file already exists in database
            let rows = self
                .conn
                .query("SELECT COUNT(*) FROM files WHERE path = $1", &[&blob.path])?;

            if rows.get(0).get::<usize, i64>(0) == 0 {
                trans.query(
                    "INSERT INTO files (path, mime, content) VALUES ($1, $2, $3)",
                    &[&blob.path, &blob.mime, &blob.content],
                )?;
            } else {
                trans.query(
                    "UPDATE files SET mime = $2, content = $3, date_updated = NOW() \
                                WHERE path = $1",
                    &[&blob.path, &blob.mime, &blob.content],
                )?;
            }

can be simplified to

            trans.query(
                "INSERT INTO files (path, mime, content)
                 VALUES ($1, $2, $3)
                 ON CONFLICT (path) DO UPDATE
                    SET mime = EXCLUDED.mime, content = EXCLUDED.content",
                &[&blob.path, &blob.mime, &blob.content],
            )?;

It would be great to do this for other similar patterns in docs.rs:

@jyn514 jyn514 added mentor This has instructions for getting started E-easy Effort: Should be easy to implement and would make a good first PR labels Apr 15, 2020
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
E-easy Effort: Should be easy to implement and would make a good first PR mentor This has instructions for getting started
Projects
None yet
Development

Successfully merging a pull request may close this issue.

1 participant