#!/usr/bin/ruby -Ilib

# --------------------------------------------------------------------------
# queries.rb -- examples of the query features of SQLite
# Copyright (C) 2003 Jamis Buck (jgb3@email.byu.edu)
# --------------------------------------------------------------------------
# This file is part of the SQLite ruby interface.
# 
# The SQLite/Ruby Interface is free software; you can redistribute it and/or
# modify  it  under the terms of the GNU General Public License as published
# by  the  Free  Software  Foundation;  either  version 2 of the License, or
# (at your option) any later version.
# 
# The SQLite/Ruby Interface is distributed in the hope that it will be useful,
# but   WITHOUT   ANY   WARRANTY;  without  even  the  implied  warranty  of
# MERCHANTABILITY  or  FITNESS  FOR  A  PARTICULAR  PURPOSE.   See  the  GNU
# General Public License for more details.
# 
# You  should  have  received  a  copy  of  the  GNU  General Public License
# along with the SQLite/Ruby Interface;  if  not, write to the Free Software
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
# --------------------------------------------------------------------------
# This demonstrates simple queries and joins.
#
# Author: Jamis Buck (jgb3@email.byu.edu)
# Date: June 2003
# --------------------------------------------------------------------------

require 'sqlite'

class QueryDemo
  def initialize
    @db = SQLite::Database.new( "sample.db", 0 )
  end

  def query_1
    puts "Simple Query:"
    puts "  %20-s %20-s %12-s" % [ "Surname", "Given Names", "Birth Date" ]
    @db.execute( "select surname, given_names, birth_date from person order by surname" ) do |row|
      puts "  %20-s %20-s %12-s" % [ row['surname'], row['given_names'], row['birth_date'] ]
    end
    puts
  end

  def query_2
    puts "Left Inner Join:"
    puts "  %20-s %20-s %12-s" % [ "Surname", "Given Names", "Email" ]
    @db.execute( "select a.surname, a.given_names, b.address " +
                 "from person a, email b " +
                 "where a.id = b.person_id " +
                 "order by surname" ) do |row|
      puts "  %20-s %20-s %12-s" % [ row['a.surname'], row['a.given_names'], row['b.address'] ]
    end
    puts
  end

  def query_3
    puts "Left Outer Join:"
    puts "  %20-s %20-s %12-s" % [ "Surname", "Given Names", "Email" ]
    @db.execute( "select a.surname, a.given_names, coalesce( b.address, '>> No address <<' ) " +
                 "from person a left outer join email b on a.id = b.person_id " +
                 "order by surname" ) do |row|
      puts "  %20-s %20-s %12-s" % [ row[1], row[2], row[3] ]
    end
    puts
  end
end

demo = QueryDemo.new
demo.query_1
demo.query_2
demo.query_3

