Skip to content

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

Closed
@jyn514

Description

@jyn514

@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:

Metadata

Metadata

Assignees

No one assigned

    Labels

    E-easyEffort: Should be easy to implement and would make a good first PRmentorThis has instructions for getting started

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions