Database integration

Guarded inventory update

Update only a row with enough stock; inspect the affected row count. Actual database execution NOT RUN.

Formal Syntax & Structure

java syntaxjava
UPDATE catalog_item SET stock = stock - ? WHERE sku = ? AND stock >= ?

Working Example

Example Snippetjava
import java.sql.*;import java.util.*;import javax.sql.DataSource;
public final class Catalog {    private final DataSource source;    public Catalog(DataSource source) { this.source = Objects.requireNonNull(source); }    public record Item(String sku, int stock) {}
    public Optional<Item> find(String sku) throws SQLException {        try (Connection c = source.getConnection();             PreparedStatement p = c.prepareStatement(                 "SELECT sku, stock FROM catalog_item WHERE sku = ?")) {            p.setString(1, Objects.requireNonNull(sku));            try (ResultSet r = p.executeQuery()) {                return r.next() ? Optional.of(new Item(r.getString("sku"),                        r.getInt("stock"))) : Optional.empty();            }        }    }
    public long add(String sku, int stock) throws SQLException {        if (stock < 0) throw new IllegalArgumentException("negative stock");        try (Connection c = source.getConnection();             PreparedStatement p = c.prepareStatement(                 "INSERT INTO catalog_item(sku, stock) VALUES (?, ?)",                 Statement.RETURN_GENERATED_KEYS)) {            p.setString(1, Objects.requireNonNull(sku));            p.setInt(2, stock);            if (p.executeUpdate() != 1) throw new SQLException("insert count");            try (ResultSet keys = p.getGeneratedKeys()) {                if (!keys.next()) throw new SQLException("missing generated key");                return keys.getLong(1);            }        }    }
    public void reserve(String sku, int quantity) throws SQLException {        if (quantity <= 0) throw new IllegalArgumentException("positive quantity required");        Objects.requireNonNull(sku);        try (Connection c = source.getConnection()) {            Tx.run(c, () -> {                try (PreparedStatement p = c.prepareStatement(                         "UPDATE catalog_item SET stock = stock - ? WHERE sku = ? AND stock >= ?")) {                    p.setInt(1, quantity);                    p.setString(2, sku);                    p.setInt(3, quantity);                    if (p.executeUpdate() != 1) throw new SQLException("missing item or insufficient stock");                }                try (PreparedStatement p = c.prepareStatement(                         "INSERT INTO reservation(sku, quantity) VALUES (?, ?)")) {                    p.setString(1, sku);                    p.setInt(2, quantity);                    if (p.executeUpdate() != 1) throw new SQLException("reservation count");                }            });        }    }}
Java Reference