DEV Community

Discussion on: Why does PostgreSQL have pg_locks

 
rhymes profile image
rhymes

Ok, got it. It's a list of all the locks held by various connections

Thread Thread
 
j0nimost profile image
John Nyingi

So, they lock requests to the DB? I thought a good practice would to return an error instead of locking requests.

Thread Thread
 
rhymes profile image
rhymes • Edited

Oh, sorry my bad, I thought you wanted to understand the purpose of the view pg_locks, which is the name of a special view where PostgreSQL lists all the active locks (a locked table, or a row or others). Instead I think that you're actually asking what locks are for.

I thought a good practice would to return an error instead of locking requests.

It depends. If every concurrent operation would result in an error sent to the caller, those database would quickly become a single user and single process server.

Not very unlike locks in multithreading, database locks serve the purpose of protecting access to shared resources (tables, rows, data).

In a system where tens if not hundreds of connections operate on the same dataset, there has to be a system to avoid that two connections invalidate each other's operation (or in other cases causing a deadlock). Most RDBMS system promise you they are ACID, which means atomic, consistent, isolated and durable.

Locks are a way to do that. An operation comes to the DB, declares they need a resource, finishes its own modification, then releases such resource, so that the next operation can do the same. If they didn't lock their resource two operations might overwrite each other's data causing disasters.

Locks are not errors, they are handled automatically by the DB, unless you're doing something that abuses resources so you need to monitor the pg_locks table and understand what you're doing wrong.

Lock problems are not uncommon, but they are not that easy to trigger either.

Thread Thread
 
j0nimost profile image
John Nyingi

Wow thank you.