[Ruby on Rails (RoR)] Pessimistic Locking in Rails
Optimistic locking
Locking::Pessimistic provides support for row-level locking using SELECT … FOR UPDATE and other lock types.
Locking::Pessimistic provides support for row-level locking using SELECT … FOR UPDATE and other lock types.
If your class produces objects that never change, you can make these objects compile-time constants. To do this, define a const constructor and make sure that all instance variables are final
.
By default, Active Record uses some naming conventions to find out how the mapping between models and database tables should be created. Rails will pluralize your class names to find the respective database table. So, for a class Book, you should have a database table called books. The Rails pluralization mechanisms are very powerful, being capable of pluralizing (and singularizing) both regular and irregular words. When using class names composed of two or more words, the model class name should follow the Ruby conventions, using the CamelCase form, while the table name must contain the words separated by underscores. Examples:
Transactions are protective blocks where SQL statements are only permanent if they can all succeed as one atomic action. The classic example is a transfer between two accounts where you can only have a deposit if the withdrawal succeeded and vice versa. Transactions enforce the integrity of the database and guard the data against program errors or database break-downs. So basically you should use transaction blocks whenever you have a number of statements that must be executed together or not at all.
For example:
1 | ActiveRecord::Base.transaction do |
This example will only take money from David and give it to Mary if neither withdrawal nor deposit raise an exception. Exceptions will force a ROLLBACK
that returns the database to the state before the transaction began. Be aware, though, that the objects will not have their instance data returned to their pre-transactional state.
Though the transaction class method is called on some Active Record class, the objects within the transaction block need not all be instances of that class. This is because transactions are per-database connection, not per-model.
In this example a balance record is transactionally saved even though transaction is called on the Account class:
1 | Account.transaction do |
The transaction method is also available as a model instance method. For example, you can also do this:
1 | balance.transaction do |
A transaction acts on a single database connection. If you have multiple class-specific databases, the transaction will not protect interaction among them. One workaround is to begin a transaction on each class whose models you alter:
1 | Student.transaction do |
This is a poor solution, but fully distributed transactions are beyond the scope of Active Record.
Both #save
and #destroy
come wrapped in a transaction that ensures that whatever you do in validations or callbacks will happen under its protected cover. So you can use validations to check for values that the transaction depends on or you can raise exceptions in the callbacks to rollback, including after_* callbacks.
As a consequence changes to the database are not seen outside your connection until the operation is complete. For example, if you try to update the index of a search engine in after_save
the indexer won’t see the updated record. The after_commit
callback is the only one that is triggered once the update is committed. See below.
Any unhandled exception that occurs during the transaction will also cause it to be aborted. There are two common ways to raise these exceptions:
Using ActiveRecord methods ending with an exclamation-mark: save!, update!, destroy! etc.
Manually raising an exception
In ActiveRecord, when a method name ends with an exclamation-mark (also called a “bang”), it will raise an exception on failure.
Let’s say we have a transaction that involves creating a new user account, while also updating the record of another user (the referrer):
1 | ActiveRecord::Base.transaction do |
The create!
and update!
methods will raise an exception if something goes wrong.
If we were to use the create
and update
methods (without the exclamation mark), they would indicate a failure via their return value, and the transaction would keep running.
Of course, we could always check the return value ourselves and “manually” raise an exception if we wanted to:
1 | ActiveRecord::Base.transaction do |
It doesn’t matter what kind of exception you raise. Any exception class will abort the transaction.
Also have in mind that exceptions thrown within a transaction block will be propagated (after triggering the ROLLBACK
), so you should be ready to catch those in your application code.
Don’t forget to rescue the exception if you need to.
1 | def create_referrer_account |
ActiveRecord::Rollback
exceptionOne exception is the ActiveRecord::Rollback
exception, which will trigger a ROLLBACK
when raised, but not be re-raised by the transaction block.
1 | ActiveRecord::Base.transaction do |
Warning: one should not catch ActiveRecord::StatementInvalid
exceptions inside a transaction block. ActiveRecord::StatementInvalid exceptions indicate that an error occurred at the database level, for example when a unique constraint is violated. On some database systems, such as PostgreSQL, database errors inside a transaction cause the entire transaction to become unusable until it’s restarted from the beginning. Here is an example which demonstrates the problem:
1 | # Suppose that we have a Number model with a unique column called 'i'. |
One should restart the entire transaction if an ActiveRecord::StatementInvalid
occurred.
transaction calls can be nested. By default, this makes all database statements in the nested transaction block become part of the parent transaction. For example, the following behavior may be surprising:
1 | User.transaction do |
creates both “Kotori” and “Nemu”. Reason is the ActiveRecord::Rollback
exception in the nested block does not issue a ROLLBACK. Since these exceptions are captured in transaction blocks, the parent block does not see it and the real transaction is committed.
In order to get a ROLLBACK
for the nested transaction you may ask for a real sub-transaction by passing requires_new: true. If anything goes wrong, the database rolls back to the beginning of the sub-transaction without rolling back the parent transaction. If we add it to the previous example:
1 | User.transaction do |
only “Kotori” is created.
Most databases don’t support true nested transactions. At the time of writing, the only database that we’re aware of that supports true nested transactions, is MS-SQL. Because of this, Active Record emulates nested transactions by using savepoints. See MySQL :: MySQL 8.0 Reference Manual :: 13.3.4 SAVEPOINT, ROLLBACK TO SAVEPOINT, and RELEASE SAVEPOINT Statements - https://dev.mysql.com/doc/refman/8.0/en/savepoint.html for more information about savepoints.
There are two types of callbacks associated with committing and rolling back transactions: after_commit
and after_rollback
.
after_commit
callbacks are called on every record saved or destroyed within a transaction immediately after the transaction is committed.
after_rollback
callbacks are called on every record saved or destroyed within a transaction immediately after the transaction or savepoint is rolled back.
These callbacks are useful for interacting with other systems since you will be guaranteed that the callback is only executed when the database is in a permanent state. For example, after_commit
is a good spot to put in a hook to clearing a cache since clearing it from within a transaction could trigger the cache to be regenerated before the database is updated.
If your database supports setting the isolation level for a transaction, you can set it like so:
1 | Post.transaction(isolation: :serializable) do |
Valid isolation levels are:
:read_uncommitted
:read_committed
:repeatable_read
:serializable
You should consult the documentation for your database to understand the semantics of these different levels:
An ActiveRecord::TransactionIsolationError
will be raised if:
The adapter does not support setting the isolation level
You are joining an existing open transaction
You are creating a nested (savepoint) transaction
The mysql2
and postgresql
adapters support setting the transaction isolation level.
If you’re on MySQL, then do not use Data Definition Language (DDL) operations in nested transactions blocks that are emulated with savepoints. That is, do not execute statements like ‘CREATE TABLE’ inside such blocks. This is because MySQL automatically releases all savepoints upon executing a DDL operation. When transaction is finished and tries to release the savepoint it created earlier, a database error will occur because the savepoint has already been automatically released. The following example demonstrates the problem:
1 | Model.connection.transaction do # BEGIN |
Note that “TRUNCATE” is also a MySQL DDL statement!
This callback is called after a record has been created, updated, or destroyed.
You can specify that the callback should only be fired by a certain action with the :on
option:
1 | after_commit :do_foo, on: :create |
after_create_commit(*args, &block)Link
Shortcut for after_commit :hook, on: :create.
Source: show | on GitHub
after_destroy_commit(*args, &block)Link
Shortcut for after_commit :hook, on: :destroy.
Source: show | on GitHub
after_rollback(*args, &block)Link
This callback is called after a create, update, or destroy are rolled back.
Please check the documentation of after_commit for options.
Source: show | on GitHub
after_save_commit(*args, &block)Link
Shortcut for after_commit :hook, on: [ :create, :update ].
Source: show | on GitHub
after_update_commit(*args, &block)Link
Shortcut for after_commit :hook, on: :update.
Source: show | on GitHub
Race conditions are arguably the most insidious kind of bug; they’re intermittent, subtle, and most likely to occur in production. ActiveRecord’s update_counter
and other methods provides us with a convenient way to avoid race conditions when incrementing or decrementing values in the database.
A reference for beginners and forgetful professionals to Array for Ruby developer.
[1] Ruby Arrays Cheat Sheet | ShortcutFoo - https://www.shortcutfoo.com/app/dojos/ruby-arrays/cheatsheet
Logrus mate is a tool for Logrus, it will help you to initial logger by config, including Formatter
, Hook
,Level
and Output
.
Logrus is a structured logger for Go (golang), completely API compatible with the standard library logger.
Doorkeeper is a gem (Rails engine) that makes it easy to introduce OAuth 2 provider functionality to your Ruby on Rails or Grape application.
The rails console
command lets you interact with your Rails application from the command line. On the underside, rails console uses IRB deault, so if you’ve ever used it, you’ll be right at home. This is useful for testing out quick ideas with code and changing data server-side without touching the website.
You can also use the alias “c” to invoke the console: rails c
.
Role models are important.
— Officer Alex J. Murphy / RoboCop
The goal of this guide is to present a set of best practices and style prescriptions for Ruby on Rails 4 development. It’s a complementary guide to the already existing community-driven Ruby coding style guide.