Retrieves a connection from the pool. Sets `query_only` pragma to the provided value to prevent accidental misuse of connection for writing when reading is intended. Only pass `query_only=false` if you want to use the connection for writing.
(self: Arc<Self>, query_only: bool)
| 91 | /// Only pass `query_only=false` if you want |
| 92 | /// to use the connection for writing. |
| 93 | pub async fn get(self: Arc<Self>, query_only: bool) -> Result<PooledConnection> { |
| 94 | if query_only { |
| 95 | let permit = self.semaphore.clone().acquire_owned().await?; |
| 96 | let conn = { |
| 97 | let mut connections = self.connections.lock(); |
| 98 | connections |
| 99 | .pop() |
| 100 | .context("Got a permit when there are no connections in the pool")? |
| 101 | }; |
| 102 | let conn = PooledConnection { |
| 103 | pool: Arc::downgrade(&self), |
| 104 | conn: Some(conn), |
| 105 | _permit: permit, |
| 106 | _write_mutex_guard: None, |
| 107 | }; |
| 108 | conn.pragma_update(None, "query_only", "1")?; |
| 109 | Ok(conn) |
| 110 | } else { |
| 111 | // We get write guard first to avoid taking a permit |
| 112 | // and not using it, blocking a reader from getting a connection |
| 113 | // while being ourselves blocked by another wrtier. |
| 114 | let write_mutex_guard = Arc::clone(&self.write_mutex).lock_owned().await; |
| 115 | |
| 116 | // We may still have to wait for a connection |
| 117 | // to be returned by some reader. |
| 118 | let permit = self.semaphore.clone().acquire_owned().await?; |
| 119 | let conn = { |
| 120 | let mut connections = self.connections.lock(); |
| 121 | connections.pop().context( |
| 122 | "Got a permit and write lock when there are no connections in the pool", |
| 123 | )? |
| 124 | }; |
| 125 | let conn = PooledConnection { |
| 126 | pool: Arc::downgrade(&self), |
| 127 | conn: Some(conn), |
| 128 | _permit: permit, |
| 129 | _write_mutex_guard: Some(write_mutex_guard), |
| 130 | }; |
| 131 | conn.pragma_update(None, "query_only", "0")?; |
| 132 | Ok(conn) |
| 133 | } |
| 134 | } |
| 135 | } |
| 136 | |
| 137 | /// Pooled connection. |