Skip to main content

open_configured

Function open_configured 

pub fn open_configured(path: impl AsRef<Path>) -> Result<Connection>
Available on crate features event-store or projection-store only.
Expand description

Opens (creating if absent) the database at path and configures it.

This is the single door both SqliteEventStore::open and SqliteProjectionStore::open go through, so that neither role can drift from the other’s settings.

§Errors

Returns the driver’s error if the file cannot be opened or created — a missing directory, a permission refusal, a corrupt header — or if a pragma statement is rejected.

Examples found in repository?
examples/rebuilding-read-models/src/main.rs (line 156)
153async fn run(path: &Path) -> Result<()> {
154    let events = SqliteEventStore::open(path)?;
155    let models = SqliteProjectionStore::open(path)?;
156    let app = open_configured(path)?;
157    app.execute_batch(READ_MODEL_DDL)?;
158
159    seed_the_log(&events).await?;
160    two_views_two_checkpoints(&events, &models, &app).await?;
161    a_third_view_added_late(&events, &models, &app).await?;
162    reset_and_rebuild(&events, &models, &app).await?;
163    one_poisoned_view(&events, &models).await?;
164
165    writeln!(io::stdout().lock(), "\n== final log ==")?;
166    print_log(&events).await?;
167
168    Ok(())
169}
More examples
Hide additional examples
examples/transfers-on-sqlite/src/main.rs (line 130)
127async fn before_the_reopen(path: &Path) -> Result<()> {
128    let events = SqliteEventStore::open(path)?;
129    let models = SqliteProjectionStore::open(path)?;
130    let app = open_configured(path)?;
131    app.execute_batch(READ_MODEL_DDL)?;
132
133    println!("\n== opening two accounts ==");
134    open_account(&events, "a1").await?;
135    open_account(&events, "a2").await?;
136    println!("   a1 and a2 opened");
137
138    println!("\n== depositing 100 into a1 ==");
139    deposit(&events, "a1", 100).await?;
140    println!("   deposited");
141
142    println!("\n== transferring 40 from a1 to a2 ==");
143    transfer(&events, "a1", "a2", 40).await?;
144    println!("   transferred: one append, two events, both accounts checked");
145
146    println!("\n== transferring 500 from a1 to a2 ==");
147    match transfer(&events, "a1", "a2", 500).await {
148        Ok(()) => bail!("an overdrawn transfer should have been rejected"),
149        Err(err) => println!("   rejected: {err}"),
150    }
151
152    println!("\n== projecting balances into the same file ==");
153    let mut balances = Balances::new();
154    let chunk = Chunk::of(CHUNK.try_into()?);
155    let done = run_projection(&events, &models, &mut balances, &Json, chunk).await?;
156    println!("   applied {} event(s)", done.applied);
157    print_read_model(&app)?;
158
159    Ok(())
160}
161
162/// Everything after the reopen, against the same file.
163///
164/// Nothing is carried in from above but the path.
165async fn after_the_reopen(path: &Path) -> Result<()> {
166    println!("\n== everything above is dropped; reopening the same file ==");
167    let events = SqliteEventStore::open(path)?;
168    let models = SqliteProjectionStore::open(path)?;
169    let app = open_configured(path)?;
170    println!("   reopened");
171
172    println!("\n== the read model, straight off disk ==");
173    print_read_model(&app)?;
174
175    println!("\n== the same balances, folded again from the event log ==");
176    for account in ["a1", "a2"] {
177        let balance = fold_balance(&events, account).await?;
178        println!("   {account}: {}", balance.held);
179    }
180
181    println!("\n== the checkpoint survived too ==");
182    let mut balances = Balances::new();
183    let chunk = Chunk::of(CHUNK.try_into()?);
184    let done = run_projection(&events, &models, &mut balances, &Json, chunk).await?;
185    println!(
186        "   re-running the projection applied {} event(s) — the log is not replayed",
187        done.applied
188    );
189
190    println!("\n== the reopened store is live, not merely readable ==");
191    transfer(&events, "a2", "a1", 15).await?;
192    let done = run_projection(&events, &models, &mut balances, &Json, chunk).await?;
193    println!(
194        "   transferred 15 back, and the projection applied {} event(s)",
195        done.applied
196    );
197    print_read_model(&app)?;
198
199    println!("\n== final log ==");
200    print_log(&events).await?;
201
202    Ok(())
203}
examples/tickets-over-http/src/api.rs (line 192)
161async fn show_the_seats(state: &State, request: &Request, stream: &mut TcpStream) -> Result<()> {
162    let through = checkpoint_through(&state.models, &state.checkpoint).await?;
163    let checkpoint = through.map_or_else(|| "none".to_owned(), |position| position.to_string());
164
165    if let Some(raw) = request.param("at") {
166        let wanted = match requested_position(raw) {
167            Ok(position) => position,
168            Err(bad) => {
169                return Ok(respond(
170                    stream,
171                    400,
172                    "Bad Request",
173                    &[],
174                    &format!("`{bad}` is not a position\n"),
175                )
176                .await?);
177            }
178        };
179
180        if through.is_none_or(|reached| reached < wanted.get()) {
181            return Ok(respond(
182                stream,
183                202,
184                "Accepted",
185                &[("X-Happenstance-Checkpoint", checkpoint)],
186                "the read model has not reached that position yet\n",
187            )
188            .await?);
189        }
190    }
191
192    let app = open_configured(&state.path)?;
193    let mut body = String::new();
194    for (seat, patron) in seat_rows(&app)? {
195        // Writing into a `String` cannot fail; the `Result` is discarded rather
196        // than `unwrap`ped so this server carries no panic path a request could
197        // reach even in principle.
198        let _ = writeln!(body, "{seat} {patron}");
199    }
200
201    Ok(respond(
202        stream,
203        200,
204        "OK",
205        &[("X-Happenstance-Checkpoint", checkpoint)],
206        &body,
207    )
208    .await?)
209}
examples/tickets-over-http/src/lib.rs (line 79)
78pub fn ensure_schema(path: &Path) -> rusqlite::Result<()> {
79    open_configured(path)?.execute_batch(READ_MODEL_DDL)
80}
examples/two-devices-one-seat/src/scenario.rs (line 70)
59    pub(crate) fn open(dir: &Path, at: Place) -> Result<Self, StoryError> {
60        let file = dir.join(format!("{at}.db"));
61        let events = SqliteEventStore::open(&file).map_err(|source| StoryError::Open {
62            file: file.clone(),
63            source,
64        })?;
65        let models =
66            SqliteProjectionStore::open(&file).map_err(|source| StoryError::OpenModel {
67                file: file.clone(),
68                source,
69            })?;
70        let app = open_configured(&file)
71            .and_then(|app| app.execute_batch(DDL).map(|()| app))
72            .map_err(|source| StoryError::ReadModel {
73                file: file.clone(),
74                source,
75            })?;
76        Ok(Self {
77            events,
78            models,
79            app,
80            file,
81        })
82    }