1use std::collections::BTreeMap;
15use std::sync::Arc;
16
17use mln_util::chrono::{Timestamp, now};
18use mln_util::compression::{compress, decompress};
19use mln_util::constants::DEFAULT_MAX_CACHE_SIZE;
20use mln_util::error::{Error, ErrorKind};
21use mln_util::logging::{Event, EventSeverity, Log};
22use rusqlite::types::FromSqlError;
23use rusqlite::{Connection, OpenFlags, Row, ffi, params};
24
25use crate::merge_sideloaded::MERGE_SIDELOADED_DATABASE_SQL;
26use crate::offline::{
27 OfflineRegion, OfflineRegionDefinition, OfflineRegionMetadata, OfflineRegionStatus, OfflineRegions,
28 decode_offline_region_definition, encode_offline_region_definition,
29};
30use crate::offline_schema::OFFLINE_DATABASE_SCHEMA;
31use crate::resource::{Kind, Resource, TileData};
32use crate::response::Response;
33
34pub(crate) const MAX_PENDING_ACCESSED: usize = 4096;
37
38#[derive(Clone, Debug, thiserror::Error)]
40pub enum DatabaseError {
41 #[error("{message}")]
43 Sqlite { code: i32, message: String },
44 #[error("{message}")]
46 Io { code: i32, message: String },
47 #[error("{0}")]
50 Runtime(String),
51 #[error("{0}")]
53 Logic(String),
54 #[error("no offline region has ID {0}")]
56 RegionNotFound(i64),
57}
58
59impl From<rusqlite::Error> for DatabaseError {
60 fn from(e: rusqlite::Error) -> Self {
61 let code = e.sqlite_error().map_or(ffi::SQLITE_ERROR, |error| error.extended_code);
62 DatabaseError::Sqlite { code, message: e.to_string() }
63 }
64}
65
66impl From<FromSqlError> for DatabaseError {
67 fn from(e: FromSqlError) -> Self {
69 DatabaseError::Sqlite { code: ffi::SQLITE_ERROR, message: e.to_string() }
70 }
71}
72
73impl From<Error> for DatabaseError {
74 fn from(e: Error) -> Self {
75 match e.kind {
76 ErrorKind::InvalidArgument => DatabaseError::Logic(e.message),
77 _ => DatabaseError::Runtime(e.message),
78 }
79 }
80}
81
82impl From<DatabaseError> for Error {
83 fn from(error: DatabaseError) -> Self {
86 let kind = match error {
87 DatabaseError::Logic(_) => ErrorKind::InvalidArgument,
88 DatabaseError::RegionNotFound(_) => ErrorKind::NotFound,
89 _ => ErrorKind::Native,
90 };
91 Error::new(kind, error.to_string())
92 }
93}
94
95type DbResult<T> = Result<T, DatabaseError>;
96
97fn tile_data(resource: &Resource) -> Option<&TileData> {
101 resource.tile_data.as_ref().filter(|_| resource.kind == Kind::Tile)
102}
103
104fn delete_file(filename: &str) -> DbResult<()> {
105 match std::fs::remove_file(filename) {
106 Ok(()) => Ok(()),
107 Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(()),
108 Err(e) => {
109 let code = e.raw_os_error().unwrap_or(0);
110 let what = std::io::Error::from_raw_os_error(code).to_string();
112 let what = what.split(" (os error").next().unwrap_or(&what).to_owned();
113 Err(DatabaseError::Io { code, message: format!("Could not delete file {filename}: {what}") })
114 }
115 }
116}
117
118struct DatabaseSizeChangeStats {
121 page_size: u64,
122 page_count: u64,
123 initial_size: u64,
124}
125
126impl DatabaseSizeChangeStats {
127 fn new(db: &mut OfflineDatabase) -> DbResult<Self> {
128 let page_size = db.get_pragma_i64("PRAGMA page_size")? as u64;
129 let page_count = db.get_pragma_i64("PRAGMA page_count")? as u64;
130 let freelist_count = db.get_pragma_i64("PRAGMA freelist_count")?;
131 let initial_size = page_size.wrapping_mul(page_count.wrapping_sub(freelist_count as u64));
132 Ok(DatabaseSizeChangeStats { page_size, page_count, initial_size })
133 }
134
135 fn diff(&self, db: &mut OfflineDatabase) -> DbResult<i64> {
138 let page_count = db.get_pragma_i64("PRAGMA page_count")?;
139 let freelist_count = db.get_pragma_i64("PRAGMA freelist_count")?;
140 let current_size = (self.page_size as i64).wrapping_mul(page_count.wrapping_sub(freelist_count));
141 Ok(current_size.wrapping_sub(self.initial_size as i64))
142 }
143
144 fn bytes_released(&self, db: &mut OfflineDatabase) -> DbResult<u64> {
147 let freelist_count = db.get_pragma_i64("PRAGMA freelist_count")?;
148 let current_size = self.page_size.wrapping_mul(self.page_count.wrapping_sub(freelist_count as u64));
149 Ok((self.initial_size.wrapping_sub(current_size) as i64).max(0) as u64)
150 }
151
152 fn page_size(&self) -> u64 {
154 self.page_size
155 }
156}
157
158pub struct OfflineDatabase {
159 path: String,
160 db: Option<Connection>,
161
162 maximum_ambient_cache_size: u64,
163 current_ambient_cache_size: Option<u64>,
164
165 autopack: bool,
166 read_only: bool,
167
168 pending_resource_accessed: BTreeMap<i64, i64>,
171 pending_tile_accessed: BTreeMap<i64, i64>,
172 pending_applied_for_eviction: bool,
175 accessed_flush_failed: bool,
178 accessed_callback: Option<Box<dyn FnMut() + Send>>,
179}
180
181impl Drop for OfflineDatabase {
182 fn drop(&mut self) {
183 self.cleanup();
184 }
185}
186
187impl OfflineDatabase {
188 #[must_use]
193 pub(crate) fn cache_key(resource: &Resource) -> String {
194 let Some((first, second)) = resource.data_range else {
195 return resource.url.clone();
196 };
197 let sep = if resource.url.contains('?') { '&' } else { '?' };
198 format!("{}{}_mlnRange={}-{}", resource.url, sep, first, second)
199 }
200
201 pub fn new(path: impl Into<String>) -> Self {
202 let mut db = OfflineDatabase {
203 path: path.into(),
204 db: None,
205 maximum_ambient_cache_size: DEFAULT_MAX_CACHE_SIZE,
206 current_ambient_cache_size: None,
207 autopack: true,
208 read_only: false,
209 pending_resource_accessed: BTreeMap::new(),
210 pending_tile_accessed: BTreeMap::new(),
211 pending_applied_for_eviction: false,
212 accessed_flush_failed: false,
213 accessed_callback: None,
214 };
215 if let Err(e) = db.initialize() {
216 db.handle_error(&e, "open database");
217 }
218 db
221 }
222
223 fn initialize(&mut self) -> DbResult<()> {
224 assert!(self.db.is_none());
225
226 let flags = if self.read_only {
227 OpenFlags::SQLITE_OPEN_READ_ONLY | OpenFlags::SQLITE_OPEN_URI
228 } else {
229 OpenFlags::default()
230 };
231 let db = self.db.insert(Connection::open_with_flags(&self.path, flags)?);
232 db.busy_timeout(std::time::Duration::from_millis(i32::MAX as u64))?;
233 exec(db, "PRAGMA foreign_keys = ON")?;
234 if self.read_only {
235 return Ok(());
236 }
237
238 let user_version = self.get_pragma_i64("PRAGMA user_version")?;
239 match user_version {
240 0 | 1 => {
241 self.remove_old_cache_table()?;
244 self.create_schema()?;
245 Ok(())
246 }
247 2..=6 => {
248 if user_version == 2 {
249 self.migrate_to_version3()?;
250 }
251 if user_version <= 4 {
253 self.migrate_to_version5()?;
254 }
255 if user_version <= 5 {
256 self.migrate_to_version6()?;
257 }
258 Ok(())
260 }
261 _ => {
262 self.remove_existing()?;
264 self.initialize()
265 }
266 }
267 }
268
269 #[cfg(test)]
270 pub(crate) fn change_path(&mut self, path: &str) {
271 Log::info(Event::Database, "Changing the database path.");
272 self.cleanup();
273 self.path = path.to_owned();
274 if let Err(e) = self.initialize() {
275 self.handle_error(&e, "open database");
277 }
278 }
279
280 fn cleanup(&mut self) {
281 self.flush_accessed();
282 self.discard_pending_accessed();
283 self.db = None;
286 }
287
288 pub(crate) fn set_accessed_callback(&mut self, callback: Box<dyn FnMut() + Send>) {
293 self.accessed_callback = Some(callback);
294 }
295
296 #[must_use]
298 pub(crate) fn pending_accessed_count(&self) -> usize {
299 self.pending_resource_accessed.len() + self.pending_tile_accessed.len()
300 }
301
302 pub(crate) fn flush_accessed(&mut self) -> bool {
306 if self.pending_accessed_count() == 0 {
307 return true;
308 }
309 if self.read_only || self.db.is_none() {
310 return false;
311 }
312 match self.with_transaction(Begin::Immediate, Self::apply_pending_accessed) {
313 Ok(()) => {
314 self.discard_pending_accessed();
315 true
316 }
317 Err(e) => {
318 self.accessed_flush_failed = true;
319 self.handle_error(&e, "flush accessed timestamps");
320 false
321 }
322 }
323 }
324
325 fn discard_pending_accessed(&mut self) {
326 self.pending_resource_accessed.clear();
327 self.pending_tile_accessed.clear();
328 self.accessed_flush_failed = false;
329 }
330
331 fn apply_pending_accessed(&mut self) -> DbResult<()> {
333 self.get_db()?;
334 let Some(conn) = &self.db else {
335 return Ok(());
336 };
337 for (sql, pending) in [
338 ("UPDATE resources SET accessed = MAX(accessed, ?1) WHERE id = ?2", &self.pending_resource_accessed),
339 ("UPDATE tiles SET accessed = MAX(accessed, ?1) WHERE id = ?2", &self.pending_tile_accessed),
340 ] {
341 if pending.is_empty() {
342 continue;
343 }
344 let mut stmt = conn.prepare_cached(sql)?;
345 for (id, accessed) in pending {
346 stmt.execute(params![accessed, id])?;
347 }
348 }
349 Ok(())
350 }
351
352 fn queue_accessed(&mut self, tile: bool, id: i64) {
355 if self.read_only {
356 return;
357 }
358 let accessed = now().secs_since_epoch();
359 let full = self.pending_accessed_count() >= MAX_PENDING_ACCESSED;
360 let pending = if tile { &mut self.pending_tile_accessed } else { &mut self.pending_resource_accessed };
361 if let Some(existing) = pending.get_mut(&id) {
362 *existing = (*existing).max(accessed);
363 } else if !full {
364 pending.insert(id, accessed);
365 }
366 }
367
368 fn disabled(&mut self) -> bool {
369 if self.maximum_ambient_cache_size != 0 {
370 return false;
371 }
372
373 let regions = self.list_regions();
374 regions.map_or(true, |regions| regions.is_empty())
375 }
376
377 fn handle_error(&mut self, error: &DatabaseError, action: &str) {
378 match error {
379 DatabaseError::Sqlite { code, message } => {
380 let primary_code = code & 0xff;
381 if primary_code == ffi::SQLITE_NOTADB
382 || primary_code == ffi::SQLITE_CORRUPT
383 || *code == ffi::SQLITE_READONLY_DBMOVED
384 {
385 Log::record(
389 EventSeverity::Error,
390 Event::Database,
391 i64::from(primary_code),
392 &format!("Can't {action}: {message}"),
393 );
394 if let Err(io_ex) = self.remove_existing() {
395 self.handle_error(&io_ex, action);
396 }
397 } else {
398 Log::record(
401 EventSeverity::Warning,
402 Event::Database,
403 i64::from(primary_code),
404 &format!("Can't {action}: {message}"),
405 );
406 }
407 }
408 DatabaseError::Io { code, message } => {
409 Log::record(
411 EventSeverity::Error,
412 Event::Database,
413 i64::from(*code),
414 &format!("Can't {action}: {message}"),
415 );
416 }
417 DatabaseError::Runtime(message) => {
418 Log::error(Event::Database, format!("Can't {action}: {message}"));
419 }
420 DatabaseError::Logic(_) => {
421 Log::error(Event::Database, format!("Can't {action}"));
423 }
424 DatabaseError::RegionNotFound(_) => {}
426 }
427 }
428
429 fn remove_existing(&mut self) -> DbResult<()> {
430 Log::warning(Event::Database, "Removing existing incompatible offline database");
431
432 self.discard_pending_accessed();
433 let filename = match &self.db {
434 Some(db) => db.path().unwrap_or("").to_owned(),
435 None => self.path.clone(),
436 };
437 self.db = None;
438
439 if !filename.is_empty() {
440 delete_file(&filename)?;
441 }
442 Ok(())
443 }
444
445 fn remove_old_cache_table(&mut self) -> DbResult<()> {
446 self.check_flags()?;
447 exec(self.get_db()?, "DROP TABLE IF EXISTS http_cache")?;
448 if self.autopack {
449 self.vacuum()?;
450 }
451 Ok(())
452 }
453
454 fn create_schema(&mut self) -> DbResult<()> {
455 self.check_flags()?;
456
457 self.vacuum()?;
458 let db = self.get_db()?;
459 exec(db, "PRAGMA journal_mode = DELETE")?;
460 exec(db, "PRAGMA synchronous = FULL")?;
461 self.with_transaction(Begin::Deferred, |this| {
462 let db = this.get_db()?;
463 exec(db, OFFLINE_DATABASE_SCHEMA)?;
464 exec(db, "PRAGMA user_version = 6")?;
465 Ok(())
466 })
467 }
468
469 fn migrate_to_version3(&mut self) -> DbResult<()> {
470 self.check_flags()?;
471 self.vacuum()?;
472 exec(self.get_db()?, "PRAGMA user_version = 3")?;
473 Ok(())
474 }
475
476 fn migrate_to_version5(&mut self) -> DbResult<()> {
484 self.check_flags()?;
485 let db = self.get_db()?;
486 exec(db, "PRAGMA journal_mode = DELETE")?;
487 exec(db, "PRAGMA synchronous = FULL")?;
488 exec(db, "PRAGMA user_version = 5")?;
489 Ok(())
490 }
491
492 fn migrate_to_version6(&mut self) -> DbResult<()> {
493 self.check_flags()?;
494 self.with_transaction(Begin::Deferred, |this| {
495 let db = this.get_db()?;
496 exec(db, "ALTER TABLE resources ADD COLUMN must_revalidate INTEGER NOT NULL DEFAULT 0")?;
497 exec(db, "ALTER TABLE tiles ADD COLUMN must_revalidate INTEGER NOT NULL DEFAULT 0")?;
498 exec(db, "PRAGMA user_version = 6")?;
499 Ok(())
500 })
501 }
502
503 fn vacuum(&mut self) -> DbResult<()> {
504 self.check_flags()?;
505 if self.get_pragma_i64("PRAGMA auto_vacuum")? == 2 {
506 exec(self.get_db()?, "PRAGMA incremental_vacuum")?;
507 } else {
508 let empty = self.get_pragma_i64("PRAGMA page_count")? == 0;
511 let db = self.get_db()?;
512 exec(db, "PRAGMA auto_vacuum = INCREMENTAL")?;
513 if !empty {
514 exec(db, "VACUUM")?;
515 }
516 }
517 Ok(())
518 }
519
520 fn check_flags(&self) -> DbResult<()> {
521 if self.read_only {
522 return Err(DatabaseError::Runtime("Cannot modify database in read-only mode".to_owned()));
523 }
524 Ok(())
525 }
526
527 fn get_db(&mut self) -> DbResult<&Connection> {
529 if self.db.is_none() {
530 self.initialize()?;
531 }
532 Ok(self.db.as_ref().expect("initialized database"))
533 }
534
535 fn execute(&mut self, sql: &str, params: impl rusqlite::Params) -> DbResult<u64> {
538 let conn = self.get_db()?;
539 let mut stmt = conn.prepare_cached(sql)?;
540 Ok(stmt.execute(params)? as u64)
541 }
542
543 fn query_row<T>(
546 &mut self,
547 sql: &str,
548 params: impl rusqlite::Params,
549 f: impl FnOnce(&Row<'_>) -> DbResult<T>,
550 ) -> DbResult<Option<T>> {
551 let conn = self.get_db()?;
552 let mut stmt = conn.prepare_cached(sql)?;
553 let mut rows = stmt.query(params)?;
554 match rows.next()? {
555 None => Ok(None),
556 Some(row) => f(row).map(Some),
557 }
558 }
559
560 fn last_insert_row_id(&mut self) -> DbResult<i64> {
562 let conn = self.get_db()?;
563 Ok(conn.last_insert_rowid())
564 }
565
566 fn with_transaction<T>(&mut self, begin: Begin, f: impl FnOnce(&mut Self) -> DbResult<T>) -> DbResult<T> {
569 exec(self.get_db()?, begin.sql())?;
570 match f(self) {
571 Ok(value) => {
572 exec(self.get_db()?, "COMMIT TRANSACTION")?;
573 Ok(value)
574 }
575 Err(e) => {
576 if let Some(db) = &self.db {
578 let _ = exec(db, "ROLLBACK TRANSACTION");
579 }
580 Err(e)
581 }
582 }
583 }
584
585 fn get_pragma_i64(&mut self, sql: &str) -> DbResult<i64> {
586 Ok(self.query_row(sql, [], |row| Ok(row.get(0)?))?.unwrap_or(0))
587 }
588
589 pub fn get(&mut self, resource: &Resource) -> Option<Response> {
591 let result = (|| -> DbResult<Option<Response>> {
592 if self.disabled() {
593 return Ok(None);
594 }
595
596 let result = self.get_internal(resource)?;
597 Ok(result.map(|(response, _size)| response))
598 })();
599 match result {
600 Ok(response) => response,
601 Err(e) => {
602 self.handle_error(&e, "read resource");
603 None
604 }
605 }
606 }
607
608 fn get_internal(&mut self, resource: &Resource) -> DbResult<Option<(Response, u64)>> {
609 let result = if let Some(tile_data) = tile_data(resource) {
610 self.get_tile(tile_data)
611 } else {
612 self.get_resource(resource)
613 }?;
614 if self.pending_accessed_count() >= MAX_PENDING_ACCESSED && !self.accessed_flush_failed {
615 self.flush_accessed();
616 }
617 if result.is_some()
618 && self.pending_accessed_count() > 0
619 && let Some(callback) = &mut self.accessed_callback
620 {
621 callback();
622 }
623 Ok(result)
624 }
625
626 fn has_internal(&mut self, resource: &Resource) -> DbResult<Option<(i64, bool)>> {
629 if let Some(tile_data) = tile_data(resource) { self.has_tile(tile_data) } else { self.has_resource(resource) }
630 }
631
632 pub fn put(&mut self, resource: &Resource, response: &Response) -> (bool, u64) {
636 if self.read_only || response.tile_not_found {
637 return (false, 0);
638 }
639
640 let result = (|| -> DbResult<(bool, u64)> {
641 if self.db.is_none() {
642 self.initialize()?;
643 }
644
645 if self.disabled() {
646 return Ok((false, 0));
647 }
648
649 self.pending_applied_for_eviction = false;
650 let result = self.with_transaction(Begin::Immediate, |this| this.put_internal(resource, response, true))?;
651 if self.pending_applied_for_eviction {
652 self.discard_pending_accessed();
653 }
654 Ok(result)
655 })();
656 match result {
657 Ok(result) => result,
658 Err(e) => {
659 self.handle_error(&e, "write resource");
660 (false, 0)
661 }
662 }
663 }
664
665 fn put_internal(&mut self, resource: &Resource, response: &Response, evict: bool) -> DbResult<(bool, u64)> {
666 self.check_flags()?;
667
668 if response.error.is_some() {
669 return Ok((false, 0));
670 }
671
672 if evict && self.maximum_ambient_cache_size == 0 {
674 return Ok((false, 0));
675 }
676
677 let mut compressed_data = Vec::new();
678 let mut compressed = false;
679 let mut size = 0u64;
680
681 if let Some(data) = &response.data {
682 compressed_data = compress(data).map_err(DatabaseError::Runtime)?;
683 compressed = compressed_data.len() < data.len();
684 size = if compressed { compressed_data.len() } else { data.len() } as u64;
685 }
686
687 let mut stats = None;
688 if evict {
689 let s = DatabaseSizeChangeStats::new(self)?;
690 if !self.evict(size, &s, true)? {
691 Log::info(Event::Database, "Unable to make space for entry");
692 return Ok((false, 0));
693 }
694 stats = Some(s);
695 }
696
697 let data: &[u8] = if compressed {
698 &compressed_data
699 } else if let Some(data) = &response.data {
700 data
701 } else {
702 b""
703 };
704
705 let inserted = if let Some(tile_data) = tile_data(resource) {
706 self.put_tile(tile_data, response, data, compressed)?
707 } else {
708 self.put_resource(resource, response, data, compressed)?
709 };
710
711 if let Some(stats) = stats {
712 self.update_ambient_cache_size(&stats)?;
713 }
714
715 Ok((inserted, size))
716 }
717
718 fn read_response(row: &Row<'_>) -> DbResult<(Response, u64, i64)> {
721 let mut response = Response::new();
722 let mut size = 0u64;
723
724 response.etag = row.get(0)?;
725 response.expires = row.get::<_, Option<i64>>(1)?.map(Timestamp::from_secs);
726 response.must_revalidate = row.get(2)?;
727 response.modified = row.get::<_, Option<i64>>(3)?.map(Timestamp::from_secs);
728
729 match row.get_ref(4)?.as_bytes_or_null()? {
730 None => response.no_content = true,
731 Some(data) => {
732 size = data.len() as u64;
733 let data = if row.get(5)? { decompress(data).map_err(DatabaseError::Runtime)? } else { data.to_vec() };
734 response.data = Some(Arc::new(data));
735 }
736 }
737
738 Ok((response, size, row.get(6)?))
739 }
740
741 fn get_resource(&mut self, resource: &Resource) -> DbResult<Option<(Response, u64)>> {
742 let key = Self::cache_key(resource);
743 let row = self.query_row(
744 "SELECT etag, expires, must_revalidate, modified, data, compressed, id \
746 FROM resources \
747 WHERE url = ?",
748 params![key],
749 Self::read_response,
750 )?;
751 Ok(row.map(|(response, size, id)| {
752 self.queue_accessed(false, id);
753 (response, size)
754 }))
755 }
756
757 fn has_resource(&mut self, resource: &Resource) -> DbResult<Option<(i64, bool)>> {
758 let key = Self::cache_key(resource);
759 Ok(self
760 .query_row(
761 "SELECT length(data), must_revalidate, expires FROM resources WHERE url = ?",
762 params![key],
763 Self::read_size_and_usable,
764 )?
765 .flatten())
766 }
767
768 fn read_size_and_usable(row: &Row<'_>) -> DbResult<Option<(i64, bool)>> {
771 let Some(size) = row.get(0)? else {
772 return Ok(None);
773 };
774 let mut response = Response::new();
775 response.must_revalidate = row.get(1)?;
776 response.expires = row.get::<_, Option<i64>>(2)?.map(Timestamp::from_secs);
777 Ok(Some((size, response.is_usable())))
778 }
779
780 fn put_resource(
781 &mut self,
782 resource: &Resource,
783 response: &Response,
784 data: &[u8],
785 compressed: bool,
786 ) -> DbResult<bool> {
787 self.check_flags()?;
788
789 let key = Self::cache_key(resource);
790 let expires = response.expires.map(Timestamp::secs_since_epoch);
791 let modified = response.modified.map(Timestamp::secs_since_epoch);
792
793 if response.not_modified {
794 self.execute(
795 "UPDATE resources \
796 SET accessed = ?1, \
797 expires = ?2, \
798 must_revalidate = ?3 \
799 WHERE url = ?4 ",
800 params![now().secs_since_epoch(), expires, response.must_revalidate, key],
801 )?;
802 return Ok(false);
803 }
804
805 let (data, compressed): (Option<&[u8]>, bool) =
808 if response.no_content { (None, false) } else { (Some(data), compressed) };
809
810 let changes = self.execute(
812 "UPDATE resources \
813 SET kind = ?1, \
814 etag = ?2, \
815 expires = ?3, \
816 must_revalidate = ?4, \
817 modified = ?5, \
818 accessed = ?6, \
819 data = ?7, \
820 compressed = ?8 \
821 WHERE url = ?9 ",
822 params![
823 resource.kind as i32,
824 response.etag,
825 expires,
826 response.must_revalidate,
827 modified,
828 now().secs_since_epoch(),
829 data,
830 compressed,
831 key
832 ],
833 )?;
834 if changes != 0 {
835 return Ok(false);
836 }
837
838 self.execute(
839 "INSERT INTO resources (url, kind, etag, expires, must_revalidate, modified, accessed, data, compressed) \
840 VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9) ",
841 params![
842 key,
843 resource.kind as i32,
844 response.etag,
845 expires,
846 response.must_revalidate,
847 modified,
848 now().secs_since_epoch(),
849 data,
850 compressed
851 ],
852 )?;
853
854 Ok(true)
855 }
856
857 fn get_tile(&mut self, tile: &TileData) -> DbResult<Option<(Response, u64)>> {
858 let row = self.query_row(
859 "SELECT etag, expires, must_revalidate, modified, data, compressed, id \
861 FROM tiles \
862 WHERE url_template = ?1 \
863 AND pixel_ratio = ?2 \
864 AND x = ?3 \
865 AND y = ?4 \
866 AND z = ?5 ",
867 params![tile.url_template, tile.pixel_ratio, tile.x, tile.y, tile.z],
868 Self::read_response,
869 )?;
870 Ok(row.map(|(response, size, id)| {
871 self.queue_accessed(true, id);
872 (response, size)
873 }))
874 }
875
876 fn has_tile(&mut self, tile: &TileData) -> DbResult<Option<(i64, bool)>> {
877 Ok(self
878 .query_row(
879 "SELECT length(data), must_revalidate, expires \
880 FROM tiles \
881 WHERE url_template = ?1 \
882 AND pixel_ratio = ?2 \
883 AND x = ?3 \
884 AND y = ?4 \
885 AND z = ?5 ",
886 params![tile.url_template, tile.pixel_ratio, tile.x, tile.y, tile.z],
887 Self::read_size_and_usable,
888 )?
889 .flatten())
890 }
891
892 fn put_tile(&mut self, tile: &TileData, response: &Response, data: &[u8], compressed: bool) -> DbResult<bool> {
893 self.check_flags()?;
894
895 let expires = response.expires.map(Timestamp::secs_since_epoch);
896 let modified = response.modified.map(Timestamp::secs_since_epoch);
897
898 if response.not_modified {
899 self.execute(
900 "UPDATE tiles \
901 SET accessed = ?1, \
902 expires = ?2, \
903 must_revalidate = ?3 \
904 WHERE url_template = ?4 \
905 AND pixel_ratio = ?5 \
906 AND x = ?6 \
907 AND y = ?7 \
908 AND z = ?8 ",
909 params![
910 now().secs_since_epoch(),
911 expires,
912 response.must_revalidate,
913 tile.url_template,
914 tile.pixel_ratio,
915 tile.x,
916 tile.y,
917 tile.z
918 ],
919 )?;
920 return Ok(false);
921 }
922
923 let (data, compressed): (Option<&[u8]>, bool) =
924 if response.no_content { (None, false) } else { (Some(data), compressed) };
925
926 let changes = self.execute(
928 "UPDATE tiles \
929 SET modified = ?1, \
930 etag = ?2, \
931 expires = ?3, \
932 must_revalidate = ?4, \
933 accessed = ?5, \
934 data = ?6, \
935 compressed = ?7 \
936 WHERE url_template = ?8 \
937 AND pixel_ratio = ?9 \
938 AND x = ?10 \
939 AND y = ?11 \
940 AND z = ?12 ",
941 params![
942 modified,
943 response.etag,
944 expires,
945 response.must_revalidate,
946 now().secs_since_epoch(),
947 data,
948 compressed,
949 tile.url_template,
950 tile.pixel_ratio,
951 tile.x,
952 tile.y,
953 tile.z
954 ],
955 )?;
956 if changes != 0 {
957 return Ok(false);
958 }
959
960 self.execute(
961 "INSERT INTO tiles (url_template, pixel_ratio, x, y, z, modified, must_revalidate, etag, expires, accessed, data, compressed) \
962 VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9, ?10, ?11, ?12)",
963 params![
964 tile.url_template,
965 tile.pixel_ratio,
966 tile.x,
967 tile.y,
968 tile.z,
969 modified,
970 response.must_revalidate,
971 response.etag,
972 expires,
973 now().secs_since_epoch(),
974 data,
975 compressed
976 ],
977 )?;
978
979 Ok(true)
980 }
981
982 pub(crate) fn invalidate_ambient_cache(&mut self) -> Option<DatabaseError> {
985 let result = (|| -> DbResult<()> {
986 self.check_flags()?;
987
988 self.execute(
989 "UPDATE tiles \
990 SET expires = 0, must_revalidate = 1 \
991 WHERE id NOT IN (\
992 SELECT tile_id FROM region_tiles\
993 )",
994 [],
995 )?;
996
997 self.execute(
998 "UPDATE resources \
999 SET expires = 0, must_revalidate = 1 \
1000 WHERE id NOT IN (\
1001 SELECT resource_id FROM region_resources\
1002 )",
1003 [],
1004 )?;
1005 Ok(())
1006 })();
1007 self.exception_ptr(result, "invalidate ambient cache")
1008 }
1009
1010 pub(crate) fn clear_ambient_cache(&mut self) -> Option<DatabaseError> {
1012 let result = (|| -> DbResult<()> {
1013 self.check_flags()?;
1014 self.discard_pending_accessed();
1016
1017 self.execute(
1018 "DELETE FROM tiles \
1019 WHERE id NOT IN (\
1020 SELECT tile_id FROM region_tiles\
1021 )",
1022 [],
1023 )?;
1024
1025 self.execute(
1026 "DELETE FROM resources \
1027 WHERE id NOT IN (\
1028 SELECT resource_id FROM region_resources\
1029 )",
1030 [],
1031 )?;
1032
1033 if self.autopack {
1034 self.vacuum()?;
1035 }
1036 Ok(())
1037 })();
1038 self.exception_ptr(result, "clear ambient cache")
1039 }
1040
1041 pub fn invalidate_region(&mut self, region_id: i64) -> Option<DatabaseError> {
1042 let result = (|| -> DbResult<()> {
1043 self.check_flags()?;
1044
1045 self.execute(
1046 "UPDATE tiles \
1047 SET expires = 0, must_revalidate = 1 \
1048 WHERE id IN (\
1049 SELECT tile_id FROM region_tiles WHERE region_id = ?\
1050 )",
1051 params![region_id],
1052 )?;
1053
1054 self.execute(
1055 "UPDATE resources \
1056 SET expires = 0, must_revalidate = 1 \
1057 WHERE id IN (\
1058 SELECT resource_id FROM region_resources WHERE region_id = ?\
1059 )",
1060 params![region_id],
1061 )?;
1062 Ok(())
1063 })();
1064 self.exception_ptr(result, "invalidate region")
1065 }
1066
1067 fn exception_ptr(&mut self, result: DbResult<()>, action: &str) -> Option<DatabaseError> {
1070 match result {
1071 Ok(()) => None,
1072 Err(e) => {
1073 self.handle_error(&e, action);
1074 Some(e)
1075 }
1076 }
1077 }
1078
1079 fn expected<T>(&mut self, result: DbResult<T>, action: &str) -> DbResult<T> {
1082 if let Err(e) = &result {
1083 self.handle_error(e, action);
1084 }
1085 result
1086 }
1087
1088 pub fn list_regions(&mut self) -> Result<OfflineRegions, DatabaseError> {
1089 let result = (|| -> DbResult<OfflineRegions> {
1090 let rows = {
1091 let conn = self.get_db()?;
1092 let mut stmt = conn.prepare_cached("SELECT id, definition, description FROM regions")?;
1093 let mut rows = stmt.query([])?;
1094 let mut result = Vec::new();
1095 while let Some(row) = rows.next()? {
1096 result.push((row.get(0)?, text_or_blob(row, 1)?, text_or_blob(row, 2)?));
1097 }
1098 result
1099 };
1100 let mut result = OfflineRegions::new();
1101 for (id, definition, description) in rows {
1102 match decode_offline_region_definition(&definition) {
1103 Ok(definition) => result.push(OfflineRegion { id, definition, metadata: description }),
1104 Err(ex) => {
1105 Log::error(Event::General, &ex.message);
1108 }
1109 }
1110 }
1111 Ok(result)
1112 })();
1113 self.expected(result, "list regions")
1114 }
1115
1116 pub fn get_region(&mut self, region_id: i64) -> Result<Option<OfflineRegion>, DatabaseError> {
1117 let result = (|| -> DbResult<Option<OfflineRegion>> {
1118 let row = self.query_row(
1119 "SELECT definition, description FROM regions WHERE id = ?1",
1120 params![region_id],
1121 |row| Ok((text_or_blob(row, 0)?, text_or_blob(row, 1)?)),
1122 )?;
1123 let Some((definition, description)) = row else {
1124 return Ok(None);
1125 };
1126
1127 if definition.is_empty() && description.is_empty() {
1128 return Err(DatabaseError::Runtime(format!("Region {region_id} not found in database")));
1129 }
1130
1131 Ok(Some(OfflineRegion {
1132 id: region_id,
1133 definition: decode_offline_region_definition(&definition)?,
1134 metadata: description,
1135 }))
1136 })();
1137 self.expected(result, "get region")
1138 }
1139
1140 pub fn create_region(
1141 &mut self,
1142 definition: &OfflineRegionDefinition,
1143 metadata: &OfflineRegionMetadata,
1144 ) -> Result<OfflineRegion, DatabaseError> {
1145 let result = (|| -> DbResult<OfflineRegion> {
1146 self.check_flags()?;
1147
1148 self.execute(
1149 "INSERT INTO regions (definition, description) \
1150 VALUES (?1, ?2) ",
1151 params![encode_offline_region_definition(definition), metadata_blob(metadata)],
1152 )?;
1153 Ok(OfflineRegion {
1154 id: self.last_insert_row_id()?,
1155 definition: definition.clone(),
1156 metadata: metadata.clone(),
1157 })
1158 })();
1159 self.expected(result, "create region")
1160 }
1161
1162 pub fn merge_database(&mut self, side_database_path: &str) -> Result<OfflineRegions, DatabaseError> {
1163 self.check_flags()?;
1164
1165 match self.execute("ATTACH DATABASE ?1 AS side", params![side_database_path]) {
1166 Ok(_) => {}
1167 Err(e @ DatabaseError::Sqlite { code, .. }) => {
1168 Log::record(
1169 EventSeverity::Error,
1170 Event::Database,
1171 i64::from(code & 0xff),
1172 &format!("Can't attach database ({side_database_path}) for merge: {e}"),
1173 );
1174 return Err(e);
1175 }
1176 Err(e) => return Err(e),
1177 }
1178
1179 let result = (|| -> DbResult<OfflineRegions> {
1180 let side_user_version = self.get_pragma_i64("PRAGMA side.user_version")? as i32;
1184 let main_user_version = self.get_pragma_i64("PRAGMA user_version")?;
1185 if side_user_version < 6 || i64::from(side_user_version) != main_user_version {
1186 return Err(DatabaseError::Runtime("Merge database has incorrect user_version".to_owned()));
1187 }
1188
1189 self.with_transaction(Begin::Deferred, |this| {
1190 exec(this.get_db()?, MERGE_SIDELOADED_DATABASE_SQL)?;
1191 Ok(())
1192 })?;
1193
1194 let rows = {
1195 let conn = self.get_db()?;
1196 let mut stmt = conn.prepare_cached(
1197 "SELECT DISTINCT r.id, r.definition, r.description \
1198 FROM side.regions sr \
1199 JOIN regions r ON sr.definition = r.definition AND sr.description IS r.description",
1200 )?;
1201 let mut rows = stmt.query([])?;
1202 let mut result = Vec::new();
1203 while let Some(row) = rows.next()? {
1204 result.push((row.get(0)?, text_or_blob(row, 1)?, text_or_blob(row, 2)?));
1205 }
1206 result
1207 };
1208 let mut result = OfflineRegions::new();
1209 for (id, definition, description) in rows {
1210 result.push(OfflineRegion {
1211 id,
1212 definition: decode_offline_region_definition(&definition)?,
1213 metadata: description,
1214 });
1215 }
1216 exec(self.get_db()?, "DETACH DATABASE side")?;
1217 Ok(result)
1218 })();
1219
1220 match result {
1221 Err(e) if !matches!(e, DatabaseError::Logic(_)) => {
1224 exec(self.get_db()?, "DETACH DATABASE side")?;
1225 Log::error(Event::Database, e.to_string());
1226 Err(e)
1227 }
1228 result => result,
1229 }
1230 }
1231
1232 pub fn update_metadata(
1233 &mut self,
1234 region_id: i64,
1235 metadata: &OfflineRegionMetadata,
1236 ) -> Result<OfflineRegionMetadata, DatabaseError> {
1237 let result = (|| -> DbResult<OfflineRegionMetadata> {
1238 self.check_flags()?;
1239
1240 self.execute(
1241 "UPDATE regions SET description = ?1 \
1242 WHERE id = ?2",
1243 params![metadata_blob(metadata), region_id],
1244 )?;
1245
1246 Ok(metadata.clone())
1247 })();
1248 self.expected(result, "update region metadata")
1249 }
1250
1251 pub fn delete_region(&mut self, region: &OfflineRegion) -> Option<DatabaseError> {
1252 let result = (|| -> DbResult<()> {
1253 self.check_flags()?;
1254 self.flush_accessed();
1256
1257 self.execute("DELETE FROM regions WHERE id = ?", params![region.id])?;
1258
1259 let stats = DatabaseSizeChangeStats::new(self)?;
1260 self.evict(0, &stats, false)?;
1261 if self.autopack {
1262 self.vacuum()?;
1263 }
1264 self.update_ambient_cache_size(&stats)?;
1265 Ok(())
1266 })();
1267 self.exception_ptr(result, "delete region")
1268 }
1269
1270 pub fn get_region_resource(&mut self, resource: &Resource) -> Option<(Response, u64)> {
1272 match self.get_internal(resource) {
1273 Ok(result) => result,
1274 Err(e) => {
1275 self.handle_error(&e, "read region resource");
1276 None
1277 }
1278 }
1279 }
1280
1281 #[cfg(test)]
1282 pub(crate) fn has_region_resource(&mut self, resource: &Resource) -> Option<i64> {
1283 self.check_region_resource(resource).map(|(size, _)| size)
1284 }
1285
1286 pub fn check_region_resource(&mut self, resource: &Resource) -> Option<(i64, bool)> {
1289 match self.has_internal(resource) {
1290 Ok(result) => result,
1291 Err(e) => {
1292 self.handle_error(&e, "query region resource");
1293 None
1294 }
1295 }
1296 }
1297
1298 pub fn put_region_resource(&mut self, region_id: i64, resource: &Resource, response: &Response) -> u64 {
1299 let result = (|| -> DbResult<u64> {
1300 self.check_flags()?;
1301
1302 if self.db.is_none() {
1303 self.initialize()?;
1304 }
1305 self.with_transaction(Begin::Deferred, |this| {
1306 this.put_region_resource_internal(region_id, resource, response)
1307 })
1308 })();
1309 result.unwrap_or_else(|e| {
1310 self.handle_error(&e, "write region resource");
1311 0
1312 })
1313 }
1314
1315 pub fn put_region_resources(
1316 &mut self,
1317 region_id: i64,
1318 resources: &[(Resource, Response)],
1319 status: &mut OfflineRegionStatus,
1320 ) {
1321 let result = (|| -> DbResult<()> {
1322 self.check_flags()?;
1323
1324 if self.db.is_none() {
1325 self.initialize()?;
1326 }
1327 let mut completed_resource_count = 0u64;
1331 let mut completed_resource_size = 0u64;
1332 let mut completed_tile_count = 0u64;
1333 let mut completed_tile_size = 0u64;
1334
1335 self.with_transaction(Begin::Deferred, |this| {
1336 for (resource, response) in resources {
1337 let resource_size = this.put_region_resource_internal(region_id, resource, response)?;
1338 completed_resource_count += 1;
1339 completed_resource_size += resource_size;
1340 if resource.kind == Kind::Tile {
1341 completed_tile_count += 1;
1342 completed_tile_size += resource_size;
1343 }
1344 }
1345 Ok(())
1346 })?;
1347
1348 status.completed_resource_count += completed_resource_count;
1349 status.completed_resource_size += completed_resource_size;
1350 status.completed_tile_count += completed_tile_count;
1351 status.completed_tile_size += completed_tile_size;
1352 Ok(())
1353 })();
1354 if let Err(e) = result {
1355 self.handle_error(&e, "write region resources");
1356 }
1357 }
1358
1359 fn put_region_resource_internal(
1360 &mut self,
1361 region_id: i64,
1362 resource: &Resource,
1363 response: &Response,
1364 ) -> DbResult<u64> {
1365 self.check_flags()?;
1366
1367 let mut size = self.put_internal(resource, response, false)?.1;
1368 if response.not_modified {
1369 size = self.has_internal(resource)?.map_or(0, |(stored, _)| stored as u64);
1371 }
1372 self.mark_used(region_id, resource)?;
1373 Ok(size)
1374 }
1375
1376 fn mark_used(&mut self, region_id: i64, resource: &Resource) -> DbResult<()> {
1378 self.check_flags()?;
1379
1380 if let Some(tile) = tile_data(resource) {
1381 self.execute(
1382 "INSERT OR IGNORE INTO region_tiles (region_id, tile_id) \
1383 SELECT ?1, tiles.id \
1384 FROM tiles \
1385 WHERE url_template = ?2 \
1386 AND pixel_ratio = ?3 \
1387 AND x = ?4 \
1388 AND y = ?5 \
1389 AND z = ?6 ",
1390 params![region_id, tile.url_template, tile.pixel_ratio, tile.x, tile.y, tile.z],
1391 )?;
1392 } else {
1393 self.execute(
1394 "INSERT OR IGNORE INTO region_resources (region_id, resource_id) \
1395 SELECT ?1, resources.id \
1396 FROM resources \
1397 WHERE resources.url = ?2 ",
1398 params![region_id, Self::cache_key(resource)],
1399 )?;
1400 }
1401 Ok(())
1402 }
1403
1404 #[cfg(test)]
1405 pub(crate) fn get_region_definition(&mut self, region_id: i64) -> Result<OfflineRegionDefinition, DatabaseError> {
1406 let result = (|| -> DbResult<OfflineRegionDefinition> {
1407 let definition = self
1409 .query_row("SELECT definition FROM regions WHERE id = ?1", params![region_id], |row| {
1410 text_or_blob(row, 0)
1411 })?
1412 .unwrap_or_default();
1413
1414 Ok(decode_offline_region_definition(&definition)?)
1415 })();
1416 self.expected(result, "load region")
1417 }
1418
1419 pub fn get_region_completed_status(&mut self, region_id: i64) -> Result<OfflineRegionStatus, DatabaseError> {
1420 let result = (|| -> DbResult<OfflineRegionStatus> {
1421 let mut result = OfflineRegionStatus::default();
1422
1423 let (count, size) = self.get_completed_resource_count_and_size(region_id)?;
1424 result.completed_resource_count = count as u64;
1425 result.completed_resource_size = size as u64;
1426 let (count, size) = self.get_completed_tile_count_and_size(region_id)?;
1427 result.completed_tile_count = count as u64;
1428 result.completed_tile_size = size as u64;
1429
1430 result.completed_resource_count += result.completed_tile_count;
1431 result.completed_resource_size += result.completed_tile_size;
1432
1433 Ok(result)
1434 })();
1435 self.expected(result, "get region status")
1436 }
1437
1438 fn get_completed_resource_count_and_size(&mut self, region_id: i64) -> DbResult<(i64, i64)> {
1439 Ok(self
1440 .query_row(
1441 "SELECT COUNT(*), IFNULL(SUM(LENGTH(data)), 0) \
1442 FROM region_resources, resources \
1443 WHERE region_id = ?1 \
1444 AND resource_id = resources.id ",
1445 params![region_id],
1446 |row| Ok((row.get(0)?, row.get(1)?)),
1447 )?
1448 .unwrap_or_default())
1449 }
1450
1451 fn get_completed_tile_count_and_size(&mut self, region_id: i64) -> DbResult<(i64, i64)> {
1452 Ok(self
1453 .query_row(
1454 "SELECT COUNT(*), IFNULL(SUM(LENGTH(data)), 0) \
1455 FROM region_tiles, tiles \
1456 WHERE region_id = ?1 \
1457 AND tile_id = tiles.id ",
1458 params![region_id],
1459 |row| Ok((row.get(0)?, row.get(1)?)),
1460 )?
1461 .unwrap_or_default())
1462 }
1463
1464 fn evict(
1479 &mut self,
1480 needed_free_size: u64,
1481 stats: &DatabaseSizeChangeStats,
1482 apply_accessed: bool,
1483 ) -> DbResult<bool> {
1484 self.check_flags()?;
1485 let ambient_cache_size = if self.init_ambient_cache_size()?.is_none() {
1486 self.current_ambient_cache_size.expect("initialized ambient cache size")
1487 } else {
1488 self.maximum_ambient_cache_size
1489 };
1490 let mut new_ambient_cache_size =
1491 ambient_cache_size.wrapping_add(needed_free_size).wrapping_add(stats.page_size());
1492
1493 if apply_accessed
1494 && new_ambient_cache_size > self.maximum_ambient_cache_size
1495 && self.pending_accessed_count() > 0
1496 {
1497 self.apply_pending_accessed()?;
1498 self.pending_applied_for_eviction = true;
1499 }
1500 while new_ambient_cache_size > self.maximum_ambient_cache_size {
1501 let accessed = self.query_row(
1502 "SELECT max(accessed) \
1503 FROM ( \
1504 SELECT accessed \
1505 FROM resources \
1506 LEFT JOIN region_resources \
1507 ON resource_id = resources.id \
1508 WHERE resource_id IS NULL \
1509 UNION ALL \
1510 SELECT accessed \
1511 FROM tiles \
1512 LEFT JOIN region_tiles \
1513 ON tile_id = tiles.id \
1514 WHERE tile_id IS NULL \
1515 ORDER BY accessed ASC LIMIT ?1 \
1516 ) ",
1517 params![50],
1518 |row| Ok(row.get::<_, Option<i64>>(0)?),
1519 )?;
1520 let Some(accessed) = accessed.flatten() else {
1521 return Ok(false);
1522 };
1523
1524 let resource_changes = self.execute(
1525 "DELETE FROM resources \
1526 WHERE id IN ( \
1527 SELECT id FROM resources \
1528 LEFT JOIN region_resources \
1529 ON resource_id = resources.id \
1530 WHERE resource_id IS NULL \
1531 AND accessed <= ?1 \
1532 ) ",
1533 params![accessed],
1534 )?;
1535
1536 let tile_changes = self.execute(
1537 "DELETE FROM tiles \
1538 WHERE id IN ( \
1539 SELECT id FROM tiles \
1540 LEFT JOIN region_tiles \
1541 ON tile_id = tiles.id \
1542 WHERE tile_id IS NULL \
1543 AND accessed <= ?1 \
1544 ) ",
1545 params![accessed],
1546 )?;
1547
1548 let released = stats.bytes_released(self)?;
1551 new_ambient_cache_size = (new_ambient_cache_size as i64).wrapping_sub(released as i64).max(0) as u64;
1552
1553 if resource_changes == 0 && tile_changes == 0 {
1557 return Ok(false);
1558 }
1559 }
1560
1561 Ok(true)
1562 }
1563
1564 fn init_ambient_cache_size(&mut self) -> DbResult<Option<DatabaseError>> {
1567 if self.current_ambient_cache_size.is_none() {
1568 let size = self.query_row(
1569 "SELECT SUM(data) \
1570 FROM ( \
1571 SELECT SUM(IFNULL(LENGTH(data), 0) \
1572 + IFNULL(LENGTH(id), 0) \
1573 + IFNULL(LENGTH(url_template), 0) \
1574 + IFNULL(LENGTH(pixel_ratio), 0) \
1575 + IFNULL(LENGTH(x), 0) \
1576 + IFNULL(LENGTH(y), 0) \
1577 + IFNULL(LENGTH(z), 0) \
1578 + IFNULL(LENGTH(expires), 0) \
1579 + IFNULL(LENGTH(modified), 0) \
1580 + IFNULL(LENGTH(etag), 0) \
1581 + IFNULL(LENGTH(compressed), 0) \
1582 + IFNULL(LENGTH(accessed), 0) \
1583 + IFNULL(LENGTH(must_revalidate), 0) \
1584 ) as data \
1585 FROM tiles \
1586 LEFT JOIN region_tiles \
1587 ON tile_id = tiles.id \
1588 WHERE tile_id IS NULL \
1589 UNION ALL \
1590 SELECT SUM(IFNULL(LENGTH(data), 0) \
1591 + IFNULL(LENGTH(id), 0) \
1592 + IFNULL(LENGTH(url), 0) \
1593 + IFNULL(LENGTH(kind), 0) \
1594 + IFNULL(LENGTH(expires), 0) \
1595 + IFNULL(LENGTH(modified), 0) \
1596 + IFNULL(LENGTH(etag), 0) \
1597 + IFNULL(LENGTH(compressed), 0) \
1598 + IFNULL(LENGTH(accessed), 0) \
1599 + IFNULL(LENGTH(must_revalidate), 0) \
1600 ) as data \
1601 FROM resources \
1602 LEFT JOIN region_resources \
1603 ON resource_id = resources.id \
1604 WHERE resource_id IS NULL \
1605 ) ",
1606 [],
1607 |row| Ok(row.get::<_, Option<i64>>(0)?),
1608 );
1609 match size {
1610 Ok(size) => self.current_ambient_cache_size = Some(size.flatten().unwrap_or(0) as u64),
1611 Err(e @ DatabaseError::Sqlite { .. }) => {
1612 self.handle_error(&e, "cannot get current ambient cache size");
1613 return Ok(Some(e));
1614 }
1615 Err(e) => return Err(e),
1616 }
1617 }
1618
1619 Ok(None)
1620 }
1621
1622 pub(crate) fn set_maximum_ambient_cache_size(&mut self, size: u64) -> Option<DatabaseError> {
1623 self.flush_accessed();
1625 let previous_maximum_ambient_cache_size = self.maximum_ambient_cache_size;
1626
1627 match self.init_ambient_cache_size() {
1629 Ok(Some(exception)) | Err(exception) => return Some(exception),
1630 Ok(None) => {}
1631 }
1632
1633 let result = (|| -> DbResult<()> {
1634 self.maximum_ambient_cache_size = size;
1635
1636 if self.current_ambient_cache_size.expect("initialized ambient cache size")
1637 > self.maximum_ambient_cache_size
1638 {
1639 let stats = DatabaseSizeChangeStats::new(self)?;
1640 self.evict(0, &stats, false)?;
1641 if self.autopack {
1642 self.vacuum()?;
1643 }
1644 self.update_ambient_cache_size(&stats)?;
1645 }
1646
1647 Ok(())
1648 })();
1649 match result {
1650 Ok(()) => None,
1651 Err(e) => {
1652 self.maximum_ambient_cache_size = previous_maximum_ambient_cache_size;
1653 self.handle_error(&e, "set maximum ambient cache size");
1654 Some(e)
1655 }
1656 }
1657 }
1658
1659 pub fn mark_used_resources(&mut self, region_id: i64, resources: &[Resource]) {
1660 let result = (|| -> DbResult<()> {
1661 if self.db.is_none() {
1662 self.initialize()?;
1663 }
1664 self.with_transaction(Begin::Deferred, |this| {
1665 for resource in resources {
1666 this.mark_used(region_id, resource)?;
1667 }
1668 Ok(())
1669 })
1670 })();
1671 if let Err(e) = result {
1672 self.handle_error(&e, "mark resources as used");
1673 }
1674 }
1675
1676 pub(crate) fn pack(&mut self) -> Option<DatabaseError> {
1677 let result = (|| -> DbResult<()> {
1678 if self.db.is_none() {
1679 self.initialize()?;
1680 }
1681 self.vacuum()
1682 })();
1683 self.exception_ptr(result, "pack storage")
1684 }
1685
1686 #[cfg(test)]
1687 pub(crate) fn run_pack_database_automatically(&mut self, autopack: bool) {
1688 self.autopack = autopack;
1689 }
1690
1691 pub(crate) fn reopen_database_read_only(&mut self, read_only: bool) {
1692 if self.read_only == read_only {
1693 return;
1694 }
1695 self.cleanup();
1696 self.read_only = read_only;
1697 if let Err(e) = self.initialize() {
1698 self.handle_error(&e, "reopen database read-only");
1699 }
1700 }
1701
1702 pub(crate) fn reset_database(&mut self) -> Option<DatabaseError> {
1705 let result = self.remove_existing().and_then(|()| self.initialize());
1706 self.exception_ptr(result, "reset database")
1707 }
1708
1709 fn update_ambient_cache_size(&mut self, stats: &DatabaseSizeChangeStats) -> DbResult<()> {
1710 debug_assert!(self.current_ambient_cache_size.is_some());
1711 if let Some(current) = self.current_ambient_cache_size {
1712 let diff = stats.diff(self)?;
1713 self.current_ambient_cache_size = Some((current as i64).wrapping_add(diff).max(0) as u64);
1714 }
1715 Ok(())
1716 }
1717}
1718
1719#[derive(Clone, Copy)]
1721enum Begin {
1722 Deferred,
1723 Immediate,
1724}
1725
1726impl Begin {
1727 fn sql(self) -> &'static str {
1728 match self {
1729 Begin::Deferred => "BEGIN DEFERRED TRANSACTION",
1730 Begin::Immediate => "BEGIN IMMEDIATE TRANSACTION",
1731 }
1732 }
1733}
1734
1735fn exec(conn: &Connection, sql: &str) -> rusqlite::Result<()> {
1739 use rusqlite::fallible_iterator::FallibleIterator as _;
1740
1741 let mut batch = rusqlite::Batch::new(conn, sql);
1742 while let Some(mut stmt) = batch.next()? {
1743 let mut rows = stmt.raw_query();
1744 while rows.next()?.is_some() {}
1745 }
1746 Ok(())
1747}
1748
1749fn text_or_blob(row: &Row<'_>, index: usize) -> DbResult<Vec<u8>> {
1752 Ok(row.get_ref(index)?.as_bytes_or_null()?.unwrap_or_default().to_vec())
1753}
1754
1755fn metadata_blob(metadata: &OfflineRegionMetadata) -> Option<&[u8]> {
1758 if metadata.is_empty() { None } else { Some(metadata.as_slice()) }
1759}