Skip to content

Commit 284e0c9

Browse files
committed
refactoring(sql): recreate config table with UNIQUE constraint
1 parent 1c9662a commit 284e0c9

File tree

2 files changed

+28
-16
lines changed

2 files changed

+28
-16
lines changed

src/sql.rs

+7-16
Original file line numberDiff line numberDiff line change
@@ -572,22 +572,13 @@ impl Sql {
572572
pub async fn set_raw_config(&self, key: &str, value: Option<&str>) -> Result<()> {
573573
let mut lock = self.config_cache.write().await;
574574
if let Some(value) = value {
575-
let exists = self
576-
.exists("SELECT COUNT(*) FROM config WHERE keyname=?;", (key,))
577-
.await?;
578-
579-
if exists {
580-
self.execute("UPDATE config SET value=? WHERE keyname=?;", (value, key))
581-
.await?;
582-
} else {
583-
self.execute(
584-
"INSERT INTO config (keyname, value) VALUES (?, ?);",
585-
(key, value),
586-
)
587-
.await?;
588-
}
575+
self.execute(
576+
"INSERT OR REPLACE INTO config (keyname, value) VALUES (?, ?)",
577+
(key, value),
578+
)
579+
.await?;
589580
} else {
590-
self.execute("DELETE FROM config WHERE keyname=?;", (key,))
581+
self.execute("DELETE FROM config WHERE keyname=?", (key,))
591582
.await?;
592583
}
593584
lock.insert(key.to_string(), value.map(|s| s.to_string()));
@@ -608,7 +599,7 @@ impl Sql {
608599

609600
let mut lock = self.config_cache.write().await;
610601
let value = self
611-
.query_get_value("SELECT value FROM config WHERE keyname=?;", (key,))
602+
.query_get_value("SELECT value FROM config WHERE keyname=?", (key,))
612603
.await
613604
.context(format!("failed to fetch raw config: {key}"))?;
614605
lock.insert(key.to_string(), value.clone());

src/sql/migrations.rs

+21
Original file line numberDiff line numberDiff line change
@@ -785,6 +785,27 @@ CREATE INDEX msgs_status_updates_index2 ON msgs_status_updates (uid);
785785
.await?;
786786
}
787787

788+
if dbversion < 106 {
789+
// Recreate `config` table with UNIQUE constraint on `keyname`.
790+
sql.execute_migration(
791+
r#"
792+
CREATE TABLE new_config (
793+
id INTEGER PRIMARY KEY,
794+
keyname TEXT UNIQUE,
795+
value TEXT NOT NULL
796+
);
797+
INSERT OR IGNORE INTO new_config SELECT
798+
id, keyname, value
799+
FROM config;
800+
DROP TABLE config;
801+
ALTER TABLE new_config RENAME TO config;
802+
CREATE INDEX config_index1 ON config (keyname);
803+
"#,
804+
106,
805+
)
806+
.await?;
807+
}
808+
788809
let new_version = sql
789810
.get_raw_config_int(VERSION_CFG)
790811
.await?

0 commit comments

Comments
 (0)