La descarga está en progreso. Por favor, espere

La descarga está en progreso. Por favor, espere

Principios de las Transacciones SQL

Presentaciones similares


Presentación del tema: "Principios de las Transacciones SQL"— Transcripción de la presentación:

1 Principios de las Transacciones SQL
Principios de las Transacciones SQL “Big Picture” para comprender COMMIT y ROLLBACK de transacciones SQL Fileros, Buffers, Listener, Hebras de Servicio, y Transacciones Databases provide the reliable storage and services for data of applications. However, these reliable services provided by DBMS products need to be met by well designed SQL transactions by the applications, which is a challenge to application developers. So, the SQL transactions are basic building blocks of reliable data access, units of data access work, recovery and concurrency. The ACID principle describes the ideal properties of a reliable SQL transaction, in which A stands for Atomicity of the transaction work, C for consistency, I for isolation, and D for durability of the data. The purpose of this presentation is to provide a basic level overview of the files, buffers, processes/threads, and functionalities of a database server for managing the Atomicity i.e. recoverability of data by ROLLBACK commands, and Durability of data acchieved by COMMIT commands. The concurrency control (CC) services provided by DBMS products and the Isolation property configuring the use of these services for the transaction will be covered in a separate presentation. Martti Laiho

2 Transacción SQL (Plana)
[BEGIN TRANSACTION] [SET TRANSACTION ISOLATION .. ] SELECT … INSERT … UPDATE … DELETE … COMMIT o ROLLBACK Base de Datos Log de Transacciones The basic SQL transaction model of ISO SQL standard is flat transaction which starts implicitly by the first SQL command in the SQL session, or first SQL command after the previous SQL transaction. It is independent of other transactions in the session, and does not contain other (nested) transactions. A successful SQL transaction should be ended by COMMIT command, and a failed transaction should be ended by ROLLBACK command, which automatically rolls back all changes the transaction has made into the database. Some DBMS products, tools, and APIs, such as JDBC, by default use AUTOCOMMIT mode, which means that every SQL command will be committed automatically, and cannot be rolled back. In that case a proper transactional mode has to be started explicitly by some BEGIN WORK, BEGIN TRANSACTION, or START TRANSACTION command. In Oracle and MySQL any SQL DDL command will automatically commit the current SQL transaction. Use of SAVEPOINTs and more advanced transaction models are out of scope of this presentation

3 Visión de Instancia de Servidor de Base de Datos
Conexiones (sesiones) transacciones - Comandos y resultados SQL red Memoria principal listener & hebras de servicio bufferpool(s) Procesos de instancia De SGBD (hebras) x startup log cache(s) disco Ficheros control instancia To explain the context of SQL transactions in terms of the database server operations, we start with a generic and simplified overview of a database server instance (in the following we refer to this as ”instance”), which could be applied to the mainstream DBMS products, such as Oracle, DB2 and SQL Server. The architectures of these the DBMS products are slightly different, but they have also common concepts and functionalities, although may use different names for these. The detailed and advanced descriptions of these products are out of scope of this presentation. About the terminology: For a database server instance, the DBMS product needs first to be installed on the server computer. Then one or more instances can be created into the computer. With the term ”database server” one can refer to the server computer, but here we consider it as the synonym of database server instance. The properties of an instance are configered as parameter values in instance control files. The instance can be configured to start automatically as a system service when the computer is started, or it can be started manually by some ”startup” command. At startup, the set of work processes, a listener for client connections, and service threads (called also as server threads or agents) are started. On Unix/Linux platforms these can be processes and on Windows threads of the instance process. Then into the instance, one or more databases can be created. A database consists of data files (building table spaces for table and index structures of the database), transaction log files, and control files containing the configuration parameters for the database and its various operational main memory buffers (caches), including control data caches, data caches (usually called as buffer pools), log caches. Names of these concepts can be different in the DBMS products, but in the following we call a table space (”filegroup” in SQL Server) as a tablespace, and a data cache as a bufferpool. These are the generic names often used in literature, and for example, names of these concepts in the command language of DB2. The name of bufferpool in Oracle’s SQL language is buffer_pool. Software SGBD Ficheros control BD Ficheros de alertas y trazas Ficheros espacio tablas Logs transacciones Ficheros de base de datos

4 Arquitecturas de bases de datos
Instancia DB2 Instancia Oracle bufferpools BD bufferpools BD bufferpools BD Ficheros control directorios Ficheros control directorios Para cada base de datos los logs de transacciones activas forman una cadena circular Oracle llama a las cadenas de logs de Transacciones activas logs de reconstrucción Instancias SQL Server bufferpool BDs sistema Una instacia de servidor puede incluir una o varias Bases de datos dependiendo del producto SGBD. En adelante nos centraremos en un caso simple de Una única base de datos In case of SQL Server the instance configuration parameters, databases in the instance, and user login information are stored in the Master database, instead of using the instance control files as Oracle and DB2 are using. master BD BD Los logs de transacciones activas son alojadas en ficheros De log virtuales en un único fichero que forma una cadena circular Martti Laiho

5 Ficheros y Cachés Listener Aplicaciones (clientes) . . .
Esperando peticiones De conexión de clientes . . . Hebras de servicio (agentes) Caché de Control Control e transacción, etc Cache de páginas de datos Para el procesamiento rápido De datos minimizando Operaciones de E/S de disco Caché de Datos (Bufferpool) Protocolo LRU para liberar páginas Caché de Log Punto de Control Cache de imágenes Previas y posteriores De filas de Transacciones activas Ficheros de Datos en discos constituyen el espacio de tablas Para tablas e índices Páginas de datos para filas WAL protocolo write-ahead-logging On idle time between checkpoints dirty page can be written to database by Lazy Writer of SQL Server, or Page Cleaners of DB2. Archivo de Log (historial) Cadena circular de log de transacciones Martti Laiho

6 Estructuras de Páginas de Datos
Datos de control incluyendo punteros, dirty bit, LSN, etc Cabecera Página Cabecera Página PCTFREE Porcentaje de espacio libre originalmente en páginas Registro de la fila Registro fila Resto de la fila Slot directory Slot directory Dirección de una fila es RID (ROWID) File# : Page# : Slot# Una fila puede continuar en otras páginas o el registro original puede contener sólo un enlace a una nuevadirección, preservando el valor RID original de la dirección de la fila. LSN (Log Sequence Number) on page header is the LSN of the latest update to the page see ”Repeating History Beyond ARIES” by C. Mohan, ARIES (Algorithms for Recovery and Isolation Exploiting Semantics) is the basic CC&R (concurrency control and recovery) model developed by C. Mohan and his team at IBM Almaden Lab, and used nowadays in most DBMS products, such as DB2 and SQL Server. Cada fichero de datos tiene un file# en la BD y el espacio de trabla se gestiona como una secuancia de Páginas. Page# es el número ordinal de la página en el fichero. Un tamaño de página típico hoy día es 4, 8, 16 o 32 KB. Martti Laiho

7 Sesión SQL: Un cliente inicia su conexión SQL ..
connect? Listener . . . Hebras de Servicio (agentes) Caché de Control Caché de Datos (Bufferpool) Caché de Log Ficheros de Datos A client sends connect request to start a SQL session in the database Archivo de Log Logs de Transacciones Martti Laiho

8 .. Obtiene una hebra de servicio
connect? Listener . . . Hebras de Servicio (agentes) Caché de Control Caché de Datos (Bufferpool) Caché de Log Ficheros de Datos Listener finds a free service thread (agent) to serve the SQL session of the client Archivo de Log Logs de Transacciones Martti Laiho

9 .. Cliente usa un comando SQL para actualizar una fila (aún en disco)
El primer comando SQL inicia Una nueva trasacción update T set .. where id=.. Listener . . . Hebras de Servicio (agentes) Caché de Control Transaction #tr Caché de Datos (Bufferpool) Caché de Log # begin Ficheros de Datos La transacción obtienen un ID (#) Y un registro begin_transaction se escribe en la Caché de Logs Here we assume implicit transaction mode Archivo de Log Logs de Transacciones Martti Laiho

10 SGBD leé la página de la fila en bufferpool
update T set .. where id=.. Listener . . . Hebras de Servicio (agentes) Caché de Control Transaction #tr Caché de Datos (Bufferpool) . . . Caché de Log # begin Ficheros de Datos . . . . The SQL command to be executed will be parsed, bound to objects according to system table structures, optimized, and the proper row(s) will be searched using the data access method decided by the optimizer. This means searching through multiple system table pages, index pages, and table pages. Every needed page which is not yet in the bufferpool, need to be fetched there before processing. Finally, the row(s) to be updated are available in the bufferpool for processing. Archivo de Log Logs de Transacciones Martti Laiho

11 La fila es actualizada y la página actualizada se marca con Dirty Bit
update T set .. where id=.. Listener . . . Hebras de Servicio (agentes) Caché de Control Transaction #tr dirty bit Caché de Datos (Bufferpool) xxx Caché de Log # begin Ficheros de Datos The row is updated and the updated page is marked with the Dirty Bit. Alternative solution for marking the dirty pages is the separate dirty_pages table containg list of the page Ids of th edirty pages, as described in ARIES. Archivo de Log Logs de Transacciones Martti Laiho

12 Hebras de Servicio (agentes) Caché de Control
Un registro de log de la imagen previa y posterior de la fila se escribe en la cahñe de logs update T set .. where id=.. Listener . . . Hebras de Servicio (agentes) Caché de Control Transaction #tr dirty bit Caché de Datos (Bufferpool) xxx Caché de Log # begin #tr & before image & after image xxx # Ficheros de Datos A log record of the before image and after image of the row is written to log cache and marked with the transaction ID Archivo de Log Logs de Transacciones Martti Laiho

13 Hebras de Servicio (agentes) Caché de Control
Con commit los registros de log de la transacción se escriben en el log de la transacción COMMIT Listener . . . Hebras de Servicio (agentes) Caché de Control Transaction #tr dirty bit Caché de Datos (Bufferpool) xxx Caché de Log # begin xxx # Ficheros de Datos On commit all log records of the transaction are written to the transaction log followed by the commit record of the transaction Archivo de Log commit # xxx begin Logs de Transacciones Martti Laiho

14 Hebras de Servicio (agentes) Caché de Control
.. Pero en caso de ROLLBACK las imágenes previas son devueltas a sus direcciones originales ROLLBACK Listener . . . Hebras de Servicio (agentes) Caché de Control Transaction #tr dirty bit Caché de Datos (Bufferpool) Caché de Log # begin xxx # Ficheros de Datos In case of ROLLBACK the before images of all log records of the transaction are returned to original addresses. If some of the log records of the transaction have already been written to the transaction log, these records are first read from the transaction log for recovering the before images. Anyhow, the log records of the transaction still in the log buffer are written to the transaction log, followed by The rollback record of the transaction. Archivo de Log rollback # xxx begin Logs de Transacciones Martti Laiho

15 .. Finalmente el cliente cierra la conexión SQL
disconnect Listener . . . Hebras de Servicio (agentes) Caché de Control dirty bit Caché de Datos (Bufferpool) xxx Caché de Log Ficheros de Datos .. Here we continue the succesful case. At some time the client closes the connection, thus ending the SQL session and freeing the service thread. Committed data can be seen on the row in the bufferpool and on records in the transaction log file, but not necessary on the original page in the data file Archivo de Log commit # xxx begin Logs de Transacciones Martti Laiho

16 .. Algunas páginas pueden ser actualizadas por sesiones SQL de clientes
Listener . . . Hebras de Servicio (agentes) Caché de Control #tr(s) Caché de Datos (Bufferpool) xxx . . . X xx Caché de Log X xx # Ficheros de Datos The processing of possible concurrent transactions proceeds. More pages in the bufferpool may have got marked with dirty bits. The log cache gets occasionally filled with log records and some the records will get flushed to the transaction log to make room for new log records. Archivo de Log commit # xxx begin Logs de Transacciones Martti Laiho

17 De vez en cuando un punto de control para los servicios ..
Listener . . . Hebras de Servicio (agentes) Caché de Control Checkpoint #tr(s) Caché de Datos (Bufferpool) xxx . . . xxx Caché de Log X xx # Ficheros de Datos 1. write-ahead-logging (WAL) From time to time a Checkpoint stops the service threads. According to the WAL protocol all records from the log cache will first get flushed to the transaction log. Archivo de Log commit # xxx begin Logs de Transacciones Martti Laiho

18 Hebras de Servicio (agentes) Caché de Control Checkpoint #tr(s)
Y todas las pa´ginas “sucias” se escriben en los ficheros de datos limpiando los dirty bits Listener . . . Hebras de Servicio (agentes) Caché de Control Checkpoint #tr(s) Caché de Datos (Bufferpool) xxx . . . xxx Log Cache Caché de Log 2. Ficheros de Datos .. Then all dirty pages are synchronized back to Data files, that is, written to their original addresses in data files clearing the dirty bits on the bufferpool pages. Note 1: for fast accessing the pages with dirty bits on, these pages are managed in a linked list. Note 2: in SQL Server synchronising of dirty pages to the data files may get done even before the checkpoint by LazyWriter thread, to speed up the next checkpoint processing. xxx xxx Archivo de Log commit # xxx begin # X xx Logs de Transacciones Martti Laiho

19 Y escribe el registro de punto de control
Listener . . . Hebras de Servicio (agentes) Caché de Control Checkpoint #tr(s) Caché de Datos (Bufferpool) xxx . . . xxx Caché de Log Ficheros de Datos and writes a begin_checkpoint record to transaction log, followed by the list of the current transaction IDs and end_checkpoint record. Archivo de Log Checkpoint record commit # xxx begin 3. - Chk Begin - #tr list - Chk End CBg ### CEn CBg ### CEn # X xx Logs de Transacciones Martti Laiho

20 Después del punto de control los clientes puedne continuar
Listener . . . Hebras de Servicio (agentes) Caché de Control #tr(s) Caché de Datos (Bufferpool) xxx . . . xxx Caché de Log Ficheros de Datos After the checkpoint the serving of clients can continue xxx xxx Archivo de Log commit # xxx begin CBg ### CEn # X xx Logs de Transacciones Martti Laiho

21 Hebras de Servicio (agentes) Caché de Control
Los contenidos de los ficheros de log de transacciones se copian en el archivo .. Listener . . . Hebras de Servicio (agentes) Caché de Control #tr(s) Caché de Datos (Bufferpool) xxx . . . xxx Caché de Log Ficheros de Datos When some of the circular transaction log file gets full it will be copied to the end of the Log Archive collection of the transaction logs, writing to transaction log continues on the next file in the circular linked list, and .. xxx xxx Archivo de Log commit # xxx begin CBg ### CEn # X xx Logs de Transacciones commit # xxx begin Martti Laiho

22 .. Y el espacio de los ficheros de log copiados puede ser reutilizado
Listener . . . #tr(s) xxx . . . xxx .. and the space of the copied transaction log file will get marked as free for reuse on the next round of the circular file chain xxx xxx CBg ### CEn # X xx commit # xxx begin Martti Laiho

23 Una pruebade log usando SQL Server 2012
Basado en el ejercicio original de Kari Silpiö 21 Cabecera Página 10 Slots Page ID 1:77 11 21 22 23 10 11 21 In our example above we have filtered out lots of technical records and fields, for example on locking. Information of active transactions during the checkpoint is stored in [Log Record] field, which we have not listed on the slide. Compare this with the Log File and Checkpointing descriptions in Chapter Recovery Facilities and Figure in the book ” Database Systems” 5th edition by Thomas Collnolly and Caroline Begg See also Paul S. Randal’s article ”How do checkpoints work and what gets logged” at

24 Algunas Notas .. Least Recently Used (LRU) es necesario cuando el SGBD necesita recuperar espacio libre en el/los bufferpool(s). Las páginas que no han sido usadas por mayor tiempo y tienen reiniciado el dirty bit, serán sustituidas por páginas nuevas para leerse de ficheros de datos. Los ficheros circulares de log de transacciones activas son los ficheros más importantes de una base de datos ya que contienen datos de las transacciones más recientes confirmadas Dual logging (replicado) se recomienda para estos ficheros en discos dedicados. Basado en el último registro de punto de control y el log de transacciones circular un SGBD puede recuperar una base de datos después de un soft crash automaticamente mediante roll-back recovery de fallos y roll-forward recovery de transacciones confirmadas al nivel de la última trnsacción confirmada antes del soft crash. En caso de hardware crash el contenido de la base de datos tiene que se restaurado desde el backup de la base de datos y la aplicaciónand de roll-forward recovery del historial de transacciones desde el archivo y los últimos logs circulares, y finalmente rollback recovery de las últimas transacciones fallidas. Estos temas están cubiertos en tutoriales distintos.


Descargar ppt "Principios de las Transacciones SQL"

Presentaciones similares


Anuncios Google