sequel 5.83.0 → 5.84.0

Sign up to get free protection for your applications and to get access to all the features.
Files changed (126) hide show
  1. checksums.yaml +4 -4
  2. data/lib/sequel/adapters/shared/sqlite.rb +3 -1
  3. data/lib/sequel/database/connecting.rb +1 -1
  4. data/lib/sequel/database/misc.rb +8 -3
  5. data/lib/sequel/database/schema_methods.rb +2 -0
  6. data/lib/sequel/extensions/pg_json_ops.rb +328 -1
  7. data/lib/sequel/sql.rb +8 -5
  8. data/lib/sequel/version.rb +1 -1
  9. metadata +2 -236
  10. data/CHANGELOG +0 -1393
  11. data/README.rdoc +0 -936
  12. data/doc/advanced_associations.rdoc +0 -884
  13. data/doc/association_basics.rdoc +0 -1859
  14. data/doc/bin_sequel.rdoc +0 -146
  15. data/doc/cheat_sheet.rdoc +0 -255
  16. data/doc/code_order.rdoc +0 -104
  17. data/doc/core_extensions.rdoc +0 -405
  18. data/doc/dataset_basics.rdoc +0 -96
  19. data/doc/dataset_filtering.rdoc +0 -222
  20. data/doc/extensions.rdoc +0 -77
  21. data/doc/fork_safety.rdoc +0 -84
  22. data/doc/mass_assignment.rdoc +0 -98
  23. data/doc/migration.rdoc +0 -660
  24. data/doc/model_dataset_method_design.rdoc +0 -129
  25. data/doc/model_hooks.rdoc +0 -254
  26. data/doc/model_plugins.rdoc +0 -270
  27. data/doc/mssql_stored_procedures.rdoc +0 -43
  28. data/doc/object_model.rdoc +0 -563
  29. data/doc/opening_databases.rdoc +0 -439
  30. data/doc/postgresql.rdoc +0 -611
  31. data/doc/prepared_statements.rdoc +0 -144
  32. data/doc/querying.rdoc +0 -1070
  33. data/doc/reflection.rdoc +0 -120
  34. data/doc/release_notes/5.0.0.txt +0 -159
  35. data/doc/release_notes/5.1.0.txt +0 -31
  36. data/doc/release_notes/5.10.0.txt +0 -84
  37. data/doc/release_notes/5.11.0.txt +0 -83
  38. data/doc/release_notes/5.12.0.txt +0 -141
  39. data/doc/release_notes/5.13.0.txt +0 -27
  40. data/doc/release_notes/5.14.0.txt +0 -63
  41. data/doc/release_notes/5.15.0.txt +0 -39
  42. data/doc/release_notes/5.16.0.txt +0 -110
  43. data/doc/release_notes/5.17.0.txt +0 -31
  44. data/doc/release_notes/5.18.0.txt +0 -69
  45. data/doc/release_notes/5.19.0.txt +0 -28
  46. data/doc/release_notes/5.2.0.txt +0 -33
  47. data/doc/release_notes/5.20.0.txt +0 -89
  48. data/doc/release_notes/5.21.0.txt +0 -87
  49. data/doc/release_notes/5.22.0.txt +0 -48
  50. data/doc/release_notes/5.23.0.txt +0 -56
  51. data/doc/release_notes/5.24.0.txt +0 -56
  52. data/doc/release_notes/5.25.0.txt +0 -32
  53. data/doc/release_notes/5.26.0.txt +0 -35
  54. data/doc/release_notes/5.27.0.txt +0 -21
  55. data/doc/release_notes/5.28.0.txt +0 -16
  56. data/doc/release_notes/5.29.0.txt +0 -22
  57. data/doc/release_notes/5.3.0.txt +0 -121
  58. data/doc/release_notes/5.30.0.txt +0 -20
  59. data/doc/release_notes/5.31.0.txt +0 -148
  60. data/doc/release_notes/5.32.0.txt +0 -46
  61. data/doc/release_notes/5.33.0.txt +0 -24
  62. data/doc/release_notes/5.34.0.txt +0 -40
  63. data/doc/release_notes/5.35.0.txt +0 -56
  64. data/doc/release_notes/5.36.0.txt +0 -60
  65. data/doc/release_notes/5.37.0.txt +0 -30
  66. data/doc/release_notes/5.38.0.txt +0 -28
  67. data/doc/release_notes/5.39.0.txt +0 -19
  68. data/doc/release_notes/5.4.0.txt +0 -80
  69. data/doc/release_notes/5.40.0.txt +0 -40
  70. data/doc/release_notes/5.41.0.txt +0 -25
  71. data/doc/release_notes/5.42.0.txt +0 -136
  72. data/doc/release_notes/5.43.0.txt +0 -98
  73. data/doc/release_notes/5.44.0.txt +0 -32
  74. data/doc/release_notes/5.45.0.txt +0 -34
  75. data/doc/release_notes/5.46.0.txt +0 -87
  76. data/doc/release_notes/5.47.0.txt +0 -59
  77. data/doc/release_notes/5.48.0.txt +0 -14
  78. data/doc/release_notes/5.49.0.txt +0 -59
  79. data/doc/release_notes/5.5.0.txt +0 -61
  80. data/doc/release_notes/5.50.0.txt +0 -78
  81. data/doc/release_notes/5.51.0.txt +0 -47
  82. data/doc/release_notes/5.52.0.txt +0 -87
  83. data/doc/release_notes/5.53.0.txt +0 -23
  84. data/doc/release_notes/5.54.0.txt +0 -27
  85. data/doc/release_notes/5.55.0.txt +0 -21
  86. data/doc/release_notes/5.56.0.txt +0 -51
  87. data/doc/release_notes/5.57.0.txt +0 -23
  88. data/doc/release_notes/5.58.0.txt +0 -31
  89. data/doc/release_notes/5.59.0.txt +0 -73
  90. data/doc/release_notes/5.6.0.txt +0 -31
  91. data/doc/release_notes/5.60.0.txt +0 -22
  92. data/doc/release_notes/5.61.0.txt +0 -43
  93. data/doc/release_notes/5.62.0.txt +0 -132
  94. data/doc/release_notes/5.63.0.txt +0 -33
  95. data/doc/release_notes/5.64.0.txt +0 -50
  96. data/doc/release_notes/5.65.0.txt +0 -21
  97. data/doc/release_notes/5.66.0.txt +0 -24
  98. data/doc/release_notes/5.67.0.txt +0 -32
  99. data/doc/release_notes/5.68.0.txt +0 -61
  100. data/doc/release_notes/5.69.0.txt +0 -26
  101. data/doc/release_notes/5.7.0.txt +0 -108
  102. data/doc/release_notes/5.70.0.txt +0 -35
  103. data/doc/release_notes/5.71.0.txt +0 -21
  104. data/doc/release_notes/5.72.0.txt +0 -33
  105. data/doc/release_notes/5.73.0.txt +0 -66
  106. data/doc/release_notes/5.74.0.txt +0 -45
  107. data/doc/release_notes/5.75.0.txt +0 -35
  108. data/doc/release_notes/5.76.0.txt +0 -86
  109. data/doc/release_notes/5.77.0.txt +0 -63
  110. data/doc/release_notes/5.78.0.txt +0 -67
  111. data/doc/release_notes/5.79.0.txt +0 -28
  112. data/doc/release_notes/5.8.0.txt +0 -170
  113. data/doc/release_notes/5.80.0.txt +0 -40
  114. data/doc/release_notes/5.81.0.txt +0 -31
  115. data/doc/release_notes/5.82.0.txt +0 -61
  116. data/doc/release_notes/5.83.0.txt +0 -56
  117. data/doc/release_notes/5.9.0.txt +0 -99
  118. data/doc/schema_modification.rdoc +0 -679
  119. data/doc/security.rdoc +0 -443
  120. data/doc/sharding.rdoc +0 -286
  121. data/doc/sql.rdoc +0 -648
  122. data/doc/testing.rdoc +0 -204
  123. data/doc/thread_safety.rdoc +0 -15
  124. data/doc/transactions.rdoc +0 -250
  125. data/doc/validations.rdoc +0 -558
  126. data/doc/virtual_rows.rdoc +0 -265
data/README.rdoc DELETED
@@ -1,936 +0,0 @@
1
- == Sequel: The Database Toolkit for Ruby
2
-
3
- Sequel is a simple, flexible, and powerful SQL database access
4
- toolkit for Ruby.
5
-
6
- * Sequel provides thread safety, connection pooling and a concise
7
- DSL for constructing SQL queries and table schemas.
8
- * Sequel includes a comprehensive ORM layer for mapping
9
- records to Ruby objects and handling associated records.
10
- * Sequel supports advanced database features such as prepared
11
- statements, bound variables, savepoints, two-phase commit,
12
- transaction isolation, primary/replica configurations, and
13
- database sharding.
14
- * Sequel currently has adapters for ADO, Amalgalite,
15
- IBM_DB, JDBC, MySQL, Mysql2, ODBC, Oracle,
16
- PostgreSQL, SQLAnywhere, SQLite3, TinyTDS, and Trilogy.
17
-
18
- == Resources
19
-
20
- Website :: https://sequel.jeremyevans.net
21
- RDoc Documentation :: https://sequel.jeremyevans.net/rdoc
22
- Source Code :: https://github.com/jeremyevans/sequel
23
- Bug tracking (GitHub Issues) :: https://github.com/jeremyevans/sequel/issues
24
- Discussion Forum (GitHub Discussions) :: https://github.com/jeremyevans/sequel/discussions
25
- Archived Discussion Forum (sequel-talk Google Group) :: https://www.mail-archive.com/sequel-talk@googlegroups.com/
26
-
27
- If you have questions about how to use Sequel, please ask on
28
- GitHub Discussions.
29
- Only use the the bug tracker to report
30
- bugs in Sequel, not to ask for help on using Sequel.
31
-
32
- To check out the source code:
33
-
34
- git clone git://github.com/jeremyevans/sequel.git
35
-
36
- === Contact
37
-
38
- If you have any comments or suggestions please post to the Google group.
39
-
40
- == Installation
41
-
42
- gem install sequel
43
-
44
- == A Short Example
45
-
46
- require 'sequel'
47
-
48
- DB = Sequel.sqlite # memory database, requires sqlite3
49
-
50
- DB.create_table :items do
51
- primary_key :id
52
- String :name
53
- Float :price
54
- end
55
-
56
- items = DB[:items] # Create a dataset
57
-
58
- # Populate the table
59
- items.insert(name: 'abc', price: rand * 100)
60
- items.insert(name: 'def', price: rand * 100)
61
- items.insert(name: 'ghi', price: rand * 100)
62
-
63
- # Print out the number of records
64
- puts "Item count: #{items.count}"
65
-
66
- # Print out the average price
67
- puts "The average price is: #{items.avg(:price)}"
68
-
69
- == The Sequel Console
70
-
71
- Sequel includes an IRB console for quick access to databases (usually referred to as <tt>bin/sequel</tt>). You can use it like this:
72
-
73
- sequel sqlite://test.db # test.db in current directory
74
-
75
- You get an IRB session with the Sequel::Database object stored in DB.
76
-
77
- In addition to providing an IRB shell (the default behavior), bin/sequel also has support for migrating databases, dumping schema migrations, and copying databases. See the {bin/sequel guide}[rdoc-ref:doc/bin_sequel.rdoc] for more details.
78
-
79
- == An Introduction
80
-
81
- 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.
82
-
83
- 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.
84
-
85
- For example, the following one-liner returns the average GDP for countries in the middle east region:
86
-
87
- DB[:countries].where(region: 'Middle East').avg(:GDP)
88
-
89
- Which is equivalent to:
90
-
91
- SELECT avg(GDP) FROM countries WHERE region = 'Middle East'
92
-
93
- Since datasets retrieve records only when needed, they can be stored and later reused. Records are fetched as hashes, and are accessed using an +Enumerable+ interface:
94
-
95
- middle_east = DB[:countries].where(region: 'Middle East')
96
- middle_east.order(:name).each{|r| puts r[:name]}
97
-
98
- Sequel also offers convenience methods for extracting data from Datasets, such as an extended +map+ method:
99
-
100
- middle_east.map(:name) # => ['Egypt', 'Turkey', 'Israel', ...]
101
- middle_east.map([:id, :name]) # => [[1, 'Egypt'], [3, 'Turkey'], [2, 'Israel'], ...]
102
-
103
- Or getting results as a hash via +as_hash+, with one column as key and another as value:
104
-
105
- middle_east.as_hash(:name, :area) # => {'Israel' => 20000, 'Turkey' => 120000, ...}
106
-
107
- == Getting Started
108
-
109
- === Connecting to a database
110
-
111
- To connect to a database you simply provide <tt>Sequel.connect</tt> with a URL:
112
-
113
- require 'sequel'
114
- DB = Sequel.connect('sqlite://blog.db') # requires sqlite3
115
-
116
- The connection URL can also include such stuff as the user name, password, and port:
117
-
118
- DB = Sequel.connect('postgres://user:password@host:port/database_name') # requires pg
119
-
120
- You can also specify optional parameters, such as the connection pool size, or loggers for logging SQL queries:
121
-
122
- DB = Sequel.connect("postgres://user:password@host:port/database_name",
123
- max_connections: 10, logger: Logger.new('log/db.log'))
124
-
125
- It is also possible to use a hash instead of a connection URL, but make sure to include the :adapter option in this case:
126
-
127
- DB = Sequel.connect(adapter: :postgres, user: 'user', password: 'password', host: 'host', port: port,
128
- database: 'database_name', max_connections: 10, logger: Logger.new('log/db.log'))
129
-
130
- You can specify a block to connect, which will disconnect from the database after it completes:
131
-
132
- Sequel.connect('postgres://user:password@host:port/database_name'){|db| db[:posts].delete}
133
-
134
- === The DB convention
135
-
136
- Throughout Sequel's documentation, you will see the +DB+ constant used to refer to the Sequel::Database instance you create.
137
- This reflects the recommendation that for an app with a single Sequel::Database instance, the Sequel convention is to store
138
- the instance in the +DB+ constant. This is just a convention, it's not required, but it is recommended.
139
-
140
- Note that some frameworks that use Sequel may create the Sequel::Database instance for you, and you might not know
141
- how to access it. In most cases, you can access the Sequel::Database instance through <tt>Sequel::Model.db</tt>.
142
-
143
- === Arbitrary SQL queries
144
-
145
- You can execute arbitrary SQL code using <tt>Database#run</tt>:
146
-
147
- DB.run("create table t (a text, b text)")
148
- DB.run("insert into t values ('a', 'b')")
149
-
150
- You can also create datasets based on raw SQL:
151
-
152
- dataset = DB['select id from items']
153
- dataset.count # will return the number of records in the result set
154
- dataset.map(:id) # will return an array containing all values of the id column in the result set
155
-
156
- You can also fetch records with raw SQL through the dataset:
157
-
158
- DB['select * from items'].each do |row|
159
- p row
160
- end
161
-
162
- You can use placeholders in your SQL string as well:
163
-
164
- name = 'Jim'
165
- DB['select * from items where name = ?', name].each do |row|
166
- p row
167
- end
168
-
169
- === Getting Dataset Instances
170
-
171
- Datasets are the primary way records are retrieved and manipulated. They are generally created via the <tt>Database#from</tt> or <tt>Database#[]</tt> methods:
172
-
173
- posts = DB.from(:posts)
174
- posts = DB[:posts] # same
175
-
176
- Datasets will only fetch records when you tell them to. They can be manipulated to filter records, change ordering, join tables, etc. Datasets are always frozen, and they are safe to use by multiple threads concurrently.
177
-
178
- === Retrieving Records
179
-
180
- You can retrieve all records by using the +all+ method:
181
-
182
- posts.all
183
- # SELECT * FROM posts
184
-
185
- The +all+ method returns an array of hashes, where each hash corresponds to a record.
186
-
187
- You can also iterate through records one at a time using +each+:
188
-
189
- posts.each{|row| p row}
190
-
191
- Or perform more advanced stuff:
192
-
193
- names_and_dates = posts.map([:name, :date])
194
- old_posts, recent_posts = posts.partition{|r| r[:date] < Date.today - 7}
195
-
196
- You can also retrieve the first record in a dataset:
197
-
198
- posts.order(:id).first
199
- # SELECT * FROM posts ORDER BY id LIMIT 1
200
-
201
- Note that you can get the first record in a dataset even if it isn't ordered:
202
-
203
- posts.first
204
- # SELECT * FROM posts LIMIT 1
205
-
206
- If the dataset is ordered, you can also ask for the last record:
207
-
208
- posts.order(:stamp).last
209
- # SELECT * FROM posts ORDER BY stamp DESC LIMIT 1
210
-
211
- You can also provide a filter when asking for a single record:
212
-
213
- posts.first(id: 1)
214
- # SELECT * FROM posts WHERE id = 1 LIMIT 1
215
-
216
- Or retrieve a single value for a specific record:
217
-
218
- posts.where(id: 1).get(:name)
219
- # SELECT name FROM posts WHERE id = 1 LIMIT 1
220
-
221
- === Filtering Records
222
-
223
- The most common way to filter records is to provide a hash of values to match to +where+:
224
-
225
- my_posts = posts.where(category: 'ruby', author: 'david')
226
- # WHERE ((category = 'ruby') AND (author = 'david'))
227
-
228
- You can also specify ranges:
229
-
230
- my_posts = posts.where(stamp: (Date.today - 14)..(Date.today - 7))
231
- # WHERE ((stamp >= '2010-06-30') AND (stamp <= '2010-07-07'))
232
-
233
- Or arrays of values:
234
-
235
- my_posts = posts.where(category: ['ruby', 'postgres', 'linux'])
236
- # WHERE (category IN ('ruby', 'postgres', 'linux'))
237
-
238
- By passing a block to where, you can use expressions (this is fairly "magical"):
239
-
240
- my_posts = posts.where{stamp > Date.today << 1}
241
- # WHERE (stamp > '2010-06-14')
242
- my_posts = posts.where{stamp =~ Date.today}
243
- # WHERE (stamp = '2010-07-14')
244
-
245
- If you want to wrap the objects yourself, you can use expressions without the "magic":
246
-
247
- my_posts = posts.where(Sequel[:stamp] > Date.today << 1)
248
- # WHERE (stamp > '2010-06-14')
249
- my_posts = posts.where(Sequel[:stamp] =~ Date.today)
250
- # WHERE (stamp = '2010-07-14')
251
-
252
- Some databases such as PostgreSQL and MySQL also support filtering via Regexps:
253
-
254
- my_posts = posts.where(category: /ruby/i)
255
- # WHERE (category ~* 'ruby')
256
-
257
- You can also use an inverse filter via +exclude+:
258
-
259
- my_posts = posts.exclude(category: ['ruby', 'postgres', 'linux'])
260
- # WHERE (category NOT IN ('ruby', 'postgres', 'linux'))
261
-
262
- But note that this does a full inversion of the filter:
263
-
264
- my_posts = posts.exclude(category: ['ruby', 'postgres', 'linux'], id: 1)
265
- # WHERE ((category NOT IN ('ruby', 'postgres', 'linux')) OR (id != 1))
266
-
267
- If at any point you want to use a custom SQL fragment for part of a query,
268
- you can do so via +Sequel.lit+:
269
-
270
- posts.where(Sequel.lit('stamp IS NOT NULL'))
271
- # WHERE (stamp IS NOT NULL)
272
-
273
- You can safely interpolate parameters into the custom SQL fragment by
274
- providing them as additional arguments:
275
-
276
- author_name = 'JKR'
277
- posts.where(Sequel.lit('(stamp < ?) AND (author != ?)', Date.today - 3, author_name))
278
- # WHERE ((stamp < '2010-07-11') AND (author != 'JKR'))
279
-
280
- Datasets can also be used as subqueries:
281
-
282
- DB[:items].where(Sequel[:price] > DB[:items].select{avg(price) + 100})
283
- # WHERE (price > (SELECT avg(price) + 100 FROM items))
284
-
285
- After filtering, you can retrieve the matching records by using any of the retrieval methods:
286
-
287
- my_posts.each{|row| p row}
288
-
289
- See the {Dataset Filtering}[rdoc-ref:doc/dataset_filtering.rdoc] file for more details.
290
-
291
- === Security
292
-
293
- Designing apps with security in mind is a best practice.
294
- Please read the {Security Guide}[rdoc-ref:doc/security.rdoc] for details on security
295
- issues that you should be aware of when using Sequel.
296
-
297
- === Summarizing Records
298
-
299
- Counting records is easy using +count+:
300
-
301
- posts.where(Sequel.like(:category, '%ruby%')).count
302
- # SELECT COUNT(*) FROM posts WHERE (category LIKE '%ruby%' ESCAPE '\')
303
-
304
- And you can also query maximum/minimum values via +max+ and +min+:
305
-
306
- max = DB[:history].max(:value)
307
- # SELECT max(value) FROM history
308
-
309
- min = DB[:history].min(:value)
310
- # SELECT min(value) FROM history
311
-
312
- Or calculate a sum or average via +sum+ and +avg+:
313
-
314
- sum = DB[:items].sum(:price)
315
- # SELECT sum(price) FROM items
316
- avg = DB[:items].avg(:price)
317
- # SELECT avg(price) FROM items
318
-
319
- === Ordering Records
320
-
321
- Ordering datasets is simple using +order+:
322
-
323
- posts.order(:stamp)
324
- # ORDER BY stamp
325
- posts.order(:stamp, :name)
326
- # ORDER BY stamp, name
327
-
328
- +order+ always overrides the existing order:
329
-
330
- posts.order(:stamp).order(:name)
331
- # ORDER BY name
332
-
333
- If you would like to add to the existing order, use +order_append+ or +order_prepend+:
334
-
335
- posts.order(:stamp).order_append(:name)
336
- # ORDER BY stamp, name
337
- posts.order(:stamp).order_prepend(:name)
338
- # ORDER BY name, stamp
339
-
340
- You can also specify descending order:
341
-
342
- posts.reverse_order(:stamp)
343
- # ORDER BY stamp DESC
344
- posts.order(Sequel.desc(:stamp))
345
- # ORDER BY stamp DESC
346
-
347
- === Core Extensions
348
-
349
- Note the use of <tt>Sequel.desc(:stamp)</tt> in the above example. Much of Sequel's DSL uses this style, calling methods on the Sequel module that return SQL expression objects. Sequel also ships with a {core_extensions extension}[rdoc-ref:doc/core_extensions.rdoc] that integrates Sequel's DSL better into the Ruby language, allowing you to write:
350
-
351
- :stamp.desc
352
-
353
- instead of:
354
-
355
- Sequel.desc(:stamp)
356
-
357
- === Selecting Columns
358
-
359
- Selecting specific columns to be returned is also simple using +select+:
360
-
361
- posts.select(:stamp)
362
- # SELECT stamp FROM posts
363
- posts.select(:stamp, :name)
364
- # SELECT stamp, name FROM posts
365
-
366
- Like +order+, +select+ overrides an existing selection:
367
-
368
- posts.select(:stamp).select(:name)
369
- # SELECT name FROM posts
370
-
371
- As you might expect, there are +order_append+ and +order_prepend+ equivalents for +select+ called +select_append+ and +select_prepend+:
372
-
373
- posts.select(:stamp).select_append(:name)
374
- # SELECT stamp, name FROM posts
375
- posts.select(:stamp).select_prepend(:name)
376
- # SELECT name, stamp FROM posts
377
-
378
- === Deleting Records
379
-
380
- Deleting records from the table is done with +delete+:
381
-
382
- posts.where(Sequel[:stamp] < Date.today - 3).delete
383
- # DELETE FROM posts WHERE (stamp < '2010-07-11')
384
-
385
- Be very careful when deleting, as +delete+ affects all rows in the dataset.
386
- Call +where+ first and +delete+ second:
387
-
388
- # DO THIS:
389
- posts.where(Sequel[:stamp] < Date.today - 7).delete
390
- # NOT THIS:
391
- posts.delete.where(Sequel[:stamp] < Date.today - 7)
392
-
393
- === Inserting Records
394
-
395
- Inserting records into the table is done with +insert+:
396
-
397
- posts.insert(category: 'ruby', author: 'david')
398
- # INSERT INTO posts (category, author) VALUES ('ruby', 'david')
399
-
400
- === Updating Records
401
-
402
- Updating records in the table is done with +update+:
403
-
404
- posts.where(Sequel[:stamp] < Date.today - 7).update(state: 'archived')
405
- # UPDATE posts SET state = 'archived' WHERE (stamp < '2010-07-07')
406
-
407
- You can provide arbitrary expressions when choosing what values to set:
408
-
409
- posts.where(Sequel[:stamp] < Date.today - 7).update(backup_number: Sequel[:backup_number] + 1)
410
- # UPDATE posts SET backup_number = (backup_number + 1) WHERE (stamp < '2010-07-07'))))
411
-
412
- As with +delete+, +update+ affects all rows in the dataset, so +where+ first,
413
- +update+ second:
414
-
415
- # DO THIS:
416
- posts.where(Sequel[:stamp] < Date.today - 7).update(state: 'archived')
417
- # NOT THIS:
418
- posts.update(state: 'archived').where(Sequel[:stamp] < Date.today - 7)
419
-
420
- === Merging records
421
-
422
- Merging records using the SQL MERGE statement is done using <tt>merge*</tt> methods.
423
- You use +merge_using+ to specify the merge source and join conditions.
424
- You can use +merge_insert+, +merge_delete+, and/or +merge_update+ to set the
425
- INSERT, DELETE, and UPDATE clauses for the merge. +merge_insert+ takes the same
426
- arguments as +insert+, and +merge_update+ takes the same arguments as +update+.
427
- +merge_insert+, +merge_delete+, and +merge_update+ can all be called with blocks,
428
- to set the conditions for the related INSERT, DELETE, or UPDATE.
429
-
430
- Finally, after calling all of the other <tt>merge_*</tt> methods, you call +merge+
431
- to run the MERGE statement on the database.
432
-
433
- ds = DB[:m1]
434
- merge_using(:m2, i1: :i2).
435
- merge_insert(i1: :i2, a: Sequel[:b]+11).
436
- merge_delete{a > 30}.
437
- merge_update(i1: Sequel[:i1]+:i2+10, a: Sequel[:a]+:b+20)
438
-
439
- ds.merge
440
- # MERGE INTO m1 USING m2 ON (i1 = i2)
441
- # WHEN NOT MATCHED THEN INSERT (i1, a) VALUES (i2, (b + 11))
442
- # WHEN MATCHED AND (a > 30) THEN DELETE
443
- # WHEN MATCHED THEN UPDATE SET i1 = (i1 + i2 + 10), a = (a + b + 20)
444
-
445
- === Transactions
446
-
447
- You can wrap a block of code in a database transaction using the <tt>Database#transaction</tt> method:
448
-
449
- DB.transaction do
450
- # BEGIN
451
- posts.insert(category: 'ruby', author: 'david')
452
- # INSERT
453
- posts.where(Sequel[:stamp] < Date.today - 7).update(state: 'archived')
454
- # UPDATE
455
- end
456
- # COMMIT
457
-
458
- If the block does not raise an exception, the transaction will be committed.
459
- If the block does raise an exception, the transaction will be rolled back,
460
- and the exception will be reraised. If you want to rollback the transaction
461
- and not raise an exception outside the block, you can raise the
462
- <tt>Sequel::Rollback</tt> exception inside the block:
463
-
464
- DB.transaction do
465
- # BEGIN
466
- posts.insert(category: 'ruby', author: 'david')
467
- # INSERT
468
- if posts.where('stamp < ?', Date.today - 7).update(state: 'archived') == 0
469
- # UPDATE
470
- raise Sequel::Rollback
471
- end
472
- end
473
- # ROLLBACK
474
-
475
- === Joining Tables
476
-
477
- Sequel makes it easy to join tables:
478
-
479
- order_items = DB[:items].join(:order_items, item_id: :id).where(order_id: 1234)
480
- # SELECT * FROM items
481
- # INNER JOIN order_items ON (order_items.item_id = items.id)
482
- # WHERE (order_id = 1234)
483
-
484
- The important thing to note here is that item_id is automatically qualified with
485
- the table being joined, and id is automatically qualified with the last table
486
- joined.
487
-
488
- You can then do anything you like with the dataset:
489
-
490
- order_total = order_items.sum(:price)
491
- # SELECT sum(price) FROM items
492
- # INNER JOIN order_items ON (order_items.item_id = items.id)
493
- # WHERE (order_id = 1234)
494
-
495
- Note that the default selection in Sequel is <tt>*</tt>, which includes all columns
496
- in all joined tables. Because Sequel returns results as a hash keyed by column name
497
- symbols, if any tables have columns with the same name, this will clobber the columns
498
- in the returned hash. So when joining you are usually going to want to change the
499
- selection using +select+, +select_all+, and/or +select_append+.
500
-
501
- == Column references in Sequel
502
-
503
- 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:
504
-
505
- items.where(x: 1)
506
- # SELECT * FROM items WHERE (x = 1)
507
- items.where(1 => :x)
508
- # SELECT * FROM items WHERE (1 = x)"
509
-
510
- Ruby strings are generally treated as SQL strings:
511
-
512
- items.where(x: 'x')
513
- # SELECT * FROM items WHERE (x = 'x')
514
-
515
- === Qualifying identifiers (column/table names)
516
-
517
- An identifier in SQL is a name that represents a column, table, or schema.
518
- The recommended way to qualify columns is to use <tt>Sequel[][]</tt> or +Sequel.qualify+
519
-
520
- Sequel[:table][:column]
521
- Sequel.qualify(:table, :column)
522
- # table.column
523
-
524
- You can also qualify tables with schemas:
525
-
526
- Sequel[:schema][:table]
527
- # schema.table
528
-
529
- or use multi-level qualification:
530
-
531
- Sequel[:schema][:table][:column]
532
- # schema.table.column
533
-
534
- === Expression aliases
535
-
536
- You can alias identifiers using <tt>Sequel[].as</tt> or +Sequel.as+:
537
-
538
- Sequel[:column].as(:alias)
539
- Sequel.as(:column, :alias)
540
- # column AS alias
541
-
542
- You can use the <tt>Sequel.as</tt> method to alias arbitrary expressions, not just identifiers:
543
-
544
- Sequel.as(DB[:posts].select{max(id)}, :p)
545
- # (SELECT max(id) FROM posts) AS p
546
-
547
- And most Sequel expression objects support an +as+ method for aliasing:
548
-
549
- (Sequel[:column] + 2).as(:c_plus_2)
550
- # (column + 2) AS c_plus_2
551
-
552
- == Sequel Models
553
-
554
- A model class wraps a dataset, and an instance of that class wraps a single record in the dataset.
555
-
556
- Model classes are defined as regular Ruby classes inheriting from <tt>Sequel::Model</tt>:
557
-
558
- DB = Sequel.connect('sqlite://blog.db')
559
- class Post < Sequel::Model
560
- end
561
-
562
- When a model class is created, it parses the schema in the table from the database, and
563
- automatically sets up accessor methods for all of the columns in the table (Sequel::Model
564
- implements the active record pattern).
565
-
566
- Sequel model classes assume that the table name is an underscored plural of the class name:
567
-
568
- Post.table_name # => :posts
569
-
570
- You can explicitly set the table name or even the dataset used:
571
-
572
- class Post < Sequel::Model(:my_posts); end
573
- # or:
574
- class Post < Sequel::Model(DB[:my_posts]); end
575
-
576
- If you pass a symbol to the <tt>Sequel::Model</tt> method, it assumes you are referring to the table with the same name. You can also call it with a dataset, which will set the defaults for all retrievals for that model:
577
-
578
- class Post < Sequel::Model(DB[:my_posts].where(category: 'ruby')); end
579
- class Post < Sequel::Model(DB[:my_posts].select(:id, :name).order(:date)); end
580
-
581
- === Model instances
582
-
583
- Model instances are identified by a primary key. Sequel queries the database to determine the primary key for each model. The <tt>Model.[]</tt> method can be used to fetch records by their primary key:
584
-
585
- post = Post[123]
586
-
587
- The +pk+ method is used to retrieve the record's primary key value:
588
-
589
- post.pk # => 123
590
-
591
- If you want to override which column(s) to use as the primary key, you can use +set_primary_key+:
592
-
593
- class Post < Sequel::Model
594
- set_primary_key [:category, :title]
595
- end
596
-
597
- post = Post['ruby', 'hello world']
598
- post.pk # => ['ruby', 'hello world']
599
-
600
- You can also define a model class that does not have a primary key via +no_primary_key+, but then you lose the ability to easily update and delete records:
601
-
602
- Post.no_primary_key
603
-
604
- A single model instance can also be fetched by specifying a condition:
605
-
606
- post = Post.first(title: 'hello world')
607
- post = Post.first{num_comments < 10}
608
-
609
- The dataset for a model class returns rows of model instances instead of plain hashes:
610
-
611
- DB[:posts].first.class # => Hash
612
- Post.first.class # => Post
613
-
614
- === Acts like a dataset
615
-
616
- A model class forwards 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.:
617
-
618
- Post.where(category: 'ruby').each{|post| p post}
619
-
620
- You can also manipulate the records in the dataset:
621
-
622
- Post.where{num_comments < 7}.delete
623
- Post.where(Sequel.like(:title, /ruby/)).update(category: 'ruby')
624
-
625
- === Accessing record values
626
-
627
- A model instance stores its values as a hash with column symbol keys, which you can access directly via the +values+ method:
628
-
629
- post.values # => {:id => 123, :category => 'ruby', :title => 'hello world'}
630
-
631
- You can read the record values as object attributes, assuming the attribute names are valid columns in the model's dataset:
632
-
633
- post.id # => 123
634
- post.title # => 'hello world'
635
-
636
- If the record's attributes names are not valid columns in the model's dataset (maybe because you used +select_append+ to add a computed value column), you can use <tt>Model#[]</tt> to access the values:
637
-
638
- post[:id] # => 123
639
- post[:title] # => 'hello world'
640
-
641
- You can also modify record values using attribute setters or the <tt>[]=</tt> method.
642
-
643
- post.title = 'hey there'
644
- post[:title] = 'hey there'
645
-
646
- That will just change the value for the object, it will not update the row in the database. To update the database row, call the +save+ method:
647
-
648
- post.save
649
-
650
- === Mass assignment
651
-
652
- You can also set the values for multiple columns in a single method call, using one of the mass-assignment methods. See the {mass assignment guide}[rdoc-ref:doc/mass_assignment.rdoc] for details. For example +set+ updates the model's column values without saving:
653
-
654
- post.set(title: 'hey there', updated_by: 'foo')
655
-
656
- and +update+ updates the model's column values and then saves the changes to the database:
657
-
658
- post.update(title: 'hey there', updated_by: 'foo')
659
-
660
- === Creating new records
661
-
662
- New model instances can be created by calling <tt>Model.new</tt>, which returns a new model instance without updating the database:
663
-
664
- post = Post.new(title: 'hello world')
665
-
666
- You can save the record to the database later by calling +save+ on the model instance:
667
-
668
- post.save
669
-
670
- If you want to create a new record and save it to the database at the same time, you can use <tt>Model.create</tt>:
671
-
672
- post = Post.create(title: 'hello world')
673
-
674
- You can also supply a block to <tt>Model.new</tt> and <tt>Model.create</tt>:
675
-
676
- post = Post.new do |p|
677
- p.title = 'hello world'
678
- end
679
-
680
- post = Post.create{|p| p.title = 'hello world'}
681
-
682
- === Hooks
683
-
684
- 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:
685
-
686
- class Post < Sequel::Model
687
- def after_create
688
- super
689
- author.increase_post_count
690
- end
691
-
692
- def after_destroy
693
- super
694
- author.decrease_post_count
695
- end
696
- end
697
-
698
- Note the use of +super+ if you define your own hook methods. Almost all <tt>Sequel::Model</tt> 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.
699
-
700
- 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 modifying the database through model instances, and even then they are often subject to race conditions. It's best to use database triggers and database constraints to enforce data integrity.
701
-
702
- === Deleting records
703
-
704
- 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:
705
-
706
- post.delete # => bypasses hooks
707
- post.destroy # => runs hooks
708
-
709
- Records can also be deleted en-masse by calling <tt>delete</tt> and <tt>destroy</tt> on the model's dataset. As stated above, you can specify filters for the deleted records:
710
-
711
- Post.where(category: 32).delete # => bypasses hooks
712
- Post.where(category: 32).destroy # => runs hooks
713
-
714
- Please note that if <tt>destroy</tt> is called, each record is deleted
715
- separately, but <tt>delete</tt> deletes all matching records with a single
716
- SQL query.
717
-
718
- === Associations
719
-
720
- 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. You specify model associations via class methods:
721
-
722
- class Post < Sequel::Model
723
- many_to_one :author
724
- one_to_many :comments
725
- one_to_one :first_comment, class: :Comment, order: :id
726
- many_to_many :tags
727
- one_through_one :first_tag, class: :Tag, order: :name, right_key: :tag_id
728
- end
729
-
730
- +many_to_one+ and +one_to_one+ create a getter and setter for each model object:
731
-
732
- post = Post.create(name: 'hi!')
733
- post.author = Author.first(name: 'Sharon')
734
- post.author
735
-
736
- +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:
737
-
738
- post = Post.create(name: 'hi!')
739
- post.comments
740
-
741
- comment = Comment.create(text: 'hi')
742
- post.add_comment(comment)
743
- post.remove_comment(comment)
744
- post.remove_all_comments
745
-
746
- tag = Tag.create(tag: 'interesting')
747
- post.add_tag(tag)
748
- post.remove_tag(tag)
749
- post.remove_all_tags
750
-
751
- 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.
752
-
753
- All associations add a dataset method that can be used to further filter or reorder the returned objects, or modify all of them:
754
-
755
- # Delete all of this post's comments from the database
756
- post.comments_dataset.destroy
757
-
758
- # Return all tags related to this post with no subscribers, ordered by the tag's name
759
- post.tags_dataset.where(subscribers: 0).order(:name).all
760
-
761
- === Eager Loading
762
-
763
- Associations can be eagerly loaded via +eager+ and the <tt>:eager</tt> 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.
764
-
765
- class Person < Sequel::Model
766
- one_to_many :posts, eager: [:tags]
767
- end
768
-
769
- class Post < Sequel::Model
770
- many_to_one :person
771
- one_to_many :replies
772
- many_to_many :tags
773
- end
774
-
775
- class Tag < Sequel::Model
776
- many_to_many :posts
777
- many_to_many :replies
778
- end
779
-
780
- class Reply < Sequel::Model
781
- many_to_one :person
782
- many_to_one :post
783
- many_to_many :tags
784
- end
785
-
786
- # Eager loading via .eager
787
- Post.eager(:person).all
788
-
789
- # eager is a dataset method, so it works with filters/orders/limits/etc.
790
- Post.where{topic > 'M'}.order(:date).limit(5).eager(:person).all
791
-
792
- person = Person.first
793
- # Eager loading via :eager (will eagerly load the tags for this person's posts)
794
- person.posts
795
-
796
- # These are equivalent
797
- Post.eager(:person, :tags).all
798
- Post.eager(:person).eager(:tags).all
799
-
800
- # Cascading via .eager
801
- Tag.eager(posts: :replies).all
802
-
803
- # Will also grab all associated posts' tags (because of :eager)
804
- Reply.eager(person: :posts).all
805
-
806
- # No depth limit (other than memory/stack), and will also grab posts' tags
807
- # Loads all people, their posts, their posts' tags, replies to those posts,
808
- # the person for each reply, the tag for each reply, and all posts and
809
- # replies that have that tag. Uses a total of 8 queries.
810
- Person.eager(posts: {replies: [:person, {tags: [:posts, :replies]}]}).all
811
-
812
- 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 API is similar. Note that using +eager_graph+ to eagerly load multiple <tt>*_to_many</tt> 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.
813
-
814
- You can dynamically customize the eagerly loaded dataset by using a proc. This proc is passed the dataset used for eager loading, and should return a modified copy of that dataset:
815
-
816
- # Eagerly load only replies containing 'foo'
817
- Post.eager(replies: proc{|ds| ds.where(Sequel.like(text, '%foo%'))}).all
818
-
819
- This also works when using +eager_graph+, in which case the proc is called with dataset to graph into the current dataset:
820
-
821
- Post.eager_graph(replies: proc{|ds| ds.where(Sequel.like(text, '%foo%'))}).all
822
-
823
- You can dynamically customize eager loads for both +eager+ and +eager_graph+ while also cascading, by making the value a single entry hash with the proc as a key, and the cascaded associations as the value:
824
-
825
- # Eagerly load only replies containing 'foo', and the person and tags for those replies
826
- Post.eager(replies: {proc{|ds| ds.where(Sequel.like(text, '%foo%'))} => [:person, :tags]}).all
827
-
828
- === Joining with Associations
829
-
830
- You can use the +association_join+ method to add a join to the model's dataset based on the association:
831
-
832
- Post.association_join(:author)
833
- # SELECT * FROM posts
834
- # INNER JOIN authors AS author ON (author.id = posts.author_id)
835
-
836
- This comes with variants for different join types:
837
-
838
- Post.association_left_join(:replies)
839
- # SELECT * FROM posts
840
- # LEFT JOIN replies ON (replies.post_id = posts.id)
841
-
842
- Similar to the eager loading methods, you can use multiple associations and nested associations:
843
-
844
- Post.association_join(:author, replies: :person).all
845
- # SELECT * FROM posts
846
- # INNER JOIN authors AS author ON (author.id = posts.author_id)
847
- # INNER JOIN replies ON (replies.post_id = posts.id)
848
- # INNER JOIN people AS person ON (person.id = replies.person_id)
849
-
850
- === Extending the underlying dataset
851
-
852
- The recommended way to implement table-wide logic by defining methods on the dataset using +dataset_module+:
853
-
854
- class Post < Sequel::Model
855
- dataset_module do
856
- def with_few_comments
857
- where{num_comments < 30}
858
- end
859
-
860
- def clean_boring
861
- with_few_comments.delete
862
- end
863
- end
864
- end
865
-
866
- This allows you to have access to your model API from filtered datasets as well:
867
-
868
- Post.where(category: 'ruby').clean_boring
869
- # DELETE FROM posts WHERE ((category = 'ruby') AND (num_comments < 30))
870
-
871
- Inside +dataset_module+ blocks, there are numerous methods that support easy creation of dataset methods.
872
- Most of these methods are named after the dataset methods themselves, such as +select+, +order+, and
873
- +group+:
874
-
875
- class Post < Sequel::Model
876
- dataset_module do
877
- where(:with_few_comments, Sequel[:num_comments] < 30)
878
- select :with_title_and_date, :id, :title, :post_date
879
- order :by_post_date, :post_date
880
- limit :top10, 10
881
- end
882
- end
883
-
884
- Post.with_few_comments.with_title_and_date.by_post_date.top10
885
- # SELECT id, title, post_date
886
- # FROM posts
887
- # ORDER BY post_date
888
- # LIMIT 10
889
-
890
- One advantage of using these methods inside dataset_module blocks, instead of
891
- defining methods manually, is that the created methods will generally cache
892
- the resulting values and result in better performance.
893
-
894
- === Model Validations
895
-
896
- You can define a +validate+ method for your model, which +save+
897
- will check before attempting to save the model in the database.
898
- If an attribute of the model isn't valid, you should add an error
899
- message for that attribute to the model object's +errors+. If an
900
- object has any errors added by the validate method, +save+ will
901
- raise an error by default:
902
-
903
- class Post < Sequel::Model
904
- def validate
905
- super
906
- errors.add(:name, "can't be empty") if name.empty?
907
- errors.add(:written_on, "should be in the past") if written_on >= Time.now
908
- end
909
- end
910
-
911
- == Testing Sequel
912
-
913
- Please see the {testing guide}[rdoc-ref:doc/testing.rdoc] for recommendations on testing
914
- applications that use Sequel, as well as the how to run the tests for Sequel itself.
915
-
916
- == Sequel Release Policy
917
-
918
- New major versions of Sequel do not have a defined release policy, but historically have
919
- occurred once every few years.
920
-
921
- New minor versions of Sequel are released around once a month near the start of the month.
922
-
923
- New tiny versions of Sequel are only released to address security issues or regressions
924
- in the most current release.
925
-
926
- == Ruby Support Policy
927
-
928
- Sequel fully supports the currently supported versions of Ruby (MRI) and JRuby. It may
929
- support unsupported versions of Ruby or JRuby, but such support may be dropped in any
930
- minor version if keeping it becomes a support issue. The minimum Ruby version
931
- required to run the current version of Sequel is 1.9.2, and the minimum JRuby version is
932
- 9.2.0.0 (due to the bigdecimal dependency).
933
-
934
- == Maintainer
935
-
936
- Jeremy Evans <code@jeremyevans.net>