LoginSignup
2
2

More than 3 years have passed since last update.

UUIDをHashidsに変換して戻してみた。

Posted at

目的

DBでUUIDで生成したキーをもとにテーブル分割すると「table_dd6ee086-936c-4dae-bbd7-f94e4203d868」みたいに長くなるのが嫌でなんとか短くしたいです。
base64とかやってみたけど「+,/,=」みたいな記号のハンドリングがめんどくさかったです。
そこでhashidsという数値とアルファベットだけで変換してくれるライブラリがあったのでこれを使いました。
RustとRubyとPostgreSQLで使いたかったので、それぞれ試してみました。

コード

Rust

Cargo.toml
[package]
name = "test"
version = "0.1.0"
edition = "2018"

[dependencies]
uuid = { version = "^0.8", features = ["v4"] }
harsh = "^0.1"
main.rs
fn main() {
    let converter = harsh::HarshBuilder::new().salt("salt goes here!").init().unwrap();
    let my_uuid = uuid::Uuid::new_v4();
    println!("{}", my_uuid);
    let target = converter.encode_hex(&my_uuid.to_simple().to_string()).unwrap();
    println!("{}", target);
    let my_uuid = uuid::Uuid::parse_str(&converter.decode_hex(&target).unwrap()).unwrap();
    println!("{}", my_uuid);
}

Ruby

Gemfile
# frozen_string_literal: true

source "https://rubygems.org"

git_source(:github) {|repo_name| "https://github.com/#{repo_name}" }

gem "hashids"
main.rb
require 'securerandom'
require 'hashids'

uuid = SecureRandom.uuid
puts uuid
hashids = Hashids.new "this is my salt"
id = hashids.encode_hex(uuid.gsub(/-/,""))
puts id
decoded = hashids.decode_hex(id).downcase
uuid = "#{decoded[0..7]}-#{decoded[8..11]}-#{decoded[12..15]}-#{decoded[16..19]}-#{decoded[20..35]}"
puts uuid

PostgreSQL

select 
    t3.src
    ,t3.simple
    ,t3.id
    ,hashids.decode_hex(id := t3.id, salt := 'salt')::uuid as dst
from (
select 
    t2.src
    ,t2.simple
    ,hashids.encode_hex(hex := t2.simple, salt := 'salt') as id
from 
(
select
    t1.src
    ,regexp_replace(t1.src::text, '-', '', 'g') as simple
from (
 select gen_random_uuid() as src
) as t1
) as t2
) as t3

結果

3f44b2e6-d6c4-4d2e-9956-bb56bfd58032
gyBm1Kw7M9u8Ral478g6ixxRXZrB
3f44b2e6-d6c4-4d2e-9956-bb56bfd58032

ハイフンを抜くと4文字しか得しませんね😇

参考

hashids
PL/pgSQL implementation of Hashids

2
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
2