epugh-sequel 0.0.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- data/README.rdoc +652 -0
- data/VERSION.yml +4 -0
- data/bin/sequel +104 -0
- data/lib/sequel.rb +1 -0
- data/lib/sequel/adapters/ado.rb +85 -0
- data/lib/sequel/adapters/db2.rb +132 -0
- data/lib/sequel/adapters/dbi.rb +101 -0
- data/lib/sequel/adapters/do.rb +197 -0
- data/lib/sequel/adapters/do/mysql.rb +38 -0
- data/lib/sequel/adapters/do/postgres.rb +92 -0
- data/lib/sequel/adapters/do/sqlite.rb +31 -0
- data/lib/sequel/adapters/firebird.rb +307 -0
- data/lib/sequel/adapters/informix.rb +75 -0
- data/lib/sequel/adapters/jdbc.rb +485 -0
- data/lib/sequel/adapters/jdbc/h2.rb +62 -0
- data/lib/sequel/adapters/jdbc/mysql.rb +56 -0
- data/lib/sequel/adapters/jdbc/oracle.rb +23 -0
- data/lib/sequel/adapters/jdbc/postgresql.rb +101 -0
- data/lib/sequel/adapters/jdbc/sqlite.rb +43 -0
- data/lib/sequel/adapters/mysql.rb +370 -0
- data/lib/sequel/adapters/odbc.rb +184 -0
- data/lib/sequel/adapters/openbase.rb +57 -0
- data/lib/sequel/adapters/oracle.rb +140 -0
- data/lib/sequel/adapters/postgres.rb +453 -0
- data/lib/sequel/adapters/shared/mssql.rb +93 -0
- data/lib/sequel/adapters/shared/mysql.rb +341 -0
- data/lib/sequel/adapters/shared/oracle.rb +62 -0
- data/lib/sequel/adapters/shared/postgres.rb +743 -0
- data/lib/sequel/adapters/shared/progress.rb +34 -0
- data/lib/sequel/adapters/shared/sqlite.rb +263 -0
- data/lib/sequel/adapters/sqlite.rb +243 -0
- data/lib/sequel/adapters/utils/date_format.rb +21 -0
- data/lib/sequel/adapters/utils/stored_procedures.rb +75 -0
- data/lib/sequel/adapters/utils/unsupported.rb +62 -0
- data/lib/sequel/connection_pool.rb +258 -0
- data/lib/sequel/core.rb +204 -0
- data/lib/sequel/core_sql.rb +185 -0
- data/lib/sequel/database.rb +687 -0
- data/lib/sequel/database/schema_generator.rb +324 -0
- data/lib/sequel/database/schema_methods.rb +164 -0
- data/lib/sequel/database/schema_sql.rb +324 -0
- data/lib/sequel/dataset.rb +422 -0
- data/lib/sequel/dataset/convenience.rb +237 -0
- data/lib/sequel/dataset/prepared_statements.rb +220 -0
- data/lib/sequel/dataset/sql.rb +1105 -0
- data/lib/sequel/deprecated.rb +529 -0
- data/lib/sequel/exceptions.rb +44 -0
- data/lib/sequel/extensions/blank.rb +42 -0
- data/lib/sequel/extensions/inflector.rb +288 -0
- data/lib/sequel/extensions/pagination.rb +96 -0
- data/lib/sequel/extensions/pretty_table.rb +78 -0
- data/lib/sequel/extensions/query.rb +48 -0
- data/lib/sequel/extensions/string_date_time.rb +47 -0
- data/lib/sequel/metaprogramming.rb +44 -0
- data/lib/sequel/migration.rb +212 -0
- data/lib/sequel/model.rb +142 -0
- data/lib/sequel/model/association_reflection.rb +263 -0
- data/lib/sequel/model/associations.rb +1024 -0
- data/lib/sequel/model/base.rb +911 -0
- data/lib/sequel/model/deprecated.rb +188 -0
- data/lib/sequel/model/deprecated_hooks.rb +103 -0
- data/lib/sequel/model/deprecated_inflector.rb +335 -0
- data/lib/sequel/model/deprecated_validations.rb +384 -0
- data/lib/sequel/model/errors.rb +37 -0
- data/lib/sequel/model/exceptions.rb +7 -0
- data/lib/sequel/model/inflections.rb +230 -0
- data/lib/sequel/model/plugins.rb +74 -0
- data/lib/sequel/object_graph.rb +230 -0
- data/lib/sequel/plugins/caching.rb +122 -0
- data/lib/sequel/plugins/hook_class_methods.rb +122 -0
- data/lib/sequel/plugins/schema.rb +53 -0
- data/lib/sequel/plugins/single_table_inheritance.rb +63 -0
- data/lib/sequel/plugins/validation_class_methods.rb +373 -0
- data/lib/sequel/sql.rb +854 -0
- data/lib/sequel/version.rb +11 -0
- data/lib/sequel_core.rb +1 -0
- data/lib/sequel_model.rb +1 -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 +875 -0
- data/spec/adapters/oracle_spec.rb +272 -0
- data/spec/adapters/postgres_spec.rb +692 -0
- data/spec/adapters/spec_helper.rb +10 -0
- data/spec/adapters/sqlite_spec.rb +550 -0
- data/spec/core/connection_pool_spec.rb +526 -0
- data/spec/core/core_ext_spec.rb +156 -0
- data/spec/core/core_sql_spec.rb +528 -0
- data/spec/core/database_spec.rb +1214 -0
- data/spec/core/dataset_spec.rb +3513 -0
- data/spec/core/expression_filters_spec.rb +363 -0
- data/spec/core/migration_spec.rb +261 -0
- data/spec/core/object_graph_spec.rb +280 -0
- data/spec/core/pretty_table_spec.rb +58 -0
- data/spec/core/schema_generator_spec.rb +167 -0
- data/spec/core/schema_spec.rb +778 -0
- data/spec/core/spec_helper.rb +82 -0
- data/spec/core/version_spec.rb +7 -0
- data/spec/extensions/blank_spec.rb +67 -0
- data/spec/extensions/caching_spec.rb +201 -0
- data/spec/extensions/hook_class_methods_spec.rb +470 -0
- data/spec/extensions/inflector_spec.rb +122 -0
- data/spec/extensions/pagination_spec.rb +99 -0
- data/spec/extensions/pretty_table_spec.rb +91 -0
- data/spec/extensions/query_spec.rb +85 -0
- data/spec/extensions/schema_spec.rb +111 -0
- data/spec/extensions/single_table_inheritance_spec.rb +53 -0
- data/spec/extensions/spec_helper.rb +90 -0
- data/spec/extensions/string_date_time_spec.rb +93 -0
- data/spec/extensions/validation_class_methods_spec.rb +1054 -0
- data/spec/integration/dataset_test.rb +160 -0
- data/spec/integration/eager_loader_test.rb +683 -0
- data/spec/integration/prepared_statement_test.rb +130 -0
- data/spec/integration/schema_test.rb +183 -0
- data/spec/integration/spec_helper.rb +75 -0
- data/spec/integration/type_test.rb +96 -0
- data/spec/model/association_reflection_spec.rb +93 -0
- data/spec/model/associations_spec.rb +1780 -0
- data/spec/model/base_spec.rb +494 -0
- data/spec/model/caching_spec.rb +217 -0
- data/spec/model/dataset_methods_spec.rb +78 -0
- data/spec/model/eager_loading_spec.rb +1165 -0
- data/spec/model/hooks_spec.rb +472 -0
- data/spec/model/inflector_spec.rb +126 -0
- data/spec/model/model_spec.rb +588 -0
- data/spec/model/plugins_spec.rb +142 -0
- data/spec/model/record_spec.rb +1243 -0
- data/spec/model/schema_spec.rb +92 -0
- data/spec/model/spec_helper.rb +124 -0
- data/spec/model/validations_spec.rb +1080 -0
- data/spec/rcov.opts +6 -0
- data/spec/spec.opts +0 -0
- data/spec/spec_config.rb.example +10 -0
- metadata +202 -0
|
@@ -0,0 +1,743 @@
|
|
|
1
|
+
module Sequel
|
|
2
|
+
# Top level module for holding all PostgreSQL-related modules and classes
|
|
3
|
+
# for Sequel. There are a few module level accessors that are added via
|
|
4
|
+
# metaprogramming. These are:
|
|
5
|
+
# * client_min_messages (only available when using the native adapter) -
|
|
6
|
+
# Change the minimum level of messages that PostgreSQL will send to the
|
|
7
|
+
# the client. The PostgreSQL default is NOTICE, the Sequel default is
|
|
8
|
+
# WARNING. Set to nil to not change the server default.
|
|
9
|
+
# * force_standard_strings - Set to false to not force the use of
|
|
10
|
+
# standard strings
|
|
11
|
+
# * use_iso_date_format (only available when using the native adapter) -
|
|
12
|
+
# Set to false to not change the date format to
|
|
13
|
+
# ISO. This disables one of Sequel's optimizations.
|
|
14
|
+
#
|
|
15
|
+
# Changes in these settings only affect future connections. To make
|
|
16
|
+
# sure that they are applied, they should generally be called right
|
|
17
|
+
# after the Database object is instantiated and before a connection
|
|
18
|
+
# is actually made. For example, to use whatever the server defaults are:
|
|
19
|
+
#
|
|
20
|
+
# DB = Sequel.postgres(...)
|
|
21
|
+
# Sequel::Postgres.client_min_messages = nil
|
|
22
|
+
# Sequel::Postgres.force_standard_strings = false
|
|
23
|
+
# Sequel::Postgres.use_iso_date_format = false
|
|
24
|
+
# # A connection to the server is not made until here
|
|
25
|
+
# DB[:t].all
|
|
26
|
+
#
|
|
27
|
+
# The reason they can't be done earlier is that the Sequel::Postgres
|
|
28
|
+
# module is not loaded until a Database object which uses PostgreSQL
|
|
29
|
+
# is created.
|
|
30
|
+
module Postgres
|
|
31
|
+
# Array of exceptions that need to be converted. JDBC
|
|
32
|
+
# uses NativeExceptions, the native adapter uses PGError.
|
|
33
|
+
CONVERTED_EXCEPTIONS = []
|
|
34
|
+
|
|
35
|
+
@client_min_messages = :warning
|
|
36
|
+
@force_standard_strings = true
|
|
37
|
+
|
|
38
|
+
class << self
|
|
39
|
+
# By default, Sequel sets the minimum level of log messages sent to the client
|
|
40
|
+
# to WARNING, where PostgreSQL uses a default of NOTICE. This is to avoid a lot
|
|
41
|
+
# of mostly useless messages when running migrations, such as a couple of lines
|
|
42
|
+
# for every serial primary key field.
|
|
43
|
+
attr_accessor :client_min_messages
|
|
44
|
+
|
|
45
|
+
# By default, Sequel forces the use of standard strings, so that
|
|
46
|
+
# '\\' is interpreted as \\ and not \. While PostgreSQL defaults
|
|
47
|
+
# to interpreting plain strings as extended strings, this will change
|
|
48
|
+
# in a future version of PostgreSQL. Sequel assumes that SQL standard
|
|
49
|
+
# strings will be used.
|
|
50
|
+
attr_accessor :force_standard_strings
|
|
51
|
+
end
|
|
52
|
+
|
|
53
|
+
# Methods shared by adapter/connection instances.
|
|
54
|
+
module AdapterMethods
|
|
55
|
+
attr_writer :db
|
|
56
|
+
|
|
57
|
+
SELECT_CURRVAL = "SELECT currval('%s')".freeze
|
|
58
|
+
SELECT_CUSTOM_SEQUENCE = proc do |schema, table| <<-end_sql
|
|
59
|
+
SELECT '"' || name.nspname || '"."' || CASE
|
|
60
|
+
WHEN split_part(def.adsrc, '''', 2) ~ '.' THEN
|
|
61
|
+
substr(split_part(def.adsrc, '''', 2),
|
|
62
|
+
strpos(split_part(def.adsrc, '''', 2), '.')+1)
|
|
63
|
+
ELSE split_part(def.adsrc, '''', 2)
|
|
64
|
+
END || '"'
|
|
65
|
+
FROM pg_class t
|
|
66
|
+
JOIN pg_namespace name ON (t.relnamespace = name.oid)
|
|
67
|
+
JOIN pg_attribute attr ON (t.oid = attrelid)
|
|
68
|
+
JOIN pg_attrdef def ON (adrelid = attrelid AND adnum = attnum)
|
|
69
|
+
JOIN pg_constraint cons ON (conrelid = adrelid AND adnum = conkey[1])
|
|
70
|
+
WHERE cons.contype = 'p'
|
|
71
|
+
AND def.adsrc ~* 'nextval'
|
|
72
|
+
#{"AND name.nspname = '#{schema}'" if schema}
|
|
73
|
+
AND t.relname = '#{table}'
|
|
74
|
+
end_sql
|
|
75
|
+
end
|
|
76
|
+
SELECT_PK = proc do |schema, table| <<-end_sql
|
|
77
|
+
SELECT pg_attribute.attname
|
|
78
|
+
FROM pg_class, pg_attribute, pg_index, pg_namespace
|
|
79
|
+
WHERE pg_class.oid = pg_attribute.attrelid
|
|
80
|
+
AND pg_class.relnamespace = pg_namespace.oid
|
|
81
|
+
AND pg_class.oid = pg_index.indrelid
|
|
82
|
+
AND pg_index.indkey[0] = pg_attribute.attnum
|
|
83
|
+
AND pg_index.indisprimary = 't'
|
|
84
|
+
#{"AND pg_namespace.nspname = '#{schema}'" if schema}
|
|
85
|
+
AND pg_class.relname = '#{table}'
|
|
86
|
+
end_sql
|
|
87
|
+
end
|
|
88
|
+
SELECT_SERIAL_SEQUENCE = proc do |schema, table| <<-end_sql
|
|
89
|
+
SELECT '"' || name.nspname || '"."' || seq.relname || '"'
|
|
90
|
+
FROM pg_class seq, pg_attribute attr, pg_depend dep,
|
|
91
|
+
pg_namespace name, pg_constraint cons
|
|
92
|
+
WHERE seq.oid = dep.objid
|
|
93
|
+
AND seq.relnamespace = name.oid
|
|
94
|
+
AND seq.relkind = 'S'
|
|
95
|
+
AND attr.attrelid = dep.refobjid
|
|
96
|
+
AND attr.attnum = dep.refobjsubid
|
|
97
|
+
AND attr.attrelid = cons.conrelid
|
|
98
|
+
AND attr.attnum = cons.conkey[1]
|
|
99
|
+
AND cons.contype = 'p'
|
|
100
|
+
#{"AND name.nspname = '#{schema}'" if schema}
|
|
101
|
+
AND seq.relname = '#{table}'
|
|
102
|
+
end_sql
|
|
103
|
+
end
|
|
104
|
+
|
|
105
|
+
# Depth of the current transaction on this connection, used
|
|
106
|
+
# to implement multi-level transactions with savepoints.
|
|
107
|
+
attr_accessor :transaction_depth
|
|
108
|
+
|
|
109
|
+
# Apply connection settings for this connection. Currently, turns
|
|
110
|
+
# standard_conforming_strings ON if Postgres.force_standard_strings
|
|
111
|
+
# is true.
|
|
112
|
+
def apply_connection_settings
|
|
113
|
+
if Postgres.force_standard_strings
|
|
114
|
+
sql = "SET standard_conforming_strings = ON"
|
|
115
|
+
@db.log_info(sql)
|
|
116
|
+
# This setting will only work on PostgreSQL 8.2 or greater
|
|
117
|
+
# and we don't know the server version at this point, so
|
|
118
|
+
# try it unconditionally and rescue any errors.
|
|
119
|
+
execute(sql) rescue nil
|
|
120
|
+
end
|
|
121
|
+
if cmm = Postgres.client_min_messages
|
|
122
|
+
sql = "SET client_min_messages = '#{cmm.to_s.upcase}'"
|
|
123
|
+
@db.log_info(sql)
|
|
124
|
+
execute(sql)
|
|
125
|
+
end
|
|
126
|
+
end
|
|
127
|
+
|
|
128
|
+
# Get the last inserted value for the given sequence.
|
|
129
|
+
def last_insert_id(sequence)
|
|
130
|
+
sql = SELECT_CURRVAL % sequence
|
|
131
|
+
@db.log_info(sql)
|
|
132
|
+
execute(sql) do |r|
|
|
133
|
+
val = single_value(r)
|
|
134
|
+
return val.to_i if val
|
|
135
|
+
end
|
|
136
|
+
end
|
|
137
|
+
|
|
138
|
+
# Get the primary key for the given table.
|
|
139
|
+
def primary_key(schema, table)
|
|
140
|
+
sql = SELECT_PK[schema, table]
|
|
141
|
+
@db.log_info(sql)
|
|
142
|
+
execute(sql) do |r|
|
|
143
|
+
return single_value(r)
|
|
144
|
+
end
|
|
145
|
+
end
|
|
146
|
+
|
|
147
|
+
# Get the primary key and sequence for the given table.
|
|
148
|
+
def sequence(schema, table)
|
|
149
|
+
sql = SELECT_SERIAL_SEQUENCE[schema, table]
|
|
150
|
+
@db.log_info(sql)
|
|
151
|
+
execute(sql) do |r|
|
|
152
|
+
seq = single_value(r)
|
|
153
|
+
return seq if seq
|
|
154
|
+
end
|
|
155
|
+
|
|
156
|
+
sql = SELECT_CUSTOM_SEQUENCE[schema, table]
|
|
157
|
+
@db.log_info(sql)
|
|
158
|
+
execute(sql) do |r|
|
|
159
|
+
return single_value(r)
|
|
160
|
+
end
|
|
161
|
+
end
|
|
162
|
+
end
|
|
163
|
+
|
|
164
|
+
# Methods shared by Database instances that connect to PostgreSQL.
|
|
165
|
+
module DatabaseMethods
|
|
166
|
+
PREPARED_ARG_PLACEHOLDER = LiteralString.new('$').freeze
|
|
167
|
+
RE_CURRVAL_ERROR = /currval of sequence "(.*)" is not yet defined in this session|relation "(.*)" does not exist/.freeze
|
|
168
|
+
SQL_BEGIN = 'BEGIN'.freeze
|
|
169
|
+
SQL_SAVEPOINT = 'SAVEPOINT autopoint_%d'.freeze
|
|
170
|
+
SQL_COMMIT = 'COMMIT'.freeze
|
|
171
|
+
SQL_ROLLBACK_TO_SAVEPOINT = 'ROLLBACK TO SAVEPOINT autopoint_%d'.freeze
|
|
172
|
+
SQL_ROLLBACK = 'ROLLBACK'.freeze
|
|
173
|
+
SQL_RELEASE_SAVEPOINT = 'RELEASE SAVEPOINT autopoint_%d'.freeze
|
|
174
|
+
SYSTEM_TABLE_REGEXP = /^pg|sql/.freeze
|
|
175
|
+
TYPES = Sequel::Database::TYPES.merge(File=>'bytea', String=>'text')
|
|
176
|
+
|
|
177
|
+
# Creates the function in the database. See create_function_sql for arguments.
|
|
178
|
+
def create_function(*args)
|
|
179
|
+
self << create_function_sql(*args)
|
|
180
|
+
end
|
|
181
|
+
|
|
182
|
+
# SQL statement to create database function. Arguments:
|
|
183
|
+
# * name : name of the function to create
|
|
184
|
+
# * definition : string definition of the function, or object file for a dynamically loaded C function.
|
|
185
|
+
# * opts : options hash:
|
|
186
|
+
# * :args : function arguments, can be either a symbol or string specifying a type or an array of 1-3 elements:
|
|
187
|
+
# * element 1 : argument data type
|
|
188
|
+
# * element 2 : argument name
|
|
189
|
+
# * element 3 : argument mode (e.g. in, out, inout)
|
|
190
|
+
# * :behavior : Should be IMMUTABLE, STABLE, or VOLATILE. PostgreSQL assumes VOLATILE by default.
|
|
191
|
+
# * :cost : The estimated cost of the function, used by the query planner.
|
|
192
|
+
# * :language : The language the function uses. SQL is the default.
|
|
193
|
+
# * :link_symbol : For a dynamically loaded see function, the function's link symbol if different from the definition argument.
|
|
194
|
+
# * :returns : The data type returned by the function. If you are using OUT or INOUT argument modes, this is ignored.
|
|
195
|
+
# Otherwise, if this is not specified, void is used by default to specify the function is not supposed to return a value.
|
|
196
|
+
# * :rows : The estimated number of rows the function will return. Only use if the function returns SETOF something.
|
|
197
|
+
# * :security_definer : Makes the privileges of the function the same as the privileges of the user who defined the function instead of
|
|
198
|
+
# the privileges of the user who runs the function. There are security implications when doing this, see the PostgreSQL documentation.
|
|
199
|
+
# * :set : Configuration variables to set while the function is being run, can be a hash or an array of two pairs. search_path is
|
|
200
|
+
# often used here if :security_definer is used.
|
|
201
|
+
# * :strict : Makes the function return NULL when any argument is NULL.
|
|
202
|
+
def create_function_sql(name, definition, opts={})
|
|
203
|
+
args = opts[:args]
|
|
204
|
+
if !opts[:args].is_a?(Array) || !opts[:args].any?{|a| Array(a).length == 3 and %w'OUT INOUT'.include?(a[2].to_s)}
|
|
205
|
+
returns = opts[:returns] || 'void'
|
|
206
|
+
end
|
|
207
|
+
language = opts[:language] || 'SQL'
|
|
208
|
+
<<-END
|
|
209
|
+
CREATE#{' OR REPLACE' if opts[:replace]} FUNCTION #{name}#{sql_function_args(args)}
|
|
210
|
+
#{"RETURNS #{returns}" if returns}
|
|
211
|
+
LANGUAGE #{language}
|
|
212
|
+
#{opts[:behavior].to_s.upcase if opts[:behavior]}
|
|
213
|
+
#{'STRICT' if opts[:strict]}
|
|
214
|
+
#{'SECURITY DEFINER' if opts[:security_definer]}
|
|
215
|
+
#{"COST #{opts[:cost]}" if opts[:cost]}
|
|
216
|
+
#{"ROWS #{opts[:rows]}" if opts[:rows]}
|
|
217
|
+
#{opts[:set].map{|k,v| " SET #{k} = #{v}"}.join("\n") if opts[:set]}
|
|
218
|
+
AS #{literal(definition.to_s)}#{", #{literal(opts[:link_symbol].to_s)}" if opts[:link_symbol]}
|
|
219
|
+
END
|
|
220
|
+
end
|
|
221
|
+
|
|
222
|
+
# Create the procedural language in the database. See create_language_sql for arguments.
|
|
223
|
+
def create_language(*args)
|
|
224
|
+
self << create_language_sql(*args)
|
|
225
|
+
end
|
|
226
|
+
|
|
227
|
+
# SQL for creating a procedural language. Arguments:
|
|
228
|
+
# * name : Name of the procedural language (e.g. plpgsql)
|
|
229
|
+
# * opts : options hash:
|
|
230
|
+
# * :handler : The name of a previously registered function used as a call handler for this language.
|
|
231
|
+
# * :trusted : Marks the language being created as trusted, allowing unprivileged users to create functions using this language.
|
|
232
|
+
# * :validator : The name of previously registered function used as a validator of functions defined in this language.
|
|
233
|
+
def create_language_sql(name, opts={})
|
|
234
|
+
"CREATE#{' TRUSTED' if opts[:trusted]} LANGUAGE #{name}#{" HANDLER #{opts[:handler]}" if opts[:handler]}#{" VALIDATOR #{opts[:validator]}" if opts[:validator]}"
|
|
235
|
+
end
|
|
236
|
+
|
|
237
|
+
# Create a trigger in the database. See create_trigger_sql for arguments.
|
|
238
|
+
def create_trigger(*args)
|
|
239
|
+
self << create_trigger_sql(*args)
|
|
240
|
+
end
|
|
241
|
+
|
|
242
|
+
# SQL for creating a database trigger. Arguments:
|
|
243
|
+
# * table : the table on which this trigger operates
|
|
244
|
+
# * name : the name of this trigger
|
|
245
|
+
# * function : the function to call for this trigger, which should return type trigger.
|
|
246
|
+
# * opts : options hash:
|
|
247
|
+
# * :after : Calls the trigger after execution instead of before.
|
|
248
|
+
# * :args : An argument or array of arguments to pass to the function.
|
|
249
|
+
# * :each_row : Calls the trigger for each row instead of for each statement.
|
|
250
|
+
# * :events : Can be :insert, :update, :delete, or an array of any of those. Calls the trigger whenever that type of statement is used. By default,
|
|
251
|
+
# the trigger is called for insert, update, or delete.
|
|
252
|
+
def create_trigger_sql(table, name, function, opts={})
|
|
253
|
+
events = opts[:events] ? Array(opts[:events]) : [:insert, :update, :delete]
|
|
254
|
+
whence = opts[:after] ? 'AFTER' : 'BEFORE'
|
|
255
|
+
"CREATE TRIGGER #{name} #{whence} #{events.map{|e| e.to_s.upcase}.join(' OR ')} ON #{quote_schema_table(table)}#{' FOR EACH ROW' if opts[:each_row]} EXECUTE PROCEDURE #{function}(#{Array(opts[:args]).map{|a| literal(a)}.join(', ')})"
|
|
256
|
+
end
|
|
257
|
+
|
|
258
|
+
# Drops the function from the database. See drop_function_sql for arguments.
|
|
259
|
+
def drop_function(*args)
|
|
260
|
+
self << drop_function_sql(*args)
|
|
261
|
+
end
|
|
262
|
+
|
|
263
|
+
# SQL for dropping a function from the database. Arguments:
|
|
264
|
+
# * name : name of the function to drop
|
|
265
|
+
# * opts : options hash:
|
|
266
|
+
# * :args : The arguments for the function. See create_function_sql.
|
|
267
|
+
# * :cascade : Drop other objects depending on this function.
|
|
268
|
+
# * :if_exists : Don't raise an error if the function doesn't exist.
|
|
269
|
+
def drop_function_sql(name, opts={})
|
|
270
|
+
"DROP FUNCTION#{' IF EXISTS' if opts[:if_exists]} #{name}#{sql_function_args(opts[:args])}#{' CASCADE' if opts[:cascade]}"
|
|
271
|
+
end
|
|
272
|
+
|
|
273
|
+
# Drops a procedural language from the database. See drop_language_sql for arguments.
|
|
274
|
+
def drop_language(*args)
|
|
275
|
+
self << drop_language_sql(*args)
|
|
276
|
+
end
|
|
277
|
+
|
|
278
|
+
# SQL for dropping a procedural language from the database. Arguments:
|
|
279
|
+
# * name : name of the procedural language to drop
|
|
280
|
+
# * opts : options hash:
|
|
281
|
+
# * :cascade : Drop other objects depending on this function.
|
|
282
|
+
# * :if_exists : Don't raise an error if the function doesn't exist.
|
|
283
|
+
def drop_language_sql(name, opts={})
|
|
284
|
+
"DROP LANGUAGE#{' IF EXISTS' if opts[:if_exists]} #{name}#{' CASCADE' if opts[:cascade]}"
|
|
285
|
+
end
|
|
286
|
+
|
|
287
|
+
# Remove the cached entries for primary keys and sequences when dropping a table.
|
|
288
|
+
def drop_table(*names)
|
|
289
|
+
names.each do |name|
|
|
290
|
+
name = quote_schema_table(name)
|
|
291
|
+
@primary_keys.delete(name)
|
|
292
|
+
@primary_key_sequences.delete(name)
|
|
293
|
+
end
|
|
294
|
+
super
|
|
295
|
+
end
|
|
296
|
+
|
|
297
|
+
# Always CASCADE the table drop
|
|
298
|
+
def drop_table_sql(name)
|
|
299
|
+
"DROP TABLE #{quote_schema_table(name)} CASCADE"
|
|
300
|
+
end
|
|
301
|
+
|
|
302
|
+
# Drops a trigger from the database. See drop_trigger_sql for arguments.
|
|
303
|
+
def drop_trigger(*args)
|
|
304
|
+
self << drop_trigger_sql(*args)
|
|
305
|
+
end
|
|
306
|
+
|
|
307
|
+
# SQL for dropping a trigger from the database. Arguments:
|
|
308
|
+
# * table : table from which to drop the trigger
|
|
309
|
+
# * name : name of the trigger to drop
|
|
310
|
+
# * opts : options hash:
|
|
311
|
+
# * :cascade : Drop other objects depending on this function.
|
|
312
|
+
# * :if_exists : Don't raise an error if the function doesn't exist.
|
|
313
|
+
def drop_trigger_sql(table, name, opts={})
|
|
314
|
+
"DROP TRIGGER#{' IF EXISTS' if opts[:if_exists]} #{name} ON #{quote_schema_table(table)}#{' CASCADE' if opts[:cascade]}"
|
|
315
|
+
end
|
|
316
|
+
|
|
317
|
+
# PostgreSQL specific index SQL.
|
|
318
|
+
def index_definition_sql(table_name, index)
|
|
319
|
+
index_name = index[:name] || default_index_name(table_name, index[:columns])
|
|
320
|
+
expr = literal(Array(index[:columns]))
|
|
321
|
+
unique = "UNIQUE " if index[:unique]
|
|
322
|
+
index_type = index[:type]
|
|
323
|
+
filter = index[:where] || index[:filter]
|
|
324
|
+
filter = " WHERE #{filter_expr(filter)}" if filter
|
|
325
|
+
case index_type
|
|
326
|
+
when :full_text
|
|
327
|
+
cols = Array(index[:columns]).map{|x| SQL::Function.new(:COALESCE, x, '')}.sql_string_join(' ')
|
|
328
|
+
expr = "(to_tsvector(#{literal(index[:language] || 'simple')}, #{literal(cols)}))"
|
|
329
|
+
index_type = :gin
|
|
330
|
+
when :spatial
|
|
331
|
+
index_type = :gist
|
|
332
|
+
end
|
|
333
|
+
"CREATE #{unique}INDEX #{quote_identifier(index_name)} ON #{quote_schema_table(table_name)} #{"USING #{index_type} " if index_type}#{expr}#{filter}"
|
|
334
|
+
end
|
|
335
|
+
|
|
336
|
+
# Dataset containing all current database locks
|
|
337
|
+
def locks
|
|
338
|
+
dataset.from(:pg_class).join(:pg_locks, :relation=>:relfilenode).select(:pg_class__relname, Sequel::SQL::ColumnAll.new(:pg_locks))
|
|
339
|
+
end
|
|
340
|
+
|
|
341
|
+
# Return primary key for the given table.
|
|
342
|
+
def primary_key(table, opts={})
|
|
343
|
+
quoted_table = quote_schema_table(table)
|
|
344
|
+
return @primary_keys[quoted_table] if @primary_keys.include?(quoted_table)
|
|
345
|
+
@primary_keys[quoted_table] = if conn = opts[:conn]
|
|
346
|
+
conn.primary_key(*schema_and_table(table))
|
|
347
|
+
else
|
|
348
|
+
synchronize(opts[:server]){|con| con.primary_key(*schema_and_table(table))}
|
|
349
|
+
end
|
|
350
|
+
end
|
|
351
|
+
|
|
352
|
+
# Return the sequence providing the default for the primary key for the given table.
|
|
353
|
+
def primary_key_sequence(table, opts={})
|
|
354
|
+
quoted_table = quote_schema_table(table)
|
|
355
|
+
return @primary_key_sequences[quoted_table] if @primary_key_sequences.include?(quoted_table)
|
|
356
|
+
@primary_key_sequences[quoted_table] = if conn = opts[:conn]
|
|
357
|
+
conn.sequence(*schema_and_table(table))
|
|
358
|
+
else
|
|
359
|
+
synchronize(opts[:server]){|con| con.sequence(*schema_and_table(table))}
|
|
360
|
+
end
|
|
361
|
+
end
|
|
362
|
+
|
|
363
|
+
# SQL DDL statement for renaming a table. PostgreSQL doesn't allow you to change a table's schema in
|
|
364
|
+
# a rename table operation, so speciying a new schema in new_name will not have an effect.
|
|
365
|
+
def rename_table_sql(name, new_name)
|
|
366
|
+
"ALTER TABLE #{quote_schema_table(name)} RENAME TO #{quote_identifier(schema_and_table(new_name).last)}"
|
|
367
|
+
end
|
|
368
|
+
|
|
369
|
+
# PostgreSQL uses SERIAL psuedo-type instead of AUTOINCREMENT for
|
|
370
|
+
# managing incrementing primary keys.
|
|
371
|
+
def serial_primary_key_options
|
|
372
|
+
{:primary_key => true, :type => :serial}
|
|
373
|
+
end
|
|
374
|
+
|
|
375
|
+
# The version of the PostgreSQL server, used for determining capability.
|
|
376
|
+
def server_version(server=nil)
|
|
377
|
+
return @server_version if @server_version
|
|
378
|
+
@server_version = synchronize(server) do |conn|
|
|
379
|
+
(conn.server_version rescue nil) if conn.respond_to?(:server_version)
|
|
380
|
+
end
|
|
381
|
+
unless @server_version
|
|
382
|
+
m = /PostgreSQL (\d+)\.(\d+)\.(\d+)/.match(get(SQL::Function.new(:version)))
|
|
383
|
+
@server_version = (m[1].to_i * 10000) + (m[2].to_i * 100) + m[3].to_i
|
|
384
|
+
end
|
|
385
|
+
@server_version
|
|
386
|
+
end
|
|
387
|
+
|
|
388
|
+
# Whether the given table exists in the database
|
|
389
|
+
#
|
|
390
|
+
# Options:
|
|
391
|
+
# * :schema - The schema to search (default_schema by default)
|
|
392
|
+
# * :server - The server to use
|
|
393
|
+
def table_exists?(table, opts={})
|
|
394
|
+
schema, table = schema_and_table(table)
|
|
395
|
+
opts[:schema] ||= schema
|
|
396
|
+
tables(opts){|ds| !ds.first(:relname=>ds.send(:input_identifier, table)).nil?}
|
|
397
|
+
end
|
|
398
|
+
|
|
399
|
+
# Array of symbols specifying table names in the current database.
|
|
400
|
+
# The dataset used is yielded to the block if one is provided,
|
|
401
|
+
# otherwise, an array of symbols of table names is returned.
|
|
402
|
+
#
|
|
403
|
+
# Options:
|
|
404
|
+
# * :schema - The schema to search (default_schema by default)
|
|
405
|
+
# * :server - The server to use
|
|
406
|
+
def tables(opts={})
|
|
407
|
+
ds = self[:pg_class].filter(:relkind=>'r').select(:relname).exclude(:relname.like(SYSTEM_TABLE_REGEXP)).server(opts[:server])
|
|
408
|
+
ds.join!(:pg_namespace, :oid=>:relnamespace, :nspname=>(opts[:schema]||default_schema).to_s) if opts[:schema] || default_schema
|
|
409
|
+
ds.identifier_input_method = nil
|
|
410
|
+
ds.identifier_output_method = nil
|
|
411
|
+
ds2 = dataset
|
|
412
|
+
block_given? ? yield(ds) : ds.map{|r| ds2.send(:output_identifier, r[:relname])}
|
|
413
|
+
end
|
|
414
|
+
|
|
415
|
+
# PostgreSQL supports multi-level transactions using save points.
|
|
416
|
+
# To use a savepoint instead of reusing the current transaction,
|
|
417
|
+
# use the :savepoint=>true option.
|
|
418
|
+
def transaction(opts={})
|
|
419
|
+
unless opts.is_a?(Hash)
|
|
420
|
+
Deprecation.deprecate('Passing an argument other than a Hash to Database#transaction', "Use DB.transaction(:server=>#{opts.inspect})")
|
|
421
|
+
opts = {:server=>opts}
|
|
422
|
+
end
|
|
423
|
+
synchronize(opts[:server]) do |conn|
|
|
424
|
+
return yield(conn) if @transactions.include?(Thread.current) and !opts[:savepoint]
|
|
425
|
+
conn.transaction_depth = 0 if conn.transaction_depth.nil?
|
|
426
|
+
if conn.transaction_depth > 0
|
|
427
|
+
log_info(SQL_SAVEPOINT % conn.transaction_depth)
|
|
428
|
+
conn.execute(SQL_SAVEPOINT % conn.transaction_depth)
|
|
429
|
+
else
|
|
430
|
+
log_info(SQL_BEGIN)
|
|
431
|
+
conn.execute(SQL_BEGIN)
|
|
432
|
+
end
|
|
433
|
+
begin
|
|
434
|
+
conn.transaction_depth += 1
|
|
435
|
+
@transactions << Thread.current
|
|
436
|
+
yield conn
|
|
437
|
+
rescue ::Exception => e
|
|
438
|
+
if conn.transaction_depth > 1
|
|
439
|
+
log_info(SQL_ROLLBACK_TO_SAVEPOINT % [conn.transaction_depth - 1])
|
|
440
|
+
conn.execute(SQL_ROLLBACK_TO_SAVEPOINT % [conn.transaction_depth - 1])
|
|
441
|
+
else
|
|
442
|
+
log_info(SQL_ROLLBACK)
|
|
443
|
+
conn.execute(SQL_ROLLBACK) rescue nil
|
|
444
|
+
end
|
|
445
|
+
transaction_error(e, *CONVERTED_EXCEPTIONS)
|
|
446
|
+
ensure
|
|
447
|
+
unless e
|
|
448
|
+
begin
|
|
449
|
+
if conn.transaction_depth < 2
|
|
450
|
+
log_info(SQL_COMMIT)
|
|
451
|
+
conn.execute(SQL_COMMIT)
|
|
452
|
+
@transactions.delete(Thread.current)
|
|
453
|
+
else
|
|
454
|
+
log_info(SQL_RELEASE_SAVEPOINT % [conn.transaction_depth - 1])
|
|
455
|
+
conn.execute(SQL_RELEASE_SAVEPOINT % [conn.transaction_depth - 1])
|
|
456
|
+
end
|
|
457
|
+
rescue => e
|
|
458
|
+
log_info(e.message)
|
|
459
|
+
raise_error(e, :classes=>CONVERTED_EXCEPTIONS)
|
|
460
|
+
end
|
|
461
|
+
end
|
|
462
|
+
conn.transaction_depth -= 1
|
|
463
|
+
end
|
|
464
|
+
end
|
|
465
|
+
end
|
|
466
|
+
|
|
467
|
+
private
|
|
468
|
+
|
|
469
|
+
# PostgreSQL folds unquoted identifiers to lowercase, so it shouldn't need to upcase identifiers on input.
|
|
470
|
+
def identifier_input_method_default
|
|
471
|
+
nil
|
|
472
|
+
end
|
|
473
|
+
|
|
474
|
+
# PostgreSQL folds unquoted identifiers to lowercase, so it shouldn't need to upcase identifiers on output.
|
|
475
|
+
def identifier_output_method_default
|
|
476
|
+
nil
|
|
477
|
+
end
|
|
478
|
+
|
|
479
|
+
# The result of the insert for the given table and values. If values
|
|
480
|
+
# is an array, assume the first column is the primary key and return
|
|
481
|
+
# that. If values is a hash, lookup the primary key for the table. If
|
|
482
|
+
# the primary key is present in the hash, return its value. Otherwise,
|
|
483
|
+
# look up the sequence for the table's primary key. If one exists,
|
|
484
|
+
# return the last value the of the sequence for the connection.
|
|
485
|
+
def insert_result(conn, table, values)
|
|
486
|
+
case values
|
|
487
|
+
when Hash
|
|
488
|
+
return nil unless pk = primary_key(table, :conn=>conn)
|
|
489
|
+
if pk and pkv = values[pk.to_sym]
|
|
490
|
+
pkv
|
|
491
|
+
else
|
|
492
|
+
begin
|
|
493
|
+
if seq = primary_key_sequence(table, :conn=>conn)
|
|
494
|
+
conn.last_insert_id(seq)
|
|
495
|
+
end
|
|
496
|
+
rescue Exception => e
|
|
497
|
+
raise_error(e, :classes=>CONVERTED_EXCEPTIONS) unless RE_CURRVAL_ERROR.match(e.message)
|
|
498
|
+
end
|
|
499
|
+
end
|
|
500
|
+
when Array
|
|
501
|
+
values.first
|
|
502
|
+
else
|
|
503
|
+
nil
|
|
504
|
+
end
|
|
505
|
+
end
|
|
506
|
+
|
|
507
|
+
# Use a dollar sign instead of question mark for the argument
|
|
508
|
+
# placeholder.
|
|
509
|
+
def prepared_arg_placeholder
|
|
510
|
+
PREPARED_ARG_PLACEHOLDER
|
|
511
|
+
end
|
|
512
|
+
|
|
513
|
+
# The dataset used for parsing table schemas, using the pg_* system catalogs.
|
|
514
|
+
def schema_parse_table(table_name, opts)
|
|
515
|
+
ds2 = dataset
|
|
516
|
+
ds = dataset.select(:pg_attribute__attname___name,
|
|
517
|
+
SQL::Function.new(:format_type, :pg_type__oid, :pg_attribute__atttypmod).as(:db_type),
|
|
518
|
+
SQL::Function.new(:pg_get_expr, :pg_attrdef__adbin, :pg_class__oid).as(:default),
|
|
519
|
+
SQL::BooleanExpression.new(:NOT, :pg_attribute__attnotnull).as(:allow_null),
|
|
520
|
+
SQL::Function.new(:COALESCE, {:pg_attribute__attnum => SQL::Function.new(:ANY, :pg_index__indkey)}.sql_expr, false).as(:primary_key)).
|
|
521
|
+
from(:pg_class).
|
|
522
|
+
join(:pg_attribute, :attrelid=>:oid).
|
|
523
|
+
join(:pg_type, :oid=>:atttypid).
|
|
524
|
+
left_outer_join(:pg_attrdef, :adrelid=>:pg_class__oid, :adnum=>:pg_attribute__attnum).
|
|
525
|
+
left_outer_join(:pg_index, :indrelid=>:pg_class__oid, :indisprimary=>true).
|
|
526
|
+
filter(:pg_attribute__attisdropped=>false).
|
|
527
|
+
filter{|o| o.pg_attribute__attnum > 0}.
|
|
528
|
+
filter(:pg_class__relname=>ds2.send(:input_identifier, table_name)).
|
|
529
|
+
order(:pg_attribute__attnum)
|
|
530
|
+
ds.join!(:pg_namespace, :oid=>:pg_class__relnamespace, :nspname=>(opts[:schema] || default_schema).to_s) if opts[:schema] || default_schema
|
|
531
|
+
ds.identifier_input_method = nil
|
|
532
|
+
ds.identifier_output_method = nil
|
|
533
|
+
ds.map do |row|
|
|
534
|
+
row[:default] = nil if blank_object?(row[:default])
|
|
535
|
+
row[:type] = schema_column_type(row[:db_type])
|
|
536
|
+
[ds2.send(:output_identifier, row.delete(:name)), row]
|
|
537
|
+
end
|
|
538
|
+
end
|
|
539
|
+
|
|
540
|
+
# Turns an array of argument specifiers into an SQL fragment used for function arguments. See create_function_sql.
|
|
541
|
+
def sql_function_args(args)
|
|
542
|
+
"(#{Array(args).map{|a| Array(a).reverse.join(' ')}.join(', ')})"
|
|
543
|
+
end
|
|
544
|
+
|
|
545
|
+
# Override the standard type conversions with PostgreSQL specific ones
|
|
546
|
+
def type_literal_base(column)
|
|
547
|
+
TYPES[column[:type]]
|
|
548
|
+
end
|
|
549
|
+
end
|
|
550
|
+
|
|
551
|
+
# Instance methods for datasets that connect to a PostgreSQL database.
|
|
552
|
+
module DatasetMethods
|
|
553
|
+
ACCESS_SHARE = 'ACCESS SHARE'.freeze
|
|
554
|
+
ACCESS_EXCLUSIVE = 'ACCESS EXCLUSIVE'.freeze
|
|
555
|
+
BOOL_FALSE = 'false'.freeze
|
|
556
|
+
BOOL_TRUE = 'true'.freeze
|
|
557
|
+
COMMA_SEPARATOR = ', '.freeze
|
|
558
|
+
EXCLUSIVE = 'EXCLUSIVE'.freeze
|
|
559
|
+
EXPLAIN = 'EXPLAIN '.freeze
|
|
560
|
+
EXPLAIN_ANALYZE = 'EXPLAIN ANALYZE '.freeze
|
|
561
|
+
FOR_SHARE = ' FOR SHARE'.freeze
|
|
562
|
+
FOR_UPDATE = ' FOR UPDATE'.freeze
|
|
563
|
+
LOCK = 'LOCK TABLE %s IN %s MODE'.freeze
|
|
564
|
+
NULL = LiteralString.new('NULL').freeze
|
|
565
|
+
PG_TIMESTAMP_FORMAT = "TIMESTAMP '%Y-%m-%d %H:%M:%S".freeze
|
|
566
|
+
QUERY_PLAN = 'QUERY PLAN'.to_sym
|
|
567
|
+
ROW_EXCLUSIVE = 'ROW EXCLUSIVE'.freeze
|
|
568
|
+
ROW_SHARE = 'ROW SHARE'.freeze
|
|
569
|
+
SELECT_CLAUSE_ORDER = %w'distinct columns from join where group having compounds order limit lock'.freeze
|
|
570
|
+
SHARE = 'SHARE'.freeze
|
|
571
|
+
SHARE_ROW_EXCLUSIVE = 'SHARE ROW EXCLUSIVE'.freeze
|
|
572
|
+
SHARE_UPDATE_EXCLUSIVE = 'SHARE UPDATE EXCLUSIVE'.freeze
|
|
573
|
+
|
|
574
|
+
# Shared methods for prepared statements when used with PostgreSQL databases.
|
|
575
|
+
module PreparedStatementMethods
|
|
576
|
+
# Override insert action to use RETURNING if the server supports it.
|
|
577
|
+
def prepared_sql
|
|
578
|
+
return @prepared_sql if @prepared_sql
|
|
579
|
+
super
|
|
580
|
+
if @prepared_type == :insert and !@opts[:disable_insert_returning] and server_version >= 80200
|
|
581
|
+
@prepared_sql = insert_returning_pk_sql(@prepared_modify_values)
|
|
582
|
+
meta_def(:insert_returning_pk_sql){|*args| prepared_sql}
|
|
583
|
+
end
|
|
584
|
+
@prepared_sql
|
|
585
|
+
end
|
|
586
|
+
end
|
|
587
|
+
|
|
588
|
+
# Add the disable_insert_returning! mutation method
|
|
589
|
+
def self.extended(obj)
|
|
590
|
+
obj.def_mutation_method(:disable_insert_returning)
|
|
591
|
+
end
|
|
592
|
+
|
|
593
|
+
# Add the disable_insert_returning! mutation method
|
|
594
|
+
def self.included(mod)
|
|
595
|
+
mod.def_mutation_method(:disable_insert_returning)
|
|
596
|
+
end
|
|
597
|
+
|
|
598
|
+
# Return the results of an ANALYZE query as a string
|
|
599
|
+
def analyze(opts = nil)
|
|
600
|
+
analysis = []
|
|
601
|
+
fetch_rows(EXPLAIN_ANALYZE + select_sql(opts)) do |r|
|
|
602
|
+
analysis << r[QUERY_PLAN]
|
|
603
|
+
end
|
|
604
|
+
analysis.join("\r\n")
|
|
605
|
+
end
|
|
606
|
+
|
|
607
|
+
# Disable the use of INSERT RETURNING, even if the server supports it
|
|
608
|
+
def disable_insert_returning
|
|
609
|
+
clone(:disable_insert_returning=>true)
|
|
610
|
+
end
|
|
611
|
+
|
|
612
|
+
# Return the results of an EXPLAIN query as a string
|
|
613
|
+
def explain(opts = nil)
|
|
614
|
+
analysis = []
|
|
615
|
+
fetch_rows(EXPLAIN + select_sql(opts)) do |r|
|
|
616
|
+
analysis << r[QUERY_PLAN]
|
|
617
|
+
end
|
|
618
|
+
analysis.join("\r\n")
|
|
619
|
+
end
|
|
620
|
+
|
|
621
|
+
# Return a cloned dataset with a :share lock type.
|
|
622
|
+
def for_share
|
|
623
|
+
clone(:lock => :share)
|
|
624
|
+
end
|
|
625
|
+
|
|
626
|
+
# Return a cloned dataset with a :update lock type.
|
|
627
|
+
def for_update
|
|
628
|
+
clone(:lock => :update)
|
|
629
|
+
end
|
|
630
|
+
|
|
631
|
+
# PostgreSQL specific full text search syntax, using tsearch2 (included
|
|
632
|
+
# in 8.3 by default, and available for earlier versions as an add-on).
|
|
633
|
+
def full_text_search(cols, terms, opts = {})
|
|
634
|
+
lang = opts[:language] || 'simple'
|
|
635
|
+
cols = Array(cols).map{|x| SQL::Function.new(:COALESCE, x, '')}.sql_string_join(' ')
|
|
636
|
+
filter("to_tsvector(#{literal(lang)}, #{literal(cols)}) @@ to_tsquery(#{literal(lang)}, #{literal(Array(terms).join(' | '))})")
|
|
637
|
+
end
|
|
638
|
+
|
|
639
|
+
# Insert given values into the database.
|
|
640
|
+
def insert(*values)
|
|
641
|
+
if !@opts[:sql] and !@opts[:disable_insert_returning] and server_version >= 80200
|
|
642
|
+
clone(default_server_opts(:sql=>insert_returning_pk_sql(*values))).single_value
|
|
643
|
+
else
|
|
644
|
+
execute_insert(insert_sql(*values), :table=>opts[:from].first,
|
|
645
|
+
:values=>values.size == 1 ? values.first : values)
|
|
646
|
+
end
|
|
647
|
+
end
|
|
648
|
+
|
|
649
|
+
# Use the RETURNING clause to return the columns listed in returning.
|
|
650
|
+
def insert_returning_sql(returning, *values)
|
|
651
|
+
"#{insert_sql(*values)} RETURNING #{column_list(Array(returning))}"
|
|
652
|
+
end
|
|
653
|
+
|
|
654
|
+
# Insert a record returning the record inserted
|
|
655
|
+
def insert_select(*values)
|
|
656
|
+
naked.clone(default_server_opts(:sql=>insert_returning_sql(nil, *values))).single_record if server_version >= 80200
|
|
657
|
+
end
|
|
658
|
+
|
|
659
|
+
# Locks the table with the specified mode.
|
|
660
|
+
def lock(mode, server=nil)
|
|
661
|
+
sql = LOCK % [source_list(@opts[:from]), mode]
|
|
662
|
+
@db.synchronize(server) do
|
|
663
|
+
if block_given? # perform locking inside a transaction and yield to block
|
|
664
|
+
@db.transaction(server){@db.execute(sql, :server=>server); yield}
|
|
665
|
+
else
|
|
666
|
+
@db.execute(sql, :server=>server) # lock without a transaction
|
|
667
|
+
self
|
|
668
|
+
end
|
|
669
|
+
end
|
|
670
|
+
end
|
|
671
|
+
|
|
672
|
+
# For PostgreSQL version > 8.2, allow inserting multiple rows at once.
|
|
673
|
+
def multi_insert_sql(columns, values)
|
|
674
|
+
return super if server_version < 80200
|
|
675
|
+
|
|
676
|
+
# postgresql 8.2 introduces support for multi-row insert
|
|
677
|
+
values = values.map {|r| literal(Array(r))}.join(COMMA_SEPARATOR)
|
|
678
|
+
["INSERT INTO #{source_list(@opts[:from])} (#{identifier_list(columns)}) VALUES #{values}"]
|
|
679
|
+
end
|
|
680
|
+
|
|
681
|
+
private
|
|
682
|
+
|
|
683
|
+
# Use the RETURNING clause to return the primary key of the inserted record, if it exists
|
|
684
|
+
def insert_returning_pk_sql(*values)
|
|
685
|
+
pk = db.primary_key(opts[:from].first)
|
|
686
|
+
insert_returning_sql(pk ? Sequel::SQL::Identifier.new(pk) : NULL, *values)
|
|
687
|
+
end
|
|
688
|
+
|
|
689
|
+
def literal_blob(v)
|
|
690
|
+
"'#{v.gsub(/[\000-\037\047\134\177-\377]/){|b| "\\#{("%o" % b[0..1].unpack("C")[0]).rjust(3, '0')}"}}'"
|
|
691
|
+
end
|
|
692
|
+
|
|
693
|
+
def literal_datetime(v)
|
|
694
|
+
"#{v.strftime(PG_TIMESTAMP_FORMAT)}.#{sprintf("%06d", (v.sec_fraction * 86400000000).to_i)}'"
|
|
695
|
+
end
|
|
696
|
+
|
|
697
|
+
def literal_false
|
|
698
|
+
BOOL_FALSE
|
|
699
|
+
end
|
|
700
|
+
|
|
701
|
+
def literal_string(v)
|
|
702
|
+
"'#{v.gsub("'", "''")}'"
|
|
703
|
+
end
|
|
704
|
+
|
|
705
|
+
def literal_true
|
|
706
|
+
BOOL_TRUE
|
|
707
|
+
end
|
|
708
|
+
|
|
709
|
+
def literal_time(v)
|
|
710
|
+
"#{v.strftime(PG_TIMESTAMP_FORMAT)}.#{sprintf("%06d",v.usec)}'"
|
|
711
|
+
end
|
|
712
|
+
|
|
713
|
+
# PostgreSQL is smart and can use parantheses around all datasets to get
|
|
714
|
+
# the correct answers.
|
|
715
|
+
def select_compounds_sql(sql, opts)
|
|
716
|
+
return unless opts[:compounds]
|
|
717
|
+
opts[:compounds].each do |type, dataset, all|
|
|
718
|
+
sql.replace("(#{sql} #{type.to_s.upcase}#{' ALL' if all} #{subselect_sql(dataset)})")
|
|
719
|
+
end
|
|
720
|
+
end
|
|
721
|
+
|
|
722
|
+
# The order of clauses in the SELECT SQL statement
|
|
723
|
+
def select_clause_order
|
|
724
|
+
SELECT_CLAUSE_ORDER
|
|
725
|
+
end
|
|
726
|
+
|
|
727
|
+
# Support lock mode, allowing FOR SHARE and FOR UPDATE queries.
|
|
728
|
+
def select_lock_sql(sql, opts)
|
|
729
|
+
case opts[:lock]
|
|
730
|
+
when :update
|
|
731
|
+
sql << FOR_UPDATE
|
|
732
|
+
when :share
|
|
733
|
+
sql << FOR_SHARE
|
|
734
|
+
end
|
|
735
|
+
end
|
|
736
|
+
|
|
737
|
+
# The version of the database server
|
|
738
|
+
def server_version
|
|
739
|
+
db.server_version(@opts[:server])
|
|
740
|
+
end
|
|
741
|
+
end
|
|
742
|
+
end
|
|
743
|
+
end
|