sequel 3.11.0 → 3.12.0

Sign up to get free protection for your applications and to get access to all the features.
Files changed (136) hide show
  1. data/CHANGELOG +70 -0
  2. data/Rakefile +1 -1
  3. data/doc/active_record.rdoc +896 -0
  4. data/doc/advanced_associations.rdoc +46 -31
  5. data/doc/association_basics.rdoc +14 -9
  6. data/doc/dataset_basics.rdoc +3 -3
  7. data/doc/migration.rdoc +1011 -0
  8. data/doc/model_hooks.rdoc +198 -0
  9. data/doc/querying.rdoc +811 -86
  10. data/doc/release_notes/3.12.0.txt +304 -0
  11. data/doc/sharding.rdoc +17 -0
  12. data/doc/sql.rdoc +537 -0
  13. data/doc/validations.rdoc +501 -0
  14. data/lib/sequel/adapters/jdbc.rb +19 -27
  15. data/lib/sequel/adapters/jdbc/postgresql.rb +0 -7
  16. data/lib/sequel/adapters/mysql.rb +5 -4
  17. data/lib/sequel/adapters/odbc.rb +3 -2
  18. data/lib/sequel/adapters/shared/mssql.rb +7 -6
  19. data/lib/sequel/adapters/shared/mysql.rb +2 -7
  20. data/lib/sequel/adapters/shared/postgres.rb +2 -8
  21. data/lib/sequel/adapters/shared/sqlite.rb +2 -5
  22. data/lib/sequel/adapters/sqlite.rb +4 -4
  23. data/lib/sequel/core.rb +0 -1
  24. data/lib/sequel/database.rb +2 -1060
  25. data/lib/sequel/database/connecting.rb +227 -0
  26. data/lib/sequel/database/dataset.rb +58 -0
  27. data/lib/sequel/database/dataset_defaults.rb +127 -0
  28. data/lib/sequel/database/logging.rb +62 -0
  29. data/lib/sequel/database/misc.rb +246 -0
  30. data/lib/sequel/database/query.rb +390 -0
  31. data/lib/sequel/database/schema_generator.rb +7 -3
  32. data/lib/sequel/database/schema_methods.rb +351 -7
  33. data/lib/sequel/dataset/actions.rb +9 -2
  34. data/lib/sequel/dataset/misc.rb +6 -2
  35. data/lib/sequel/dataset/mutation.rb +3 -11
  36. data/lib/sequel/dataset/query.rb +49 -6
  37. data/lib/sequel/exceptions.rb +3 -0
  38. data/lib/sequel/extensions/migration.rb +395 -113
  39. data/lib/sequel/extensions/schema_dumper.rb +21 -13
  40. data/lib/sequel/model.rb +27 -25
  41. data/lib/sequel/model/associations.rb +72 -34
  42. data/lib/sequel/model/base.rb +74 -18
  43. data/lib/sequel/model/errors.rb +8 -1
  44. data/lib/sequel/plugins/active_model.rb +8 -0
  45. data/lib/sequel/plugins/association_pks.rb +87 -0
  46. data/lib/sequel/plugins/association_proxies.rb +8 -0
  47. data/lib/sequel/plugins/boolean_readers.rb +12 -6
  48. data/lib/sequel/plugins/caching.rb +14 -7
  49. data/lib/sequel/plugins/class_table_inheritance.rb +15 -9
  50. data/lib/sequel/plugins/composition.rb +2 -1
  51. data/lib/sequel/plugins/force_encoding.rb +10 -7
  52. data/lib/sequel/plugins/hook_class_methods.rb +12 -11
  53. data/lib/sequel/plugins/identity_map.rb +9 -0
  54. data/lib/sequel/plugins/instance_hooks.rb +23 -13
  55. data/lib/sequel/plugins/lazy_attributes.rb +4 -1
  56. data/lib/sequel/plugins/many_through_many.rb +18 -4
  57. data/lib/sequel/plugins/nested_attributes.rb +1 -0
  58. data/lib/sequel/plugins/optimistic_locking.rb +1 -1
  59. data/lib/sequel/plugins/rcte_tree.rb +9 -8
  60. data/lib/sequel/plugins/schema.rb +8 -0
  61. data/lib/sequel/plugins/serialization.rb +1 -3
  62. data/lib/sequel/plugins/sharding.rb +135 -0
  63. data/lib/sequel/plugins/single_table_inheritance.rb +117 -25
  64. data/lib/sequel/plugins/skip_create_refresh.rb +35 -0
  65. data/lib/sequel/plugins/string_stripper.rb +26 -0
  66. data/lib/sequel/plugins/tactical_eager_loading.rb +8 -0
  67. data/lib/sequel/plugins/timestamps.rb +15 -2
  68. data/lib/sequel/plugins/touch.rb +13 -0
  69. data/lib/sequel/plugins/update_primary_key.rb +48 -0
  70. data/lib/sequel/plugins/validation_class_methods.rb +8 -0
  71. data/lib/sequel/plugins/validation_helpers.rb +1 -1
  72. data/lib/sequel/sql.rb +17 -20
  73. data/lib/sequel/version.rb +1 -1
  74. data/spec/adapters/postgres_spec.rb +5 -5
  75. data/spec/core/core_sql_spec.rb +17 -1
  76. data/spec/core/database_spec.rb +17 -5
  77. data/spec/core/dataset_spec.rb +31 -8
  78. data/spec/core/schema_generator_spec.rb +8 -1
  79. data/spec/core/schema_spec.rb +13 -0
  80. data/spec/extensions/association_pks_spec.rb +85 -0
  81. data/spec/extensions/hook_class_methods_spec.rb +9 -9
  82. data/spec/extensions/migration_spec.rb +339 -219
  83. data/spec/extensions/schema_dumper_spec.rb +28 -17
  84. data/spec/extensions/sharding_spec.rb +272 -0
  85. data/spec/extensions/single_table_inheritance_spec.rb +92 -4
  86. data/spec/extensions/skip_create_refresh_spec.rb +17 -0
  87. data/spec/extensions/string_stripper_spec.rb +23 -0
  88. data/spec/extensions/update_primary_key_spec.rb +65 -0
  89. data/spec/extensions/validation_class_methods_spec.rb +5 -5
  90. data/spec/files/bad_down_migration/001_create_alt_basic.rb +4 -0
  91. data/spec/files/bad_down_migration/002_create_alt_advanced.rb +4 -0
  92. data/spec/files/bad_timestamped_migrations/1273253849_create_sessions.rb +9 -0
  93. data/spec/files/bad_timestamped_migrations/1273253851_create_nodes.rb +9 -0
  94. data/spec/files/bad_timestamped_migrations/1273253853_3_create_users.rb +3 -0
  95. data/spec/files/bad_up_migration/001_create_alt_basic.rb +4 -0
  96. data/spec/files/bad_up_migration/002_create_alt_advanced.rb +3 -0
  97. data/spec/files/convert_to_timestamp_migrations/001_create_sessions.rb +9 -0
  98. data/spec/files/convert_to_timestamp_migrations/002_create_nodes.rb +9 -0
  99. data/spec/files/convert_to_timestamp_migrations/003_3_create_users.rb +4 -0
  100. data/spec/files/convert_to_timestamp_migrations/1273253850_create_artists.rb +9 -0
  101. data/spec/files/convert_to_timestamp_migrations/1273253852_create_albums.rb +9 -0
  102. data/spec/files/duplicate_integer_migrations/001_create_alt_advanced.rb +4 -0
  103. data/spec/files/duplicate_integer_migrations/001_create_alt_basic.rb +4 -0
  104. data/spec/files/duplicate_timestamped_migrations/1273253849_create_sessions.rb +9 -0
  105. data/spec/files/duplicate_timestamped_migrations/1273253853_create_nodes.rb +9 -0
  106. data/spec/files/duplicate_timestamped_migrations/1273253853_create_users.rb +4 -0
  107. data/spec/files/integer_migrations/001_create_sessions.rb +9 -0
  108. data/spec/files/integer_migrations/002_create_nodes.rb +9 -0
  109. data/spec/files/integer_migrations/003_3_create_users.rb +4 -0
  110. data/spec/files/interleaved_timestamped_migrations/1273253849_create_sessions.rb +9 -0
  111. data/spec/files/interleaved_timestamped_migrations/1273253850_create_artists.rb +9 -0
  112. data/spec/files/interleaved_timestamped_migrations/1273253851_create_nodes.rb +9 -0
  113. data/spec/files/interleaved_timestamped_migrations/1273253852_create_albums.rb +9 -0
  114. data/spec/files/interleaved_timestamped_migrations/1273253853_3_create_users.rb +4 -0
  115. data/spec/files/missing_integer_migrations/001_create_alt_basic.rb +4 -0
  116. data/spec/files/missing_integer_migrations/003_create_alt_advanced.rb +4 -0
  117. data/spec/files/missing_timestamped_migrations/1273253849_create_sessions.rb +9 -0
  118. data/spec/files/missing_timestamped_migrations/1273253853_3_create_users.rb +4 -0
  119. data/spec/files/timestamped_migrations/1273253849_create_sessions.rb +9 -0
  120. data/spec/files/timestamped_migrations/1273253851_create_nodes.rb +9 -0
  121. data/spec/files/timestamped_migrations/1273253853_3_create_users.rb +4 -0
  122. data/spec/files/uppercase_timestamped_migrations/1273253849_CREATE_SESSIONS.RB +9 -0
  123. data/spec/files/uppercase_timestamped_migrations/1273253851_CREATE_NODES.RB +9 -0
  124. data/spec/files/uppercase_timestamped_migrations/1273253853_3_CREATE_USERS.RB +4 -0
  125. data/spec/integration/eager_loader_test.rb +20 -20
  126. data/spec/integration/migrator_test.rb +187 -0
  127. data/spec/integration/plugin_test.rb +150 -0
  128. data/spec/integration/schema_test.rb +13 -2
  129. data/spec/model/associations_spec.rb +41 -14
  130. data/spec/model/base_spec.rb +69 -0
  131. data/spec/model/eager_loading_spec.rb +7 -3
  132. data/spec/model/record_spec.rb +79 -4
  133. data/spec/model/validations_spec.rb +21 -9
  134. metadata +66 -5
  135. data/doc/schema.rdoc +0 -36
  136. data/lib/sequel/database/schema_sql.rb +0 -320
@@ -0,0 +1,304 @@
1
+ = Migration Changes
2
+
3
+ * A TimestampMigrator has been added to Sequel, and is
4
+ automatically used if any migration has a version greater than
5
+ 20000100. This migrator operates similarly to the default
6
+ ActiveRecord migrator, in that it allows missing migrations.
7
+ It differs from the ActiveRecord migrator in that it supports
8
+ migrations with the same timestamp/version as well as a wide
9
+ variety of timestamp formats (though the ActiveRecord default
10
+ of YYYYMMDDHHMMSS is recommended and should be used in
11
+ portable code).
12
+
13
+ Sequel still defaults to the old migrator, but you can use the
14
+ new one without making changes to your old migrations. Just
15
+ make sure your new migration starts with a version greater than
16
+ 20000100, and Sequel will automatically convert the previous
17
+ schema table to the new format.
18
+
19
+ * A new migration DSL was added:
20
+
21
+ Sequel.migration do
22
+ up do
23
+ end
24
+
25
+ down do
26
+ end
27
+ end
28
+
29
+ The old style of using a Sequel::Migration subclass is still
30
+ supported, but it is recommended that new code use the new DSL.
31
+
32
+ * The default migrator also had significant issues fixed. First,
33
+ it now saves the migration version after each migration, instead
34
+ of after all migrations, which means Sequel won't attempt to
35
+ apply already applied migrations if there was previously an error
36
+ when applying multiple migrations at once on a database that
37
+ didn't support transactional schema modification.
38
+
39
+ Second, duplicate migration versions in the default migrator now
40
+ raise an exception, as do missing migration versions. Neither
41
+ should happen when using the default migrator, which requires
42
+ consecutive integer versions, similar to the old ActiveRecord
43
+ migrator.
44
+
45
+ * Execution times for migrations are now logged to the database's
46
+ loggers.
47
+
48
+ = New Plugins
49
+
50
+ * A sharding plugin has been added that allows model objects to
51
+ work well with sharded databases. When using it, model objects
52
+ know which shard they were retrieved from, so when you save
53
+ the object, it is saved back to that shard. The sharding plugin
54
+ also works with associations, so associated records are retrieved
55
+ from the same shard the main object was retreived from. The
56
+ sharding plugin also works with both methods of eager loading, and
57
+ provides methods that you can use to create objects on specific
58
+ shards.
59
+
60
+ * An update_primary_key plugin has been added that allows Sequel
61
+ to work correctly if you modify the primary key of a model object.
62
+ This should not be necessary if you are using surrogate keys, but
63
+ if your database uses natural primary keys which can change, this
64
+ should be helpful.
65
+
66
+ * An association_pks plugin has been added that adds association_pks
67
+ and association_pks= methods to model objects for both one_to_many
68
+ and many_to_many associations. The association_pks method returns
69
+ an array of primary key values for the associated objects, and
70
+ the association_pks= method modifies the database to ensure that
71
+ the object is only associated to the objects specified by the
72
+ array of primary keys provided to it.
73
+
74
+ * A string_stripper plugin has been added that strips all strings
75
+ that are assigned to attribute values. This is useful for web
76
+ applications where you want to easily remove leading and trailing
77
+ whitespace in form entries before storing them in the database.
78
+
79
+ * A skip_create_refresh plugin has been added that skips the refresh
80
+ of after you save a new model object. On most databases, Sequel
81
+ refreshes the model object after inserting it in order to get
82
+ values for all of the columns. For performance reasons, you can
83
+ use this plugin to skip the refresh if it isn't necessary for you.
84
+
85
+ = Other New Features
86
+
87
+ * Sequel::Model#set_fields and update_fields were added. These
88
+ methods have a similar API to set_only and update_only, but they
89
+ operate differently. While set_only and update_only operate over
90
+ the hash, these methods operate over the array of fields,
91
+ so they don't raise errors if the hash contains fields not
92
+ in the array:
93
+
94
+ params = {:a=>1, :b=>2, :c=>3}
95
+ album = Album[1]
96
+
97
+ # raises Error because :a is not in the fields
98
+ album.set_only(params, [:b, :c])
99
+
100
+ # Just sets the value of album.b and album.c
101
+ album.set_fields(params, [:b, :c])
102
+
103
+ Other than handling entries in the hash that aren't in the array,
104
+ set_fields and update_fields also handle entries not in the hash
105
+ differently:
106
+
107
+ # Doesn't modify the object, since the hash is empty
108
+ album.set_only({}, [:b, :c])
109
+
110
+ # Sets album.b and album.c to nil, since they aren't in the hash
111
+ album.set_fields({}, [:b, :c])
112
+
113
+ * The :eager_loader association option has a new API, though the
114
+ previous API still works. Instead of accepting three arguments,
115
+ it can now accept a single hash argument, which will use the
116
+ :key_hash, :rows, and :association keys for the previous three
117
+ arguments. The hash will also contain a :self key whose value
118
+ is the dataset doing the eager load, which was not possible to
119
+ determine using the old API.
120
+
121
+ * Sequel::SQL::Expression#hash has been added so that the objects
122
+ are now safe to use as hash keys.
123
+
124
+ * A Dataset#order_prepend method has been added allowing you to
125
+ prepend to an existing order. This is useful if want to modify
126
+ a dataset's order such that it first orders by the columns you
127
+ provide, but for any rows where the columns you provide are
128
+ equal, uses the existing order to further order the dataset:
129
+
130
+ ds.order(:albums__name).order_prepend(:artists__name)
131
+ # ORDER BY artists.name, albums.name
132
+
133
+ * When creating foreign key columns, you can now use a :deferrable
134
+ option to set up a foreign key constraint that is not checked
135
+ until the end of the transaction:
136
+
137
+ DB.create_table(:albums) do
138
+ primary_key :id
139
+ String :name
140
+ foreign_key :artist_id, :artists, :deferrable=>true
141
+ end
142
+
143
+ * many_to_many associations now support a :join_table_block option
144
+ that is used by the add/remove/remove_all methods. It can modify
145
+ the dataset to ensure that certain columns are included when
146
+ inserting or to add a filter so that only certain records are
147
+ deleted. It's useful if you have a many_to_many association that
148
+ is filtered to only a subset of the matching rows in the join
149
+ table.
150
+
151
+ * The single_table_inheritance plugin now supports :model_map and
152
+ :key_map options to set up a custom mapping of column values to
153
+ model classes. For simple situations such as when you are mapping
154
+ integer values to certain classes, a :model_map hash is sufficient:
155
+
156
+ Employee.plugin :single_table_inheritance, :type_id,
157
+ :model_map=>{1=>:Staff, 2=>:Manager}
158
+
159
+ Here the :model_map keys are type_id column values, and the
160
+ :model_map values are symbols or strings specifying class names.
161
+
162
+ For more complex conditions, you can use a pair of procs:
163
+
164
+ Employee.plugin :single_table_inheritance, :type_name,
165
+ :model_map=>proc{|v| v.reverse},
166
+ :key_map=>proc{|klass| klass.name.reverse}
167
+
168
+ Here the type_name column is a string column holding the reverse
169
+ of the class's name.
170
+
171
+ * The single_table_inheritance plugin now correctly sets up subclass
172
+ filters for middle tables in a class hierarchy with more than 2
173
+ levels. For example, with this code:
174
+
175
+ class Employee < Sequel::Model; end
176
+ Employee.plugin :single_table_inheritance, :kind
177
+ class Manager < Employee; end
178
+ class Executive < Manager; end
179
+
180
+ Sequel previously would not return Executives if you used
181
+ Manager.all. It now correctly recognizes subclasses so that it
182
+ will return both Managers and Executives.
183
+
184
+ * Sequel::Model.qualified_primary_key_hash has been added, giving
185
+ you a hash that can be used for filtering. It is similar to
186
+ primary_key_hash, but it qualifies the keys with the model's
187
+ table. It's useful if you have joined the table to another table
188
+ that has columns with the same name, but you want to only look
189
+ for a single model object in that dataset.
190
+
191
+ * For consistency, you can now use Dataset#order_append as an alias
192
+ for order_more.
193
+
194
+ = Other Improvements
195
+
196
+ * Sequel now correctly removes schema entries when altering tables.
197
+ Previously, some adapters that had to query the existing schema
198
+ when altering tables resulted in the previous schema being cached.
199
+
200
+ * Sequel::Model::Errors#on now always returns nil if there are no
201
+ errors on the attribute. Previously, it would return an empty
202
+ array in certain cases. Additionally, Sequel::Model::Errors#empty?
203
+ now returns true if there are no errors, where it certain cases
204
+ it would return false even if there were no errors.
205
+
206
+ * The schema_dumper extension now works with tables specified as
207
+ Sequel::SQL::Identifiers.
208
+
209
+ * Sequel now recognizes the timestamp(N) with(out) time zone column
210
+ type.
211
+
212
+ * The lazy_attributes plugin no longer requires the core extensions
213
+ to work correctly.
214
+
215
+ * DatabaseDisconnectError support has been added to the ODBC adapter,
216
+ allowing Sequel to detect disconnects and remove the connection
217
+ from the connection pool.
218
+
219
+ * A leak of JDBC statement objects when using transactions was
220
+ fixed in the jdbc adapter.
221
+
222
+ * The jdbc adapter now gives a nicer error message if you use a
223
+ connection string that it doesn't recognize and there is an error
224
+ when connecting.
225
+
226
+ * Temporary table creation was fixed on Microsoft SQL Server, but
227
+ it is not recommended as it changes the name of the table. If
228
+ you use Microsoft SQL Server, you should prefix your temporary
229
+ table names with # and use the regular create table method.
230
+
231
+ * A large number of guides were added to Sequel to make it easier
232
+ for new and existing users to learn more about Sequel. The
233
+ following guides were added:
234
+
235
+ * Querying in Sequel
236
+ * Migration and Schema Modification
237
+ * Model Hooks
238
+ * Model Validations
239
+ * Sequel for SQL Users
240
+ * Sequel for ActiveRecord Users
241
+
242
+ * RDoc section support was added to Sequel::Database, making the
243
+ method documentation easier to read.
244
+
245
+ = Backwards Compatibility
246
+
247
+ * Sequel::Database now defines the indexes and tables methods, even
248
+ if the adapter does not implement them, similar to how connect
249
+ and execute are defined. Previously, you could use respond_to? to
250
+ check if the adapter supported them, now they raise
251
+ Sequel::NotImplemented if the database adapter does not implement
252
+ them.
253
+
254
+ * Sequel used to raise NotImplementedError in certain default
255
+ definitions of methods inside Sequel::Database and Sequel::Dataset,
256
+ when the methods were supposed to be overridden in subclasses.
257
+ Sequel now uses a Sequel::NotImplemented exception class for these
258
+ exceptions, which is a subclass of Sequel::Error.
259
+
260
+ * Sequel no longer applies all association options to the dataset
261
+ used to remove all many_to_many associated objects. You should
262
+ use the new :join_table_block option to get similar behavior if
263
+ you were filtering the many_to_many association based on columns
264
+ in the join table and you wanted remove_all to only remove the
265
+ related columns.
266
+
267
+ * Sequel now calls certain before and after hook actions in plugins
268
+ in a different order than before. This should not have an effect
269
+ unless you were relying on them being called in the previous order.
270
+ Now, when overriding before hooks in plugins, Sequel always does
271
+ actions before calling super, and when overriding after hooks in
272
+ plugins, Sequel always does actions after calling super.
273
+
274
+ * The hook_class_methods plugin no longer skips later after hooks if
275
+ a previous after hook returns false. That behavior now only occurs
276
+ for before hooks.
277
+
278
+ * Sequel now only removes primary key values when updating objects if
279
+ you are saving the entire object and you have not modified the
280
+ values of the primary keys. Previously, Sequel would remove
281
+ primary key values when updating even if you specified the primary
282
+ key column specifically or the primary key column was modified and
283
+ you used save_changes/update.
284
+
285
+ * Sequel now uses explicit methods instead of aliases for certain
286
+ methods. This should only affect you if for example you overrode
287
+ Dataset#group to do one thing and wanted Dataset#group_by to do
288
+ the default action. Now, Dataset#group_by, and methods like it, are
289
+ explicit methods that just call the methods they previously
290
+ aliased. This also means that if you were overriding Dataset#group
291
+ and explicitly aliasing group_by to it, you no longer need the
292
+ alias.
293
+
294
+ * The single_table_inheritance plugin now uses IN instead of = for
295
+ subclass filters. This could lead to poor performance if the
296
+ database has a very bad query planner.
297
+
298
+ * The private transaction_statement_object method was removed from
299
+ the JDBC adapter, and Sequel will no longer check for the presence
300
+ of the method in the transaction code.
301
+
302
+ * The Sequel::Migrator object is now a class instead of a module, and
303
+ has been pretty much rewritten. If you were using any methods of
304
+ it besides apply and run, they no longer work.
data/doc/sharding.rdoc CHANGED
@@ -111,3 +111,20 @@ the shard to use. This is fairly easy using a Sequel::Model:
111
111
  end
112
112
 
113
113
  Rainbow.plaintext_for_hash("e580726d31f6e1ad216ffd87279e536d1f74e606")
114
+
115
+ === Sharding Plugin
116
+
117
+ Sequel comes with a sharding plugin that makes it easy to use sharding with model objects.
118
+ It makes sure that objects retrieved from a specific shard are always saved back to that
119
+ shard, allows you to create objects on specific shards, and even makes sure associations
120
+ work well with shards. You just need to remember to set to model to use the plugin:
121
+
122
+ class Rainbow < Sequel::Model(:hashes)
123
+ plugin :sharding
124
+ end
125
+
126
+ Rainbow.server(:a).first(:id=>1).update(:plaintext=>'VGM')
127
+
128
+ If all of your models are sharded, you can set all models to use the plugin via:
129
+
130
+ Sequel::Model.plugin :sharding
data/doc/sql.rdoc ADDED
@@ -0,0 +1,537 @@
1
+ = Sequel for SQL Users
2
+
3
+ One of the main benefits of Sequel is that it doesn't require the user know SQL in order to use it, though SQL knowledge is certainly helpful. Unlike most other Sequel documentation, this guide assumes you know SQL, and provides an easy way to discover how to do something in Sequel given the knowledge of how to do so in SQL.
4
+
5
+ == You Can Just Use SQL
6
+
7
+ With Sequel, it's very easy to just use SQL for your queries. If learning Sequel's DSL seems like a waste of time, you are certainly free to write all your queries in SQL. Sequel uses a few different methods depending on the type of query you are doing.
8
+
9
+ === SELECT
10
+
11
+ For SELECT queries, you should probably use <tt>Database#fetch</tt> with a string and a block:
12
+
13
+ DB.fetch("SELECT * FROM albums") do |row|
14
+ puts row[:name]
15
+ end
16
+
17
+ <tt>Database#fetch</tt> will take the query you give it, execute it on the database, and yield a hash with column symbol keys for each row returned. If you want to use some placeholder variables, you can set the placeholders with ? and add the arguments to fetch:
18
+
19
+ DB.fetch("SELECT * FROM albums WHERE name LIKE ?", 'A%') do |row|
20
+ puts row[:name]
21
+ end
22
+
23
+ You can also use named placeholders by starting the placeholder with a colon, and using a hash for the argument:
24
+
25
+ DB.fetch("SELECT * FROM albums WHERE name LIKE :pattern", :pattern=>'A%') do |row|
26
+ puts row[:name]
27
+ end
28
+
29
+ This can be helpful for long queries where it is difficult to match the ? with the arguments.
30
+
31
+ What Sequel actually does internally is two separate things. It first creates a dataset representing the query, and then it executes the dataset's SQL code to retrieve the objects. Often, you want to define a dataset at some point, but not execute it till later. You can do this by leaving off the block, and storing the dataset in a variable:
32
+
33
+ ds = DB.fetch("SELECT * FROM albums")
34
+
35
+ Then when you want to retrieve the rows later, you can call +each+ on the dataset to retrieve the rows:
36
+
37
+ ds.each{|r| puts r[:name]}
38
+
39
+ You should note that <tt>Database#[]</tt> calls <tt>Database#fetch</tt> if a string is provided, so you can also do:
40
+
41
+ ds = DB["SELECT * FROM albums"]
42
+ ds.each{|r| puts r[:name]}
43
+
44
+ However, note that <tt>Database#[]</tt> cannot take a block directly, you have to call +each+ on the returned dataset. There are plenty of other methods besides +each+, one is +all+ which returns all records as an array:
45
+
46
+ DB["SELECT * FROM albums"].all # [{:id=>1, :name=>'RF', ...}, ...]
47
+
48
+ === INSERT, UPDATE, DELETE
49
+
50
+ INSERT, UPDATE, and DELETE all work the same way. You first create the dataset with the SQL you want to execute using <tt>Database#[]</tt>:
51
+
52
+ insert_ds = DB["INSERT INTO albums (name) VALUES (?)", 'RF']
53
+ update_ds = DB["UPDATE albums SET name = ? WHERE name = ?", 'MO', 'RF']
54
+ delete_ds = DB["DELETE FROM albums WHERE name = ?", 'MO']
55
+
56
+ Then, you call the +insert+, +update+, or +delete+ method on the returned dataset:
57
+
58
+ insert_ds.insert
59
+ update_ds.update
60
+ delete_ds.delete
61
+
62
+ +update+ and +delete+ should return the number of rows affected, and +insert+ should return the autogenerated primary key integer for the row inserted (if any).
63
+
64
+ === Other Queries
65
+
66
+ All other queries such as TRUNCATE, CREATE TABLE, and ALTER TABLE should be executed using <tt>Database#run</tt>:
67
+
68
+ DB.run "CREATE TABLE albums (id integer primary key, name varchar(255))"
69
+
70
+ You can also use <tt>Database#<<</tt>:
71
+
72
+ DB << "ALTER TABLE albums ADD COLUMN copies_sold INTEGER"
73
+
74
+ === Other Places
75
+
76
+ Almost everywhere in Sequel, you can drop down to literal SQL by providing a literal string, which you can create with <tt>String#lit</tt>:
77
+
78
+ DB[:albums].select('name') # SELECT 'name' FROM albums
79
+ DB[:albums].select('name'.lit) # SELECT name FROM albums
80
+
81
+ So you can use Sequel's DSL for everywhere you find it helpful, and fallback to literal SQL if the DSL can't do what you want or you just find literal SQL easier.
82
+
83
+ == Translating SQL Expressions into Sequel
84
+
85
+ The rest of this guide assumes you want to use Sequel's DSL to represent your query, that you know how to write the query in SQL, but you aren't sure how to write it in Sequel.
86
+
87
+ This section will describe how specific SQL expressions are handled in Sequel. The next section will discuss how to create queries by using method chaining on datasets.
88
+
89
+ === <tt>Database#literal</tt>
90
+
91
+ Before we get started, I think it's important to get familiar with the <tt>Database#literal</tt> method, which will return the SQL that will be used for a given expression:
92
+
93
+ DB.literal(1)
94
+ # => "1"
95
+ DB.literal(:column)
96
+ # => "\"column\""
97
+ DB.literal('string')
98
+ # => "'string'"
99
+
100
+ I encourage you to just play around to see how different objects get literalized into SQL
101
+
102
+ === Database Loggers
103
+
104
+ Some Sequel methods handle literalization slightly differently than <tt>Database#literal</tt>. If you want to see all SQL queries that Sequel is sending to the database, you should add a database logger:
105
+
106
+ DB.loggers << Logger.new($stdout)
107
+
108
+ Now that you know how to see what SQL is being used, let's jump in and see how to map SQL syntax to Sequel syntax:
109
+
110
+ === Identifiers
111
+
112
+ In Sequel, SQL identifiers are usually specified as ruby symbols:
113
+
114
+ :column # "column"
115
+
116
+ As you can see, Sequel quotes identifiers by default. Depending on your database, it may uppercase them by default as well:
117
+
118
+ :column # "COLUMN" on some databases
119
+
120
+ A plain symbol is usually treated as an unqualified identifier. However, if you are using multiple tables in a query, and you want to reference a column in one of the tables that has the same name as a column in another one of the tables, you need to qualify that reference. There's two main ways in Sequel to do that. The first is implicit qualification inside the symbol, using the double underscore:
121
+
122
+ :table__column # "table"."column"
123
+
124
+ Note that you can't use a period to separate them:
125
+
126
+ :table.column # calls the column method on the symbol
127
+
128
+ Also note that specifying the period inside the symbol doesn't work if you are quoting identifiers:
129
+
130
+ :"table.column" # "table.column"
131
+
132
+ The other way to qualify an identifier is to use the +qualify+ method on the column symbol with the table symbol:
133
+
134
+ :column.qualify(:table) # "table"."column"
135
+
136
+ Another way to generate identifiers is to use Sequel's {virtual row support}[link:files/doc/virtual_rows_rdoc.html]:
137
+
138
+ DB[:albums].select{name} # SELECT "name" FROM "albums"
139
+ DB[:albums].select{albums__name} # SELECT "albums"."name" FROM "albums"
140
+
141
+ === Numbers
142
+
143
+ In general, ruby numbers map directly to SQL numbers:
144
+
145
+ # Integers
146
+ 1 # 1
147
+ -1 # -1
148
+
149
+ # Floats
150
+ 1.5 # 1.5
151
+
152
+ # BigDecimals
153
+ BigDecimal.new('1000000.123091029') # 1000000.123091029
154
+
155
+ === Strings
156
+
157
+ In general, ruby strings map directly to SQL strings:
158
+
159
+ 'name' # 'name'
160
+ "name" # 'name'
161
+
162
+ === Aliasing
163
+
164
+ Sequel allows for implicit aliasing in column symbols using the triple underscore:
165
+
166
+ :column___alias # "column" AS "alias"
167
+
168
+ You can combine this with implicit qualification:
169
+
170
+ :table__column___alias # "table"."column" AS "alias"
171
+
172
+ You can also use the +as+ method on symbols and most Sequel-specific expression objects:
173
+
174
+ :column.as(:alias) # "column" AS "alias"
175
+ :column.qualify(:table).as(:alias) # "table"."column" AS "alias"
176
+
177
+ === Functions
178
+
179
+ The easiest way to use SQL functions is via a virtual row:
180
+
181
+ DB[:albums].select{function{}} # SELECT function() FROM "albums"
182
+ DB[:albums].select{function(col1, col2)} # SELECT function("col1", "col2") FROM "albums"
183
+
184
+ You can also use the +sql_function+ method on the symbol that contains the function name:
185
+
186
+ :function.sql_function # function()
187
+ :function.sql_function(:col1, :col2) # function("col1", "col2")
188
+
189
+ === Aggregate Functions
190
+
191
+ Aggregate functions work the same way as normal functions, since they share the same syntax:
192
+
193
+ :sum.sql_function(:column) # sum(column)
194
+
195
+ However, if you want to use the DISTINCT modifier to an aggregate function, you either have to use literal SQL or a virtual row block:
196
+
197
+ :sum.sql_function('DISTINCT column'.lit) # sum(DISTINCT column)
198
+ DB[:albums].select{sum(:distinct, :column){}} # SELECT sum(DISTINCT column) FROM albums
199
+
200
+ If you want to use the wildcard as the sole argument of the aggregate function, you again have to use literal SQL or a virtual row block:
201
+
202
+ :count.sql_function('*'.lit) # count(*)
203
+ DB[:albums].select{count(:*){}} # SELECT count(*) FROM albums
204
+
205
+ Note that Sequel provides helper methods for aggregate functions such as +count+, +sum+, +min+, +max+, +avg+, and +group_and_count+, which handle common uses of aggregate functions.
206
+
207
+ === Window Functions
208
+
209
+ If the database supports window functions, Sequel can handle them using a virtual row block:
210
+
211
+ DB[:albums].select{function(:over){}}
212
+ # SELECT function() OVER () FROM albums
213
+
214
+ DB[:albums].select{count(:over, :*=>true){}}
215
+ # SELECT count(*) OVER () FROM albums
216
+
217
+ DB[:albums].select{function(:over, :args=>col1, :partition=>col2, :order=>col3){}}
218
+ # SELECT function(col1) OVER (PARTITION BY col2 ORDER BY col3) FROM albums
219
+
220
+ DB[:albums].select{function(:over, :args=>[c1, c2], :partition=>[c3, c4], :order=>[c5, c6]){}}
221
+ # SELECT function(c1, c2) OVER (PARTITION BY c3, c4 ORDER BY c5, c6) FROM albums
222
+
223
+ === Equality Operator (=)
224
+
225
+ Sequel uses hashes to specify equality:
226
+
227
+ {:column=>1} # ("column" = 1)
228
+
229
+ You can also specify this as an array of two element arrays:
230
+
231
+ [[:column, 1]] # ("column" = 1)
232
+
233
+ === Not Equal Operator (!=)
234
+
235
+ You can specify a not equals condition by inverting the hash or array of two element arrays using +sql_negate+ or ~:
236
+
237
+ {:column => 1}.sql_negate # ("column" != 1)
238
+ [[:column, 1]].sql_negate # ("column" != 1)
239
+ ~{:column => 1} # ("column" != 1)
240
+ ~[[:column, 1]] # ("column" != 1)
241
+
242
+ The most common need for not equals is in filters, in which case you can use the +exclude+ method:
243
+
244
+ DB[:albums].exclude(:column=>1) # SELECT * FROM "albums" WHERE ("column" != 1)
245
+
246
+ === Inclusion and Exclusion Operators (IN, NOT IN)
247
+
248
+ Sequel also uses hashes to specify inclusion, and inversions of those hashes to specify exclusion:
249
+
250
+ {:column=>[1, 2, 3]} # ("column" IN (1, 2, 3))
251
+ ~{:column=>[1, 2, 3]} # ("column" NOT IN (1, 2, 3))
252
+
253
+ As you may have guessed, Sequel switches from an = to an IN when the hash value is an array. It also does this for datasets, which easily allows you to test for inclusion and exclusion in a subselect:
254
+
255
+ {:column=>DB[:albums].select(:id)} # ("column" IN (SELECT "id" FROM "albums"))
256
+ ~{:column=>DB[:albums].select(:id)} # ("column" NOT IN (SELECT "id" FROM "albums"))
257
+
258
+ Sequel also supports the SQL EXISTS operator using <tt>Dataset#exists</tt>:
259
+
260
+ DB[:albums].exists # EXISTS (SELECT * FROM albums)
261
+
262
+ === Identity Operators (IS, IS NOT)
263
+
264
+ Hashes in Sequel use IS if the value is true, false, or nil:
265
+
266
+ {:column=>nil) # ("column" IS NULL)
267
+ {:column=>true) # ("column" IS TRUE)
268
+ {:column=>false) # ("column" IS FALSE)
269
+
270
+ Negation works the same way as it does for equality and inclusion:
271
+
272
+ {:column=>nil).sql_negate # ("column" IS NOT NULL)
273
+ {:column=>true).sql_negate # ("column" IS NOT TRUE)
274
+ {:column=>false).sql_negate # ("column" IS NOT FALSE)
275
+
276
+ === Inversion Operator (NOT)
277
+
278
+ Sequel's general inversion operator is ~, which works on symbols and most Sequel-specific expression objects:
279
+
280
+ ~:column # NOT "column"
281
+
282
+ Note that ~ will actually apply the inversion operation to the underlying object, which is why
283
+
284
+ ~{:column=>1}
285
+
286
+ produces <tt>(column != 1)</tt> instead of <tt>NOT (column = 1)</tt>.
287
+
288
+ === Inequality Operators (< > <= >=)
289
+
290
+ Sequel defines the inequality operators directly on most Sequel-specific expression objects:
291
+
292
+ :column.qualify(:table) > 1 # ("table"."column" > 1)
293
+ :column.qualify(:table) < 1 # ("table"."column" < 1)
294
+ :function.sql_function >= 1 # (function() >= 1)
295
+ :function.sql_function(:column) <= 1 # (function("column") <= 1)
296
+
297
+ If you want to use them on a symbol, you should call +identifier+ on the symbol:
298
+
299
+ :column.identifier > 1 # ("column" > 1)
300
+
301
+ A common use of virtual rows is to handle inequality operators:
302
+
303
+ DB[:albums].filter{col1 > col2} # SELECT * FROM "albums" WHERE ("col1" > "col2")
304
+
305
+ === Standard Mathematical Operators (+ - * /)
306
+
307
+ The standard mathematical operates are defined on symbol and most Sequel-specific expression objects:
308
+
309
+ :column + 1 # "column" + 1
310
+ :table__column - 1 # "table"."column" - 1
311
+ :column.qualify(:table) * 1 # "table"."column" * 1
312
+ :column / 1 # "column" / 1
313
+
314
+ Note that the following does not work:
315
+
316
+ 1 + :column # raises TypeError
317
+
318
+ For commutative operates such as + and *, this isn't a problem as you can just reorder, but non-commutative operators such as - and * cannot be expressed directly. However, Sequel comes with an +sql_expr+ extension that adds an +sql_expr+ method to all objects, allowing you to do:
319
+
320
+ Sequel.extension :sql_expr
321
+ 1.sql_expr / :column # (1 / "column")
322
+
323
+ === Boolean Operators (AND OR)
324
+
325
+ Sequel defines the & and | methods on symbols, hashes, and most Sequel-specific expression objects to handle AND and OR:
326
+
327
+ :column1 & :column2 # ("column1" AND "column2")
328
+ {:column1=>1} | {:column2=>2} # (("column1" = 1) OR ("column2" = 2))
329
+ (:function.sql_function > 1) & :column3 # ((function() > 1) AND "column3")
330
+
331
+ Note the use of parentheses in the last statement. If you omit them, you won't get what you expect:
332
+
333
+ :function.sql_function > 1 & :column3 # (function() > 1)
334
+
335
+ This is because & has higher precedence than >, so it is parsed as:
336
+
337
+ :function.sql_function > (1 & :column3)
338
+
339
+ In this case, <tt>:column3.to_int</tt> returns an odd integer, so:
340
+
341
+ 1 & :column3 # => 1
342
+
343
+ You can use hashes and arrays of two element arrays to specify AND and OR with equality conditions:
344
+
345
+ {:column1=>1, :column2=>2} # (("column1" = 1) AND ("column2" = 2))
346
+ [[:column1, 1], [:column2, 2]] # (("column1" = 1) AND ("column2" = 2))
347
+
348
+ As you can see, these literalize with ANDs by default. You can use the +sql_or+ method to use OR instead:
349
+
350
+ {:column1=>1, :column2=>2}.sql_or # (("column1" = 1) OR ("column2" = 2))
351
+
352
+ You've already seen the +sql_negate+ method, which will use ANDs if multiple entries are used:
353
+
354
+ {:column1=>1, :column2=>2}.sql_negate # (("column1" != 1) AND ("column2" != 2))
355
+
356
+ To negate while using ORs, the ~ operator can be used:
357
+
358
+ ~{:column1=>1, :column2=>2} # (("column1" != 1) OR ("column2" != 2))
359
+
360
+ Note that <tt>Dataset#exclude</tt> uses ~, not +sql_negate+:
361
+
362
+ DB[:albums].exclude(:column1=>1, :column2=>2) # SELECT * FROM "albums" WHERE (("column" != 1) OR ("column2" != 2))
363
+
364
+ === Casts
365
+
366
+ Casting in Sequel is done with the +cast+ method, which is available on strings, symbols, and most of the Sequel-specific expression objects:
367
+
368
+ :name.cast(:text) # CAST("name" AS text)
369
+ '1'.cast(:integer) # CAST('1' AS integer)
370
+ :column.qualify(:table).cast(:date) # CAST("table"."column" AS date)
371
+
372
+ === Bitwise Mathematical Operators (& | ^ << >> ~)
373
+
374
+ Sequel allows the use of bitwise mathematical operators on Sequel::SQL::NumericExpression objects:
375
+
376
+ :number + 1 # => #<Sequel::SQL::NumericExpression ...>
377
+ (:number + 1) & 5 # (("number" + 1) & 5)
378
+
379
+ As you can see, when you use the + operator on a symbol, you get a NumericExpression. You can turn a symbol into a NumericExpression using +sql_number+:
380
+
381
+ :number.sql_number | 5 # ("number" | 5)
382
+
383
+ +sql_number+ also works on the many other Sequel-specific expression objects:
384
+
385
+ :function.sql_function.sql_number << 7 # (function() << 7)
386
+ :name.cast(:integer).sql_number >> 8 # (CAST("name" AS integer) >> 8)
387
+
388
+ Sequel allows you to do the cast and conversion at the same time via +cast_numeric+:
389
+
390
+ :name.cast_numeric ^ 9 # (CAST("name" AS integer) ^ 9)
391
+
392
+ Note that &, |, and ~ are already defined to do AND, OR, and NOT on most objects, so if you want to use the bitwise operators, you need to make sure that they are converted first:
393
+
394
+ ~:name # NOT "name"
395
+ ~:name.sql_number # ~"name"
396
+
397
+ === String Operators (||, LIKE, Regexp)
398
+
399
+ Sequel allows the use of the string concatenation operator on Sequel::SQL::StringExpression objects, which can be created using the +sql_string+ method:
400
+
401
+ :name.sql_string + ' - Name' # ("name" || ' - Name')
402
+
403
+ Just like for the bitwise operators, Sequel allows you do do the cast and conversion at the same time via +cast_string+:
404
+
405
+ :number.cast_string + ' - Number' # (CAST(number AS varchar(255)) || ' - Number')
406
+
407
+ Note that similar to the mathematical operators, you cannot switch the order the expression and have it work:
408
+
409
+ 'Name - ' + :name.sql_string # raises TypeError
410
+
411
+ Just like for the mathematical operators, you can use the +sql_expr+ extension to work around this:
412
+
413
+ Sequel.extension :sql_expr
414
+ 'Name - '.sql_expr + :name # ('Name - ' || "name")
415
+
416
+ Sequel also adds an <tt>Array#sql_string_join</tt> method, which concatentates all of the elements in the array:
417
+
418
+ ['Name', :name].sql_string_join # ('Name' || "name")
419
+
420
+ Just like ruby's <tt>String#join</tt>, you can provide an argument for a string used to join each element:
421
+
422
+ ['Name', :name].sql_string_join(' - ') # ('Name' || ' - ' || "name")
423
+
424
+ For the LIKE operator, Sequel defines the +like+ and +ilike+ methods on symbol and most Sequel-specific expression objects:
425
+
426
+ :name.like('A%') # ("name" LIKE 'A%')
427
+ :name.qualify.ilike('A%') # ("name" ILIKE 'A%')
428
+
429
+ Note the above syntax, while Sequel's default, is specific to PostgreSQL. However, most other adapters override the behavior. For example, on MySQL, Sequel uses LIKE BINARY for +like+, and LIKE for +ilike+. If the database supports both case sensitive and case insensitive LIKE, then +like+ will use a case sensitive LIKE, and +ilike+ will use a case insensitive LIKE. Some databases only support case insensitive behavior, in which case +like+ and +ilike+ will act identically.
430
+
431
+ Inverting the LIKE operator works like other inversions:
432
+
433
+ ~:name.like('A%') # ("name" NOT LIKE 'A%')
434
+
435
+ Sequel also supports SQL regular expressions on MySQL and PostgreSQL. You can use these by passing a ruby regular expression to the +like+ or +ilike+ method, or by making the regular expression a hash value:
436
+
437
+ :name.like(/^A/) # ("name" ~ '^A')
438
+ ~:name.ilike(/^A/) # ("name" !~* '^A')
439
+ {:name=>/^A/i} # ("name" ~* '^A')
440
+ ~{:name=>/^A/} # ("name" !~ '^A')
441
+
442
+ Note that using +ilike+ with a regular expression will always make the regexp case insensitive. If you use +like+ or the hash with regexp value, it will only be case insensitive if the Regexp itself is case insensitive.
443
+
444
+ === Order Specifications (ASC, DESC)
445
+
446
+ Sequel supports specifying ascending or descending order using the +asc+ and +desc+ method on symbols and most Sequel-specific expression objects:
447
+
448
+ :column.asc # "column" ASC
449
+ :column.qualify(:table).desc # "table"."column" DESC
450
+
451
+ === All Columns (.*)
452
+
453
+ To select all columns in a table, Sequel supports the * method on symbols without an argument:
454
+
455
+ :table.* # "table".*
456
+
457
+ === CASE statements
458
+
459
+ Sequel allows the easy production of SQL CASE statements using the +case+ method of hashes and arrays of two element arrays. The argument to +case+ is the default value, the keys of the hash (or first element in each array) is the WHEN condition, and the values of the hash (or second element in each array) is the THEN result. Here are some examples:
460
+
461
+ {:column=>1}.case(0) # (CASE WHEN "column" THEN 1 ELSE 0 END)
462
+ [[column, 1]].case(0) # (CASE WHEN "column" THEN 1 ELSE 0 END)
463
+ {{:column=>nil}=>1}.case(0) # (CASE WHEN (column IS NULL) THEN 1 ELSE 0 END)
464
+
465
+ If the hash or array has multiple arguments, multiple WHEN clauses are used:
466
+
467
+ {:c=>1, :d=>2}.case(0) # (CASE WHEN "c" THEN 1 WHEN "d" THEN 2 ELSE 0 END)
468
+ [[:c, 1], [:d, 2]].case(0) # (CASE WHEN "c" THEN 1 WHEN "d" THEN 2 ELSE 0 END)
469
+
470
+ If you provide a 2nd argument to CASE, it goes between CASE and WHEN:
471
+
472
+ {2=>1, 3=>5}.case(0, :column) # (CASE column WHEN 2 THEN 1 WHEN 3 THEN 5 ELSE 0 END)
473
+
474
+ === Subscripts/Array Access ([])
475
+
476
+ Sequel supports SQL subscripts using the +sql_subscript+ method on symbols and most Sequel-specific expression objects:
477
+
478
+ :column.sql_subscript(3) # column[3]
479
+ :column.qualify(:table).sql_subscript(3) # table.column[3]
480
+
481
+ Just like in SQL, you can use any expression as a subscript:
482
+
483
+ :column.sql_subscript(:function.sql_function) # column[function()]
484
+
485
+ == Building Queries in Sequel
486
+
487
+ In Sequel, the SQL queries are build with method chaining.
488
+
489
+ === Creating Datasets
490
+
491
+ You generally start by creating a dataset by calling <tt>Dataset#[]</tt> with a symbol specifying the table name:
492
+
493
+ DB[:albums] # SELECT * FROM albums
494
+
495
+ If you want to select from multiple FROM tables, use multiple arguments:
496
+
497
+ DB[:albums, :artists] # SELECT * FROM albums, artists
498
+
499
+ If you don't want to select from any FROM tables, use no arguments:
500
+
501
+ DB[] # SELECT *
502
+
503
+ === Chaining Methods
504
+
505
+ Once you have your dataset object, you build queries by chaining methods, usually with one method per clause in the query:
506
+
507
+ DB[:albums].select(:id, :name).where(:name.like('A%')).order(:name)
508
+ # SELECT id, name FROM albums WHERE (name LIKE 'A%') ORDER BY name
509
+
510
+ Note that the order of your method chain is not usually important unless you have multiple methods that affect the same clause:
511
+
512
+ DB[:albums].order(:name).where(:name.like('A%')).select(:id, :name)
513
+ # SELECT id, name FROM albums WHERE (name LIKE 'A%') ORDER BY name
514
+
515
+ === Using the Same Dataset for SELECT, INSERT, UPDATE, and DELETE
516
+
517
+ Also note that while the SELECT clause is displayed when you look at a dataset, a Sequel dataset can be used for INSERT, UPDATE, and DELETE as well. Here's an example:
518
+
519
+ ds = DB[:albums]
520
+ ds.all # SELECT * FROM albums
521
+ ds.insert(:name=>'RF') # INSERT INTO albums (name) VALUES ('RF')
522
+ ds.update(:name=>'RF') # UPDATE albums SET name = 'RF'
523
+ ds.delete # DELETE FROM albums
524
+
525
+ In general, the +insert+, +update+, and +delete+ methods use the appropriate clauses you defined on the dataset:
526
+
527
+ ds = DB[:albums].filter(:id=>1)
528
+ ds.all # SELECT * FROM albums WHERE (id = 1)
529
+ ds.insert(:name=>'RF') # INSERT INTO albums (name) VALUES ('RF')
530
+ ds.update(:name=>'RF') # UPDATE albums SET name = 'RF' WHERE (id = 1)
531
+ ds.delete # DELETE FROM albums WHERE (id = 1)
532
+
533
+ Note how +update+ and +delete+ used the +filter+ argument, but that +insert+ did not, because INSERT doesn't use a WHERE clause.
534
+
535
+ === Methods Used for Each SQL Clause
536
+
537
+ To see which methods exist that affect each SQL clause, see the {"Dataset Basics" guide}[link:files/doc/dataset_basics_rdoc.html].