From ab647e6233da84656632fcb3ea915637a0ec8a8e Mon Sep 17 00:00:00 2001 From: Juan Rodriguez Date: Sun, 14 Jul 2024 21:56:04 +0200 Subject: [PATCH] fix: update slug size after 2nd attemp --- app/controllers/link.cr | 6 ++- .../20240714215409_update_slug_size_links.sql | 49 +++++++++++++++++++ 2 files changed, 53 insertions(+), 2 deletions(-) create mode 100644 db/migrations/20240714215409_update_slug_size_links.sql diff --git a/app/controllers/link.cr b/app/controllers/link.cr index 077d8d4..1feb807 100644 --- a/app/controllers/link.cr +++ b/app/controllers/link.cr @@ -27,12 +27,14 @@ module App::Controllers::Link link.url = url link.user = user + attempts = 0 loop do - slug = Random::Secure.urlsafe_base64(5).gsub(/[^a-zA-Z0-9]/, "") - if !Database.get_by(Link, slug: slug) + slug = Random::Secure.urlsafe_base64(attempts >= 2 ? 6 : 5).gsub(/[^a-zA-Z0-9]/, "") + unless Database.get_by(Link, slug: slug) link.slug = slug break end + attempts += 1 end changeset = Database.insert(link) diff --git a/db/migrations/20240714215409_update_slug_size_links.sql b/db/migrations/20240714215409_update_slug_size_links.sql new file mode 100644 index 0000000..d6842b4 --- /dev/null +++ b/db/migrations/20240714215409_update_slug_size_links.sql @@ -0,0 +1,49 @@ +-- +micrate Up +-- SQL in section 'Up' is executed when this migration is applied + +-- Step 1: Create a new table with the desired column type +CREATE TABLE links_new ( + id TEXT PRIMARY KEY NOT NULL, + user_id TEXT NOT NULL, + slug VARCHAR(8) UNIQUE NOT NULL, + url TEXT NOT NULL, + created_at INTEGER DEFAULT CURRENT_TIMESTAMP NOT NULL, + updated_at INTEGER DEFAULT CURRENT_TIMESTAMP NOT NULL, + + FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE +); + +-- Step 2: Copy data from the old table to the new table +INSERT INTO links_new (id, user_id, slug, url, created_at, updated_at) +SELECT id, user_id, slug, url, created_at, updated_at FROM links; + +-- Step 3: Drop the old table +DROP TABLE links; + +-- Step 4: Rename the new table to the old table's name +ALTER TABLE links_new RENAME TO links; + +-- +micrate Down +-- SQL section 'Down' is executed when this migration is rolled back + +-- Step 1: Create a new table with the original column type +CREATE TABLE links_old ( + id TEXT PRIMARY KEY NOT NULL, + user_id TEXT NOT NULL, + slug VARCHAR(4) UNIQUE NOT NULL, + url TEXT NOT NULL, + created_at INTEGER DEFAULT CURRENT_TIMESTAMP NOT NULL, + updated_at INTEGER DEFAULT CURRENT_TIMESTAMP NOT NULL, + + FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE +); + +-- Step 2: Copy data from the current table to the old table +INSERT INTO links_old (id, user_id, slug, url, created_at, updated_at) +SELECT id, user_id, substr(slug, 1, 4), url, created_at, updated_at FROM links; + +-- Step 3: Drop the current table +DROP TABLE links; + +-- Step 4: Rename the old table to the current table's name +ALTER TABLE links_old RENAME TO links;