Skip to content

Commit 793a121

Browse files
committed
add SQLite3::Database#db_filename
Returns the file associated with +database_name+. Can return nil or an empty string if the database is temporary, or in-memory.
1 parent 6a1ce90 commit 793a121

File tree

2 files changed

+30
-0
lines changed

2 files changed

+30
-0
lines changed

ext/sqlite3/database.c

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -795,6 +795,24 @@ static VALUE transaction_active_p(VALUE self)
795795
return sqlite3_get_autocommit(ctx->db) ? Qfalse : Qtrue;
796796
}
797797

798+
/* call-seq: db.db_filename(database_name)
799+
*
800+
* Returns the file associated with +database_name+. Can return nil or an
801+
* empty string if the database is temporary, or in-memory.
802+
*/
803+
static VALUE db_filename(VALUE self, VALUE db_name)
804+
{
805+
sqlite3RubyPtr ctx;
806+
const char * fname;
807+
Data_Get_Struct(self, sqlite3Ruby, ctx);
808+
REQUIRE_OPEN_DB(ctx);
809+
810+
fname = sqlite3_db_filename(ctx->db, StringValueCStr(db_name));
811+
812+
if(fname) return SQLITE3_UTF8_STR_NEW2(fname);
813+
return Qnil;
814+
}
815+
798816
void init_sqlite3_database()
799817
{
800818
ID id_utf16, id_results_as_hash, id_type_translation;
@@ -822,6 +840,7 @@ void init_sqlite3_database()
822840
rb_define_method(cSqlite3Database, "busy_handler", busy_handler, -1);
823841
rb_define_method(cSqlite3Database, "busy_timeout=", set_busy_timeout, 1);
824842
rb_define_method(cSqlite3Database, "transaction_active?", transaction_active_p, 0);
843+
rb_define_method(cSqlite3Database, "db_filename", db_filename, 1);
825844

826845
#ifdef HAVE_SQLITE3_LOAD_EXTENSION
827846
rb_define_method(cSqlite3Database, "load_extension", load_extension, 1);

test/test_database.rb

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,17 +1,28 @@
11
require 'helper'
2+
require 'tempfile'
23

34
module SQLite3
45
class TestDatabase < SQLite3::TestCase
56
attr_reader :db
67

78
def setup
89
@db = SQLite3::Database.new(':memory:')
10+
super
911
end
1012

1113
def test_segv
1214
assert_raises(TypeError) { SQLite3::Database.new 1 }
1315
end
1416

17+
def test_db_filename
18+
assert_equal '', @db.db_filename('main')
19+
tf = Tempfile.new
20+
@db = SQLite3::Database.new tf.path
21+
assert_equal tf.path, @db.db_filename('main')
22+
ensure
23+
tf.unlink
24+
end
25+
1526
def test_bignum
1627
num = 4907021672125087844
1728
db.execute 'CREATE TABLE "employees" ("token" integer(8), "name" varchar(20) NOT NULL)'

0 commit comments

Comments
 (0)