diff --git a/migrations/0_init_schema.sql b/migrations/0_init_schema.sql index d358fbc..8de8871 100644 --- a/migrations/0_init_schema.sql +++ b/migrations/0_init_schema.sql @@ -8,7 +8,7 @@ CREATE TABLE IF NOT EXISTS questions ( -- Create tags table CREATE TABLE IF NOT EXISTS tags ( id SERIAL PRIMARY KEY, - label TEXT NOT NULL + label TEXT UNIQUE NOT NULL ); -- Create question_tag table diff --git a/src/pg_store.rs b/src/pg_store.rs index ce64b59..9e6e2b8 100644 --- a/src/pg_store.rs +++ b/src/pg_store.rs @@ -72,13 +72,14 @@ impl Store { } } + // Add new tags to tags table, only if tags with existing label do not exist pub async fn _add_tags(&mut self, tag_labels: Vec) -> Result, String> { let insert_values: Vec = tag_labels .iter() .map(|label| format!("({}),", label)) .collect(); - - let result = sqlx::query("INSERT INTO tags (label) VALUES $1 RETURNING id, label") + let query = "INSERT INTO tags (label) VALUES $1 ON CONFLICT (label) DO NOTHING RETURNING *" + let result = sqlx::query(query) .bind(insert_values) .fetch_all(&self.connection) .await; @@ -190,13 +191,6 @@ impl Store { } } - /// Creates passed in tag labels in the tags table, only if they do not already exists - /// Returns list of all tags from passed in labels, regardless of if they already existed - pub fn _add_tags_if_not_exists(&mut self, _tags_labels: Vec) { - todo!() - } - - /// pub fn _sync_question_tags(&mut self, _tags: Vec) { todo!() }