Kilitleri ve kilitlenmeleri anlama
PostgreSQL'deki farklı kilit türlerini ve kilitlenmeleri nasıl belirleyip önleyebileceğinizi öğrenin.
Kilitleri ve kilitlenmeleri anlama, CoddyKit'te ücretsiz bir PostgreSQL Performance & Query Optimization dersidir. Bu, 4 dersinin 1. dersidir. Aşağıdan dersin tamamını ücretsiz okuyabilir, sonra tarayıcıda yerleşik kod editörü ve 7/24 yapay zeka koçu ile uygulamalı olarak pratik yapabilirsin. Bu, PostgreSQL Performance & Query Optimization öğrenme yolunun bir parçasıdır ve ilerlemeniz web ve CoddyKit uygulaması arasında senkronize olur. PostgreSQL Performance & Query Optimization kursu toplamda 4 dersten oluşur.
Bu dersin bazı bölümleri henüz çevrilmemiş olup İngilizce olarak gösterilmektedir.
Welcome to Concurrency
When many users or applications access a database at the same time, it's called concurrency. PostgreSQL, like other databases, needs to manage these concurrent operations carefully.
Without proper management, multiple operations could try to modify the same data simultaneously, leading to inconsistencies or errors. This is where locks come in!
What are Database Locks?
A database lock is a mechanism that controls access to data by multiple transactions. It ensures that data remains consistent and prevents conflicts.
- Data Integrity: Guarantees that data is accurate and reliable.
- Consistency: Ensures that transactions see a consistent view of the database.
- Conflict Prevention: Stops different operations from corrupting data by trying to write to the same place at the same time.
PostgreSQL Lock Modes
PostgreSQL uses various lock modes to define the level of access transactions have to a particular resource. These modes determine compatibility: some allow shared access, while others are exclusive.
- ACCESS SHARE: Acquired by simple
SELECTstatements. Allows other transactions to also acquire ACCESS SHARE, ROW SHARE, etc. - ROW EXCLUSIVE: Acquired by
INSERT,UPDATE,DELETE. Allows concurrent reads but prevents other transactions from acquiring ROW EXCLUSIVE on the same row. - ACCESS EXCLUSIVE: The most restrictive lock. Acquired by
DROP TABLEorTRUNCATE. Prevents all other access to the table.
Implicit Locks in Action
Most of the time, PostgreSQL automatically acquires the necessary locks for you. These are called implicit locks.
For example:
- When you run a
SELECTquery, an ACCESS SHARE lock is acquired on the table. - When you run an
UPDATE,INSERT, orDELETEquery, a ROW EXCLUSIVE lock is acquired on the affected rows and a corresponding table-level lock.
This automatic locking ensures data consistency without you needing to explicitly manage it.
Explicit Table Locks
While implicit locks handle most cases, you can also acquire locks explicitly using the LOCK TABLE command. This is useful for specific scenarios where you need to control access more precisely.
You can specify the lock mode, like ACCESS EXCLUSIVE to block all other operations, or SHARE for concurrent index creation.
Demo: Locking a Table
Try running this example. It creates a simple table and then explicitly locks it in ACCESS EXCLUSIVE mode. While this lock is held (for the duration of the transaction), no other transaction can read or write to this table.
CREATE TABLE IF NOT EXISTS inventory (
item_id SERIAL PRIMARY KEY,
item_name VARCHAR(100),
quantity INT
);
TRUNCATE TABLE inventory;
INSERT INTO inventory (item_name, quantity) VALUES ('Widget A', 50);
-- This command acquires an ACCESS EXCLUSIVE lock on the 'inventory' table.
-- In a real scenario, this would block other operations until committed.
LOCK TABLE inventory IN ACCESS EXCLUSIVE MODE;
SELECT 'Table locked successfully!' AS status;
-- The lock is released when this script finishes (transaction commits).Explicit Row Locks: SELECT FOR UPDATE
For fine-grained control, you can lock specific rows using SELECT FOR UPDATE or SELECT FOR SHARE. This is crucial for preventing race conditions in application logic.
SELECT ... FOR UPDATE: Acquires a ROW EXCLUSIVE lock on selected rows. Other transactions can read but cannot update or lock these rows for update until your transaction commits.SELECT ... FOR SHARE: Acquires a ROW SHARE lock. Other transactions can also acquire ROW SHARE locks, but not ROW EXCLUSIVE.
Spotting Active Locks with pg_locks
To see what locks are currently active in your database, you can query the pg_locks system view. This view provides detailed information about each lock.
Key columns to look for:
pid: The process ID holding or waiting for the lock.locktype: Type of resource being locked (e.g., relation, transactionid).mode: The lock mode (e.g., ACCESS SHARE, ROW EXCLUSIVE).granted:tif the lock is held,fif waiting.
You can query it like this:
SELECT * FROM pg_locks WHERE NOT granted;Understanding Deadlocks
A deadlock occurs when two or more transactions are waiting for each other to release a resource, resulting in a standstill. Neither transaction can proceed.
PostgreSQL automatically detects deadlocks and aborts one of the transactions (the 'deadlock victim') to allow the other to complete. This usually results in an error message for the aborted transaction.
A Classic Deadlock Scenario
Imagine two transactions, T1 and T2, trying to update two rows, Row A and Row B:
- T1: Locks Row A, then tries to lock Row B.
- T2: Locks Row B, then tries to lock Row A.
At this point, T1 holds A and waits for B, while T2 holds B and waits for A. Neither can progress. PostgreSQL detects this cycle and terminates one transaction.
Lock Mode Check
Which lock mode is typically acquired by a simple SELECT statement?
Recap: Locks & Deadlocks
We've covered the essentials of database locks and deadlocks in PostgreSQL. Locks ensure data consistency and integrity in concurrent environments, operating through various lock modes.
Remember:
- PostgreSQL uses implicit and explicit locks.
pg_lockshelps monitor active locks.- Deadlocks occur when transactions wait for each other, and PostgreSQL detects and resolves them by aborting one transaction.
Understanding these concepts is key to building robust and performant applications!
Sıkça Sorulan Sorular
“Kilitleri ve kilitlenmeleri anlama” dersi ücretsiz mi?
Evet — “Kilitleri ve kilitlenmeleri anlama” dersin tüm metni burada web'de ücretsiz olarak okunabilir. Etkileşimli olarak pratik yapmak (yerleşik kod editörü ve 7/24 yapay zeka koçu) ve PostgreSQL Performance & Query Optimization kursunun geri kalanını açmak için CoddyKit PRO'ya yükselt. PostgreSQL Performance & Query Optimization kursu toplamda 4 dersten oluşur.
“Kilitleri ve kilitlenmeleri anlama” dersinde ne öğreneceğim?
PostgreSQL'deki farklı kilit türlerini ve kilitlenmeleri nasıl belirleyip önleyebileceğinizi öğrenin. PostgreSQL Performance & Query Optimization ile uygulamalı kodu tarayıcıda doğrudan çalıştırarak pratik yaparsın ve 7/24 yapay zeka koçu dersi çalışırken sorularını yanıtlar.
PostgreSQL Performance & Query Optimization öğrenmeye başlamak için deneyim gerekli mi?
Önceden deneyim gerekmez. CoddyKit'te PostgreSQL Performance & Query Optimization, başlangıçtan ileri seviyeye kadar yapılandırıldığı için buradan başlayabilir veya başından başlayıp kendi hızında ilerleme yapabilirsin. Bu, 4 dersinin 1. dersidir.
“Kilitleri ve kilitlenmeleri anlama” dersi ne kadar sürer?
Çoğu CoddyKit dersi yaklaşık 5–10 dakika sürer. Her biri kısa ve etkileşimli olduğu için sabit ilerleme yaparsın ve web ile uygulama arasında tam olarak bıraktığın yerden devam edebilirsin.
Bu PostgreSQL Performance & Query Optimization dersinde kod yazıp çalıştırabilir miyim?
Evet. Her PostgreSQL Performance & Query Optimization dersi yerleşik bir kod editörü içerir, bu sayede tarayıcıda gerçek kod yazıp çalıştırabilir ve anlık yapay zeka geri bildirimi alırsın — yerel kurulum gerekli değildir.
Bu kursun tüm dersleri
- Kilitleri ve kilitlenmeleri anlama
- Kilit Çekişmesini Belirleme ve Giderme
- Satır Düzeyi Kilitleme Stratejileri
- Uygulama Eşgüdümü için Danışma Kilitleri