Sobes.tech
Senior

Tell me about locks in Postgres.

sobes.tech AI

Answer from AI

In PostgreSQL, locks are used to ensure data integrity and consistency when multiple transactions access the database concurrently.

Main types of locks:

  • Row-level locks — applied to specific rows in a table, allowing other transactions to work with different rows without conflicts. For example, SELECT ... FOR UPDATE places an exclusive lock on selected rows.

  • Table-level locks — lock the entire table for certain operations. For example, LOCK TABLE explicitly locks a table.

  • Advisory locks — user-defined locks that do not affect the database engine's operation but are used for synchronization at the application level.

PostgreSQL uses a multi-level locking system with different modes (AccessShareLock, RowExclusiveLock, etc.), which are compatible or conflict with each other.

Example in Go using database/sql:

import (
    "database/sql"
    _ "github.com/lib/pq"
    "log"
)

func lockRow(db *sql.DB, id int) error {
    tx, err := db.Begin()
    if err != nil {
        return err
    }
    defer tx.Rollback()

    // Lock the row with the specified id for update
    row := tx.QueryRow("SELECT * FROM users WHERE id=$1 FOR UPDATE", id)
    // process row...

    return tx.Commit()
}

It is important to understand that improper use of locks can lead to deadlocks and reduced performance, so transaction logic should be carefully designed.

Tell me about locks in Postgres. — Golang - sobes.tech