Skip to content
Browse files

Create sqlite3 directory if not present

If the `db/` directory is not present on a remote machine it will blow up in unexpected ways with error messages that do not indicate there is a missing directory:

```
SQLite3::CantOpenException: unable to open database file
```

This PR checks to see if a directory exists for the sqlite3 file and if not creates it for you.

This PR is an alternative to #11692 as suggested by @josevalim
  • Loading branch information...
1 parent 3baee09 commit f036239447c79843983ee1c0d3dfe68484d63203 @schneems schneems committed Aug 5, 2013
View
4 activerecord/CHANGELOG.md
@@ -1,3 +1,7 @@
+* Create a directory for sqlite3 file if not present on the system.
+
+ *Richard Schneeman*
+
* Removed redundant override of `xml` column definition for PG,
in order to use `xml` column type instead of `text`.
View
8 activerecord/lib/active_record/connection_adapters/sqlite3_adapter.rb
@@ -17,12 +17,14 @@ def sqlite3_connection(config)
# Allow database path relative to Rails.root, but only if
# the database path is not the special path that tells
# Sqlite to build a database only in memory.
- if defined?(Rails.root) && ':memory:' != config[:database]
- config[:database] = File.expand_path(config[:database], Rails.root)
+ if ':memory:' != config[:database]
+ config[:database] = Pathname.new(config[:database])
+ config[:database] = config[:database].expand_path(Rails.root) if defined?(Rails.root)
+ config[:database].dirname.mkdir unless config[:database].dirname.directory?
end
db = SQLite3::Database.new(
- config[:database],
+ config[:database].to_s,
:results_as_hash => true
)
View
21 activerecord/test/cases/adapters/sqlite3/sqlite3_create_folder_test.rb
@@ -0,0 +1,21 @@
+# encoding: utf-8
+require "cases/helper"
+require 'models/owner'
+
+module ActiveRecord
+ module ConnectionAdapters
+ class SQLite3CreateFolder < ActiveRecord::TestCase
+ def test_sqlite_creates_directory
+ Dir.mktmpdir do |dir|
+ dir = Pathname.new(dir)
+ @conn = Base.sqlite3_connection :database => dir.join("db/foo.sqlite3"),
+ :adapter => 'sqlite3',
+ :timeout => 100
+
+ assert Dir.exists? dir.join('db')
+ assert File.exist? dir.join('db/foo.sqlite3')
+ end
+ end
+ end
+ end
+end

0 comments on commit f036239

Please sign in to comment.
Something went wrong with that request. Please try again.