Connect to the sqlite database at the given path. Creates the database if it does not exist. Uses WAL journal mode.
(path: &str, opts: SqliteOpts, migrate: Migrations)
| 84 | /// Connect to the sqlite database at the given path. Creates the database if it does not exist. |
| 85 | /// Uses WAL journal mode. |
| 86 | pub async fn connect(path: &str, opts: SqliteOpts, migrate: Migrations) -> Result<Self> { |
| 87 | let conn_opts = SqliteConnectOptions::from_str(path)? |
| 88 | .journal_mode(SqliteJournalMode::Wal) |
| 89 | .synchronous(sqlx::sqlite::SqliteSynchronous::Normal) |
| 90 | .create_if_missing(true) |
| 91 | .foreign_keys(true) |
| 92 | .analysis_limit(opts.analysis_limit); |
| 93 | |
| 94 | let conn_opts = if let Some(cache) = opts.cache_size { |
| 95 | conn_opts.pragma("cache_size", cache.to_string()) |
| 96 | } else { |
| 97 | conn_opts |
| 98 | }; |
| 99 | let conn_opts = if let Some(mmap) = opts.mmap_size { |
| 100 | conn_opts.pragma("mmap_size", mmap.to_string()) |
| 101 | } else { |
| 102 | conn_opts |
| 103 | }; |
| 104 | let conn_opts = if let Some(temp) = opts.temp_store { |
| 105 | conn_opts.pragma("temp_store", temp.pragma_value()) |
| 106 | } else { |
| 107 | conn_opts |
| 108 | }; |
| 109 | |
| 110 | let ro_opts = conn_opts.clone().read_only(true); |
| 111 | |
| 112 | // optimize can only be used on connections with write access |
| 113 | // make sure the initial limit is set above always and use the limit when closing as well |
| 114 | let write_opts = if opts.optimize { |
| 115 | conn_opts.optimize_on_close(true, opts.analysis_limit) |
| 116 | } else { |
| 117 | conn_opts |
| 118 | }; |
| 119 | |
| 120 | let writer = SqlitePoolOptions::new() |
| 121 | .min_connections(1) |
| 122 | .max_connections(1) |
| 123 | .connect_with(write_opts) |
| 124 | .await?; |
| 125 | let reader = SqlitePoolOptions::new() |
| 126 | .min_connections(1) |
| 127 | .max_connections(opts.max_ro_connections) |
| 128 | .connect_with(ro_opts) |
| 129 | .await?; |
| 130 | |
| 131 | if migrate == Migrations::Apply { |
| 132 | sqlx::migrate!("../migrations/sqlite") |
| 133 | .run(&writer) |
| 134 | .await |
| 135 | .map_err(sqlx::Error::from)?; |
| 136 | } |
| 137 | |
| 138 | Ok(Self { |
| 139 | writer, |
| 140 | reader, |
| 141 | optimize_requested: opts.optimize, |
| 142 | }) |
| 143 | } |