refactor(sql): recreate config table with UNIQUE constraint

This commit is contained in:
link2xt
2023-11-30 19:35:50 +00:00
parent 467f313091
commit 58620988d7
2 changed files with 26 additions and 16 deletions

View File

@@ -572,22 +572,13 @@ impl Sql {
pub async fn set_raw_config(&self, key: &str, value: Option<&str>) -> Result<()> { pub async fn set_raw_config(&self, key: &str, value: Option<&str>) -> Result<()> {
let mut lock = self.config_cache.write().await; let mut lock = self.config_cache.write().await;
if let Some(value) = value { if let Some(value) = value {
let exists = self self.execute(
.exists("SELECT COUNT(*) FROM config WHERE keyname=?;", (key,)) "INSERT OR REPLACE INTO config (keyname, value) VALUES (?, ?)",
.await?; (key, value),
)
if exists { .await?;
self.execute("UPDATE config SET value=? WHERE keyname=?;", (value, key))
.await?;
} else {
self.execute(
"INSERT INTO config (keyname, value) VALUES (?, ?);",
(key, value),
)
.await?;
}
} else { } else {
self.execute("DELETE FROM config WHERE keyname=?;", (key,)) self.execute("DELETE FROM config WHERE keyname=?", (key,))
.await?; .await?;
} }
lock.insert(key.to_string(), value.map(|s| s.to_string())); lock.insert(key.to_string(), value.map(|s| s.to_string()));
@@ -608,7 +599,7 @@ impl Sql {
let mut lock = self.config_cache.write().await; let mut lock = self.config_cache.write().await;
let value = self let value = self
.query_get_value("SELECT value FROM config WHERE keyname=?;", (key,)) .query_get_value("SELECT value FROM config WHERE keyname=?", (key,))
.await .await
.context(format!("failed to fetch raw config: {key}"))?; .context(format!("failed to fetch raw config: {key}"))?;
lock.insert(key.to_string(), value.clone()); lock.insert(key.to_string(), value.clone());

View File

@@ -785,6 +785,25 @@ CREATE INDEX msgs_status_updates_index2 ON msgs_status_updates (uid);
.await?; .await?;
} }
if dbversion < 106 {
// Recreate `config` table with UNIQUE constraint on `keyname`.
sql.execute_migration(
"CREATE TABLE new_config (
id INTEGER PRIMARY KEY,
keyname TEXT UNIQUE,
value TEXT NOT NULL
);
INSERT OR IGNORE INTO new_config SELECT
id, keyname, value
FROM config;
DROP TABLE config;
ALTER TABLE new_config RENAME TO config;
CREATE INDEX config_index1 ON config (keyname);",
106,
)
.await?;
}
let new_version = sql let new_version = sql
.get_raw_config_int(VERSION_CFG) .get_raw_config_int(VERSION_CFG)
.await? .await?