Skip to content

Instantly share code, notes, and snippets.

@Anonyfox
Created January 8, 2013 11:55
Show Gist options
  • Save Anonyfox/4483202 to your computer and use it in GitHub Desktop.
Save Anonyfox/4483202 to your computer and use it in GitHub Desktop.
Trying to get activerecord use sqlite3's shared_cache
# encoding: utf-8
require "active_record"
#require "activerecord-jdbcsqlite3-adapter" # gem install this, but not require
require 'activerecord-jdbc-adapter'
# a very basic migration
class CreateSamplesTable < ActiveRecord::Migration
def change
create_table :samples do |t|
t.integer :num
end
end
end
# minimal class
class Sample < ActiveRecord::Base
end
# connect to the database
ActiveRecord::Base.establish_connection(
:adapter => 'jdbcsqlite3',
#:adapter => 'sqlite3',
:database => ":memory:",
#:url => "jdbc:sqlite:file::memory:;cache=shared",
#:cache => "shared",
#:database => "db_file",
#url: "jdbc:sqlite::memory:",
:wait_timeout => 1,
:timeout => 250,
#:reconnect => true,
:encoding => "utf-8",
:pool => 10
)
# migrate
CreateSamplesTable.migrate :up unless Sample.table_exists?
# populate the table
Sample.create num: 17 if Sample.all.empty?
Thread.new do
# output the same.
# without the shared cache this will throw an error
# because every thread rebuilds the database
begin
puts "number of samples: #{Sample.count}"
rescue => e
puts "ERROR from Thread: #{e.message}"
end
end
# output. should be 1 since its the main thread
puts "number of samples: #{Sample.count}"
sleep 5 # let the thread finish before exit
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment