colincasey-sequel 2.10.0 → 2.10.1
Sign up to get free protection for your applications and to get access to all the features.
- data/CHANGELOG +7 -1
- data/doc/advanced_associations.rdoc +614 -0
- data/doc/cheat_sheet.rdoc +223 -0
- data/doc/dataset_filtering.rdoc +158 -0
- data/doc/prepared_statements.rdoc +104 -0
- data/doc/release_notes/1.0.txt +38 -0
- data/doc/release_notes/1.1.txt +143 -0
- data/doc/release_notes/1.3.txt +101 -0
- data/doc/release_notes/1.4.0.txt +53 -0
- data/doc/release_notes/1.5.0.txt +155 -0
- data/doc/release_notes/2.0.0.txt +298 -0
- data/doc/release_notes/2.1.0.txt +271 -0
- data/doc/release_notes/2.10.0.txt +328 -0
- data/doc/release_notes/2.2.0.txt +253 -0
- data/doc/release_notes/2.3.0.txt +88 -0
- data/doc/release_notes/2.4.0.txt +106 -0
- data/doc/release_notes/2.5.0.txt +137 -0
- data/doc/release_notes/2.6.0.txt +157 -0
- data/doc/release_notes/2.7.0.txt +166 -0
- data/doc/release_notes/2.8.0.txt +171 -0
- data/doc/release_notes/2.9.0.txt +97 -0
- data/doc/schema.rdoc +29 -0
- data/doc/sharding.rdoc +113 -0
- data/lib/sequel.rb +1 -0
- data/lib/sequel_core/adapters/ado.rb +89 -0
- data/lib/sequel_core/adapters/db2.rb +143 -0
- data/lib/sequel_core/adapters/dbi.rb +112 -0
- data/lib/sequel_core/adapters/do/mysql.rb +38 -0
- data/lib/sequel_core/adapters/do/postgres.rb +92 -0
- data/lib/sequel_core/adapters/do/sqlite.rb +31 -0
- data/lib/sequel_core/adapters/do.rb +205 -0
- data/lib/sequel_core/adapters/firebird.rb +298 -0
- data/lib/sequel_core/adapters/informix.rb +85 -0
- data/lib/sequel_core/adapters/jdbc/h2.rb +69 -0
- data/lib/sequel_core/adapters/jdbc/mysql.rb +66 -0
- data/lib/sequel_core/adapters/jdbc/oracle.rb +23 -0
- data/lib/sequel_core/adapters/jdbc/postgresql.rb +113 -0
- data/lib/sequel_core/adapters/jdbc/sqlite.rb +43 -0
- data/lib/sequel_core/adapters/jdbc.rb +491 -0
- data/lib/sequel_core/adapters/mysql.rb +369 -0
- data/lib/sequel_core/adapters/odbc.rb +174 -0
- data/lib/sequel_core/adapters/openbase.rb +68 -0
- data/lib/sequel_core/adapters/oracle.rb +107 -0
- data/lib/sequel_core/adapters/postgres.rb +456 -0
- data/lib/sequel_core/adapters/shared/ms_access.rb +110 -0
- data/lib/sequel_core/adapters/shared/mssql.rb +102 -0
- data/lib/sequel_core/adapters/shared/mysql.rb +325 -0
- data/lib/sequel_core/adapters/shared/oracle.rb +61 -0
- data/lib/sequel_core/adapters/shared/postgres.rb +715 -0
- data/lib/sequel_core/adapters/shared/progress.rb +31 -0
- data/lib/sequel_core/adapters/shared/sqlite.rb +265 -0
- data/lib/sequel_core/adapters/sqlite.rb +248 -0
- data/lib/sequel_core/connection_pool.rb +258 -0
- data/lib/sequel_core/core_ext.rb +217 -0
- data/lib/sequel_core/core_sql.rb +202 -0
- data/lib/sequel_core/database/schema.rb +164 -0
- data/lib/sequel_core/database.rb +691 -0
- data/lib/sequel_core/dataset/callback.rb +13 -0
- data/lib/sequel_core/dataset/convenience.rb +237 -0
- data/lib/sequel_core/dataset/pagination.rb +96 -0
- data/lib/sequel_core/dataset/prepared_statements.rb +220 -0
- data/lib/sequel_core/dataset/query.rb +41 -0
- data/lib/sequel_core/dataset/schema.rb +15 -0
- data/lib/sequel_core/dataset/sql.rb +1010 -0
- data/lib/sequel_core/dataset/stored_procedures.rb +75 -0
- data/lib/sequel_core/dataset/unsupported.rb +43 -0
- data/lib/sequel_core/dataset.rb +511 -0
- data/lib/sequel_core/deprecated.rb +26 -0
- data/lib/sequel_core/exceptions.rb +44 -0
- data/lib/sequel_core/migration.rb +212 -0
- data/lib/sequel_core/object_graph.rb +230 -0
- data/lib/sequel_core/pretty_table.rb +71 -0
- data/lib/sequel_core/schema/generator.rb +320 -0
- data/lib/sequel_core/schema/sql.rb +325 -0
- data/lib/sequel_core/schema.rb +2 -0
- data/lib/sequel_core/sql.rb +887 -0
- data/lib/sequel_core/version.rb +11 -0
- data/lib/sequel_core.rb +172 -0
- data/lib/sequel_model/association_reflection.rb +267 -0
- data/lib/sequel_model/associations.rb +499 -0
- data/lib/sequel_model/base.rb +523 -0
- data/lib/sequel_model/caching.rb +82 -0
- data/lib/sequel_model/dataset_methods.rb +26 -0
- data/lib/sequel_model/eager_loading.rb +370 -0
- data/lib/sequel_model/exceptions.rb +7 -0
- data/lib/sequel_model/hooks.rb +101 -0
- data/lib/sequel_model/inflector.rb +281 -0
- data/lib/sequel_model/plugins.rb +62 -0
- data/lib/sequel_model/record.rb +568 -0
- data/lib/sequel_model/schema.rb +49 -0
- data/lib/sequel_model/validations.rb +429 -0
- data/lib/sequel_model.rb +91 -0
- data/spec/adapters/ado_spec.rb +46 -0
- data/spec/adapters/firebird_spec.rb +376 -0
- data/spec/adapters/informix_spec.rb +96 -0
- data/spec/adapters/mysql_spec.rb +881 -0
- data/spec/adapters/oracle_spec.rb +244 -0
- data/spec/adapters/postgres_spec.rb +687 -0
- data/spec/adapters/spec_helper.rb +10 -0
- data/spec/adapters/sqlite_spec.rb +555 -0
- data/spec/integration/dataset_test.rb +134 -0
- data/spec/integration/eager_loader_test.rb +696 -0
- data/spec/integration/prepared_statement_test.rb +130 -0
- data/spec/integration/schema_test.rb +180 -0
- data/spec/integration/spec_helper.rb +58 -0
- data/spec/integration/type_test.rb +96 -0
- data/spec/rcov.opts +6 -0
- data/spec/sequel_core/connection_pool_spec.rb +526 -0
- data/spec/sequel_core/core_ext_spec.rb +156 -0
- data/spec/sequel_core/core_sql_spec.rb +522 -0
- data/spec/sequel_core/database_spec.rb +1188 -0
- data/spec/sequel_core/dataset_spec.rb +3481 -0
- data/spec/sequel_core/expression_filters_spec.rb +363 -0
- data/spec/sequel_core/migration_spec.rb +261 -0
- data/spec/sequel_core/object_graph_spec.rb +272 -0
- data/spec/sequel_core/pretty_table_spec.rb +58 -0
- data/spec/sequel_core/schema_generator_spec.rb +167 -0
- data/spec/sequel_core/schema_spec.rb +780 -0
- data/spec/sequel_core/spec_helper.rb +55 -0
- data/spec/sequel_core/version_spec.rb +7 -0
- data/spec/sequel_model/association_reflection_spec.rb +93 -0
- data/spec/sequel_model/associations_spec.rb +1767 -0
- data/spec/sequel_model/base_spec.rb +419 -0
- data/spec/sequel_model/caching_spec.rb +215 -0
- data/spec/sequel_model/dataset_methods_spec.rb +78 -0
- data/spec/sequel_model/eager_loading_spec.rb +1165 -0
- data/spec/sequel_model/hooks_spec.rb +485 -0
- data/spec/sequel_model/inflector_spec.rb +119 -0
- data/spec/sequel_model/model_spec.rb +588 -0
- data/spec/sequel_model/plugins_spec.rb +80 -0
- data/spec/sequel_model/record_spec.rb +1184 -0
- data/spec/sequel_model/schema_spec.rb +90 -0
- data/spec/sequel_model/spec_helper.rb +78 -0
- data/spec/sequel_model/validations_spec.rb +1067 -0
- data/spec/spec.opts +0 -0
- data/spec/spec_config.rb.example +10 -0
- metadata +177 -3
@@ -0,0 +1,31 @@
|
|
1
|
+
module Sequel
|
2
|
+
module Progress
|
3
|
+
module DatabaseMethods
|
4
|
+
|
5
|
+
def dataset(opts = nil)
|
6
|
+
ds = super
|
7
|
+
ds.extend(DatasetMethods)
|
8
|
+
ds
|
9
|
+
end
|
10
|
+
end
|
11
|
+
|
12
|
+
module DatasetMethods
|
13
|
+
include Dataset::UnsupportedIntersectExcept
|
14
|
+
|
15
|
+
SELECT_CLAUSE_ORDER = %w'limit distinct columns from join where group order having compounds'.freeze
|
16
|
+
|
17
|
+
private
|
18
|
+
|
19
|
+
def select_clause_order
|
20
|
+
SELECT_CLAUSE_ORDER
|
21
|
+
end
|
22
|
+
|
23
|
+
# Progress uses TOP for limit, but it is only supported in Progress 10.
|
24
|
+
# The Progress adapter targets Progress 9, so it silently ignores the option.
|
25
|
+
def select_limit_sql(sql, opts)
|
26
|
+
raise(Error, "OFFSET not supported") if opts[:offset]
|
27
|
+
#sql << " TOP #{opts[:limit]}" if opts[:limit]
|
28
|
+
end
|
29
|
+
end
|
30
|
+
end
|
31
|
+
end
|
@@ -0,0 +1,265 @@
|
|
1
|
+
module Sequel
|
2
|
+
module SQLite
|
3
|
+
module DatabaseMethods
|
4
|
+
AUTO_VACUUM = {'0' => :none, '1' => :full, '2' => :incremental}.freeze
|
5
|
+
SYNCHRONOUS = {'0' => :off, '1' => :normal, '2' => :full}.freeze
|
6
|
+
TABLES_FILTER = "type = 'table' AND NOT name = 'sqlite_sequence'"
|
7
|
+
TEMP_STORE = {'0' => :default, '1' => :file, '2' => :memory}.freeze
|
8
|
+
TYPES = Sequel::Schema::SQL::TYPES.merge(Bignum=>'integer')
|
9
|
+
|
10
|
+
# Run all alter_table commands in a transaction. This is technically only
|
11
|
+
# needed for drop column.
|
12
|
+
def alter_table(name, generator=nil, &block)
|
13
|
+
transaction{super}
|
14
|
+
end
|
15
|
+
|
16
|
+
# SQLite supports limited table modification. You can add a column
|
17
|
+
# or an index. Dropping columns is supported by copying the table into
|
18
|
+
# a temporary table, dropping the table, and creating a new table without
|
19
|
+
# the column inside of a transaction.
|
20
|
+
def alter_table_sql(table, op)
|
21
|
+
case op[:op]
|
22
|
+
when :add_column, :add_index, :drop_index
|
23
|
+
super
|
24
|
+
when :drop_column
|
25
|
+
qt = quote_schema_table(table)
|
26
|
+
bt = quote_identifier(backup_table_name(qt.gsub('`', '')))
|
27
|
+
columns_str = dataset.send(:identifier_list, columns_for(table, :except => op[:name]))
|
28
|
+
defined_columns_str = column_list_sql(defined_columns_for(table, :except => op[:name]))
|
29
|
+
["CREATE TEMPORARY TABLE #{bt}(#{defined_columns_str})",
|
30
|
+
"INSERT INTO #{bt} SELECT #{columns_str} FROM #{qt}",
|
31
|
+
"DROP TABLE #{qt}",
|
32
|
+
"CREATE TABLE #{qt}(#{defined_columns_str})",
|
33
|
+
"INSERT INTO #{qt} SELECT #{columns_str} FROM #{bt}",
|
34
|
+
"DROP TABLE #{bt}"]
|
35
|
+
when :rename_column
|
36
|
+
qt = quote_schema_table(table)
|
37
|
+
bt = quote_identifier(backup_table_name(qt.gsub('`', '')))
|
38
|
+
old_columns = dataset.send(:identifier_list, columns_for(table))
|
39
|
+
new_columns_arr = columns_for(table)
|
40
|
+
|
41
|
+
# Replace the old column in place. This is extremely important.
|
42
|
+
new_columns_arr[new_columns_arr.index(op[:name])] = op[:new_name]
|
43
|
+
|
44
|
+
new_columns = dataset.send(:identifier_list, new_columns_arr)
|
45
|
+
|
46
|
+
def_old_columns = column_list_sql(defined_columns_for(table))
|
47
|
+
|
48
|
+
def_new_columns_arr = defined_columns_for(table).map do |c|
|
49
|
+
c[:name] = op[:new_name].to_s if c[:name] == op[:name].to_s
|
50
|
+
c
|
51
|
+
end
|
52
|
+
|
53
|
+
def_new_columns = column_list_sql(def_new_columns_arr)
|
54
|
+
|
55
|
+
[
|
56
|
+
"CREATE TEMPORARY TABLE #{bt}(#{def_old_columns})",
|
57
|
+
"INSERT INTO #{bt}(#{old_columns}) SELECT #{old_columns} FROM #{qt}",
|
58
|
+
"DROP TABLE #{qt}",
|
59
|
+
"CREATE TABLE #{qt}(#{def_new_columns})",
|
60
|
+
"INSERT INTO #{qt}(#{new_columns}) SELECT #{old_columns} FROM #{bt}",
|
61
|
+
"DROP TABLE #{bt}"
|
62
|
+
]
|
63
|
+
|
64
|
+
else
|
65
|
+
raise Error, "Unsupported ALTER TABLE operation"
|
66
|
+
end
|
67
|
+
end
|
68
|
+
|
69
|
+
# A symbol signifying the value of the auto_vacuum PRAGMA.
|
70
|
+
def auto_vacuum
|
71
|
+
AUTO_VACUUM[pragma_get(:auto_vacuum).to_s]
|
72
|
+
end
|
73
|
+
|
74
|
+
# Set the auto_vacuum PRAGMA using the given symbol (:none, :full, or
|
75
|
+
# :incremental).
|
76
|
+
def auto_vacuum=(value)
|
77
|
+
value = AUTO_VACUUM.key(value) || (raise Error, "Invalid value for auto_vacuum option. Please specify one of :none, :full, :incremental.")
|
78
|
+
pragma_set(:auto_vacuum, value)
|
79
|
+
end
|
80
|
+
|
81
|
+
# Get the value of the given PRAGMA.
|
82
|
+
def pragma_get(name)
|
83
|
+
self["PRAGMA #{name}"].single_value
|
84
|
+
end
|
85
|
+
|
86
|
+
# Set the value of the given PRAGMA to value.
|
87
|
+
def pragma_set(name, value)
|
88
|
+
execute_ddl("PRAGMA #{name} = #{value}")
|
89
|
+
end
|
90
|
+
|
91
|
+
# A symbol signifying the value of the synchronous PRAGMA.
|
92
|
+
def synchronous
|
93
|
+
SYNCHRONOUS[pragma_get(:synchronous).to_s]
|
94
|
+
end
|
95
|
+
|
96
|
+
# Set the synchronous PRAGMA using the given symbol (:off, :normal, or :full).
|
97
|
+
def synchronous=(value)
|
98
|
+
value = SYNCHRONOUS.key(value) || (raise Error, "Invalid value for synchronous option. Please specify one of :off, :normal, :full.")
|
99
|
+
pragma_set(:synchronous, value)
|
100
|
+
end
|
101
|
+
|
102
|
+
# Array of symbols specifying the table names in the current database.
|
103
|
+
#
|
104
|
+
# Options:
|
105
|
+
# * :server - Set the server to use.
|
106
|
+
def tables(opts={})
|
107
|
+
ds = self[:sqlite_master].server(opts[:server]).filter(TABLES_FILTER)
|
108
|
+
ds.identifier_output_method = nil
|
109
|
+
ds.identifier_input_method = nil
|
110
|
+
ds2 = dataset
|
111
|
+
ds.map{|r| ds2.send(:output_identifier, r[:name])}
|
112
|
+
end
|
113
|
+
|
114
|
+
# A symbol signifying the value of the temp_store PRAGMA.
|
115
|
+
def temp_store
|
116
|
+
TEMP_STORE[pragma_get(:temp_store).to_s]
|
117
|
+
end
|
118
|
+
|
119
|
+
# Set the temp_store PRAGMA using the given symbol (:default, :file, or :memory).
|
120
|
+
def temp_store=(value)
|
121
|
+
value = TEMP_STORE.key(value) || (raise Error, "Invalid value for temp_store option. Please specify one of :default, :file, :memory.")
|
122
|
+
pragma_set(:temp_store, value)
|
123
|
+
end
|
124
|
+
|
125
|
+
private
|
126
|
+
|
127
|
+
# The array of column symbols in the table, except for ones given in opts[:except]
|
128
|
+
def backup_table_name(table, opts={})
|
129
|
+
(opts[:times]||1000).times do |i|
|
130
|
+
table_name = "#{table}_backup#{i}"
|
131
|
+
return table_name unless table_exists?(table_name)
|
132
|
+
end
|
133
|
+
end
|
134
|
+
|
135
|
+
# The array of column symbols in the table, except for ones given in opts[:except]
|
136
|
+
def columns_for(table, opts={})
|
137
|
+
cols = schema_parse_table(table, {}).map{|c| c[0]}
|
138
|
+
cols = cols - Array(opts[:except])
|
139
|
+
cols
|
140
|
+
end
|
141
|
+
|
142
|
+
# The array of column schema hashes, except for the ones given in opts[:except]
|
143
|
+
def defined_columns_for(table, opts={})
|
144
|
+
cols = parse_pragma(table, {})
|
145
|
+
cols.each{|c| c[:default] = c[:default].lit if c[:default]}
|
146
|
+
if opts[:except]
|
147
|
+
nono= Array(opts[:except]).compact.map{|n| n.to_s}
|
148
|
+
cols.reject!{|c| nono.include? c[:name] }
|
149
|
+
end
|
150
|
+
cols
|
151
|
+
end
|
152
|
+
|
153
|
+
# SQLite folds unquoted identifiers to lowercase, so it shouldn't need to upcase identifiers on input.
|
154
|
+
def identifier_input_method_default
|
155
|
+
nil
|
156
|
+
end
|
157
|
+
|
158
|
+
# SQLite folds unquoted identifiers to lowercase, so it shouldn't need to upcase identifiers on output.
|
159
|
+
def identifier_output_method_default
|
160
|
+
nil
|
161
|
+
end
|
162
|
+
|
163
|
+
# Parse the output of the table_info pragma
|
164
|
+
def parse_pragma(table_name, opts)
|
165
|
+
ds2 = dataset
|
166
|
+
ds = self["PRAGMA table_info(?)", ds2.send(:input_identifier, table_name)]
|
167
|
+
ds.identifier_output_method = nil
|
168
|
+
ds.map do |row|
|
169
|
+
row.delete(:cid)
|
170
|
+
row[:allow_null] = row.delete(:notnull).to_i == 0
|
171
|
+
row[:default] = row.delete(:dflt_value)
|
172
|
+
row[:primary_key] = row.delete(:pk).to_i == 1
|
173
|
+
row[:default] = nil if row[:default].blank?
|
174
|
+
row[:db_type] = row.delete(:type)
|
175
|
+
row[:type] = schema_column_type(row[:db_type])
|
176
|
+
row
|
177
|
+
end
|
178
|
+
end
|
179
|
+
|
180
|
+
# SQLite supports schema parsing using the table_info PRAGMA, so
|
181
|
+
# parse the output of that into the format Sequel expects.
|
182
|
+
def schema_parse_table(table_name, opts)
|
183
|
+
ds = dataset
|
184
|
+
parse_pragma(table_name, opts).map do |row|
|
185
|
+
[ds.send(:output_identifier, row.delete(:name)), row]
|
186
|
+
end
|
187
|
+
end
|
188
|
+
|
189
|
+
# Override the standard type conversions with SQLite specific ones
|
190
|
+
def type_literal_base(column)
|
191
|
+
TYPES[column[:type]]
|
192
|
+
end
|
193
|
+
end
|
194
|
+
|
195
|
+
# Instance methods for datasets that connect to an SQLite database
|
196
|
+
module DatasetMethods
|
197
|
+
include Dataset::UnsupportedIntersectExceptAll
|
198
|
+
|
199
|
+
# SQLite does not support pattern matching via regular expressions.
|
200
|
+
# SQLite is case insensitive (depending on pragma), so use LIKE for
|
201
|
+
# ILIKE.
|
202
|
+
def complex_expression_sql(op, args)
|
203
|
+
case op
|
204
|
+
when :~, :'!~', :'~*', :'!~*'
|
205
|
+
raise Error, "SQLite does not support pattern matching via regular expressions"
|
206
|
+
when :LIKE, :'NOT LIKE', :ILIKE, :'NOT ILIKE'
|
207
|
+
# SQLite is case insensitive for ASCII, and non case sensitive for other character sets
|
208
|
+
"#{'NOT ' if [:'NOT LIKE', :'NOT ILIKE'].include?(op)}(#{literal(args.at(0))} LIKE #{literal(args.at(1))})"
|
209
|
+
else
|
210
|
+
super(op, args)
|
211
|
+
end
|
212
|
+
end
|
213
|
+
|
214
|
+
# SQLite performs a TRUNCATE style DELETE if no filter is specified.
|
215
|
+
# Since we want to always return the count of records, add a condition
|
216
|
+
# that is always true and then delete.
|
217
|
+
def delete(opts = {})
|
218
|
+
# check if no filter is specified
|
219
|
+
opts = @opts.merge(opts)
|
220
|
+
super(opts[:where] ? opts : opts.merge(:where=>{1=>1}))
|
221
|
+
end
|
222
|
+
|
223
|
+
# Insert the values into the database.
|
224
|
+
def insert(*values)
|
225
|
+
execute_insert(insert_sql(*values))
|
226
|
+
end
|
227
|
+
|
228
|
+
# Allow inserting of values directly from a dataset.
|
229
|
+
def insert_sql(*values)
|
230
|
+
if (values.size == 1) && values.first.is_a?(Sequel::Dataset)
|
231
|
+
"INSERT INTO #{source_list(@opts[:from])} #{values.first.sql};"
|
232
|
+
else
|
233
|
+
super(*values)
|
234
|
+
end
|
235
|
+
end
|
236
|
+
|
237
|
+
def literal(v)
|
238
|
+
case v
|
239
|
+
when ::Sequel::SQL::Blob
|
240
|
+
blob = ''
|
241
|
+
v.each_byte{|x| blob << sprintf('%02x', x)}
|
242
|
+
"X'#{blob}'"
|
243
|
+
when Time
|
244
|
+
literal(v.iso8601)
|
245
|
+
when Date, DateTime
|
246
|
+
literal(v.to_s)
|
247
|
+
else
|
248
|
+
super
|
249
|
+
end
|
250
|
+
end
|
251
|
+
|
252
|
+
# SQLite uses the nonstandard ` (backtick) for quoting identifiers.
|
253
|
+
def quoted_identifier(c)
|
254
|
+
"`#{c}`"
|
255
|
+
end
|
256
|
+
|
257
|
+
private
|
258
|
+
|
259
|
+
# SQLite uses string literals instead of identifiers in AS clauses.
|
260
|
+
def as_sql(expression, aliaz)
|
261
|
+
"#{expression} AS #{literal(aliaz.to_s)}"
|
262
|
+
end
|
263
|
+
end
|
264
|
+
end
|
265
|
+
end
|
@@ -0,0 +1,248 @@
|
|
1
|
+
require 'sqlite3'
|
2
|
+
require 'sequel_core/adapters/shared/sqlite'
|
3
|
+
|
4
|
+
module Sequel
|
5
|
+
# Top level module for holding all SQLite-related modules and classes
|
6
|
+
# for Sequel.
|
7
|
+
module SQLite
|
8
|
+
# Database class for PostgreSQL databases used with Sequel and the
|
9
|
+
# ruby-sqlite3 driver.
|
10
|
+
class Database < Sequel::Database
|
11
|
+
UNIX_EPOCH_TIME_FORMAT = /\A\d+\z/.freeze
|
12
|
+
include ::Sequel::SQLite::DatabaseMethods
|
13
|
+
|
14
|
+
set_adapter_scheme :sqlite
|
15
|
+
|
16
|
+
# Mimic the file:// uri, by having 2 preceding slashes specify a relative
|
17
|
+
# path, and 3 preceding slashes specify an absolute path.
|
18
|
+
def self.uri_to_options(uri) # :nodoc:
|
19
|
+
{ :database => (uri.host.nil? && uri.path == '/') ? nil : "#{uri.host}#{uri.path}" }
|
20
|
+
end
|
21
|
+
|
22
|
+
private_class_method :uri_to_options
|
23
|
+
|
24
|
+
# Connect to the database. Since SQLite is a file based database,
|
25
|
+
# the only options available are :database (to specify the database
|
26
|
+
# name), and :timeout, to specify how long to wait for the database to
|
27
|
+
# be available if it is locked, given in milliseconds (default is 5000).
|
28
|
+
def connect(server)
|
29
|
+
opts = server_opts(server)
|
30
|
+
opts[:database] = ':memory:' if opts[:database].blank?
|
31
|
+
db = ::SQLite3::Database.new(opts[:database])
|
32
|
+
db.busy_timeout(opts.fetch(:timeout, 5000))
|
33
|
+
db.type_translation = true
|
34
|
+
|
35
|
+
# Handle datetime's with Sequel.datetime_class
|
36
|
+
prok = proc do |t,v|
|
37
|
+
v = Time.at(v.to_i).iso8601 if UNIX_EPOCH_TIME_FORMAT.match(v)
|
38
|
+
v.to_sequel_time
|
39
|
+
end
|
40
|
+
db.translator.add_translator("timestamp", &prok)
|
41
|
+
db.translator.add_translator("datetime", &prok)
|
42
|
+
|
43
|
+
# Handle numeric values with BigDecimal
|
44
|
+
prok = proc{|t,v| BigDecimal.new(v) rescue v}
|
45
|
+
db.translator.add_translator("numeric", &prok)
|
46
|
+
db.translator.add_translator("decimal", &prok)
|
47
|
+
db.translator.add_translator("money", &prok)
|
48
|
+
|
49
|
+
# Handle floating point values with Float
|
50
|
+
prok = proc{|t,v| Float(v) rescue v}
|
51
|
+
db.translator.add_translator("float", &prok)
|
52
|
+
db.translator.add_translator("real", &prok)
|
53
|
+
db.translator.add_translator("double precision", &prok)
|
54
|
+
|
55
|
+
# Handle blob values with Sequel::SQL::Blob
|
56
|
+
db.translator.add_translator("blob"){|t,v| ::Sequel::SQL::Blob.new(v)}
|
57
|
+
|
58
|
+
db
|
59
|
+
end
|
60
|
+
|
61
|
+
# Return instance of Sequel::SQLite::Dataset with the given options.
|
62
|
+
def dataset(opts = nil)
|
63
|
+
SQLite::Dataset.new(self, opts)
|
64
|
+
end
|
65
|
+
|
66
|
+
# Run the given SQL with the given arguments and return the number of changed rows.
|
67
|
+
def execute_dui(sql, opts={})
|
68
|
+
_execute(sql, opts){|conn| conn.execute_batch(sql, opts[:arguments]); conn.changes}
|
69
|
+
end
|
70
|
+
|
71
|
+
# Run the given SQL with the given arguments and return the last inserted row id.
|
72
|
+
def execute_insert(sql, opts={})
|
73
|
+
_execute(sql, opts){|conn| conn.execute(sql, opts[:arguments]); conn.last_insert_row_id}
|
74
|
+
end
|
75
|
+
|
76
|
+
# Run the given SQL with the given arguments and yield each row.
|
77
|
+
def execute(sql, opts={}, &block)
|
78
|
+
_execute(sql, opts){|conn| conn.query(sql, opts[:arguments], &block)}
|
79
|
+
end
|
80
|
+
|
81
|
+
# Run the given SQL with the given arguments and return the first value of the first row.
|
82
|
+
def single_value(sql, opts={})
|
83
|
+
_execute(sql, opts){|conn| conn.get_first_value(sql, opts[:arguments])}
|
84
|
+
end
|
85
|
+
|
86
|
+
# Use the native driver transaction method if there isn't already a transaction
|
87
|
+
# in progress on the connection, always yielding a connection inside a transaction
|
88
|
+
# transaction.
|
89
|
+
def transaction(server=nil, &block)
|
90
|
+
synchronize(server) do |conn|
|
91
|
+
return yield(conn) if conn.transaction_active?
|
92
|
+
begin
|
93
|
+
result = nil
|
94
|
+
log_info('Transaction.begin')
|
95
|
+
conn.transaction{result = yield(conn)}
|
96
|
+
result
|
97
|
+
rescue ::Exception => e
|
98
|
+
log_info('Transaction.rollback')
|
99
|
+
transaction_error(e, SQLite3::Exception)
|
100
|
+
ensure
|
101
|
+
log_info('Transaction.commit') unless e
|
102
|
+
end
|
103
|
+
end
|
104
|
+
end
|
105
|
+
|
106
|
+
private
|
107
|
+
|
108
|
+
# Log the SQL and the arguments, and yield an available connection. Rescue
|
109
|
+
# any SQLite3::Exceptions and turn the into Error::InvalidStatements.
|
110
|
+
def _execute(sql, opts)
|
111
|
+
begin
|
112
|
+
log_info(sql, opts[:arguments])
|
113
|
+
synchronize(opts[:server]){|conn| yield conn}
|
114
|
+
rescue SQLite3::Exception => e
|
115
|
+
raise_error(e)
|
116
|
+
end
|
117
|
+
end
|
118
|
+
|
119
|
+
# SQLite does not need the pool to convert exceptions.
|
120
|
+
# Also, force the max connections to 1 if a memory database is being
|
121
|
+
# used, as otherwise each connection gets a separate database.
|
122
|
+
def connection_pool_default_options
|
123
|
+
o = super.merge(:pool_convert_exceptions=>false)
|
124
|
+
# Default to only a single connection if a memory database is used,
|
125
|
+
# because otherwise each connection will get a separate database
|
126
|
+
o[:max_connections] = 1 if @opts[:database] == ':memory:' || @opts[:database].blank?
|
127
|
+
o
|
128
|
+
end
|
129
|
+
|
130
|
+
# Disconnect given connections from the database.
|
131
|
+
def disconnect_connection(c)
|
132
|
+
c.close
|
133
|
+
end
|
134
|
+
end
|
135
|
+
|
136
|
+
# Dataset class for SQLite datasets that use the ruby-sqlite3 driver.
|
137
|
+
class Dataset < Sequel::Dataset
|
138
|
+
include ::Sequel::SQLite::DatasetMethods
|
139
|
+
|
140
|
+
EXPLAIN = 'EXPLAIN %s'.freeze
|
141
|
+
PREPARED_ARG_PLACEHOLDER = ':'.freeze
|
142
|
+
|
143
|
+
# SQLite already supports named bind arguments, so use directly.
|
144
|
+
module ArgumentMapper
|
145
|
+
include Sequel::Dataset::ArgumentMapper
|
146
|
+
|
147
|
+
protected
|
148
|
+
|
149
|
+
# Return a hash with the same values as the given hash,
|
150
|
+
# but with the keys converted to strings.
|
151
|
+
def map_to_prepared_args(hash)
|
152
|
+
args = {}
|
153
|
+
hash.each{|k,v| args[k.to_s] = v}
|
154
|
+
args
|
155
|
+
end
|
156
|
+
|
157
|
+
private
|
158
|
+
|
159
|
+
# SQLite uses a : before the name of the argument for named
|
160
|
+
# arguments.
|
161
|
+
def prepared_arg(k)
|
162
|
+
"#{prepared_arg_placeholder}#{k}".lit
|
163
|
+
end
|
164
|
+
end
|
165
|
+
|
166
|
+
# SQLite prepared statement uses a new prepared statement each time
|
167
|
+
# it is called, but it does use the bind arguments.
|
168
|
+
module PreparedStatementMethods
|
169
|
+
include ArgumentMapper
|
170
|
+
|
171
|
+
private
|
172
|
+
|
173
|
+
# Run execute_select on the database with the given SQL and the stored
|
174
|
+
# bind arguments.
|
175
|
+
def execute(sql, opts={}, &block)
|
176
|
+
super(sql, {:arguments=>bind_arguments}.merge(opts), &block)
|
177
|
+
end
|
178
|
+
|
179
|
+
# Same as execute, explicit due to intricacies of alias and super.
|
180
|
+
def execute_dui(sql, opts={}, &block)
|
181
|
+
super(sql, {:arguments=>bind_arguments}.merge(opts), &block)
|
182
|
+
end
|
183
|
+
|
184
|
+
# Same as execute, explicit due to intricacies of alias and super.
|
185
|
+
def execute_insert(sql, opts={}, &block)
|
186
|
+
super(sql, {:arguments=>bind_arguments}.merge(opts), &block)
|
187
|
+
end
|
188
|
+
end
|
189
|
+
|
190
|
+
# Prepare an unnamed statement of the given type and call it with the
|
191
|
+
# given values.
|
192
|
+
def call(type, hash, values=nil, &block)
|
193
|
+
prepare(type, nil, values).call(hash, &block)
|
194
|
+
end
|
195
|
+
|
196
|
+
# Return an array of strings specifying a query explanation for the
|
197
|
+
# current dataset.
|
198
|
+
def explain
|
199
|
+
res = []
|
200
|
+
@db.result_set(EXPLAIN % select_sql(opts), nil) {|r| res << r}
|
201
|
+
res
|
202
|
+
end
|
203
|
+
|
204
|
+
# Yield a hash for each row in the dataset.
|
205
|
+
def fetch_rows(sql)
|
206
|
+
execute(sql) do |result|
|
207
|
+
@columns = result.columns.map{|c| output_identifier(c)}
|
208
|
+
column_count = @columns.size
|
209
|
+
result.each do |values|
|
210
|
+
row = {}
|
211
|
+
column_count.times {|i| row[@columns[i]] = values[i]}
|
212
|
+
yield row
|
213
|
+
end
|
214
|
+
end
|
215
|
+
end
|
216
|
+
|
217
|
+
# Use the ISO format for dates and timestamps, and quote strings
|
218
|
+
# using the ::SQLite3::Database.quote method.
|
219
|
+
def literal(v)
|
220
|
+
case v
|
221
|
+
when LiteralString, ::Sequel::SQL::Blob
|
222
|
+
super
|
223
|
+
when String
|
224
|
+
"'#{::SQLite3::Database.quote(v)}'"
|
225
|
+
else
|
226
|
+
super
|
227
|
+
end
|
228
|
+
end
|
229
|
+
|
230
|
+
# Prepare the given type of query with the given name and store
|
231
|
+
# it in the database. Note that a new native prepared statement is
|
232
|
+
# created on each call to this prepared statement.
|
233
|
+
def prepare(type, name=nil, values=nil)
|
234
|
+
ps = to_prepared_statement(type, values)
|
235
|
+
ps.extend(PreparedStatementMethods)
|
236
|
+
db.prepared_statements[name] = ps if name
|
237
|
+
ps
|
238
|
+
end
|
239
|
+
|
240
|
+
private
|
241
|
+
|
242
|
+
# SQLite uses a : before the name of the argument as a placeholder.
|
243
|
+
def prepared_arg_placeholder
|
244
|
+
PREPARED_ARG_PLACEHOLDER
|
245
|
+
end
|
246
|
+
end
|
247
|
+
end
|
248
|
+
end
|