/rust/registry/src/index.crates.io-1949cf8c6b5b557f/surrealmx-0.15.0/src/pool.rs
Line | Count | Source |
1 | | // Copyright © SurrealDB Ltd |
2 | | // |
3 | | // Licensed under the Apache License, Version 2.0 (the "License"); |
4 | | // you may not use this file except in compliance with the License. |
5 | | // You may obtain a copy of the License at |
6 | | // |
7 | | // http://www.apache.org/licenses/LICENSE-2.0 |
8 | | // |
9 | | // Unless required by applicable law or agreed to in writing, software |
10 | | // distributed under the License is distributed on an "AS IS" BASIS, |
11 | | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
12 | | // See the License for the specific language governing permissions and |
13 | | // limitations under the License. |
14 | | |
15 | | //! This module stores the transaction pool for database transactions. |
16 | | |
17 | | use crate::inner::Inner; |
18 | | use crate::tx::Transaction; |
19 | | use crate::TransactionInner; |
20 | | use crossbeam_queue::ArrayQueue; |
21 | | use std::sync::Arc; |
22 | | |
23 | | /// The default transaction pool size |
24 | | pub(crate) const DEFAULT_POOL_SIZE: usize = 512; |
25 | | |
26 | | /// A memory-allocated transaction pool for database transactions |
27 | | pub(crate) struct Pool { |
28 | | /// The parent database for this transaction pool |
29 | | inner: Arc<Inner>, |
30 | | /// A queue for storing the allocated transactions |
31 | | pool: ArrayQueue<TransactionInner>, |
32 | | } |
33 | | |
34 | | impl Pool { |
35 | | /// Creates a new transaction pool for allocated transactions |
36 | 508 | pub(crate) fn new(inner: Arc<Inner>, size: usize) -> Arc<Self> { |
37 | 508 | Arc::new(Self { |
38 | 508 | inner, |
39 | 508 | pool: ArrayQueue::new(size), |
40 | 508 | }) |
41 | 508 | } |
42 | | |
43 | | /// Put a transaction back into the pool |
44 | 12.7k | pub(crate) fn put(self: &Arc<Self>, inner: TransactionInner) { |
45 | 12.7k | let _ = self.pool.push(inner); |
46 | 12.7k | } |
47 | | |
48 | | /// Get a new transaction from the pool |
49 | 12.7k | pub(crate) fn get(self: &Arc<Self>, write: bool) -> Transaction { |
50 | | // Fetch a new or pooled inner transaction |
51 | 12.7k | let inner = if let Some(mut tx) = self.pool.pop() { |
52 | 12.4k | tx.reset(write); |
53 | 12.4k | tx |
54 | | } else { |
55 | 289 | TransactionInner::new(self.inner.clone(), write) |
56 | | }; |
57 | | // Return a new enclosing transaction |
58 | 12.7k | Transaction { |
59 | 12.7k | inner: Some(inner), |
60 | 12.7k | pool: Arc::clone(self), |
61 | 12.7k | } |
62 | 12.7k | } |
63 | | } |