sqlsrv

Check-in Differences
Login

Check-in Differences

Many hyperlinks are disabled.
Use anonymous login to enable hyperlinks.

Difference From sqlsrv-0.1.0 To sqlsrv-0.1.1

2024-01-26
10:18
Rework callbacks to return Result. check-in: 4ca6763477 user: jan tags: trunk
2024-01-24
17:30
Happy clippy check-in: 4d97ec049f user: jan tags: sqlsrv-0.1.1, trunk
17:24
Release maintenance. check-in: c644a253f0 user: jan tags: trunk
17:23
Add means to register ro or wr connection SQL functions. check-in: a8fb47cff8 user: jan tags: trunk
2024-01-21
17:32
Release maintenance. check-in: 161dbe5b26 user: jan tags: sqlsrv-0.1.0, trunk
17:27
Introduce a tpool feature to enable/disable threadpool support. check-in: cb6654deac user: jan tags: trunk

Changes to Cargo.toml.

1
2
3
4
5
6
7
8
9
10
[package]
name = "sqlsrv"
version = "0.1.0"
edition = "2021"
license = "0BSD"
categories = [ "database" ]
keywords = [ "sqlite", "server" ]
repository = "https://repos.qrnch.tech/pub/sqlsrv"
description = "Utility functions for managing SQLite connections in a server application."
rust-version = "1.56"


|







1
2
3
4
5
6
7
8
9
10
[package]
name = "sqlsrv"
version = "0.1.1"
edition = "2021"
license = "0BSD"
categories = [ "database" ]
keywords = [ "sqlite", "server" ]
repository = "https://repos.qrnch.tech/pub/sqlsrv"
description = "Utility functions for managing SQLite connections in a server application."
rust-version = "1.56"

Changes to src/lib.rs.

23
24
25
26
27
28
29
30

31
32
33
34
35
36
37

mod changehook;
mod err;
mod rawhook;
mod wrconn;

use std::{
  mem::ManuallyDrop, num::NonZeroUsize, path::Path, str::FromStr, sync::Arc

};

use parking_lot::{Condvar, Mutex};

use r2d2::{CustomizeConnection, PooledConnection};

use r2d2_sqlite::SqliteConnectionManager;







|
>







23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38

mod changehook;
mod err;
mod rawhook;
mod wrconn;

use std::{
  fmt, mem::ManuallyDrop, num::NonZeroUsize, path::Path, str::FromStr,
  sync::Arc
};

use parking_lot::{Condvar, Mutex};

use r2d2::{CustomizeConnection, PooledConnection};

use r2d2_sqlite::SqliteConnectionManager;
101
102
103
104
105
106
107



108
109
110









111
112
113
114
115
116
117





118
119
120
121
122
123
124
  /// The number of pages to process from the freelist each time an
  /// incremental autovacuum is triggered.
  ///
  /// If this is `None` then all pages will be processed.
  npages: Option<NonZeroUsize>
}




/// Read-only connection.
#[derive(Debug)]
struct RoConn {}










impl CustomizeConnection<rusqlite::Connection, rusqlite::Error> for RoConn {
  fn on_acquire(
    &self,
    conn: &mut rusqlite::Connection
  ) -> Result<(), rusqlite::Error> {
    conn.pragma_update(None, "foreign_keys", "ON")?;





    Ok(())
  }

  fn on_release(&self, _conn: rusqlite::Connection) {}
}









>
>
>

<
|
>
>
>
>
>
>
>
>
>







>
>
>
>
>







102
103
104
105
106
107
108
109
110
111
112

113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
  /// The number of pages to process from the freelist each time an
  /// incremental autovacuum is triggered.
  ///
  /// If this is `None` then all pages will be processed.
  npages: Option<NonZeroUsize>
}

type RoRegCb = dyn Fn(&Connection) + Send + Sync;
type RwRegCb = dyn Fn(&Connection);

/// Read-only connection.

struct RoConn {
  regfuncs: Option<Arc<RoRegCb>>
}

impl fmt::Debug for RoConn {
  fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
    write!(f, "RoConn {{}}")
  }
}


impl CustomizeConnection<rusqlite::Connection, rusqlite::Error> for RoConn {
  fn on_acquire(
    &self,
    conn: &mut rusqlite::Connection
  ) -> Result<(), rusqlite::Error> {
    conn.pragma_update(None, "foreign_keys", "ON")?;

    if let Some(ref regfuncs) = self.regfuncs {
      regfuncs(conn);
    }

    Ok(())
  }

  fn on_release(&self, _conn: rusqlite::Connection) {}
}


136
137
138
139
140
141
142
143


144
145
146
147
148
149
150
pub struct Builder {
  schmgr: Box<dyn SchemaMgr>,
  full_vacuum: bool,
  max_readers: usize,
  #[cfg(feature = "tpool")]
  thrdpool: ThrdPool,
  autoclean: Option<AutoClean>,
  hook: Option<Arc<dyn Hook + Send + Sync>>


}

/// Internal methods.
impl Builder {
  /// Open the writer connection.
  fn open_writer(&self, fname: &Path) -> Result<Connection, rusqlite::Error> {
    let conn = Connection::open(fname)?;







|
>
>







153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
pub struct Builder {
  schmgr: Box<dyn SchemaMgr>,
  full_vacuum: bool,
  max_readers: usize,
  #[cfg(feature = "tpool")]
  thrdpool: ThrdPool,
  autoclean: Option<AutoClean>,
  hook: Option<Arc<dyn Hook + Send + Sync>>,
  rofuncs: Option<Box<RoRegCb>>,
  rwfuncs: Option<Box<RwRegCb>>
}

/// Internal methods.
impl Builder {
  /// Open the writer connection.
  fn open_writer(&self, fname: &Path) -> Result<Connection, rusqlite::Error> {
    let conn = Connection::open(fname)?;
164
165
166
167
168
169
170
171

172
173
174
175

176
177
178
179
180
181
182
183
  fn full_vacuum(&self, conn: &Connection) -> Result<(), rusqlite::Error> {
    conn.execute("VACUUM;", params![])?;
    Ok(())
  }

  fn create_ro_pool(
    &self,
    fname: &Path

  ) -> Result<r2d2::Pool<SqliteConnectionManager>, r2d2::Error> {
    let fl =
      OpenFlags::SQLITE_OPEN_READ_ONLY | OpenFlags::SQLITE_OPEN_NO_MUTEX;
    let manager = SqliteConnectionManager::file(fname).with_flags(fl);

    let roconn_initterm = RoConn {};
    let max_readers = u32::try_from(self.max_readers).unwrap();
    r2d2::Pool::builder()
      .max_size(max_readers)
      .connection_customizer(Box::new(roconn_initterm))
      .build(manager)
  }








|
>




>
|







183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
  fn full_vacuum(&self, conn: &Connection) -> Result<(), rusqlite::Error> {
    conn.execute("VACUUM;", params![])?;
    Ok(())
  }

  fn create_ro_pool(
    &self,
    fname: &Path,
    regfuncs: Option<Box<RoRegCb>>
  ) -> Result<r2d2::Pool<SqliteConnectionManager>, r2d2::Error> {
    let fl =
      OpenFlags::SQLITE_OPEN_READ_ONLY | OpenFlags::SQLITE_OPEN_NO_MUTEX;
    let manager = SqliteConnectionManager::file(fname).with_flags(fl);
    let regfuncs = regfuncs.map(Arc::from);
    let roconn_initterm = RoConn { regfuncs };
    let max_readers = u32::try_from(self.max_readers).unwrap();
    r2d2::Pool::builder()
      .max_size(max_readers)
      .connection_customizer(Box::new(roconn_initterm))
      .build(manager)
  }

209
210
211
212
213
214
215
216


217
218
219
220
221
222
223
    Self {
      schmgr,
      full_vacuum: false,
      max_readers: 2,
      #[cfg(feature = "tpool")]
      thrdpool: ThrdPool::default(),
      autoclean: None,
      hook: None


    }
  }

  /// Trigger a full vacuum when initializing the connection pool.
  ///
  /// Operates on an owned `Builder` object.
  pub fn init_vacuum(mut self) -> Self {







|
>
>







230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
    Self {
      schmgr,
      full_vacuum: false,
      max_readers: 2,
      #[cfg(feature = "tpool")]
      thrdpool: ThrdPool::default(),
      autoclean: None,
      hook: None,
      rofuncs: None,
      rwfuncs: None
    }
  }

  /// Trigger a full vacuum when initializing the connection pool.
  ///
  /// Operates on an owned `Builder` object.
  pub fn init_vacuum(mut self) -> Self {
308
309
310
311
312
313
314
315
















316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331





332
333
334
335
336
337
338
  ) -> Self {
    self.autoclean = Some(AutoClean {
      dirt_threshold: dirt_watermark,
      npages
    });
    self
  }

















  /// Construct a connection pool.
  pub fn build<P>(self, fname: P) -> Result<ConnPool, Error>
  where
    P: AsRef<Path>
  {
    // ToDo: Use std::path::absolute() once stabilized
    let fname = fname.as_ref();
    let db_exists = fname.exists();

    //
    // Set up the read/write connection
    //
    // This must be done before creating the read-only connection pool, because
    // at that point the database file must already exist.
    //
    let mut conn = self.open_writer(fname)?;






    //
    // Perform schema initialization.
    //
    // This must be done after auto_vacuum is set, because auto_vacuum requires
    // configuration before any tables have been created.
    // See: https://www.sqlite.org/pragma.html#pragma_auto_vacuum








>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>

|














>
>
>
>
>







331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
  ) -> Self {
    self.autoclean = Some(AutoClean {
      dirt_threshold: dirt_watermark,
      npages
    });
    self
  }

  pub fn register_ro_functions<F>(mut self, f: F) -> Self
  where
    F: Fn(&Connection) + Send + Sync + 'static
  {
    self.rofuncs = Some(Box::new(f));
    self
  }

  pub fn register_rw_functions<F>(mut self, f: F) -> Self
  where
    F: Fn(&Connection) + 'static
  {
    self.rwfuncs = Some(Box::new(f));
    self
  }

  /// Construct a connection pool.
  pub fn build<P>(mut self, fname: P) -> Result<ConnPool, Error>
  where
    P: AsRef<Path>
  {
    // ToDo: Use std::path::absolute() once stabilized
    let fname = fname.as_ref();
    let db_exists = fname.exists();

    //
    // Set up the read/write connection
    //
    // This must be done before creating the read-only connection pool, because
    // at that point the database file must already exist.
    //
    let mut conn = self.open_writer(fname)?;

    // Register read/write connection functions
    if let Some(ref regfn) = self.rwfuncs {
      regfn(&conn);
    }

    //
    // Perform schema initialization.
    //
    // This must be done after auto_vacuum is set, because auto_vacuum requires
    // configuration before any tables have been created.
    // See: https://www.sqlite.org/pragma.html#pragma_auto_vacuum
361
362
363
364
365
366
367

368
369
370
371
372
373
374
375
    //
    #[cfg(feature = "tpool")]
    let tpool = self.init_tpool();

    //
    // Set up connection pool for read-only connections.
    //

    let rpool = self.create_ro_pool(fname)?;

    //
    // Prepare shared data
    //
    let iconn = InnerWrConn { conn, dirt: 0 };
    let inner = Inner { conn: Some(iconn) };
    let sh = Arc::new(Shared {







>
|







405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
    //
    #[cfg(feature = "tpool")]
    let tpool = self.init_tpool();

    //
    // Set up connection pool for read-only connections.
    //
    let rofuncs = self.rofuncs.take();
    let rpool = self.create_ro_pool(fname, rofuncs)?;

    //
    // Prepare shared data
    //
    let iconn = InnerWrConn { conn, dirt: 0 };
    let inner = Inner { conn: Some(iconn) };
    let sh = Arc::new(Shared {
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
  ///
  /// This method should not be called if the application has requested to add
  /// a raw update hook.
  ///
  /// # Panic
  /// This method will panic if a hook has been added to the Builder.
  pub fn build_with_changelog_hook<P, D, T>(
    self,
    fname: P,
    hook: Box<dyn ChangeLogHook<Database = D, Table = T> + Send>
  ) -> Result<ConnPool, Error>
  where
    P: AsRef<Path>,
    D: FromStr + Send + Sized + 'static,
    T: FromStr + Send + Sized + 'static







|







439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
  ///
  /// This method should not be called if the application has requested to add
  /// a raw update hook.
  ///
  /// # Panic
  /// This method will panic if a hook has been added to the Builder.
  pub fn build_with_changelog_hook<P, D, T>(
    mut self,
    fname: P,
    hook: Box<dyn ChangeLogHook<Database = D, Table = T> + Send>
  ) -> Result<ConnPool, Error>
  where
    P: AsRef<Path>,
    D: FromStr + Send + Sized + 'static,
    T: FromStr + Send + Sized + 'static
420
421
422
423
424
425
426





427
428
429
430
431
432
433
    //
    // Set up the read/write connection
    //
    // This must be done before creating the read-only connection pool, because
    // at that point the database file must already exist.
    //
    let mut conn = self.open_writer(fname)?;






    //
    // Perform schema initialization.
    //
    // This must be done after auto_vacuum is set, because auto_vacuum requires
    // configuration before any tables have been created.
    // See: https://www.sqlite.org/pragma.html#pragma_auto_vacuum







>
>
>
>
>







465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
    //
    // Set up the read/write connection
    //
    // This must be done before creating the read-only connection pool, because
    // at that point the database file must already exist.
    //
    let mut conn = self.open_writer(fname)?;

    // Register read/write connection functions
    if let Some(ref regfn) = self.rwfuncs {
      regfn(&conn);
    }

    //
    // Perform schema initialization.
    //
    // This must be done after auto_vacuum is set, because auto_vacuum requires
    // configuration before any tables have been created.
    // See: https://www.sqlite.org/pragma.html#pragma_auto_vacuum
454
455
456
457
458
459
460

461
462
463
464
465
466
467
468
    //
    #[cfg(feature = "tpool")]
    let tpool = self.init_tpool();

    //
    // Set up connection pool for read-only connections.
    //

    let rpool = self.create_ro_pool(fname)?;

    //
    // Prepare shared data
    //
    let iconn = InnerWrConn { conn, dirt: 0 };
    let inner = Inner { conn: Some(iconn) };
    let sh = Arc::new(Shared {







>
|







504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
    //
    #[cfg(feature = "tpool")]
    let tpool = self.init_tpool();

    //
    // Set up connection pool for read-only connections.
    //
    let rofuncs = self.rofuncs.take();
    let rpool = self.create_ro_pool(fname, rofuncs)?;

    //
    // Prepare shared data
    //
    let iconn = InnerWrConn { conn, dirt: 0 };
    let inner = Inner { conn: Some(iconn) };
    let sh = Arc::new(Shared {

Changes to www/changelog.md.

1
2
3
4
5
6
7
8
9
10
11
12











13
14
15
16
17
18
19
# Change Log

## [Unreleased]

[Details](/vdiff?from=sqlsrv-0.1.0&to=trunk)

### Added

### Changed

### Removed












---

## [0.1.0] - 2024-01-21

[Details](/vdiff?from=sqlsrv-0.0.4&to=sqlsrv-0.1.0)

### Changed




|







>
>
>
>
>
>
>
>
>
>
>







1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
# Change Log

## [Unreleased]

[Details](/vdiff?from=sqlsrv-0.1.1&to=trunk)

### Added

### Changed

### Removed

---

## [0.1.1] - 2024-01-24

[Details](/vdiff?from=sqlsrv-0.1.0&to=sqlsrv-0.1.1)

### Added

- Add ability to register callback functions for registering SQL functions for
  both read-only and read/write connections.

---

## [0.1.0] - 2024-01-21

[Details](/vdiff?from=sqlsrv-0.0.4&to=sqlsrv-0.1.0)

### Changed