提交 9a4e183f 编写于 作者: A Aaron Patterson

add a truncate method to the connection

it doesn't work on SQLite3 since it doesn't support truncate, but that's
OK.  If you call truncate on the connection, you're now bound to that
database (same as if you use hstore or any other db specific feature).
上级 53a8a7f9
* Add a truncate method to the connection.
* Don't autosave unchanged has_one through records.
*Alan Kennedy*, *Steve Parrington*
......
......@@ -83,6 +83,11 @@ def exec_delete(sql, name, binds)
exec_query(sql, name, binds)
end
# Executes the truncate statement.
def truncate(table_name, name = nil)
raise NotImplementedError
end
# Executes update +sql+ statement in the context of this connection using
# +binds+ as the bind substitutes. +name+ is logged along with
# the executed +sql+ statement.
......
......@@ -389,6 +389,10 @@ def tables(name = nil, database = nil, like = nil) #:nodoc:
end
end
def truncate(table_name, name = nil)
execute "TRUNCATE TABLE #{quote_table_name(table_name)}", name
end
def table_exists?(name)
return false unless name.present?
return true if tables(nil, nil, name).any?
......
......@@ -255,6 +255,10 @@ def clear_cache!
@statements.clear
end
def truncate(table_name, name = nil)
exec_query "TRUNCATE TABLE #{quote_table_name(table_name)}", name, []
end
# Is this connection alive and ready for queries?
def active?
@connection.query 'SELECT 1'
......
......@@ -4,6 +4,8 @@
class MysqlConnectionTest < ActiveRecord::TestCase
include ConnectionHelper
fixtures :comments
def setup
super
@subscriber = SQLSubscriber.new
......@@ -24,6 +26,17 @@ def test_bad_connection
end
end
def test_truncate
rows = ActiveRecord::Base.connection.exec_query("select count(*) from comments")
count = rows.first.values.first
assert_operator count, :>, 0
ActiveRecord::Base.connection.truncate("comments")
rows = ActiveRecord::Base.connection.exec_query("select count(*) from comments")
count = rows.first.values.first
assert_equal 0, count
end
def test_no_automatic_reconnection_after_timeout
assert @connection.active?
@connection.update('set @@wait_timeout=1')
......
......@@ -8,6 +8,8 @@ class PostgresqlConnectionTest < ActiveRecord::TestCase
class NonExistentTable < ActiveRecord::Base
end
fixtures :comments
def setup
super
@subscriber = SQLSubscriber.new
......@@ -20,6 +22,14 @@ def teardown
super
end
def test_truncate
count = ActiveRecord::Base.connection.execute("select count(*) from comments").first['count'].to_i
assert_operator count, :>, 0
ActiveRecord::Base.connection.truncate("comments")
count = ActiveRecord::Base.connection.execute("select count(*) from comments").first['count'].to_i
assert_equal 0, count
end
def test_encoding
assert_not_nil @connection.encoding
end
......
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册