Skip to content

Commit

Permalink
fix: update slug size after 2nd attemp
Browse files Browse the repository at this point in the history
  • Loading branch information
sjdonado committed Jul 14, 2024
1 parent 451a5fb commit ab647e6
Show file tree
Hide file tree
Showing 2 changed files with 53 additions and 2 deletions.
6 changes: 4 additions & 2 deletions app/controllers/link.cr
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down
49 changes: 49 additions & 0 deletions db/migrations/20240714215409_update_slug_size_links.sql
Original file line number Diff line number Diff line change
@@ -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;

0 comments on commit ab647e6

Please sign in to comment.