viking-sequel 3.10.0
Sign up to get free protection for your applications and to get access to all the features.
- data/CHANGELOG +3134 -0
- data/COPYING +19 -0
- data/README.rdoc +723 -0
- data/Rakefile +193 -0
- data/bin/sequel +196 -0
- data/doc/advanced_associations.rdoc +644 -0
- data/doc/cheat_sheet.rdoc +218 -0
- data/doc/dataset_basics.rdoc +106 -0
- data/doc/dataset_filtering.rdoc +158 -0
- data/doc/opening_databases.rdoc +296 -0
- data/doc/prepared_statements.rdoc +104 -0
- data/doc/reflection.rdoc +84 -0
- data/doc/release_notes/1.0.txt +38 -0
- data/doc/release_notes/1.1.txt +143 -0
- data/doc/release_notes/1.3.txt +101 -0
- data/doc/release_notes/1.4.0.txt +53 -0
- data/doc/release_notes/1.5.0.txt +155 -0
- data/doc/release_notes/2.0.0.txt +298 -0
- data/doc/release_notes/2.1.0.txt +271 -0
- data/doc/release_notes/2.10.0.txt +328 -0
- data/doc/release_notes/2.11.0.txt +215 -0
- data/doc/release_notes/2.12.0.txt +534 -0
- data/doc/release_notes/2.2.0.txt +253 -0
- data/doc/release_notes/2.3.0.txt +88 -0
- data/doc/release_notes/2.4.0.txt +106 -0
- data/doc/release_notes/2.5.0.txt +137 -0
- data/doc/release_notes/2.6.0.txt +157 -0
- data/doc/release_notes/2.7.0.txt +166 -0
- data/doc/release_notes/2.8.0.txt +171 -0
- data/doc/release_notes/2.9.0.txt +97 -0
- data/doc/release_notes/3.0.0.txt +221 -0
- data/doc/release_notes/3.1.0.txt +406 -0
- data/doc/release_notes/3.10.0.txt +286 -0
- data/doc/release_notes/3.2.0.txt +268 -0
- data/doc/release_notes/3.3.0.txt +192 -0
- data/doc/release_notes/3.4.0.txt +325 -0
- data/doc/release_notes/3.5.0.txt +510 -0
- data/doc/release_notes/3.6.0.txt +366 -0
- data/doc/release_notes/3.7.0.txt +179 -0
- data/doc/release_notes/3.8.0.txt +151 -0
- data/doc/release_notes/3.9.0.txt +233 -0
- data/doc/schema.rdoc +36 -0
- data/doc/sharding.rdoc +113 -0
- data/doc/virtual_rows.rdoc +205 -0
- data/lib/sequel.rb +1 -0
- data/lib/sequel/adapters/ado.rb +90 -0
- data/lib/sequel/adapters/ado/mssql.rb +30 -0
- data/lib/sequel/adapters/amalgalite.rb +176 -0
- data/lib/sequel/adapters/db2.rb +139 -0
- data/lib/sequel/adapters/dbi.rb +113 -0
- data/lib/sequel/adapters/do.rb +188 -0
- data/lib/sequel/adapters/do/mysql.rb +49 -0
- data/lib/sequel/adapters/do/postgres.rb +91 -0
- data/lib/sequel/adapters/do/sqlite.rb +40 -0
- data/lib/sequel/adapters/firebird.rb +283 -0
- data/lib/sequel/adapters/informix.rb +77 -0
- data/lib/sequel/adapters/jdbc.rb +587 -0
- data/lib/sequel/adapters/jdbc/as400.rb +58 -0
- data/lib/sequel/adapters/jdbc/h2.rb +133 -0
- data/lib/sequel/adapters/jdbc/mssql.rb +57 -0
- data/lib/sequel/adapters/jdbc/mysql.rb +78 -0
- data/lib/sequel/adapters/jdbc/oracle.rb +50 -0
- data/lib/sequel/adapters/jdbc/postgresql.rb +108 -0
- data/lib/sequel/adapters/jdbc/sqlite.rb +55 -0
- data/lib/sequel/adapters/mysql.rb +421 -0
- data/lib/sequel/adapters/odbc.rb +143 -0
- data/lib/sequel/adapters/odbc/mssql.rb +42 -0
- data/lib/sequel/adapters/openbase.rb +64 -0
- data/lib/sequel/adapters/oracle.rb +131 -0
- data/lib/sequel/adapters/postgres.rb +504 -0
- data/lib/sequel/adapters/shared/mssql.rb +490 -0
- data/lib/sequel/adapters/shared/mysql.rb +498 -0
- data/lib/sequel/adapters/shared/oracle.rb +195 -0
- data/lib/sequel/adapters/shared/postgres.rb +830 -0
- data/lib/sequel/adapters/shared/progress.rb +44 -0
- data/lib/sequel/adapters/shared/sqlite.rb +389 -0
- data/lib/sequel/adapters/sqlite.rb +224 -0
- data/lib/sequel/adapters/utils/stored_procedures.rb +84 -0
- data/lib/sequel/connection_pool.rb +99 -0
- data/lib/sequel/connection_pool/sharded_single.rb +84 -0
- data/lib/sequel/connection_pool/sharded_threaded.rb +211 -0
- data/lib/sequel/connection_pool/single.rb +29 -0
- data/lib/sequel/connection_pool/threaded.rb +150 -0
- data/lib/sequel/core.rb +293 -0
- data/lib/sequel/core_sql.rb +241 -0
- data/lib/sequel/database.rb +1079 -0
- data/lib/sequel/database/schema_generator.rb +327 -0
- data/lib/sequel/database/schema_methods.rb +203 -0
- data/lib/sequel/database/schema_sql.rb +320 -0
- data/lib/sequel/dataset.rb +32 -0
- data/lib/sequel/dataset/actions.rb +441 -0
- data/lib/sequel/dataset/features.rb +86 -0
- data/lib/sequel/dataset/graph.rb +254 -0
- data/lib/sequel/dataset/misc.rb +119 -0
- data/lib/sequel/dataset/mutation.rb +64 -0
- data/lib/sequel/dataset/prepared_statements.rb +227 -0
- data/lib/sequel/dataset/query.rb +709 -0
- data/lib/sequel/dataset/sql.rb +996 -0
- data/lib/sequel/exceptions.rb +51 -0
- data/lib/sequel/extensions/blank.rb +43 -0
- data/lib/sequel/extensions/inflector.rb +242 -0
- data/lib/sequel/extensions/looser_typecasting.rb +21 -0
- data/lib/sequel/extensions/migration.rb +239 -0
- data/lib/sequel/extensions/named_timezones.rb +61 -0
- data/lib/sequel/extensions/pagination.rb +100 -0
- data/lib/sequel/extensions/pretty_table.rb +82 -0
- data/lib/sequel/extensions/query.rb +52 -0
- data/lib/sequel/extensions/schema_dumper.rb +271 -0
- data/lib/sequel/extensions/sql_expr.rb +122 -0
- data/lib/sequel/extensions/string_date_time.rb +46 -0
- data/lib/sequel/extensions/thread_local_timezones.rb +48 -0
- data/lib/sequel/metaprogramming.rb +9 -0
- data/lib/sequel/model.rb +120 -0
- data/lib/sequel/model/associations.rb +1514 -0
- data/lib/sequel/model/base.rb +1069 -0
- data/lib/sequel/model/default_inflections.rb +45 -0
- data/lib/sequel/model/errors.rb +39 -0
- data/lib/sequel/model/exceptions.rb +21 -0
- data/lib/sequel/model/inflections.rb +162 -0
- data/lib/sequel/model/plugins.rb +70 -0
- data/lib/sequel/plugins/active_model.rb +59 -0
- data/lib/sequel/plugins/association_dependencies.rb +103 -0
- data/lib/sequel/plugins/association_proxies.rb +41 -0
- data/lib/sequel/plugins/boolean_readers.rb +53 -0
- data/lib/sequel/plugins/caching.rb +141 -0
- data/lib/sequel/plugins/class_table_inheritance.rb +214 -0
- data/lib/sequel/plugins/composition.rb +138 -0
- data/lib/sequel/plugins/force_encoding.rb +72 -0
- data/lib/sequel/plugins/hook_class_methods.rb +126 -0
- data/lib/sequel/plugins/identity_map.rb +116 -0
- data/lib/sequel/plugins/instance_filters.rb +98 -0
- data/lib/sequel/plugins/instance_hooks.rb +57 -0
- data/lib/sequel/plugins/lazy_attributes.rb +77 -0
- data/lib/sequel/plugins/many_through_many.rb +208 -0
- data/lib/sequel/plugins/nested_attributes.rb +206 -0
- data/lib/sequel/plugins/optimistic_locking.rb +81 -0
- data/lib/sequel/plugins/rcte_tree.rb +281 -0
- data/lib/sequel/plugins/schema.rb +66 -0
- data/lib/sequel/plugins/serialization.rb +166 -0
- data/lib/sequel/plugins/single_table_inheritance.rb +74 -0
- data/lib/sequel/plugins/subclasses.rb +45 -0
- data/lib/sequel/plugins/tactical_eager_loading.rb +61 -0
- data/lib/sequel/plugins/timestamps.rb +87 -0
- data/lib/sequel/plugins/touch.rb +118 -0
- data/lib/sequel/plugins/typecast_on_load.rb +72 -0
- data/lib/sequel/plugins/validation_class_methods.rb +405 -0
- data/lib/sequel/plugins/validation_helpers.rb +223 -0
- data/lib/sequel/sql.rb +1020 -0
- data/lib/sequel/timezones.rb +161 -0
- data/lib/sequel/version.rb +12 -0
- data/lib/sequel_core.rb +1 -0
- data/lib/sequel_model.rb +1 -0
- data/spec/adapters/firebird_spec.rb +407 -0
- data/spec/adapters/informix_spec.rb +97 -0
- data/spec/adapters/mssql_spec.rb +403 -0
- data/spec/adapters/mysql_spec.rb +1019 -0
- data/spec/adapters/oracle_spec.rb +286 -0
- data/spec/adapters/postgres_spec.rb +969 -0
- data/spec/adapters/spec_helper.rb +51 -0
- data/spec/adapters/sqlite_spec.rb +432 -0
- data/spec/core/connection_pool_spec.rb +808 -0
- data/spec/core/core_sql_spec.rb +417 -0
- data/spec/core/database_spec.rb +1662 -0
- data/spec/core/dataset_spec.rb +3827 -0
- data/spec/core/expression_filters_spec.rb +595 -0
- data/spec/core/object_graph_spec.rb +296 -0
- data/spec/core/schema_generator_spec.rb +159 -0
- data/spec/core/schema_spec.rb +830 -0
- data/spec/core/spec_helper.rb +56 -0
- data/spec/core/version_spec.rb +7 -0
- data/spec/extensions/active_model_spec.rb +76 -0
- data/spec/extensions/association_dependencies_spec.rb +127 -0
- data/spec/extensions/association_proxies_spec.rb +50 -0
- data/spec/extensions/blank_spec.rb +67 -0
- data/spec/extensions/boolean_readers_spec.rb +92 -0
- data/spec/extensions/caching_spec.rb +250 -0
- data/spec/extensions/class_table_inheritance_spec.rb +252 -0
- data/spec/extensions/composition_spec.rb +194 -0
- data/spec/extensions/force_encoding_spec.rb +117 -0
- data/spec/extensions/hook_class_methods_spec.rb +470 -0
- data/spec/extensions/identity_map_spec.rb +202 -0
- data/spec/extensions/inflector_spec.rb +181 -0
- data/spec/extensions/instance_filters_spec.rb +55 -0
- data/spec/extensions/instance_hooks_spec.rb +133 -0
- data/spec/extensions/lazy_attributes_spec.rb +153 -0
- data/spec/extensions/looser_typecasting_spec.rb +39 -0
- data/spec/extensions/many_through_many_spec.rb +884 -0
- data/spec/extensions/migration_spec.rb +332 -0
- data/spec/extensions/named_timezones_spec.rb +72 -0
- data/spec/extensions/nested_attributes_spec.rb +396 -0
- data/spec/extensions/optimistic_locking_spec.rb +100 -0
- data/spec/extensions/pagination_spec.rb +99 -0
- data/spec/extensions/pretty_table_spec.rb +91 -0
- data/spec/extensions/query_spec.rb +85 -0
- data/spec/extensions/rcte_tree_spec.rb +205 -0
- data/spec/extensions/schema_dumper_spec.rb +357 -0
- data/spec/extensions/schema_spec.rb +127 -0
- data/spec/extensions/serialization_spec.rb +209 -0
- data/spec/extensions/single_table_inheritance_spec.rb +96 -0
- data/spec/extensions/spec_helper.rb +91 -0
- data/spec/extensions/sql_expr_spec.rb +89 -0
- data/spec/extensions/string_date_time_spec.rb +93 -0
- data/spec/extensions/subclasses_spec.rb +52 -0
- data/spec/extensions/tactical_eager_loading_spec.rb +65 -0
- data/spec/extensions/thread_local_timezones_spec.rb +45 -0
- data/spec/extensions/timestamps_spec.rb +150 -0
- data/spec/extensions/touch_spec.rb +155 -0
- data/spec/extensions/typecast_on_load_spec.rb +69 -0
- data/spec/extensions/validation_class_methods_spec.rb +984 -0
- data/spec/extensions/validation_helpers_spec.rb +438 -0
- data/spec/integration/associations_test.rb +281 -0
- data/spec/integration/database_test.rb +26 -0
- data/spec/integration/dataset_test.rb +963 -0
- data/spec/integration/eager_loader_test.rb +734 -0
- data/spec/integration/model_test.rb +130 -0
- data/spec/integration/plugin_test.rb +814 -0
- data/spec/integration/prepared_statement_test.rb +213 -0
- data/spec/integration/schema_test.rb +361 -0
- data/spec/integration/spec_helper.rb +73 -0
- data/spec/integration/timezone_test.rb +55 -0
- data/spec/integration/transaction_test.rb +122 -0
- data/spec/integration/type_test.rb +96 -0
- data/spec/model/association_reflection_spec.rb +175 -0
- data/spec/model/associations_spec.rb +2633 -0
- data/spec/model/base_spec.rb +418 -0
- data/spec/model/dataset_methods_spec.rb +78 -0
- data/spec/model/eager_loading_spec.rb +1391 -0
- data/spec/model/hooks_spec.rb +240 -0
- data/spec/model/inflector_spec.rb +26 -0
- data/spec/model/model_spec.rb +593 -0
- data/spec/model/plugins_spec.rb +236 -0
- data/spec/model/record_spec.rb +1500 -0
- data/spec/model/spec_helper.rb +97 -0
- data/spec/model/validations_spec.rb +153 -0
- data/spec/rcov.opts +6 -0
- data/spec/spec_config.rb.example +10 -0
- metadata +346 -0
data/COPYING
ADDED
@@ -0,0 +1,19 @@
|
|
1
|
+
Copyright (c) 2007-2008 Sharon Rosner
|
2
|
+
Copyright (c) 2008-2010 Jeremy Evans
|
3
|
+
|
4
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
5
|
+
of this software and associated documentation files (the "Software"), to
|
6
|
+
deal in the Software without restriction, including without limitation the
|
7
|
+
rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
|
8
|
+
sell copies of the Software, and to permit persons to whom the Software is
|
9
|
+
furnished to do so, subject to the following conditions:
|
10
|
+
|
11
|
+
The above copyright notice and this permission notice shall be included in
|
12
|
+
all copies or substantial portions of the Software.
|
13
|
+
|
14
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
15
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
16
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
|
17
|
+
THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
|
18
|
+
IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
|
19
|
+
CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
|
data/README.rdoc
ADDED
@@ -0,0 +1,723 @@
|
|
1
|
+
== Sequel: The Database Toolkit for Ruby
|
2
|
+
|
3
|
+
Sequel is a lightweight database access toolkit for Ruby.
|
4
|
+
|
5
|
+
* Sequel provides thread safety, connection pooling and a concise DSL
|
6
|
+
for constructing database queries and table schemas.
|
7
|
+
* Sequel also includes a lightweight but comprehensive ORM layer for
|
8
|
+
mapping records to Ruby objects and handling associated records.
|
9
|
+
* Sequel supports advanced database features such as prepared
|
10
|
+
statements, bound variables, stored procedures, master/slave
|
11
|
+
configurations, and database sharding.
|
12
|
+
* Sequel makes it easy to deal with multiple records without having
|
13
|
+
to break your teeth on SQL.
|
14
|
+
* Sequel currently has adapters for ADO, Amalgalite, DataObjects,
|
15
|
+
DB2, DBI, Firebird, Informix, JDBC, MySQL, ODBC, OpenBase, Oracle,
|
16
|
+
PostgreSQL and SQLite3.
|
17
|
+
|
18
|
+
== Resources
|
19
|
+
|
20
|
+
* {Website}[http://sequel.rubyforge.org]
|
21
|
+
* {Website}[http://sequel.heroku.com]
|
22
|
+
* {Source code}[http://github.com/jeremyevans/sequel]
|
23
|
+
* {Bug tracking}[http://code.google.com/p/ruby-sequel/issues/list]
|
24
|
+
* {Google group}[http://groups.google.com/group/sequel-talk]
|
25
|
+
* {RDoc}[http://sequel.rubyforge.org/rdoc]
|
26
|
+
|
27
|
+
To check out the source code:
|
28
|
+
|
29
|
+
git clone git://github.com/jeremyevans/sequel.git
|
30
|
+
|
31
|
+
=== Contact
|
32
|
+
|
33
|
+
If you have any comments or suggestions please post to the Google group.
|
34
|
+
|
35
|
+
== Installation
|
36
|
+
|
37
|
+
sudo gem install sequel
|
38
|
+
|
39
|
+
== A Short Example
|
40
|
+
|
41
|
+
require 'rubygems'
|
42
|
+
require 'sequel'
|
43
|
+
|
44
|
+
DB = Sequel.sqlite # memory database
|
45
|
+
|
46
|
+
DB.create_table :items do
|
47
|
+
primary_key :id
|
48
|
+
String :name
|
49
|
+
Float :price
|
50
|
+
end
|
51
|
+
|
52
|
+
items = DB[:items] # Create a dataset
|
53
|
+
|
54
|
+
# Populate the table
|
55
|
+
items.insert(:name => 'abc', :price => rand * 100)
|
56
|
+
items.insert(:name => 'def', :price => rand * 100)
|
57
|
+
items.insert(:name => 'ghi', :price => rand * 100)
|
58
|
+
|
59
|
+
# Print out the number of records
|
60
|
+
puts "Item count: #{items.count}"
|
61
|
+
|
62
|
+
# Print out the average price
|
63
|
+
puts "The average price is: #{items.avg(:price)}"
|
64
|
+
|
65
|
+
== The Sequel Console
|
66
|
+
|
67
|
+
Sequel includes an IRB console for quick access to databases. You can use it like this:
|
68
|
+
|
69
|
+
sequel sqlite://test.db # test.db in current directory
|
70
|
+
|
71
|
+
You get an IRB session with the database object stored in DB.
|
72
|
+
|
73
|
+
== An Introduction
|
74
|
+
|
75
|
+
Sequel is designed to take the hassle away from connecting to databases and manipulating them. Sequel deals with all the boring stuff like maintaining connections, formatting SQL correctly and fetching records so you can concentrate on your application.
|
76
|
+
|
77
|
+
Sequel uses the concept of datasets to retrieve data. A Dataset object encapsulates an SQL query and supports chainability, letting you fetch data using a convenient Ruby DSL that is both concise and flexible.
|
78
|
+
|
79
|
+
For example, the following one-liner returns the average GDP for countries in the middle east region:
|
80
|
+
|
81
|
+
DB[:countries].filter(:region => 'Middle East').avg(:GDP)
|
82
|
+
|
83
|
+
Which is equivalent to:
|
84
|
+
|
85
|
+
SELECT avg(GDP) FROM countries WHERE region = 'Middle East'
|
86
|
+
|
87
|
+
Since datasets retrieve records only when needed, they can be stored and later reused. Records are fetched as hashes (or custom model objects), and are accessed using an Enumerable interface:
|
88
|
+
|
89
|
+
middle_east = DB[:countries].filter(:region => 'Middle East')
|
90
|
+
middle_east.order(:name).each{|r| puts r[:name]}
|
91
|
+
|
92
|
+
Sequel also offers convenience methods for extracting data from Datasets, such as an extended map method:
|
93
|
+
|
94
|
+
middle_east.map(:name) #=> ['Egypt', 'Greece', 'Israel', ...]
|
95
|
+
|
96
|
+
Or getting results as a transposed hash, with one column as key and another as value:
|
97
|
+
|
98
|
+
middle_east.to_hash(:name, :area) #=> {'Israel' => 20000, 'Greece' => 120000, ...}
|
99
|
+
|
100
|
+
== Getting Started
|
101
|
+
|
102
|
+
=== Connecting to a database
|
103
|
+
|
104
|
+
To connect to a database you simply provide Sequel with a URL:
|
105
|
+
|
106
|
+
require 'sequel'
|
107
|
+
DB = Sequel.connect('sqlite://blog.db')
|
108
|
+
|
109
|
+
The connection URL can also include such stuff as the user name and password:
|
110
|
+
|
111
|
+
DB = Sequel.connect('postgres://cico:12345@localhost:5432/mydb')
|
112
|
+
|
113
|
+
You can also specify optional parameters, such as the connection pool size, or loggers for logging SQL queries:
|
114
|
+
|
115
|
+
DB = Sequel.connect("postgres://postgres:postgres@localhost/my_db",
|
116
|
+
:max_connections => 10, :logger => Logger.new('log/db.log'))
|
117
|
+
|
118
|
+
You can specify a block to connect, which will disconnect from the database after it completes:
|
119
|
+
|
120
|
+
Sequel.connect('postgres://cico:12345@localhost:5432/mydb'){|db| db[:posts].delete}
|
121
|
+
|
122
|
+
=== Arbitrary SQL queries
|
123
|
+
|
124
|
+
You can execute arbitrary SQL code using Database#run:
|
125
|
+
|
126
|
+
DB.run("create table t (a text, b text)")
|
127
|
+
DB.run("insert into t values ('a', 'b')")
|
128
|
+
|
129
|
+
You can also create datasets based on raw SQL:
|
130
|
+
|
131
|
+
dataset = DB['select id from items']
|
132
|
+
dataset.count # will return the number of records in the result set
|
133
|
+
dataset.map(:id) # will return an array containing all values of the id column in the result set
|
134
|
+
|
135
|
+
You can also fetch records with raw SQL through the dataset:
|
136
|
+
|
137
|
+
DB['select * from items'].each do |row|
|
138
|
+
p row
|
139
|
+
end
|
140
|
+
|
141
|
+
You can use placeholders in your SQL string as well:
|
142
|
+
|
143
|
+
name = 'Jim'
|
144
|
+
DB['select * from items where name = ?', name].each do |row|
|
145
|
+
p row
|
146
|
+
end
|
147
|
+
|
148
|
+
=== Getting Dataset Instances
|
149
|
+
|
150
|
+
Datasets are the primary way records are retrieved and manipulated. They are generally created via the Database#from or Database#[] methods:
|
151
|
+
|
152
|
+
posts = DB.from(:posts)
|
153
|
+
posts = DB[:posts] # same
|
154
|
+
|
155
|
+
Datasets will only fetch records when you tell them to. They can be manipulated to filter records, change ordering, join tables, etc..
|
156
|
+
|
157
|
+
=== Retrieving Records
|
158
|
+
|
159
|
+
You can retrieve all records by using the all method:
|
160
|
+
|
161
|
+
posts.all
|
162
|
+
# SELECT * FROM posts
|
163
|
+
|
164
|
+
The all method returns an array of hashes, where each hash corresponds to a record.
|
165
|
+
|
166
|
+
You can also iterate through records one at a time:
|
167
|
+
|
168
|
+
posts.each{|row| p row}
|
169
|
+
|
170
|
+
Or perform more advanced stuff:
|
171
|
+
|
172
|
+
names_and_dates = posts.map{|r| [r[:name], r[:date]]}
|
173
|
+
old_posts, recent_posts = posts.partition{|r| r[:date] < Date.today - 7}
|
174
|
+
|
175
|
+
You can also retrieve the first record in a dataset:
|
176
|
+
|
177
|
+
posts.first
|
178
|
+
# SELECT * FROM posts LIMIT 1
|
179
|
+
|
180
|
+
Or retrieve a single record with a specific value:
|
181
|
+
|
182
|
+
posts[:id => 1]
|
183
|
+
# SELECT * FROM posts WHERE id = 1 LIMIT 1
|
184
|
+
|
185
|
+
If the dataset is ordered, you can also ask for the last record:
|
186
|
+
|
187
|
+
posts.order(:stamp).last
|
188
|
+
# SELECT * FROM posts ORDER BY stamp DESC LIMIT 1
|
189
|
+
|
190
|
+
=== Filtering Records
|
191
|
+
|
192
|
+
An easy way to filter records is to provide a hash of values to match:
|
193
|
+
|
194
|
+
my_posts = posts.filter(:category => 'ruby', :author => 'david')
|
195
|
+
# WHERE category = 'ruby' AND author = 'david'
|
196
|
+
|
197
|
+
You can also specify ranges:
|
198
|
+
|
199
|
+
my_posts = posts.filter(:stamp => (Date.today - 14)..(Date.today - 7))
|
200
|
+
# WHERE stamp >= '2010-06-30' AND stamp <= '2010-07-07'
|
201
|
+
|
202
|
+
Or arrays of values:
|
203
|
+
|
204
|
+
my_posts = posts.filter(:category => ['ruby', 'postgres', 'linux'])
|
205
|
+
# WHERE category IN ('ruby', 'postgres', 'linux')
|
206
|
+
|
207
|
+
Sequel also accepts expressions:
|
208
|
+
|
209
|
+
my_posts = posts.filter{|o| o.stamp > Date.today << 1}
|
210
|
+
# WHERE stamp > '2010-06-14'
|
211
|
+
|
212
|
+
Some adapters will also let you specify Regexps:
|
213
|
+
|
214
|
+
my_posts = posts.filter(:category => /ruby/i)
|
215
|
+
# WHERE category ~* 'ruby'
|
216
|
+
|
217
|
+
You can also use an inverse filter:
|
218
|
+
|
219
|
+
my_posts = posts.exclude(:category => /ruby/i)
|
220
|
+
# WHERE category !~* 'ruby'
|
221
|
+
|
222
|
+
You can also specify a custom WHERE clause using a string:
|
223
|
+
|
224
|
+
posts.filter('stamp IS NOT NULL')
|
225
|
+
# WHERE stamp IS NOT NULL
|
226
|
+
|
227
|
+
You can use parameters in your string, as well:
|
228
|
+
|
229
|
+
author_name = 'JKR'
|
230
|
+
posts.filter('(stamp < ?) AND (author != ?)', Date.today - 3, author_name)
|
231
|
+
# WHERE (stamp < '2010-07-11') AND (author != 'JKR')
|
232
|
+
posts.filter{|o| (o.stamp < Date.today - 3) & ~{:author => author_name}} # same as above
|
233
|
+
|
234
|
+
Datasets can also be used as subqueries:
|
235
|
+
|
236
|
+
DB[:items].filter('price > ?', DB[:items].select{|o| o.avg(:price) + 100})
|
237
|
+
# WHERE price > (SELECT avg(price) + 100 FROM items)
|
238
|
+
|
239
|
+
After filtering you can retrieve the matching records by using any of the retrieval methods:
|
240
|
+
|
241
|
+
my_posts.each{|row| p row}
|
242
|
+
|
243
|
+
See the doc/dataset_filtering.rdoc file for more details.
|
244
|
+
|
245
|
+
=== Summarizing Records
|
246
|
+
|
247
|
+
Counting records is easy:
|
248
|
+
|
249
|
+
posts.filter(:category => /ruby/i).count
|
250
|
+
# SELECT COUNT(*) FROM posts WHERE category ~* 'ruby'
|
251
|
+
|
252
|
+
And you can also query maximum/minimum values:
|
253
|
+
|
254
|
+
max = DB[:history].max(:value)
|
255
|
+
# SELECT max(value) FROM history
|
256
|
+
|
257
|
+
min = DB[:history].min(:value)
|
258
|
+
# SELECT min(value) FROM history
|
259
|
+
|
260
|
+
Or calculate a sum or average:
|
261
|
+
sum = DB[:items].sum(:price)
|
262
|
+
# SELECT sum(price) FROM items
|
263
|
+
avg = DB[:items].avg(:price)
|
264
|
+
# SELECT avg(price) FROM items
|
265
|
+
|
266
|
+
=== Ordering Records
|
267
|
+
|
268
|
+
Ordering datasets is simple:
|
269
|
+
|
270
|
+
posts.order(:stamp)
|
271
|
+
# ORDER BY stamp
|
272
|
+
posts.order(:stamp, :name)
|
273
|
+
# ORDER BY stamp, name
|
274
|
+
|
275
|
+
Chaining order doesn't work the same as filter:
|
276
|
+
|
277
|
+
posts.order(:stamp).order(:name)
|
278
|
+
# ORDER BY name
|
279
|
+
|
280
|
+
The order_more method chains this way, though:
|
281
|
+
|
282
|
+
posts.order(:stamp).order_more(:name)
|
283
|
+
# ORDER BY stamp, name
|
284
|
+
|
285
|
+
You can also specify descending order:
|
286
|
+
|
287
|
+
posts.order(:stamp.desc)
|
288
|
+
# ORDER BY stamp DESC
|
289
|
+
|
290
|
+
=== Selecting Columns
|
291
|
+
|
292
|
+
Selecting specific columns to be returned is also simple:
|
293
|
+
|
294
|
+
posts.select(:stamp)
|
295
|
+
# SELECT stamp FROM posts
|
296
|
+
posts.select(:stamp, :name)
|
297
|
+
# SELECT stamp, name FROM posts
|
298
|
+
|
299
|
+
Chaining select works like order, not filter:
|
300
|
+
|
301
|
+
posts.select(:stamp).select(:name)
|
302
|
+
# SELECT name FROM posts
|
303
|
+
|
304
|
+
As you might expect, there is an order_more equivalent for select:
|
305
|
+
|
306
|
+
posts.select(:stamp).select_more(:name)
|
307
|
+
# SELECT stamp, name FROM posts
|
308
|
+
|
309
|
+
=== Deleting Records
|
310
|
+
|
311
|
+
Deleting records from the table is done with delete:
|
312
|
+
|
313
|
+
posts.filter('stamp < ?', Date.today - 3).delete
|
314
|
+
# DELETE FROM posts WHERE stamp < '2010-07-11'
|
315
|
+
|
316
|
+
Be very careful when deleting, as delete affects all rows in the dataset.
|
317
|
+
Filter first, delete second, unless you want to empty the table:
|
318
|
+
|
319
|
+
# DO THIS:
|
320
|
+
posts.filter('stamp < ?', Date.today - 7).delete
|
321
|
+
# NOT THIS:
|
322
|
+
posts.delete.filter('stamp < ?', Date.today - 7)
|
323
|
+
|
324
|
+
=== Inserting Records
|
325
|
+
|
326
|
+
Inserting records into the table is done with insert:
|
327
|
+
|
328
|
+
posts.insert(:category => 'ruby', :author => 'david')
|
329
|
+
# INSERT INTO posts (category, author) VALUES ('ruby', 'david')
|
330
|
+
|
331
|
+
=== Updating Records
|
332
|
+
|
333
|
+
Updating records in the table is done with update:
|
334
|
+
|
335
|
+
posts.filter('stamp < ?', Date.today - 7).update(:state => 'archived')
|
336
|
+
# UPDATE posts SET state = 'archived' WHERE stamp < '2010-07-07'
|
337
|
+
|
338
|
+
You can reference table columns when choosing what values to set:
|
339
|
+
|
340
|
+
posts.filter{|o| o.stamp < Date.today - 7}.update(:backup_number => :backup_number + 1)
|
341
|
+
# UPDATE posts SET backup_number = backup_number + 1 WHERE stamp < '2010-07-07'
|
342
|
+
|
343
|
+
As with delete, this affects all rows in the dataset, so filter first,
|
344
|
+
update second, unless you want to update all rows:
|
345
|
+
|
346
|
+
# DO THIS:
|
347
|
+
posts.filter('stamp < ?', Date.today - 7).update(:state => 'archived')
|
348
|
+
# NOT THIS:
|
349
|
+
posts.update(:state => 'archived').filter('stamp < ?', Date.today - 7)
|
350
|
+
|
351
|
+
=== Joining Tables
|
352
|
+
|
353
|
+
Sequel makes it easy to join tables:
|
354
|
+
|
355
|
+
order_items = DB[:items].join(:order_items, :item_id => :id).
|
356
|
+
filter(:order_items__order_id => 1234)
|
357
|
+
|
358
|
+
This is equivalent to the SQL:
|
359
|
+
|
360
|
+
SELECT * FROM items INNER JOIN order_items
|
361
|
+
ON order_items.item_id = items.id
|
362
|
+
WHERE order_items.order_id = 1234
|
363
|
+
|
364
|
+
You can then do anything you like with the dataset:
|
365
|
+
|
366
|
+
order_total = order_items.sum(:price)
|
367
|
+
|
368
|
+
Which is equivalent to the SQL:
|
369
|
+
|
370
|
+
SELECT sum(price) FROM items INNER JOIN order_items
|
371
|
+
ON order_items.item_id = items.id
|
372
|
+
WHERE order_items.order_id = 1234
|
373
|
+
|
374
|
+
=== Graphing Datasets
|
375
|
+
|
376
|
+
When retrieving records from joined datasets, you get the results in a single hash, which is subject to clobbering if you have columns with the same name in multiple tables:
|
377
|
+
|
378
|
+
DB[:items].join(:order_items, :item_id => :id).first
|
379
|
+
=> {:id=>order_items.id, :item_id=>order_items.item_id}
|
380
|
+
|
381
|
+
Using graph, you can split the result hashes into subhashes, one per join:
|
382
|
+
|
383
|
+
DB[:items].graph(:order_items, :item_id => :id).first
|
384
|
+
=> {:items=>{:id=>items.id}, :order_items=>{:id=>order_items.id, :item_id=>order_items.item_id}}
|
385
|
+
|
386
|
+
== An aside: column references in Sequel
|
387
|
+
|
388
|
+
Sequel expects column names to be specified using symbols. In addition, returned hashes always use symbols as their keys. This allows you to freely mix literal values and column references in many cases. For example, the two following lines produce equivalent SQL:
|
389
|
+
|
390
|
+
items.filter(:x => 1)
|
391
|
+
# SELECT * FROM items WHERE (x = 1)
|
392
|
+
items.filter(1 => :x)
|
393
|
+
# SELECT * FROM items WHERE (1 = x)"
|
394
|
+
|
395
|
+
Ruby strings are generally treated as SQL strings:
|
396
|
+
|
397
|
+
items.filter(:x => 'x')
|
398
|
+
# SELECT * FROM items WHERE (x = 'x')
|
399
|
+
|
400
|
+
=== Qualifying column names
|
401
|
+
|
402
|
+
Column references can be qualified by using the double underscore special notation :table__column:
|
403
|
+
|
404
|
+
items.literal(:items__price)
|
405
|
+
# items.price
|
406
|
+
|
407
|
+
=== Column aliases
|
408
|
+
|
409
|
+
You can also alias columns by using the triple undersecore special notation :column___alias or :table__column___alias:
|
410
|
+
|
411
|
+
items.literal(:price___p)
|
412
|
+
# price AS p
|
413
|
+
items.literal(:items__price___p)
|
414
|
+
# items.price AS p
|
415
|
+
|
416
|
+
Another way to alias columns is to use the #as method:
|
417
|
+
|
418
|
+
items.literal(:price.as(:p))
|
419
|
+
# price AS p
|
420
|
+
|
421
|
+
== Sequel Models
|
422
|
+
|
423
|
+
A model class wraps a dataset, and an instance of that class wraps a single record in the dataset.
|
424
|
+
|
425
|
+
Model classes are defined as regular Ruby classes:
|
426
|
+
|
427
|
+
DB = Sequel.connect('sqlite://blog.db')
|
428
|
+
class Post < Sequel::Model
|
429
|
+
end
|
430
|
+
|
431
|
+
Just like in DataMapper or ActiveRecord, Sequel model classes assume that the table name is a plural of the class name:
|
432
|
+
|
433
|
+
Post.table_name #=> :posts
|
434
|
+
|
435
|
+
You can, however, explicitly set the table name or even the dataset used:
|
436
|
+
|
437
|
+
class Post < Sequel::Model(:my_posts)
|
438
|
+
end
|
439
|
+
# or:
|
440
|
+
Post.set_dataset :my_posts
|
441
|
+
|
442
|
+
If you use a symbol, it assumes you are referring to the table with the same name. You can also give it a dataset, which will set the defaults for all retrievals for that model:
|
443
|
+
|
444
|
+
Post.set_dataset DB[:my_posts].filter(:category => 'ruby')
|
445
|
+
Post.set_dataset DB[:my_posts].select(:id, :name).order(:date)
|
446
|
+
|
447
|
+
=== Model instances
|
448
|
+
|
449
|
+
Model instances are identified by a primary key. In most cases, Sequel can introspec the database to determine the primary key, but if not, it defaults to using :id. The Model.[] method can be used to fetch records by their primary key:
|
450
|
+
|
451
|
+
post = Post[123]
|
452
|
+
|
453
|
+
The Model#pk method is used to retrieve the record's primary key value:
|
454
|
+
|
455
|
+
post.pk #=> 123
|
456
|
+
|
457
|
+
Sequel models allow you to use any column as a primary key, and even composite keys made from multiple columns:
|
458
|
+
|
459
|
+
class Post < Sequel::Model
|
460
|
+
set_primary_key [:category, :title]
|
461
|
+
end
|
462
|
+
|
463
|
+
post = Post['ruby', 'hello world']
|
464
|
+
post.pk #=> ['ruby', 'hello world']
|
465
|
+
|
466
|
+
You can also define a model class that does not have a primary key, but then you lose the ability to easily update and delete records.
|
467
|
+
|
468
|
+
A model instance can also be fetched by specifying a condition:
|
469
|
+
|
470
|
+
post = Post[:title => 'hello world']
|
471
|
+
post = Post.find{|o| o.num_comments < 10}
|
472
|
+
|
473
|
+
=== Iterating over records
|
474
|
+
|
475
|
+
A model class lets you iterate over subsets of records by proxying many methods to the underlying dataset. This means that you can use most of the Dataset API to create customized queries that return model instances, e.g.:
|
476
|
+
|
477
|
+
Post.filter(:category => 'ruby').each{|post| p post}
|
478
|
+
|
479
|
+
You can also manipulate the records in the dataset:
|
480
|
+
|
481
|
+
Post.filter{|o| o.num_comments < 7}.delete
|
482
|
+
Post.filter(:title.like(/ruby/)).update(:category => 'ruby')
|
483
|
+
|
484
|
+
=== Accessing record values
|
485
|
+
|
486
|
+
A model instances stores its values as a hash:
|
487
|
+
|
488
|
+
post.values #=> {:id => 123, :category => 'ruby', :title => 'hello world'}
|
489
|
+
|
490
|
+
You can read the record values as object attributes, assuming the attribute names are valid columns in the model's dataset:
|
491
|
+
|
492
|
+
post.id #=> 123
|
493
|
+
post.title #=> 'hello world'
|
494
|
+
|
495
|
+
If the record's attributes names are not valid columns in the model's dataset (maybe because you used select_more to add a computed value column), you can use Model#[] to access the values:
|
496
|
+
|
497
|
+
post[:id] #=> 123
|
498
|
+
post[:title] #=> 'hello world'
|
499
|
+
|
500
|
+
You can also change record values:
|
501
|
+
|
502
|
+
post.title = 'hey there'
|
503
|
+
# or
|
504
|
+
post.set(:title=>'hey there')
|
505
|
+
|
506
|
+
That will just change the value for the object, it will not persist the changes to the database. To persist the record, call the #save method:
|
507
|
+
|
508
|
+
post.save
|
509
|
+
|
510
|
+
If you want to modify record values and save the changes to the object after doing so, use the #update method:
|
511
|
+
|
512
|
+
post.update(:title => 'hey there')
|
513
|
+
|
514
|
+
=== Creating new records
|
515
|
+
|
516
|
+
New records can be created by calling Model.create:
|
517
|
+
|
518
|
+
post = Post.create(:title => 'hello world')
|
519
|
+
|
520
|
+
Another way is to construct a new instance and save it later:
|
521
|
+
|
522
|
+
post = Post.new
|
523
|
+
post.title = 'hello world'
|
524
|
+
post.save
|
525
|
+
|
526
|
+
You can also supply a block to Model.new and Model.create:
|
527
|
+
|
528
|
+
post = Post.new do |p|
|
529
|
+
p.title = 'hello world'
|
530
|
+
end
|
531
|
+
|
532
|
+
post = Post.create{|p| p.title = 'hello world'}
|
533
|
+
|
534
|
+
=== Hooks
|
535
|
+
|
536
|
+
You can execute custom code when creating, updating, or deleting records by defining hook methods. The before_create and after_create hook methods wrap record creation. The before_update and after_update hook methods wrap record updating. The before_save and after_save hook methods wrap record creation and updating. The before_destroy and after_destroy hook methods wrap destruction. The before_validation and after_validation hook methods wrap validation. Example:
|
537
|
+
|
538
|
+
class Post < Sequel::Model
|
539
|
+
def after_create
|
540
|
+
super
|
541
|
+
author.increase_post_count
|
542
|
+
end
|
543
|
+
|
544
|
+
def after_destroy
|
545
|
+
super
|
546
|
+
author.decrease_post_count
|
547
|
+
end
|
548
|
+
end
|
549
|
+
|
550
|
+
Note the use of super if you define your own hook methods. Almost all Sequel::Model class and instance methods (not just hook methods) can be overridden safely, but you have to make sure to call super when doing so, otherwise you risk breaking things.
|
551
|
+
|
552
|
+
For the example above, you should probably use a database trigger if you can. Hooks can be used for data integrity, but they will only enforce that integrity when you are using the model. If you plan on allowing any other access to the database, it's best to use database triggers for data integrity.
|
553
|
+
|
554
|
+
=== Deleting records
|
555
|
+
|
556
|
+
You can delete individual records by calling #delete or #destroy. The only difference between the two methods is that #destroy invokes before_destroy and after_destroy hook methods, while #delete does not:
|
557
|
+
|
558
|
+
post.delete #=> bypasses hooks
|
559
|
+
post.destroy #=> runs hooks
|
560
|
+
|
561
|
+
Records can also be deleted en-masse by invoking Model.delete and Model.destroy. As stated above, you can specify filters for the deleted records:
|
562
|
+
|
563
|
+
Post.filter(:category => 32).delete #=> bypasses hooks
|
564
|
+
Post.filter(:category => 32).destroy #=> runs hooks
|
565
|
+
|
566
|
+
Please note that if Model.destroy is called, each record is deleted
|
567
|
+
separately, but Model.delete deletes all matching records with a single
|
568
|
+
SQL query.
|
569
|
+
|
570
|
+
=== Associations
|
571
|
+
|
572
|
+
Associations are used in order to specify relationships between model classes that reflect relationships between tables in the database, which are usually specified using foreign keys.
|
573
|
+
|
574
|
+
class Post < Sequel::Model
|
575
|
+
many_to_one :author
|
576
|
+
one_to_many :comments
|
577
|
+
many_to_many :tags
|
578
|
+
end
|
579
|
+
|
580
|
+
many_to_one creates a getter and setter for each model object:
|
581
|
+
|
582
|
+
class Post < Sequel::Model
|
583
|
+
many_to_one :author
|
584
|
+
end
|
585
|
+
|
586
|
+
post = Post.create(:name => 'hi!')
|
587
|
+
post.author = Author[:name => 'Sharon']
|
588
|
+
post.author
|
589
|
+
|
590
|
+
one_to_many and many_to_many create a getter method, a method for adding an object to the association, a method for removing an object from the association, and a method for removing all associated objects from the association:
|
591
|
+
|
592
|
+
class Post < Sequel::Model
|
593
|
+
one_to_many :comments
|
594
|
+
many_to_many :tags
|
595
|
+
end
|
596
|
+
|
597
|
+
post = Post.create(:name => 'hi!')
|
598
|
+
post.comments
|
599
|
+
comment = Comment.create(:text=>'hi')
|
600
|
+
post.add_comment(comment)
|
601
|
+
post.remove_comment(comment)
|
602
|
+
post.remove_all_comments
|
603
|
+
tag = Tag.create(:tag=>'interesting')
|
604
|
+
post.add_tag(tag)
|
605
|
+
post.remove_tag(tag)
|
606
|
+
post.remove_all_tags
|
607
|
+
|
608
|
+
Note that the remove_* and remove_all_* methods do not delete the object from the database, they merely disassociate the associated object from the receiver.
|
609
|
+
|
610
|
+
All associations add a dataset method that can be used to further filter or reorder the returned objects, or modify all of them:
|
611
|
+
|
612
|
+
# Delete all of this post's comments from the database
|
613
|
+
post.comments_dataset.destroy
|
614
|
+
|
615
|
+
# Return all tags related to this post with no subscribers, ordered by the tag's name
|
616
|
+
post.tags_dataset.filter(:subscribers=>0).order(:name).all
|
617
|
+
|
618
|
+
=== Eager Loading
|
619
|
+
|
620
|
+
Associations can be eagerly loaded via .eager and the :eager association option. Eager loading is used when loading a group of objects. It loads all associated objects for all of the current objects in one query, instead of using a separate query to get the associated objects for each current object. Eager loading requires that you retrieve all model objects at once via .all (instead of individually by .each). Eager loading can be cascaded, loading association's associated objects.
|
621
|
+
|
622
|
+
class Person < Sequel::Model
|
623
|
+
one_to_many :posts, :eager=>[:tags]
|
624
|
+
end
|
625
|
+
|
626
|
+
class Post < Sequel::Model
|
627
|
+
many_to_one :person
|
628
|
+
one_to_many :replies
|
629
|
+
many_to_many :tags
|
630
|
+
end
|
631
|
+
|
632
|
+
class Tag < Sequel::Model
|
633
|
+
many_to_many :posts
|
634
|
+
many_to_many :replies
|
635
|
+
end
|
636
|
+
|
637
|
+
class Reply < Sequel::Model
|
638
|
+
many_to_one :person
|
639
|
+
many_to_one :post
|
640
|
+
many_to_many :tags
|
641
|
+
end
|
642
|
+
|
643
|
+
# Eager loading via .eager
|
644
|
+
Post.eager(:person).all
|
645
|
+
|
646
|
+
# eager is a dataset method, so it works with filters/orders/limits/etc.
|
647
|
+
Post.filter{|o| o.topic > 'M'}.order(:date).limit(5).eager(:person).all
|
648
|
+
|
649
|
+
person = Person.first
|
650
|
+
# Eager loading via :eager (will eagerly load the tags for this person's posts)
|
651
|
+
person.posts
|
652
|
+
|
653
|
+
# These are equivalent
|
654
|
+
Post.eager(:person, :tags).all
|
655
|
+
Post.eager(:person).eager(:tags).all
|
656
|
+
|
657
|
+
# Cascading via .eager
|
658
|
+
Tag.eager(:posts=>:replies).all
|
659
|
+
|
660
|
+
# Will also grab all associated posts' tags (because of :eager)
|
661
|
+
Reply.eager(:person=>:posts).all
|
662
|
+
|
663
|
+
# No depth limit (other than memory/stack), and will also grab posts' tags
|
664
|
+
# Loads all people, their posts, their posts' tags, replies to those posts,
|
665
|
+
# the person for each reply, the tag for each reply, and all posts and
|
666
|
+
# replies that have that tag. Uses a total of 8 queries.
|
667
|
+
Person.eager(:posts=>{:replies=>[:person, {:tags=>{:posts, :replies}}]}).all
|
668
|
+
|
669
|
+
In addition to using eager, you can also use eager_graph, which will use a single query to get the object and all associated objects. This may be necessary if you want to filter or order the result set based on columns in associated tables. It works with cascading as well, the syntax is exactly the same. Note that using eager_graph to eagerly load multiple *_to_many associations will cause the result set to be a cartesian product, so you should be very careful with your filters when using it in that case.
|
670
|
+
|
671
|
+
=== Extending the underlying dataset
|
672
|
+
|
673
|
+
The obvious way to add table-wide logic is to define class methods to the model class definition. That way you can define subsets of the underlying dataset, change the ordering, or perform actions on multiple records:
|
674
|
+
|
675
|
+
class Post < Sequel::Model
|
676
|
+
def self.posts_with_few_comments
|
677
|
+
filter{|o| o.num_comments < 30}
|
678
|
+
end
|
679
|
+
|
680
|
+
def self.clean_posts_with_few_comments
|
681
|
+
posts_with_few_comments.delete
|
682
|
+
end
|
683
|
+
end
|
684
|
+
|
685
|
+
You can also implement table-wide logic by defining methods on the dataset:
|
686
|
+
|
687
|
+
class Post < Sequel::Model
|
688
|
+
def_dataset_method(:posts_with_few_comments) do
|
689
|
+
filter{|o| o.num_comments < 30}
|
690
|
+
end
|
691
|
+
|
692
|
+
def_dataset_method(:clean_posts_with_few_comments) do
|
693
|
+
posts_with_few_comments.delete
|
694
|
+
end
|
695
|
+
end
|
696
|
+
|
697
|
+
This is the recommended way of implementing table-wide operations, and allows you to have access to your model API from filtered datasets as well:
|
698
|
+
|
699
|
+
Post.filter(:category => 'ruby').clean_posts_with_few_comments
|
700
|
+
|
701
|
+
Sequel models also provide a short hand notation for filters:
|
702
|
+
|
703
|
+
class Post < Sequel::Model
|
704
|
+
subset(:posts_with_few_comments){|o| o.num_comments < 30}
|
705
|
+
subset :invisible, ~:visible
|
706
|
+
end
|
707
|
+
|
708
|
+
=== Model Validations
|
709
|
+
|
710
|
+
You can define a validate method for your model, which #save
|
711
|
+
will check before attempting to save the model in the database.
|
712
|
+
If an attribute of the model isn't valid, you should add a error
|
713
|
+
message for that attribute to the model object's errors. If an
|
714
|
+
object has any errors added by the validate method, save will
|
715
|
+
raise an error or return false depending on how it is configured.
|
716
|
+
|
717
|
+
class Post < Sequel::Model
|
718
|
+
def validate
|
719
|
+
errors.add(:name, "can't be empty") if name.empty?
|
720
|
+
errors.add(:written_on, "should be in the past") if written_on >= Time.now
|
721
|
+
end
|
722
|
+
end
|
723
|
+
|