Skip to content
Sarj Code Standards

store-field-update-reuses-upsert

Review per-field store setters beside the store's upsert command; a plain field UPDATE duplicates fields it already writes.

Why

Independent per-field SQL methods duplicate write policy and can drift from the existing model command's validation, conflict handling and timestamps.

Fix

Prefer one typed model command for ordinary writable fields. Reuse or extend its write implementation while preserving update-only, missing-row, omission/null, authorization and concurrency contracts; retain domain transitions as separate operations.

Examples

Before — flagged Review a separate guarded setter
app/item_store.py
from psycopg import AsyncCursor
class ItemStore:
def __init__(self, cursor: AsyncCursor):
self.cursor = cursor
async def upsert(self, item):
await self.cursor.execute(
"INSERT INTO item(id, name) VALUES(%s, %s) ON CONFLICT(id) DO UPDATE SET name=EXCLUDED.name",
(item.id, item.name),
)
async def set_name_before_start(self, key, name):
await self.cursor.execute(
"UPDATE item SET name=%s WHERE id=%s AND started_at IS NULL", (name, key)
)
After — preferred Different relation ownership is preserved
app/item_store.py
from psycopg import AsyncCursor
class ItemStore:
def __init__(self, cursor: AsyncCursor):
self.cursor = cursor
async def upsert(self, item):
await self.cursor.execute(
"INSERT INTO item(id, name) VALUES(%s, %s) ON CONFLICT(id) DO UPDATE SET name=EXCLUDED.name",
(item.id, item.name),
)
async def set_name_before_start(self, key, name):
await self.cursor.execute(
"UPDATE other SET name=%s WHERE id=%s AND started_at IS NULL", (name, key)
)
Before — flagged Consolidate an ordinary field write
app/user_store.py
from pydantic import BaseModel
class UserInput(BaseModel):
id: str
name: str
class UserStore:
async def upsert(self, data: UserInput) -> User:
await self.cursor.execute(
"INSERT INTO users (id, name) VALUES (%s, %s) ON CONFLICT (id) DO UPDATE SET name = EXCLUDED.name",
(data.id, data.name),
)
async def set_name(self, id_: str, name: str) -> User:
await self.cursor.execute(
"UPDATE users SET name = %s WHERE id = %s", (name, id_)
)
After — preferred Keep an update with a distinct concurrency contract
app/user_store.py
from pydantic import BaseModel
class UserInput(BaseModel):
id: str
name: str
class UserStore:
async def upsert(self, data: UserInput) -> User:
await self.cursor.execute(
"INSERT INTO users (id, name) VALUES (%s, %s) ON CONFLICT (id) DO UPDATE SET name = EXCLUDED.name",
(data.id, data.name),
)
async def set_name(self, id_: str, name: str, version: int) -> User:
await self.cursor.execute(
"UPDATE users SET name = %s WHERE id = %s AND version = %s",
(name, id_, version),
)

Formerly: store-mutation-command-fanout