Count, Size & Length methods. Which one to use where? What’s the difference between these?

Even the experienced developers will struggle to answer this correctly. Where to use count method? Where to use size method? Where to use length method? What is the difference among these? What is the advantages/disadvantages of using this? Which one is effective in using which areas? etc…, Find the answer below for the above questions :-

Consider, you have use any of these methods in both Active record (and) as a ruby method. First let us see which one to use as a ruby method.

AS A RUBY METHOD

names=[“Sachin”, “Dravid”, “Ashwin”]

Now, if you use names.size it will return the value 3. If you use names.length again it will return the same value 3. But I would recommended to go for names.length rather than names.size. Because, see the below example :-

If you try to find the size of any numbers using size method, it will return you some value whereas length method will throw the error. So if we use size method, we will not be 100% sure whether the output returned is correct or not..

1.size => 4

1.length => NoMethodError: undefined method `length’ for 1:Fixnum

AS A ACTIVE RECORD METHOD

Assume that we have 2 tables, one is user  and another is chats which has the relation as below :-

User -> has many –> Chats

Chats -> belongs_to –> User

user.chats.length –> This always loads the content of the association into memory, and then returns the number of elements loaded.

Chat Load (0.1ms)   SELECT * FROM `chats` WHERE (`chats`.user_id = 1) 

user.chats.count –> Determines the number of elements with the simple SQL count query.

1st time (Before the collection was loaded)

Chat Columns (1.0ms) SHOW FIELDS FROM `chats`
SQL (0.1ms) SELECT count(*) AS count_all FROM `chats` WHERE (`chats`.user_id = 1)

2nd time (Before the collection was loaded)

SQL (0.1ms) SELECT count(*) AS count_all FROM `chats` WHERE (`chats`.user_id = 1)

After running user.chats.length (or collection was already loaded)

SQL (0.1ms) SELECT count(*) AS count_all FROM `chats` WHERE (`chats`.user_id = 1)

user.chats.size –> This method has some caching mechanism, and it is like using the ‘count’ method if the collection was not already loaded (Executes the SQL count query). But if the collection was already loaded, it just takes the caching mechanism to display the size without even firing a SQL query.

1st time (Before the collection was loaded)

Chat Columns (1.0ms) SHOW FIELDS FROM `chats`

SQL (0.1ms) SELECT count(*) AS count_all FROM `chats` WHERE (`chats`.user_id = 1)

2nd time (Before the collection was loaded)

SQL (0.1 ms) SELECT count(*) AS count_all FROM `chats` WHERE (`chats`.user_id = 1)

After running user.chats.length (or collection was already loaded)

(NO SQL QUERY WILL BE FIRED, AND IT RETURNS THE CACHE VALUE)

CONCLUSION 


If you are going to use any of these methods during ActiveRecord I would suggest you to use the SIZE method.

If you are going to use any of these methods during normal ruby process I would suggest you to use the LENGTH method. 

Trigger

A database trigger is procedural code that is automatically executed in response to certain events on a particular table or view in a database. The trigger is mostly used for keeping the integrity of the information on the database. For example, when a new record (representing a new worker) is added to the employees table, new records should be created also in the tables of the taxes, vacations, and salaries. Triggers are always created on DML statements only (INSERT, UPDATE & DELETE)

Example :-

CREATE TRIGGER insert_trigger BEFORE INSERT ON comments

FOR EACH ROW

BEGIN

SET NEW.comment = “This is my new comment”

END

Database Backup (only particular tables) – MYSQL

How do you take a database backup for only particular tables, that too dynamically… Say i have tables like map1, map2, map3, ….. map1000. How do you write a query? Don’t worry it’s very simple :) Just follow the below command

mysql test_v382_development -u root -proot -e ‘show tables like “map%”‘ | grep -v Tables_in| xargs mysqldump  test_v382_development -u root -proot emp dept > backup.sql

The above command will take the database backup for the tables, map1, map2, … mapN dynamically and the tables ’emp’ and ‘dept’. Other tables in the database will not be included in the database backup.

DB and Log backup’s using Rake Tasks

Add this in your rakefile for taking log and db backup’s.

require ‘fileutils’
namespace :backup do
  #for taking log backup -start
  desc ‘backup log’
  namespace :log do
   desc ‘rake backup:log:all’
   task :all do
    backup_path = File.join(Rails.root, ‘backup’, ‘log’, “#{Date.today.month}”)
    FileUtils.mkdir_p(backup_path) unless File.exist?(backup_path)
    filename = File.join(backup_path, “log_#{Time.now.strftime(“%Y%m%d”)}.tar.gz”)
    cmd = “tar -czvf #{filename} log/*.log”
    `#{cmd}`
    Rake::Task[“log:clear”].invoke if File.size?(filename)
   end
  end
  #for taking log backup -end

  #for taking db backup -start
  desc ‘backup db’
   namespace :db do
   desc ‘rake backup:db:mysql’
   task :mysql => :environment do
    backup_path = File.join(Rails.root, ‘backup’, ‘db’, “#{Date.today.year}-#{Date.today.month}”)
    FileUtils.mkdir_p(backup_path) unless File.exist?(backup_path)
    tmp_filename = File.join(Rails.root, ‘backup’, ‘db’, ‘tmp.sql’)
    filename = File.join(backup_path, “db_#{Rails.env}_#{Time.now.strftime(“%Y%m%d%H%M%S”)}.tar.gz”)
    db_options = YAML.load_file(File.join(Rails.root, ‘config’, ‘database.yml’))[Rails.env].symbolize_keys
    cmd = <<-CMD
        mysqldump  GetProject_development -u root -proot  > #{tmp_filename}
tar -czvf #{filename} backup/db/tmp.sql

    CMD
    `#{cmd}`
   end
  end
#for taking db backup -end
end

That’s it now run

rake backup:log:all

to take a backup of log (you can also run this rake daily once automatically for taking daily backups). This will take a backup of log, and clear the current log file’s contents. Similarly, for taking db backup run

rake backup:db:mysql

All the backups will be stored in a folder named “backup” which will be available at the root path of the app.

Plugin for running MySQL common database tasks

Download the plugin and run the MySQL common database tasks like create, destroy, backup & restore.

Install

./script/plugin install http://sbecker.net/shared/plugins/mysql_tasks

Components

rake db:mysql:create           # Create database (using database.yml config)
rake db:mysql:destroy          # Destroy database (using database.yml config)
rake db:mysql:backup           # Dump schema and data to an SQL file (/db/backup_YYYY_MM_DD.sql)
rake db:mysql:restore          # Load schema and data from an SQL file (/db/restore.sql)