Skip to content

Commit

Permalink
Implemented table name rewriting to ensure queries use the configured…
Browse files Browse the repository at this point in the history
… table prefix.
  • Loading branch information
artob committed Oct 8, 2010
1 parent da3ba88 commit d98852d
Showing 1 changed file with 19 additions and 9 deletions.
28 changes: 19 additions & 9 deletions lib/opencoinage/wallet/database.rb
Original file line number Diff line number Diff line change
Expand Up @@ -218,9 +218,7 @@ def empty?
# @return [void]
# @see http://rdoc.info/github/luislavena/sqlite3-ruby/master/SQLite3/Database#execute-instance_method
def execute(sql, *args, &block)
prefix = (options[:prefix] || DEFAULT_TABLE_PREFIX).to_s
# TODO: rewrite table names in the query
@db.execute(sql, *args, &block)
@db.execute(rewrite_table_names(sql), *args, &block)
end

##
Expand All @@ -231,9 +229,7 @@ def execute(sql, *args, &block)
# @return [void]
# @see http://rdoc.info/github/luislavena/sqlite3-ruby/master/SQLite3/Database#execute_batch-instance_method
def execute_batch(sql, *args, &block)
prefix = (options[:prefix] || DEFAULT_TABLE_PREFIX).to_s
# TODO: rewrite table names in the query
@db.execute_batch(sql, *args, &block)
@db.execute_batch(rewrite_table_names(sql), *args, &block)
end

##
Expand Down Expand Up @@ -325,6 +321,20 @@ def tokens(options = {}, &block)

protected

##
# Rewrites table names in the given SQL query to include the table
# prefix configured for this database.
#
# @example
# db.rewrite_table_names('SELECT * FROM {currency}') #=> 'SELECT * FROM opencoinage_currency'
#
# @param [String] sql
# @return [String]
def rewrite_table_names(sql)
prefix = (options[:prefix] || DEFAULT_TABLE_PREFIX).to_s
sql.gsub(/{([^}]+)}/) { |match| prefix + match[1...-1] }
end

##
# Initializes the database connection.
#
Expand Down Expand Up @@ -383,15 +393,15 @@ def self.upgrade(db, from = 0, to = CURRENT_VERSION)
end

UPGRADE_1 = <<-EOS
CREATE TABLE issuers (
CREATE TABLE {issuer} (
id INTEGER PRIMARY KEY AUTOINCREMENT,
uri TEXT NOT NULL
);
CREATE TABLE currencies (
CREATE TABLE {currency} (
id INTEGER PRIMARY KEY AUTOINCREMENT,
uri TEXT NOT NULL
);
CREATE TABLE tokens (
CREATE TABLE {token} (
id INTEGER PRIMARY KEY AUTOINCREMENT,
data BLOB NOT NULL UNIQUE,
amount NUMERIC DEFAULT NULL,
Expand Down

0 comments on commit d98852d

Please sign in to comment.