Buscar en moleculax

Este blog es un ensayo digital donde el pensamiento estructurado se encuentra con la introspección profunda. Explora la arquitectura del conocimiento: desde lo técnico hasta los fundamentos éticos. Aquí, cada algoritmo tiene propósito, cada línea de código refleja intención, y cada reflexión filosófica busca optimizar no solo sistemas, sino también decisiones humanas. Este blog no solo enseña a pensar, enseña a discernir, a construir con sentido. Porque el verdadero desarrollo nace de la conciencia, y eso exige precisión, virtud y coraje.

Tenemos que aprender a contemplar las potenciales consecuencias de nuestros planes, para impedir que nos sorprendan. De esta manera, tendremos más control sobre las situaciones difíciles ya que el verdadero progreso no se mide por la velocidad con la que avanzamos, sino por la dirección que elegimos. En un mundo cada vez más interconectado, el desarrollo de la humanidad exige más que tecnología y conocimiento: requiere conciencia, empatía y propósito.

Debemos cultivar una inteligencia que no solo resuelva problemas, sino que los prevenga con sabiduría. Una ciencia que no solo descubra, sino que se pregunte por qué y para quién. Una economía que no solo crezca, sino que reparta con justicia. Y una cultura que no solo celebre lo diverso, sino que lo abrace como fuerza vital.

Cada decisión que tomamos, cada palabra que decimos, cada idea que compartimos, puede ser una semilla de transformación. El futuro no está escrito: lo estamos escribiendo juntos, ahora mismo.

Que el desarrollo humano sea integral, sostenible y profundamente humano. Porque solo cuando elevamos a todos, nos elevamos como especie.

Sabiduría Justicia Templanza Coraje
READ ONLY transactions in MariaDB and MySQL

 Transactions are the least known RDBMS features. Everyone knows they exist, but few know how they work. For this reason, it is not obvious that they can be read only. This article explains what read only transactions are and why we should use them when appropriate.

What is a read only transaction?

An objection I’ve heard more than once is: transactions are for writes, SELECTs don’t even happen inside a transaction! But this is wrong. Transactions are not only about ROLLBACK and COMMIT. They are also about isolation.

As a general rule, this is what happens. When you start a transaction we acquire a view, or snapshot, on data. Until the end of the transaction we will see that snapshot, not modifications made by other connections.

Reads are generally non-locking. After you’ve read a row, other users can still modify it, even if your transaction is still in progress. Internally, MySQL will keep the information that allow to “rebuild” data as they were when you acquired the snapshot, so you can still see them. This information is preserved in the transaction logs.

To be clear, we actually always use transactions. By default, we run queries in autocommit mode, and we don’t start or end transactions explicitly. But even in this case, every SQL statement we run is a transaction.

There is no such thing as reading objective data. We always read from (or write to) snapshots acquired at a certain point of time, that include all the changes made by committed transactions.

Why should we use read only transactions?

Ok, we know what read only transactions are now. But why should we use them?

Results consistency

One reason should be obvious now. When we want to run more than one SELECT, and we want the results to be consistent, we should do it in a read only transaction. For example, we could do something like this:

SET @date := CURRENT_DATE();
SELECT COUNT(DISTINCT user_id)
    FROM product WHERE date = @date;
SELECT COUNT(DISTINCT product_id)
    FROM product WHERE date = @date;

If we want the two results to reflect the reality at a certain point in time, we need to do this in a transaction:

SET @date := CURRENT_DATE();
START TRANSACTION READ ONLY;
SELECT COUNT(DISTINCT user_id)
    FROM product WHERE date = @date;
SELECT COUNT(DISTINCT product_id)
    FROM product WHERE date = @date;
COMMIT;

The question implies something: why should we use a read only transaction, when we can use a regular read write transaction? If for some reason we try to write something, the statement will fail. So it’s simpler to just always use read write transactions.

A reason for using read only transactions is mentioned in the MySQL manual:

InnoDB can avoid the overhead associated with setting up the transaction ID (TRX_ID field) for transactions that are known to be read-only. A transaction ID is only needed for a transaction that might perform write operations or locking reads such as SELECT ... FOR UPDATE. Eliminating unnecessary transaction IDs reduces the size of internal data structures that are consulted each time a query or data change statement constructs a read view.

8.5.3 Optimizing InnoDB Read-Only Transactions – 25 August 2019

Finding bugs

Another reason for using read only transactions is to avoid writes to the database that shouldn’t happened, that occur because of a bug. As mentioned before, trying to write rows in the middle of a read only transaction will produce an error:

MariaDB [test]> START TRANSACTION READ ONLY;
Query OK, 0 rows affected (0.001 sec)

MariaDB [test]> INSERT INTO person (first_name, last_name, email) VALUES ('John', 'Doe', 'je.suis@example.com');
ERROR 1792 (25006): Cannot execute statement in a READ ONLY transaction

Remember to log your production database errors, and make sure that errors generate alerts or are somehow periodically reviewed. This particular error indicates an interesting bug in an application code.

Isolation levels

Isolation level is a setting that defines how much the current transaction is isolated from concurrent transactions. It can be changed at session level, before starting the next transaction. There is also a global setting, which takes effect for sessions that don’t change their isolation level. By default it is REPEATABLE READ.

Isolation levels are:

  • READ UNCOMMITTED;
  • READ COMMITTED;
  • REPEATABLE READ.

(We’re skipping SERIALIZABLE here, as it’s just a variation of REPEATABLE READ and it does not make sense with read only transactions)

This list is only valid for MySQL. Different DBMSs support different isolation levels.

The behavior described above refers to REPEATABLE READ. To recap, it acquires a snapshot of the data, which is used for the whole duration of the transaction.

Another isolation level is READ COMMITTED. It acquires a new snapshot for each query in the transaction. But this does not make sense for a read only transaction.

A usually underestimated isolation level is READ UNCOMMITTED. The reason why it is underestimated is that it reads data that are being written by other transactions, but are not yet committed – and possibly, will never be. For this reason, highly inconsistent data may be returned.

However, this can be an important optimisation. In my experience, it can make some queries much faster and greatly reduce CPU usage, especially when you are running expensive analytics SELECTs on write-intensive servers.

There are cases when results inconsistencies don’t matter. A typical example is running aggregations on many rows: an average on one million values will not change sensibly. Another example is when reading session-level data, that no one else is modifying; or old data, that no one is supposed to modify anymore.

If you want to use READ UNCOMMITTED, there is no reason to wrap multiple queries in a single transaction. For each query, you can run something like this:

SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED;
START TRANSACTION;
SELECT COUNT(*) FROM product;
COMMIT;

MetaData Lock and the rollback trick

When accessing a table using a non-transactional engine (like MyISAM) inside a transaction, MySQL will return a warning. They seem to assume that there is no reason to access such tables from a transaction, which is false. MariaDB doesn’t return such warning.

In reality, transactions acquire metadata locks (MDL). This means that other connections will not be able to run an ALTER TABLE on those tables until the transaction finishes. Preventing such problems is very important and should be done every time it’s useful.

mysqldump rolls back

mysqldump --single-transaction uses default read write transactions, not read only ones. My guess is that they don’t consider it important for a single long transaction, but only for many concurrent transactions.

However, the MariaDB version of mysqldump does something interesting with rollbacks:

ROLLBACK TO SAVEPOINT in --single-transaction mode to release metadata lock on table which was already dumped. This allows to avoid blocking concurrent DDL on this table without sacrificing correctness, as we won't access table second time and dumps created by --single-transaction mode have validity point at the start of transaction anyway.

Note that this doesn't make --single-transaction mode with concurrent DDL safe in general case. It just improves situation for people for whom it might be working.

mysqldump in MariaDB repo, taken from commit 624dd71b9419555eca8baadc695e3376de72286f

To recap:

  • An MDL blocks some operations, so it can be a problem just like any other lock, especially in a long transaction;
  • An MDL is only useful for data that we are going to access again, just like any other lock;
  • Transactions support savepoints in the middle of a transaction, and we can rollback to a savepoint instead of rolling the whole transaction back;
  • Doing so releases the MDLs on objects that were only accessed after the savepoint.

Conclusions

Here we discussed a feature that should probably be used more often. Actually, if you know from the beginning that a transaction is read only, there is no reason not to inform MySQL about that.

We discussed which isolation levels make sense for read only transactions, and the nice ROLLBACK TO SAVEPOINT trick used by mysqldump for MariaDB.


.

15dias (4) agenda 2023 (1) Algo que leer (268) Android (2) Angular (2) Apache (6) API (1) Arte y Cultura (11) Artes Marciales (10) Astro (1) Banner (1) Base de datos (37) Batalla Cultural (5) Big Data (12) Budismo (4) cabala judia (2) Calculo Asistido por computadoras (2) Canaima (6) Caos (1) Ceo (1) ciencias (3) Cine (1) Cobol (12) Cobra Kai (1) Codigo Linux Documental (2) Computación (4) Computación forense (14) Configurando Samba (1) Conocimiento (1) Consola (8) contenedores (10) cosmo (2) Criptomonedas (3) Cultura (1) Cursos (16) Darkweeb (3) Data Mining (1) Debian (18) Deep Learning (2) DeepWeb (7) demografia (9) Deporte y Recreación (9) Deportes (10) desclasificados (7) Desktop (1) developers (1) DevOps (1) Docker (12) Document (1) Ecología (6) Editor (3) Editores (4) Educacion y TIC (31) Electronica (2) Empleos (1) Emprendimiento (7) Espiritualidad (2) estoicismo (4) Eventos (2) Excel (1) Express (1) fedora (1) Filosofía (25) Fisica (1) Flisol 2008 (3) Flisol 2010 (1) Flisol 2015 (1) framework (2) Funny (1) Geografía (1) Gerencia y Liderazgo (72) Gestor de Volúmenes Lógicos (1) Git (7) GitHub (8) Globalizacion (5) gnu (28) Go (1) gobiernos (2) golang (2) Google por dentro (1) GraphQL (2) gRPC (1) Hackers - Documental (8) Hacking (31) Historia (3) howto (189) html (1) IA (22) IntelliJIDEA (1) Internet (6) Introducción a los patrones (2) J SON (1) java (58) java eclipse (4) javaScript (9) JDK (1) jiujitsu (4) Json (1) Junit (1) kali (39) kernel (2) Kotlin (1) Laravel (2) Latin (1) lecturas (2) LIbreOffice (1) Libros (4) Linux (49) Linux VirtualBox (1) Literatura (1) Machine Learning (2) Manuales (42) mariaDB (2) Markdown (4) Marketing (1) Matando ladilla (9) Matematicas (3) Matematricas (1) Math (1) maven (1) metodos https (1) Modelos (1) MongoDB (17) Multimedia (1) Musica (1) mvc (2) Mysql (22) MySQL Workbench (1) Nagios (2) Naturismo (1) NextJS (2) node (5) Node.js (6) NodeJS (10) NoSQL (1) npm (1) Oracle (11) Oracle sql (10) Php (4) PL/SQL (1) Plsql (1) PNL (1) Poblacion (2) Podman (1) Poesia (1) Politica (5) Política (1) Postgresql (12) PowerShell (1) programacion (88) Psicologia (11) Python (7) React (4) Recomiendo (1) Redes (31) Redis (2) Religion (2) REST (2) Rock (1) Rock/Metal Mp3 (2) RUP (1) Salud (5) sc:snap:android-studio (1) sc:snap:datagrip (1) sc:snap:gitkraken linux (1) Seguridad (18) Seguridad con Gnu Privacy (2) Seo (1) simulaEntrevistas (10) simularExamen (10) Sistemas Operativos (69) SOAP (1) Sociedad (5) Software Libre (169) Soporte Tecnico (12) Sphinx (1) spring (1) spring boot (12) SQL (4) SQL en postgreSQL (42) Taekwondo (11) Tecnologia (5) Tecnología (27) Templarios (5) Tendencias (1) Tensorflow (4) Thymeleaf (1) Tomcat (2) Tor (9) Trialectica (3) TYPEACRIPT (1) Ubuntu (5) unix (2) Vida activa (1) Videos (11) Videos Educativos (10) Vim (1) Viral (3) Visual Studio (1) wallpaper (2) web (1) Wifi (2) Windows (3) WWW (2) Xrandr (1) Zero Trust (2)

Sabiduria Justicia Templanza Coraje.

Hay que contemplar las potenciales consecuencias de nuestros planes, para impedir que nos sorprendan. De esta manera, tendremos más control sobre las situaciones difíciles.


Powered by

Moleculax es un blog de ciencia, biología, astronomía, tecnología y reflexiones sobre el futuro de la humanidad. Explora ideas innovadoras, descubrimientos científicos y conocimientos que inspiran la curiosidad y la imaginación. ¿Cómo saber si te han bloqueado en WhatsApp?, ¿COMO PROGRAMAR?, דודו פארוק, ¿QUES ES estructurada,modular, MongoDBSpain CheetSheet, ORIENTADA A OBJETOS?, Bases de datos estáticas, base de datos dinamicas bases de datos nosql, estructuras de base de datos, Bases de datos de texto completo, base de datos gerarquicas HTML, CSS, XML, JavaScript, mysql, oracle, postgresql, C, C#, php, java, python, liderazgo, libros, books, informix, ¿COMO REPARAR PAQUETES ROTOS EN DEBIAN?, REPARAR paquetes ROTOS ubuntu gerencia, COMO APRENDER laravel, ACTIVAR wifi en CANAIMA, exotics, exoticas, COMO APRENDER MONGODB, agapornio, agapomis, seguros, ganar dinero, bitcoin, freeBitcoin invertir en bolsa, marketing online, ofertas de coches Описание Блога Moleculax Moleculax — это цифровое эссе, в котором структурированное мышление встречается с глубокой интроспекцией. Наш блог исследует архитектуру знаний: от технических тонкостей разработки программного обеспечения до этических основ и философии. Ключевые Темы: Разработка и Технологии: Программирование, базы данных (SQL, NoSQL), Big Data, Node.js, Java. Наука и Мышление: Астрономия, биология, научные открытия, а также такие философские направления, как Стоицизм. Этика и Будущее: Размышления о развитии человечества, моральные принципы в технологиях и этические вызовы. Наша миссия: Развивать интеллект, который не только решает проблемы, но и предотвращает их с мудростью. Moleculax 是一个关于科学、生物学、天文学、技术以及人类未来思考的博客。它探索创新的理念、科学发现和能够激发好奇心与想象力的知识。 如何知道你在 WhatsApp 上被拉黑?如何编程? דודו פארוק,什么是结构化、模块化、面向对象?MongoDBSpain 速查表,静态数据库、动态数据库、NoSQL 数据库、数据库结构、全文数据库、层次型数据库。 HTML、CSS、XML、JavaScript、MySQL、Oracle、PostgreSQL、C、C#、PHP、Java、Python,领导力、书籍、Informix。如何修复 Debian 中损坏的软件包?修复 Ubuntu 损坏的软件包,管理,如何学习 Laravel,如何在 Canaima 激活 WiFi,异域、奇异,如何学习 MongoDB,爱情鸟、保险、赚钱、比特币、FreeBitcoin、投资股票市场、网络营销、汽车优惠。 Moleculax 博客描述: Moleculax 是一篇数字随笔,在这里结构化的思维与深刻的自省相遇。我们的博客探索知识的架构:从软件开发的技术细节到伦理基础与哲学。 核心主题: - 开发与技术:编程、数据库(SQL、NoSQL)、大数据、Node.js、Java。 - 科学与思维:天文学、生物学、科学发现,以及诸如斯多葛主义等哲学流派。 - 伦理与未来:关于人类发展的思考、技术中的道德原则与伦理挑战。 我们的使命:培养一种不仅能解决问题,而且能以智慧预防问题的智能。