1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290
|
# frozen-string-literal: true
require_relative '../utils/emulate_offset_with_reverse_and_count'
require_relative '../utils/unmodified_identifiers'
module Sequel
module Access
Sequel::Database.set_shared_adapter_scheme(:access, self)
module DatabaseMethods
include UnmodifiedIdentifiers::DatabaseMethods
def database_type
:access
end
# Doesn't work, due to security restrictions on MSysObjects
#def tables
# from(:MSysObjects).where(:Type=>1, :Flags=>0).select_map(:Name).map(&:to_sym)
#end
# Access doesn't support renaming tables from an SQL query,
# so create a copy of the table and then drop the from table.
def rename_table(from_table, to_table)
create_table(to_table, :as=>from(from_table))
drop_table(from_table)
end
# Access uses type Counter for an autoincrementing keys
def serial_primary_key_options
{:primary_key => true, :type=>:Counter}
end
private
def alter_table_set_column_type_sql(table, op)
"ALTER COLUMN #{quote_identifier(op[:name])} #{type_literal(op)}"
end
# Access doesn't support CREATE TABLE AS, it only supports SELECT INTO.
# Emulating CREATE TABLE AS using SELECT INTO is only possible if a dataset
# is given as the argument, it can't work with a string, so raise an
# Error if a string is given.
def create_table_as(name, ds, options)
raise(Error, "must provide dataset instance as value of create_table :as option on Access") unless ds.is_a?(Sequel::Dataset)
run(ds.into(name).sql)
end
DATABASE_ERROR_REGEXPS = {
/The changes you requested to the table were not successful because they would create duplicate values in the index, primary key, or relationship/ => UniqueConstraintViolation,
/You cannot add or change a record because a related record is required|The record cannot be deleted or changed because table/ => ForeignKeyConstraintViolation,
/One or more values are prohibited by the validation rule/ => CheckConstraintViolation,
/You must enter a value in the .+ field|cannot contain a Null value because the Required property for this field is set to True/ => NotNullConstraintViolation,
}.freeze
def database_error_regexps
DATABASE_ERROR_REGEXPS
end
def drop_index_sql(table, op)
"DROP INDEX #{quote_identifier(op[:name] || default_index_name(table, op[:columns]))} ON #{quote_schema_table(table)}"
end
# Access doesn't have a 64-bit integer type, so use integer and hope
# the user isn't using more than 32 bits.
def type_literal_generic_bignum_symbol(column)
:integer
end
# Access doesn't have a true boolean class, so it uses bit
def type_literal_generic_trueclass(column)
:bit
end
# Access uses image type for blobs
def type_literal_generic_file(column)
:image
end
end
module DatasetMethods
include(Module.new do
Dataset.def_sql_method(self, :select, %w'select distinct limit columns into from join where group order having compounds')
end)
include EmulateOffsetWithReverseAndCount
include UnmodifiedIdentifiers::DatasetMethods
EXTRACT_MAP = {:year=>"'yyyy'", :month=>"'m'", :day=>"'d'", :hour=>"'h'", :minute=>"'n'", :second=>"'s'"}.freeze
EXTRACT_MAP.each_value(&:freeze)
OPS = {:'%'=>' Mod '.freeze, :'||'=>' & '.freeze}.freeze
CAST_TYPES = {String=>:CStr, Integer=>:CLng, Date=>:CDate, Time=>:CDate, DateTime=>:CDate, Numeric=>:CDec, BigDecimal=>:CDec, File=>:CStr, Float=>:CDbl, TrueClass=>:CBool, FalseClass=>:CBool}.freeze
# Access doesn't support CASE, so emulate it with nested IIF function calls.
def case_expression_sql_append(sql, ce)
literal_append(sql, ce.with_merged_expression.conditions.reverse.inject(ce.default){|exp,(cond,val)| Sequel::SQL::Function.new(:IIF, cond, val, exp)})
end
# Access doesn't support CAST, it uses separate functions for
# type conversion
def cast_sql_append(sql, expr, type)
sql << CAST_TYPES.fetch(type, type).to_s
sql << '('
literal_append(sql, expr)
sql << ')'
end
def complex_expression_sql_append(sql, op, args)
case op
when :ILIKE
complex_expression_sql_append(sql, :LIKE, args)
when :'NOT ILIKE'
complex_expression_sql_append(sql, :'NOT LIKE', args)
when :'!='
sql << '('
literal_append(sql, args[0])
sql << ' <> '
literal_append(sql, args[1])
sql << ')'
when :'%', :'||'
sql << '('
c = false
op_str = OPS[op]
args.each do |a|
sql << op_str if c
literal_append(sql, a)
c ||= true
end
sql << ')'
when :**
sql << '('
literal_append(sql, args[0])
sql << ' ^ '
literal_append(sql, args[1])
sql << ')'
when :extract
part = args[0]
raise(Sequel::Error, "unsupported extract argument: #{part.inspect}") unless format = EXTRACT_MAP[part]
sql << "datepart(" << format.to_s << ', '
literal_append(sql, args[1])
sql << ')'
else
super
end
end
# Use Date(), Now(), and Time() for CURRENT_DATE, CURRENT_TIMESTAMP, and CURRENT_TIME
def constant_sql_append(sql, constant)
case constant
when :CURRENT_DATE
sql << 'Date()'
when :CURRENT_TIMESTAMP
sql << 'Now()'
when :CURRENT_TIME
sql << 'Time()'
else
super
end
end
# Emulate cross join by using multiple tables in the FROM clause.
def cross_join(table)
clone(:from=>@opts[:from] + [table])
end
# Access uses [] to escape metacharacters, instead of backslashes.
def escape_like(string)
string.gsub(/[\\*#?\[]/){|m| "[#{m}]"}
end
# Specify a table for a SELECT ... INTO query.
def into(table)
clone(:into => table)
end
# Access uses [] for quoting identifiers, and can't handle
# ] inside identifiers.
def quoted_identifier_append(sql, v)
sql << '[' << v.to_s << ']'
end
# Access does not support derived column lists.
def supports_derived_column_lists?
false
end
# Access doesn't support INTERSECT or EXCEPT
def supports_intersect_except?
false
end
# Access does not support IS TRUE
def supports_is_true?
false
end
# Access doesn't support JOIN USING
def supports_join_using?
false
end
# Access does not support multiple columns for the IN/NOT IN operators
def supports_multiple_column_in?
false
end
# Access doesn't support truncate, so do a delete instead.
def truncate
delete
nil
end
private
# Access uses # to quote dates
def literal_date(d)
d.strftime('#%Y-%m-%d#')
end
# Access uses # to quote datetimes
def literal_datetime(t)
t.strftime('#%Y-%m-%d %H:%M:%S#')
end
alias literal_time literal_datetime
# Use 0 for false on MSSQL
def literal_false
'0'
end
# Use -1 for true on MSSQL
def literal_true
'-1'
end
# Emulate the char_length function with len
def native_function_name(emulated_function)
if emulated_function == :char_length
'len'
else
super
end
end
# Access does not natively support NULLS FIRST/LAST.
def requires_emulating_nulls_first?
true
end
# Access doesn't support ESCAPE for LIKE.
def requires_like_escape?
false
end
# Access requires parentheses when joining more than one table
def select_from_sql(sql)
if f = @opts[:from]
sql << ' FROM '
if (j = @opts[:join]) && !j.empty?
sql << ('(' * j.length)
end
source_list_append(sql, f)
end
end
def select_into_sql(sql)
if i = @opts[:into]
sql << " INTO "
identifier_append(sql, i)
end
end
# Access requires parentheses when joining more than one table
def select_join_sql(sql)
if js = @opts[:join]
js.each do |j|
literal_append(sql, j)
sql << ')'
end
end
end
# Access uses TOP for limits
def select_limit_sql(sql)
if l = @opts[:limit]
sql << " TOP "
literal_append(sql, l)
end
end
end
end
end
|