-
Notifications
You must be signed in to change notification settings - Fork 7
Expand file tree
/
Copy pathstoring_uuids_as_binaries.rb
More file actions
88 lines (67 loc) · 2.13 KB
/
storing_uuids_as_binaries.rb
File metadata and controls
88 lines (67 loc) · 2.13 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
# See README for comparison between string and binary storage.
ENV["DB"] ||= "sqlite3"
if ENV["DB"] == "postgresql"
puts <<~MESSAGE
Example irrelevant for selected database (#{ENV['DB']}).
Storing UUIDs as binaries is not compatible with PostgreSQL adapter.
MESSAGE
exit(0)
end
require "bundler/setup"
Bundler.require :development
require "activeid"
require_relative "../spec/support/0_logger"
require_relative "../spec/support/1_db_connection"
#### SCHEMA ####
ActiveRecord::Schema.define do
create_table :works, id: false, force: true do |t|
t.binary :id, limit: 16, primary_key: true
t.binary :author_id, limit: 16, index: true
t.string :title
t.timestamps
end
create_table :authors, id: false, force: true do |t|
t.binary :id, limit: 16, primary_key: true
t.string :name
t.timestamps
end
end
#### MODELS ####
class Work < ActiveRecord::Base
include ActiveID::Model
attribute :id, ActiveID::Type::BinaryUUID.new
attribute :author_id, ActiveID::Type::BinaryUUID.new
belongs_to :author
end
class Author < ActiveRecord::Base
include ActiveID::Model
attribute :id, ActiveID::Type::BinaryUUID.new
has_many :works
end
#### PROOF ####
SolidAssert.enable_assertions
poe = Author.create! name: "Edgar Alan Poe"
thu = Author.create! name: "Thucydides"
Work.create! title: "The Raven", author: poe
Work.create! title: "The Black Cat", author: poe
Work.create! title: "History of the Peloponnesian War", author: thu
assert Author.count == 2
assert Work.count == 3
assert Author.find_by(name: "Edgar Alan Poe").works.size == 2
assert Author.find_by(name: "Thucydides").works.size == 1
assert UUIDTools::UUID === Author.first.id
assert UUIDTools::UUID === Work.first.id
assert UUIDTools::UUID === Work.first.author_id
# Version 4 means randomly generated UUID
assert Author.first.id.version == 4
# UUIDs are stored in database as 16 bytes long binaries
raw_id = Author.first.attributes_before_type_cast["id"]
assert raw_id.bytes.size == 16
#### PROVE THAT ASSERTIONS WERE WORKING ####
begin
assert 1 == 2
rescue SolidAssert::AssertionFailedError
puts "All OK."
else
raise "Assertions do not work!"
end