Friday, November 18, 2011

What is the performance difference distinct vs group by SQL command


Don't use distinct command.It performance way is slow. group by command performance very high compare to distinct command.Please see the real time difference in the below example query.

1) select count(*) from (select distinct contact_id from contacts_lists) a;

 count
 65474

 1 row(s)

 Total runtime: 40,800.186 ms

2) select count(*) from (select contact_id from contacts_lists group by contact_id) a;

 count
 65474

 1 row(s)

 Total runtime: 32,302.381 ms


Wednesday, November 16, 2011

PGError: ERROR: duplicate key value violates unique constraint


Syntax: 

SELECT setval('table_name_id_seq'::regclass, MAX(id)) FROM table_name;

Example of usage:

SELECT setval('personal_contacts_personal_folders_id_seq'::regclass, MAX(id)) FROM personal_contacts_personal_folders;



Tuesday, January 11, 2011

Eager Loading Associations in rails


Eager loading is the mechanism for loading the associated records of the objects returned by Model.find using as few queries as possible.
N + 1 queries problem
Consider the following code, which finds 10 clients and prints their postcodes:


clients = Client.all(:limit => 10)
clients.each do |client|
  puts client.address.postcode
end

This code looks fine at the first sight. But the problem lies within the total number of queries executed. The above code executes 1 ( to find 10 clients ) + 10 ( one per each client to load the address ) = 11 queries in total.


This is possible by specifying the includes method of the Model.find call
Revisiting the above case, we could rewrite Client.all to use eager load addresses:

clients = Client.includes(:address).limit(10)
clients.each do |client|
  puts client.address.postcode
end

The above code will execute just 2 queries, as opposed to 11 queries in the previous case:

SELECT * FROM clients LIMIT 10
SELECT addresses.* FROM addresses
  WHERE (addresses.client_id IN (1,2,3,4,5,6,7,8,9,10))

Saturday, July 31, 2010

Ruby string array converted into integer array


["1","2","3","4"].map(&:to_i) => [1, 2, 3, 4]
    OR
["1","2","3","4"].collect(&:to_i) => [1, 2, 3, 4]

Dynamic html tag loop creation

arr = [1,2,3,4]
str = ''
i = 0
arr.each do |a|
        if i % 3 == 0
                str<<"#{a}"
        else
                str<<"#{a}"
        end
        i = i+1
        if i % 3 == 0 || arr.length == i
             str <<"
"
        end
end

puts str.inspect

output is like :

  • 1

    2

    3

  • 4

  • Thursday, May 13, 2010

    Escaping HTML in Rails,sanitize method in rails

    http://railspikes.com/2008/1/28/auto-escaping-html-with-rails
    http://stackoverflow.com/questions/698700/escaping-html-in-rails

    strip_tags(html)
    Strips all HTML tags from the html, including comments. This uses the html-scanner tokenizer and so its HTML parsing ability is limited by that of html-scanner.

    Examples

    strip_tags("Strip these tags!")
      # => Strip these tags!
    
      strip_tags("Bold no more!  See more here...")
      # => Bold no more!  See more here...
    
      strip_tags("
    
    
    
    
    
    Welcome to my website!
    ") # => Welcome to my website!
    strip_links(html)
    Strips all link tags from text leaving just the link text.

    Examples

    strip_links('Ruby on Rails')
      # => Ruby on Rails
    
      strip_links('Please e-mail me at me@email.com.')
      # => Please e-mail me at me@email.com.
    
      strip_links('Blog: Visit.')
      # => Blog: Visit
    sanitize(html, options = {})
    This sanitize helper will html encode all tags and strip all attributes that aren’t specifically allowed. It also strips href/src tags with invalid protocols, like javascript: especially. It does its best to counter any tricks that hackers may use, like throwing in unicode/ascii/hex values to get past the javascript: filters. Check out the extensive test suite.
    <%= sanitize @article.body %>
    You can add or remove tags/attributes if you want to customize it a bit. See ActionView::Base for full docs on the available options. You can add tags/attributes for single uses of sanitize by passing either the :attributes or :tags options:
    Normal Use
    <%= sanitize @article.body %>
    Custom Use (only the mentioned tags and attributes are allowed, nothing else)
    <%= sanitize @article.body, :tags => %w(table tr td), :attributes => %w(id class style)
    Add table tags to the default allowed tags
    Rails::Initializer.run do |config|
        config.action_view.sanitized_allowed_tags = 'table', 'tr', 'td'
      end
    Remove tags to the default allowed tags
    Rails::Initializer.run do |config|
        config.after_initialize do
          ActionView::Base.sanitized_allowed_tags.delete 'div'
        end
      end
    Change allowed default attributes
    Rails::Initializer.run do |config|
        config.action_view.sanitized_allowed_attributes = 'id', 'class', 'style'
      end
    Please note that sanitizing user-provided text does not guarantee that the resulting markup is valid (conforming to a document type) or even well-formed. The output may still contain e.g. unescaped ’<’, ’>’, ’&’ characters and confuse browsers.