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

Add upsert support #26

Merged
merged 1 commit into from
Nov 14, 2024
Merged

Add upsert support #26

merged 1 commit into from
Nov 14, 2024

Conversation

piercefreeman
Copy link
Owner

@piercefreeman piercefreeman commented Nov 14, 2024

In Postgres, an upsert is just a special case of INSERT with the extended ON CONFLICT flags. While we could override our connection.insert method to support this case, it overly complicates the API contract for a case that is pretty disjoint in practical usage. This PR adds new explicit logic to insert a batch of objects and optionally return fields:

    await db_connection.conn.execute(
        """
        ALTER TABLE userdemo
        ADD CONSTRAINT email_unique UNIQUE (name, email)
        """
    )

    users = [
        UserDemo(name="John Doe", email="[email protected]"),
        UserDemo(name="John Doe", email="[email protected]"),
        UserDemo(name="Jane Doe", email="[email protected]"),
    ]
    result = await db_connection.upsert(
        users,
        conflict_fields=(UserDemo.name, UserDemo.email),
        returning_fields=(UserDemo.name, UserDemo.email),
    )

    assert result is not None
    assert len(result) == 2
    assert {r[1] for r in result} == {"[email protected]", "[email protected]"}

@piercefreeman piercefreeman merged commit cf4d011 into main Nov 14, 2024
5 checks passed
@piercefreeman piercefreeman deleted the feature/add-upsert branch November 14, 2024 05:18
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

1 participant