Sequel Gem Flashcards

You may prefer our related Brainscape-certified flashcards:
1
Q

Sequel Gem

what is sequel

A

SQL database access toolkit for Ruby

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

Sequel Gem

what is a Dataset

A

a dataset object encapsulates an SQL query;

it supports chainability;

retrieves records only when needed;

accessed using Enumerable interface

ex

DB[:countries].filter(region: ‘Middle East’).avg(:GDP)

equivalent to

SELECT avg(GDP) FROM countries WHERE region = ‘Middle East’;

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q

Sequel Gem

how to connect to a database

A

Sequel.connect(‘url’)

supports other options

ex

DB = Sequel.connect(“postgres://user:password@host:port/database_name”, :max_connections => 10, :logger => Logger.new(‘log/db.log’))

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
4
Q

Sequel Gem

naming convention for instance of a database connection

A

DB

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
5
Q

Sequel Gem

execute raw sql statements in Sequel

A

DB.run(“create table t (a text, b text)”)

DB.run(“insert into t values (‘a’, ‘b’)”)

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
6
Q

Sequel Gem

create a dataset with raw sql

A

dataset = DB[‘select id from items’]

dataset. count
dataset. map(:id)

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
7
Q

Sequel Gem

fetch records with a dataset created with raw sql

A

DB[‘select * from items’].each { |row| p row }

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
8
Q

Sequel Gem

use placeholders in raw sql statements

A

name = ‘Jim’

DB[‘select * from items where name = ?’, name].each { |row| p row }

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
9
Q

Sequel Gem

the primary way records are retrieved and manipulated

A

datasets

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
10
Q

Sequel Gem

two primary ways datasets are created

A

Database#from or Database#[]

ex

posts = DB.from(:posts)

posts = DB[:posts] # same

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
11
Q

Sequel Gem

characteristic of datasets that allows you to manipulate them after they are created: to filter records, change ordering, join tables, etc

A

datasets only fetch records when you tell them to

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
12
Q

Sequel Gem

method that retrieves all records from a dataset

A

Dataset#all

returns an array of hashes, where each hash corresponds to a record

if a block is given, yields all objects after loading them

ex

posts.all

SELECT * FROM posts

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
13
Q

Sequel Gem

iterate through a dataset one record at a time

A

Dataset#each

ex

posts.each { |row| p row }

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
14
Q

Sequel Gem

retrieve the first or last record from a dataset

A

Dataset#first

ex

posts.first

ex

posts.order(:stamp).last

SELECT * FROM posts ORDER BY stamp DESC LIMIT 1

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
15
Q

Sequel Gem

return an array of one or more column values from a dataset

A

Dataset#map

ex

DB[:table].map(:id)

=> [1, 2, 3, …]

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
16
Q

Sequel Gem

retrieve a single record with a specific value from a dataset

A

Dataset#[]

ex

posts[:id => 1]

SELECT * FROM posts WHERE id = 1 LIMIT 1

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
17
Q

Sequel Gem

method that allows you to filter records in a dataset

A

Dataset#where

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
18
Q

Sequel Gem

use Dataset#where to filter based on a hash of values

A

my_posts = posts.where(:category => ‘ruby’, :author => ‘david’)

WHERE category = ‘ruby’ AND author = ‘david’

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
19
Q

Sequel Gem

use Dataset#where to filter based on a range

A

my_posts = posts.where(:stamp => (Date.today - 14)..(Date.today - 7))

WHERE stamp >= ‘2010-06-30’ AND stamp

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
20
Q

Sequel Gem

use Dataset#where to filter based on an array of values

A

my_posts = posts.where(:category => [‘ruby’, ‘postgres’, ‘linux’])

WHERE category IN (‘ruby’, ‘postgres’, ‘linux’)

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
21
Q

Sequel Gem

method that allows you to use an inverse filter on a dataset; i.e. opposite of Dataset#where

A

Dataset#exclude

ex

my_posts = posts.exclude(:category => [‘ruby’, ‘postgres’, ‘linux’])

WHERE category NOT IN (‘ruby’, ‘postgres’, ‘linux’)

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
22
Q

Sequel Gem

use a custom where clause with Dataset#where

A

posts.where(‘stamp IS NOT NULL’)

WHERE stamp IS NOT NULL

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
23
Q

Sequel Gem

return the number of records in a dataset

A

Dataset#count

ex

posts.where(Sequel.like(:category, ‘%ruby%’)).count

SELECT COUNT(*) FROM posts WHERE category LIKE ‘%ruby%’

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
24
Q

Sequel Gem

query maximum/minimum values in a dataset

A

Dataset#max, Dataset#min

ex

max = DB[:history].max(:value)

SELECT max(value) FROM history

min = DB[:history].min(:value)

SELECT min(value) FROM history

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
25
Q

Sequel Gem

calculate a sum or average from a dataset

A

Dataset#sum

ex

sum = DB[:items].sum(:price)

SELECT sum(price) FROM items

avg = DB[:items].avg(:price)

SELECT avg(price) FROM items

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
26
Q

Sequel Gem

order the records in a dataset

A

Dataset#order

ex

posts.order(:stamp)

ORDER BY stamp

posts.order(:stamp, :name)

ORDER BY stamp, name

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
27
Q

Sequel Gem

methods used to chain additional order by clauses on a dataset

A

Dataset#order_append, Dataset#order_prepend

ex

posts.order(:stamp).order_append(:name)

ORDER BY stamp, name

posts.order(:stamp).order_prepend(:name)

ORDER BY name, stamp

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
28
Q

Sequel Gem

specify descending order in an order by clause

A

Dataset#reverse_order

ex

posts.reverse_order(:stamp)

ORDER BY stamp DESC

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
29
Q

Sequel Gem

select specific columns to be returned from a dataset

A

Dataset#select

ex

posts.select(:stamp)

SELECT stamp FROM posts

posts.select(:stamp, :name)

SELECT stamp, name FROM posts

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
30
Q

Sequel Gem

methods used to chain additional select statements on a dataset

A

Dataset#select_append

ex

posts.select(:stamp).select_append(:name)

SELECT stamp, name FROM posts

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
31
Q

Sequel Gem

delete rows from a table

A

Dataset#delete

posts.where(‘stamp

DELETE FROM posts WHERE stamp

call WHERE before DELETE

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
32
Q

Sequel Gem

insert records into a table

A

Dataset#insert

ex

posts.insert(:category => ‘ruby’, :author => ‘david’)

INSERT INTO posts (category, author) VALUES (‘ruby’, ‘david’)

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
33
Q

Sequel Gem

update records in a dataset

A

Dataset#update

ex

posts.where(‘stamp ‘archived’)

UPDATE posts SET state = ‘archived’ WHERE stamp

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
34
Q

Sequel Gem

update records in a dataset with a value from another column

A

posts.where{|o| o.stamp Sequel.+(:backup_number, 1))

UPDATE posts SET backup_number = backup_number + 1 WHERE stamp

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
35
Q

Sequel Gem

method that wraps code in a database transaction

A

Database#transaction

ex

DB.transaction do

posts. insert(:category => ‘ruby’, :author => ‘david’)
posts. where(‘stamp ‘archived’)

end

36
Q

Sequel Gem

method that joins two tables

A

Dataset#join

ex

order_items = DB[:items].join(:order_items, :item_id => :id). where(:order_id => 1234)

SELECT * FROM items INNER JOIN order_items

ON order_items.item_id = items.id

WHERE order_id = 1234

!! item_id is automatically qualified with the table being joined, and id is automatically qualified with the last table joined.

37
Q

Sequel Gem

execute a select statement manually with a string

A

Database#fetch

ex

DB.fetch(“SELECT * FROM albums”) do |row|
puts row[:name]
end

38
Q

Sequel Gem

use a named placeholder with Database#fetch

A

DB.fetch(“SELECT * FROM albums WHERE name LIKE :pattern”, :pattern=>‘A%’) do |row|

puts row[:name]

end

39
Q

Sequel Gem

what Database#fetch returns when a block is not provided

A

Dataset

ex

ds = DB.fetch(“SELECT * FROM albums”)

40
Q

Sequel Gem

how to insert, update or delete using SQL

A

first create the dataset, then execute:

ds. insert
ds. update
ds. delete

41
Q

Sequel Gem

return the SQL that will be used for a given expression

A

Database#literal

ex

DB.literal(1) # => “1”

DB.literal(:column) # => “"column"”

DB.literal(‘string’) # => “‘string’”

42
Q

Sequel Gem

create a log file

A

DB.loggers

43
Q

Sequel Gem

how identifies are usually specified in Sequel gem

A

symbols

ex

:column # “column”

44
Q

Sequel Gem

syntax to qualifiy a column reference that exists in two different tables

A

double underscore

ex

:table__column # “table”.”column”

45
Q

Sequel Gem

method that qualifiies a column reference that exists in two different tables

A

Sequel.qualify

ex

Sequel.qualify(:table, :column) # “table”.”column”

46
Q

Sequel Gem

syntax to alias a column symbol

A

triple underscore

ex

:column___alias # “column” AS “alias”

ex with qualification

:table__column___alias # “table”.”column” AS “alias”

47
Q

Sequel Gem

method that creates an alias

A

Sequel.as

ex

Sequel.as(:column, :alias) # “column” AS “alias”

Sequel.qualify(:table, :column).as(:alias) # “table”.”column” AS “alias”

48
Q

Sequel Gem

syntax to use SQL functions

A

virtual row

ex

DB[:albums].select{func.function} # SELECT func() FROM “albums”

DB[:albums].select{func(col1, col2)} # SELECT func(“col1”, “col2”) FROM “albums”

49
Q

Sequel Gem

method that allows you to use a SQL function

A

Sequel.function

ex

Sequel.function(:func) # func()

Sequel.function(:func, :col1, :col2) # func(“col1”, “col2”)

50
Q

Sequel Gem

method that allows you to use SQL aggregate functions

A

Sequel.function

ex

Sequel.function(:sum, :column) # sum(column)

51
Q

Sequel Gem

method that adds the ‘distinct’ modifier to aggregate functions

A

distinct

ex

DB[:albums].select{sum(:column).distinct} # SELECT sum(DISTINCT column) FROM albums

52
Q

Sequel Gem

method that allows you to use the wildcard as the sole argument of the aggregate function

A

*

ex

Sequel.function(:count).* # count(*)

DB[:albums].select{count.function.*} # SELECT count(*) FROM albums

53
Q

Sequel Gem

equality operator

A

sequel uses hashes to specify equality

ex

{:column=>1} # (“column” = 1)

54
Q

Sequel Gem

not equal operator

A

Sequel.negate or Sequel.~

ex

Sequel.negate(:column => 1) # (“column” != 1)

Sequel.~(:column => 1) # (“column” != 1)

55
Q

Sequel Gem

difference between Sequel.negate and Sequel.~

A

Sequel.negate negates all entries

Sequel.~ does a general inversion

ex

Sequel.negate(:column => 1, :foo => 2) # ((“column” != 1) AND (foo != 2))

Sequel.~(:column => 1, :foo => 2) # ((“column” != 1) OR (foo != 2))

56
Q

Sequel Gem

method that uses not equal operator in where clause

A

Dataset#exclude

ex

DB[:albums].exclude(:column=>1) # SELECT * FROM “albums” WHERE (“column” != 1)

57
Q

Sequel Gem

use inclusion and exclusion operators

A

inclusion and exclusion work the same way as equality and inequality. Sequel swithces from = or != to IN or NOT IN when the hash value is an array or a dataset

ex

{:column=>[1, 2, 3]} # (“column” IN (1, 2, 3))

Sequel.~(:column=>[1, 2, 3]) # (“column” NOT IN (1, 2, 3))

58
Q

Sequel Gem

method that allows use of EXISTS operator

A

exists

ex

DB[:albums].exists # EXISTS (SELECT * FROM albums)

59
Q

Sequel Gem

use identity operators (IS and IS NOT)

A

identity operators work the same way as equality does

ex

{:column=>nil} # (“column” IS NULL)

{:column=>true} # (“column” IS TRUE)

{:column=>false} # (“column” IS FALSE)

Sequel.~(:column=>nil) # (“column” IS NOT NULL)

Sequel.~(:column=>true) # (“column” IS NOT TRUE)

Sequel.~(:column=>false) # (“column” IS NOT FALSE)

60
Q

Sequel Gem

use inversion operator (NOT)

A

Sequel.~

ex

Sequel.~(:column) # NOT “column”

61
Q

Sequel Gem

syntax to use inequality operators ( =)

A

= directly on expression objects

ex

Sequel.qualify(:table, :column) > 1 # (“table”.”column” > 1)

Sequel.qualify(:table, :column)

Sequel.function(:func) >= 1 # (func() >= 1)

Sequel.function(:func, :column)

62
Q

Sequel Gem

use inequality operators ( =) on symbols

A

Sequel.expr

ex

Sequel.expr(:column) > 1 # (“column” > 1)

63
Q

Sequel Gem

syntax to use mathematical operators (+ - * /)

A

+ - * / directly on expression objects

ex

Sequel.expr(:column) + 1 # “column” + 1

Sequel.expr(:table__column) - 1 # “table”.”column” - 1

Sequel.qualify(:table, :column) * 1 # “table”.”column” * 1

Sequel.expr(:column) / 1 # “column” / 1 Sequel.expr(:column) ** 1 # power(“column”, 1)

64
Q

Sequel Gem

syntax to use boolean operators (AND OR)

A

& and | methods directly on expression objects

ex

Sequel.expr(:column1) & :column2 # (“column1” AND “column2”)

Sequel.expr(:column1=>1) | {:column2=>2} # ((“column1” = 1) OR (“column2” = 2))

(Sequel.function(:func) > 1) & :column3 # ((func() > 1) AND “column3”)

65
Q

Sequel Gem

how to cast data types

A

the cast method directly on expression objects

ex

Sequel.expr(:name).cast(:text) # CAST(“name” AS text)

Sequel.expr(‘1’).cast(:integer) # CAST(‘1’ AS integer)

Sequel.qualify(:table, :column).cast(:date) # CAST(“table”.”column” AS date)

66
Q

Sequel Gem

use the LIKE operator

A

the like and ilike methods directly on expression objects

ex

Sequel.expr(:name).like(‘A%’) # (“name” LIKE ‘A%’ ESCAPE ‘')

Sequel.expr(:name).ilike(‘A%’) # (“name” ILIKE ‘A%’ ESCAPE ‘')

67
Q

Sequel Gem

how to use a regular expression with MySQL or Postgres

A

by passing a ruby regular expression to like or ilike

ex

Sequel.like(:name, /^A/) # (“name” ~ ‘^A’)

~Sequel.ilike(:name, /^A/) # (“name” !~* ‘^A’)

68
Q

Sequel Gem

how to use the SQL CASE statement

A

Sequel.case(conditions_hsh, default_value) # the keys of the hash is WHEN, the values are THEN

ex

Sequel.case({:column=>1}, 0) # (CASE WHEN “column” THEN 1 ELSE 0 END)

Sequel.case([[column, 1]], 0) # (CASE WHEN “column” THEN 1 ELSE 0 END)

Sequel.case({{:column=>nil}=>1}, 0) # (CASE WHEN (column IS NULL) THEN 1 ELSE 0 END)

69
Q

Sequel Gem

how datasets are generally created

A

Database#[] # passing in 1 or more table names

ex

ds = DB[:albums, :artists] # this dataset is not ready to be manipulated by chaining methods

ex

ds.select(:id, :name).where(Sequel.like(:name, ‘A%’)).order(:name) # SELECT id, name FROM albums WHERE (name LIKE ‘A%’ ESCAPE ‘') ORDER BY name

70
Q

Sequel Gem

add additional OR WHERE clause

A

Dataset#or

ex

ds.where(:name => ‘George’).or([[:id => [2,3]]]) # SELECT * FROM people WHERE ((name = ‘George’) OR (id IN (2, 3)))

71
Q

Sequel Gem

method that allows you to use the LIKE operator for string comparison

A

Dataset#grep(:field, ‘match_string’)

ex

ds.grep(:name, ‘G%’) # SELECT * FROM people WHERE ((name LIKE ‘G%’))

72
Q

Sequel Gem

wildcard used with LIKE operator that matches zero or more of any character

A

%

ex

‘G%’ matches George, but does not match SING

73
Q

Sequel Gem

wildcard used with LIKE operator that matches exactly one of any character

A

_

ex

‘G_’ matches Go but does not match George

74
Q

Sequel Gem

the main Sequel object that you deal with and how it is instantiated

A

Sequel::Database

ex

Sequel.connect(‘postgres://localhost/dbname’) => Sequel::Database

75
Q

Sequel Gem

method that can be used to take any object that Sequel handles and literalize the object to an SQL string fragment

A

Sequel::Database#literal => string

ex

DB.literal(DB[:table]) => ‘(SELECT * FROM “table”)’

76
Q

objects that represent abstract collections of rows in the database

A

Sequel::Dataset

77
Q

ruby type that represents identifiers (tables, columns, schemas), qualified identifiers (table.column), aliased identifiers (column as alias), and qualified aliased identifiers (table.column as alias)

A

symbols

ex

:table # “table”

:column # “column”

:table__column # “table”.”column”

:column___alias # “column” AS “alias”

:table__column___alias # “table”.”column” AS “alias”

78
Q

used to represent an SQL concept that doesn’t map directly to a ruby class

A

Sequel::SQL::Expression

79
Q

Sequel Gem

create a literal sequel string, copied verbatim into an SQL statement

A

Sequel::LiteralString

ex

Sequel.lit(“co’de”) # co’de

ex

DB[:albums].select(‘name’) # SELECT ‘name’ FROM albums DB[:albums].select(Sequel.lit(‘name’)) # SELECT name FROM albums

80
Q

separate subclasses for representing boolean operations such as AND and OR, mathematical operations such as + and -, and string operations such as || and LIKE

A

Sequel::SQL::ComplexExpression

ex

Sequel.or(:col1, :col2) # (“col1” OR “col2”)

Sequel.+(:column, 2) # (“column” + 2)

81
Q

object that represent SQL CASE expressions

A

Sequel::SQL::CaseExpression

ex

Sequel.case({2=>1}, 0, :a) # CASE “a” WHEN 2 THEN 1 ELSE 0 END

Sequel.case({{:a=>2}=>1}, 0) # CASE WHEN (“a” = 2) THEN 1 ELSE 0 END

82
Q

object that represents CAST expressions in SQL, which does explicit typecasting in the database

A

Sequel::SQL::Cast

ex

Sequel.cast(:a, String) # (CAST “a” AS text)

Sequel.cast(:a, :int4) # (CAST “a” AS int4)

83
Q

object that represents an evaluation that is delayed until query literalization

A

Sequel::SQL::DelayedEvaluation

ex

Sequel.delay{some_model.updated_at}

84
Q

object that represents database function calls, which take a function name and any arguments

A

Sequel::SQL::Function

ex

Sequel.function(:func, :a, 2) # func(“a”, 2)

85
Q

object that represents a literal SQL string with placeholders for variables

A

Sequel::SQL::PlaceholderLiteralString

ex

Sequel.lit(‘? = ?’, :a, 1) # “a” = 1

Sequel.lit(‘:b = :v’, :b=>:a, :v=>1) # “a” = 1

Sequel.lit([’’, ‘ = ‘], :a, 1) # “a” = 1

86
Q

object that represents ascending or descending sorts, used by the Dataset order methods

A

Sequel::SQL::OrderedExpression

ex

Sequel.asc(:a) # “a” ASC

Sequel.desc(:a) # “a” DESC

Sequel.asc(:a, :nulls=>:first) # “a” ASC NULLS FIRST

Sequel.desc(:a, :nulls=>:last) # “a” DESC NULLS LAST

87
Q

BasicObject subclass that is the backbone behind the block expression support

A

Sequel::SQL::VirtualRow

ex

DB[:table].where{a < 1} # the block is instance-evaled inside a VirtualRow instance