Skip to content

Instantly share code, notes, and snippets.

@fxn
Created April 28, 2024 15:05
Show Gist options
  • Save fxn/a2cc0b23735328abb2803537e9143c3e to your computer and use it in GitHub Desktop.
Save fxn/a2cc0b23735328abb2803537e9143c3e to your computer and use it in GitHub Desktop.
docker run \
-d \
--name=mysql-test-truncation \
-e MYSQL_ROOT_PASSWORD=root \
-e MYSQL_ROOT_HOST=% \
-p 3307:3306 \
mysql/mysql-server:latest
require 'benchmark'
require 'mysql2'
def table(n) = "t#{n}"
# Database name, created if needed.
DATABASE = 'test_truncation'
# Number of tables to create, to be truncated later.
N = 1000
# If true, truncations are sent in one shot, otherwise, one by one.
MULTI_STATEMENTS = false
options = {
host: '127.0.0.1',
port: 3307,
username: 'root',
password: 'root'
}
options[:flags] = Mysql2::Client::MULTI_STATEMENTS if MULTI_STATEMENTS
client = Mysql2::Client.new(options)
client.query("CREATE DATABASE IF NOT EXISTS #{DATABASE}")
client.query("USE #{DATABASE}")
puts "creating..."
N.times do |n|
client.query(<<~SQL)
CREATE TABLE IF NOT EXISTS #{table(n)} (
id INT AUTO_INCREMENT PRIMARY KEY,
data VARCHAR(255)
)
SQL
end
puts "populating..."
N.times do |n|
values = (["('dummy data')"] * 10).join(',')
client.query("INSERT INTO #{table(n)} (data) VALUES #{values}")
end
puts "truncating..."
puts Benchmark.realtime {
if MULTI_STATEMENTS
sql = ''
N.times do |n|
sql << "TRUNCATE #{table(n)};"
end
client.query(sql)
else
N.times do |n|
client.query("TRUNCATE #{table(n)}")
end
end
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment