-
Notifications
You must be signed in to change notification settings - Fork 5
Asynchronous Queries
topofocus edited this page Jul 24, 2019
·
2 revisions
To speed things up, its possible to send concurrent queries to the database.
> V.create :test_model
> thread_array = (0..99).map do | i|
> Thread.new do
> TestModel.create nr: i, count: TestModel.count
> end
> end
>
> thread_array.each &:join
> TestModel.all.map &:nr
=> [1, 16, 20, 31, 38, 47, 54, 62, 69, 96, 85, 94, 8, 13, 21, 29, 39, 48, 55, 64, 72, 76, 83, 90, 3, 7, 15, 24, 32, 41, 45, 57, 63, 70, 73, 81, 88, 5, 10, 17, 27, 33, 40, 49, 56, 65, 77, 95, 82, 92, 2, 9, 18, 23, 34, 42, 50, 58, 66, 78, 87, 93, 6, 0, 11, 19, 26, 36, 43, 51, 59, 67, 71, 89, 84, 98, 99, 14, 25, 28, 35, 44, 53, 61, 68, 74, 91, 80, 4, 12, 22, 30, 37, 46, 52, 60, 75, 79, 86, 97]
> TestModel.all.map &:count
=> [0, 10, 18, 28, 36, 44, 51, 59, 66, 77, 82, 89, 0, 9, 18, 28, 37, 44, 53, 61, 68, 77, 84, 95, 0, 0, 9, 19, 28, 37, 44, 54, 60, 66, 77, 85, 95, 0, 6, 10, 19, 30, 37, 45, 54, 61, 70, 78, 87, 95, 0, 6, 12, 19, 32, 39, 46, 55, 63, 70, 78, 87, 95, 0, 9, 18, 19, 33, 39, 48, 56, 65, 73, 82, 88, 95, 0, 9, 19, 24, 33, 42, 51, 59, 66, 73, 82, 87, 0, 9, 18, 26, 34, 44, 50, 58, 67, 75, 84, 91]
Although the create-statements were created sequential, database-operations are performed asynchronous. In the example, to create a record, a database query is fired (count). Create waits for the completion of this process. The moment the count-query is received, because of further inserts its value has most likely changed. Therefor its volatile and a progress-indicator.
The Log reveals that 99 connections to the database were established, thus it's up to the database itself to arrange the sequence.
Overview
Data Management
- Joining Tables, embedded Lists
- Links and Link Lists
- Relations
- Bidirectional Connections
- Working with Hashes
Public API
- Database
- Model CRUD
Misc