Skip to content

Using uuid data type

hsgubert edited this page Jul 21, 2013 · 1 revision

Create a test table

rails generate cassandra_migration create_posts

In your migration file, make it create a table and drop it on its way back:

class CreatePosts < CassandraMigrations::Migration
  def up
    create_table :posts do |p|
      p.uuid :id, :primary_key => true
      p.timestamp :created_at
      p.string :title
      p.text :text
    end
  end
  
  def self.down
    drop_table :posts
  end
end

And now run:

rake cassandra:migrate 

Writing/retrieving data

To write uuid's it is necessary to use a Cql::Uuid as a value. This class enables you to create uuid's from strings or numbers, or the other way around, as following:

Cql:Uuid.new('12345678-1234-1234-1234-1234567890ab') # => 12345678-1234-1234-1234-1234567890ab
uuid = Cql:Uuid.new(123) # => 00000000-0000-0000-0000-00000000007b

uuid.to_s # => "00000000-0000-0000-0000-00000000007b"
uuid.value # => 123

So to write your record:

CassandraMigrations::Cassandra.write!(:posts, {
  :id => Cql::Uuid.new("00000000-0000-0000-0000-00000000007b"),
  :created_at => Time.current,
  :title => 'My new post',
  :text => 'lorem ipsum dolor sit amet.'
})

And to retrieve your record:

CassandraMigrations::Cassandra.select(:posts).first['id'].to_s # => "00000000-0000-0000-0000-00000000007b"