repo stringlengths 5 92 | file_url stringlengths 80 287 | file_path stringlengths 5 197 | content stringlengths 0 32.8k | language stringclasses 1
value | license stringclasses 7
values | commit_sha stringlengths 40 40 | retrieved_at stringdate 2026-01-04 15:37:27 2026-01-04 17:58:21 | truncated bool 2
classes |
|---|---|---|---|---|---|---|---|---|
pat/riddle | https://github.com/pat/riddle/blob/748ca04d14a9c04b7a5f2d64dbcd4897c1ab3f43/lib/riddle/configuration/section.rb | lib/riddle/configuration/section.rb | # frozen_string_literal: true
module Riddle
class Configuration
class Section
def self.settings
[]
end
def valid?
true
end
private
def settings_body
settings.select { |setting|
!send(setting).nil?
}.collect { |setting|
if send(setting) == ""
conf = " #{setting} = "
else
conf = setting_to_array(setting).collect { |set|
" #{setting} = #{rendered_setting set}"
}
end
conf.length == 0 ? nil : conf
}.flatten.compact
end
def setting_to_array(setting)
value = send(setting)
case value
when Array then value
when TrueClass then [1]
when FalseClass then [0]
else
[value]
end
end
def rendered_setting(setting)
return setting unless setting.is_a?(String)
index = 8100
output = String.new(setting)
while index < output.length
output.insert(index, "\\\n")
index += 8100
end
output
end
def settings
self.class.settings
end
end
end
end
| ruby | MIT | 748ca04d14a9c04b7a5f2d64dbcd4897c1ab3f43 | 2026-01-04T17:45:28.600554Z | false |
pat/riddle | https://github.com/pat/riddle/blob/748ca04d14a9c04b7a5f2d64dbcd4897c1ab3f43/lib/riddle/configuration/parser.rb | lib/riddle/configuration/parser.rb | # encoding: UTF-8
# frozen_string_literal: true
require 'stringio'
class Riddle::Configuration::Parser
SOURCE_CLASSES = {
'mysql' => Riddle::Configuration::SQLSource,
'pgsql' => Riddle::Configuration::SQLSource,
'mssql' => Riddle::Configuration::SQLSource,
'xmlpipe' => Riddle::Configuration::XMLSource,
'xmlpipe2' => Riddle::Configuration::XMLSource,
'odbc' => Riddle::Configuration::SQLSource,
'tsvpipe' => Riddle::Configuration::TSVSource
}
INDEX_CLASSES = {
'plain' => Riddle::Configuration::Index,
'distributed' => Riddle::Configuration::DistributedIndex,
'rt' => Riddle::Configuration::RealtimeIndex,
'template' => Riddle::Configuration::TemplateIndex
}
def initialize(input)
@input = input
end
def parse!
set_common
set_indexer
set_searchd
set_sources
set_indices
add_orphan_sources
configuration
end
private
def add_orphan_sources
all_names = sources.keys
attached_names = configuration.indices.collect { |index|
index.respond_to?(:sources) ? index.sources.collect(&:name) : []
}.flatten
(all_names - attached_names).each do |name|
configuration.sources << sources[name]
end
end
def inner
@inner ||= InnerParser.new(@input).parse!
end
def configuration
@configuration ||= Riddle::Configuration.new
end
def sources
@sources ||= {}
end
def each_with_prefix(prefix)
inner.keys.select { |key| key[/^#{prefix}\s+/] }.each do |key|
yield key.gsub(/^#{prefix}\s+/, '').gsub(/\s*\{$/, ''), inner[key]
end
end
def set_common
if inner['common'] && inner['common'].values.compact.any?
configuration.common.common_sphinx_configuration = true
end
set_settings configuration.common, inner['common'] || {}
end
def set_indexer
set_settings configuration.indexer, inner['indexer'] || {}
end
def set_searchd
set_settings configuration.searchd, inner['searchd'] || {}
end
def set_sources
each_with_prefix 'source' do |name, settings|
names = name.split(/\s*:\s*/)
types = settings.delete('type')
parent = names.length > 1 ? names.last : nil
types ||= [sources[parent].type] if parent
type = types.first
source = SOURCE_CLASSES[type].new names.first, type
source.parent = parent
set_settings source, settings
sources[source.name] = source
end
end
def set_indices
each_with_prefix 'index' do |name, settings|
names = name.split(/\s*:\s*/)
type = (settings.delete('type') || ['plain']).first
index = INDEX_CLASSES[type].new names.first
index.parent = names.last if names.length > 1
(settings.delete('source') || []).each do |source_name|
index.sources << sources[source_name]
end
set_settings index, settings
configuration.indices << index
end
end
def set_settings(object, hash)
hash.each do |key, values|
values.each do |value|
set_setting object, key, value
end
end
end
def set_setting(object, key, value)
if object.send(key).is_a?(Array)
object.send(key) << value
else
object.send "#{key}=", value
end
end
class InnerParser
SETTING_PATTERN = /^(\w+)\s*=\s*(.*)$/
EndOfFileError = Class.new StandardError
def initialize(input)
@stream = StringIO.new(input.gsub("\\\n", ''))
@sections = {}
end
def parse!
while label = next_line do
@sections[label] = next_settings
end
@sections
rescue EndOfFileError
@sections
end
private
def next_line
line = @stream.gets
raise EndOfFileError if line.nil?
line = line.strip
(line.empty? || line[/^#/]) ? next_line : line
end
def next_settings
settings = Hash.new { |hash, key| hash[key] = [] }
line = ''
while line.empty? || line == '{' do
line = next_line
end
while line != '}' do
begin
match = SETTING_PATTERN.match(line)
unless match.nil?
key, value = *match.captures
settings[key] << value
while value[/\\$/] do
value = next_line
settings[key].last << "\n" << value
end
end
rescue => error
raise error, "Error handling line '#{line}': #{error.message}",
error.backtrace
end
line = next_line
end
settings
end
end
end
| ruby | MIT | 748ca04d14a9c04b7a5f2d64dbcd4897c1ab3f43 | 2026-01-04T17:45:28.600554Z | false |
pat/riddle | https://github.com/pat/riddle/blob/748ca04d14a9c04b7a5f2d64dbcd4897c1ab3f43/lib/riddle/configuration/remote_index.rb | lib/riddle/configuration/remote_index.rb | # frozen_string_literal: true
module Riddle
class Configuration
class RemoteIndex
attr_accessor :address, :port, :name
def initialize(address, port, name)
@address = address
@port = port
@name = name
end
def remote
"#{address}:#{port}"
end
end
end
end | ruby | MIT | 748ca04d14a9c04b7a5f2d64dbcd4897c1ab3f43 | 2026-01-04T17:45:28.600554Z | false |
pat/riddle | https://github.com/pat/riddle/blob/748ca04d14a9c04b7a5f2d64dbcd4897c1ab3f43/lib/riddle/configuration/searchd.rb | lib/riddle/configuration/searchd.rb | # frozen_string_literal: true
module Riddle
class Configuration
class Searchd < Riddle::Configuration::Section
def self.settings
[
:listen, :address, :port, :log, :query_log,
:query_log_format, :read_timeout, :client_timeout, :max_children,
:pid_file, :max_matches, :seamless_rotate, :preopen_indexes,
:unlink_old, :attr_flush_period, :ondisk_dict_default,
:max_packet_size, :mva_updates_pool, :crash_log_path, :max_filters,
:max_filter_values, :listen_backlog, :read_buffer, :read_unhinted,
:max_batch_queries, :subtree_docs_cache, :subtree_hits_cache,
:workers, :dist_threads, :binlog_path, :binlog_flush,
:binlog_max_log_size, :snippets_file_prefix, :collation_server,
:collation_libc_locale, :mysql_version_string,
:rt_flush_period, :thread_stack, :expansion_limit,
:compat_sphinxql_magics, :watchdog, :prefork_rotation_throttle,
:sphinxql_state, :ha_ping_interval, :ha_period_karma,
:persistent_connections_limit, :rt_merge_iops, :rt_merge_maxiosize,
:predicted_time_costs, :snippets_file_prefix, :shutdown_timeout,
:ondisk_attrs_default, :query_log_min_msec, :agent_connect_timeout,
:agent_query_timeout, :agent_retry_count, :agenty_retry_delay,
:client_key
]
end
attr_accessor *self.settings
attr_accessor :mysql41, :socket
def render
raise ConfigurationError unless valid?
(
["searchd", "{"] +
settings_body +
["}", ""]
).join("\n")
end
def valid?
!( @port.nil? || @pid_file.nil? )
end
end
end
end
| ruby | MIT | 748ca04d14a9c04b7a5f2d64dbcd4897c1ab3f43 | 2026-01-04T17:45:28.600554Z | false |
pat/riddle | https://github.com/pat/riddle/blob/748ca04d14a9c04b7a5f2d64dbcd4897c1ab3f43/lib/riddle/configuration/index_settings.rb | lib/riddle/configuration/index_settings.rb | # frozen_string_literal: true
module Riddle
class Configuration
module IndexSettings
def self.settings
[
:type, :path, :docinfo, :mlock, :morphology,
:dict, :index_sp, :index_zones, :min_stemming_len, :stopwords,
:wordforms, :exceptions, :min_word_len, :charset_dictpath,
:charset_type, :charset_table, :ignore_chars, :min_prefix_len,
:min_infix_len, :prefix_fields, :infix_fields, :enable_star,
:expand_keywords, :ngram_len, :ngram_chars, :phrase_boundary,
:phrase_boundary_step, :blend_chars, :blend_mode, :html_strip,
:html_index_attrs, :html_remove_elements, :preopen, :ondisk_dict,
:inplace_enable, :inplace_hit_gap, :inplace_docinfo_gap,
:inplace_reloc_factor, :inplace_write_factor, :index_exact_words,
:overshort_step, :stopword_step, :hitless_words, :ha_strategy,
:bigram_freq_words, :bigram_index, :index_field_lengths,
:regexp_filter, :stopwords_unstemmed, :global_idf, :rlp_context,
:ondisk_attrs
]
end
attr_accessor :name, :type, :path, :docinfo, :mlock,
:morphologies, :dict, :index_sp, :index_zones, :min_stemming_len,
:stopword_files, :wordform_files, :exception_files, :min_word_len,
:charset_dictpath, :charset_type, :charset_table, :ignore_characters,
:min_prefix_len, :min_infix_len, :prefix_field_names,
:infix_field_names, :enable_star, :expand_keywords, :ngram_len,
:ngram_characters, :phrase_boundaries, :phrase_boundary_step,
:blend_chars, :blend_mode, :html_strip, :html_index_attrs,
:html_remove_element_tags, :preopen, :ondisk_dict, :inplace_enable,
:inplace_hit_gap, :inplace_docinfo_gap, :inplace_reloc_factor,
:inplace_write_factor, :index_exact_words, :overshort_step,
:stopword_step, :hitless_words, :ha_strategy, :bigram_freq_words,
:bigram_index, :index_field_lengths, :regexp_filter,
:stopwords_unstemmed, :global_idf, :rlp_context, :ondisk_attrs
def initialize_settings
@morphologies = []
@stopword_files = []
@wordform_files = []
@exception_files = []
@ignore_characters = []
@prefix_field_names = []
@infix_field_names = []
@ngram_characters = []
@phrase_boundaries = []
@html_remove_element_tags = []
@regexp_filter = []
end
def morphology
nil_join @morphologies, ", "
end
def morphology=(morphology)
@morphologies = nil_split morphology, /,\s?/
end
def stopwords
nil_join @stopword_files, " "
end
def stopwords=(stopwords)
@stopword_files = nil_split stopwords, ' '
end
def wordforms
nil_join @wordform_files, " "
end
def wordforms=(wordforms)
@wordform_files = nil_split wordforms, ' '
end
def exceptions
nil_join @exception_files, " "
end
def exceptions=(exceptions)
@exception_files = nil_split exceptions, ' '
end
def ignore_chars
nil_join @ignore_characters, ", "
end
def ignore_chars=(ignore_chars)
@ignore_characters = nil_split ignore_chars, /,\s?/
end
def prefix_fields
nil_join @prefix_field_names, ", "
end
def prefix_fields=(fields)
if fields.is_a?(Array)
@prefix_field_names = fields
else
@prefix_field_names = fields.split(/,\s*/)
end
end
def infix_fields
nil_join @infix_field_names, ", "
end
def infix_fields=(fields)
if fields.is_a?(Array)
@infix_field_names = fields
else
@infix_field_names = fields.split(/,\s*/)
end
end
def ngram_chars
nil_join @ngram_characters, ", "
end
def ngram_chars=(ngram_chars)
@ngram_characters = nil_split ngram_chars, /,\s?/
end
def phrase_boundary
nil_join @phrase_boundaries, ", "
end
def phrase_boundary=(phrase_boundary)
@phrase_boundaries = nil_split phrase_boundary, /,\s?/
end
def html_remove_elements
nil_join @html_remove_element_tags, ", "
end
def html_remove_elements=(html_remove_elements)
@html_remove_element_tags = nil_split html_remove_elements, /,\s?/
end
private
def nil_split(string, pattern)
(string || "").split(pattern)
end
def nil_join(array, delimiter)
if array.length == 0
nil
else
array.join(delimiter)
end
end
end
end
end
| ruby | MIT | 748ca04d14a9c04b7a5f2d64dbcd4897c1ab3f43 | 2026-01-04T17:45:28.600554Z | false |
pat/riddle | https://github.com/pat/riddle/blob/748ca04d14a9c04b7a5f2d64dbcd4897c1ab3f43/lib/riddle/configuration/realtime_index.rb | lib/riddle/configuration/realtime_index.rb | # frozen_string_literal: true
module Riddle
class Configuration
class RealtimeIndex < Riddle::Configuration::Section
include Riddle::Configuration::IndexSettings
def self.settings
Riddle::Configuration::IndexSettings.settings + [
:rt_mem_limit, :rt_field, :rt_attr_uint, :rt_attr_bigint,
:rt_attr_float, :rt_attr_timestamp, :rt_attr_string, :rt_attr_multi,
:rt_attr_multi_64, :rt_attr_bool, :rt_attr_json
]
end
attr_accessor :rt_mem_limit, :rt_field, :rt_attr_uint, :rt_attr_bigint,
:rt_attr_float, :rt_attr_timestamp, :rt_attr_string, :rt_attr_multi,
:rt_attr_multi_64, :rt_attr_bool, :rt_attr_json
def initialize(name)
@name = name
@rt_field = []
@rt_attr_uint = []
@rt_attr_bigint = []
@rt_attr_float = []
@rt_attr_timestamp = []
@rt_attr_string = []
@rt_attr_multi = []
@rt_attr_multi_64 = []
@rt_attr_bool = []
@rt_attr_json = []
initialize_settings
end
def type
"rt"
end
def valid?
!(@name.nil? || @path.nil?)
end
def render
raise ConfigurationError unless valid?
(
["index #{name}", "{"] +
settings_body +
["}", ""]
).join("\n")
end
end
end
end
| ruby | MIT | 748ca04d14a9c04b7a5f2d64dbcd4897c1ab3f43 | 2026-01-04T17:45:28.600554Z | false |
pat/riddle | https://github.com/pat/riddle/blob/748ca04d14a9c04b7a5f2d64dbcd4897c1ab3f43/lib/riddle/configuration/distributed_index.rb | lib/riddle/configuration/distributed_index.rb | # frozen_string_literal: true
module Riddle
class Configuration
class DistributedIndex < Riddle::Configuration::Section
def self.settings
[
:type, :local, :agent, :agent_blackhole,
:agent_connect_timeout, :agent_query_timeout
]
end
attr_accessor :name, :local_indices, :remote_indices, :agent_blackhole,
:agent_connect_timeout, :agent_query_timeout
def initialize(name)
@name = name
@local_indices = []
@remote_indices = []
@agent_blackhole = []
end
def type
"distributed"
end
def local
self.local_indices
end
def agent
agents = remote_indices.collect { |index| index.remote }.uniq
agents.collect { |agent|
agent + ":" + remote_indices.select { |index|
index.remote == agent
}.collect { |index| index.name }.join(",")
}
end
def render
raise ConfigurationError unless valid?
(
["index #{name}", "{"] +
settings_body +
["}", ""]
).join("\n")
end
def valid?
@local_indices.length > 0 || @remote_indices.length > 0
end
end
end
end
| ruby | MIT | 748ca04d14a9c04b7a5f2d64dbcd4897c1ab3f43 | 2026-01-04T17:45:28.600554Z | false |
pat/riddle | https://github.com/pat/riddle/blob/748ca04d14a9c04b7a5f2d64dbcd4897c1ab3f43/lib/riddle/configuration/indexer.rb | lib/riddle/configuration/indexer.rb | # frozen_string_literal: true
module Riddle
class Configuration
class Indexer < Riddle::Configuration::Section
def self.settings
[
:mem_limit, :max_iops, :max_iosize, :max_xmlpipe2_field,
:write_buffer, :max_file_field_buffer, :on_file_field_error,
:lemmatizer_cache
] + shared_settings
end
def self.shared_settings
[
:lemmatizer_base, :json_autoconv_numbers, :json_autoconv_keynames,
:on_json_attr_error, :rlp_root, :rlp_environment, :rlp_max_batch_size,
:rlp_max_batch_docs
]
end
attr_accessor :common_sphinx_configuration, *settings
def render
raise ConfigurationError unless valid?
(
["indexer", "{"] +
settings_body +
["}", ""]
).join("\n")
end
private
def settings
settings = self.class.settings
settings -= self.class.shared_settings if common_sphinx_configuration
settings
end
end
end
end
| ruby | MIT | 748ca04d14a9c04b7a5f2d64dbcd4897c1ab3f43 | 2026-01-04T17:45:28.600554Z | false |
pat/riddle | https://github.com/pat/riddle/blob/748ca04d14a9c04b7a5f2d64dbcd4897c1ab3f43/lib/riddle/configuration/xml_source.rb | lib/riddle/configuration/xml_source.rb | # frozen_string_literal: true
module Riddle
class Configuration
class XMLSource < Riddle::Configuration::Source
def self.settings
[
:type, :xmlpipe_command, :xmlpipe_field,
:xmlpipe_attr_uint, :xmlpipe_attr_bool, :xmlpipe_attr_timestamp,
:xmlpipe_attr_str2ordinal, :xmlpipe_attr_float, :xmlpipe_attr_multi,
:xmlpipe_fixup_utf8
]
end
attr_accessor *self.settings
def initialize(name, type)
@name = name
@type = type
@xmlpipe_field = []
@xmlpipe_attr_uint = []
@xmlpipe_attr_bool = []
@xmlpipe_attr_timestamp = []
@xmlpipe_attr_str2ordinal = []
@xmlpipe_attr_float = []
@xmlpipe_attr_multi = []
end
def valid?
super && ( !@xmlpipe_command.nil? || !parent.nil? )
end
end
end
end
| ruby | MIT | 748ca04d14a9c04b7a5f2d64dbcd4897c1ab3f43 | 2026-01-04T17:45:28.600554Z | false |
pat/riddle | https://github.com/pat/riddle/blob/748ca04d14a9c04b7a5f2d64dbcd4897c1ab3f43/lib/riddle/configuration/template_index.rb | lib/riddle/configuration/template_index.rb | # frozen_string_literal: true
module Riddle
class Configuration
class TemplateIndex < Riddle::Configuration::Section
include Riddle::Configuration::IndexSettings
def self.settings
Riddle::Configuration::IndexSettings.settings
end
attr_accessor :parent
def initialize(name)
@name = name
@type = 'template'
initialize_settings
end
def render
raise ConfigurationError, "#{@name} #{@parent}" unless valid?
inherited_name = "#{name}"
inherited_name << " : #{parent}" if parent
(
["index #{inherited_name}", "{"] +
settings_body +
["}", ""]
).join("\n")
end
def valid?
@name
end
end
end
end
| ruby | MIT | 748ca04d14a9c04b7a5f2d64dbcd4897c1ab3f43 | 2026-01-04T17:45:28.600554Z | false |
pat/riddle | https://github.com/pat/riddle/blob/748ca04d14a9c04b7a5f2d64dbcd4897c1ab3f43/lib/riddle/configuration/sql_source.rb | lib/riddle/configuration/sql_source.rb | # frozen_string_literal: true
module Riddle
class Configuration
class SQLSource < Riddle::Configuration::Source
def self.settings
[
:type, :sql_host, :sql_user, :sql_pass, :sql_db,
:sql_port, :sql_sock, :mysql_connect_flags, :mysql_ssl_cert,
:mysql_ssl_key, :mysql_ssl_ca, :odbc_dsn, :sql_query_pre, :sql_query,
:sql_joined_field, :sql_file_field, :sql_query_range,
:sql_range_step, :sql_query_killlist, :sql_attr_uint, :sql_attr_bool,
:sql_attr_bigint, :sql_attr_timestamp, :sql_attr_str2ordinal,
:sql_attr_float, :sql_attr_multi, :sql_attr_string,
:sql_attr_str2wordcount, :sql_attr_json,
:sql_column_buffers, :sql_field_string, :sql_field_str2wordcount,
:sql_query_post, :sql_query_post_index, :sql_ranged_throttle,
:sql_query_info, :mssql_winauth, :mssql_unicode, :unpack_zlib,
:unpack_mysqlcompress, :unpack_mysqlcompress_maxsize
]
end
attr_accessor *self.settings
def initialize(name, type)
@name = name
@type = type
@sql_query_pre = []
@sql_joined_field = []
@sql_file_field = []
@sql_attr_uint = []
@sql_attr_bool = []
@sql_attr_bigint = []
@sql_attr_timestamp = []
@sql_attr_str2ordinal = []
@sql_attr_float = []
@sql_attr_multi = []
@sql_attr_string = []
@sql_attr_str2wordcount = []
@sql_attr_json = []
@sql_field_string = []
@sql_field_str2wordcount = []
@sql_query_post = []
@sql_query_post_index = []
@unpack_zlib = []
@unpack_mysqlcompress = []
end
def valid?
super && (!( @sql_host.nil? || @sql_user.nil? || @sql_db.nil? ||
@sql_query.nil? ) || !@parent.nil?)
end
end
end
end
| ruby | MIT | 748ca04d14a9c04b7a5f2d64dbcd4897c1ab3f43 | 2026-01-04T17:45:28.600554Z | false |
pat/riddle | https://github.com/pat/riddle/blob/748ca04d14a9c04b7a5f2d64dbcd4897c1ab3f43/lib/riddle/configuration/tsv_source.rb | lib/riddle/configuration/tsv_source.rb | # frozen_string_literal: true
module Riddle
class Configuration
class TSVSource < Riddle::Configuration::Source
def self.settings
[:type, :tsvpipe_command, :tsvpipe_attr_field, :tsvpipe_attr_multi]
end
attr_accessor *self.settings
def initialize(name, type = 'tsvpipe')
@name, @type = name, type
end
def valid?
super && (@tsvpipe_command || @parent)
end
end
end
end
| ruby | MIT | 748ca04d14a9c04b7a5f2d64dbcd4897c1ab3f43 | 2026-01-04T17:45:28.600554Z | false |
pat/riddle | https://github.com/pat/riddle/blob/748ca04d14a9c04b7a5f2d64dbcd4897c1ab3f43/lib/riddle/2.0.1/client.rb | lib/riddle/2.0.1/client.rb | # frozen_string_literal: true
Riddle::Client::Versions[:search] = 0x118
Riddle::Client::Versions[:excerpt] = 0x103 | ruby | MIT | 748ca04d14a9c04b7a5f2d64dbcd4897c1ab3f43 | 2026-01-04T17:45:28.600554Z | false |
pat/riddle | https://github.com/pat/riddle/blob/748ca04d14a9c04b7a5f2d64dbcd4897c1ab3f43/lib/riddle/client/filter.rb | lib/riddle/client/filter.rb | # frozen_string_literal: true
module Riddle
class Client
class Filter
attr_accessor :attribute, :values, :exclude
# Attribute name, values (which can be an array or a range), and whether
# the filter should be exclusive.
def initialize(attribute, values, exclude=false)
@attribute, @values, @exclude = attribute, values, exclude
end
def exclude?
self.exclude
end
# Returns the message for this filter to send to the Sphinx service
def query_message
message = Message.new
message.append_string self.attribute.to_s
case self.values
when Range
if self.values.first.is_a?(Float) && self.values.last.is_a?(Float)
message.append_int FilterTypes[:float_range]
message.append_floats self.values.first, self.values.last
else
message.append_int FilterTypes[:range]
append_integer_range message, self.values
end
when Array
if self.values.first.is_a?(Float) && self.values.length == 1
message.append_int FilterTypes[:float_range]
message.append_floats self.values.first, self.values.first
else
message.append_int FilterTypes[:values]
message.append_int self.values.length
append_array message, self.values
end
end
message.append_int self.exclude? ? 1 : 0
message.to_s
end
private
def append_integer_range(message, range)
message.append_ints self.values.first, self.values.last
end
# Using to_f is a hack from the PHP client - to workaround 32bit signed
# ints on x32 platforms
def append_array(message, array)
message.append_ints *array.collect { |val|
case val
when TrueClass
1.0
when FalseClass
0.0
else
val.to_f
end
}
end
end
end
end
| ruby | MIT | 748ca04d14a9c04b7a5f2d64dbcd4897c1ab3f43 | 2026-01-04T17:45:28.600554Z | false |
pat/riddle | https://github.com/pat/riddle/blob/748ca04d14a9c04b7a5f2d64dbcd4897c1ab3f43/lib/riddle/client/response.rb | lib/riddle/client/response.rb | # frozen_string_literal: true
module Riddle
class Client
# Used to interrogate responses from the Sphinx daemon. Keep in mind none
# of the methods here check whether the data they're grabbing are what the
# user expects - it just assumes the user knows what the data stream is
# made up of.
class Response
# Create with the data to interpret
def initialize(str)
@str = str
@marker = 0
end
# Return the next string value in the stream
def next
len = next_int
result = @str[@marker, len]
@marker += len
Riddle.encode(result)
end
# Return the next integer value from the stream
def next_int
int = @str[@marker, 4].unpack('N*').first
@marker += 4
int
end
def next_64bit_int
high, low = @str[@marker, 8].unpack('N*N*')[0..1]
@marker += 8
(high << 32) + low
end
# Return the next float value from the stream
def next_float
float = @str[@marker, 4].unpack('N*').pack('L').unpack('f*').first
@marker += 4
float
end
# Returns an array of string items
def next_array
count = next_int
items = []
count.times do
items << self.next
end
items
end
# Returns an array of int items
def next_int_array
count = next_int
items = []
count.times do
items << self.next_int
end
items
end
def next_float_array
count = next_int
items = []
count.times do
items << self.next_float
end
items
end
def next_64bit_int_array
byte_count = next_int
items = []
(byte_count / 2).times do
items << self.next_64bit_int
end
items
end
# Returns the length of the streamed data
def length
@str.length
end
end
end
end
| ruby | MIT | 748ca04d14a9c04b7a5f2d64dbcd4897c1ab3f43 | 2026-01-04T17:45:28.600554Z | false |
pat/riddle | https://github.com/pat/riddle/blob/748ca04d14a9c04b7a5f2d64dbcd4897c1ab3f43/lib/riddle/client/message.rb | lib/riddle/client/message.rb | # frozen_string_literal: true
module Riddle
class Client
# This class takes care of the translation of ints, strings and arrays to
# the format required by the Sphinx service.
class Message
def initialize
@message = StringIO.new String.new(""), "w"
@message.set_encoding 'ASCII-8BIT'
@size_method = @message.respond_to?(:bytesize) ? :bytesize : :length
end
# Append raw data (only use if you know what you're doing)
def append(*args)
args.each { |arg| @message << arg }
end
# Append a string's length, then the string itself
def append_string(str)
string = Riddle.encode(str.dup, 'ASCII-8BIT')
@message << [string.send(@size_method)].pack('N') + string
end
# Append an integer
def append_int(int)
@message << [int.to_i].pack('N')
end
def append_64bit_int(int)
@message << [int.to_i >> 32, int.to_i & 0xFFFFFFFF].pack('NN')
end
# Append a float
def append_float(float)
@message << [float].pack('f').unpack('L*').pack("N")
end
def append_boolean(bool)
append_int(bool ? 1 : 0)
end
# Append multiple integers
def append_ints(*ints)
ints.each { |int| append_int(int) }
end
def append_64bit_ints(*ints)
ints.each { |int| append_64bit_int(int) }
end
# Append multiple floats
def append_floats(*floats)
floats.each { |float| append_float(float) }
end
# Append an array of strings - first appends the length of the array,
# then each item's length and value.
def append_array(array)
append_int(array.length)
array.each { |item| append_string(item) }
end
# Returns the entire message
def to_s
@message.string
end
end
end
end
| ruby | MIT | 748ca04d14a9c04b7a5f2d64dbcd4897c1ab3f43 | 2026-01-04T17:45:28.600554Z | false |
fnando/factory_bot-preload | https://github.com/fnando/factory_bot-preload/blob/e94a0ef8e2ffacff5de753efdc0a3b6f8f1a3acb/test/test_helper.rb | test/test_helper.rb | # frozen_string_literal: true
require "simplecov"
SimpleCov.start do
add_filter(/schema\.rb/)
end
ENV["RAILS_ENV"] = "test"
ENV["BUNDLE_GEMFILE"] = "#{File.dirname(__FILE__)}/../Gemfile"
ENV["DATABASE_URL"] = "sqlite3::memory:"
require "bundler/setup"
require "rails"
require "active_model/railtie"
require "active_record/railtie"
require "action_controller/railtie"
require "action_view/railtie"
require "rails/test_unit/railtie"
require "minitest/utils"
class SampleApplication < ::Rails::Application
config.api = true
config.root = "#{__dir__}/../spec/support/app"
config.active_support.deprecation = :log
config.eager_load = false
end
SampleApplication.initialize!
require "rails/test_help"
ActiveRecord::Migration.verbose = true
ActiveRecord::Base.establish_connection ENV["DATABASE_URL"]
load "#{__dir__}/../spec/support/app/db/schema.rb"
module ActiveSupport
class TestCase
self.use_instantiated_fixtures = true
end
end
require "factory_bot/preload"
require "#{__dir__}/../spec/support/factories"
FactoryBot::Preload.minitest
| ruby | MIT | e94a0ef8e2ffacff5de753efdc0a3b6f8f1a3acb | 2026-01-04T17:45:31.138848Z | false |
fnando/factory_bot-preload | https://github.com/fnando/factory_bot-preload/blob/e94a0ef8e2ffacff5de753efdc0a3b6f8f1a3acb/test/factory_bot/preload_test.rb | test/factory_bot/preload_test.rb | # frozen_string_literal: true
require "test_helper"
class PreloadTest < ActiveSupport::TestCase
setup do
FactoryBot::Preload.clean_with = :truncation
FactoryBot::Preload.helper_name = FactoryBot::Preload.default_helper_name
end
test "queues preloader block" do
block = proc { }
FactoryBot.preload(&block)
assert_includes FactoryBot::Preload.preloaders, block
end
test "lazy load all factories, loading only when used" do
assert_equal 1, FactoryBot::Preload.record_ids["User"][:john]
assert_nil FactoryBot::Preload.factories["User"][:john]
user = users(:john)
assert_equal user, FactoryBot::Preload.factories["User"][:john]
end
test "injects model methods" do
# this shouldn't raise an exception
users(:john)
end
test "returns :john factory for User model" do
assert_instance_of User, users(:john)
end
test "returns :ruby factory for Skill model" do
assert_instance_of Skill, skills(:ruby)
end
test "returns :my factory for Preload model" do
assert_instance_of Preload, preloads(:my)
end
test "reuses existing factories" do
assert_equal users(:john), skills(:ruby).user
end
test "raises error for missing factories" do
assert_raises(%[Couldn't find :mary factory for "User" model]) do
users(:mary)
end
end
test "raises error for missing clean type" do
FactoryBot::Preload.clean_with = :invalid
assert_raises(%[Couldn't find invalid clean type]) do
FactoryBot::Preload.clean
end
end
test "association uses preloaded record" do
assert_equal users(:john), build(:skill).user
end
test "removes records with :deletion" do
assert_equal 1, User.count
FactoryBot::Preload.clean_with = :deletion
FactoryBot::Preload.clean
assert_equal 0, User.count
end
test "removes records with :truncation" do
assert_equal 1, User.count
FactoryBot::Preload.clean_with = :truncation
FactoryBot::Preload.clean
assert_equal 0, User.count
end
test "includes factory_bot helpers" do
assert_includes self.class.included_modules, FactoryBot::Syntax::Methods
end
test "includes helpers into factory_bot" do
assert_includes FactoryBot::SyntaxRunner.included_modules,
FactoryBot::Preload::Helpers
end
test "freezes object" do
users(:john).destroy
assert users(:john).frozen?
end
test "updates invitation count" do
users(:john).increment(:invitations)
users(:john).save
assert_equal 1, users(:john).invitations
end
test "reloads factory" do
assert_equal 0, users(:john).invitations
refute users(:john).frozen?
end
test "ignores reserved table names" do
mod = Module.new do
include FactoryBot::Preload::Helpers
end
instance = Object.new.extend(mod)
refute_respond_to instance, :active_record_internal_metadata
refute_respond_to instance, :active_record_schema_migrations
refute_respond_to instance, :primary_schema_migrations
end
test "processes helper name" do
FactoryBot::Preload.helper_name = lambda do |_class_name, helper_name|
helper_name.gsub(/^models_/, "")
end
mod = Module.new do
include FactoryBot::Preload::Helpers
end
instance = Object.new.extend(mod)
assert_respond_to instance, :assets
assert_equal "Some asset", assets(:asset).name
end
end
| ruby | MIT | e94a0ef8e2ffacff5de753efdc0a3b6f8f1a3acb | 2026-01-04T17:45:31.138848Z | false |
fnando/factory_bot-preload | https://github.com/fnando/factory_bot-preload/blob/e94a0ef8e2ffacff5de753efdc0a3b6f8f1a3acb/spec/spec_helper.rb | spec/spec_helper.rb | # frozen_string_literal: true
require "simplecov"
SimpleCov.start do
add_filter(/schema\.rb/)
end
ENV["RAILS_ENV"] = "test"
ENV["BUNDLE_GEMFILE"] = "#{File.dirname(__FILE__)}/../Gemfile"
ENV["DATABASE_URL"] = "sqlite3::memory:"
require "bundler/setup"
require "rails"
require "active_model/railtie"
require "active_record/railtie"
require "action_controller/railtie"
require "action_view/railtie"
require "rails/test_unit/railtie"
module RSpec
class Application < ::Rails::Application
config.root = "#{File.dirname(__FILE__)}/support/app"
config.active_support.deprecation = :log
config.eager_load = false
end
end
RSpec::Application.initialize!
ActiveRecord::Migration.verbose = true
ActiveRecord::Base.establish_connection ENV["DATABASE_URL"]
load "#{File.dirname(__FILE__)}/support/app/db/schema.rb"
require "rspec/rails"
RSpec.configure do |config|
config.use_transactional_fixtures = true
end
require "factory_bot/preload"
require "#{File.dirname(__FILE__)}/support/factories"
| ruby | MIT | e94a0ef8e2ffacff5de753efdc0a3b6f8f1a3acb | 2026-01-04T17:45:31.138848Z | false |
fnando/factory_bot-preload | https://github.com/fnando/factory_bot-preload/blob/e94a0ef8e2ffacff5de753efdc0a3b6f8f1a3acb/spec/support/factories.rb | spec/support/factories.rb | # frozen_string_literal: true
FactoryBot.define do
sequence(:email) {|n| "john#{n}@doe.com" }
factory :user do
name { "John Doe" }
email { generate(:email) }
end
factory :skill do
user { users(:john) }
end
factory :preload do
name { "My Preload" }
end
factory :asset, class: "Models::Asset" do
name { "Some asset" }
end
preload do
factory(:john) { create(:user) }
factory(:ruby) { create(:skill, user: users(:john)) }
factory(:my) { create(:preload) }
factory(:asset) { create(:asset) }
end
end
| ruby | MIT | e94a0ef8e2ffacff5de753efdc0a3b6f8f1a3acb | 2026-01-04T17:45:31.138848Z | false |
fnando/factory_bot-preload | https://github.com/fnando/factory_bot-preload/blob/e94a0ef8e2ffacff5de753efdc0a3b6f8f1a3acb/spec/support/app/app/models/category.rb | spec/support/app/app/models/category.rb | # frozen_string_literal: true
class Category < ActiveRecord::Base
has_and_belongs_to_many :users
end
| ruby | MIT | e94a0ef8e2ffacff5de753efdc0a3b6f8f1a3acb | 2026-01-04T17:45:31.138848Z | false |
fnando/factory_bot-preload | https://github.com/fnando/factory_bot-preload/blob/e94a0ef8e2ffacff5de753efdc0a3b6f8f1a3acb/spec/support/app/app/models/skill.rb | spec/support/app/app/models/skill.rb | # frozen_string_literal: true
class Skill < ActiveRecord::Base
belongs_to :user
end
| ruby | MIT | e94a0ef8e2ffacff5de753efdc0a3b6f8f1a3acb | 2026-01-04T17:45:31.138848Z | false |
fnando/factory_bot-preload | https://github.com/fnando/factory_bot-preload/blob/e94a0ef8e2ffacff5de753efdc0a3b6f8f1a3acb/spec/support/app/app/models/preload.rb | spec/support/app/app/models/preload.rb | # frozen_string_literal: true
class Preload < ActiveRecord::Base
end
| ruby | MIT | e94a0ef8e2ffacff5de753efdc0a3b6f8f1a3acb | 2026-01-04T17:45:31.138848Z | false |
fnando/factory_bot-preload | https://github.com/fnando/factory_bot-preload/blob/e94a0ef8e2ffacff5de753efdc0a3b6f8f1a3acb/spec/support/app/app/models/user.rb | spec/support/app/app/models/user.rb | # frozen_string_literal: true
class User < ActiveRecord::Base
has_many :skills
has_and_belongs_to_many :categories
end
| ruby | MIT | e94a0ef8e2ffacff5de753efdc0a3b6f8f1a3acb | 2026-01-04T17:45:31.138848Z | false |
fnando/factory_bot-preload | https://github.com/fnando/factory_bot-preload/blob/e94a0ef8e2ffacff5de753efdc0a3b6f8f1a3acb/spec/support/app/app/models/models/asset.rb | spec/support/app/app/models/models/asset.rb | # frozen_string_literal: true
module Models
class Asset < ActiveRecord::Base
end
end
| ruby | MIT | e94a0ef8e2ffacff5de753efdc0a3b6f8f1a3acb | 2026-01-04T17:45:31.138848Z | false |
fnando/factory_bot-preload | https://github.com/fnando/factory_bot-preload/blob/e94a0ef8e2ffacff5de753efdc0a3b6f8f1a3acb/spec/support/app/db/schema.rb | spec/support/app/db/schema.rb | # frozen_string_literal: true
ActiveRecord::Schema.define(version: 0) do
begin
drop_table :users if table_exists?(:users)
drop_table :skills if table_exists?(:skills)
drop_table :preloads if table_exists?(:preloads)
drop_table :categories if table_exists?(:categories)
drop_table :categories_users if table_exists?(:categories_users)
drop_table :assets if table_exists?(:assets)
end
create_table :users do |t|
t.string :name, null: false
t.string :email, null: false
t.integer :invitations, null: false, default: 0
end
add_index :users, :email, unique: true
create_table :preloads do |t|
t.string :name
end
create_table :skills do |t|
t.references :user
end
create_table :categories
create_table :categories_users, id: false do |t|
t.references :category
t.references :user
end
create_table :assets do |t|
t.string :name
end
end
| ruby | MIT | e94a0ef8e2ffacff5de753efdc0a3b6f8f1a3acb | 2026-01-04T17:45:31.138848Z | false |
fnando/factory_bot-preload | https://github.com/fnando/factory_bot-preload/blob/e94a0ef8e2ffacff5de753efdc0a3b6f8f1a3acb/spec/factory_bot/preload_spec.rb | spec/factory_bot/preload_spec.rb | # frozen_string_literal: true
require "spec_helper"
describe FactoryBot::Preload do
it "queues preloader block" do
block = proc { }
FactoryBot.preload(&block)
expect(FactoryBot::Preload.preloaders).to include(block)
end
it "should lazy load all factories, loading only when used" do
expect(FactoryBot::Preload.record_ids["User"][:john]).to eq(1)
expect(FactoryBot::Preload.factories["User"][:john]).to be_nil
user = users(:john)
expect(FactoryBot::Preload.factories["User"][:john]).to eq(user)
end
it "injects model methods" do
expect { users(:john) }.to_not raise_error
end
it "returns :john factory for User model" do
expect(users(:john)).to be_an(User)
end
it "returns :ruby factory for Skill model" do
expect(skills(:ruby)).to be_a(Skill)
end
it "returns :my factory for Preload model" do
expect(preloads(:my)).to be_a(Preload)
end
it "reuses existing factories" do
expect(skills(:ruby).user).to eq(users(:john))
end
it "raises error for missing factories" do
expect do
users(:mary)
end.to raise_error(%[Couldn't find :mary factory for "User" model])
end
it "raises error for missing clean type" do
FactoryBot::Preload.clean_with = :invalid
expect do
FactoryBot::Preload.clean
end.to raise_error(%[Couldn't find invalid clean type])
end
it "ignores reserved table names when creating helpers" do
mod = Module.new do
include FactoryBot::Preload::Helpers
end
instance = Object.new.extend(mod)
expect(instance).not_to respond_to(:active_record_internal_metadata)
expect(instance).not_to respond_to(:active_record_schema_migrations)
expect(instance).not_to respond_to(:primary_schema_migrations)
end
it "processes helper name" do
FactoryBot::Preload.helper_name = lambda do |_class_name, helper_name|
helper_name.gsub(/^models_/, "")
end
mod = Module.new do
include FactoryBot::Preload::Helpers
end
instance = Object.new.extend(mod)
expect(instance).to respond_to(:assets)
expect(assets(:asset).name).to eq("Some asset")
end
example "association uses preloaded record" do
expect(build(:skill).user).to eq(users(:john))
end
context "removes records" do
it "with deletion" do
expect(User.count).to eq(1)
FactoryBot::Preload.clean_with = :deletion
FactoryBot::Preload.clean
expect(User.count).to eq(0)
end
it "with truncation" do
expect(User.count).to eq(1)
FactoryBot::Preload.clean_with = :truncation
FactoryBot::Preload.clean
expect(User.count).to eq(0)
end
end
context "reloadable factories" do
before :all do
FactoryBot::Preload.clean
FactoryBot::Preload.run
end
before :each do
FactoryBot::Preload.reload_factories
end
it "freezes object" do
users(:john).destroy
expect(users(:john)).to be_frozen
end
it "updates invitation count" do
users(:john).increment(:invitations)
users(:john).save
expect(users(:john).invitations).to eq(1)
end
it "reloads factory" do
expect(users(:john).invitations).to eq(0)
expect(users(:john)).not_to be_frozen
end
end
it "includes factory_bot helpers" do
expect(self.class.included_modules).to include(FactoryBot::Syntax::Methods)
end
it "includes helpers into factory_bot" do
helpers_module = FactoryBot::Preload::Helpers
expect(FactoryBot::SyntaxRunner.included_modules).to include(helpers_module)
end
end
| ruby | MIT | e94a0ef8e2ffacff5de753efdc0a3b6f8f1a3acb | 2026-01-04T17:45:31.138848Z | false |
fnando/factory_bot-preload | https://github.com/fnando/factory_bot-preload/blob/e94a0ef8e2ffacff5de753efdc0a3b6f8f1a3acb/lib/factory_bot/preload.rb | lib/factory_bot/preload.rb | # frozen_string_literal: true
require "factory_bot"
require "active_record"
module FactoryBot
module Preload
class << self
attr_accessor :preloaders, :factories, :record_ids, :clean_with,
:default_helper_name, :helper_name, :reserved_tables
end
self.preloaders = []
self.factories = {}
self.record_ids = {}
self.clean_with = :truncation
self.default_helper_name = ->(_class_name, helper_name) { helper_name }
self.helper_name = default_helper_name
self.reserved_tables = %w[
ar_internal_metadata
schema_migrations
]
require "factory_bot/preload/helpers"
require "factory_bot/preload/version"
require "factory_bot/preload/rspec" if defined?(RSpec)
require "factory_bot/preload/minitest" if defined?(Minitest)
require "factory_bot/preload/extension"
ActiveSupport.on_load(:after_initialize) do
::FactoryBot::Preload::Helpers.load_models
::FactoryBot::SyntaxRunner.include ::FactoryBot::Preload::Helpers
end
def self.active_record
ActiveRecord::Base
end
def self.connection
active_record.connection
end
def self.run
helper = Object.new.extend(Helpers)
connection.transaction requires_new: true do
preloaders.each do |block|
helper.instance_eval(&block)
end
end
end
def self.clean(*names)
query = case clean_with
when :truncation
try_truncation_query
when :deletion
"DELETE FROM %s"
else
raise "Couldn't find #{clean_with} clean type"
end
names = active_record_names if names.empty?
connection.disable_referential_integrity do
names.each do |table|
connection.execute(query % connection.quote_table_name(table))
end
end
end
def self.active_record_names
connection.tables.reject {|name| reserved_tables.include?(name) }
end
def self.reload_factories
factories.each do |class_name, group|
group.each do |name, _factory|
factories[class_name][name] = nil
end
end
end
def self.try_truncation_query
case connection.adapter_name
when "SQLite"
"DELETE FROM %s"
when "PostgreSQL"
"TRUNCATE TABLE %s RESTART IDENTITY CASCADE"
else
"TRUNCATE TABLE %s"
end
end
end
end
| ruby | MIT | e94a0ef8e2ffacff5de753efdc0a3b6f8f1a3acb | 2026-01-04T17:45:31.138848Z | false |
fnando/factory_bot-preload | https://github.com/fnando/factory_bot-preload/blob/e94a0ef8e2ffacff5de753efdc0a3b6f8f1a3acb/lib/factory_bot/preload/version.rb | lib/factory_bot/preload/version.rb | # frozen_string_literal: true
module FactoryBot
module Preload
module Version
MAJOR = 0
MINOR = 3
PATCH = 1
STRING = "#{MAJOR}.#{MINOR}.#{PATCH}"
end
end
end
| ruby | MIT | e94a0ef8e2ffacff5de753efdc0a3b6f8f1a3acb | 2026-01-04T17:45:31.138848Z | false |
fnando/factory_bot-preload | https://github.com/fnando/factory_bot-preload/blob/e94a0ef8e2ffacff5de753efdc0a3b6f8f1a3acb/lib/factory_bot/preload/helpers.rb | lib/factory_bot/preload/helpers.rb | # frozen_string_literal: true
module FactoryBot
module Preload
module Helpers
include ::FactoryBot::Syntax::Methods
def self.load_models
return unless defined?(Rails)
models_path = Rails.application.root.join("app/models/**/*.rb")
Dir[models_path].sort.each do |file|
require_dependency file
end
end
def self.define_helper_methods
ActiveRecord::Base.descendants.each do |model|
next if FactoryBot::Preload.reserved_tables.include?(model.table_name)
helper_name = model.name.underscore.tr("/", "_").pluralize
helper_name = FactoryBot::Preload.helper_name.call(
model.name,
helper_name
)
define_method(helper_name) do |name|
factory(name, model)
end
end
end
def self.included(_base)
FactoryBot::Preload::Helpers.define_helper_methods
end
def factory(name, model = nil, &block)
if block
factory_set(name, &block)
else
factory_get(name, model)
end
end
private def factory_get(name, model)
factory = Preload.factories[model.name][name]
if factory.blank? && Preload.factories[model.name].key?(name)
factory = model.find(Preload.record_ids[model.name][name])
Preload.factories[model.name][name] = factory
end
unless factory
raise "Couldn't find #{name.inspect} factory " \
"for #{model.name.inspect} model"
end
factory
end
private def factory_set(name, &block)
record = instance_eval(&block)
Preload.factories[record.class.name] ||= {}
Preload.factories[record.class.name][name.to_sym] = record
Preload.record_ids[record.class.name] ||= {}
Preload.record_ids[record.class.name][name.to_sym] = record.id
end
end
end
end
| ruby | MIT | e94a0ef8e2ffacff5de753efdc0a3b6f8f1a3acb | 2026-01-04T17:45:31.138848Z | false |
fnando/factory_bot-preload | https://github.com/fnando/factory_bot-preload/blob/e94a0ef8e2ffacff5de753efdc0a3b6f8f1a3acb/lib/factory_bot/preload/minitest.rb | lib/factory_bot/preload/minitest.rb | # frozen_string_literal: true
require "minitest"
require "factory_bot/syntax/methods"
module FactoryBot
module Preload
def self.minitest
FactoryBot::Preload::Helpers.load_models
FactoryBot::Preload.clean
FactoryBot::Preload.run
end
module MinitestSetup
def setup
FactoryBot::Preload.reload_factories
super
end
end
Minitest::Test.include Helpers
Minitest::Test.prepend MinitestSetup
end
end
| ruby | MIT | e94a0ef8e2ffacff5de753efdc0a3b6f8f1a3acb | 2026-01-04T17:45:31.138848Z | false |
fnando/factory_bot-preload | https://github.com/fnando/factory_bot-preload/blob/e94a0ef8e2ffacff5de753efdc0a3b6f8f1a3acb/lib/factory_bot/preload/rspec.rb | lib/factory_bot/preload/rspec.rb | # frozen_string_literal: true
require "rspec/core"
require "factory_bot/syntax/methods"
RSpec.configure do |config|
config.include FactoryBot::Preload::Helpers
config.before(:suite) do
FactoryBot::Preload.clean
FactoryBot::Preload.run
end
config.before(:each) do
FactoryBot::Preload.reload_factories
end
end
| ruby | MIT | e94a0ef8e2ffacff5de753efdc0a3b6f8f1a3acb | 2026-01-04T17:45:31.138848Z | false |
fnando/factory_bot-preload | https://github.com/fnando/factory_bot-preload/blob/e94a0ef8e2ffacff5de753efdc0a3b6f8f1a3acb/lib/factory_bot/preload/extension.rb | lib/factory_bot/preload/extension.rb | # frozen_string_literal: true
module FactoryBot
def self.preload(&block)
Preload.preloaders << block
end
module Syntax
module Default
class DSL
def preload(&block)
::FactoryBot.preload(&block)
end
end
end
end
end
| ruby | MIT | e94a0ef8e2ffacff5de753efdc0a3b6f8f1a3acb | 2026-01-04T17:45:31.138848Z | false |
soffes/unmarkdown | https://github.com/soffes/unmarkdown/blob/201a7df1e45a9ea071073d28e2f75efdf67d1413/test/unmarkdown_test.rb | test/unmarkdown_test.rb | require 'test_helper'
module Unmarkdown
class UnmarkdownTest < Test
def test_that_it_parses
refute_nil Unmarkdown.parse('foo')
end
end
end
| ruby | MIT | 201a7df1e45a9ea071073d28e2f75efdf67d1413 | 2026-01-04T17:45:32.739897Z | false |
soffes/unmarkdown | https://github.com/soffes/unmarkdown/blob/201a7df1e45a9ea071073d28e2f75efdf67d1413/test/test_helper.rb | test/test_helper.rb | require 'rubygems'
require 'bundler'
Bundler.require :test
if ENV['COVERAGE']
require 'simplecov'
SimpleCov.start
end
require 'minitest/autorun'
require 'unmarkdown'
# Support files
Dir["#{File.expand_path(File.dirname(__FILE__))}/support/*.rb"].each do |file|
require file
end
class Unmarkdown::Test < MiniTest::Test
end
| ruby | MIT | 201a7df1e45a9ea071073d28e2f75efdf67d1413 | 2026-01-04T17:45:32.739897Z | false |
soffes/unmarkdown | https://github.com/soffes/unmarkdown/blob/201a7df1e45a9ea071073d28e2f75efdf67d1413/test/parser_test.rb | test/parser_test.rb | require 'test_helper'
class ParserTest < Unmarkdown::Test
include Unmarkdown
def test_headers
6.times do |i|
i += 1
html = "<h#{i}>Header</h#{i}>"
markdown = ''
i.times { markdown << '#' }
markdown << ' Header'
assert_equal markdown, parse(html)
end
html = '<h1>Something Huge</h1>'
markdown = "Something Huge\n=============="
assert_equal markdown, parse(html, underline_headers: true)
html = '<h2>Something Smaller</h1>'
markdown = "Something Smaller\n-----------------"
assert_equal markdown, parse(html, underline_headers: true)
end
def test_blockquote
html = '<blockquote>Awesome.</blockquote>'
markdown = '> Awesome.'
assert_equal markdown, parse(html)
end
def test_unorder_list
html = '<ul><li>Ruby<ul><li>Gem</li><li>Stuff</li></ul></li><li>Objective-C</li></ul>'
markdown = "* Ruby\n\n * Gem\n\n * Stuff\n\n* Objective-C"
assert_equal markdown, parse(html)
end
def test_ordered_list
html = '<ol><li>Ruby<ol><li>Gem</li><li>Stuff</li></ol></li><li>Objective-C</li></ol>'
markdown = "1. Ruby\n\n 1. Gem\n\n 2. Stuff\n\n2. Objective-C"
assert_equal markdown, parse(html)
end
def test_code_block
html = "<pre>puts 'Hello world'</pre>"
markdown = " puts 'Hello world'"
assert_equal markdown, parse(html)
html = "<pre>puts 'Hello world'</pre>"
markdown = "```\nputs 'Hello world'\n```"
assert_equal markdown, parse(html, fenced_code_blocks: true)
end
def test_line_break
html = '<hr>'
markdown = '---'
assert_equal markdown, parse(html)
end
def test_link
html = '<a href="http://soff.es">Sam Soffes</a>'
markdown = '[Sam Soffes](http://soff.es)'
assert_equal markdown, parse(html)
html = '<a href="http://soff.es" title="My site">Sam Soffes</a>'
markdown = '[Sam Soffes](http://soff.es "My site")'
assert_equal markdown, parse(html)
end
def test_emphasis
html = '<i>italic</i>'
markdown = '*italic*'
assert_equal markdown, parse(html)
html = '<em>italic</em>'
markdown = '*italic*'
assert_equal markdown, parse(html)
end
def test_double_emphasis
html = '<b>bold</b>'
markdown = '**bold**'
assert_equal markdown, parse(html)
html = '<strong>bold</strong>'
markdown = '**bold**'
assert_equal markdown, parse(html)
end
def test_triple_emphasis
html = '<b><i>bold italic</i></b>'
markdown = '***bold italic***'
assert_equal markdown, parse(html)
end
def test_underline
html = '<u>underline</u>'
markdown = '_underline_'
assert_equal markdown, parse(html)
end
def test_bold_underline
html = '<b><u>underline</u></b>'
markdown = '**_underline_**'
assert_equal markdown, parse(html)
html = '<u><b>underline</b></u>'
markdown = '_**underline**_'
assert_equal markdown, parse(html)
end
def test_mark
html = '<mark>highlighted</mark>'
markdown = '==highlighted=='
assert_equal markdown, parse(html)
end
def test_code
html = '<code>Unmarkdown.parse(html)</code>'
markdown = '`Unmarkdown.parse(html)`'
assert_equal markdown, parse(html)
end
def test_image
html = '<img src="http://soffes-assets.s3.amazonaws.com/images/Sam-Soffes.jpg">'
markdown = ''
assert_equal markdown, parse(html)
html = '<img src="http://soffes-assets.s3.amazonaws.com/images/Sam-Soffes.jpg" alt="Sam Soffes">'
markdown = ''
assert_equal markdown, parse(html)
html = '<img src="http://soffes-assets.s3.amazonaws.com/images/Sam-Soffes.jpg" title="That guy">'
markdown = ''
assert_equal markdown, parse(html)
end
def test_script
html = %Q{<blockquote class="twitter-tweet"><p><a href="https://twitter.com/soffes">@soffes</a> If people think Apple is going to redo their promo videos and 3D animation intros for iOS 7 they're crazy. The design is ~final.</p>— Mike Rundle (@flyosity) <a href="https://twitter.com/flyosity/statuses/348358938296733696">June 22, 2013</a></blockquote>\n<script async src="//platform.twitter.com/widgets.js" charset="utf-8"></script>}
markdown = %Q{> [@soffes](https://twitter.com/soffes) If people think Apple is going to redo their promo videos and 3D animation intros for iOS 7 they're crazy. The design is ~final.\n> \n> — Mike Rundle (@flyosity) [June 22, 2013](https://twitter.com/flyosity/statuses/348358938296733696)}
assert_equal markdown, parse(html)
html = %Q{<blockquote class="twitter-tweet"><p><a href="https://twitter.com/soffes">@soffes</a> If people think Apple is going to redo their promo videos and 3D animation intros for iOS 7 they're crazy. The design is ~final.</p>— Mike Rundle (@flyosity) <a href="https://twitter.com/flyosity/statuses/348358938296733696">June 22, 2013</a></blockquote>\n<script async src="//platform.twitter.com/widgets.js" charset="utf-8"></script>}
markdown = %Q{> [@soffes](https://twitter.com/soffes) If people think Apple is going to redo their promo videos and 3D animation intros for iOS 7 they're crazy. The design is ~final.\n> \n> — Mike Rundle (@flyosity) [June 22, 2013](https://twitter.com/flyosity/statuses/348358938296733696)\n\n<script async src="//platform.twitter.com/widgets.js" charset="utf-8"></script>}
assert_equal markdown, parse(html, allow_scripts: true)
end
def test_autolink
html = 'Head to http://soff.es and email sam@soff.es'
assert_equal html, parse(html)
markdown = 'Head to <http://soff.es> and email <sam@soff.es>'
assert_equal markdown, parse(html, autolink: true)
end
def test_unknown
html = %Q{Some custom tag: <expand-note>hello</expand-note>. <span class="spoiler">a secret</span>}
assert_equal html, parse(html)
end
def test_comments
html = %Q{<!--One-line comment by itself-->
Line with an <!--inline comment--> inside
<!--
Block comment
-->
surrounding stuff
<!--
Block comment
-->
surrounding stuff}
assert_equal html, parse(html)
end
end
| ruby | MIT | 201a7df1e45a9ea071073d28e2f75efdf67d1413 | 2026-01-04T17:45:32.739897Z | false |
soffes/unmarkdown | https://github.com/soffes/unmarkdown/blob/201a7df1e45a9ea071073d28e2f75efdf67d1413/lib/unmarkdown.rb | lib/unmarkdown.rb | require 'unmarkdown/version'
require 'unmarkdown/parser'
module Unmarkdown
module_function
# Takes an HTML string and returns a Markdown string
def parse(html, options = {})
Parser.new(html, options).parse
end
end
| ruby | MIT | 201a7df1e45a9ea071073d28e2f75efdf67d1413 | 2026-01-04T17:45:32.739897Z | false |
soffes/unmarkdown | https://github.com/soffes/unmarkdown/blob/201a7df1e45a9ea071073d28e2f75efdf67d1413/lib/unmarkdown/version.rb | lib/unmarkdown/version.rb | module Unmarkdown
VERSION = '0.2.0'
end
| ruby | MIT | 201a7df1e45a9ea071073d28e2f75efdf67d1413 | 2026-01-04T17:45:32.739897Z | false |
soffes/unmarkdown | https://github.com/soffes/unmarkdown/blob/201a7df1e45a9ea071073d28e2f75efdf67d1413/lib/unmarkdown/parser.rb | lib/unmarkdown/parser.rb | require 'nokogiri'
module Unmarkdown
class Parser
BLOCK_ELEMENT_NAMES = %w{h1 h2 h3 h4 h5 h6 blockquote pre hr ul ol li p div}.freeze
AUTOLINK_URL_REGEX = /((?:https?|ftp):[^'"\s]+)/i.freeze
AUTOLINK_EMAIL_REGEX = %r{([-.\w]+\@[-a-z0-9]+(?:\.[-a-z0-9]+)*\.[a-z]+)}i.freeze
def initialize(html, options = {})
@html = html
@options = options
end
def parse
# If the HTML fragment starts with a comment, it is ignored. Add an
# enclosing body tag to ensure everything is included.
html = @html
unless html.include?('<body')
html = "<body>#{@html}</body>"
end
# Setup document
doc = Nokogiri::HTML(html)
doc.encoding = 'UTF-8'
# Reset bookkeeping
@list = []
@list_position = []
# Parse the root node recursively
root_node = doc.xpath('//body')
markdown = parse_nodes(root_node.children)
# Strip whitespace
markdown.rstrip.gsub(/\n{2}+/, "\n\n")
# TODO: Strip trailing whitespace
end
private
# Parse the children of a node
def parse_nodes(nodes)
output = ''
# Short-circuit if it's empty
return output if !nodes || nodes.empty?
# Loop through nodes
nodes.each do |node|
case node.name
when 'h1', 'h2', 'h3', 'h4', 'h5', 'h6'
level = node.name.match(/\Ah(\d)\Z/)[1].to_i
if @options[:underline_headers] && level < 3
content = parse_content(node)
output << content + "\n"
character = level == 1 ? '=' : '-'
content.length.times { output << character}
else
hashes = ''
level.times { hashes << '#' }
output << "#{hashes} #{parse_content(node)}"
end
when 'blockquote'
parse_content(node).split("\n").each do |line|
output << "> #{line}\n"
end
when 'ul', 'ol'
output << "\n\n" if @list.count > 0
if unordered = node.name == 'ul'
@list << :unordered
else
@list << :ordered
@list_position << 0
end
output << parse_nodes(node.children)
@list.pop
@list_position.pop unless unordered
when 'li'
(@list.count - 1).times { output << ' ' }
if @list.last == :unordered
output << "* #{parse_content(node)}"
else
num = (@list_position[@list_position.count - 1] += 1)
output << "#{num}. #{parse_content(node)}"
end
when 'pre'
content = parse_content(node)
if @options[:fenced_code_blocks]
output << "```\n#{content}\n```"
else
content.split("\n").each do |line|
output << " #{line}\n"
end
end
when 'hr'
output << "---\n\n"
when 'a'
output << "[#{parse_content(node)}](#{node['href']}#{build_title(node)})"
when 'i', 'em'
output << "*#{parse_content(node)}*"
when 'b', 'strong'
output << "**#{parse_content(node)}**"
when 'u'
output << "_#{parse_content(node)}_"
when 'mark'
output << "==#{parse_content(node)}=="
when 'code'
output << "`#{parse_content(node)}`"
when 'img'
output << "![#{node['alt']}](#{node['src']}#{build_title(node)})"
when 'text'
content = parse_content(node)
# Optionally look for links
content.gsub!(AUTOLINK_URL_REGEX, '<\1>') if @options[:autolink]
content.gsub!(AUTOLINK_EMAIL_REGEX, '<\1>') if @options[:autolink]
output << content
when 'script'
next unless @options[:allow_scripts]
output << node.to_html
when 'p'
output << parse_content(node)
else
# If it's an supported node or a node that just contains text, just append it
output << node.to_html
end
output << "\n\n" if BLOCK_ELEMENT_NAMES.include?(node.name)
end
output
end
# Get the content from a node
def parse_content(node)
if node.children.empty?
node.content
else
parse_nodes(node.children)
end
end
# Build the title for links or images
def build_title(node)
node['title'] ? %Q{ "#{node['title']}"} : ''
end
end
end
| ruby | MIT | 201a7df1e45a9ea071073d28e2f75efdf67d1413 | 2026-01-04T17:45:32.739897Z | false |
rsim/ruby-plsql | https://github.com/rsim/ruby-plsql/blob/7bee9ba2b3207de7c1ae4112d8af2636b586c610/spec/spec_helper.rb | spec/spec_helper.rb | require "rubygems"
require "bundler"
Bundler.setup(:default, :development)
unless ENV["NO_ACTIVERECORD"]
require "simplecov"
SimpleCov.configure do
load_profile "root_filter"
load_profile "test_frameworks"
end
ENV["COVERAGE"] && SimpleCov.start do
add_filter "/.rvm/"
end
end
$LOAD_PATH.unshift(File.join(File.dirname(__FILE__), "..", "lib"))
require "rspec"
unless ENV["NO_ACTIVERECORD"]
require "active_record"
else
puts "Without ActiveRecord"
end
require "ruby-plsql"
# Requires supporting ruby files with custom matchers and macros, etc,
# in spec/support/ and its subdirectories.
Dir[File.join(File.dirname(__FILE__), "support/**/*.rb")].each { |f| require f }
if ENV["USE_VM_DATABASE"] == "Y"
DATABASE_NAME = "XE"
else
DATABASE_NAME = ENV["DATABASE_NAME"] || "orcl"
end
DATABASE_SERVICE_NAME = (defined?(JRUBY_VERSION) ? "/" : "") +
(ENV["DATABASE_SERVICE_NAME"] || DATABASE_NAME)
DATABASE_HOST = ENV["DATABASE_HOST"] || "localhost"
DATABASE_PORT = (ENV["DATABASE_PORT"] || 1521).to_i
DATABASE_USERS_AND_PASSWORDS = [
[ENV["DATABASE_USER"] || "hr", ENV["DATABASE_PASSWORD"] || "hr"],
[ENV["DATABASE_USER2"] || "arunit", ENV["DATABASE_PASSWORD2"] || "arunit"]
]
# specify which database version is used (will be verified in one test)
DATABASE_VERSION = ENV["DATABASE_VERSION"] || "10.2.0.4"
if ENV["USE_VM_DATABASE"] == "Y"
RSpec.configure do |config|
config.before(:suite) do
TestDb.build
# Set Verbose off to hide warning: already initialized constant DATABASE_VERSION
original_verbosity = $VERBOSE
$VERBOSE = nil
DATABASE_VERSION = TestDb.database_version
$VERBOSE = original_verbosity
end
end
end
def oracle_error_class
unless defined?(JRUBY_VERSION)
OCIError
else
java.sql.SQLException
end
end
def get_eazy_connect_url(svc_separator = "")
"#{DATABASE_HOST}:#{DATABASE_PORT}#{svc_separator}#{DATABASE_SERVICE_NAME}"
end
def get_connection_url
unless defined?(JRUBY_VERSION)
(ENV["DATABASE_USE_TNS"] == "NO") ? get_eazy_connect_url("/") : DATABASE_NAME
else
"jdbc:oracle:thin:@#{get_eazy_connect_url}"
end
end
def get_connection(user_number = 0)
database_user, database_password = DATABASE_USERS_AND_PASSWORDS[user_number]
unless defined?(JRUBY_VERSION)
try_to_connect(OCIError) do
OCI8.new(database_user, database_password, get_connection_url)
end
else
try_to_connect(Java::JavaSql::SQLException) do
java.sql.DriverManager.getConnection(get_connection_url, database_user, database_password)
end
end
end
def try_to_connect(exception)
begin
yield
# if connection fails then sleep 5 seconds and retry
rescue exception
sleep 5
yield
end
end
CONNECTION_PARAMS = {
adapter: "oracle_enhanced",
database: DATABASE_SERVICE_NAME,
host: DATABASE_HOST,
port: DATABASE_PORT,
username: DATABASE_USERS_AND_PASSWORDS[0][0],
password: DATABASE_USERS_AND_PASSWORDS[0][1]
}
class Hash
def except(*blacklist)
self.reject { |key, value| blacklist.include?(key) }
end unless method_defined?(:except)
def only(*whitelist)
self.reject { |key, value| !whitelist.include?(key) }
end unless method_defined?(:only)
end
| ruby | MIT | 7bee9ba2b3207de7c1ae4112d8af2636b586c610 | 2026-01-04T17:45:33.227772Z | false |
rsim/ruby-plsql | https://github.com/rsim/ruby-plsql/blob/7bee9ba2b3207de7c1ae4112d8af2636b586c610/spec/plsql/version_spec.rb | spec/plsql/version_spec.rb | require "spec_helper"
describe "Version" do
it "should return ruby-plsql version" do
expect(PLSQL::VERSION).to eq(File.read(File.dirname(__FILE__) + "/../../VERSION").chomp)
end
end
| ruby | MIT | 7bee9ba2b3207de7c1ae4112d8af2636b586c610 | 2026-01-04T17:45:33.227772Z | false |
rsim/ruby-plsql | https://github.com/rsim/ruby-plsql/blob/7bee9ba2b3207de7c1ae4112d8af2636b586c610/spec/plsql/view_spec.rb | spec/plsql/view_spec.rb | require "spec_helper"
describe "View" do
before(:all) do
plsql.connect! CONNECTION_PARAMS
plsql.connection.autocommit = false
plsql.execute <<-SQL
CREATE TABLE test_employees (
employee_id NUMBER(15) NOT NULL,
first_name VARCHAR2(50),
last_name VARCHAR2(50),
hire_date DATE,
status VARCHAR2(1) DEFAULT 'N'
)
SQL
plsql.execute "CREATE OR REPLACE VIEW test_employees_v AS SELECT * FROM test_employees"
@employees = (1..10).map do |i|
{
employee_id: i,
first_name: "First #{i}",
last_name: "Last #{i}",
hire_date: Time.local(2000, 01, i),
status: "A"
}
end
@employees_all_fields = [:employee_id, :first_name, :last_name, :hire_date, :status]
@employees_all_values = @employees.map { |e| @employees_all_fields.map { |f| e[f] } }
@employees_some_fields = [:employee_id, :first_name, :last_name]
@employees_some_values = @employees.map { |e| @employees_some_fields.map { |f| e[f] } }
@employee_default_values = { hire_date: nil, status: "N" }
end
after(:all) do
plsql.execute "DROP VIEW test_employees_v"
plsql.execute "DROP TABLE test_employees"
plsql.logoff
end
after(:each) do
plsql.rollback
end
describe "find" do
it "should find existing view" do
expect(PLSQL::View.find(plsql, :test_employees_v)).not_to be_nil
end
it "should not find nonexisting view" do
expect(PLSQL::View.find(plsql, :qwerty123456)).to be_nil
end
it "should find existing view in schema" do
expect(plsql.test_employees_v).to be_instance_of(PLSQL::View)
end
end
describe "synonym" do
before(:all) do
plsql.execute "CREATE SYNONYM test_employees_v_synonym FOR hr.test_employees_v"
end
after(:all) do
plsql.execute "DROP SYNONYM test_employees_v_synonym" rescue nil
end
it "should find synonym to view" do
expect(PLSQL::View.find(plsql, :test_employees_v_synonym)).not_to be_nil
end
it "should find view using synonym in schema" do
expect(plsql.test_employees_v_synonym).to be_instance_of(PLSQL::View)
end
end
describe "public synonym" do
it "should find public synonym to view" do
expect(PLSQL::View.find(plsql, :user_tables)).not_to be_nil
end
it "should find view using public synonym in schema" do
expect(plsql.user_tables).to be_instance_of(PLSQL::View)
end
end
describe "columns" do
it "should get column names for view" do
expect(plsql.test_employees_v.column_names).to eq([:employee_id, :first_name, :last_name, :hire_date, :status])
end
it "should get columns metadata for view" do
expect(plsql.test_employees_v.columns).to eq(
employee_id: {
position: 1, data_type: "NUMBER", data_length: 22, data_precision: 15, data_scale: 0, char_used: nil,
type_owner: nil, type_name: nil, sql_type_name: nil, nullable: false, data_default: nil },
first_name: {
position: 2, data_type: "VARCHAR2", data_length: 50, data_precision: nil, data_scale: nil, char_used: "B",
type_owner: nil, type_name: nil, sql_type_name: nil, nullable: true, data_default: nil },
last_name: {
position: 3, data_type: "VARCHAR2", data_length: 50, data_precision: nil, data_scale: nil, char_used: "B",
type_owner: nil, type_name: nil, sql_type_name: nil, nullable: true, data_default: nil },
hire_date: {
position: 4, data_type: "DATE", data_length: 7, data_precision: nil, data_scale: nil, char_used: nil,
type_owner: nil, type_name: nil, sql_type_name: nil, nullable: true, data_default: nil },
status: {
position: 5, data_type: "VARCHAR2", data_length: 1, data_precision: nil, data_scale: nil, char_used: "B",
type_owner: nil, type_name: nil, sql_type_name: nil, nullable: true, data_default: nil }
)
end
end
describe "insert" do
it "should insert a record in view" do
plsql.test_employees_v.insert @employees.first
expect(plsql.test_employees_v.all).to eq([@employees.first])
end
it "should insert a record in view using partial list of columns" do
plsql.test_employees_v.insert @employees.first.except(:hire_date)
expect(plsql.test_employees_v.all).to eq([@employees.first.merge(hire_date: nil)])
end
it "should insert default value from table definition if value not provided" do
plsql.test_employees_v.insert @employees.first.except(:status)
expect(plsql.test_employees_v.all).to eq([@employees.first.merge(status: "N")])
end
it "should insert array of records in view" do
plsql.test_employees_v.insert @employees
expect(plsql.test_employees_v.all("ORDER BY employee_id")).to eq(@employees)
end
end
describe "insert values" do
it "should insert a record with array of values" do
plsql.test_employees_v.insert_values @employees_all_values.first
expect(plsql.test_employees_v.all).to eq([@employees.first])
end
it "should insert a record with list of all fields and array of values" do
plsql.test_employees_v.insert_values @employees_all_fields, @employees_all_values.first
expect(plsql.test_employees_v.all).to eq([@employees.first])
end
it "should insert a record with list of some fields and array of values" do
plsql.test_employees_v.insert_values @employees_some_fields, @employees_some_values.first
expect(plsql.test_employees_v.all).to eq([@employees.first.merge(@employee_default_values)])
end
it "should insert many records with array of values" do
plsql.test_employees_v.insert_values *@employees_all_values
expect(plsql.test_employees_v.all).to eq(@employees)
end
it "should insert many records with list of all fields and array of values" do
plsql.test_employees_v.insert_values @employees_all_fields, *@employees_all_values
expect(plsql.test_employees_v.all).to eq(@employees)
end
it "should insert many records with list of some fields and array of values" do
plsql.test_employees_v.insert_values @employees_some_fields, *@employees_some_values
expect(plsql.test_employees_v.all).to eq(@employees.map { |e| e.merge(@employee_default_values) })
end
end
describe "select" do
before(:each) do
plsql.test_employees_v.insert @employees
end
it "should select first record in view" do
expect(plsql.test_employees_v.select(:first, "ORDER BY employee_id")).to eq(@employees.first)
expect(plsql.test_employees_v.first("ORDER BY employee_id")).to eq(@employees.first)
end
it "should select all records in view" do
expect(plsql.test_employees_v.select(:all, "ORDER BY employee_id")).to eq(@employees)
expect(plsql.test_employees_v.all("ORDER BY employee_id")).to eq(@employees)
expect(plsql.test_employees_v.all(order_by: :employee_id)).to eq(@employees)
end
it "should select record in view using WHERE condition" do
expect(plsql.test_employees_v.select(:first, "WHERE employee_id = :1", @employees.first[:employee_id])).to eq(@employees.first)
expect(plsql.test_employees_v.first("WHERE employee_id = :1", @employees.first[:employee_id])).to eq(@employees.first)
expect(plsql.test_employees_v.first(employee_id: @employees.first[:employee_id])).to eq(@employees.first)
end
it "should select record in view using :column => nil condition" do
employee = @employees.last
employee[:employee_id] = employee[:employee_id] + 1
employee[:hire_date] = nil
plsql.test_employees_v.insert employee
expect(plsql.test_employees_v.first("WHERE hire_date IS NULL")).to eq(employee)
expect(plsql.test_employees_v.first(hire_date: nil)).to eq(employee)
end
it "should count records in view" do
expect(plsql.test_employees_v.select(:count)).to eq(@employees.size)
expect(plsql.test_employees_v.count).to eq(@employees.size)
end
it "should count records in view using condition" do
expect(plsql.test_employees_v.select(:count, "WHERE employee_id <= :1", @employees[2][:employee_id])).to eq(3)
expect(plsql.test_employees_v.count("WHERE employee_id <= :1", @employees[2][:employee_id])).to eq(3)
end
end
describe "update" do
it "should update a record in view" do
employee_id = @employees.first[:employee_id]
plsql.test_employees_v.insert @employees.first
plsql.test_employees_v.update first_name: "Test", where: { employee_id: employee_id }
expect(plsql.test_employees_v.first(employee_id: employee_id)[:first_name]).to eq("Test")
end
it "should update a record in view using String WHERE condition" do
employee_id = @employees.first[:employee_id]
plsql.test_employees_v.insert @employees
plsql.test_employees_v.update first_name: "Test", where: "employee_id = #{employee_id}"
expect(plsql.test_employees_v.first(employee_id: employee_id)[:first_name]).to eq("Test")
# all other records should not be changed
plsql.test_employees_v.all("WHERE employee_id > :1", employee_id) do |employee|
expect(employee[:first_name]).not_to eq("Test")
end
end
it "should update all records in view" do
plsql.test_employees_v.insert @employees
plsql.test_employees_v.update first_name: "Test"
plsql.test_employees_v.all do |employee|
expect(employee[:first_name]).to eq("Test")
end
end
end
describe "delete" do
it "should delete record from view" do
employee_id = @employees.first[:employee_id]
plsql.test_employees_v.insert @employees
plsql.test_employees_v.delete employee_id: employee_id
expect(plsql.test_employees_v.first(employee_id: employee_id)).to be_nil
expect(plsql.test_employees_v.all(order_by: :employee_id)).to eq(@employees[1, @employees.size - 1])
end
it "should delete all records from view" do
plsql.test_employees_v.insert @employees
plsql.test_employees_v.delete
expect(plsql.test_employees_v.all).to be_empty
end
end
end
| ruby | MIT | 7bee9ba2b3207de7c1ae4112d8af2636b586c610 | 2026-01-04T17:45:33.227772Z | false |
rsim/ruby-plsql | https://github.com/rsim/ruby-plsql/blob/7bee9ba2b3207de7c1ae4112d8af2636b586c610/spec/plsql/package_spec.rb | spec/plsql/package_spec.rb | require "spec_helper"
describe "Package" do
before(:all) do
plsql.connection = get_connection
plsql.execute <<-SQL
CREATE OR REPLACE PACKAGE test_package IS
test_variable NUMBER;
FUNCTION test_procedure ( p_string VARCHAR2 )
RETURN VARCHAR2;
END;
SQL
plsql.execute <<-SQL
CREATE OR REPLACE PACKAGE BODY test_package IS
FUNCTION test_procedure ( p_string VARCHAR2 )
RETURN VARCHAR2
IS
BEGIN
RETURN UPPER(p_string);
END test_procedure;
END;
SQL
end
after(:all) do
plsql.execute "DROP PACKAGE test_package"
plsql.logoff
end
before(:each) do
end
it "should find existing package" do
expect(PLSQL::Package.find(plsql, :test_package)).not_to be_nil
end
it "should not find nonexisting package" do
expect(PLSQL::Package.find(plsql, :qwerty123456)).to be_nil
end
it "should find existing package in schema" do
expect(plsql.test_package.class).to eq(PLSQL::Package)
end
it "should execute package function and return correct value" do
expect(plsql.test_package.test_procedure("xxx")).to eq("XXX")
end
it "should report an existing procedure as existing" do
expect(plsql.test_package.procedure_defined?(:test_procedure)).to be_truthy
end
it "should report an inexistent procedure as not existing" do
expect(plsql.test_package.procedure_defined?(:inexistent_procedure)).to be_falsey
end
it "should search objects via []" do
package = PLSQL::Package.find(plsql, :test_package)
[:Test_Procedure, :test_procedure, "test_procedure", "TEST_PROCEDURE"].each do |name_variant|
expect(package[name_variant]).to be_a PLSQL::Procedure
end
[:Test_Variable, :test_variable, "test_variable", "TEST_VARIABLE"].each do |name_variant|
expect(package[name_variant]).to be_a PLSQL::Variable
end
end
context "with a user with execute privilege who is not the package owner" do
before(:all) do
plsql.execute("grant execute on TEST_PACKAGE to #{DATABASE_USERS_AND_PASSWORDS[1][0]}")
@original_connection = plsql.connection
@conn = get_connection(1)
end
before(:each) do
# resetting connection clears cached package objects and schema name
plsql.connection = @conn
end
after(:all) do
plsql.logoff
plsql.connection = @original_connection
end
it "should not find existing package" do
expect(PLSQL::Package.find(plsql, :test_package)).to be_nil
end
context "who sets current_schema to match the package owner" do
before(:all) do
plsql.execute "ALTER SESSION set current_schema=#{DATABASE_USERS_AND_PASSWORDS[0][0]}"
end
it "should find existing package" do
expect(PLSQL::Package.find(plsql, :test_package)).not_to be_nil
end
it "should report an existing procedure as existing" do
expect(plsql.test_package.procedure_defined?(:test_procedure)).to be_truthy
end
end
end
describe "variables" do
it "should set and get package variable value" do
plsql.test_package.test_variable = 1
expect(plsql.test_package.test_variable).to eq(1)
end
end
end
describe "Synonym to package" do
before(:all) do
plsql.connection = get_connection
plsql.execute <<-SQL
CREATE OR REPLACE PACKAGE hr.test_package IS
FUNCTION test_procedure ( p_string VARCHAR2 )
RETURN VARCHAR2;
END;
SQL
plsql.execute <<-SQL
CREATE OR REPLACE PACKAGE BODY hr.test_package IS
FUNCTION test_procedure ( p_string VARCHAR2 )
RETURN VARCHAR2
IS
BEGIN
RETURN UPPER(p_string);
END test_procedure;
END;
SQL
plsql.execute "CREATE SYNONYM test_pkg_synonym FOR hr.test_package"
end
after(:all) do
plsql.execute "DROP SYNONYM test_pkg_synonym" rescue nil
plsql.logoff
end
it "should find synonym to package" do
expect(PLSQL::Package.find(plsql, :test_pkg_synonym)).not_to be_nil
end
it "should execute package function using synonym and return correct value" do
expect(plsql.test_pkg_synonym.test_procedure("xxx")).to eq("XXX")
end
end
describe "Public synonym to package" do
before(:all) do
plsql.connection = get_connection
end
after(:all) do
plsql.logoff
end
it "should find public synonym to package" do
expect(PLSQL::Package.find(plsql, :utl_encode)).not_to be_nil
end
it "should execute package function using public synonym and return correct value" do
expect(plsql.utl_encode.base64_encode("abc")).to eq("4372773D")
end
end
| ruby | MIT | 7bee9ba2b3207de7c1ae4112d8af2636b586c610 | 2026-01-04T17:45:33.227772Z | false |
rsim/ruby-plsql | https://github.com/rsim/ruby-plsql/blob/7bee9ba2b3207de7c1ae4112d8af2636b586c610/spec/plsql/sql_statements_spec.rb | spec/plsql/sql_statements_spec.rb | require "spec_helper"
describe "SQL statements /" do
before(:all) do
plsql.connect! CONNECTION_PARAMS
plsql.connection.autocommit = false
end
after(:all) do
plsql.logoff
end
after(:each) do
plsql.rollback
end
describe "SELECT" do
before(:all) do
plsql.execute "DROP TABLE test_employees" rescue nil
plsql.execute <<-SQL
CREATE TABLE test_employees (
employee_id NUMBER(15),
first_name VARCHAR2(50),
last_name VARCHAR(50),
hire_date DATE
)
SQL
plsql.execute <<-SQL
CREATE OR REPLACE PROCEDURE test_insert_employee(p_employee test_employees%ROWTYPE)
IS
BEGIN
INSERT INTO test_employees
VALUES p_employee;
END;
SQL
@employees = (1..10).map do |i|
{
employee_id: i,
first_name: "First #{i}",
last_name: "Last #{i}",
hire_date: Time.local(2000, 01, i)
}
end
plsql.connection.prefetch_rows = 100
end
before(:each) do
@employees.each do |e|
plsql.test_insert_employee(e)
end
end
after(:all) do
plsql.execute "DROP PROCEDURE test_insert_employee"
plsql.execute "DROP TABLE test_employees"
plsql.connection.prefetch_rows = 1
end
it "should select first result" do
expect(plsql.select(:first, "SELECT * FROM test_employees WHERE employee_id = :employee_id",
@employees.first[:employee_id])).to eq(@employees.first)
end
it "should prefetch only one row when selecting first result" do
expect {
plsql.select(:first, "SELECT 1 FROM dual UNION ALL SELECT 1/0 FROM dual")
}.not_to raise_error
end
it "should select one value" do
expect(plsql.select_one("SELECT count(*) FROM test_employees")).to eq(@employees.size)
end
it "should return nil when selecting non-existing one value" do
expect(plsql.select_one("SELECT employee_id FROM test_employees WHERE 1=2")).to be_nil
end
it "should prefetch only one row when selecting one value" do
expect {
plsql.select_one("SELECT 1 FROM dual UNION ALL SELECT 1/0 FROM dual")
}.not_to raise_error
end
it "should select all results" do
expect(plsql.select(:all, "SELECT * FROM test_employees ORDER BY employee_id")).to eq(@employees)
expect(plsql.select("SELECT * FROM test_employees ORDER BY employee_id")).to eq(@employees)
end
end
end
| ruby | MIT | 7bee9ba2b3207de7c1ae4112d8af2636b586c610 | 2026-01-04T17:45:33.227772Z | false |
rsim/ruby-plsql | https://github.com/rsim/ruby-plsql/blob/7bee9ba2b3207de7c1ae4112d8af2636b586c610/spec/plsql/type_spec.rb | spec/plsql/type_spec.rb | require "spec_helper"
describe "Type" do
before(:all) do
plsql.connection = get_connection
plsql.execute "DROP TYPE t_employee" rescue nil
plsql.execute "DROP TYPE t_phones" rescue nil
plsql.execute "DROP TYPE t_phone" rescue nil
plsql.execute <<-SQL
CREATE OR REPLACE TYPE t_address AS OBJECT (
street VARCHAR2(50),
city VARCHAR2(50),
country VARCHAR2(50),
CONSTRUCTOR FUNCTION t_address(p_full_address VARCHAR2)
RETURN SELF AS RESULT,
MEMBER FUNCTION display_address(p_separator VARCHAR2 DEFAULT ',') RETURN VARCHAR2,
MEMBER FUNCTION display_address(p_uppercase BOOLEAN, p_separator VARCHAR2 DEFAULT ',') RETURN VARCHAR2,
MEMBER PROCEDURE set_country(p_country VARCHAR2),
MEMBER PROCEDURE set_country2(p_country VARCHAR2, x_display_address OUT VARCHAR2),
STATIC FUNCTION create_address(p_full_address VARCHAR2) RETURN t_address
);
SQL
plsql.execute <<-SQL
CREATE OR REPLACE TYPE BODY t_address AS
CONSTRUCTOR FUNCTION t_address(p_full_address VARCHAR2)
RETURN SELF AS RESULT
AS
l_comma1_pos INTEGER;
l_comma2_pos INTEGER;
BEGIN
l_comma1_pos := INSTR(p_full_address, ',', 1, 1);
l_comma2_pos := INSTR(p_full_address, ',', 1, 2);
SELF.street := TRIM(SUBSTR(p_full_address, 1, l_comma1_pos - 1));
SELF.city := TRIM(SUBSTR(p_full_address, l_comma1_pos+1, l_comma2_pos - l_comma1_pos - 1));
SELF.country := TRIM(SUBSTR(p_full_address, l_comma2_pos+1));
RETURN;
END;
MEMBER FUNCTION display_address(p_separator VARCHAR2) RETURN VARCHAR2 IS
l_separator VARCHAR2(10) := p_separator;
BEGIN
IF SUBSTR(l_separator,-1) != ' ' THEN
l_separator := l_separator || ' ';
END IF;
RETURN SELF.street || l_separator || SELF.city || l_separator || SELF.country;
END;
MEMBER FUNCTION display_address(p_uppercase BOOLEAN, p_separator VARCHAR2) RETURN VARCHAR2 IS
l_separator VARCHAR2(10) := p_separator;
BEGIN
IF p_uppercase THEN
RETURN UPPER(SELF.display_address(p_separator));
ELSE
RETURN SELF.display_address(p_separator);
END IF;
END;
MEMBER PROCEDURE set_country(p_country VARCHAR2) IS
BEGIN
SELF.country := p_country;
END;
MEMBER PROCEDURE set_country2(p_country VARCHAR2, x_display_address OUT VARCHAR2) IS
BEGIN
SELF.country := p_country;
x_display_address := SELF.display_address();
END;
STATIC FUNCTION create_address(p_full_address VARCHAR2) RETURN t_address IS
BEGIN
RETURN t_address(p_full_address);
END;
END;
SQL
plsql.execute <<-SQL
CREATE OR REPLACE TYPE t_phone AS OBJECT (
type VARCHAR2(10),
phone_number VARCHAR2(50)
)
SQL
plsql.execute <<-SQL
CREATE OR REPLACE TYPE t_phones AS VARRAY(10) OF T_PHONE
SQL
plsql.execute <<-SQL
CREATE OR REPLACE TYPE t_employee AS OBJECT (
employee_id NUMBER(15),
first_name VARCHAR2(50),
last_name VARCHAR(50),
hire_date DATE,
address t_address,
phones t_phones
)
SQL
end
after(:all) do
plsql.execute "DROP TYPE t_employee"
plsql.execute "DROP TYPE t_address"
plsql.execute "DROP TYPE t_phones"
plsql.execute "DROP TYPE t_phone"
plsql.logoff
end
after(:each) do
plsql.rollback
end
describe "find" do
it "should find existing type" do
expect(PLSQL::Type.find(plsql, :t_employee)).not_to be_nil
end
it "should not find nonexisting type" do
expect(PLSQL::Type.find(plsql, :qwerty123456)).to be_nil
end
it "should find existing type in schema" do
expect(plsql.t_employee).to be_a(PLSQL::Type)
end
end
describe "synonym" do
before(:all) do
plsql.execute "CREATE SYNONYM t_employee_synonym FOR hr.t_employee"
end
after(:all) do
plsql.execute "DROP SYNONYM t_employee_synonym" rescue nil
end
it "should find synonym to type" do
expect(PLSQL::Type.find(plsql, :t_employee_synonym)).not_to be_nil
end
it "should find type using synonym in schema" do
expect(plsql.t_employee_synonym).to be_a(PLSQL::Type)
end
end
describe "public synonym" do
it "should find public synonym to type" do
expect(PLSQL::Type.find(plsql, :xmltype)).not_to be_nil
end
it "should find type using public synonym in schema" do
expect(plsql.xmltype).to be_a(PLSQL::Type)
end
end
describe "typecode" do
it "should get typecode of object type" do
expect(plsql.t_employee.typecode).to eq("OBJECT")
end
it "should get typecode of collection type" do
expect(plsql.t_phones.typecode).to eq("COLLECTION")
end
end
describe "attributes" do
it "should get attribute names" do
expect(plsql.t_employee.attribute_names).to eq([:employee_id, :first_name, :last_name, :hire_date, :address, :phones])
end
it "should get attributes metadata" do
expect(plsql.t_employee.attributes).to eq(
employee_id: { position: 1, data_type: "NUMBER", data_length: nil, data_precision: 15, data_scale: 0, type_owner: nil, type_name: nil, sql_type_name: nil },
first_name: { position: 2, data_type: "VARCHAR2", data_length: 50, data_precision: nil, data_scale: nil, type_owner: nil, type_name: nil, sql_type_name: nil },
last_name: { position: 3, data_type: "VARCHAR2", data_length: 50, data_precision: nil, data_scale: nil, type_owner: nil, type_name: nil, sql_type_name: nil },
hire_date: { position: 4, data_type: "DATE", data_length: nil, data_precision: nil, data_scale: nil, type_owner: nil, type_name: nil, sql_type_name: nil },
address: { position: 5, data_type: "OBJECT", data_length: nil, data_precision: nil, data_scale: nil, type_owner: "HR", type_name: "T_ADDRESS", sql_type_name: "HR.T_ADDRESS" },
phones: { position: 6, data_type: "TABLE", data_length: nil, data_precision: nil, data_scale: nil, type_owner: "HR", type_name: "T_PHONES", sql_type_name: "HR.T_PHONES" }
)
end
end
describe "object instance" do
before(:all) do
@phone_attributes = { type: "mobile", phone_number: "123456" }
@address_attributes = { street: "Street", city: "City", country: "Country" }
@full_address = "#{@address_attributes[:street]}, #{@address_attributes[:city]}, #{@address_attributes[:country]}"
end
it "should get new object instance using named parameters" do
expect(plsql.t_phone(@phone_attributes)).to eq(@phone_attributes)
end
it "should be an ObjectInstance" do
expect(plsql.t_phone(@phone_attributes)).to be_a(PLSQL::ObjectInstance)
end
it "should get new object instance using sequential parameters" do
expect(plsql.t_phone(@phone_attributes[:type], @phone_attributes[:phone_number])).to eq(@phone_attributes)
end
it "should get new object instance using custom constructor" do
expect(plsql.t_address(@full_address)).to eq(@address_attributes)
expect(plsql.t_address(p_full_address: @full_address)).to eq(@address_attributes)
end
it "should get new object instance using default constructor when custom constructor exists" do
expect(plsql.t_address(@address_attributes)).to eq(@address_attributes)
expect(plsql.t_address(@address_attributes[:street], @address_attributes[:city], @address_attributes[:country])).to eq(@address_attributes)
end
it "should get new empty collection of objects instance" do
expect(plsql.t_phones.new).to eq([])
expect(plsql.t_phones([])).to eq([])
end
it "should get new collection of objects instances" do
phone = plsql.t_phone(@phone_attributes)
expect(plsql.t_phones([phone, phone])).to eq([phone, phone])
expect(plsql.t_phones(phone, phone)).to eq([phone, phone])
expect(plsql.t_phones(@phone_attributes, @phone_attributes)).to eq([phone, phone])
end
end
describe "member procedures" do
before(:all) do
@address_attributes = { street: "Street", city: "City", country: "Country" }
@full_address = "#{@address_attributes[:street]}, #{@address_attributes[:city]}, #{@address_attributes[:country]}"
end
it "should call object instance member function without parameters" do
expect(plsql.t_address(@address_attributes).display_address).to eq(@full_address)
end
it "should call object instance member function with parameters" do
expect(plsql.t_address(@address_attributes).display_address(",")).to eq(@full_address)
end
it "should call object instance member function with named parameters" do
expect(plsql.t_address(@address_attributes).display_address(p_separator: ",")).to eq(@full_address)
end
it "should call object overloaded instance member function" do
expect(plsql.t_address(@address_attributes).display_address(true)).to eq(@full_address.upcase)
expect(plsql.t_address(@address_attributes).display_address(true, ",")).to eq(@full_address.upcase)
end
it "should call object instance member function with explicit first SELF parameter" do
expect(plsql.t_address.display_address(@address_attributes, ",")).to eq(@full_address)
end
it "should call object instance member function with explicit named SELF parameter" do
expect(plsql.t_address.display_address(self: @address_attributes, p_separator: ",")).to eq(@full_address)
end
it "should call object instance member procedure" do
other_country = "Other"
expect(plsql.t_address(@address_attributes).set_country(other_country)).to eq(@address_attributes.merge(country: other_country))
end
it "should call object instance member procedure with output parameters" do
other_country = "Other"
expect(plsql.t_address(@address_attributes).set_country2(other_country)).to eq(
[@address_attributes.merge(country: other_country),
{ x_display_address: "#{@address_attributes[:street]}, #{@address_attributes[:city]}, #{other_country}" }]
)
end
it "should raise error if invalid member procedure is called" do
expect do
plsql.t_address(@address_attributes).invalid_procedure
end.to raise_error(ArgumentError)
end
end
describe "static procedures" do
before(:all) do
@address_attributes = { street: "Street", city: "City", country: "Country" }
@full_address = "#{@address_attributes[:street]}, #{@address_attributes[:city]}, #{@address_attributes[:country]}"
end
it "should call object type static function" do
expect(plsql.t_address.create_address(@full_address)).to eq(@address_attributes)
end
it "should call object type static function with named parameters" do
expect(plsql.t_address.create_address(p_full_address: @full_address)).to eq(@address_attributes)
end
it "should raise error if invalid static procedure is called" do
expect do
plsql.t_address.invalid_procedure
end.to raise_error(ArgumentError)
end
end
end
| ruby | MIT | 7bee9ba2b3207de7c1ae4112d8af2636b586c610 | 2026-01-04T17:45:33.227772Z | false |
rsim/ruby-plsql | https://github.com/rsim/ruby-plsql/blob/7bee9ba2b3207de7c1ae4112d8af2636b586c610/spec/plsql/procedure_spec.rb | spec/plsql/procedure_spec.rb | # encoding: utf-8
require "spec_helper"
describe "Parameter type mapping /" do
shared_examples "Function with string parameters" do |datatype|
before(:all) do
plsql.connect! CONNECTION_PARAMS
plsql.execute <<-SQL
CREATE OR REPLACE FUNCTION test_uppercase
( p_string #{datatype} )
RETURN #{datatype}
IS
BEGIN
RETURN UPPER(p_string);
END test_uppercase;
SQL
end
after(:all) do
plsql.execute "DROP FUNCTION test_uppercase"
plsql.logoff
end
it "should find existing procedure" do
expect(PLSQL::Procedure.find(plsql, :test_uppercase)).not_to be_nil
end
it "should not find nonexisting procedure" do
expect(PLSQL::Procedure.find(plsql, :qwerty123456)).to be_nil
end
it "should execute function and return correct value" do
expect(plsql.test_uppercase("xxx")).to eq("XXX")
end
it "should execute function with named parameters and return correct value" do
expect(plsql.test_uppercase(p_string: "xxx")).to eq("XXX")
end
it "should raise error if wrong number of arguments is passed" do
expect { plsql.test_uppercase("xxx", "yyy") }.to raise_error(ArgumentError)
end
it "should raise error if wrong named argument is passed" do
expect { plsql.test_uppercase(p_string2: "xxx") }.to raise_error(ArgumentError)
end
it "should execute function with schema name specified" do
expect(plsql.hr.test_uppercase("xxx")).to eq("XXX")
end
it "should process nil parameter as NULL" do
expect(plsql.test_uppercase(nil)).to be_nil
end
end
["VARCHAR", "VARCHAR2"].each do |datatype|
describe "Function with #{datatype} parameters" do
it_should_behave_like "Function with string parameters", datatype
end
end
shared_examples "Function with numeric" do |ora_data_type, class_, num1, num2, expected, mandatory|
before(:all) do
plsql.connect! CONNECTION_PARAMS
plsql.execute <<-SQL
CREATE OR REPLACE FUNCTION test_sum
( p_num1 #{ora_data_type}, p_num2 #{ora_data_type} )
RETURN #{ora_data_type}
IS
BEGIN
RETURN p_num1 + p_num2;
END test_sum;
SQL
end
after(:all) do
plsql.execute "DROP FUNCTION test_sum"
plsql.logoff
end
it "should get #{ora_data_type} variable type mapped to #{class_.to_s}" do
expect(plsql.test_sum(num1, num2)).to be_a class_
end
it "should process input parameters and return correct result" do
expect(plsql.test_sum(num1, num2)).to eq(expected)
end
it "should process nil parameter as NULL" do
expect(plsql.test_sum(num1, nil)).to be_nil
end unless mandatory
end
@big_number = ("1234567890" * 3).to_i
[
{ ora_data_type: "INTEGER", class: Integer, num1: @big_number, num2: @big_number, expected: @big_number * 2 },
{ ora_data_type: "NUMBER", class: BigDecimal, num1: 12345.12345, num2: 12345.12345, expected: 24690.2469 },
{ ora_data_type: "PLS_INTEGER", class: Integer, num1: 123456789, num2: 123456789, expected: 246913578 },
{ ora_data_type: "BINARY_INTEGER", class: Integer, num1: 123456789, num2: 123456789, expected: 246913578 },
{ ora_data_type: "SIMPLE_INTEGER", class: Integer, num1: 123456789, num2: 123456789, expected: 246913578, mandatory: true },
{ ora_data_type: "NATURAL", class: Integer, num1: 123456789, num2: 123456789, expected: 246913578 },
{ ora_data_type: "NATURALN", class: Integer, num1: 123456789, num2: 123456789, expected: 246913578, mandatory: true },
{ ora_data_type: "POSITIVE", class: Integer, num1: 123456789, num2: 123456789, expected: 246913578 },
{ ora_data_type: "POSITIVEN", class: Integer, num1: 123456789, num2: 123456789, expected: 246913578, mandatory: true },
{ ora_data_type: "SIGNTYPE", class: Integer, num1: 1, num2: -1, expected: 0 },
].each do |row|
ora_data_type, class_, num1, num2, expected, mandatory = row.values
describe ora_data_type do
include_examples "Function with numeric", ora_data_type, class_, num1, num2, expected, mandatory
end
end
describe "Boolean to NUMBER conversion" do
before(:all) do
plsql.connect! CONNECTION_PARAMS
plsql.execute <<-SQL
CREATE OR REPLACE FUNCTION test_num ( p_num NUMBER) RETURN NUMBER
IS
BEGIN
RETURN p_num;
END test_num;
SQL
end
after(:all) do
plsql.execute "DROP FUNCTION test_num"
plsql.logoff
end
it "should convert true value to 1 for NUMBER parameter" do
expect(plsql.test_num(true)).to eq(1)
end
it "should convert false value to 0 for NUMBER parameter" do
expect(plsql.test_num(false)).to eq(0)
end
end
describe "Function with date parameters" do
before(:all) do
plsql.connect! CONNECTION_PARAMS
plsql.execute <<-SQL
CREATE OR REPLACE FUNCTION test_date
( p_date DATE )
RETURN DATE
IS
BEGIN
RETURN p_date + 1;
END test_date;
SQL
end
before(:each) do
plsql.default_timezone = :local
end
after(:all) do
plsql.execute "DROP FUNCTION test_date"
plsql.logoff
end
it "should process Time parameters" do
now = Time.local(2008, 8, 12, 14, 28, 0)
expect(plsql.test_date(now)).to eq(now + 60 * 60 * 24)
end
it "should process UTC Time parameters" do
plsql.default_timezone = :utc
now = Time.utc(2008, 8, 12, 14, 28, 0)
expect(plsql.test_date(now)).to eq(now + 60 * 60 * 24)
end
it "should process DateTime parameters" do
now = DateTime.parse(Time.local(2008, 8, 12, 14, 28, 0).iso8601)
result = plsql.test_date(now)
expect(result.class).to eq(Time)
expect(result).to eq(Time.parse((now + 1).strftime("%c")))
end
it "should process old DateTime parameters" do
now = DateTime.civil(1901, 1, 1, 12, 0, 0, plsql.local_timezone_offset)
result = plsql.test_date(now)
expect(result.class).to eq(Time)
expect(result).to eq(Time.parse((now + 1).strftime("%c")))
end
it "should process Date parameters" do
now = Date.new(2008, 8, 12)
result = plsql.test_date(now)
expect(result.class).to eq(Time)
expect(result).to eq(Time.parse((now + 1).strftime("%c")))
end
it "should process old Date parameters" do
now = Date.new(1901, 1, 1)
result = plsql.test_date(now)
expect(result.class).to eq(Time)
expect(result).to eq(Time.parse((now + 1).strftime("%c")))
end
it "should process nil date parameter as NULL" do
expect(plsql.test_date(nil)).to be_nil
end
end
describe "Function with timestamp parameters" do
before(:all) do
plsql.connect! CONNECTION_PARAMS
plsql.execute <<-SQL
CREATE OR REPLACE FUNCTION test_timestamp
( p_time TIMESTAMP )
RETURN TIMESTAMP
IS
BEGIN
RETURN p_time + NUMTODSINTERVAL(1, 'DAY');
END test_timestamp;
SQL
end
after(:all) do
plsql.execute "DROP FUNCTION test_timestamp"
plsql.logoff
end
it "should process timestamp parameters" do
# now = Time.now
now = Time.local(2008, 8, 12, 14, 28, 0)
expect(plsql.test_timestamp(now)).to eq(now + 60 * 60 * 24)
end
end
describe "Function or procedure with XMLType parameters" do
before(:all) do
plsql.connect! CONNECTION_PARAMS
@oracle12c_or_higher = !! plsql.connection.select_all(
"select * from product_component_version where product like 'Oracle%' and to_number(substr(version,1,2)) >= 12")
skip "Skip until furtuer investigation for #114" if @oracle12c_or_higher
plsql.execute <<-SQL
CREATE OR REPLACE FUNCTION test_xmltype
( p_xml XMLTYPE )
RETURN XMLTYPE
IS
BEGIN
RETURN p_xml;
END test_xmltype;
SQL
plsql.execute <<-SQL
CREATE OR REPLACE PROCEDURE test_xmltype2
( p_xml XMLTYPE, po_xml OUT XMLTYPE )
IS
BEGIN
po_xml := p_xml;
END test_xmltype2;
SQL
end
after(:all) do
plsql.execute "DROP FUNCTION test_xmltype" unless @oracle12c_or_higher
plsql.execute "DROP PROCEDURE test_xmltype2" unless @oracle12c_or_higher
plsql.logoff
end
it "should process XMLType parameters" do
xml = "<DUMMY>value</DUMMY>"
result = plsql.test_xmltype(xml)
expect(result).to eq("<DUMMY>value</DUMMY>")
end
it "should work when passing a NULL value" do
result = plsql.test_xmltype(nil)
expect(result).to be_nil
end
it "should assign input parameter to putput parameter" do
xml = "<DUMMY>value</DUMMY>"
result = plsql.test_xmltype2(xml)
expect(result[:po_xml]).to eq("<DUMMY>value</DUMMY>")
end
end
describe "Procedure with output parameters" do
before(:all) do
plsql.connect! CONNECTION_PARAMS
plsql.execute <<-SQL
CREATE OR REPLACE PROCEDURE test_copy
( p_from VARCHAR2, p_to OUT VARCHAR2, p_to_double OUT VARCHAR2 )
IS
BEGIN
p_to := p_from;
p_to_double := p_from || p_from;
END test_copy;
SQL
end
after(:all) do
plsql.execute "DROP PROCEDURE test_copy"
plsql.logoff
end
it "should return hash with output parameters" do
expect(plsql.test_copy("abc", nil, nil)).to eq(p_to: "abc", p_to_double: "abcabc")
end
it "should return hash with output parameters when called with named parameters" do
expect(plsql.test_copy(p_from: "abc", p_to: nil, p_to_double: nil)).to eq(p_to: "abc", p_to_double: "abcabc")
end
it "should substitute output parameters with nil if they are not specified" do
expect(plsql.test_copy("abc")).to eq(p_to: "abc", p_to_double: "abcabc")
end
it "should substitute named output parameters with nil if they are not specified" do
expect(plsql.test_copy(p_from: "abc")).to eq(p_to: "abc", p_to_double: "abcabc")
end
end
describe "Package with procedures with same name but different argument lists" do
before(:all) do
plsql.connect! CONNECTION_PARAMS
plsql.execute <<-SQL
CREATE OR REPLACE PACKAGE test_package2 IS
FUNCTION test_procedure ( p_string VARCHAR2 )
RETURN VARCHAR2;
PROCEDURE test_procedure ( p_string VARCHAR2, p_result OUT VARCHAR2 )
;
PROCEDURE test_procedure ( p_number NUMBER, p_result OUT VARCHAR2 )
;
FUNCTION test_procedure2 ( p_string VARCHAR2 )
RETURN VARCHAR2;
FUNCTION test_function ( p_string VARCHAR2, p_string2 VARCHAR2 DEFAULT ' ')
RETURN VARCHAR2;
FUNCTION test_function ( p_number NUMBER, p_number2 NUMBER DEFAULT 1 )
RETURN NUMBER;
END;
SQL
plsql.execute <<-SQL
CREATE OR REPLACE PACKAGE BODY test_package2 IS
FUNCTION test_procedure ( p_string VARCHAR2 )
RETURN VARCHAR2
IS
BEGIN
RETURN UPPER(p_string);
END test_procedure;
PROCEDURE test_procedure ( p_string VARCHAR2, p_result OUT VARCHAR2 )
IS
BEGIN
p_result := UPPER(p_string);
END test_procedure;
PROCEDURE test_procedure ( p_number NUMBER, p_result OUT VARCHAR2 )
IS
BEGIN
p_result := LOWER(TO_CHAR(p_number));
END test_procedure;
FUNCTION test_procedure2 ( p_string VARCHAR2 )
RETURN VARCHAR2
IS
BEGIN
RETURN UPPER(p_string);
END test_procedure2;
FUNCTION test_function ( p_string VARCHAR2, p_string2 VARCHAR2)
RETURN VARCHAR2
IS
BEGIN
RETURN p_string||p_string2;
END;
FUNCTION test_function ( p_number NUMBER, p_number2 NUMBER)
RETURN NUMBER
IS
BEGIN
RETURN p_number + p_number2;
END;
END;
SQL
end
after(:all) do
plsql.execute "DROP PACKAGE test_package2"
plsql.logoff
end
it "should find existing package" do
expect(PLSQL::Package.find(plsql, :test_package2)).not_to be_nil
end
it "should identify overloaded procedure definition" do
@procedure = PLSQL::Procedure.find(plsql, :test_procedure, "TEST_PACKAGE2")
expect(@procedure).not_to be_nil
expect(@procedure).to be_overloaded
end
it "should identify non-overloaded procedure definition" do
@procedure = PLSQL::Procedure.find(plsql, :test_procedure2, "TEST_PACKAGE2")
expect(@procedure).not_to be_nil
expect(@procedure).not_to be_overloaded
end
it "should execute correct procedures based on number of arguments and return correct value" do
expect(plsql.test_package2.test_procedure("xxx")).to eq("XXX")
expect(plsql.test_package2.test_procedure("xxx", nil)).to eq(p_result: "XXX")
end
it "should execute correct procedures based on number of named arguments and return correct value" do
expect(plsql.test_package2.test_procedure(p_string: "xxx")).to eq("XXX")
expect(plsql.test_package2.test_procedure(p_string: "xxx", p_result: nil)).to eq(p_result: "XXX")
end
it "should raise exception if procedure cannot be found based on number of arguments" do
expect { plsql.test_package2.test_procedure() }.to raise_error(/wrong number or types of arguments/i)
end
it "should find procedure based on types of arguments" do
expect(plsql.test_package2.test_procedure(111, nil)).to eq(p_result: "111")
end
it "should find procedure based on names of named arguments" do
expect(plsql.test_package2.test_procedure(p_number: 111, p_result: nil)).to eq(p_result: "111")
end
it "should find matching procedure based on partial list of named arguments" do
expect(plsql.test_package2.test_function(p_string: "xxx")).to eq("xxx ")
expect(plsql.test_package2.test_function(p_number: 1)).to eq(2)
end
end
describe "Function with output parameters" do
before(:all) do
plsql.connect! CONNECTION_PARAMS
plsql.execute <<-SQL
CREATE OR REPLACE FUNCTION test_copy_function
( p_from VARCHAR2, p_to OUT VARCHAR2, p_to_double OUT VARCHAR2 )
RETURN NUMBER
IS
BEGIN
p_to := p_from;
p_to_double := p_from || p_from;
RETURN LENGTH(p_from);
END test_copy_function;
SQL
end
after(:all) do
plsql.execute "DROP FUNCTION test_copy_function"
plsql.logoff
end
it "should return array with return value and hash of output parameters" do
expect(plsql.test_copy_function("abc", nil, nil)).to eq([3, { p_to: "abc", p_to_double: "abcabc" }])
end
it "should return array with return value and hash of output parameters when called with named parameters" do
expect(plsql.test_copy_function(p_from: "abc", p_to: nil, p_to_double: nil)).to eq(
[3, { p_to: "abc", p_to_double: "abcabc" }]
)
end
it "should substitute output parameters with nil if they are not specified" do
expect(plsql.test_copy_function("abc")).to eq([3, { p_to: "abc", p_to_double: "abcabc" }])
end
end
describe "Function or procedure without parameters" do
before(:all) do
plsql.connect! CONNECTION_PARAMS
plsql.execute <<-SQL
CREATE OR REPLACE FUNCTION test_no_params
RETURN VARCHAR2
IS
BEGIN
RETURN 'dummy';
END test_no_params;
SQL
plsql.execute <<-SQL
CREATE OR REPLACE PROCEDURE test_proc_no_params
IS
BEGIN
NULL;
END test_proc_no_params;
SQL
end
after(:all) do
plsql.execute "DROP FUNCTION test_no_params"
plsql.execute "DROP PROCEDURE test_proc_no_params"
plsql.logoff
end
it "should find function" do
expect(PLSQL::Procedure.find(plsql, :test_no_params)).not_to be_nil
end
it "should return function value" do
expect(plsql.test_no_params).to eq("dummy")
end
it "should find procedure" do
expect(PLSQL::Procedure.find(plsql, :test_proc_no_params)).not_to be_nil
end
it "should execute procedure" do
expect(plsql.test_proc_no_params).to be_nil
end
end
describe "Function with CLOB parameter and return value" do
before(:all) do
plsql.connect! CONNECTION_PARAMS
plsql.execute <<-SQL
CREATE OR REPLACE FUNCTION test_clob
( p_clob CLOB )
RETURN CLOB
IS
BEGIN
RETURN p_clob;
END test_clob;
SQL
plsql.execute "CREATE TABLE test_clob_table (clob_col CLOB)"
plsql.execute <<-SQL
CREATE OR REPLACE FUNCTION test_clob_insert
( p_clob CLOB )
RETURN CLOB
IS
CURSOR clob_cur IS
SELECT clob_col
FROM test_clob_table;
v_dummy CLOB;
BEGIN
DELETE FROM test_clob_table;
INSERT INTO test_clob_table (clob_col) VALUES (p_clob);
OPEN clob_cur;
FETCH clob_cur INTO v_dummy;
CLOSE clob_cur;
RETURN v_dummy;
END test_clob_insert;
SQL
end
after(:all) do
plsql.execute "DROP FUNCTION test_clob"
plsql.execute "DROP FUNCTION test_clob_insert"
plsql.execute "DROP TABLE test_clob_table"
plsql.logoff
end
it "should find existing procedure" do
expect(PLSQL::Procedure.find(plsql, :test_clob)).not_to be_nil
end
it "should execute function and return correct value" do
large_text = "ābčdēfghij" * 10_000
expect(plsql.test_clob(large_text)).to eq(large_text)
end
unless defined?(JRUBY_VERSION)
it "should execute function with empty string and return nil (oci8 cannot pass empty CLOB parameter)" do
text = ""
expect(plsql.test_clob(text)).to be_nil
end
it "should execute function which inserts the CLOB parameter into a table with empty string and return nil" do
text = ""
expect(plsql.test_clob_insert(text)).to be_nil
end
else
it "should execute function with empty string and return empty string" do
text = ""
expect(plsql.test_clob(text)).to eq(text)
end
end
it "should execute function with nil and return nil" do
expect(plsql.test_clob(nil)).to be_nil
end
it "should execute function which inserts the CLOB parameter into a table with nil and return nil" do
expect(plsql.test_clob_insert(nil)).to be_nil
end
end
describe "Procedrue with CLOB parameter and return value" do
before(:all) do
plsql.connect! CONNECTION_PARAMS
plsql.execute <<-SQL
CREATE OR REPLACE PROCEDURE test_clob_proc
( p_clob CLOB,
p_return OUT CLOB)
IS
BEGIN
p_return := p_clob;
END test_clob_proc;
SQL
end
after(:all) do
plsql.execute "DROP PROCEDURE test_clob_proc"
plsql.logoff
end
it "should find existing procedure" do
expect(PLSQL::Procedure.find(plsql, :test_clob_proc)).not_to be_nil
end
it "should execute function and return correct value" do
large_text = "ābčdēfghij" * 10_000
expect(plsql.test_clob_proc(large_text)[:p_return]).to eq(large_text)
end
end
describe "Procedrue with BLOB parameter and return value" do
before(:all) do
plsql.connect! CONNECTION_PARAMS
plsql.execute <<-SQL
CREATE OR REPLACE PROCEDURE test_blob_proc
( p_blob BLOB,
p_return OUT BLOB)
IS
BEGIN
p_return := p_blob;
END test_blob_proc;
SQL
end
after(:all) do
plsql.execute "DROP PROCEDURE test_blob_proc"
plsql.logoff
end
it "should find existing procedure" do
expect(PLSQL::Procedure.find(plsql, :test_blob_proc)).not_to be_nil
end
it "should execute function and return correct value" do
large_binary = '\000\001\002\003\004\005\006\007\010\011' * 10_000
expect(plsql.test_blob_proc(large_binary)[:p_return]).to eq(large_binary)
end
end
describe "Function with record parameter" do
before(:all) do
plsql.connect! CONNECTION_PARAMS
plsql.execute "DROP TABLE test_employees" rescue nil
plsql.execute <<-SQL
CREATE TABLE test_employees (
employee_id NUMBER(15),
first_name VARCHAR2(50),
last_name VARCHAR(50),
hire_date DATE
)
SQL
plsql.execute <<-SQL
CREATE OR REPLACE FUNCTION test_full_name (p_employee test_employees%ROWTYPE)
RETURN VARCHAR2
IS
BEGIN
RETURN p_employee.first_name || ' ' || p_employee.last_name;
END test_full_name;
SQL
plsql.execute <<-SQL
CREATE OR REPLACE PACKAGE test_record IS
TYPE t_employee IS RECORD(
employee_id NUMBER(15),
first_name VARCHAR2(50),
last_name VARCHAR(50),
hire_date DATE
);
TYPE t_candidate IS RECORD(
candidate_id NUMBER(5),
is_approved BOOLEAN
);
TYPE table_of_records IS TABLE OF test_record.t_employee;
FUNCTION test_full_name(p_employee t_employee)
RETURN VARCHAR2;
FUNCTION test_empty_records
RETURN table_of_records;
FUNCTION is_approved(p_candidate t_candidate)
RETURN BOOLEAN;
FUNCTION f_set_candidate_status(p_candidate t_candidate, p_status boolean)
RETURN t_candidate;
PROCEDURE p_set_candidate_status(p_candidate t_candidate, p_status boolean, p_result OUT t_candidate);
END;
SQL
plsql.execute <<-SQL
CREATE OR REPLACE PACKAGE BODY test_record IS
FUNCTION test_full_name (p_employee t_employee)
RETURN VARCHAR2
IS
BEGIN
RETURN p_employee.first_name || ' ' || p_employee.last_name;
END;
FUNCTION test_empty_records
RETURN table_of_records
IS
CURSOR employees_cur
IS
SELECT
null employee_id,
null first_name,
null last_name,
null hire_date
FROM dual
WHERE 1 = 2;
employees_tab table_of_records;
BEGIN
OPEN employees_cur;
FETCH employees_cur BULK COLLECT INTO employees_tab;
CLOSE employees_cur;
RETURN employees_tab;
END;
FUNCTION is_approved(p_candidate t_candidate)
RETURN BOOLEAN
IS
BEGIN
RETURN p_candidate.is_approved;
END;
FUNCTION f_set_candidate_status(p_candidate t_candidate, p_status boolean)
RETURN t_candidate
IS
result t_candidate := p_candidate;
BEGIN
result.is_approved := p_status;
return result;
END;
PROCEDURE p_set_candidate_status(p_candidate t_candidate, p_status boolean, p_result OUT t_candidate)
IS
BEGIN
p_result := p_candidate;
p_result.is_approved := p_status;
END;
END;
SQL
plsql.execute <<-SQL
CREATE OR REPLACE FUNCTION test_employee_record (p_employee test_employees%ROWTYPE)
RETURN test_employees%ROWTYPE
IS
BEGIN
RETURN p_employee;
END test_employee_record;
SQL
plsql.execute <<-SQL
CREATE OR REPLACE FUNCTION test_employee_record2 (p_employee test_employees%ROWTYPE, x_employee IN OUT test_employees%ROWTYPE)
RETURN test_employees%ROWTYPE
IS
BEGIN
x_employee.employee_id := p_employee.employee_id;
x_employee.first_name := p_employee.first_name;
x_employee.last_name := p_employee.last_name;
x_employee.hire_date := p_employee.hire_date;
RETURN p_employee;
END test_employee_record2;
SQL
@p_employee = {
employee_id: 1,
first_name: "First",
last_name: "Last",
hire_date: Time.local(2000, 01, 31)
}
@p_employee2 = {
"employee_id" => 1,
"FIRST_NAME" => "Second",
"last_name" => "Last",
"hire_date" => Time.local(2000, 01, 31)
}
end
after(:all) do
plsql.execute "DROP FUNCTION test_full_name"
plsql.execute "DROP PACKAGE test_record"
plsql.execute "DROP FUNCTION test_employee_record"
plsql.execute "DROP FUNCTION test_employee_record2"
plsql.execute "DROP TABLE test_employees"
plsql.logoff
end
it "should find existing function" do
expect(PLSQL::Procedure.find(plsql, :test_full_name)).not_to be_nil
end
it "should execute function with named parameter and return correct value" do
expect(plsql.test_full_name(p_employee: @p_employee)).to eq("First Last")
end
it "should execute function with sequential parameter and return correct value" do
expect(plsql.test_full_name(@p_employee)).to eq("First Last")
end
it "should execute function with Hash parameter using strings as keys" do
expect(plsql.test_full_name(@p_employee2)).to eq("Second Last")
end
it "should raise error if wrong field name is passed for record parameter" do
expect do
expect(plsql.test_full_name(@p_employee.merge xxx: "xxx")).to eq("Second Last")
end.to raise_error(ArgumentError)
end
it "should return empty table of records" do
expect(plsql.test_record.test_empty_records()).to eq([])
end
it "should return record return value" do
expect(plsql.test_employee_record(@p_employee)).to eq(@p_employee)
end
it "should return record return value and output record parameter value" do
expect(plsql.test_employee_record2(@p_employee, @p_employee2)).to eq([@p_employee, { x_employee: @p_employee }])
end
it "should execute package function with parameter with record type defined in package" do
expect(plsql.test_record.test_full_name(@p_employee)).to eq("First Last")
end
context "functions with record parameters having boolean attributes" do
def new_candidate(status)
{ candidate_id: 1, is_approved: status }
end
[true, false, nil].each do |status|
it "should execute function with record having boolean attribute (#{status})" do
expect(plsql.test_record.is_approved(new_candidate(status))).to eq status
end
it "procedure should return record with boolean attribute as output parameter (#{status})" do
expect(plsql.test_record.p_set_candidate_status(new_candidate(nil), status)[:p_result]).to eq new_candidate(status)
end
it "function should return record with boolean attribute (#{status})" do
expect(plsql.test_record.f_set_candidate_status(new_candidate(nil), status)).to eq new_candidate(status)
end
end
end
end
describe "Function with boolean parameters" do
before(:all) do
plsql.connect! CONNECTION_PARAMS
plsql.execute <<-SQL
CREATE OR REPLACE FUNCTION test_boolean
( p_boolean BOOLEAN )
RETURN BOOLEAN
IS
BEGIN
RETURN p_boolean;
END test_boolean;
SQL
plsql.execute <<-SQL
CREATE OR REPLACE PROCEDURE test_boolean2
( p_boolean BOOLEAN, x_boolean OUT BOOLEAN )
IS
BEGIN
x_boolean := p_boolean;
END test_boolean2;
SQL
end
after(:all) do
plsql.execute "DROP FUNCTION test_boolean"
plsql.execute "DROP PROCEDURE test_boolean2"
plsql.logoff
end
it "should accept true value and return true value" do
expect(plsql.test_boolean(true)).to eq(true)
end
it "should accept false value and return false value" do
expect(plsql.test_boolean(false)).to eq(false)
end
it "should accept nil value and return nil value" do
expect(plsql.test_boolean(nil)).to be_nil
end
it "should accept true value and assign true value to output parameter" do
expect(plsql.test_boolean2(true, nil)).to eq(x_boolean: true)
end
it "should accept false value and assign false value to output parameter" do
expect(plsql.test_boolean2(false, nil)).to eq(x_boolean: false)
end
it "should accept nil value and assign nil value to output parameter" do
expect(plsql.test_boolean2(nil, nil)).to eq(x_boolean: nil)
end
end
describe "Function with object type parameter" do
before(:all) do
plsql.connect! CONNECTION_PARAMS
plsql.execute "DROP TYPE t_employee" rescue nil
plsql.execute "DROP TYPE t_phones" rescue nil
plsql.execute <<-SQL
CREATE OR REPLACE TYPE t_address AS OBJECT (
street VARCHAR2(50),
city VARCHAR2(50),
country VARCHAR2(50)
)
SQL
plsql.execute <<-SQL
CREATE OR REPLACE TYPE t_phone AS OBJECT (
type VARCHAR2(10),
phone_number VARCHAR2(50)
)
SQL
plsql.execute <<-SQL
CREATE OR REPLACE TYPE t_phones AS TABLE OF T_PHONE
SQL
plsql.execute <<-SQL
CREATE OR REPLACE TYPE t_employee AS OBJECT (
employee_id NUMBER(15),
first_name VARCHAR2(50),
last_name VARCHAR(50),
hire_date DATE,
address t_address,
phones t_phones
)
SQL
plsql.execute <<-SQL
CREATE OR REPLACE FUNCTION test_full_name (p_employee t_employee)
RETURN VARCHAR2
IS
BEGIN
RETURN p_employee.first_name || ' ' || p_employee.last_name;
END;
SQL
plsql.execute <<-SQL
CREATE OR REPLACE FUNCTION test_employee_object (p_employee t_employee)
RETURN t_employee
IS
BEGIN
RETURN p_employee;
END;
SQL
plsql.execute <<-SQL
CREATE OR REPLACE FUNCTION test_employee_object2 (p_employee t_employee, x_employee OUT t_employee)
RETURN t_employee
IS
BEGIN
x_employee := p_employee;
RETURN p_employee;
END;
SQL
@p_employee = {
employee_id: 1,
first_name: "First",
last_name: "Last",
hire_date: Time.local(2000, 01, 31),
address: { street: "Main street 1", city: "Riga", country: "Latvia" },
phones: [{ type: "mobile", phone_number: "123456" }, { type: "home", phone_number: "654321" }]
}
end
after(:all) do
plsql.execute "DROP FUNCTION test_full_name"
plsql.execute "DROP FUNCTION test_employee_object"
plsql.execute "DROP FUNCTION test_employee_object2"
plsql.execute "DROP TYPE t_employee"
plsql.execute "DROP TYPE t_address"
plsql.execute "DROP TYPE t_phones"
plsql.execute "DROP TYPE t_phone"
plsql.logoff
end
it "should find existing function" do
expect(PLSQL::Procedure.find(plsql, :test_full_name)).not_to be_nil
end
it "should execute function with named parameter and return correct value" do
expect(plsql.test_full_name(p_employee: @p_employee)).to eq("First Last")
end
it "should execute function with sequential parameter and return correct value" do
expect(plsql.test_full_name(@p_employee)).to eq("First Last")
end
it "should raise error if wrong field name is passed for record parameter" do
expect do
plsql.test_full_name(@p_employee.merge xxx: "xxx")
end.to raise_error(ArgumentError)
end
it "should return object type return value" do
expect(plsql.test_employee_object(@p_employee)).to eq(@p_employee)
end
it "should return object type return value and output object type parameter value" do
expect(plsql.test_employee_object2(@p_employee, nil)).to eq([@p_employee, { x_employee: @p_employee }])
end
it "should accept NULL as input parameter" do
expect(plsql.test_employee_object(nil)).to eq(nil)
end
end
| ruby | MIT | 7bee9ba2b3207de7c1ae4112d8af2636b586c610 | 2026-01-04T17:45:33.227772Z | true |
rsim/ruby-plsql | https://github.com/rsim/ruby-plsql/blob/7bee9ba2b3207de7c1ae4112d8af2636b586c610/spec/plsql/schema_spec.rb | spec/plsql/schema_spec.rb | require "spec_helper"
describe "Schema" do
it "should create Schema object" do
expect(plsql.class).to eq(PLSQL::Schema)
end
end
describe "Schema connection" do
before(:each) do
@conn = get_connection
end
after(:each) do
unless defined? JRUBY_VERSION
@conn.logoff
else
@conn.close
end
end
it "should connect to test database" do
plsql.connection = @conn
expect(plsql.connection.raw_connection).to eq(@conn)
end
it "should connect to test database using connection alias" do
plsql(:hr).connection = @conn
expect(plsql(:hr).connection.raw_connection).to eq(@conn)
end
it "should return schema name" do
plsql.connection = @conn
expect(plsql.schema_name).to eq(DATABASE_USERS_AND_PASSWORDS[0][0].upcase)
end
it "should match altered current_schema in database session" do
plsql.connection = @conn
expected_current_schema = DATABASE_USERS_AND_PASSWORDS[1][0]
plsql.execute "ALTER SESSION set current_schema=#{expected_current_schema}"
expect(plsql.schema_name).to eq(expected_current_schema.upcase)
end
it "should return new schema name after reconnection" do
plsql.connection = @conn
expect(plsql.schema_name).to eq(DATABASE_USERS_AND_PASSWORDS[0][0].upcase)
plsql.connection = get_connection(1)
expect(plsql.schema_name).to eq(DATABASE_USERS_AND_PASSWORDS[1][0].upcase)
end
it "should return nil schema name if not connected" do
expect(plsql(:xxx).schema_name).to eq(nil)
end
end
describe "Connection with connect!" do
before(:all) do
@username, @password = DATABASE_USERS_AND_PASSWORDS[0]
@database = DATABASE_NAME
@database_service = DATABASE_SERVICE_NAME
@host = DATABASE_HOST
@port = DATABASE_PORT
end
after(:each) do
plsql.logoff if plsql.connection
end
it "should connect with username, password and database alias" do
plsql.connect! @username, @password, @database
expect(plsql.connection).not_to be_nil
expect(plsql.schema_name).to eq(@username.upcase)
end
it "should connect with username, password, host, port and database name" do
plsql.connect! @username, @password, host: @host, port: @port, database: @database_service
expect(plsql.connection).not_to be_nil
expect(plsql.schema_name).to eq(@username.upcase)
end
it "should connect with username, password, host, database name and default port" do
skip "Non-default port used for test database" unless @port == 1521
plsql.connect! @username, @password, host: @host, database: @database_service
expect(plsql.connection).not_to be_nil
expect(plsql.schema_name).to eq(@username.upcase)
end
it "should not connect with wrong port number" do
expect {
plsql.connect! @username, @password, host: @host, port: 9999, database: @database
}.to raise_error(/ORA-12541|could not establish the connection/)
end
it "should connect with one Hash parameter" do
plsql.connect! username: @username, password: @password, database: @database
expect(plsql.connection).not_to be_nil
expect(plsql.schema_name).to eq(@username.upcase)
end
it "should set session time zone from ORA_SDTZ environment variable" do
plsql.connect! @username, @password, @database
expect(plsql.connection.time_zone).to eq(ENV["ORA_SDTZ"])
end if ENV["ORA_SDTZ"]
it "should set session time zone from :time_zone parameter" do
plsql.connect! username: @username, password: @password, database: @database, time_zone: "EET"
expect(plsql.connection.time_zone).to eq("EET")
end
end
describe "Named Schema" do
before(:all) do
plsql.connection = @conn = get_connection
end
after(:all) do
plsql.connection.logoff
end
it "should find existing schema" do
expect(plsql.hr.class).to eq(PLSQL::Schema)
end
it "should have the same connection as default schema" do
expect(plsql.hr.connection.raw_connection).to eq(@conn)
end
it "should return schema name" do
expect(plsql.hr.schema_name).to eq("HR")
end
it "should not find named schema if specified twice" do
expect { plsql.hr.hr }.to raise_error(ArgumentError)
end
end
describe "Schema commit and rollback" do
before(:all) do
plsql.connection = @conn = get_connection
plsql.connection.autocommit = false
plsql.execute "CREATE TABLE test_commit (dummy VARCHAR2(100))"
@data = { dummy: "test" }
@data2 = { dummy: "test2" }
end
after(:all) do
plsql.execute "DROP TABLE test_commit"
plsql.logoff
end
after(:each) do
plsql.test_commit.delete
plsql.commit
end
it "should do commit" do
plsql.test_commit.insert @data
plsql.commit
expect(plsql.test_commit.first).to eq(@data)
end
it "should do rollback" do
plsql.test_commit.insert @data
plsql.rollback
expect(plsql.test_commit.first).to be_nil
end
it "should create savepoint and rollback to savepoint" do
plsql.test_commit.insert @data
plsql.savepoint "test"
plsql.test_commit.insert @data2
expect(plsql.test_commit.all).to eq([@data, @data2])
plsql.rollback_to "test"
expect(plsql.test_commit.all).to eq([@data])
end
end
describe "ActiveRecord connection" do
before(:all) do
ActiveRecord::Base.establish_connection(CONNECTION_PARAMS)
class TestBaseModel < ActiveRecord::Base
self.abstract_class = true
end
class TestModel < TestBaseModel
end
end
before(:each) do
plsql.activerecord_class = ActiveRecord::Base
end
it "should connect to test database" do
unless defined?(JRUBY_VERSION)
expect(plsql.connection.is_a?(PLSQL::OCIConnection)).to be_truthy
else
expect(plsql.connection.is_a?(PLSQL::JDBCConnection)).to be_truthy
end
end
it "should return schema name" do
expect(plsql.schema_name).to eq("HR")
end
it "should use ActiveRecord::Base.default_timezone as default" do
ActiveRecord::Base.default_timezone = :utc
expect(plsql.default_timezone).to eq(:utc)
end
it "should have the same connection as default schema" do
expect(plsql.hr.connection).to eq(plsql.connection)
end
it "should accept inherited ActiveRecord class" do
plsql.activerecord_class = TestBaseModel
expect(plsql.schema_name).to eq("HR")
end
it "should accept subclass of inherited ActiveRecord class" do
plsql.activerecord_class = TestModel
expect(plsql.schema_name).to eq("HR")
end
it "should safely close cursors in threaded environment" do
if (plsql.connection.database_version <=> [18, 0, 0, 0]) >= 0
expect {
t1 = Thread.new { plsql.dbms_session.sleep(1) }.tap { |t| t.abort_on_exception = true }
t2 = Thread.new { plsql.dbms_session.sleep(2) }.tap { |t| t.abort_on_exception = true }
[t2, t1].each { |t| t.join }
}.not_to raise_error
else
expect {
t1 = Thread.new { plsql.dbms_lock.sleep(1) }.tap { |t| t.abort_on_exception = true }
t2 = Thread.new { plsql.dbms_lock.sleep(2) }.tap { |t| t.abort_on_exception = true }
[t2, t1].each { |t| t.join }
}.not_to raise_error
end
end
end if defined?(ActiveRecord)
describe "DBMS_OUTPUT logging" do
before(:all) do
plsql.connection = get_connection
plsql.execute <<-SQL
CREATE OR REPLACE PROCEDURE test_dbms_output(p_string VARCHAR2, p_raise_error BOOLEAN := false)
IS
BEGIN
DBMS_OUTPUT.PUT_LINE(p_string);
IF p_raise_error THEN
RAISE_APPLICATION_ERROR(-20000 - 12, 'Test Error');
END IF;
END;
SQL
plsql.execute <<-SQL
CREATE OR REPLACE PROCEDURE test_dbms_output_large(p_string VARCHAR2, p_times INTEGER)
IS
i INTEGER;
BEGIN
FOR i IN 1..p_times LOOP
DBMS_OUTPUT.PUT_LINE(p_string);
END LOOP;
END;
SQL
@buffer = StringIO.new
end
before(:each) do
@buffer.rewind
@buffer.reopen
end
after(:all) do
plsql.dbms_output_stream = nil
plsql.execute "DROP PROCEDURE test_dbms_output"
plsql.execute "DROP PROCEDURE test_dbms_output_large"
plsql.logoff
end
describe "with standard connection" do
before(:all) do
plsql.dbms_output_stream = @buffer
end
before(:each) do
plsql.dbms_output_buffer_size = nil
end
it "should log output to specified stream" do
plsql.test_dbms_output("test_dbms_output")
expect(@buffer.string).to eq("DBMS_OUTPUT: test_dbms_output\n")
end
it "should log output to specified stream in case of exception" do
expect { plsql.test_dbms_output("test_dbms_output", true) }.to raise_error /Test Error/
expect(@buffer.string).to eq("DBMS_OUTPUT: test_dbms_output\n")
end
it "should not log output to stream when output is disabled" do
plsql.test_dbms_output("enabled")
plsql.dbms_output_stream = nil
plsql.test_dbms_output("disabled")
plsql.dbms_output_stream = @buffer
plsql.test_dbms_output("enabled again")
expect(@buffer.string).to eq("DBMS_OUTPUT: enabled\nDBMS_OUTPUT: enabled again\n")
end
it "should log 20_000 character output with default buffer size" do
times = 2_000
plsql.test_dbms_output_large("1234567890", times)
expect(@buffer.string).to eq("DBMS_OUTPUT: 1234567890\n" * times)
end
it "should log 100_000 character output with specified buffer size" do
times = 10_000
plsql.dbms_output_buffer_size = 10 * times
plsql.test_dbms_output_large("1234567890", times)
expect(@buffer.string).to eq("DBMS_OUTPUT: 1234567890\n" * times)
end
it "should log output when database version is less than 10.2" do
allow(plsql.connection).to receive(:database_version).and_return([9, 2, 0, 0])
times = 2_000
plsql.test_dbms_output_large("1234567890", times)
expect(@buffer.string).to eq("DBMS_OUTPUT: 1234567890\n" * times)
end
it "should log output when calling procedure with schema prefix" do
plsql.hr.test_dbms_output("test_dbms_output")
expect(@buffer.string).to eq("DBMS_OUTPUT: test_dbms_output\n")
end
end
describe "with Activerecord connection" do
before(:all) do
ActiveRecord::Base.establish_connection(CONNECTION_PARAMS)
plsql(:ar).activerecord_class = ActiveRecord::Base
plsql(:ar).dbms_output_stream = @buffer
end
it "should log output to specified stream" do
plsql(:ar).test_dbms_output("test_dbms_output")
expect(@buffer.string).to eq("DBMS_OUTPUT: test_dbms_output\n")
end
it "should log output after reconnection" do
ActiveRecord::Base.connection.reconnect!
plsql(:ar).test_dbms_output("after reconnection")
expect(@buffer.string).to eq("DBMS_OUTPUT: after reconnection\n")
end
end if defined?(ActiveRecord)
end
| ruby | MIT | 7bee9ba2b3207de7c1ae4112d8af2636b586c610 | 2026-01-04T17:45:33.227772Z | false |
rsim/ruby-plsql | https://github.com/rsim/ruby-plsql/blob/7bee9ba2b3207de7c1ae4112d8af2636b586c610/spec/plsql/table_spec.rb | spec/plsql/table_spec.rb | require "spec_helper"
describe "Table" do
before(:all) do
plsql.connect! CONNECTION_PARAMS
plsql.connection.autocommit = false
plsql.execute <<-SQL
CREATE TABLE test_employees (
employee_id NUMBER(15) NOT NULL,
first_name VARCHAR2(50),
last_name VARCHAR(50),
hire_date DATE,
created_at TIMESTAMP,
status VARCHAR2(1) DEFAULT 'N'
)
SQL
plsql.execute <<-SQL
CREATE OR REPLACE TYPE t_address AS OBJECT (
street VARCHAR2(50),
city VARCHAR2(50),
country VARCHAR2(50)
)
SQL
plsql.execute <<-SQL
CREATE OR REPLACE TYPE t_phone AS OBJECT (
type VARCHAR2(10),
phone_number VARCHAR2(50)
)
SQL
plsql.execute <<-SQL
CREATE OR REPLACE TYPE t_phones AS VARRAY(10) OF T_PHONE
SQL
plsql.execute <<-SQL
CREATE TABLE test_employees2 (
employee_id NUMBER(15) NOT NULL,
first_name VARCHAR2(50),
last_name VARCHAR(50),
hire_date DATE DEFAULT SYSDATE,
address t_address,
phones t_phones
)
SQL
@employees = (1..10).map do |i|
{
employee_id: i,
first_name: "First #{i}",
last_name: "Last #{i}",
hire_date: Time.local(2000, 01, i),
created_at: Time.local(2000, 01, i, 9, 15, 30, i),
status: "A"
}
end
@employees_all_fields = [:employee_id, :first_name, :last_name, :hire_date, :created_at, :status]
@employees_all_values = @employees.map { |e| @employees_all_fields.map { |f| e[f] } }
@employees_some_fields = [:employee_id, :first_name, :last_name]
@employees_some_values = @employees.map { |e| @employees_some_fields.map { |f| e[f] } }
@employee_default_values = { hire_date: nil, created_at: nil, status: "N" }
@employees2 = (1..10).map do |i|
{
employee_id: i,
first_name: "First #{i}",
last_name: "Last #{i}",
hire_date: Time.local(2000, 01, i),
address: { street: "Street #{i}", city: "City #{i}", country: "County #{i}" },
phones: [{ type: "mobile", phone_number: "Mobile#{i}" }, { type: "fixed", phone_number: "Fixed#{i}" }]
}
end
end
after(:all) do
plsql.execute "DROP TABLE test_employees"
plsql.execute "DROP TABLE test_employees2"
plsql.execute "DROP TYPE t_phones"
plsql.execute "DROP TYPE t_phone"
plsql.execute "DROP TYPE t_address"
plsql.logoff
end
after(:each) do
plsql.rollback
end
describe "find" do
it "should find existing table" do
expect(PLSQL::Table.find(plsql, :test_employees)).not_to be_nil
end
it "should not find nonexisting table" do
expect(PLSQL::Table.find(plsql, :qwerty123456)).to be_nil
end
it "should find existing table in schema" do
expect(plsql.test_employees).to be_a(PLSQL::Table)
end
end
describe "synonym" do
before(:all) do
plsql.execute "CREATE SYNONYM test_employees_synonym FOR hr.test_employees"
end
after(:all) do
plsql.execute "DROP SYNONYM test_employees_synonym" rescue nil
end
it "should find synonym to table" do
expect(PLSQL::Table.find(plsql, :test_employees_synonym)).not_to be_nil
end
it "should find table using synonym in schema" do
expect(plsql.test_employees_synonym).to be_a(PLSQL::Table)
end
end
describe "public synonym" do
it "should find public synonym to table" do
expect(PLSQL::Table.find(plsql, :dual)).not_to be_nil
end
it "should find table using public synonym in schema" do
expect(plsql.dual).to be_a(PLSQL::Table)
end
end
describe "columns" do
it "should get column names for table" do
expect(plsql.test_employees.column_names).to eq(@employees_all_fields)
end
it "should get columns metadata for table" do
expect(plsql.test_employees.columns).to eq(
employee_id: {
position: 1, data_type: "NUMBER", data_length: 22, data_precision: 15, data_scale: 0, char_used: nil,
type_owner: nil, type_name: nil, sql_type_name: nil, nullable: false, data_default: nil },
first_name: {
position: 2, data_type: "VARCHAR2", data_length: 50, data_precision: nil, data_scale: nil, char_used: "B",
type_owner: nil, type_name: nil, sql_type_name: nil, nullable: true, data_default: nil },
last_name: {
position: 3, data_type: "VARCHAR2", data_length: 50, data_precision: nil, data_scale: nil, char_used: "B",
type_owner: nil, type_name: nil, sql_type_name: nil, nullable: true, data_default: nil },
hire_date: {
position: 4, data_type: "DATE", data_length: 7, data_precision: nil, data_scale: nil, char_used: nil,
type_owner: nil, type_name: nil, sql_type_name: nil, nullable: true, data_default: nil },
created_at: {
position: 5, data_type: "TIMESTAMP", data_length: 11, data_precision: nil, data_scale: 6, char_used: nil,
type_owner: nil, type_name: nil, sql_type_name: nil, nullable: true, data_default: nil },
status: {
position: 6, data_type: "VARCHAR2", data_length: 1, data_precision: nil, data_scale: nil, char_used: "B",
type_owner: nil, type_name: nil, sql_type_name: nil, nullable: true, data_default: "'N'" }
)
end
it "should get columns metadata for table with object columns" do
expect(plsql.test_employees2.columns).to eq(
employee_id: {
position: 1, data_type: "NUMBER", data_length: 22, data_precision: 15, data_scale: 0, char_used: nil,
type_owner: nil, type_name: nil, sql_type_name: nil, nullable: false, data_default: nil },
first_name: {
position: 2, data_type: "VARCHAR2", data_length: 50, data_precision: nil, data_scale: nil, char_used: "B",
type_owner: nil, type_name: nil, sql_type_name: nil, nullable: true, data_default: nil },
last_name: {
position: 3, data_type: "VARCHAR2", data_length: 50, data_precision: nil, data_scale: nil, char_used: "B",
type_owner: nil, type_name: nil, sql_type_name: nil, nullable: true, data_default: nil },
hire_date: {
position: 4, data_type: "DATE", data_length: 7, data_precision: nil, data_scale: nil, char_used: nil,
type_owner: nil, type_name: nil, sql_type_name: nil, nullable: true, data_default: "SYSDATE" },
address: {
position: 5, data_type: "OBJECT", data_length: nil, data_precision: nil, data_scale: nil,
char_used: nil, type_owner: "HR", type_name: "T_ADDRESS", sql_type_name: "HR.T_ADDRESS", nullable: true, data_default: nil },
phones: {
position: 6, data_type: "TABLE", data_length: nil, data_precision: nil, data_scale: nil, char_used: nil,
type_owner: "HR", type_name: "T_PHONES", sql_type_name: "HR.T_PHONES", nullable: true, data_default: nil }
)
end
end
describe "insert" do
it "should insert a record in table" do
plsql.test_employees.insert @employees.first
expect(plsql.test_employees.all).to eq([@employees.first])
end
it "should insert a record in table using partial list of columns" do
plsql.test_employees.insert @employees.first.except(:hire_date)
expect(plsql.test_employees.all).to eq([@employees.first.merge(hire_date: nil)])
end
it "should insert default value from table definition if value not provided" do
plsql.test_employees.insert @employees.first.except(:status)
expect(plsql.test_employees.all).to eq([@employees.first.merge(status: "N")])
end
it "should insert array of records in table" do
plsql.test_employees.insert @employees
expect(plsql.test_employees.all("ORDER BY employee_id")).to eq(@employees)
end
it "should insert a record in table with object types" do
plsql.test_employees2.insert @employees2.first
expect(plsql.test_employees2.all).to eq([@employees2.first])
end
it "should insert array of records in table with object types" do
plsql.test_employees2.insert @employees2
expect(plsql.test_employees2.all("ORDER BY employee_id")).to eq(@employees2)
end
it "should insert with case-insensetive table name" do
plsql.test_employees.insert @employees.first.map { |k, v| [k.upcase.to_sym, v] }.to_h
expect(plsql.test_employees.all).to eq([@employees.first])
end
end
describe "insert values" do
it "should insert a record with array of values" do
plsql.test_employees.insert_values @employees_all_values.first
expect(plsql.test_employees.all).to eq([@employees.first])
end
it "should insert a record with list of all fields and array of values" do
plsql.test_employees.insert_values @employees_all_fields, @employees_all_values.first
expect(plsql.test_employees.all).to eq([@employees.first])
end
it "should insert a record with list of some fields and array of values" do
plsql.test_employees.insert_values @employees_some_fields, @employees_some_values.first
expect(plsql.test_employees.all).to eq([@employees.first.merge(@employee_default_values)])
end
it "should insert many records with array of values" do
plsql.test_employees.insert_values *@employees_all_values
expect(plsql.test_employees.all).to eq(@employees)
end
it "should insert many records with list of all fields and array of values" do
plsql.test_employees.insert_values @employees_all_fields, *@employees_all_values
expect(plsql.test_employees.all).to eq(@employees)
end
it "should insert many records with list of some fields and array of values" do
plsql.test_employees.insert_values @employees_some_fields, *@employees_some_values
expect(plsql.test_employees.all).to eq(@employees.map { |e| e.merge(@employee_default_values) })
end
end
describe "select" do
before(:each) do
plsql.test_employees.insert @employees
end
it "should select first record in table" do
expect(plsql.test_employees.select(:first, "ORDER BY employee_id")).to eq(@employees.first)
expect(plsql.test_employees.first("ORDER BY employee_id")).to eq(@employees.first)
end
it "should select all records in table" do
expect(plsql.test_employees.select(:all, "ORDER BY employee_id")).to eq(@employees)
expect(plsql.test_employees.all("ORDER BY employee_id")).to eq(@employees)
expect(plsql.test_employees.all(order_by: :employee_id)).to eq(@employees)
end
it "should select record in table using WHERE condition" do
expect(plsql.test_employees.select(:first, "WHERE employee_id = :1", @employees.first[:employee_id])).to eq(@employees.first)
expect(plsql.test_employees.first("WHERE employee_id = :1", @employees.first[:employee_id])).to eq(@employees.first)
expect(plsql.test_employees.first(employee_id: @employees.first[:employee_id])).to eq(@employees.first)
end
it "should select records in table using WHERE condition and ORDER BY sorting" do
expect(plsql.test_employees.all(employee_id: @employees.first[:employee_id], order_by: :employee_id)).to eq([@employees.first])
end
it "should select record in table using :column => nil condition" do
employee = @employees.last.dup
employee[:employee_id] = employee[:employee_id] + 1
employee[:hire_date] = nil
plsql.test_employees.insert employee
expect(plsql.test_employees.first("WHERE hire_date IS NULL")).to eq(employee)
expect(plsql.test_employees.first(hire_date: nil)).to eq(employee)
end
it "should select record in table using :column => :is_null condition" do
employee = @employees.last.dup
employee[:employee_id] = employee[:employee_id] + 1
employee[:hire_date] = nil
plsql.test_employees.insert employee
expect(plsql.test_employees.first(hire_date: :is_null)).to eq(employee)
end
it "should select record in table using :column => :is_not_null condition" do
employee = @employees.last.dup
employee[:employee_id] = employee[:employee_id] + 1
employee[:hire_date] = nil
plsql.test_employees.insert employee
expect(plsql.test_employees.all(hire_date: :is_not_null, order_by: :employee_id)).to eq(@employees)
end
it "should count records in table" do
expect(plsql.test_employees.select(:count)).to eq(@employees.size)
expect(plsql.test_employees.count).to eq(@employees.size)
end
it "should count records in table using condition" do
expect(plsql.test_employees.select(:count, "WHERE employee_id <= :1", @employees[2][:employee_id])).to eq(3)
expect(plsql.test_employees.count("WHERE employee_id <= :1", @employees[2][:employee_id])).to eq(3)
end
end
describe "update" do
it "should update a record in table" do
employee_id = @employees.first[:employee_id]
plsql.test_employees.insert @employees.first
plsql.test_employees.update first_name: "Test", where: { employee_id: employee_id }
expect(plsql.test_employees.first(employee_id: employee_id)[:first_name]).to eq("Test")
end
it "should update a record in table using String WHERE condition" do
employee_id = @employees.first[:employee_id]
plsql.test_employees.insert @employees
plsql.test_employees.update first_name: "Test", where: "employee_id = #{employee_id}"
expect(plsql.test_employees.first(employee_id: employee_id)[:first_name]).to eq("Test")
# all other records should not be changed
plsql.test_employees.all("WHERE employee_id > :1", employee_id) do |employee|
expect(employee[:first_name]).not_to eq("Test")
end
end
it "should update all records in table" do
plsql.test_employees.insert @employees
plsql.test_employees.update first_name: "Test"
plsql.test_employees.all do |employee|
expect(employee[:first_name]).to eq("Test")
end
end
it "should update a record in table with object type" do
employee = @employees2[0]
employee2 = @employees2[1]
plsql.test_employees2.insert employee
plsql.test_employees2.update address: employee2[:address], phones: employee2[:phones], where: { employee_id: employee[:employee_id] }
updated_employee = plsql.test_employees2.first(employee_id: employee[:employee_id])
expect(updated_employee[:address]).to eq(employee2[:address])
expect(updated_employee[:phones]).to eq(employee2[:phones])
end
end
describe "delete" do
it "should delete record from table" do
employee_id = @employees.first[:employee_id]
plsql.test_employees.insert @employees
plsql.test_employees.delete employee_id: employee_id
expect(plsql.test_employees.first(employee_id: employee_id)).to be_nil
expect(plsql.test_employees.all(order_by: :employee_id)).to eq(@employees[1, @employees.size - 1])
end
it "should delete all records from table" do
plsql.test_employees.insert @employees
plsql.test_employees.delete
expect(plsql.test_employees.all).to be_empty
end
end
end
| ruby | MIT | 7bee9ba2b3207de7c1ae4112d8af2636b586c610 | 2026-01-04T17:45:33.227772Z | false |
rsim/ruby-plsql | https://github.com/rsim/ruby-plsql/blob/7bee9ba2b3207de7c1ae4112d8af2636b586c610/spec/plsql/variable_spec.rb | spec/plsql/variable_spec.rb | # encoding: utf-8
require "spec_helper"
describe "Package variables /" do
describe "String" do
before(:all) do
plsql.connect! CONNECTION_PARAMS
plsql.execute <<-SQL
CREATE OR REPLACE PACKAGE test_package IS
varchar2_variable VARCHAR2(50);
varchar2_variable2 VARCHAR2(50); -- some comment
varchar2_default varchar2(50) := 'default' ;
varchar2_default2 varchar2(50) DEFAULT 'default';
varchar2_default3 varchar2(50) NOT NULL := 'default';
varchar2_3_char VARCHAR2(3 CHAR);
varchar2_3_byte VARCHAR2(3 BYTE);
varchar_variable VARCHAR(50);
char_variable char(10) ;
nvarchar2_variable NVARCHAR2(50);
nchar_variable NCHAR(10);
END;
SQL
plsql.execute <<-SQL
CREATE OR REPLACE PACKAGE BODY test_package IS
END;
SQL
end
after(:all) do
plsql.execute "DROP PACKAGE test_package"
plsql.logoff
end
it "should set and get VARCHAR variable" do
plsql.test_package.varchar_variable = "abc"
expect(plsql.test_package.varchar_variable).to eq("abc")
end
it "should set and get VARCHAR2 variable" do
plsql.test_package.varchar2_variable = "abc"
expect(plsql.test_package.varchar2_variable).to eq("abc")
end
it "should set and get VARCHAR2 variable with comment" do
plsql.test_package.varchar2_variable2 = "abc"
expect(plsql.test_package.varchar2_variable2).to eq("abc")
end
it "should get VARCHAR2 variable default value" do
expect(plsql.test_package.varchar2_default).to eq("default")
expect(plsql.test_package.varchar2_default2).to eq("default")
expect(plsql.test_package.varchar2_default3).to eq("default")
end
describe "with character or byte limit" do
before(:each) do
if !defined?(JRUBY_VERSION) && OCI8.properties.has_key?(:length_semantics)
@original_length_semantics = OCI8.properties[:length_semantics]
OCI8.properties[:length_semantics] = :char
end
end
after(:each) do
if !defined?(JRUBY_VERSION) && OCI8.properties.has_key?(:length_semantics)
OCI8.properties[:length_semantics] = @original_length_semantics
end
end
it "should set and get VARCHAR2(n CHAR) variable" do
plsql.test_package.varchar2_3_char = "āčē"
expect(plsql.test_package.varchar2_3_char).to eq("āčē")
expect { plsql.test_package.varchar2_3_char = "aceg" }.to raise_error(/buffer too small/)
end
it "should set and get VARCHAR2(n BYTE) variable" do
plsql.test_package.varchar2_3_byte = "ace"
expect(plsql.test_package.varchar2_3_byte).to eq("ace")
expect { plsql.test_package.varchar2_3_byte = "āce" }.to raise_error(/buffer too small/)
expect { plsql.test_package.varchar2_3_byte = "aceg" }.to raise_error(/buffer too small/)
end
end
it "should set and get CHAR variable" do
plsql.test_package.char_variable = "abc"
expect(plsql.test_package.char_variable).to eq("abc" + " " * 7)
end
it "should set and get NVARCHAR2 variable" do
plsql.test_package.nvarchar2_variable = "abc"
expect(plsql.test_package.nvarchar2_variable).to eq("abc")
end
it "should set and get NCHAR variable" do
plsql.test_package.nchar_variable = "abc"
expect(plsql.test_package.nchar_variable).to eq("abc" + " " * 7)
end
end
shared_examples "Numeric" do |ora_data_type, default, class_, given, expected|
before(:all) do
plsql.connect! CONNECTION_PARAMS
plsql.execute <<-SQL
CREATE OR REPLACE PACKAGE test_package IS
numeric_var #{ora_data_type}#{default ? ':= ' + default.to_s : nil};
END;
SQL
end
after(:all) do
plsql.execute "DROP PACKAGE test_package"
plsql.logoff
end
it "should get #{ora_data_type} variable default value" do
expect(plsql.test_package.numeric_var).to eq(default)
end if default
it "should get #{ora_data_type} variable type mapped to #{class_.to_s}" do
plsql.test_package.numeric_var = given
expect(plsql.test_package.numeric_var).to be_a class_
end
it "should set and get #{ora_data_type} variable" do
plsql.test_package.numeric_var = given
expect(plsql.test_package.numeric_var).to eq(expected)
end
end
[
{ ora_data_type: "INTEGER", default: nil, class: Integer, given: 1, expected: 1 },
{ ora_data_type: "NUMBER(10)", default: nil, class: Integer, given: 1, expected: 1 },
{ ora_data_type: "NUMBER(10)", default: 5, class: Integer, given: 1, expected: 1 },
{ ora_data_type: "NUMBER", default: nil, class: BigDecimal, given: 123.456, expected: 123.456 },
{ ora_data_type: "NUMBER(15,2)", default: nil, class: BigDecimal, given: 123.456, expected: 123.46 },
{ ora_data_type: "PLS_INTEGER", default: nil, class: Integer, given: 1, expected: 1 },
{ ora_data_type: "BINARY_INTEGER", default: nil, class: Integer, given: 1, expected: 1 },
{ ora_data_type: "SIMPLE_INTEGER", default: 10, class: Integer, given: 1, expected: 1 },
{ ora_data_type: "NATURAL", default: nil, class: Integer, given: 1, expected: 1 },
{ ora_data_type: "NATURALN", default: 0, class: Integer, given: 1, expected: 1 },
{ ora_data_type: "POSITIVE", default: nil, class: Integer, given: 1, expected: 1 },
{ ora_data_type: "POSITIVEN", default: 5, class: Integer, given: 1, expected: 1 },
{ ora_data_type: "SIGNTYPE", default: -1, class: Integer, given: 1, expected: 1 },
].each do |row|
ora_data_type, default, class_, given, expected = row.values
describe ora_data_type + (default ? " with default" : "") do
include_examples "Numeric", ora_data_type, default, class_, given, expected
end
end
describe "Date and Time" do
before(:all) do
plsql.connect! CONNECTION_PARAMS
plsql.execute <<-SQL
CREATE OR REPLACE PACKAGE test_package IS
date_variable DATE;
date_default DATE := TO_DATE('2009-12-21', 'YYYY-MM-DD');
timestamp_variable TIMESTAMP;
timestamptz_variable TIMESTAMP WITH TIME ZONE;
timestampltz_variable TIMESTAMP WITH LOCAL TIME ZONE;
END;
SQL
plsql.execute <<-SQL
CREATE OR REPLACE PACKAGE BODY test_package IS
END;
SQL
@date = Time.local(2009, 12, 21)
@timestamp = Time.local(2009, 12, 21, 14, 10, 30, 11)
end
after(:all) do
plsql.execute "DROP PACKAGE test_package"
plsql.logoff
end
it "should set and get DATE variable" do
plsql.test_package.date_variable = @date
expect(plsql.test_package.date_variable).to be_a Time
expect(plsql.test_package.date_variable).to eq(@date)
end
it "should get DATE variable default value" do
expect(plsql.test_package.date_default).to eq(@date)
end
it "should set and get TIMESTAMP variable" do
plsql.test_package.timestamp_variable = @timestamp
expect(plsql.test_package.timestamp_variable).to be_a Time
expect(plsql.test_package.timestamp_variable).to eq(@timestamp)
end
it "should set and get TIMESTAMP WITH TIME ZONE variable" do
plsql.test_package.timestamptz_variable = @timestamp
expect(plsql.test_package.timestamptz_variable).to be_a Time
expect(plsql.test_package.timestamptz_variable).to eq(@timestamp)
end
it "should set and get TIMESTAMP WITH LOCAL TIME ZONE variable" do
plsql.test_package.timestampltz_variable = @timestamp
expect(plsql.test_package.timestampltz_variable).to be_a Time
expect(plsql.test_package.timestampltz_variable).to eq(@timestamp)
end
end
describe "LOB" do
before(:all) do
plsql.connect! CONNECTION_PARAMS
plsql.execute <<-SQL
CREATE OR REPLACE PACKAGE test_package IS
clob_variable CLOB;
clob_default CLOB := 'default';
nclob_variable CLOB;
blob_variable BLOB;
END;
SQL
plsql.execute <<-SQL
CREATE OR REPLACE PACKAGE BODY test_package IS
END;
SQL
end
after(:all) do
plsql.execute "DROP PACKAGE test_package"
plsql.logoff
end
it "should set and get CLOB variable" do
plsql.test_package.clob_variable = "abc"
expect(plsql.test_package.clob_variable).to eq("abc")
end
it "should get CLOB variable default value" do
expect(plsql.test_package.clob_default).to eq("default")
end
it "should set and get NCLOB variable" do
plsql.test_package.nclob_variable = "abc"
expect(plsql.test_package.nclob_variable).to eq("abc")
end
it "should set and get BLOB variable" do
plsql.test_package.blob_variable = "\000\001\003"
expect(plsql.test_package.blob_variable).to eq("\000\001\003")
end
end
describe "table column type" do
before(:all) do
plsql.connect! CONNECTION_PARAMS
plsql.execute <<-SQL
CREATE TABLE test_employees (
employee_id NUMBER(15),
first_name VARCHAR2(50),
last_name VARCHAR2(50),
hire_date DATE
)
SQL
plsql.execute <<-SQL
CREATE OR REPLACE PACKAGE test_package IS
employee_id test_employees.employee_id%TYPE;
first_name test_employees.first_name%TYPE;
hire_date test_employees.hire_date%TYPE;
END;
SQL
plsql.execute <<-SQL
CREATE OR REPLACE PACKAGE BODY test_package IS
END;
SQL
end
after(:all) do
plsql.execute "DROP PACKAGE test_package"
plsql.execute "DROP TABLE test_employees"
plsql.logoff
end
it "should set and get NUMBER variable" do
plsql.test_package.employee_id = 1
expect(plsql.test_package.employee_id).to eq(1)
end
it "should set and get VARCHAR2 variable" do
plsql.test_package.first_name = "First"
expect(plsql.test_package.first_name).to eq("First")
end
it "should set and get DATE variable" do
today = Time.local(2009, 12, 22)
plsql.test_package.hire_date = today
expect(plsql.test_package.hire_date).to eq(today)
end
end
describe "constants" do
before(:all) do
plsql.connect! CONNECTION_PARAMS
plsql.execute <<-SQL
CREATE OR REPLACE PACKAGE test_package IS
integer_constant CONSTANT NUMBER(1) := 1;
string_constant CONSTANT VARCHAR2(10) := 'constant';
END;
SQL
plsql.execute <<-SQL
CREATE OR REPLACE PACKAGE BODY test_package IS
END;
SQL
end
after(:all) do
plsql.execute "DROP PACKAGE test_package"
plsql.logoff
end
it "should get NUMBER constant" do
expect(plsql.test_package.integer_constant).to eq(1)
end
it "should get VARCHAR2 constant" do
expect(plsql.test_package.string_constant).to eq("constant")
end
it "should raise error when trying to set constant" do
expect {
plsql.test_package.integer_constant = 2
}.to raise_error(/PLS-00363/)
end
end
describe "object type" do
before(:all) do
plsql.connect! CONNECTION_PARAMS
plsql.execute "DROP TYPE t_employee" rescue nil
plsql.execute "DROP TYPE t_phones" rescue nil
plsql.execute <<-SQL
CREATE OR REPLACE TYPE t_address AS OBJECT (
street VARCHAR2(50),
city VARCHAR2(50),
country VARCHAR2(50)
)
SQL
plsql.execute <<-SQL
CREATE OR REPLACE TYPE t_phone AS OBJECT (
type VARCHAR2(10),
phone_number VARCHAR2(50)
)
SQL
plsql.execute <<-SQL
CREATE OR REPLACE TYPE t_phones AS TABLE OF T_PHONE
SQL
plsql.execute <<-SQL
CREATE OR REPLACE TYPE t_employee AS OBJECT (
employee_id NUMBER(15),
first_name VARCHAR2(50),
last_name VARCHAR2(50),
hire_date DATE,
address t_address,
phones t_phones
)
SQL
@phones = [{ type: "mobile", phone_number: "123456" }, { type: "home", phone_number: "654321" }]
@employee = {
employee_id: 1,
first_name: "First",
last_name: "Last",
hire_date: Time.local(2000, 01, 31),
address: { street: "Main street 1", city: "Riga", country: "Latvia" },
phones: @phones
}
plsql.execute <<-SQL
CREATE OR REPLACE PACKAGE test_package IS
g_employee t_employee;
g_employee2 hr.t_employee;
g_phones t_phones;
END;
SQL
plsql.execute <<-SQL
CREATE OR REPLACE PACKAGE BODY test_package IS
END;
SQL
end
after(:all) do
plsql.execute "DROP PACKAGE test_package"
plsql.execute "DROP TYPE t_employee"
plsql.execute "DROP TYPE t_address"
plsql.execute "DROP TYPE t_phones"
plsql.execute "DROP TYPE t_phone"
plsql.logoff
end
it "should set and get object type variable" do
plsql.test_package.g_employee = @employee
expect(plsql.test_package.g_employee).to eq(@employee)
end
it "should set and get object type variable when schema prefix is used with type" do
plsql.hr.test_package.g_employee2 = @employee
expect(plsql.hr.test_package.g_employee2).to eq(@employee)
end
it "should set and get collection type variable" do
plsql.test_package.g_phones = @phones
expect(plsql.test_package.g_phones).to eq(@phones)
end
end
describe "table row type" do
before(:all) do
plsql.connect! CONNECTION_PARAMS
plsql.execute <<-SQL
CREATE TABLE test_employees (
employee_id NUMBER(15),
first_name VARCHAR2(50),
last_name VARCHAR2(50),
hire_date DATE
)
SQL
@employee = {
employee_id: 1,
first_name: "First",
last_name: "Last",
hire_date: Time.local(2000, 01, 31)
}
plsql.execute <<-SQL
CREATE OR REPLACE PACKAGE test_package IS
g_employee test_employees%ROWTYPE;
END;
SQL
plsql.execute <<-SQL
CREATE OR REPLACE PACKAGE BODY test_package IS
END;
SQL
end
after(:all) do
plsql.execute "DROP PACKAGE test_package"
plsql.execute "DROP TABLE test_employees"
plsql.logoff
end
it "should set and get table ROWTYPE variable" do
plsql.test_package.g_employee = @employee
expect(plsql.test_package.g_employee).to eq(@employee)
end
end
describe "booleans" do
before(:all) do
plsql.connect! CONNECTION_PARAMS
plsql.execute <<-SQL
CREATE OR REPLACE PACKAGE test_package IS
boolean_variable BOOLEAN;
END;
SQL
plsql.execute <<-SQL
CREATE OR REPLACE PACKAGE BODY test_package IS
END;
SQL
end
after(:all) do
plsql.execute "DROP PACKAGE test_package"
plsql.logoff
end
it "should set and get BOOLEAN variable" do
expect(plsql.test_package.boolean_variable).to be_nil
plsql.test_package.boolean_variable = true
expect(plsql.test_package.boolean_variable).to be_truthy
plsql.test_package.boolean_variable = false
expect(plsql.test_package.boolean_variable).to be_falsey
end
end
end
| ruby | MIT | 7bee9ba2b3207de7c1ae4112d8af2636b586c610 | 2026-01-04T17:45:33.227772Z | false |
rsim/ruby-plsql | https://github.com/rsim/ruby-plsql/blob/7bee9ba2b3207de7c1ae4112d8af2636b586c610/spec/plsql/connection_spec.rb | spec/plsql/connection_spec.rb | # encoding: utf-8
require "spec_helper"
describe "Connection" do
before(:all) do
@raw_conn = get_connection
@conn = PLSQL::Connection.create(@raw_conn)
end
after(:all) do
unless defined?(JRuby)
@raw_conn.logoff rescue nil
else
@raw_conn.close rescue nil
end
end
describe "create and destroy" do
before(:all) do
@raw_conn1 = get_connection
end
before(:each) do
@conn1 = PLSQL::Connection.create(@raw_conn1)
end
it "should create connection" do
expect(@conn1.raw_connection).to eq @raw_conn1
end
unless defined?(JRuby)
it "should be oci connection" do
expect(@conn1).to be_oci
expect(@conn1.raw_driver).to eq :oci
end
else
it "should be jdbc connection" do
expect(@conn1).to be_jdbc
expect(@conn1.raw_driver).to eq :jdbc
end
end
it "should logoff connection" do
expect(@conn1.logoff).to be true
end
end
# Ruby 1.8 and 1.9
unless defined?(JRuby)
describe "OCI data type conversions" do
it "should translate PL/SQL VARCHAR to Ruby String" do
expect(@conn.plsql_to_ruby_data_type(data_type: "VARCHAR", data_length: 100)).to eq [String, 100]
expect(@conn.plsql_to_ruby_data_type(data_type: "VARCHAR", data_length: nil)).to eq [String, 32767]
end
it "should translate PL/SQL VARCHAR2 to Ruby String" do
expect(@conn.plsql_to_ruby_data_type(data_type: "VARCHAR2", data_length: 100)).to eq [String, 100]
expect(@conn.plsql_to_ruby_data_type(data_type: "VARCHAR2", data_length: nil)).to eq [String, 32767]
end
it "should translate PL/SQL CLOB to Ruby String" do
expect(@conn.plsql_to_ruby_data_type(data_type: "CLOB", data_length: 100_000)).to eq [OCI8::CLOB, nil]
expect(@conn.plsql_to_ruby_data_type(data_type: "CLOB", data_length: nil)).to eq [OCI8::CLOB, nil]
end
it "should translate PL/SQL NUMBER to Ruby OraNumber" do
expect(@conn.plsql_to_ruby_data_type(data_type: "NUMBER", data_length: 15)).to eq [OraNumber, nil]
end
it "should translate PL/SQL DATE to Ruby DateTime" do
expect(@conn.plsql_to_ruby_data_type(data_type: "DATE", data_length: nil)).to eq [DateTime, nil]
end
it "should translate PL/SQL TIMESTAMP to Ruby Time" do
expect(@conn.plsql_to_ruby_data_type(data_type: "TIMESTAMP", data_length: nil)).to eq [Time, nil]
end
it "should not translate small Ruby Integer when OraNumber type specified" do
expect(@conn.ruby_value_to_ora_value(100, OraNumber)).to eql(100)
end
it "should not translate big Ruby Integer when OraNumber type specified" do
ora_number = @conn.ruby_value_to_ora_value(12345678901234567890, OraNumber)
expect(ora_number).to be_an Integer
expect(ora_number.to_s).to eq "12345678901234567890"
# OraNumber has more numeric comparison methods in ruby-oci8 2.0
expect(ora_number).to eq OraNumber.new("12345678901234567890") if OCI8::VERSION >= "2.0.0"
end
it "should translate Ruby String value to OCI8::CLOB when OCI8::CLOB type specified" do
large_text = "x" * 100_000
ora_value = @conn.ruby_value_to_ora_value(large_text, OCI8::CLOB)
expect(ora_value.class).to eq OCI8::CLOB
expect(ora_value.size).to eq 100_000
ora_value.rewind
expect(ora_value.read).to eq large_text
end
it "should translate Oracle OraNumber integer value to Integer" do
expect(@conn.ora_value_to_ruby_value(OraNumber.new(100))).to eql(100)
end
it "should translate Oracle OraNumber float value to BigDecimal" do
expect(@conn.ora_value_to_ruby_value(OraNumber.new(100.11))).to eql(BigDecimal("100.11"))
end
# ruby-oci8 2.0 returns DATE as Time or DateTime
if OCI8::VERSION < "2.0.0"
it "should translate Oracle OraDate value to Time" do
now = OraDate.now
expect(@conn.ora_value_to_ruby_value(now)).to eql(now.to_time)
end
end
it "should translate Oracle CLOB value to String" do
large_text = "x" * 100_000
clob = OCI8::CLOB.new(@raw_conn, large_text)
expect(@conn.ora_value_to_ruby_value(clob)).to eq large_text
end
end
# JRuby
else
describe "JDBC data type conversions" do
it "should translate PL/SQL VARCHAR to Ruby String" do
expect(@conn.plsql_to_ruby_data_type(data_type: "VARCHAR", data_length: 100)).to eq [String, 100]
expect(@conn.plsql_to_ruby_data_type(data_type: "VARCHAR", data_length: nil)).to eq [String, 32767]
end
it "should translate PL/SQL VARCHAR2 to Ruby String" do
expect(@conn.plsql_to_ruby_data_type(data_type: "VARCHAR2", data_length: 100)).to eq [String, 100]
expect(@conn.plsql_to_ruby_data_type(data_type: "VARCHAR2", data_length: nil)).to eq [String, 32767]
end
it "should translate PL/SQL NUMBER to Ruby BigDecimal" do
expect(@conn.plsql_to_ruby_data_type(data_type: "NUMBER", data_length: 15)).to eq [BigDecimal, nil]
end
it "should translate PL/SQL DATE to Ruby DateTime" do
expect(@conn.plsql_to_ruby_data_type(data_type: "DATE", data_length: nil)).to eq [DateTime, nil]
end
it "should translate PL/SQL TIMESTAMP to Ruby Time" do
expect(@conn.plsql_to_ruby_data_type(data_type: "TIMESTAMP", data_length: nil)).to eq [Time, nil]
end
it "should not translate Ruby Integer when BigDecimal type specified" do
expect(@conn.ruby_value_to_ora_value(100, BigDecimal)).to eq java.math.BigDecimal.new(100)
end
it "should translate Ruby String to string value" do
expect(@conn.ruby_value_to_ora_value(1.1, String)).to eq "1.1"
end
it "should translate Ruby Integer value to BigDecimal when BigDecimal type specified" do
big_decimal = @conn.ruby_value_to_ora_value(12345678901234567890, BigDecimal)
expect(big_decimal).to eq java.math.BigDecimal.new("12345678901234567890")
end
it "should translate Ruby String value to Java::OracleSql::CLOB when Java::OracleSql::CLOB type specified" do
large_text = "x" * 100_000
ora_value = @conn.ruby_value_to_ora_value(large_text, Java::OracleSql::CLOB)
expect(ora_value.class).to eq Java::OracleSql::CLOB
expect(ora_value.length).to eq 100_000
expect(ora_value.getSubString(1, ora_value.length)).to eq large_text
ora_value.freeTemporary
end
it "should translate Ruby nil value to nil when Java::OracleSql::CLOB type specified" do
ora_value = @conn.ruby_value_to_ora_value(nil, Java::OracleSql::CLOB)
expect(ora_value).to be_nil
end
it "should translate Oracle BigDecimal integer value to Integer" do
expect(@conn.ora_value_to_ruby_value(BigDecimal("100"))).to eql(100)
end
it "should translate Oracle BigDecimal float value to BigDecimal" do
expect(@conn.ora_value_to_ruby_value(BigDecimal("100.11"))).to eql(BigDecimal("100.11"))
end
it "should translate Oracle CLOB value to String" do
large_text = "āčē" * 100_000
clob = @conn.ruby_value_to_ora_value(large_text, Java::OracleSql::CLOB)
expect(@conn.ora_value_to_ruby_value(clob)).to eq large_text
clob.freeTemporary
end
it "should translate empty Oracle CLOB value to nil" do
clob = @conn.ruby_value_to_ora_value(nil, Java::OracleSql::CLOB)
expect(@conn.ora_value_to_ruby_value(clob)).to be_nil
end
end
end
describe "SQL SELECT statements" do
it "should execute SQL statement and return first result" do
@now = Time.local(2008, 05, 31, 23, 22, 11)
expect(@conn.select_first("SELECT 'abc',123,123.456,
TO_DATE('#{@now.strftime("%Y-%m-%d %H:%M:%S")}','YYYY-MM-DD HH24:MI:SS')
FROM dual")).to eq ["abc", 123, 123.456, @now]
end
it "should execute SQL statement and return first result as hash" do
@now = Time.local(2008, 05, 31, 23, 22, 11)
expect(@conn.select_hash_first("SELECT 'abc' a, 123 b, 123.456 c,
TO_DATE('#{@now.strftime("%Y-%m-%d %H:%M:%S")}', 'YYYY-MM-DD HH24:MI:SS') d
FROM dual")).to eq(a: "abc", b: 123, c: 123.456, d: @now)
end
it "should execute SQL statement with bind parameters and return first result" do
@today = Date.parse("2008-05-31")
@now = Time.local(2008, 05, 31, 23, 22, 11)
expect(@conn.select_first("SELECT :1,:2,:3,:4,:5 FROM dual",
"abc", 123, 123.456, @now, @today)).to eq ["abc", 123, 123.456, @now, Time.parse(@today.to_s)]
end
it "should execute SQL statement with NULL values and return first result" do
@now = Time.local(2008, 05, 31, 23, 22, 11)
expect(@conn.select_first("SELECT NULL,123,123.456,
TO_DATE('#{@now.strftime("%Y-%m-%d %H:%M:%S")}','YYYY-MM-DD HH24:MI:SS')
FROM dual")).to eq [nil, 123, 123.456, @now]
end
if defined?(JRuby)
it "should execute SQL statement with NULL values as bind parameters and return first result" do
@today = Date.parse("2008-05-31")
@now = Time.local(2008, 05, 31, 23, 22, 11)
expect(@conn.select_first("SELECT :1,:2,:3,:4,:5 FROM dual",
nil, 123, 123.456, @now, @today)).to eq [nil, 123, 123.456, @now, Time.parse(@today.to_s)]
end
end
it "should execute SQL statement and return all results" do
@now = Time.local(2008, 05, 31, 23, 22, 11)
expect(@conn.select_all("SELECT 'abc',123,123.456,
TO_DATE('#{@now.strftime("%Y-%m-%d %H:%M:%S")}','YYYY-MM-DD HH24:MI:SS')
FROM dual
UNION ALL SELECT 'abc',123,123.456,
TO_DATE('#{@now.strftime("%Y-%m-%d %H:%M:%S")}','YYYY-MM-DD HH24:MI:SS')
FROM dual")).to eq [["abc", 123, 123.456, @now], ["abc", 123, 123.456, @now]]
end
it "should execute SQL statement and return all results as hash" do
@now = Time.local(2008, 05, 31, 23, 22, 11)
expect(@conn.select_hash_all("SELECT 'abc' a, 123 b, 123.456 c,
TO_DATE('#{@now.strftime("%Y-%m-%d %H:%M:%S")}','YYYY-MM-DD HH24:MI:SS') d
FROM dual
UNION ALL SELECT 'def' a, 123 b, 123.456 c,
TO_DATE('#{@now.strftime("%Y-%m-%d %H:%M:%S")}','YYYY-MM-DD HH24:MI:SS') d
FROM dual")).to eq [{ a: "abc", b: 123, c: 123.456, d: @now }, { a: "def", b: 123, c: 123.456, d: @now }]
end
it "should execute SQL statement with bind parameters and return all results" do
@now = Time.local(2008, 05, 31, 23, 22, 11)
expect(@conn.select_all("SELECT :1,:2,:3,:4 FROM dual UNION ALL SELECT :1,:2,:3,:4 FROM dual",
"abc", 123, 123.456, @now, "abc", 123, 123.456, @now)).to eq [["abc", 123, 123.456, @now], ["abc", 123, 123.456, @now]]
end
it "should execute SQL statement and yield all results in block" do
@now = Time.local(2008, 05, 31, 23, 22, 11)
expect(@conn.select_all("SELECT 'abc',123,123.456,
TO_DATE('#{@now.strftime("%Y-%m-%d %H:%M:%S")}','YYYY-MM-DD HH24:MI:SS')
FROM dual
UNION ALL SELECT 'abc',123,123.456,
TO_DATE('#{@now.strftime("%Y-%m-%d %H:%M:%S")}','YYYY-MM-DD HH24:MI:SS')
FROM dual") do |r|
expect(r).to eq ["abc", 123, 123.456, @now]
end).to eq 2
end
it "should execute SQL statement with bind parameters and yield all results in block" do
@now = Time.local(2008, 05, 31, 23, 22, 11)
expect(@conn.select_all("SELECT :1,:2,:3,:4 FROM dual UNION ALL SELECT :1,:2,:3,:4 FROM dual",
"abc", 123, 123.456, @now, "abc", 123, 123.456, @now) do |r|
expect(r).to eq ["abc", 123, 123.456, @now]
end).to eq 2
end
end
describe "PL/SQL procedures" do
before(:all) do
@random = rand(1000)
@now = Time.local(2008, 05, 31, 23, 22, 11)
sql = <<-SQL
CREATE OR REPLACE FUNCTION test_add_random (p_number NUMBER, p_varchar IN OUT VARCHAR2, p_date IN OUT DATE)
RETURN NUMBER
IS
BEGIN
RETURN p_number + #{@random};
END test_add_random;
SQL
expect(@conn.exec(sql)).to be true
end
after(:all) do
@conn.exec "DROP FUNCTION test_add_random"
end
it "should parse PL/SQL procedure call and bind parameters and exec and get bind parameter value" do
sql = <<-SQL
BEGIN
:result := test_add_random (:p_number, :p_varchar, :p_date);
END;
SQL
cursor = @conn.parse(sql)
cursor.bind_param(":result", nil, data_type: "NUMBER", in_out: "OUT")
cursor.bind_param(":p_number", 100, data_type: "NUMBER", in_out: "IN")
cursor.bind_param(":p_varchar", "abc", data_type: "VARCHAR2", in_out: "IN/OUT")
cursor.bind_param(":p_date", @now, data_type: "DATE", in_out: "IN/OUT")
cursor.exec
expect(cursor[":result"]).to eq @random + 100
expect(cursor[":p_varchar"]).to eq "abc"
expect(cursor[":p_date"]).to eq @now
expect(cursor.close).to be_nil
end
end
describe "commit and rollback" do
before(:all) do
expect(@conn.exec("CREATE TABLE test_commit (dummy VARCHAR2(100))")).to be true
@conn.autocommit = false
expect(@conn).not_to be_autocommit
end
after(:all) do
@conn.exec "DROP TABLE test_commit"
end
after(:each) do
@conn.exec "DELETE FROM test_commit"
@conn.commit
end
it "should do commit" do
@conn.exec("INSERT INTO test_commit VALUES ('test')")
@conn.commit
expect(@conn.select_first("SELECT COUNT(*) FROM test_commit")[0]).to eq 1
end
it "should do rollback" do
@conn.exec("INSERT INTO test_commit VALUES ('test')")
@conn.rollback
expect(@conn.select_first("SELECT COUNT(*) FROM test_commit")[0]).to eq 0
end
it "should do commit and rollback should not undo commited transaction" do
@conn.exec("INSERT INTO test_commit VALUES ('test')")
@conn.commit
@conn.rollback
expect(@conn.select_first("SELECT COUNT(*) FROM test_commit")[0]).to eq 1
end
end
describe "prefetch rows" do
after(:each) do
@conn.prefetch_rows = 1 # set back to default
end
it "should set prefetch rows for connection" do
sql = "SELECT 1 FROM dual UNION ALL SELECT 1/0 FROM dual"
@conn.prefetch_rows = 2
expect {
@conn.cursor_from_query(sql)
}.to raise_error(/divisor is equal to zero/)
@conn.prefetch_rows = 1
expect {
@conn.cursor_from_query(sql)
}.not_to raise_error
end
it "should fetch just one row when using select_first" do
sql = "SELECT 1 FROM dual UNION ALL SELECT 1/0 FROM dual"
@conn.prefetch_rows = 2
expect {
@conn.select_first(sql)
}.not_to raise_error
end
end
describe "describe synonym" do
before(:all) do
@conn.exec "CREATE SYNONYM hr.synonym_for_dual FOR sys.dual"
end
after(:all) do
@conn.exec "DROP SYNONYM hr.synonym_for_dual"
end
it "should describe local synonym" do
expect(@conn.describe_synonym("HR", "SYNONYM_FOR_DUAL")).to eq ["SYS", "DUAL"]
expect(@conn.describe_synonym("hr", "synonym_for_dual")).to eq ["SYS", "DUAL"]
expect(@conn.describe_synonym(:hr, :synonym_for_dual)).to eq ["SYS", "DUAL"]
end
it "should return nil on non-existing synonym" do
expect(@conn.describe_synonym("HR", "SYNONYM_FOR_XXX")).to be_nil
expect(@conn.describe_synonym("hr", "synonym_for_xxx")).to be_nil
expect(@conn.describe_synonym(:hr, :synonym_for_xxx)).to be_nil
end
it "should describe public synonym" do
expect(@conn.describe_synonym("PUBLIC", "DUAL")).to eq ["SYS", "DUAL"]
expect(@conn.describe_synonym("PUBLIC", "dual")).to eq ["SYS", "DUAL"]
expect(@conn.describe_synonym("PUBLIC", :dual)).to eq ["SYS", "DUAL"]
end
end
describe "session information" do
it "should get database version" do
# using Oracle version 10.2.0.4 for unit tests
expect(@conn.database_version).to eq DATABASE_VERSION.split(".").map { |n| n.to_i }
end
it "should get session ID" do
expect(@conn.session_id).to eq @conn.select_first("SELECT USERENV('SESSIONID') FROM dual")[0].to_i
end
end
describe "drop ruby temporary tables" do
after(:all) do
@conn.drop_all_ruby_temporary_tables
end
it "should drop all ruby temporary tables" do
tmp_table = "ruby_111_222_333"
@conn.exec "CREATE GLOBAL TEMPORARY TABLE #{tmp_table} (dummy CHAR(1))"
expect { @conn.select_first("SELECT * FROM #{tmp_table}") }.not_to raise_error
@conn.drop_all_ruby_temporary_tables
expect { @conn.select_first("SELECT * FROM #{tmp_table}") }.to raise_error(/table or view does not exist/)
end
it "should drop current session ruby temporary tables" do
tmp_table = "ruby_#{@conn.session_id}_222_333"
@conn.exec "CREATE GLOBAL TEMPORARY TABLE #{tmp_table} (dummy CHAR(1))"
expect { @conn.select_first("SELECT * FROM #{tmp_table}") }.not_to raise_error
@conn.drop_session_ruby_temporary_tables
expect { @conn.select_first("SELECT * FROM #{tmp_table}") }.to raise_error(/table or view does not exist/)
end
it "should not drop other session ruby temporary tables" do
tmp_table = "ruby_#{@conn.session_id + 1}_222_333"
@conn.exec "CREATE GLOBAL TEMPORARY TABLE #{tmp_table} (dummy CHAR(1))"
expect { @conn.select_first("SELECT * FROM #{tmp_table}") }.not_to raise_error
@conn.drop_session_ruby_temporary_tables
expect { @conn.select_first("SELECT * FROM #{tmp_table}") }.not_to raise_error
end
end
describe "logoff" do
before(:each) do
# restore connection before each test
reconnect_connection
end
after(:all) do
@conn.exec "DROP TABLE test_dummy_table" rescue nil
end
def reconnect_connection
@raw_conn = get_connection
@conn = PLSQL::Connection.create(@raw_conn)
end
it "should drop current session ruby temporary tables" do
tmp_table = "ruby_#{@conn.session_id}_222_333"
@conn.exec "CREATE GLOBAL TEMPORARY TABLE #{tmp_table} (dummy CHAR(1))"
expect { @conn.select_first("SELECT * FROM #{tmp_table}") }.not_to raise_error
@conn.logoff
reconnect_connection
expect { @conn.select_first("SELECT * FROM #{tmp_table}") }.to raise_error(/table or view does not exist/)
end
it "should rollback any uncommited transactions" do
tmp_table = "ruby_#{@conn.session_id}_222_333"
old_autocommit = @conn.autocommit?
@conn.autocommit = false
@conn.exec "CREATE GLOBAL TEMPORARY TABLE #{tmp_table} (dummy CHAR(1))"
@conn.exec "CREATE TABLE test_dummy_table (dummy CHAR(1))"
@conn.exec "INSERT INTO test_dummy_table VALUES ('1')"
# logoff will drop ruby temporary tables, it should do rollback before drop table
@conn.logoff
reconnect_connection
expect(@conn.select_first("SELECT * FROM test_dummy_table")).to eq nil
@conn.autocommit = old_autocommit
end
end
end
| ruby | MIT | 7bee9ba2b3207de7c1ae4112d8af2636b586c610 | 2026-01-04T17:45:33.227772Z | false |
rsim/ruby-plsql | https://github.com/rsim/ruby-plsql/blob/7bee9ba2b3207de7c1ae4112d8af2636b586c610/spec/plsql/sequence_spec.rb | spec/plsql/sequence_spec.rb | require "spec_helper"
describe "Table" do
before(:all) do
plsql.connection = get_connection
plsql.connection.autocommit = false
plsql.execute "CREATE SEQUENCE test_employees_seq"
end
after(:all) do
plsql.execute "DROP SEQUENCE test_employees_seq"
plsql.logoff
end
after(:each) do
plsql.rollback
end
describe "find" do
it "should find existing sequence" do
expect(PLSQL::Sequence.find(plsql, :test_employees_seq)).not_to be_nil
end
it "should not find nonexisting table" do
expect(PLSQL::Sequence.find(plsql, :qwerty123456)).to be_nil
end
it "should find existing sequence in schema" do
expect(plsql.test_employees_seq).to be_a(PLSQL::Sequence)
end
end
describe "synonym" do
before(:all) do
plsql.connection.exec "CREATE SYNONYM test_employees_seq_synonym FOR hr.test_employees_seq"
end
after(:all) do
plsql.connection.exec "DROP SYNONYM test_employees_seq_synonym" rescue nil
end
it "should find synonym to sequence" do
expect(PLSQL::Sequence.find(plsql, :test_employees_seq_synonym)).not_to be_nil
end
it "should find sequence using synonym in schema" do
expect(plsql.test_employees_seq_synonym).to be_a(PLSQL::Sequence)
end
end
describe "values" do
it "should get next value from sequence" do
next_value = plsql.select_one "SELECT test_employees_seq.NEXTVAL FROM dual"
expect(plsql.test_employees_seq.nextval).to eq(next_value + 1)
end
it "should get current value from sequence" do
next_value = plsql.test_employees_seq.nextval
expect(plsql.test_employees_seq.currval).to eq(next_value)
end
end
end
| ruby | MIT | 7bee9ba2b3207de7c1ae4112d8af2636b586c610 | 2026-01-04T17:45:33.227772Z | false |
rsim/ruby-plsql | https://github.com/rsim/ruby-plsql/blob/7bee9ba2b3207de7c1ae4112d8af2636b586c610/spec/support/test_db.rb | spec/support/test_db.rb | class TestDb
DATABASE_USERS = %w{hr arunit}
def self.build
db = self.new
db.cleanup_database_users
db.create_user_tablespace
db.setup_database_users
db.connection.logoff
end
def self.database_version
db = self.new
db.database_version
end
def connection
unless defined?(@connection)
begin
Timeout::timeout(5) {
if defined?(JRUBY_VERSION)
@connection = java.sql.DriverManager.get_connection(
"jdbc:oracle:thin:@127.0.0.1:1521/XE",
"system",
"oracle"
)
else
@connection = OCI8.new(
"system",
"oracle",
"(DESCRIPTION=(ADDRESS=(PROTOCOL=tcp)(HOST=127.0.0.1)(PORT=1521))(CONNECT_DATA=(SERVICE_NAME=XE)))"
)
end
}
rescue Timeout::Error
raise "Cannot establish connection with Oracle database as SYSTEM user. Seams you need to start local Oracle database"
end
end
@connection
end
def create_user_tablespace
return unless connection
execute_statement(<<-STATEMENT
DECLARE
v_exists number;
BEGIN
SELECT count(1)
INTO v_exists
FROM dba_tablespaces
WHERE tablespace_name = 'TBS_USERS';
IF v_exists = 0 THEN
EXECUTE IMMEDIATE 'ALTER SYSTEM SET DB_CREATE_FILE_DEST = ''/u01/app/oracle/oradata/XE''';
EXECUTE IMMEDIATE 'CREATE TABLESPACE TBS_USERS DATAFILE ''tbs_users.dat'' SIZE 10M REUSE AUTOEXTEND ON NEXT 10M MAXSIZE 200M';
END IF;
END;
STATEMENT
)
end
def database_users
DATABASE_USERS.inject([]) { |array, user| array << [user.upcase, user] }
end
def cleanup_database_users
return unless connection
database_users.each do | db, _ |
execute_statement(<<-STATEMENT
DECLARE
v_count INTEGER := 0;
l_cnt INTEGER;
BEGIN
SELECT COUNT (1)
INTO v_count
FROM dba_users
WHERE username = '#{db}';
IF v_count != 0 THEN
FOR x IN (SELECT *
FROM v$session
WHERE username = '#{db}')
LOOP
EXECUTE IMMEDIATE 'ALTER SYSTEM DISCONNECT SESSION ''' || x.sid || ',' || x.serial# || ''' IMMEDIATE';
END LOOP;
EXECUTE IMMEDIATE ('DROP USER #{db} CASCADE');
END IF;
END;
STATEMENT
)
end
end
def setup_database_users
return unless connection
database_users.each do | db, passwd |
execute_statement(<<-STATEMENT
DECLARE
v_count INTEGER := 0;
BEGIN
SELECT COUNT (1)
INTO v_count
FROM dba_users
WHERE username = '#{db}';
IF v_count = 0 THEN
EXECUTE IMMEDIATE ('CREATE USER #{db} IDENTIFIED BY #{passwd} DEFAULT TABLESPACE TBS_USERS QUOTA 10m ON TBS_USERS');
EXECUTE IMMEDIATE ('GRANT create session, create table, create sequence, create procedure, create type, create view, create synonym TO #{db}');
END IF;
END;
STATEMENT
)
end
end
def database_version
query = "SELECT version FROM V$INSTANCE"
if defined?(JRUBY_VERSION)
statement = connection.create_statement
resource = statement.execute_query(query)
resource.next
value = resource.get_string("VERSION")
resource.close
statement.close
else
cursor = execute_statement(query)
value = cursor.fetch()[0]
cursor.close
end
value.match(/(.*)\.\d$/)[1]
end
def execute_statement(statement)
if defined?(JRUBY_VERSION)
statement = connection.prepare_call(statement)
statement.execute
statement.close
else
connection.exec(statement)
end
end
end
| ruby | MIT | 7bee9ba2b3207de7c1ae4112d8af2636b586c610 | 2026-01-04T17:45:33.227772Z | false |
rsim/ruby-plsql | https://github.com/rsim/ruby-plsql/blob/7bee9ba2b3207de7c1ae4112d8af2636b586c610/lib/ruby_plsql.rb | lib/ruby_plsql.rb | require "time"
require "date"
require "bigdecimal"
%w(connection sql_statements schema procedure procedure_call package variable table view sequence type version helpers).each do |file|
require "plsql/#{file}"
end
unless defined?(JRUBY_VERSION)
require "plsql/oci_connection"
else
require "plsql/jdbc_connection"
end
| ruby | MIT | 7bee9ba2b3207de7c1ae4112d8af2636b586c610 | 2026-01-04T17:45:33.227772Z | false |
rsim/ruby-plsql | https://github.com/rsim/ruby-plsql/blob/7bee9ba2b3207de7c1ae4112d8af2636b586c610/lib/ruby-plsql.rb | lib/ruby-plsql.rb | require "ruby_plsql"
| ruby | MIT | 7bee9ba2b3207de7c1ae4112d8af2636b586c610 | 2026-01-04T17:45:33.227772Z | false |
rsim/ruby-plsql | https://github.com/rsim/ruby-plsql/blob/7bee9ba2b3207de7c1ae4112d8af2636b586c610/lib/plsql/sql_statements.rb | lib/plsql/sql_statements.rb | module PLSQL
module SQLStatements
# Select first row as array or values (without column names)
def select_first(sql, *bindvars)
@connection.select_first(sql, *bindvars)
end
# Select all rows as array or values (without column names)
def select_all(sql, *bindvars, &block)
@connection.select_all(sql, *bindvars, &block)
end
# Select one value (use if only one row with one value is selected)
def select_one(sql, *bindvars)
(row = @connection.select_first(sql, *bindvars)) && row[0]
end
# Select :first or :all values. Examples:
#
# plsql.select :first, "SELECT * FROM employees WHERE employee_id = :1", 1
# plsql.select :all, "SELECT * FROM employees ORDER BY employee_id"
def select(*args)
case args[0]
when nil
raise ArgumentError, "Not enough arguments"
when :first
args.shift
@connection.select_hash_first(*args)
when :all
args.shift
@connection.select_hash_all(*args)
else
@connection.select_hash_all(*args)
end
end
# Execute SQL statement. Example:
#
# plsql.execute "DROP TABLE employees"
def execute(*args)
@connection.exec(*args)
end
# Execute COMMIT in current database session.
# Use beforehand
#
# plsql.connection.autocommit = false
#
# to turn off automatic commits after each statement.
def commit
@connection.commit
end
# Execute ROLLBACK in current database session.
# Use beforehand
#
# plsql.connection.autocommit = false
#
# to turn off automatic commits after each statement.
def rollback
@connection.rollback
end
# Create SAVEPOINT with specified name. Later use +rollback_to+ method to roll changes back
# to specified savepoint.
# Use beforehand
#
# plsql.connection.autocommit = false
#
# to turn off automatic commits after each statement.
def savepoint(name)
execute "SAVEPOINT #{name}"
end
# Roll back changes to specified savepoint (that was created using +savepoint+ method)
# Use beforehand
#
# plsql.connection.autocommit = false
#
# to turn off automatic commits after each statement.
def rollback_to(name)
execute "ROLLBACK TO #{name}"
end
end
end
| ruby | MIT | 7bee9ba2b3207de7c1ae4112d8af2636b586c610 | 2026-01-04T17:45:33.227772Z | false |
rsim/ruby-plsql | https://github.com/rsim/ruby-plsql/blob/7bee9ba2b3207de7c1ae4112d8af2636b586c610/lib/plsql/table.rb | lib/plsql/table.rb | module PLSQL
module TableClassMethods #:nodoc:
def find(schema, table)
if schema.select_first(
"SELECT table_name FROM all_tables
WHERE owner = :owner
AND table_name = :table_name",
schema.schema_name, table.to_s.upcase)
new(schema, table)
# search for synonym
elsif (row = schema.select_first(
"SELECT t.owner, t.table_name
FROM all_synonyms s, all_tables t
WHERE s.owner = :owner
AND s.synonym_name = :synonym_name
AND t.owner = s.table_owner
AND t.table_name = s.table_name
UNION ALL
SELECT t.owner, t.table_name
FROM all_synonyms s, all_tables t
WHERE s.owner = 'PUBLIC'
AND s.synonym_name = :synonym_name
AND t.owner = s.table_owner
AND t.table_name = s.table_name",
schema.schema_name, table.to_s.upcase, table.to_s.upcase))
new(schema, row[1], row[0])
else
nil
end
end
end
class Table
extend TableClassMethods
attr_reader :columns, :schema_name, :table_name #:nodoc:
def initialize(schema, table, override_schema_name = nil) #:nodoc:
@schema = schema
@schema_name = override_schema_name || schema.schema_name
@table_name = table.to_s.upcase
@columns = {}
@schema.select_all(
"SELECT c.column_name, c.column_id position,
c.data_type, c.data_length, c.data_precision, c.data_scale, c.char_used,
c.data_type_owner, c.data_type_mod,
CASE WHEN c.data_type_owner IS NULL THEN NULL
ELSE (SELECT t.typecode FROM all_types t
WHERE t.owner = c.data_type_owner
AND t.type_name = c.data_type) END typecode,
c.nullable, c.data_default
FROM all_tab_columns c
WHERE c.owner = :owner
AND c.table_name = :table_name",
@schema_name, @table_name
) do |r|
column_name, position,
data_type, data_length, data_precision, data_scale, char_used,
data_type_owner, _, typecode, nullable, data_default = r
# remove scale (n) from data_type (returned for TIMESTAMPs and INTERVALs)
data_type.sub!(/\(\d+\)/, "")
# store column metadata
@columns[column_name.downcase.to_sym] = {
position: position && position.to_i,
data_type: data_type_owner && (typecode == "COLLECTION" ? "TABLE" : "OBJECT") || data_type,
data_length: data_type_owner ? nil : data_length && data_length.to_i,
data_precision: data_precision && data_precision.to_i,
data_scale: data_scale && data_scale.to_i,
char_used: char_used,
type_owner: data_type_owner,
type_name: data_type_owner && data_type,
sql_type_name: data_type_owner && "#{data_type_owner}.#{data_type}",
nullable: nullable == "Y", # store as true or false
data_default: data_default && data_default.strip # remove leading and trailing whitespace
}
end
end
# list of table column names
def column_names
@column_names ||= @columns.keys.sort_by { |k| columns[k][:position] }
end
# General select method with :first, :all or :count as first parameter.
# It is recommended to use #first, #all or #count method instead of this one.
def select(first_or_all, sql_params = "", *bindvars)
case first_or_all
when :first, :all
select_sql = "SELECT * "
when :count
select_sql = "SELECT COUNT(*) "
else
raise ArgumentError, "Only :first, :all or :count are supported"
end
select_sql << "FROM \"#{@schema_name}\".\"#{@table_name}\" "
case sql_params
when String
select_sql << sql_params
when Hash
raise ArgumentError, "Cannot specify bind variables when passing WHERE conditions as Hash" unless bindvars.empty?
where_sqls = []
order_by_sql = nil
sql_params.each do |k, v|
if k == :order_by
order_by_sql = " ORDER BY #{v} "
elsif v.nil? || v == :is_null
where_sqls << "#{k} IS NULL"
elsif v == :is_not_null
where_sqls << "#{k} IS NOT NULL"
else
where_sqls << "#{k} = :#{k}"
bindvars << v
end
end
select_sql << "WHERE " << where_sqls.join(" AND ") unless where_sqls.empty?
select_sql << order_by_sql if order_by_sql
else
raise ArgumentError, "Only String or Hash can be provided as SQL condition argument"
end
if first_or_all == :count
@schema.select_one(select_sql, *bindvars)
else
@schema.select(first_or_all, select_sql, *bindvars)
end
end
# Select all table records using optional conditions. Examples:
#
# plsql.employees.all
# plsql.employees.all(:order_by => :employee_id)
# plsql.employees.all("WHERE employee_id > :employee_id", 5)
#
def all(sql = "", *bindvars)
select(:all, sql, *bindvars)
end
# Select first table record using optional conditions. Examples:
#
# plsql.employees.first
# plsql.employees.first(:employee_id => 1)
# plsql.employees.first("WHERE employee_id = 1")
# plsql.employees.first("WHERE employee_id = :employee_id", 1)
#
def first(sql = "", *bindvars)
select(:first, sql, *bindvars)
end
# Count table records using optional conditions. Examples:
#
# plsql.employees.count
# plsql.employees.count("WHERE employee_id > :employee_id", 5)
#
def count(sql = "", *bindvars)
select(:count, sql, *bindvars)
end
# Insert record or records in table. Examples:
#
# employee = { :employee_id => 1, :first_name => 'First', :last_name => 'Last', :hire_date => Time.local(2000,01,31) }
# plsql.employees.insert employee
# # => INSERT INTO employees VALUES (1, 'First', 'Last', ...)
#
# employees = [employee1, employee2, ... ] # array of many Hashes
# plsql.employees.insert employees
#
def insert(record)
# if Array of records is passed then insert each individually
if record.is_a?(Array)
record.each { |r| insert(r) }
return nil
end
table_proc = TableProcedure.new(@schema, self, :insert)
record = record.map { |k, v| [k.downcase.to_sym, v] }.to_h
table_proc.add_insert_arguments(record)
call = ProcedureCall.new(table_proc, table_proc.argument_values)
call.exec
end
# Insert record or records in table using array of values. Examples:
#
# # with values for all columns
# plsql.employees.insert_values [1, 'First', 'Last', Time.local(2000,01,31)]
# # => INSERT INTO employees VALUES (1, 'First', 'Last', ...)
#
# # with values for specified columns
# plsql.employees.insert_values [:employee_id, :first_name, :last_name], [1, 'First', 'Last']
# # => INSERT INTO employees (employee_id, first_name, last_name) VALUES (1, 'First', 'Last')
#
# # with values for many records
# plsql.employees.insert_values [:employee_id, :first_name, :last_name], [1, 'First', 'Last'], [2, 'Second', 'Last']
# # => INSERT INTO employees (employee_id, first_name, last_name) VALUES (1, 'First', 'Last')
# # => INSERT INTO employees (employee_id, first_name, last_name) VALUES (2, 'Second', 'Last')
#
def insert_values(*args)
raise ArgumentError, "no arguments given" unless args.first
# if first argument is array of symbols then use it as list of fields
if args.first.all? { |a| a.instance_of?(Symbol) }
fields = args.shift
# otherwise use all columns as list of fields
else
fields = column_names
end
args.each do |record|
raise ArgumentError, "record should be Array of values" unless record.is_a?(Array)
raise ArgumentError, "wrong number of column values" unless record.size == fields.size
insert(ArrayHelpers::to_hash(fields, record))
end
end
# Update table records using optional conditions. Example:
#
# plsql.employees.update(:first_name => 'Second', :where => {:employee_id => 1})
# # => UPDATE employees SET first_name = 'Second' WHERE employee_id = 1
#
def update(params)
raise ArgumentError, "Only Hash parameter can be passed to table update method" unless params.is_a?(Hash)
where = params.delete(:where)
table_proc = TableProcedure.new(@schema, self, :update)
table_proc.add_set_arguments(params)
table_proc.add_where_arguments(where) if where
call = ProcedureCall.new(table_proc, table_proc.argument_values)
call.exec
end
# Delete table records using optional conditions. Example:
#
# plsql.employees.delete(:employee_id => 1)
# # => DELETE FROM employees WHERE employee_id = 1
#
def delete(sql_params = "", *bindvars)
delete_sql = "DELETE FROM \"#{@schema_name}\".\"#{@table_name}\" "
case sql_params
when String
delete_sql << sql_params
when Hash
raise ArgumentError, "Cannot specify bind variables when passing WHERE conditions as Hash" unless bindvars.empty?
where_sqls = []
sql_params.each do |k, v|
where_sqls << "#{k} = :#{k}"
bindvars << v
end
delete_sql << "WHERE " << where_sqls.join(" AND ") unless where_sqls.empty?
else
raise ArgumentError, "Only String or Hash can be provided as SQL condition argument"
end
@schema.execute(delete_sql, *bindvars)
end
# wrapper class to simulate Procedure class for ProcedureClass#exec
class TableProcedure #:nodoc:
attr_reader :arguments, :argument_list, :return, :out_list, :schema
def initialize(schema, table, operation)
@schema = schema
@table = table
@operation = operation
@return = [nil]
@out_list = [[]]
case @operation
when :insert
@argument_list = [[]]
@arguments = [{}]
@insert_columns = []
@insert_values = []
when :update
@argument_list = [[]]
@arguments = [{}]
@set_sqls = []
@set_values = []
@where_sqls = []
@where_values = []
end
end
def overloaded?
false
end
def procedure
nil
end
def add_insert_arguments(params)
params.each do |k, v|
raise ArgumentError, "Invalid column name #{k.inspect} specified as argument" unless (column_metadata = @table.columns[k])
@argument_list[0] << k
@arguments[0][k] = column_metadata
@insert_values << v
end
end
def add_set_arguments(params)
params.each do |k, v|
raise ArgumentError, "Invalid column name #{k.inspect} specified as argument" unless (column_metadata = @table.columns[k])
@argument_list[0] << k
@arguments[0][k] = column_metadata
@set_sqls << "#{k}=:#{k}"
@set_values << v
end
end
def add_where_arguments(params)
case params
when Hash
params.each do |k, v|
raise ArgumentError, "Invalid column name #{k.inspect} specified as argument" unless (column_metadata = @table.columns[k])
@argument_list[0] << :"w_#{k}"
@arguments[0][:"w_#{k}"] = column_metadata
@where_sqls << "#{k}=:w_#{k}"
@where_values << v
end
when String
@where_sqls << params
end
end
def argument_values
case @operation
when :insert
@insert_values
when :update
@set_values + @where_values
end
end
def call_sql(params_string)
case @operation
when :insert
"INSERT INTO \"#{@table.schema_name}\".\"#{@table.table_name}\"(#{@argument_list[0].map { |a| a.to_s }.join(', ')}) VALUES (#{params_string});\n"
when :update
update_sql = "UPDATE \"#{@table.schema_name}\".\"#{@table.table_name}\" SET #{@set_sqls.join(', ')}"
update_sql << " WHERE #{@where_sqls.join(' AND ')}" unless @where_sqls.empty?
update_sql << ";\n"
update_sql
end
end
end
end
end
| ruby | MIT | 7bee9ba2b3207de7c1ae4112d8af2636b586c610 | 2026-01-04T17:45:33.227772Z | false |
rsim/ruby-plsql | https://github.com/rsim/ruby-plsql/blob/7bee9ba2b3207de7c1ae4112d8af2636b586c610/lib/plsql/version.rb | lib/plsql/version.rb | module PLSQL #:nodoc:
VERSION = File.read(File.dirname(__FILE__) + "/../../VERSION").chomp
end
| ruby | MIT | 7bee9ba2b3207de7c1ae4112d8af2636b586c610 | 2026-01-04T17:45:33.227772Z | false |
rsim/ruby-plsql | https://github.com/rsim/ruby-plsql/blob/7bee9ba2b3207de7c1ae4112d8af2636b586c610/lib/plsql/type.rb | lib/plsql/type.rb | module PLSQL
module TypeClassMethods #:nodoc:
def find(schema, type)
if schema.select_first(
"SELECT type_name FROM all_types
WHERE owner = :owner
AND type_name = :table_name",
schema.schema_name, type.to_s.upcase)
new(schema, type)
# search for synonym
elsif (row = schema.select_first(
"SELECT t.owner, t.type_name
FROM all_synonyms s, all_types t
WHERE s.owner = :owner
AND s.synonym_name = :synonym_name
AND t.owner = s.table_owner
AND t.type_name = s.table_name
UNION ALL
SELECT t.owner, t.type_name
FROM all_synonyms s, all_types t
WHERE s.owner = 'PUBLIC'
AND s.synonym_name = :synonym_name
AND t.owner = s.table_owner
AND t.type_name = s.table_name",
schema.schema_name, type.to_s.upcase, type.to_s.upcase))
new(schema, row[1], row[0])
else
nil
end
end
end
class Type
extend TypeClassMethods
attr_reader :typecode, :attributes, :schema_name, :type_name, :type_object_id #:nodoc:
def initialize(schema, type, override_schema_name = nil) #:nodoc:
@schema = schema
@schema_name = override_schema_name || schema.schema_name
@type_name = type.to_s.upcase
@attributes = {}
@type_procedures = {}
@typecode, @type_object_id = @schema.select_first(
"SELECT t.typecode, o.object_id FROM all_types t, all_objects o
WHERE t.owner = :owner
AND t.type_name = :type_name
AND o.owner = t.owner
AND o.object_name = t.type_name
AND o.object_type = 'TYPE'",
@schema_name, @type_name)
@schema.select_all(
"SELECT attr_name, attr_no,
attr_type_name, length, precision, scale,
attr_type_owner, attr_type_mod,
(SELECT t.typecode FROM all_types t
WHERE t.owner = attr_type_owner
AND t.type_name = attr_type_name) typecode
FROM all_type_attrs
WHERE owner = :owner
AND type_name = :type_name
ORDER BY attr_no",
@schema_name, @type_name
) do |r|
attr_name, position,
data_type, data_length, data_precision, data_scale,
data_type_owner, _, typecode = r
@attributes[attr_name.downcase.to_sym] = {
position: position && position.to_i,
data_type: data_type_owner && (typecode == "COLLECTION" ? "TABLE" : "OBJECT") || data_type,
data_length: data_type_owner ? nil : data_length && data_length.to_i,
data_precision: data_precision && data_precision.to_i,
data_scale: data_scale && data_scale.to_i,
type_owner: data_type_owner,
type_name: data_type_owner && data_type,
sql_type_name: data_type_owner && "#{data_type_owner}.#{data_type}"
}
end
end
# is type collection?
def collection?
@is_collection ||= @typecode == "COLLECTION"
end
# list of object type attribute names
def attribute_names
@attribute_names ||= @attributes.keys.sort_by { |k| @attributes[k][:position] }
end
# create new PL/SQL object instance
def new(*args, &block)
procedure = find_procedure(:new)
# in case of collections pass array of elements as one argument for constructor
if collection? && !(args.size == 1 && args[0].is_a?(Array))
args = [args]
end
result = procedure.exec_with_options(args, { skip_self: true }, &block)
# TODO: collection constructor should return Array of ObhjectInstance objects
if collection?
result
else
# TODO: what to do if block is passed to constructor?
ObjectInstance.create(self, result)
end
end
def method_missing(method, *args, &block) #:nodoc:
if procedure = find_procedure(method)
procedure.exec_with_options(args, {}, &block)
else
raise ArgumentError, "No PL/SQL procedure '#{method.to_s.upcase}' found for type '#{@type_name}'"
end
end
def find_procedure(new_or_procedure) #:nodoc:
@type_procedures[new_or_procedure] ||= begin
procedure_name = new_or_procedure == :new ? @type_name : new_or_procedure
# find defined procedure for type
if @schema.select_first(
"SELECT procedure_name FROM all_procedures
WHERE owner = :owner
AND object_name = :object_name
AND procedure_name = :procedure_name",
@schema_name, @type_name, procedure_name.to_s.upcase)
TypeProcedure.new(@schema, self, procedure_name)
# call default constructor
elsif new_or_procedure == :new
TypeProcedure.new(@schema, self, :new)
end
end
end
# wrapper class to simulate Procedure class for ProcedureClass#exec
class TypeProcedure #:nodoc:
include ProcedureCommon
def initialize(schema, type, procedure)
@schema = schema
@type = type
@schema_name = @type.schema_name
@type_name = @type.type_name
@object_id = @type.type_object_id
# if default constructor
if @default_constructor = (procedure == :new)
@procedure = @type.collection? ? nil : @type_name
set_default_constructor_arguments
# if defined type procedure
else
@procedure = procedure.to_s.upcase
get_argument_metadata
# add also definition for default constructor in case of custom constructor
set_default_constructor_arguments if @procedure == @type_name
end
# constructors do not need type prefix in call
@package = @procedure == @type_name ? nil : @type_name
end
# will be called for collection constructor
def call_sql(params_string)
"#{params_string};\n"
end
attr_reader :arguments, :argument_list, :out_list
def arguments_without_self
@arguments_without_self ||= begin
hash = {}
@arguments.each do |ov, args|
hash[ov] = args.reject { |key, value| key == :self }
end
hash
end
end
def argument_list_without_self
@argument_list_without_self ||= begin
hash = {}
@argument_list.each do |ov, arg_list|
hash[ov] = arg_list.select { |arg| arg != :self }
end
hash
end
end
def out_list_without_self
@out_list_without_self ||= begin
hash = {}
@out_list.each do |ov, out_list|
hash[ov] = out_list.select { |arg| arg != :self }
end
hash
end
end
def exec_with_options(args, options = {}, &block)
call = ProcedureCall.new(self, args, options)
result = call.exec(&block)
# if procedure was called then modified object is returned in SELF output parameter
if result.is_a?(Hash) && result[:self]
object = result.delete(:self)
result.empty? ? object : [object, result]
else
result
end
end
private
def set_default_constructor_arguments
@arguments ||= {}
@argument_list ||= {}
@out_list ||= {}
@return ||= {}
# either this will be the only overload or it will be additional
overload = @arguments.keys.size
# if type is collection then expect array of objects as argument
if @type.collection?
@arguments[overload] = {
value: {
position: 1,
data_type: "TABLE",
in_out: "IN",
type_owner: @schema_name,
type_name: @type_name,
sql_type_name: "#{@schema_name}.#{@type_name}"
}
}
# otherwise if type is object type then expect object attributes as argument list
else
@arguments[overload] = @type.attributes
end
attributes = @arguments[overload]
@argument_list[overload] = attributes.keys.sort { |k1, k2| attributes[k1][:position] <=> attributes[k2][:position] }
# returns object or collection
@return[overload] = {
position: 0,
data_type: @type.collection? ? "TABLE" : "OBJECT",
in_out: "OUT",
type_owner: @schema_name,
type_name: @type_name,
sql_type_name: "#{@schema_name}.#{@type_name}"
}
@out_list[overload] = []
@overloaded = overload > 0
end
end
end
class ObjectInstance < Hash #:nodoc:
attr_accessor :plsql_type
def self.create(type, attributes)
object = self.new.merge!(attributes)
object.plsql_type = type
object
end
def method_missing(method, *args, &block)
if procedure = @plsql_type.find_procedure(method)
procedure.exec_with_options(args, self: self, &block)
else
raise ArgumentError, "No PL/SQL procedure '#{method.to_s.upcase}' found for type '#{@plsql_type.type_name}' object"
end
end
end
end
| ruby | MIT | 7bee9ba2b3207de7c1ae4112d8af2636b586c610 | 2026-01-04T17:45:33.227772Z | false |
rsim/ruby-plsql | https://github.com/rsim/ruby-plsql/blob/7bee9ba2b3207de7c1ae4112d8af2636b586c610/lib/plsql/package.rb | lib/plsql/package.rb | module PLSQL
module PackageClassMethods #:nodoc:
def find(schema, package)
package_name = package.to_s.upcase
find_in_schema(schema, package_name) || find_by_synonym(schema, package_name)
end
def find_in_schema(schema, package_name)
row = schema.select_first(<<-SQL, schema.schema_name, package_name)
SELECT object_name
FROM all_objects
WHERE owner = :owner
AND object_name = :package
AND object_type = 'PACKAGE'
SQL
new(schema, package_name) if row
end
def find_by_synonym(schema, package_name)
row = schema.select_first(<<-SQL, schema.schema_name, package_name)
SELECT o.object_name, o.owner
FROM all_synonyms s,
all_objects o
WHERE s.owner IN (:owner, 'PUBLIC')
AND s.synonym_name = :synonym_name
AND o.owner = s.table_owner
AND o.object_name = s.table_name
AND o.object_type = 'PACKAGE'
ORDER BY DECODE(s.owner, 'PUBLIC', 1, 0)
SQL
new(schema, row[0], row[1]) if row
end
end
class Package #:nodoc:
extend PackageClassMethods
def initialize(schema, package, override_schema_name = nil)
@schema = schema
@override_schema_name = override_schema_name
@package = package.to_s.upcase
@package_objects = {}
end
def procedure_defined?(name)
PLSQL::Procedure.find(@schema, name, @package) ? true : false
end
def [](object_name)
object_name = object_name.to_s.downcase
@package_objects[object_name] ||= [Procedure, Variable].inject(nil) do |res, object_type|
res || object_type.find(@schema, object_name, @package, @override_schema_name)
end
end
private
def method_missing(method, *args, &block)
method = method.to_s
method.chop! if (assignment = method[/=$/])
case (object = self[method])
when Procedure
if assignment
raise ArgumentError, "Cannot assign value to package procedure '#{method.upcase}'"
end
object.exec(*args, &block)
when Variable
if assignment
unless args.size == 1 && block.nil?
raise ArgumentError, "Just one value can be assigned " \
"to package variable '#{method.upcase}'"
end
object.value = args[0]
else
unless args.size == 0 && block.nil?
raise ArgumentError, "Cannot pass arguments when getting " \
"package variable '#{method.upcase}' value"
end
object.value
end
else
raise ArgumentError, "No PL/SQL procedure or variable '#{method.upcase}' found"
end
end
end
end
| ruby | MIT | 7bee9ba2b3207de7c1ae4112d8af2636b586c610 | 2026-01-04T17:45:33.227772Z | false |
rsim/ruby-plsql | https://github.com/rsim/ruby-plsql/blob/7bee9ba2b3207de7c1ae4112d8af2636b586c610/lib/plsql/view.rb | lib/plsql/view.rb | module PLSQL
module ViewClassMethods #:nodoc:
def find(schema, view)
if schema.select_first(
"SELECT view_name FROM all_views
WHERE owner = :owner
AND view_name = :view_name",
schema.schema_name, view.to_s.upcase)
new(schema, view)
# search for synonym
elsif (row = schema.select_first(
"SELECT v.owner, v.view_name
FROM all_synonyms s, all_views v
WHERE s.owner = :owner
AND s.synonym_name = :synonym_name
AND v.owner = s.table_owner
AND v.view_name = s.table_name
UNION ALL
SELECT v.owner, v.view_name
FROM all_synonyms s, all_views v
WHERE s.owner = 'PUBLIC'
AND s.synonym_name = :synonym_name
AND v.owner = s.table_owner
AND v.view_name = s.table_name",
schema.schema_name, view.to_s.upcase, view.to_s.upcase))
new(schema, row[1], row[0])
else
nil
end
end
end
class View < Table
extend ViewClassMethods
alias :view_name :table_name #:nodoc:
end
end
| ruby | MIT | 7bee9ba2b3207de7c1ae4112d8af2636b586c610 | 2026-01-04T17:45:33.227772Z | false |
rsim/ruby-plsql | https://github.com/rsim/ruby-plsql/blob/7bee9ba2b3207de7c1ae4112d8af2636b586c610/lib/plsql/oci_connection.rb | lib/plsql/oci_connection.rb | begin
require "oci8"
rescue LoadError
# OCI8 driver is unavailable.
msg = $!.to_s
if /-- oci8$/ =~ msg
# ruby-oci8 is not installed.
# MRI <= 1.9.2, Rubinius, JRuby:
# no such file to load -- oci8
# MRI >= 1.9.3:
# cannot load such file -- oci8
msg = "Please install ruby-oci8 gem."
end
raise LoadError, "ERROR: ruby-plsql could not load ruby-oci8 library. #{msg}"
end
require "plsql/oci8_patches"
# check ruby-oci8 version
required_oci8_version = [2, 0, 3]
oci8_version_ints = OCI8::VERSION.scan(/\d+/).map { |s| s.to_i }
if (oci8_version_ints <=> required_oci8_version) < 0
raise LoadError, "ERROR: ruby-oci8 version #{OCI8::VERSION} is too old. Please install ruby-oci8 version #{required_oci8_version.join('.')} or later."
end
module PLSQL
class OCIConnection < Connection #:nodoc:
def self.create_raw(params)
connection_string = if params[:host]
"//#{params[:host]}:#{params[:port] || 1521}/#{params[:database]}"
else
params[:database]
end
new(OCI8.new(params[:username], params[:password], connection_string))
end
def logoff
super
raw_connection.logoff
end
def commit
raw_connection.commit
end
def rollback
raw_connection.rollback
end
def autocommit?
raw_connection.autocommit?
end
def autocommit=(value)
raw_connection.autocommit = value
end
def prefetch_rows=(value)
raw_connection.prefetch_rows = value
end
def exec(sql, *bindvars)
raw_connection.exec(sql, *bindvars)
true
end
class Cursor #:nodoc:
include Connection::CursorCommon
attr_reader :raw_cursor
# stack of open cursors per thread
def self.open_cursors
Thread.current[:plsql_oci_cursor_stack] ||= []
end
def initialize(conn, raw_cursor)
@connection = conn
@raw_cursor = raw_cursor
self.class.open_cursors.push self
end
def self.new_from_parse(conn, sql)
raw_cursor = conn.raw_connection.parse(sql)
self.new(conn, raw_cursor)
end
def self.new_from_query(conn, sql, bindvars = [], options = {})
cursor = new_from_parse(conn, sql)
if prefetch_rows = options[:prefetch_rows]
cursor.prefetch_rows = prefetch_rows
end
cursor.exec(*bindvars)
cursor
end
def prefetch_rows=(value)
@raw_cursor.prefetch_rows = value
end
def bind_param(arg, value, metadata)
type, length = @connection.plsql_to_ruby_data_type(metadata)
ora_value = @connection.ruby_value_to_ora_value(value, type)
@raw_cursor.bind_param(arg, ora_value, type, length)
end
def exec(*bindvars)
@raw_cursor.exec(*bindvars)
end
def [](key)
@connection.ora_value_to_ruby_value(@raw_cursor[key])
end
def fetch
row = @raw_cursor.fetch
row && row.map { |v| @connection.ora_value_to_ruby_value(v) }
end
def fields
@fields ||= @raw_cursor.get_col_names.map { |c| c.downcase.to_sym }
end
def close_raw_cursor
@raw_cursor.close
end
def close
# close all cursors that were created after this one
while (open_cursor = self.class.open_cursors.pop) && !open_cursor.equal?(self)
open_cursor.close_raw_cursor
end
close_raw_cursor
end
end
def parse(sql)
Cursor.new_from_parse(self, sql)
end
def cursor_from_query(sql, bindvars = [], options = {})
Cursor.new_from_query(self, sql, bindvars, options)
end
def plsql_to_ruby_data_type(metadata)
data_type, data_length = metadata[:data_type], metadata[:data_length]
case data_type
when "VARCHAR", "VARCHAR2", "CHAR", "NVARCHAR2", "NCHAR"
[String, data_length || 32767]
when "CLOB", "NCLOB"
[OCI8::CLOB, nil]
when "BLOB"
[OCI8::BLOB, nil]
when "NUMBER", "NATURAL", "NATURALN", "POSITIVE", "POSITIVEN", "SIGNTYPE", "SIMPLE_INTEGER", "PLS_INTEGER", "BINARY_INTEGER"
[OraNumber, nil]
when "DATE"
[DateTime, nil]
when "TIMESTAMP", "TIMESTAMP WITH TIME ZONE", "TIMESTAMP WITH LOCAL TIME ZONE"
[Time, nil]
when "TABLE", "VARRAY", "OBJECT", "XMLTYPE"
# create Ruby class for collection
klass = OCI8::Object::Base.get_class_by_typename(metadata[:sql_type_name])
unless klass
klass = Class.new(OCI8::Object::Base)
klass.set_typename metadata[:sql_type_name]
end
[klass, nil]
when "REF CURSOR"
[OCI8::Cursor]
else
[String, 32767]
end
end
def ruby_value_to_ora_value(value, type = nil)
type ||= value.class
case type.to_s.to_sym
when :Integer, :BigDecimal, :String
value
when :OraNumber
# pass parameters as OraNumber to avoid rounding errors
case value
when BigDecimal
OraNumber.new(value.to_s("F"))
when TrueClass
OraNumber.new(1)
when FalseClass
OraNumber.new(0)
else
value
end
when :DateTime
case value
when Time
::DateTime.civil(value.year, value.month, value.day, value.hour, value.min, value.sec, Rational(value.utc_offset, 86400))
when DateTime
value
when Date
::DateTime.civil(value.year, value.month, value.day, 0, 0, 0, 0)
else
value
end
when :"OCI8::CLOB", :"OCI8::BLOB"
# ruby-oci8 cannot create CLOB/BLOB from ''
value.to_s.length > 0 ? type.new(raw_oci_connection, value) : nil
when :"OCI8::Cursor"
value && value.raw_cursor
else
# collections and object types
if type.superclass == OCI8::Object::Base
return nil if value.nil?
tdo = raw_oci_connection.get_tdo_by_class(type)
if tdo.is_collection?
raise ArgumentError, "You should pass Array value for collection type parameter" unless value.is_a?(Array)
elem_list = value.map do |elem|
if (attr_tdo = tdo.coll_attr.typeinfo)
attr_type, _ = plsql_to_ruby_data_type(data_type: "OBJECT", sql_type_name: attr_tdo.typename)
else
attr_type = elem.class
end
ruby_value_to_ora_value(elem, attr_type)
end
# construct collection value
# TODO: change setting instance variable to appropriate ruby-oci8 method call when available
collection = type.new(raw_oci_connection)
collection.instance_variable_set("@attributes", elem_list)
collection
else # object type
raise ArgumentError, "You should pass Hash value for object type parameter" unless value.is_a?(Hash)
object_attrs = value.dup
object_attrs.keys.each do |key|
raise ArgumentError, "Wrong object type field passed to PL/SQL procedure" unless (attr = tdo.attr_getters[key])
case attr.datatype
when OCI8::TDO::ATTR_NAMED_TYPE, OCI8::TDO::ATTR_NAMED_COLLECTION
# nested object type or collection
attr_type, _ = plsql_to_ruby_data_type(data_type: "OBJECT", sql_type_name: attr.typeinfo.typename)
object_attrs[key] = ruby_value_to_ora_value(object_attrs[key], attr_type)
end
end
type.new(raw_oci_connection, object_attrs)
end
# all other cases
else
value
end
end
end
def ora_value_to_ruby_value(value)
case value
when Float, OraNumber, BigDecimal
ora_number_to_ruby_number(value)
when DateTime, OraDate
ora_date_to_ruby_date(value)
when OCI8::LOB
if value.available?
value.rewind
value.read
else
nil
end
when OCI8::Object::Base
tdo = raw_oci_connection.get_tdo_by_class(value.class)
if tdo.is_collection?
value.to_ary.map { |e| ora_value_to_ruby_value(e) }
else # object type
tdo.attributes.inject({}) do |hash, attr|
hash[attr.name] = ora_value_to_ruby_value(value.instance_variable_get(:@attributes)[attr.name])
hash
end
end
when OCI8::Cursor
Cursor.new(self, value)
else
value
end
end
def database_version
@database_version ||= (version = raw_connection.oracle_server_version) &&
[version.major, version.minor, version.update, version.patch]
end
private
def raw_oci_connection
if raw_connection.is_a? OCI8
raw_connection
# ActiveRecord Oracle enhanced adapter puts OCI8EnhancedAutoRecover wrapper around OCI8
# in this case we need to pass original OCI8 connection
else
if raw_connection.instance_variable_defined?(:@raw_connection)
raw_connection.instance_variable_get(:@raw_connection)
else
raw_connection.instance_variable_get(:@connection)
end
end
end
def ora_number_to_ruby_number(num)
# return BigDecimal instead of Float to avoid rounding errors
num == (num_to_i = num.to_i) ? num_to_i : (num.is_a?(BigDecimal) ? num : BigDecimal(num.to_s))
end
def ora_date_to_ruby_date(val)
case val
when DateTime
# similar implementation as in oracle_enhanced adapter
begin
Time.send(plsql.default_timezone, val.year, val.month, val.day, val.hour, val.min, val.sec)
rescue
offset = plsql.default_timezone.to_sym == :local ? plsql.local_timezone_offset : 0
DateTime.civil(val.year, val.month, val.day, val.hour, val.min, val.sec, offset)
end
when OraDate
# similar implementation as in oracle_enhanced adapter
begin
Time.send(plsql.default_timezone, val.year, val.month, val.day, val.hour, val.minute, val.second)
rescue
offset = plsql.default_timezone.to_sym == :local ? plsql.local_timezone_offset : 0
DateTime.civil(val.year, val.month, val.day, val.hour, val.minute, val.second, offset)
end
else
val
end
end
end
end
| ruby | MIT | 7bee9ba2b3207de7c1ae4112d8af2636b586c610 | 2026-01-04T17:45:33.227772Z | false |
rsim/ruby-plsql | https://github.com/rsim/ruby-plsql/blob/7bee9ba2b3207de7c1ae4112d8af2636b586c610/lib/plsql/sequence.rb | lib/plsql/sequence.rb | module PLSQL
module SequenceClassMethods #:nodoc:
def find(schema, sequence)
if schema.select_first(
"SELECT sequence_name FROM all_sequences
WHERE sequence_owner = :owner
AND sequence_name = :sequence_name",
schema.schema_name, sequence.to_s.upcase)
new(schema, sequence)
# search for synonym
elsif (row = schema.select_first(
"SELECT t.sequence_owner, t.sequence_name
FROM all_synonyms s, all_sequences t
WHERE s.owner IN (:owner, 'PUBLIC')
AND s.synonym_name = :synonym_name
AND t.sequence_owner = s.table_owner
AND t.sequence_name = s.table_name
ORDER BY DECODE(s.owner, 'PUBLIC', 1, 0)",
schema.schema_name, sequence.to_s.upcase))
new(schema, row[1], row[0])
else
nil
end
end
end
class Sequence
extend SequenceClassMethods
def initialize(schema, sequence, override_schema_name = nil) #:nodoc:
@schema = schema
@schema_name = override_schema_name || schema.schema_name
@sequence_name = sequence.to_s.upcase
end
# Get NEXTVAL of sequence
def nextval
@schema.select_one "SELECT \"#{@schema_name}\".\"#{@sequence_name}\".NEXTVAL FROM dual"
end
# Get CURRVAL of sequence (can be called just after nextval)
def currval
@schema.select_one "SELECT \"#{@schema_name}\".\"#{@sequence_name}\".CURRVAL FROM dual"
end
end
end
| ruby | MIT | 7bee9ba2b3207de7c1ae4112d8af2636b586c610 | 2026-01-04T17:45:33.227772Z | false |
rsim/ruby-plsql | https://github.com/rsim/ruby-plsql/blob/7bee9ba2b3207de7c1ae4112d8af2636b586c610/lib/plsql/helpers.rb | lib/plsql/helpers.rb | module PLSQL #:nodoc:
module ArrayHelpers #:nodoc:
def self.to_hash(keys, values) #:nodoc:
(0...keys.size).inject({}) { |hash, i| hash[keys[i]] = values[i]; hash }
end
end
end
| ruby | MIT | 7bee9ba2b3207de7c1ae4112d8af2636b586c610 | 2026-01-04T17:45:33.227772Z | false |
rsim/ruby-plsql | https://github.com/rsim/ruby-plsql/blob/7bee9ba2b3207de7c1ae4112d8af2636b586c610/lib/plsql/procedure_call.rb | lib/plsql/procedure_call.rb | module PLSQL
class ProcedureCall #:nodoc:
def initialize(procedure, args = [], options = {})
@procedure = procedure
@schema = @procedure.schema
@dbms_output_stream = @schema.dbms_output_stream
@skip_self = options[:skip_self]
@self = options[:self]
if args.size == 1 && args[0].is_a?(Hash) && args[0].keys.all? { |k| k.is_a?(Symbol) }
args[0] = args[0].map { |k, v| [k.downcase, v] }.to_h
end
@overload = get_overload_from_arguments_list(args)
@procedure.ensure_tmp_tables_created(@overload) if @procedure.respond_to?(:ensure_tmp_tables_created)
construct_sql(args)
end
def exec
# puts "DEBUG: sql = #{@sql.gsub("\n","<br/>\n")}"
@cursor = @schema.connection.parse(@sql)
@bind_values.each do |arg, value|
@cursor.bind_param(":#{arg}", value, @bind_metadata[arg])
end
@return_vars.each do |var|
@cursor.bind_param(":#{var}", nil, @return_vars_metadata[var])
end
@cursor.exec
if block_given?
yield get_return_value
nil
else
get_return_value
end
ensure
@cursor.close if @cursor
dbms_output_log
end
private
def get_overload_from_arguments_list(args)
# if not overloaded then overload index 0 is used
return 0 unless @procedure.overloaded?
# If named arguments are used then
# there should be just one Hash argument with symbol keys
if args.size == 1 && args[0].is_a?(Hash) && args[0].keys.all? { |k| k.is_a?(Symbol) }
args_keys = args[0].keys
# implicit SELF argument for object instance procedures
args_keys << :self if @self && !args_keys.include?(:self)
number_of_args = args_keys.size
matching_overloads = [] # overloads with exact or smaller number of matching named arguments
overload_argument_list.keys.each do |ov|
# assume that missing arguments have default value
missing_arguments_count = overload_argument_list[ov].size - number_of_args
if missing_arguments_count >= 0 &&
args_keys.all? { |k| overload_argument_list[ov].include?(k) }
matching_overloads << [ov, missing_arguments_count]
end
end
# pick first matching overload with smallest missing arguments count
# (hoping that missing arguments will be defaulted - cannot find default value from all_arguments)
overload = matching_overloads.sort_by { |ov, score| score }[0][0]
# otherwise try matching by sequential arguments count and types
else
number_of_args = args.size
matching_types = []
# if implicit SELF argument for object instance procedures should be passed
# then it should be added as first argument to find matches
if @self
number_of_args += 1
matching_types << ["OBJECT"]
end
args.each do |arg|
matching_types << matching_oracle_types_for_ruby_value(arg)
end
exact_overloads = [] # overloads with exact number of matching arguments
smaller_overloads = [] # overloads with smaller number of matching arguments
# overload = overload_argument_list.keys.detect do |ov|
# overload_argument_list[ov].size == number_of_args
# end
overload_argument_list.keys.each do |ov|
score = 0 # lower score is better match
ov_arg_list_size = overload_argument_list[ov].size
if (number_of_args <= ov_arg_list_size &&
(0..(number_of_args - 1)).all? do |i|
ov_arg = overload_argument_list[ov][i]
matching_types[i] == :all || # either value matches any type
(ind = matching_types[i].index(overload_arguments[ov][ov_arg][:data_type])) &&
(score += ind) # or add index of matched type
end)
if number_of_args == ov_arg_list_size
exact_overloads << [ov, score]
else
smaller_overloads << [ov, score]
end
end
end
# pick either first exact matching overload of first matching with smaller argument count
# (hoping that missing arguments will be defaulted - cannot find default value from all_arguments)
overload = if !exact_overloads.empty?
exact_overloads.sort_by { |ov, score| score }[0][0]
elsif !smaller_overloads.empty?
smaller_overloads.sort_by { |ov, score| score }[0][0]
end
end
raise ArgumentError, "Wrong number or types of arguments passed to overloaded PL/SQL procedure" unless overload
overload
end
MATCHING_TYPES = {
integer: ["NUMBER", "NATURAL", "NATURALN", "POSITIVE", "POSITIVEN", "SIGNTYPE", "SIMPLE_INTEGER", "PLS_INTEGER", "BINARY_INTEGER"],
decimal: ["NUMBER", "BINARY_FLOAT", "BINARY_DOUBLE"],
string: ["VARCHAR", "VARCHAR2", "NVARCHAR2", "CHAR", "NCHAR", "CLOB", "BLOB", "XMLTYPE"],
date: ["DATE"],
time: ["DATE", "TIMESTAMP", "TIMESTAMP WITH TIME ZONE", "TIMESTAMP WITH LOCAL TIME ZONE"],
boolean: ["PL/SQL BOOLEAN"],
hash: ["PL/SQL RECORD", "OBJECT", "PL/SQL TABLE"],
array: ["TABLE", "VARRAY"],
cursor: ["REF CURSOR"]
}
def matching_oracle_types_for_ruby_value(value)
case value
when NilClass
:all
when Integer
MATCHING_TYPES[:integer]
when BigDecimal, Float
MATCHING_TYPES[:decimal]
when String
MATCHING_TYPES[:string]
when Date
MATCHING_TYPES[:date]
when Time
MATCHING_TYPES[:time]
when TrueClass, FalseClass
MATCHING_TYPES[:boolean]
when Hash
MATCHING_TYPES[:hash]
when Array
MATCHING_TYPES[:array]
when CursorCommon
MATCHING_TYPES[:cursor]
end
end
def construct_sql(args)
@declare_sql = ""
@assignment_sql = ""
@call_sql = ""
@return_sql = ""
@return_vars = []
@return_vars_metadata = {}
@call_sql << add_return if return_metadata
# construct procedure call if procedure name is available
# otherwise will get surrounding call_sql from @procedure (used for table statements)
if procedure_name
@call_sql << "#{schema_name}." if schema_name
@call_sql << "#{package_name}." if package_name
@call_sql << "#{procedure_name}("
end
@bind_values = {}
@bind_metadata = {}
# Named arguments
# there should be just one Hash argument with symbol keys
if args.size == 1 && args[0].is_a?(Hash) && args[0].keys.all? { |k| k.is_a?(Symbol) } &&
# do not use named arguments if procedure has just one PL/SQL record PL/SQL table or object type argument -
# in that case passed Hash should be used as value for this PL/SQL record argument
# (which will be processed in sequential arguments bracnh)
!(argument_list.size == 1 &&
["PL/SQL RECORD", "PL/SQL TABLE", "OBJECT"].include?(arguments[(only_argument = argument_list[0])][:data_type]) &&
args[0].keys != [only_argument])
# Add missing output arguments with nil value
arguments.each do |arg, metadata|
if !args[0].has_key?(arg) && metadata[:in_out] == "OUT"
args[0][arg] = nil
end
end
# Add SELF argument if provided
args[0][:self] = @self if @self
# Add passed parameters to procedure call with parameter names
@call_sql << args[0].map do |arg, value|
"#{arg} => " << add_argument(arg, value)
end.join(", ")
# Sequential arguments
else
# add SELF as first argument if provided
args.unshift(@self) if @self
argument_count = argument_list.size
raise ArgumentError, "Too many arguments passed to PL/SQL procedure" if args.size > argument_count
# Add missing output arguments with nil value
if args.size < argument_count &&
(args.size...argument_count).all? { |i| arguments[argument_list[i]][:in_out] == "OUT" }
args += [nil] * (argument_count - args.size)
end
# Add passed parameters to procedure call in sequence
@call_sql << (0...args.size).map do |i|
arg = argument_list[i]
value = args[i]
add_argument(arg, value)
end.join(", ")
end
# finish procedure call construction if procedure name is available
# otherwise will get surrounding call_sql from @procedure (used for table statements)
if procedure_name
@call_sql << ");\n"
else
@call_sql = @procedure.call_sql(@call_sql)
end
add_out_variables
@sql = @declare_sql.empty? ? "" : "DECLARE\n" << @declare_sql
@sql << "BEGIN\n" << @assignment_sql << dbms_output_enable_sql << @call_sql << @return_sql << "END;\n"
end
def add_argument(argument, value, argument_metadata = nil)
argument_metadata ||= arguments[argument]
raise ArgumentError, "Wrong argument #{argument.inspect} passed to PL/SQL procedure" unless argument_metadata
case argument_metadata[:data_type]
when "PL/SQL RECORD"
add_record_declaration(argument, argument_metadata)
record_assignment_sql, record_bind_values, record_bind_metadata =
record_assignment_sql_values_metadata(argument, argument_metadata, value)
@assignment_sql << record_assignment_sql
@bind_values.merge!(record_bind_values)
@bind_metadata.merge!(record_bind_metadata)
"l_#{argument}"
when "PL/SQL BOOLEAN"
@declare_sql << "l_#{argument} BOOLEAN;\n"
@assignment_sql << "l_#{argument} := (:#{argument} = 1);\n"
@bind_values[argument] = value.nil? ? nil : (value ? 1 : 0)
@bind_metadata[argument] = argument_metadata.merge(data_type: "NUMBER", data_precision: 1)
"l_#{argument}"
when "UNDEFINED"
if argument_metadata[:type_name] == "XMLTYPE"
@declare_sql << "l_#{argument} XMLTYPE;\n"
@assignment_sql << "l_#{argument} := XMLTYPE(:#{argument});\n" if not value.nil?
@bind_values[argument] = value if not value.nil?
@bind_metadata[argument] = argument_metadata.merge(data_type: "CLOB")
"l_#{argument}"
end
else
# TABLE or PL/SQL TABLE type defined inside package
if argument_metadata[:tmp_table_name]
add_table_declaration_and_assignment(argument, argument_metadata)
insert_values_into_tmp_table(argument, argument_metadata, value)
"l_#{argument}"
else
@bind_values[argument] = value
@bind_metadata[argument] = argument_metadata
":#{argument}"
end
end
end
def add_table_declaration_and_assignment(argument, argument_metadata)
is_index_by_table = argument_metadata[:data_type] == "PL/SQL TABLE"
@declare_sql << "l_#{argument} #{argument_metadata[:sql_type_name]}#{is_index_by_table ? nil : " := #{argument_metadata[:sql_type_name]}()"};\n"
@assignment_sql << "FOR r_#{argument} IN c_#{argument} LOOP\n"
@assignment_sql << "l_#{argument}.EXTEND;\n" unless is_index_by_table
case argument_metadata[:element][:data_type]
when "PL/SQL RECORD"
fields = record_fields_sorted_by_position(argument_metadata[:element][:fields])
fields_string = is_index_by_table ? "*" : fields.join(", ")
@declare_sql << "CURSOR c_#{argument} IS SELECT #{fields_string} FROM #{argument_metadata[:tmp_table_name]} ORDER BY i__;\n"
if is_index_by_table
fields.each do |field|
@assignment_sql << "l_#{argument}(r_#{argument}.i__).#{field} := r_#{argument}.#{field};\n"
end
else
@assignment_sql << "l_#{argument}(l_#{argument}.COUNT) := r_#{argument};\n"
end
else
@declare_sql << "CURSOR c_#{argument} IS SELECT * FROM #{argument_metadata[:tmp_table_name]} ORDER BY i__;\n"
@assignment_sql << "l_#{argument}(r_#{argument}.i__) := r_#{argument}.element;\n"
end
@assignment_sql << "END LOOP;\n"
@assignment_sql << "DELETE FROM #{argument_metadata[:tmp_table_name]};\n"
end
def insert_values_into_tmp_table(argument, argument_metadata, values)
return unless values && !values.empty?
is_index_by_table = argument_metadata[:data_type] == "PL/SQL TABLE"
if is_index_by_table
raise ArgumentError, "Hash value should be passed for #{argument.inspect} argument" unless values.is_a?(Hash)
else
raise ArgumentError, "Array value should be passed for #{argument.inspect} argument" unless values.is_a?(Array)
end
tmp_table = @schema.root_schema.send(argument_metadata[:tmp_table_name])
# insert values without autocommit
old_autocommit = @schema.connection.autocommit?
@schema.connection.autocommit = false if old_autocommit
tmp_table.delete
case argument_metadata[:element][:data_type]
when "PL/SQL RECORD"
values_with_index = []
if is_index_by_table
values.each { |i, v| values_with_index << v.merge(i__: i) }
else
values.each_with_index { |v, i| values_with_index << v.merge(i__: i + 1) }
end
tmp_table.insert values_with_index
else
values_with_index = []
if is_index_by_table
values.each { |i, v| values_with_index << [v, i] }
else
values.each_with_index { |v, i| values_with_index << [v, i + 1] }
end
tmp_table.insert_values [:element, :i__], *values_with_index
end
@schema.connection.autocommit = true if old_autocommit
end
def add_record_declaration(argument, argument_metadata)
@declare_sql << if argument_metadata[:type_subname]
"l_#{argument} #{argument_metadata[:sql_type_name]};\n"
else
fields_metadata = argument_metadata[:fields]
sql = "TYPE t_#{argument} IS RECORD (\n"
sql << record_fields_sorted_by_position(fields_metadata).map do |field|
metadata = fields_metadata[field]
"#{field} #{type_to_sql(metadata)}"
end.join(",\n")
sql << ");\n"
sql << "l_#{argument} t_#{argument};\n"
end
end
def record_fields_sorted_by_position(fields_metadata)
fields_metadata.keys.sort_by { |k| fields_metadata[k][:position] }
end
def record_assignment_sql_values_metadata(argument, argument_metadata, record_value)
sql = ""
bind_values = {}
bind_metadata = {}
(record_value || {}).each do |key, value|
field = key.is_a?(Symbol) ? key : key.to_s.downcase.to_sym
metadata = argument_metadata[:fields][field]
raise ArgumentError, "Wrong field name #{key.inspect} passed to PL/SQL record argument #{argument.inspect}" unless metadata
bind_variable = :"#{argument}_f#{metadata[:position]}"
case metadata[:data_type]
when "PL/SQL BOOLEAN"
sql << "l_#{argument}.#{field} := (:#{bind_variable} = 1);\n"
bind_values[bind_variable] = value.nil? ? nil : (value ? 1 : 0)
bind_metadata[bind_variable] = metadata.merge(data_type: "NUMBER", data_precision: 1)
else
sql << "l_#{argument}.#{field} := :#{bind_variable};\n"
bind_values[bind_variable] = value
bind_metadata[bind_variable] = metadata
end
end
[sql, bind_values, bind_metadata]
end
def add_return
add_return_variable(:return, return_metadata, true)
end
def add_out_variables
out_list.each do |argument|
add_return_variable(argument, arguments[argument])
end
end
def add_return_variable(argument, argument_metadata, is_return_value = false)
case argument_metadata[:data_type]
when "PL/SQL RECORD"
add_record_declaration(argument, argument_metadata) if is_return_value
argument_metadata[:fields].each do |field, metadata|
# should use different output bind variable as JDBC does not support
# if output bind variable appears in several places
bind_variable = :"#{argument}_o#{metadata[:position]}"
case metadata[:data_type]
when "PL/SQL BOOLEAN"
@return_vars << bind_variable
@return_vars_metadata[bind_variable] = metadata.merge(data_type: "NUMBER", data_precision: 1)
arg_field = "l_#{argument}.#{field}"
@return_sql << ":#{bind_variable} := " << "CASE WHEN #{arg_field} = true THEN 1 " <<
"WHEN #{arg_field} = false THEN 0 ELSE NULL END;\n"
else
@return_vars << bind_variable
@return_vars_metadata[bind_variable] = metadata
@return_sql << ":#{bind_variable} := l_#{argument}.#{field};\n"
end
end
"l_#{argument} := " if is_return_value
when "UNDEFINED"
if argument_metadata[:type_name] == "XMLTYPE"
@declare_sql << "l_#{argument} XMLTYPE;\n" if is_return_value
bind_variable = :"o_#{argument}"
@return_vars << bind_variable
@return_vars_metadata[bind_variable] = argument_metadata.merge(data_type: "CLOB")
@return_sql << ":#{bind_variable} := CASE WHEN l_#{argument} IS NOT NULL THEN l_#{argument}.getclobval() END;\n"
"l_#{argument} := " if is_return_value
end
when "PL/SQL BOOLEAN"
@declare_sql << "l_#{argument} BOOLEAN;\n" if is_return_value
@declare_sql << "o_#{argument} NUMBER(1);\n"
# should use different output bind variable as JDBC does not support
# if output bind variable appears in several places
bind_variable = :"o_#{argument}"
@return_vars << bind_variable
@return_vars_metadata[bind_variable] = argument_metadata.merge(data_type: "NUMBER", data_precision: 1)
@return_sql << "IF l_#{argument} IS NULL THEN\no_#{argument} := NULL;\n" <<
"ELSIF l_#{argument} THEN\no_#{argument} := 1;\nELSE\no_#{argument} := 0;\nEND IF;\n" <<
":#{bind_variable} := o_#{argument};\n"
"l_#{argument} := " if is_return_value
else
if argument_metadata[:tmp_table_name]
add_return_table(argument, argument_metadata, is_return_value)
elsif is_return_value
@return_vars << argument
@return_vars_metadata[argument] = argument_metadata
":#{argument} := "
end
end
end
def add_return_table(argument, argument_metadata, is_return_value = false)
is_index_by_table = argument_metadata[:data_type] == "PL/SQL TABLE"
declare_i__
@declare_sql << "l_return #{return_metadata[:sql_type_name]};\n" if is_return_value
@return_vars << argument
@return_vars_metadata[argument] = argument_metadata.merge(data_type: "REF CURSOR")
@return_sql << if is_index_by_table
"i__ := l_#{argument}.FIRST;\nLOOP\nEXIT WHEN i__ IS NULL;\n"
else
"IF l_#{argument}.COUNT > 0 THEN\nFOR i__ IN l_#{argument}.FIRST..l_#{argument}.LAST LOOP\n"
end
case argument_metadata[:element][:data_type]
when "PL/SQL RECORD"
field_names = record_fields_sorted_by_position(argument_metadata[:element][:fields])
values_string = field_names.map { |f| "l_#{argument}(i__).#{f}" }.join(", ")
@return_sql << "INSERT INTO #{argument_metadata[:tmp_table_name]} VALUES (#{values_string}, i__);\n"
return_fields_string = is_index_by_table ? "*" : field_names.join(", ")
else
@return_sql << "INSERT INTO #{argument_metadata[:tmp_table_name]} VALUES (l_#{argument}(i__), i__);\n"
return_fields_string = "*"
end
@return_sql << "i__ := l_#{argument}.NEXT(i__);\n" if is_index_by_table
@return_sql << "END LOOP;\n"
@return_sql << "END IF;\n" unless is_index_by_table
@return_sql << "OPEN :#{argument} FOR SELECT #{return_fields_string} FROM #{argument_metadata[:tmp_table_name]} ORDER BY i__;\n"
@return_sql << "DELETE FROM #{argument_metadata[:tmp_table_name]};\n"
"l_#{argument} := " if is_return_value
end
# declare once temp variable i__ that is used as itertor
def declare_i__
unless @declared_i__
@declare_sql << "i__ PLS_INTEGER;\n"
@declared_i__ = true
end
end
def type_to_sql(metadata)
ProcedureCommon.type_to_sql(metadata)
end
def get_return_value
# if function with output parameters
if return_metadata && out_list.size > 0
result = [function_return_value, {}]
out_list.each do |k|
result[1][k] = out_variable_value(k)
end
result
# if function without output parameters
elsif return_metadata
function_return_value
# if procedure with output parameters
elsif out_list.size > 0
result = {}
out_list.each do |k|
result[k] = out_variable_value(k)
end
result
# if procedure without output parameters
else
nil
end
end
def function_return_value
return_variable_value(:return, return_metadata)
end
def out_variable_value(argument)
return_variable_value(argument, arguments[argument])
end
def return_variable_value(argument, argument_metadata)
case argument_metadata[:data_type]
when "PL/SQL RECORD"
return_value = {}
argument_metadata[:fields].each do |field, metadata|
field_value = @cursor[":#{argument}_o#{metadata[:position]}"]
case metadata[:data_type]
when "PL/SQL BOOLEAN"
return_value[field] = field_value.nil? ? nil : field_value == 1
else
return_value[field] = field_value
end
end
return_value
when "PL/SQL BOOLEAN"
numeric_value = @cursor[":o_#{argument}"]
numeric_value.nil? ? nil : numeric_value == 1
when "UNDEFINED"
if argument_metadata[:type_name] == "XMLTYPE"
@cursor[":o_#{argument}"]
end
else
if argument_metadata[:tmp_table_name]
is_index_by_table = argument_metadata[:data_type] == "PL/SQL TABLE"
case argument_metadata[:element][:data_type]
when "PL/SQL RECORD"
if is_index_by_table
Hash[*@cursor[":#{argument}"].fetch_hash_all.map { |row| [row.delete(:i__), row] }.flatten]
else
@cursor[":#{argument}"].fetch_hash_all
end
else
if is_index_by_table
Hash[*@cursor[":#{argument}"].fetch_all.map { |row| [row[1], row[0]] }.flatten]
else
@cursor[":#{argument}"].fetch_all.map { |row| row[0] }
end
end
else
@cursor[":#{argument}"]
end
end
end
def overload_argument_list
@overload_argument_list ||=
@skip_self ? @procedure.argument_list_without_self : @procedure.argument_list
end
def overload_arguments
@overload_arguments ||=
@skip_self ? @procedure.arguments_without_self : @procedure.arguments
end
def argument_list
@argument_list ||= overload_argument_list[@overload]
end
def arguments
@arguments ||= overload_arguments[@overload]
end
def return_metadata
@return_metadata ||= @procedure.return[@overload]
end
def out_list
@out_list ||=
@skip_self ? @procedure.out_list_without_self[@overload] : @procedure.out_list[@overload]
end
def schema_name
@schema_name ||= @procedure.schema_name
end
def package_name
@package_name ||= @procedure.package
end
def procedure_name
@procedure_name ||= @procedure.procedure
end
def dbms_output_enable_sql
@dbms_output_stream ? "DBMS_OUTPUT.ENABLE(#{@schema.dbms_output_buffer_size});\n" : ""
end
def dbms_output_lines
lines = []
if @dbms_output_stream
if (@schema.connection.database_version <=> [10, 2, 0, 0]) >= 0
cursor = @schema.connection.parse("BEGIN DBMS_OUTPUT.GET_LINES(:dbms_output_lines, :dbms_output_numlines); END;\n")
cursor.bind_param(":dbms_output_lines", nil,
data_type: "TABLE",
data_length: nil,
sql_type_name: "SYS.DBMSOUTPUT_LINESARRAY",
in_out: "OUT")
cursor.bind_param(":dbms_output_numlines", Schema::DBMS_OUTPUT_MAX_LINES, data_type: "NUMBER", in_out: "IN/OUT")
cursor.exec
lines = cursor[":dbms_output_lines"]
cursor.close
else
cursor = @schema.connection.parse("BEGIN sys.dbms_output.get_line(:line, :status); END;")
while true do
cursor.bind_param(":line", nil, data_type: "VARCHAR2", in_out: "OUT")
cursor.bind_param(":status", nil, data_type: "NUMBER", in_out: "OUT")
cursor.exec
break unless cursor[":status"] == 0
lines << cursor[":line"]
end
cursor.close
end
end
lines
end
def dbms_output_log
dbms_output_lines.each do |line|
@dbms_output_stream.puts "DBMS_OUTPUT: #{line}" if line
end
@dbms_output_stream.flush if @dbms_output_stream
end
end
end
| ruby | MIT | 7bee9ba2b3207de7c1ae4112d8af2636b586c610 | 2026-01-04T17:45:33.227772Z | false |
rsim/ruby-plsql | https://github.com/rsim/ruby-plsql/blob/7bee9ba2b3207de7c1ae4112d8af2636b586c610/lib/plsql/connection.rb | lib/plsql/connection.rb | module PLSQL
class Connection
attr_reader :raw_driver
attr_reader :activerecord_class
def initialize(raw_conn, ar_class = nil) #:nodoc:
@raw_driver = self.class.driver_type
@raw_connection = raw_conn
@activerecord_class = ar_class
end
def self.create(raw_conn, ar_class = nil) #:nodoc:
if ar_class && !(defined?(::ActiveRecord) && ar_class.ancestors.include?(::ActiveRecord::Base))
raise ArgumentError, "Wrong ActiveRecord class"
end
case driver_type
when :oci
OCIConnection.new(raw_conn, ar_class)
when :jdbc
JDBCConnection.new(raw_conn, ar_class)
else
raise ArgumentError, "Unknown raw driver"
end
end
def self.create_new(params) #:nodoc:
conn = case driver_type
when :oci
OCIConnection.create_raw(params)
when :jdbc
JDBCConnection.create_raw(params)
else
raise ArgumentError, "Unknown raw driver"
end
conn.set_time_zone(params[:time_zone] || ENV["ORA_SDTZ"])
conn
end
def self.driver_type #:nodoc:
# MRI 1.8.6 or YARV 1.9.1 or TruffleRuby
@driver_type ||= if (!defined?(RUBY_ENGINE) || RUBY_ENGINE == "ruby" || RUBY_ENGINE == "truffleruby") && defined?(OCI8)
:oci
# JRuby
elsif (defined?(RUBY_ENGINE) && RUBY_ENGINE == "jruby")
:jdbc
else
nil
end
end
# Returns OCI8 or JDBC connection
def raw_connection
if @activerecord_class
@activerecord_class.connection.raw_connection
else
@raw_connection
end
end
# Is it OCI8 connection
def oci?
@raw_driver == :oci
end
# Is it JDBC connection
def jdbc?
@raw_driver == :jdbc
end
def logoff #:nodoc:
# Rollback any uncommited transactions
rollback
# Common cleanup activities before logoff, should be called from particular driver method
drop_session_ruby_temporary_tables
end
def commit #:nodoc:
raise NoMethodError, "Not implemented for this raw driver"
end
def rollback #:nodoc:
raise NoMethodError, "Not implemented for this raw driver"
end
# Current autocommit mode (true or false)
def autocommit?
raise NoMethodError, "Not implemented for this raw driver"
end
# Set autocommit mode (true or false)
def autocommit=(value)
raise NoMethodError, "Not implemented for this raw driver"
end
# Set number of rows to be prefetched. This can reduce the number of network round trips when fetching many rows.
# The default value is one. (If ActiveRecord oracle_enhanced connection is used then default is 100)
def prefetch_rows=(value)
raise NoMethodError, "Not implemented for this raw driver"
end
def select_first(sql, *bindvars) #:nodoc:
cursor = cursor_from_query(sql, bindvars, prefetch_rows: 1)
cursor.fetch
ensure
cursor.close rescue nil
end
def select_hash_first(sql, *bindvars) #:nodoc:
cursor = cursor_from_query(sql, bindvars, prefetch_rows: 1)
cursor.fetch_hash
ensure
cursor.close rescue nil
end
def select_all(sql, *bindvars, &block) #:nodoc:
cursor = cursor_from_query(sql, bindvars)
results = []
row_count = 0
while row = cursor.fetch
if block_given?
yield(row)
row_count += 1
else
results << row
end
end
block_given? ? row_count : results
ensure
cursor.close rescue nil
end
def select_hash_all(sql, *bindvars, &block) #:nodoc:
cursor = cursor_from_query(sql, bindvars)
results = []
row_count = 0
while row = cursor.fetch_hash
if block_given?
yield(row)
row_count += 1
else
results << row
end
end
block_given? ? row_count : results
ensure
cursor.close rescue nil
end
def exec(sql, *bindvars) #:nodoc:
raise NoMethodError, "Not implemented for this raw driver"
end
def parse(sql) #:nodoc:
raise NoMethodError, "Not implemented for this raw driver"
end
module CursorCommon
# Fetch all rows from cursor, each row as array of values
def fetch_all
rows = []
while (row = fetch)
rows << row
end
rows
end
# Fetch all rows from cursor, each row as hash {:column => value, ...}
def fetch_hash_all
rows = []
while (row = fetch_hash)
rows << row
end
rows
end
# Fetch row from cursor as hash {:column => value, ...}
def fetch_hash
(row = fetch) && ArrayHelpers::to_hash(fields, row)
end
end
# all_synonyms view is quite slow therefore
# this implementation is overriden in OCI connection with faster native OCI method
def describe_synonym(schema_name, synonym_name) #:nodoc:
select_first(
"SELECT table_owner, table_name FROM all_synonyms WHERE owner = :owner AND synonym_name = :synonym_name",
schema_name.to_s.upcase, synonym_name.to_s.upcase)
end
# Returns array with major and minor version of database (e.g. [10, 2])
def database_version
raise NoMethodError, "Not implemented for this raw driver"
end
# Returns session ID
def session_id
@session_id ||= select_first("SELECT TO_NUMBER(USERENV('SESSIONID')) FROM dual")[0]
end
# Set time zone
def set_time_zone(time_zone = nil)
exec("alter session set time_zone = '#{time_zone}'") if time_zone
end
# Returns session time zone
def time_zone
select_first("SELECT SESSIONTIMEZONE FROM dual")[0]
end
RUBY_TEMP_TABLE_PREFIX = "ruby_"
# Drop all ruby temporary tables that are used for calling packages with table parameter types defined in packages
def drop_all_ruby_temporary_tables
select_all("SELECT table_name FROM user_tables WHERE temporary='Y' AND table_name LIKE :table_name",
RUBY_TEMP_TABLE_PREFIX.upcase + "%").each do |row|
exec "TRUNCATE TABLE #{row[0]}"
exec "DROP TABLE #{row[0]}"
end
end
# Drop ruby temporary tables created in current session that are used for calling packages with table parameter types defined in packages
def drop_session_ruby_temporary_tables
select_all("SELECT table_name FROM user_tables WHERE temporary='Y' AND table_name LIKE :table_name",
RUBY_TEMP_TABLE_PREFIX.upcase + "#{session_id}_%").each do |row|
exec "TRUNCATE TABLE #{row[0]}"
exec "DROP TABLE #{row[0]}"
end
end
end
end
| ruby | MIT | 7bee9ba2b3207de7c1ae4112d8af2636b586c610 | 2026-01-04T17:45:33.227772Z | false |
rsim/ruby-plsql | https://github.com/rsim/ruby-plsql/blob/7bee9ba2b3207de7c1ae4112d8af2636b586c610/lib/plsql/oci8_patches.rb | lib/plsql/oci8_patches.rb | # apply TIMESTAMP fractional seconds patch to ruby-oci8 2.0.3
# see http://rubyforge.org/forum/forum.php?thread_id=46576&forum_id=1078
if OCI8::VERSION == "2.0.3" &&
!OCI8::BindType::Util.method_defined?(:datetime_to_array_without_timestamp_patch)
OCI8::BindType::Util.module_eval do
alias :datetime_to_array_without_timestamp_patch :datetime_to_array
def datetime_to_array(val, full)
result = datetime_to_array_without_timestamp_patch(val, full)
if result && result[6] == 0
if val.respond_to? :nsec
fsec = val.nsec
elsif val.respond_to? :usec
fsec = val.usec * 1000
else
fsec = 0
end
result[6] = fsec
end
result
end
private :datetime_to_array_without_timestamp_patch, :datetime_to_array
end
end
| ruby | MIT | 7bee9ba2b3207de7c1ae4112d8af2636b586c610 | 2026-01-04T17:45:33.227772Z | false |
rsim/ruby-plsql | https://github.com/rsim/ruby-plsql/blob/7bee9ba2b3207de7c1ae4112d8af2636b586c610/lib/plsql/jdbc_connection.rb | lib/plsql/jdbc_connection.rb | begin
require "java"
require "jruby"
# ojdbc6.jar or ojdbc5.jar file should be in JRUBY_HOME/lib or should be in ENV['PATH'] or load path
java_version = java.lang.System.getProperty("java.version")
ojdbc_jars = if java_version =~ /^1.5/
%w(ojdbc5.jar)
elsif java_version =~ /^1.6/
%w(ojdbc6.jar)
elsif java_version >= "1.7"
# Oracle 11g client ojdbc6.jar is also compatible with Java 1.7
# Oracle 12c client provides new ojdbc7.jar
%w(ojdbc7.jar ojdbc6.jar)
else
[]
end
if ENV_JAVA["java.class.path"] !~ Regexp.new(ojdbc_jars.join("|"))
# On Unix environment variable should be PATH, on Windows it is sometimes Path
env_path = (ENV["PATH"] || ENV["Path"] || "").split(File::PATH_SEPARATOR)
# Look for JDBC driver at first in lib subdirectory (application specific JDBC file version)
# then in Ruby load path and finally in environment PATH
["./lib"].concat($LOAD_PATH).concat(env_path).detect do |dir|
# check any compatible JDBC driver in the priority order
ojdbc_jars.any? do |ojdbc_jar|
if File.exists?(file_path = File.join(dir, ojdbc_jar))
require file_path
true
end
end
end
end
java.sql.DriverManager.registerDriver Java::oracle.jdbc.OracleDriver.new
# set tns_admin property from TNS_ADMIN environment variable
if !java.lang.System.get_property("oracle.net.tns_admin") && ENV["TNS_ADMIN"]
java.lang.System.set_property("oracle.net.tns_admin", ENV["TNS_ADMIN"])
end
rescue LoadError, NameError
# JDBC driver is unavailable.
raise LoadError, "ERROR: ruby-plsql could not load Oracle JDBC driver. Please install #{ojdbc_jars.empty? ? "Oracle JDBC" : ojdbc_jars.join(' or ') } library."
end
module PLSQL
class JDBCConnection < Connection #:nodoc:
def self.create_raw(params)
database = params[:database]
url = if ENV["TNS_ADMIN"] && database && !params[:host] && !params[:url]
"jdbc:oracle:thin:@#{database}"
else
database = ":#{database}" unless database.match(/^(\:|\/)/)
params[:url] || "jdbc:oracle:thin:@#{params[:host] || 'localhost'}:#{params[:port] || 1521}#{database}"
end
new(java.sql.DriverManager.getConnection(url, params[:username], params[:password]))
end
def set_time_zone(time_zone = nil)
raw_connection.setSessionTimeZone(time_zone) if time_zone
end
def logoff
super
raw_connection.close
true
rescue
false
end
def commit
raw_connection.commit
end
def rollback
raw_connection.rollback
end
def autocommit?
raw_connection.getAutoCommit
end
def autocommit=(value)
raw_connection.setAutoCommit(value)
end
def prefetch_rows=(value)
raw_connection.setDefaultRowPrefetch(value)
end
def exec(sql, *bindvars)
cs = prepare_call(sql, *bindvars)
cs.execute
true
ensure
cs.close rescue nil
end
class CallableStatement #:nodoc:
def initialize(conn, sql)
@sql = sql
@connection = conn
@params = sql.scan(/\:\w+/)
@out_types = {}
@out_index = {}
@statement = @connection.prepare_call(sql)
end
def bind_param(arg, value, metadata)
type, length = @connection.plsql_to_ruby_data_type(metadata)
ora_value = @connection.ruby_value_to_ora_value(value, type, metadata)
@connection.set_bind_variable(@statement, arg, ora_value, type, length, metadata)
if metadata[:in_out] =~ /OUT/
@out_types[arg] = type || ora_value.class
@out_index[arg] = bind_param_index(arg)
if ["TABLE", "VARRAY", "OBJECT", "XMLTYPE"].include?(metadata[:data_type])
@statement.registerOutParameter(@out_index[arg], @connection.get_java_sql_type(ora_value, type),
metadata[:sql_type_name])
else
@statement.registerOutParameter(@out_index[arg], @connection.get_java_sql_type(ora_value, type))
end
end
end
def exec
@statement.execute
end
def [](key)
@connection.ora_value_to_ruby_value(@connection.get_bind_variable(@statement, @out_index[key], @out_types[key]))
end
def close
@statement.close
end
private
def bind_param_index(key)
return key if key.kind_of? Integer
key = ":#{key.to_s}" unless key.to_s =~ /^:/
@params.index(key) + 1
end
end
class Cursor #:nodoc:
include Connection::CursorCommon
attr_reader :result_set
attr_accessor :statement
def initialize(conn, result_set)
@connection = conn
@result_set = result_set
@metadata = @result_set.getMetaData
@column_count = @metadata.getColumnCount
@column_type_names = [nil] # column numbering starts at 1
(1..@column_count).each do |i|
@column_type_names << { type_name: @metadata.getColumnTypeName(i), sql_type: @metadata.getColumnType(i) }
end
end
def self.new_from_query(conn, sql, bindvars = [], options = {})
stmt = conn.prepare_statement(sql, *bindvars)
if prefetch_rows = options[:prefetch_rows]
stmt.setRowPrefetch(prefetch_rows)
end
cursor = Cursor.new(conn, stmt.executeQuery)
cursor.statement = stmt
cursor
rescue
# in case of any error close statement
stmt.close rescue nil
raise
end
def fetch
if @result_set.next
(1..@column_count).map do |i|
@connection.get_ruby_value_from_result_set(@result_set, i, @column_type_names[i])
end
else
nil
end
end
def fields
@fields ||= (1..@column_count).map do |i|
@metadata.getColumnName(i).downcase.to_sym
end
end
def close
@result_set.close
@statement.close if @statement
end
end
def parse(sql)
CallableStatement.new(self, sql)
end
def cursor_from_query(sql, bindvars = [], options = {})
Cursor.new_from_query(self, sql, bindvars, options)
end
def prepare_statement(sql, *bindvars)
stmt = raw_connection.prepareStatement(sql)
bindvars.each_with_index do |bv, i|
set_bind_variable(stmt, i + 1, ruby_value_to_ora_value(bv))
end
stmt
end
def prepare_call(sql, *bindvars)
stmt = raw_connection.prepareCall(sql)
bindvars.each_with_index do |bv, i|
set_bind_variable(stmt, i + 1, bv)
end
stmt
end
RUBY_CLASS_TO_SQL_TYPE = {
Integer => java.sql.Types::INTEGER,
Float => java.sql.Types::FLOAT,
BigDecimal => java.sql.Types::NUMERIC,
String => java.sql.Types::VARCHAR,
Java::OracleSql::CLOB => Java::oracle.jdbc.OracleTypes::CLOB,
Java::OracleSql::BLOB => Java::oracle.jdbc.OracleTypes::BLOB,
Date => java.sql.Types::DATE,
Time => java.sql.Types::TIMESTAMP,
DateTime => java.sql.Types::DATE,
Java::OracleSql::ARRAY => Java::oracle.jdbc.OracleTypes::ARRAY,
Array => Java::oracle.jdbc.OracleTypes::ARRAY,
Java::OracleSql::STRUCT => Java::oracle.jdbc.OracleTypes::STRUCT,
Hash => Java::oracle.jdbc.OracleTypes::STRUCT,
java.sql.ResultSet => Java::oracle.jdbc.OracleTypes::CURSOR,
}
SQL_TYPE_TO_RUBY_CLASS = {
java.sql.Types::CHAR => String,
java.sql.Types::NCHAR => String,
java.sql.Types::VARCHAR => String,
java.sql.Types::NVARCHAR => String,
java.sql.Types::LONGVARCHAR => String,
java.sql.Types::NUMERIC => BigDecimal,
java.sql.Types::INTEGER => Integer,
java.sql.Types::DATE => Time,
java.sql.Types::TIMESTAMP => Time,
Java::oracle.jdbc.OracleTypes::TIMESTAMPTZ => Time,
Java::oracle.jdbc.OracleTypes::TIMESTAMPLTZ => Time,
java.sql.Types::BLOB => String,
java.sql.Types::CLOB => String,
java.sql.Types::ARRAY => Java::OracleSql::ARRAY,
java.sql.Types::STRUCT => Java::OracleSql::STRUCT,
Java::oracle.jdbc.OracleTypes::CURSOR => java.sql.ResultSet
}
def get_java_sql_type(value, type)
RUBY_CLASS_TO_SQL_TYPE[type || value.class] || java.sql.Types::VARCHAR
end
def set_bind_variable(stmt, i, value, type = nil, length = nil, metadata = {})
key = i.kind_of?(Integer) ? nil : i.to_s.gsub(":", "")
type_symbol = (!value.nil? && type ? type : value.class).to_s.to_sym
case type_symbol
when :Fixnum, :Bignum, :Integer
stmt.send("setInt#{key && "AtName"}", key || i, value)
when :Float
stmt.send("setFloat#{key && "AtName"}", key || i, value)
when :BigDecimal, :'Java::JavaMath::BigDecimal'
stmt.send("setBigDecimal#{key && "AtName"}", key || i, value)
when :String
stmt.send("setString#{key && "AtName"}", key || i, value)
when :'Java::OracleSql::CLOB'
stmt.send("setClob#{key && "AtName"}", key || i, value)
when :'Java::OracleSql::BLOB'
stmt.send("setBlob#{key && "AtName"}", key || i, value)
when :Date, :DateTime, :'Java::OracleSql::DATE'
stmt.send("setDATE#{key && "AtName"}", key || i, value)
when :Time, :'Java::JavaSql::Timestamp'
stmt.send("setTimestamp#{key && "AtName"}", key || i, value)
when :NilClass
if ["TABLE", "VARRAY", "OBJECT", "XMLTYPE"].include?(metadata[:data_type])
stmt.send("setNull#{key && "AtName"}", key || i, get_java_sql_type(value, type),
metadata[:sql_type_name])
elsif metadata[:data_type] == "REF CURSOR"
# TODO: cannot bind NULL value to cursor parameter, getting error
# java.sql.SQLException: Unsupported feature: sqlType=-10
# Currently do nothing and assume that NULL values will not be passed to IN parameters
# If cursor is IN/OUT or OUT parameter then it should work
else
stmt.send("setNull#{key && "AtName"}", key || i, get_java_sql_type(value, type))
end
when :'Java::OracleSql::ARRAY'
stmt.send("setARRAY#{key && "AtName"}", key || i, value)
when :'Java::OracleSql::STRUCT'
stmt.send("setSTRUCT#{key && "AtName"}", key || i, value)
when :'Java::JavaSql::ResultSet'
# TODO: cannot find how to pass cursor parameter from JDBC
# setCursor is giving exception java.sql.SQLException: Unsupported feature
stmt.send("setCursor#{key && "AtName"}", key || i, value)
else
raise ArgumentError, "Don't know how to bind variable with type #{type_symbol}"
end
end
def get_bind_variable(stmt, i, type)
case type.to_s.to_sym
when :Fixnum, :Bignum, :Integer
stmt.getObject(i)
when :Float
stmt.getFloat(i)
when :BigDecimal
bd = stmt.getBigDecimal(i)
bd && BigDecimal(bd.to_s)
when :String
stmt.getString(i)
when :'Java::OracleSql::CLOB'
stmt.getClob(i)
when :'Java::OracleSql::BLOB'
stmt.getBlob(i)
when :Date, :DateTime
stmt.getDATE(i)
when :Time
stmt.getTimestamp(i)
when :'Java::OracleSql::ARRAY'
stmt.getArray(i)
when :'Java::OracleSql::STRUCT'
stmt.getSTRUCT(i)
when :'Java::JavaSql::ResultSet'
stmt.getCursor(i)
end
end
def get_ruby_value_from_result_set(rset, i, metadata)
ruby_type = SQL_TYPE_TO_RUBY_CLASS[metadata[:sql_type]]
ora_value = get_bind_variable(rset, i, ruby_type)
result_new = ora_value_to_ruby_value(ora_value)
end
def result_set_to_ruby_data_type(column_type, column_type_name)
end
def plsql_to_ruby_data_type(metadata)
data_type, data_length = metadata[:data_type], metadata[:data_length]
case data_type
when "VARCHAR", "VARCHAR2", "CHAR", "NVARCHAR2", "NCHAR"
[String, data_length || 32767]
when "CLOB", "NCLOB"
[Java::OracleSql::CLOB, nil]
when "BLOB"
[Java::OracleSql::BLOB, nil]
when "NUMBER"
[BigDecimal, nil]
when "NATURAL", "NATURALN", "POSITIVE", "POSITIVEN", "SIGNTYPE", "SIMPLE_INTEGER", "PLS_INTEGER", "BINARY_INTEGER"
[Integer, nil]
when "DATE"
[DateTime, nil]
when "TIMESTAMP", "TIMESTAMP WITH TIME ZONE", "TIMESTAMP WITH LOCAL TIME ZONE"
[Time, nil]
when "TABLE", "VARRAY"
[Java::OracleSql::ARRAY, nil]
when "OBJECT"
[Java::OracleSql::STRUCT, nil]
when "REF CURSOR"
[java.sql.ResultSet, nil]
else
[String, 32767]
end
end
def ruby_value_to_ora_value(value, type = nil, metadata = {})
type ||= value.class
case type.to_s.to_sym
when :Integer
value
when :String
value.to_s
when :BigDecimal
case value
when TrueClass
java_bigdecimal(1)
when FalseClass
java_bigdecimal(0)
else
java_bigdecimal(value)
end
when :Date, :DateTime
case value
when DateTime
java_date(Time.send(plsql.default_timezone, value.year, value.month, value.day, value.hour, value.min, value.sec))
when Date
java_date(Time.send(plsql.default_timezone, value.year, value.month, value.day, 0, 0, 0))
else
java_date(value)
end
when :Time
java_timestamp(value)
when :'Java::OracleSql::CLOB'
if value
clob = Java::OracleSql::CLOB.createTemporary(raw_connection, false, Java::OracleSql::CLOB::DURATION_SESSION)
clob.setString(1, value)
clob
else
nil
end
when :'Java::OracleSql::BLOB'
if value
blob = Java::OracleSql::BLOB.createTemporary(raw_connection, false, Java::OracleSql::BLOB::DURATION_SESSION)
blob.setBytes(1, value.to_java_bytes)
blob
else
nil
end
when :'Java::OracleSql::ARRAY'
if value
raise ArgumentError, "You should pass Array value for collection type parameter" unless value.is_a?(Array)
descriptor = Java::OracleSql::ArrayDescriptor.createDescriptor(metadata[:sql_type_name], raw_connection)
elem_type = descriptor.getBaseType
elem_type_name = descriptor.getBaseName
elem_list = value.map do |elem|
case elem_type
when Java::oracle.jdbc.OracleTypes::ARRAY
ruby_value_to_ora_value(elem, Java::OracleSql::ARRAY, sql_type_name: elem_type_name)
when Java::oracle.jdbc.OracleTypes::STRUCT
ruby_value_to_ora_value(elem, Java::OracleSql::STRUCT, sql_type_name: elem_type_name)
else
ruby_value_to_ora_value(elem)
end
end
Java::OracleSql::ARRAY.new(descriptor, raw_connection, elem_list.to_java)
end
when :'Java::OracleSql::STRUCT'
if value
raise ArgumentError, "You should pass Hash value for object type parameter" unless value.is_a?(Hash)
descriptor = Java::OracleSql::StructDescriptor.createDescriptor(metadata[:sql_type_name], raw_connection)
struct_metadata = descriptor.getMetaData
struct_fields = (1..descriptor.getLength).inject({}) do |hash, i|
hash[struct_metadata.getColumnName(i).downcase.to_sym] =
{ type: struct_metadata.getColumnType(i), type_name: struct_metadata.getColumnTypeName(i) }
hash
end
object_attrs = java.util.HashMap.new
value.each do |key, attr_value|
raise ArgumentError, "Wrong object type field passed to PL/SQL procedure" unless (field = struct_fields[key])
case field[:type]
when Java::oracle.jdbc.OracleTypes::ARRAY
# nested collection
object_attrs.put(key.to_s.upcase, ruby_value_to_ora_value(attr_value, Java::OracleSql::ARRAY, sql_type_name: field[:type_name]))
when Java::oracle.jdbc.OracleTypes::STRUCT
# nested object type
object_attrs.put(key.to_s.upcase, ruby_value_to_ora_value(attr_value, Java::OracleSql::STRUCT, sql_type_name: field[:type_name]))
else
object_attrs.put(key.to_s.upcase, ruby_value_to_ora_value(attr_value))
end
end
Java::OracleSql::STRUCT.new(descriptor, raw_connection, object_attrs)
end
when :'Java::JavaSql::ResultSet'
if value
value.result_set
end
else
value
end
end
def ora_value_to_ruby_value(value)
case value
when Float, BigDecimal
ora_number_to_ruby_number(value)
when Java::JavaMath::BigDecimal
value && ora_number_to_ruby_number(BigDecimal(value.to_s))
when Java::OracleSql::DATE
if value
d = value.dateValue
t = value.timeValue
Time.send(plsql.default_timezone, d.year + 1900, d.month + 1, d.date, t.hours, t.minutes, t.seconds)
end
when Java::JavaSql::Timestamp
if value
Time.send(plsql.default_timezone, value.year + 1900, value.month + 1, value.date, value.hours, value.minutes, value.seconds,
value.nanos / 1000)
end
when Java::OracleSql::CLOB
if value.isEmptyLob
nil
else
value.getSubString(1, value.length)
end
when Java::OracleSql::BLOB
if value.isEmptyLob
nil
else
String.from_java_bytes(value.getBytes(1, value.length))
end
when Java::OracleSql::ARRAY
value.getArray.map { |e| ora_value_to_ruby_value(e) }
when Java::OracleSql::STRUCT
descriptor = value.getDescriptor
struct_metadata = descriptor.getMetaData
field_names = (1..descriptor.getLength).map { |i| struct_metadata.getColumnName(i).downcase.to_sym }
field_values = value.getAttributes.map { |e| ora_value_to_ruby_value(e) }
ArrayHelpers::to_hash(field_names, field_values)
when Java::java.sql.ResultSet
Cursor.new(self, value)
else
value
end
end
def database_version
@database_version ||= if md = raw_connection.getMetaData
major = md.getDatabaseMajorVersion
minor = md.getDatabaseMinorVersion
if md.getDatabaseProductVersion =~ /#{major}\.#{minor}\.(\d+)\.(\d+)/
update = $1.to_i
patch = $2.to_i
else
update = patch = 0
end
[major, minor, update, patch]
end
end
private
def java_date(value)
value && Java::oracle.sql.DATE.new(value.strftime("%Y-%m-%d %H:%M:%S"))
end
def java_timestamp(value)
value && Java::java.sql.Timestamp.new(value.year - 1900, value.month - 1, value.day, value.hour, value.min, value.sec, value.usec * 1000)
end
def java_bigdecimal(value)
value && java.math.BigDecimal.new(value.to_s)
end
def ora_number_to_ruby_number(num)
# return BigDecimal instead of Float to avoid rounding errors
num == (num_to_i = num.to_i) ? num_to_i : (num.is_a?(BigDecimal) ? num : BigDecimal(num.to_s))
end
end
end
| ruby | MIT | 7bee9ba2b3207de7c1ae4112d8af2636b586c610 | 2026-01-04T17:45:33.227772Z | false |
rsim/ruby-plsql | https://github.com/rsim/ruby-plsql/blob/7bee9ba2b3207de7c1ae4112d8af2636b586c610/lib/plsql/variable.rb | lib/plsql/variable.rb | module PLSQL
module VariableClassMethods #:nodoc:
def find(schema, variable, package, override_schema_name = nil)
variable_upcase = variable.to_s.upcase
schema.select_all(
"SELECT text FROM all_source
WHERE owner = :owner
AND name = :object_name
AND type = 'PACKAGE'
AND UPPER(text) LIKE :variable_name",
override_schema_name || schema.schema_name, package, "%#{variable_upcase}%").each do |row|
if row[0] =~ /^\s*#{variable_upcase}\s+(CONSTANT\s+)?([A-Z0-9_. %]+(\([\w\s,]+\))?)\s*(NOT\s+NULL)?\s*((:=|DEFAULT).*)?;\s*(--.*)?$/i
return new(schema, variable, package, $2.strip, override_schema_name)
end
end
nil
end
end
class Variable #:nodoc:
extend VariableClassMethods
attr_reader :schema_name, :package_name, :variable_name #:nodoc:
def initialize(schema, variable, package, variable_type, override_schema_name = nil)
@schema = schema
@schema_name = override_schema_name || schema.schema_name
@variable_name = variable.to_s.upcase
@package_name = package
@variable_type = variable_type.upcase
@metadata = metadata(@variable_type)
end
def value
@variable_get_proc ||= VariableProcedure.new(@schema, self, :get, @metadata)
ProcedureCall.new(@variable_get_proc).exec
end
def value=(new_value)
@variable_set_proc ||= VariableProcedure.new(@schema, self, :set, @metadata)
ProcedureCall.new(@variable_set_proc, [new_value]).exec
new_value
end
private
def metadata(type_string)
case type_string
when /^(VARCHAR|VARCHAR2|CHAR|NVARCHAR2|NCHAR)(\((\d+)[\s\w]*\))?$/
{ data_type: $1, data_length: $3.to_i, in_out: "IN/OUT" }
when /^(CLOB|NCLOB|BLOB)$/,
/^(NUMBER)(\(.*\))?$/, /^(NATURAL|NATURALN|POSITIVE|POSITIVEN|SIGNTYPE|SIMPLE_INTEGER|PLS_INTEGER|BINARY_INTEGER)$/,
/^(DATE|TIMESTAMP|TIMESTAMP WITH TIME ZONE|TIMESTAMP WITH LOCAL TIME ZONE)$/,
/^(XMLTYPE)$/
{ data_type: $1, in_out: "IN/OUT" }
when /^INTEGER$/
{ data_type: "NUMBER", in_out: "IN/OUT" }
when /^BOOLEAN$/
{ data_type: "PL/SQL BOOLEAN", in_out: "IN/OUT" }
when /^(\w+\.)?(\w+)\.(\w+)%TYPE$/
schema = $1 ? plsql.send($1.chop) : plsql
table = schema.send($2.downcase.to_sym)
column = table.columns[$3.downcase.to_sym]
{ data_type: column[:data_type], data_length: column[:data_length], sql_type_name: column[:sql_type_name], in_out: "IN/OUT" }
when /^(\w+\.)?(\w+)$/
schema = $1 ? @schema.root_schema.send($1.chop) : @schema
begin
type = schema.send($2.downcase.to_sym)
raise ArgumentError unless type.is_a?(PLSQL::Type)
typecode = case type.typecode
when "COLLECTION" then "TABLE"
else "OBJECT"
end
{ data_type: typecode, data_length: nil, sql_type_name: "#{type.schema_name}.#{type.type_name}", in_out: "IN/OUT" }
rescue ArgumentError
raise ArgumentError, "Package variable data type #{type_string} is not object type defined in schema"
end
when /^(\w+\.)?(\w+)%ROWTYPE$/
schema = $1 ? plsql.send($1.chop) : plsql
table = schema.send($2.downcase.to_sym)
record_metadata = {
data_type: "PL/SQL RECORD",
in_out: "IN/OUT",
fields: {}
}
table.columns.each do |name, col|
record_metadata[:fields][name] =
{ data_type: col[:data_type], data_length: col[:data_length], sql_type_name: col[:sql_type_name],
position: col[:position], in_out: "IN/OUT" }
end
record_metadata
else
raise ArgumentError, "Package variable data type #{type_string} is not supported"
end
end
# wrapper class to simulate Procedure class for ProcedureClass#exec
class VariableProcedure #:nodoc:
attr_reader :arguments, :argument_list, :return, :out_list, :schema
def initialize(schema, variable, operation, metadata)
@schema = schema
@variable = variable
@operation = operation
@metadata = metadata
@out_list = [[]]
case @operation
when :get
@argument_list = [[]]
@arguments = [{}]
@return = [@metadata]
when :set
@argument_list = [[:value]]
@arguments = [{ value: @metadata }]
@return = [nil]
end
end
def overloaded?
false
end
def procedure
nil
end
def call_sql(params_string)
sql = (schema_name = @variable.schema_name) ? "#{schema_name}." : ""
sql << "#{@variable.package_name}.#{@variable.variable_name}"
case @operation
when :get
# params string contains assignment to return variable
"#{params_string} #{sql};\n"
when :set
"#{sql} := #{params_string};\n"
end
end
end
end
end
| ruby | MIT | 7bee9ba2b3207de7c1ae4112d8af2636b586c610 | 2026-01-04T17:45:33.227772Z | false |
rsim/ruby-plsql | https://github.com/rsim/ruby-plsql/blob/7bee9ba2b3207de7c1ae4112d8af2636b586c610/lib/plsql/schema.rb | lib/plsql/schema.rb | module PLSQL
class Schema
include SQLStatements
@@schemas = {}
class <<self
def find_or_new(connection_alias) #:nodoc:
connection_alias ||= :default
if @@schemas[connection_alias]
@@schemas[connection_alias]
else
@@schemas[connection_alias] = self.new
end
end
end
def initialize(raw_conn = nil, schema = nil, original_schema = nil) #:nodoc:
self.connection = raw_conn
@schema_name = schema ? schema.to_s.upcase : nil
@original_schema = original_schema
@dbms_output_stream = nil
end
# Returns connection wrapper object (this is not raw OCI8 or JDBC connection!)
attr_reader :connection
def root_schema #:nodoc:
@original_schema || self
end
def raw_connection=(raw_conn) #:nodoc:
@connection = raw_conn ? Connection.create(raw_conn) : nil
reset_instance_variables
end
# Set connection to OCI8 or JDBC connection:
#
# plsql.connection = OCI8.new(database_user, database_password, database_name)
#
# or
#
# plsql.connection = java.sql.DriverManager.getConnection(
# "jdbc:oracle:thin:@#{database_host}:#{database_port}/#{database_service_name}",
# database_user, database_password)
#
def connection=(conn)
if conn.is_a?(Connection)
@connection = conn
reset_instance_variables
else
self.raw_connection = conn
end
conn
end
# Create new OCI8 or JDBC connection using one of the following ways:
#
# plsql.connect! username, password, database_tns_alias
# plsql.connect! username, password, :host => host, :port => port, :database => database
# plsql.connect! :username => username, :password => password, :database => database_tns_alias
# plsql.connect! :username => username, :password => password, :host => host, :port => port, :database => database
#
def connect!(*args)
params = {}
params[:username] = args.shift if args[0].is_a?(String)
params[:password] = args.shift if args[0].is_a?(String)
params[:database] = args.shift if args[0].is_a?(String)
params.merge!(args.shift) if args[0].is_a?(Hash)
raise ArgumentError, "Wrong number of arguments" unless args.empty?
self.connection = Connection.create_new(params)
end
# Set connection to current ActiveRecord connection (use in initializer file):
#
# plsql.activerecord_class = ActiveRecord::Base
#
def activerecord_class=(ar_class)
@connection = ar_class ? Connection.create(nil, ar_class) : nil
reset_instance_variables
ar_class
end
# Disconnect from Oracle
def logoff
@connection.logoff
self.connection = nil
end
# Current Oracle schema name
def schema_name
return nil unless connection
@schema_name ||= select_first("SELECT SYS_CONTEXT('userenv','current_schema') FROM dual")[0]
end
# Default timezone to which database values will be converted - :utc or :local
def default_timezone
if @original_schema
@original_schema.default_timezone
else
@default_timezone ||
# Use ActiveRecord class default_timezone when ActiveRecord connection is used
(@connection && (ar_class = @connection.activerecord_class) && ar_class.default_timezone) ||
# default to local timezone
:local
end
end
# Set default timezone to which database values will be converted - :utc or :local
def default_timezone=(value)
if [:local, :utc].include?(value)
@default_timezone = value
else
raise ArgumentError, "default timezone should be :local or :utc"
end
end
# Same implementation as for ActiveRecord
# DateTimes aren't aware of DST rules, so use a consistent non-DST offset when creating a DateTime with an offset in the local zone
def local_timezone_offset #:nodoc:
::Time.local(2007).utc_offset.to_r / 86400
end
# DBMS_OUTPUT buffer size (default is 20_000)
def dbms_output_buffer_size
if @original_schema
@original_schema.dbms_output_buffer_size
else
@dbms_output_buffer_size || 20_000
end
end
# Seet DBMS_OUTPUT buffer size (default is 20_000). Example:
#
# plsql.dbms_output_buffer_size = 100_000
#
def dbms_output_buffer_size=(value)
@dbms_output_buffer_size = value
end
# Maximum line numbers for DBMS_OUTPUT in one PL/SQL call (from DBMSOUTPUT_LINESARRAY type)
DBMS_OUTPUT_MAX_LINES = 2147483647
# Specify IO stream where to log DBMS_OUTPUT from PL/SQL procedures. Example:
#
# plsql.dbms_output_stream = STDOUT
#
def dbms_output_stream=(stream)
@dbms_output_stream = stream
if @dbms_output_stream.nil? && @connection
sys.dbms_output.disable
end
end
# IO stream where to log DBMS_OUTPUT from PL/SQL procedures.
def dbms_output_stream
if @original_schema
@original_schema.dbms_output_stream
else
@dbms_output_stream
end
end
private
def reset_instance_variables
if @connection
@schema_objects = {}
else
@schema_objects = nil
end
@schema_name = nil
@default_timezone = nil
end
def method_missing(method, *args, &block)
raise ArgumentError, "No database connection" unless connection
# search in database if not in cache at first
object = (@schema_objects[method] ||= find_database_object(method) || find_other_schema(method) ||
find_public_synonym(method) || find_standard_procedure(method))
raise ArgumentError, "No database object '#{method.to_s.upcase}' found" unless object
if object.is_a?(Procedure)
object.exec(*args, &block)
elsif object.is_a?(Type) && !args.empty?
object.new(*args, &block)
else
object
end
end
def find_database_object(name, override_schema_name = nil)
object_schema_name = override_schema_name || schema_name
object_name = name.to_s.upcase
if row = select_first(
"SELECT o.object_type, o.object_id
FROM all_objects o
WHERE owner = :owner AND object_name = :object_name
AND object_type IN ('PROCEDURE','FUNCTION','PACKAGE','TABLE','VIEW','SEQUENCE','TYPE','SYNONYM')",
object_schema_name, object_name)
object_type, object_id = row
case object_type
when "PROCEDURE", "FUNCTION"
if (connection.database_version <=> [11, 1, 0, 0]) >= 0
if row = select_first(
"SELECT p.object_id FROM all_procedures p
WHERE p.owner = :owner
AND p.object_name = :object_name
AND p.object_type = :object_type",
object_schema_name, object_name, object_type)
object_id = row[0]
else
raise ArgumentError, "Database object '#{object_schema_name}.#{object_name}' is not in valid status\n#{
_errors(object_schema_name, object_name, object_type)}"
end
end
Procedure.new(self, name, nil, override_schema_name, object_id)
when "PACKAGE"
Package.new(self, name, override_schema_name)
when "TABLE"
Table.new(self, name, override_schema_name)
when "VIEW"
View.new(self, name, override_schema_name)
when "SEQUENCE"
Sequence.new(self, name, override_schema_name)
when "TYPE"
Type.new(self, name, override_schema_name)
when "SYNONYM"
target_schema_name, target_object_name = @connection.describe_synonym(object_schema_name, object_name)
find_database_object(target_object_name, target_schema_name)
end
end
end
def _errors(object_schema_name, object_name, object_type)
result = ""
previous_line = 0
select_all(
"SELECT e.line, e.position, e.text error_text, s.text source_text
FROM all_errors e, all_source s
WHERE e.owner = :owner AND e.name = :name AND e.type = :type
AND s.owner = e.owner AND s.name = e.name AND s.type = e.type AND s.line = e.line
ORDER BY e.sequence",
object_schema_name, object_name, object_type
).each do |line, position, error_text, source_text|
result << "Error on line #{'%4d' % line}: #{source_text}" if line > previous_line
result << " position #{'%4d' % position}: #{error_text}\n"
previous_line = line
end
result unless result.empty?
end
def find_other_schema(name)
return nil if @original_schema
if select_first("SELECT username FROM all_users WHERE username = :username", name.to_s.upcase)
Schema.new(connection, name, self)
else
nil
end
end
def find_standard_procedure(name)
return nil if @original_schema
Procedure.find(self, name, "STANDARD", "SYS")
end
def find_public_synonym(name)
return nil if @original_schema
target_schema_name, target_object_name = @connection.describe_synonym("PUBLIC", name)
find_database_object(target_object_name, target_schema_name) if target_schema_name
end
end
end
module Kernel
# Returns current schema object. You can now chain either database object (packages, procedures, tables, sequences)
# in current schema or specify different schema name. Examples:
#
# plsql.test_function('some parameter')
# plsql.test_package.test_function('some parameter')
# plsql.other_schema.test_package.test_function('some parameter')
# plsql.table_name.all
# plsql.other_schema.table_name.all
#
def plsql(connection_alias = nil)
PLSQL::Schema.find_or_new(connection_alias)
end
end
| ruby | MIT | 7bee9ba2b3207de7c1ae4112d8af2636b586c610 | 2026-01-04T17:45:33.227772Z | false |
rsim/ruby-plsql | https://github.com/rsim/ruby-plsql/blob/7bee9ba2b3207de7c1ae4112d8af2636b586c610/lib/plsql/procedure.rb | lib/plsql/procedure.rb | module PLSQL
module ProcedureClassMethods #:nodoc:
def find(schema, procedure, package = nil, override_schema_name = nil)
if package.nil?
if (row = schema.select_first(
"SELECT #{procedure_object_id_src(schema)}.object_id
FROM all_procedures p, all_objects o
WHERE p.owner = :owner
AND p.object_name = :object_name
AND o.owner = p.owner
AND o.object_name = p.object_name
AND o.object_type in ('PROCEDURE', 'FUNCTION')",
schema.schema_name, procedure.to_s.upcase))
new(schema, procedure, nil, nil, row[0])
# search for synonym
elsif (row = schema.select_first(
"SELECT o.owner, o.object_name, #{procedure_object_id_src(schema)}.object_id
FROM all_synonyms s, all_objects o, all_procedures p
WHERE s.owner IN (:owner, 'PUBLIC')
AND s.synonym_name = :synonym_name
AND o.owner = s.table_owner
AND o.object_name = s.table_name
AND o.object_type IN ('PROCEDURE','FUNCTION')
AND o.owner = p.owner
AND o.object_name = p.object_name
ORDER BY DECODE(s.owner, 'PUBLIC', 1, 0)",
schema.schema_name, procedure.to_s.upcase))
new(schema, row[1], nil, row[0], row[2])
else
nil
end
elsif package && (row = schema.select_first(
# older Oracle versions do not have object_id column in all_procedures
"SELECT #{procedure_object_id_src(schema)}.object_id
FROM all_procedures p, all_objects o
WHERE p.owner = :owner
AND p.object_name = :object_name
AND p.procedure_name = :procedure_name
AND o.owner = p.owner
AND o.object_name = p.object_name
AND o.object_type = 'PACKAGE'",
override_schema_name || schema.schema_name, package, procedure.to_s.upcase))
new(schema, procedure, package, override_schema_name, row[0])
else
nil
end
end
private
def procedure_object_id_src(schema)
(schema.connection.database_version <=> [11, 1, 0, 0]) >= 0 ? "p" : "o"
end
end
module ProcedureCommon #:nodoc:
attr_reader :arguments, :argument_list, :out_list, :return
attr_reader :schema, :schema_name, :package, :procedure
# return type string from metadata that can be used in DECLARE block or table definition
def self.type_to_sql(metadata) #:nodoc:
case metadata[:data_type]
when "NUMBER"
precision, scale = metadata[:data_precision], metadata[:data_scale]
"NUMBER#{precision ? "(#{precision}#{scale ? ",#{scale}" : ""})" : ""}"
when "VARCHAR", "VARCHAR2", "CHAR"
length = case metadata[:char_used]
when "C" then "#{metadata[:char_length]} CHAR"
when "B" then "#{metadata[:data_length]} BYTE"
else
metadata[:data_length]
end
"#{metadata[:data_type]}#{length && "(#{length})"}"
when "NVARCHAR2", "NCHAR"
length = metadata[:char_length]
"#{metadata[:data_type]}#{length && "(#{length})"}"
when "PL/SQL TABLE", "TABLE", "VARRAY", "OBJECT", "XMLTYPE"
metadata[:sql_type_name]
else
metadata[:data_type]
end
end
# get procedure argument metadata from data dictionary
def get_argument_metadata #:nodoc:
if (@schema.connection.database_version <=> [18, 0, 0, 0]) >= 0
get_argument_metadata_from_18c
else
get_argument_metadata_below_18c
end
end
def get_argument_metadata_below_18c #:nodoc:
@arguments = {}
@argument_list = {}
@out_list = {}
@return = {}
@overloaded = false
# store reference to previous level record or collection metadata
previous_level_argument_metadata = {}
# store tmp tables for each overload for table parameters with types defined inside packages
@tmp_table_names = {}
# store if tmp tables are created for specific overload
@tmp_tables_created = {}
# subprogram_id column is available just from version 10g
subprogram_id_column = (@schema.connection.database_version <=> [10, 2, 0, 2]) >= 0 ? "subprogram_id" : "NULL"
# defaulted is available just from version 11g
defaulted_column = (@schema.connection.database_version <=> [11, 0, 0, 0]) >= 0 ? "defaulted" : "NULL"
@schema.select_all(
"SELECT #{subprogram_id_column}, object_name, TO_NUMBER(overload), argument_name, position, data_level,
data_type, in_out, data_length, data_precision, data_scale, char_used,
char_length, type_owner, type_name, type_subname, #{defaulted_column}
FROM all_arguments
WHERE object_id = :object_id
AND owner = :owner
AND object_name = :procedure_name
ORDER BY overload, sequence",
@object_id, @schema_name, @procedure
) do |r|
subprogram_id, object_name, overload, argument_name, position, data_level,
data_type, in_out, data_length, data_precision, data_scale, char_used,
char_length, type_owner, type_name, type_subname, defaulted = r
@overloaded ||= !overload.nil?
# if not overloaded then store arguments at key 0
overload ||= 0
@arguments[overload] ||= {}
@return[overload] ||= nil
@tmp_table_names[overload] ||= []
sql_type_name = type_owner && "#{type_owner == 'PUBLIC' ? nil : "#{type_owner}."}#{type_name}#{type_subname ? ".#{type_subname}" : nil}"
tmp_table_name = nil
# type defined inside package
if type_subname
if collection_type?(data_type)
raise ArgumentError, "#{data_type} type #{sql_type_name} definition inside package is not supported as part of other type definition," <<
" use CREATE TYPE outside package" if data_level > 0
# if subprogram_id was not supported by all_arguments view
# then generate unique ID from object_name and overload
subprogram_id ||= "#{object_name.hash % 10000}#{overload}"
tmp_table_name = "#{Connection::RUBY_TEMP_TABLE_PREFIX}#{@schema.connection.session_id}_#{@object_id}_#{subprogram_id}_#{position}"
elsif data_type != "PL/SQL RECORD"
# raise exception only when there are no overloaded procedure definitions
# (as probably this overload will not be used at all)
raise ArgumentError, "Parameter type #{sql_type_name} definition inside package is not supported, use CREATE TYPE outside package" if overload == 0
end
end
argument_metadata = {
position: position && position.to_i,
data_type: data_type,
in_out: in_out,
data_length: data_length && data_length.to_i,
data_precision: data_precision && data_precision.to_i,
data_scale: data_scale && data_scale.to_i,
char_used: char_used,
char_length: char_length && char_length.to_i,
type_owner: type_owner,
type_name: type_name,
type_subname: type_subname,
sql_type_name: sql_type_name,
defaulted: defaulted
}
if tmp_table_name
@tmp_table_names[overload] << [(argument_metadata[:tmp_table_name] = tmp_table_name), argument_metadata]
end
if composite_type?(data_type)
case data_type
when "PL/SQL RECORD"
argument_metadata[:fields] = {}
end
previous_level_argument_metadata[data_level] = argument_metadata
end
# if function has return value
if argument_name.nil? && data_level == 0 && in_out == "OUT"
@return[overload] = argument_metadata
# if parameter
else
# top level parameter
if data_level == 0
# sometime there are empty IN arguments in all_arguments view for procedures without arguments (e.g. for DBMS_OUTPUT.DISABLE)
@arguments[overload][argument_name.downcase.to_sym] = argument_metadata if argument_name
# or lower level part of composite type
else
case previous_level_argument_metadata[data_level - 1][:data_type]
when "PL/SQL RECORD"
previous_level_argument_metadata[data_level - 1][:fields][argument_name.downcase.to_sym] = argument_metadata
when "PL/SQL TABLE", "TABLE", "VARRAY", "REF CURSOR"
previous_level_argument_metadata[data_level - 1][:element] = argument_metadata
end
end
end
end
# if procedure is without arguments then create default empty argument list for default overload
@arguments[0] = {} if @arguments.keys.empty?
construct_argument_list_for_overloads
end
# get procedure argument metadata from data dictionary
def get_argument_metadata_from_18c #:nodoc:
@arguments = {}
@argument_list = {}
@out_list = {}
@return = {}
@overloaded = false
# store tmp tables for each overload for table parameters with types defined inside packages
@tmp_table_names = {}
# store if tmp tables are created for specific overload
@tmp_tables_created = {}
@schema.select_all(
"SELECT subprogram_id, object_name, TO_NUMBER(overload), argument_name, position,
data_type, in_out, data_length, data_precision, data_scale, char_used,
char_length, type_owner, nvl(type_subname, type_name),
decode(type_object_type, 'PACKAGE', type_name, null), type_object_type, defaulted
FROM all_arguments
WHERE object_id = :object_id
AND owner = :owner
AND object_name = :procedure_name
ORDER BY overload, sequence",
@object_id, @schema_name, @procedure
) do |r|
subprogram_id, _object_name, overload, argument_name, position,
data_type, in_out, data_length, data_precision, data_scale, char_used,
char_length, type_owner, type_name, type_package, type_object_type, defaulted = r
@overloaded ||= !overload.nil?
# if not overloaded then store arguments at key 0
overload ||= 0
@arguments[overload] ||= {}
@return[overload] ||= nil
@tmp_table_names[overload] ||= []
sql_type_name = build_sql_type_name(type_owner, type_package, type_name)
tmp_table_name = nil
# type defined inside package
if type_package
if collection_type?(data_type)
tmp_table_name = "#{Connection::RUBY_TEMP_TABLE_PREFIX}#{@schema.connection.session_id}_#{@object_id}_#{subprogram_id}_#{position}"
end
end
argument_metadata = {
position: position && position.to_i,
data_type: data_type,
in_out: in_out,
data_length: data_length && data_length.to_i,
data_precision: data_precision && data_precision.to_i,
data_scale: data_scale && data_scale.to_i,
char_used: char_used,
char_length: char_length && char_length.to_i,
type_owner: type_owner,
type_name: type_name,
# TODO: should be renamed to type_package, when support for legacy database versions is dropped
# due to the explicit change declaration of types in oracle plsql_type-catalogs (type_package + type_name),
# the assignment of type + subtype was switched here for 18c and beyond
type_subname: type_package,
sql_type_name: sql_type_name,
defaulted: defaulted,
type_object_type: type_object_type
}
if tmp_table_name
@tmp_table_names[overload] << [(argument_metadata[:tmp_table_name] = tmp_table_name), argument_metadata]
end
if composite_type?(data_type)
case data_type
when "PL/SQL RECORD", "REF CURSOR"
argument_metadata[:fields] = get_field_definitions(argument_metadata)
when "PL/SQL TABLE", "TABLE", "VARRAY"
argument_metadata[:element] = get_element_definition(argument_metadata)
end
end
# if function has return value
if argument_name.nil? && in_out == "OUT"
@return[overload] = argument_metadata
else
# sometime there are empty IN arguments in all_arguments view for procedures without arguments (e.g. for DBMS_OUTPUT.DISABLE)
@arguments[overload][argument_name.downcase.to_sym] = argument_metadata if argument_name
end
end
# if procedure is without arguments then create default empty argument list for default overload
@arguments[0] = {} if @arguments.keys.empty?
construct_argument_list_for_overloads
end
def construct_argument_list_for_overloads #:nodoc:
@overloads = @arguments.keys.sort
@overloads.each do |overload|
@argument_list[overload] = @arguments[overload].keys.sort { |k1, k2| @arguments[overload][k1][:position] <=> @arguments[overload][k2][:position] }
@out_list[overload] = @argument_list[overload].select { |k| @arguments[overload][k][:in_out] =~ /OUT/ }
end
end
def ensure_tmp_tables_created(overload) #:nodoc:
return if @tmp_tables_created.nil? || @tmp_tables_created[overload]
@tmp_table_names[overload] && @tmp_table_names[overload].each do |table_name, argument_metadata|
sql = "CREATE GLOBAL TEMPORARY TABLE #{table_name} (\n"
element_metadata = argument_metadata[:element]
case element_metadata[:data_type]
when "PL/SQL RECORD"
fields_metadata = element_metadata[:fields]
fields_sorted_by_position = fields_metadata.keys.sort_by { |k| fields_metadata[k][:position] }
sql << fields_sorted_by_position.map do |field|
metadata = fields_metadata[field]
"#{field} #{ProcedureCommon.type_to_sql(metadata)}"
end.join(",\n")
else
sql << "element #{ProcedureCommon.type_to_sql(element_metadata)}"
end
sql << ",\ni__ NUMBER(38)\n"
sql << ") ON COMMIT PRESERVE ROWS\n"
sql_block = "DECLARE\nPRAGMA AUTONOMOUS_TRANSACTION;\nBEGIN\nEXECUTE IMMEDIATE :sql;\nEND;\n"
@schema.execute sql_block, sql
end
@tmp_tables_created[overload] = true
end
def build_sql_type_name(type_owner, type_package, type_name) #:nodoc:
if type_owner == nil || type_owner == "PUBLIC"
type_owner_res = ""
else
type_owner_res = "#{type_owner}."
end
if type_package == nil
type_name_res = type_name
else
type_name_res = "#{type_package}.#{type_name}"
end
type_name_res && "#{type_owner_res}#{type_name_res}"
end
def get_field_definitions(argument_metadata) #:nodoc:
fields = {}
case argument_metadata[:type_object_type]
when "PACKAGE"
@schema.select_all(
"SELECT attr_no, attr_name, attr_type_owner, attr_type_name, attr_type_package, length, precision, scale, char_used
FROM ALL_PLSQL_TYPES t, ALL_PLSQL_TYPE_ATTRS ta
WHERE t.OWNER = :owner AND t.type_name = :type_name AND t.package_name = :package_name
AND ta.OWNER = t.owner AND ta.TYPE_NAME = t.TYPE_NAME AND ta.PACKAGE_NAME = t.PACKAGE_NAME
ORDER BY attr_no",
@schema_name, argument_metadata[:type_name], argument_metadata[:type_subname]) do |r|
attr_no, attr_name, attr_type_owner, attr_type_name, attr_type_package, attr_length, attr_precision, attr_scale, attr_char_used = r
fields[attr_name.downcase.to_sym] = {
position: attr_no.to_i,
data_type: attr_type_owner == nil ? attr_type_name : get_composite_type(attr_type_owner, attr_type_name, attr_type_package),
in_out: argument_metadata[:in_out],
data_length: attr_length && attr_length.to_i,
data_precision: attr_precision && attr_precision.to_i,
data_scale: attr_scale && attr_scale.to_i,
char_used: attr_char_used == nil ? "0" : attr_char_used,
char_length: attr_char_used && attr_length && attr_length.to_i,
type_owner: attr_type_owner,
type_name: attr_type_owner && attr_type_name,
type_subname: attr_type_package,
sql_type_name: attr_type_owner && build_sql_type_name(attr_type_owner, attr_type_package, attr_type_name),
defaulted: argument_metadata[:defaulted]
}
if fields[attr_name.downcase.to_sym][:data_type] == "TABLE" && fields[attr_name.downcase.to_sym][:type_subname] != nil
fields[attr_name.downcase.to_sym][:fields] = get_field_definitions(fields[attr_name.downcase.to_sym])
end
end
when "TABLE", "VIEW"
@schema.select_all(
"SELECT column_id, column_name, data_type, data_length, data_precision, data_scale, char_length, char_used
FROM ALL_TAB_COLS WHERE OWNER = :owner AND TABLE_NAME = :type_name
ORDER BY column_id",
@schema_name, argument_metadata[:type_name]) do |r|
col_no, col_name, col_type_name, col_length, col_precision, col_scale, col_char_length, col_char_used = r
fields[col_name.downcase.to_sym] = {
position: col_no.to_i,
data_type: col_type_name,
in_out: argument_metadata[:in_out],
data_length: col_length && col_length.to_i,
data_precision: col_precision && col_precision.to_i,
data_scale: col_scale && col_scale.to_i,
char_used: col_char_used == nil ? "0" : col_char_used,
char_length: col_char_length && col_char_length.to_i,
type_owner: nil,
type_name: nil,
type_subname: nil,
sql_type_name: nil,
defaulted: argument_metadata[:defaulted]
}
end
end
fields
end
def get_element_definition(argument_metadata) #:nodoc:
element_metadata = {}
if collection_type?(argument_metadata[:data_type])
case argument_metadata[:type_object_type]
when "PACKAGE"
r = @schema.select_first(
"SELECT elem_type_owner, elem_type_name, elem_type_package, length, precision, scale, char_used, index_by
FROM ALL_PLSQL_COLL_TYPES t
WHERE t.OWNER = :owner AND t.TYPE_NAME = :type_name AND t.PACKAGE_NAME = :package_name",
@schema_name, argument_metadata[:type_name], argument_metadata[:type_subname])
elem_type_owner, elem_type_name, elem_type_package, elem_length, elem_precision, elem_scale, elem_char_used, index_by = r
if index_by == "VARCHAR2"
raise ArgumentError, "Index-by Varchar-Table (associative array) #{argument_metadata[:type_name]} is not supported"
end
element_metadata = {
position: 1,
data_type: if elem_type_owner == nil
elem_type_name
else
elem_type_package != nil ? "PL/SQL RECORD" : "OBJECT"
end,
in_out: argument_metadata[:in_out],
data_length: elem_length && elem_length.to_i,
data_precision: elem_precision && elem_precision.to_i,
data_scale: elem_scale && elem_scale.to_i,
char_used: elem_char_used,
char_length: elem_char_used && elem_length && elem_length.to_i,
type_owner: elem_type_owner,
type_name: elem_type_name,
type_subname: elem_type_package,
sql_type_name: elem_type_owner && build_sql_type_name(elem_type_owner, elem_type_package, elem_type_name),
type_object_type: elem_type_package != nil ? "PACKAGE" : nil,
defaulted: argument_metadata[:defaulted]
}
if elem_type_package != nil
element_metadata[:fields] = get_field_definitions(element_metadata)
end
when "TYPE"
r = @schema.select_first(
"SELECT elem_type_owner, elem_type_name, length, precision, scale, char_used
FROM ALL_COLL_TYPES t
WHERE t.owner = :owner AND t.TYPE_NAME = :type_name",
@schema_name, argument_metadata[:type_name]
)
elem_type_owner, elem_type_name, elem_length, elem_precision, elem_scale, elem_char_used = r
element_metadata = {
position: 1,
data_type: elem_type_owner == nil ? elem_type_name : "OBJECT",
in_out: argument_metadata[:in_out],
data_length: elem_length && elem_length.to_i,
data_precision: elem_precision && elem_precision.to_i,
data_scale: elem_scale && elem_scale.to_i,
char_used: elem_char_used,
char_length: elem_char_used && elem_length && elem_length.to_i,
type_owner: elem_type_owner,
type_name: elem_type_name,
type_subname: nil,
sql_type_name: elem_type_owner && build_sql_type_name(elem_type_owner, nil, elem_type_name),
defaulted: argument_metadata[:defaulted]
}
end
else
element_metadata = {
position: 1,
data_type: "PL/SQL RECORD",
in_out: argument_metadata[:in_out],
data_length: nil,
data_precision: nil,
data_scale: nil,
char_used: "B",
char_length: 0,
type_owner: argument_metadata[:type_owner],
type_name: argument_metadata[:type_name],
type_subname: argument_metadata[:type_subname],
sql_type_name: build_sql_type_name(argument_metadata[:type_owner], argument_metadata[:type_subname], argument_metadata[:type_name]),
defaulted: argument_metadata[:defaulted]
}
if element_metadata[:type_subname] != nil
element_metadata[:fields] = get_field_definitions(element_metadata)
end
end
element_metadata
end
def get_composite_type(type_owner, type_name, type_package)
r = @schema.select_first("SELECT typecode FROM all_plsql_types WHERE owner = :owner AND type_name = :type_name AND package_name = :type_package
UNION ALL
SELECT typecode FROM all_types WHERE owner = :owner AND type_name = :type_name",
type_owner, type_name, type_package, type_owner, type_name)
typecode = r[0]
raise ArgumentError, "#{type_name} type #{build_sql_type_name(type_owner, type_package, type_name)} definition inside package is not supported as part of other type definition," <<
" use CREATE TYPE outside package" if typecode == "COLLECTION"
typecode
end
PLSQL_COMPOSITE_TYPES = ["PL/SQL RECORD", "PL/SQL TABLE", "TABLE", "VARRAY", "REF CURSOR"].freeze
def composite_type?(data_type) #:nodoc:
PLSQL_COMPOSITE_TYPES.include? data_type
end
PLSQL_COLLECTION_TYPES = ["PL/SQL TABLE", "TABLE", "VARRAY"].freeze
def collection_type?(data_type) #:nodoc:
PLSQL_COLLECTION_TYPES.include? data_type
end
def overloaded? #:nodoc:
@overloaded
end
end
class Procedure #:nodoc:
extend ProcedureClassMethods
include ProcedureCommon
attr_reader :arguments, :argument_list, :out_list, :return
attr_reader :schema, :schema_name, :package, :procedure
def initialize(schema, procedure, package, override_schema_name, object_id)
@schema = schema
@schema_name = override_schema_name || schema.schema_name
@procedure = procedure.to_s.upcase
@package = package
@object_id = object_id
get_argument_metadata
end
def exec(*args, &block)
call = ProcedureCall.new(self, args)
call.exec(&block)
end
end
end
| ruby | MIT | 7bee9ba2b3207de7c1ae4112d8af2636b586c610 | 2026-01-04T17:45:33.227772Z | false |
isaacseymour/activejob-retry | https://github.com/isaacseymour/activejob-retry/blob/06045dd843e51bb8f0d91058f9f9874f033f3407/spec/retry_spec.rb | spec/retry_spec.rb | # frozen_string_literal: true
require 'spec_helper'
RSpec.describe ActiveJob::Retry do
let(:strategy) { :constant }
let(:options) { {} }
let(:retry_instance) { described_class.new(strategy: strategy, **options) }
let(:job) do
Class.new(ActiveJob::Base) do
def perform(*_args)
raise RuntimeError
end
end.send(:include, retry_instance)
end
describe 'constant strategy' do
let(:strategy) { :constant }
let(:options) { { limit: 10, delay: 5 } }
it 'sets a ConstantBackoffStrategy' do
expect(job.backoff_strategy).to be_a(ActiveJob::Retry::ConstantBackoffStrategy)
end
it 'does not pollute the class' do
klass = Class.new(ActiveJob::Base)
instance_methods = klass.instance_methods.dup
methods = klass.methods.dup
klass.send(:include, retry_instance)
expect(klass.instance_methods).
to match_array(instance_methods << :internal_retry << :retry_attempt)
expect(klass.methods).
to match_array(methods << :backoff_strategy << :retry_callback)
end
context 'invalid options' do
let(:options) { { limit: -2 } }
specify do
expect { retry_instance }.
to raise_error(ActiveJob::Retry::InvalidConfigurationError)
end
end
context 'subclassing' do
let(:subclass) { Class.new(job) }
it 'has the ConstantBackoffStrategy' do
expect(subclass.backoff_strategy).
to be_a(ActiveJob::Retry::ConstantBackoffStrategy)
end
end
end
describe 'variable strategy' do
let(:strategy) { :variable }
let(:options) { { delays: [0, 5, 10, 60, 200] } }
it 'sets a VariableBackoffStrategy' do
expect(job.backoff_strategy).to be_a(ActiveJob::Retry::VariableBackoffStrategy)
end
context 'invalid options' do
let(:options) { {} }
specify do
expect { retry_instance }.
to raise_error(ActiveJob::Retry::InvalidConfigurationError)
end
end
context 'subclassing' do
let(:subclass) { Class.new(job) }
it 'has the VariableBackoffStrategy' do
expect(subclass.backoff_strategy).
to be_a(ActiveJob::Retry::VariableBackoffStrategy)
end
it 'allows overriding' do
subclass.send(:include, described_class.new(strategy: :constant))
expect(subclass.backoff_strategy).
to be_a(ActiveJob::Retry::ConstantBackoffStrategy)
end
end
end
describe 'exponential strategy' do
let(:strategy) { :exponential }
let(:options) { { limit: 10 } }
it 'sets an ExponentialBackoffStrategy' do
expect(job.backoff_strategy).to be_a(ActiveJob::Retry::ExponentialBackoffStrategy)
end
context 'invalid limit' do
let(:options) { { limit: -2 } }
specify do
expect { retry_instance }.
to raise_error(ActiveJob::Retry::InvalidConfigurationError)
end
end
context 'invalid option included' do
let(:options) { { limit: 2, delay: 3 } }
specify do
expect { retry_instance }.
to raise_error(ActiveJob::Retry::InvalidConfigurationError)
end
end
context 'subclassing' do
let(:subclass) { Class.new(job) }
it 'has the ExponentialBackoffStrategy' do
expect(subclass.backoff_strategy).
to be_a(ActiveJob::Retry::ExponentialBackoffStrategy)
end
end
end
describe 'custom strategy' do
module CustomBackoffStrategy
def self.should_retry?(_attempt, _exception)
true
end
def self.retry_delay(_attempt, _exception)
5
end
end
it 'rejects invalid backoff strategies' do
expect { described_class.new(strategy: Object.new) }.
to raise_error(ActiveJob::Retry::InvalidConfigurationError)
end
let(:strategy) { CustomBackoffStrategy }
it 'sets the backoff_strategy when it is valid' do
expect(job.backoff_strategy).to eq(CustomBackoffStrategy)
end
context 'subclassing' do
let(:subclass) { Class.new(job) }
it 'has the CustomBackoffStrategy' do
expect(subclass.backoff_strategy).to eq(strategy)
end
end
end
describe '#serialize' do
let(:instance) { job.new }
subject { instance.serialize }
context 'first instantiated' do
it { is_expected.to include('retry_attempt' => 1) }
end
context '1st attempt' do
before { instance.instance_variable_set(:@retry_attempt, 1) }
it { is_expected.to include('retry_attempt' => 1) }
end
context '7th attempt' do
before { instance.instance_variable_set(:@retry_attempt, 7) }
it { is_expected.to include('retry_attempt' => 7) }
end
context 'when inherited' do
let(:subclass) { Class.new(job) }
let(:instance) { subclass.new }
subject { instance.serialize }
context 'first instantiated' do
it { is_expected.to include('retry_attempt' => 1) }
end
context '1st attempt' do
before { instance.instance_variable_set(:@retry_attempt, 1) }
it { is_expected.to include('retry_attempt' => 1) }
end
context '7th attempt' do
before { instance.instance_variable_set(:@retry_attempt, 7) }
it { is_expected.to include('retry_attempt' => 7) }
end
end
end
describe '#deserialize' do
subject(:instance) { job.new }
before { instance.deserialize(job_data) }
before { instance.send(:deserialize_arguments_if_needed) }
context '1st attempt' do
let(:job_data) do
{
'job_class' => 'SomeJob',
'job_id' => 'uuid',
'arguments' => ['arg1', { 'arg' => 2 }],
'retry_attempt' => 1
}
end
its(:job_id) { is_expected.to eq('uuid') }
its(:arguments) { is_expected.to eq(['arg1', { 'arg' => 2 }]) }
its(:retry_attempt) { is_expected.to eq(1) }
end
context '7th attempt' do
let(:job_data) do
{
'job_class' => 'SomeJob',
'job_id' => 'uuid',
'arguments' => ['arg1', { 'arg' => 2 }],
'retry_attempt' => 7
}
end
its(:job_id) { is_expected.to eq('uuid') }
its(:arguments) { is_expected.to eq(['arg1', { 'arg' => 2 }]) }
its(:retry_attempt) { is_expected.to eq(7) }
end
context 'when subclassing' do
let(:subclass) { Class.new(job) }
subject(:instance) { subclass.new }
before { instance.deserialize(job_data) }
before { instance.send(:deserialize_arguments_if_needed) }
context '1st attempt' do
let(:job_data) do
{
'job_class' => 'SomeJob',
'job_id' => 'uuid',
'arguments' => ['arg1', { 'arg' => 2 }],
'retry_attempt' => 1
}
end
its(:job_id) { is_expected.to eq('uuid') }
its(:arguments) { is_expected.to eq(['arg1', { 'arg' => 2 }]) }
its(:retry_attempt) { is_expected.to eq(1) }
end
context '7th attempt' do
let(:job_data) do
{
'job_class' => 'SomeJob',
'job_id' => 'uuid',
'arguments' => ['arg1', { 'arg' => 2 }],
'retry_attempt' => 7
}
end
its(:job_id) { is_expected.to eq('uuid') }
its(:arguments) { is_expected.to eq(['arg1', { 'arg' => 2 }]) }
its(:retry_attempt) { is_expected.to eq(7) }
end
end
end
describe '#rescue_with_handler' do
let(:mod) { described_class.new(strategy: :constant, limit: 100) }
let(:instance) { job.new }
subject(:perform) { instance.perform_now }
context 'when the job should be retried' do
before do
expect(job.backoff_strategy).to receive(:should_retry?).
with(1, instance_of(RuntimeError)).
and_return(true)
expect(job.backoff_strategy).to receive(:retry_delay).
with(1, instance_of(RuntimeError)).
and_return(5)
end
it 'retries the job with the defined delay' do
expect(instance).to receive(:retry_job).with(hash_including(wait: 5))
perform
end
it 'increases the retry_attempt count' do
perform
expect(instance.retry_attempt).to eq(2)
end
pending 'logs the retry' do
expect(ActiveJob::Base.logger).to receive(:log).
with(Logger::INFO, 'Retrying (attempt 1, waiting 0s)')
perform
end
end
context 'when the job should not be retried' do
before do
expect(job.backoff_strategy).to receive(:should_retry?).
with(1, instance_of(RuntimeError)).
and_return(false)
end
it 'does not retry the job' do
expect(instance).to_not receive(:retry_job)
expect { perform }.to raise_error(RuntimeError)
end
end
end
describe 'retry callback' do
let(:retry_instance) do
described_class.new(strategy: :constant, callback: callback, **options)
end
let(:callback_double) { double(call: nil) }
let(:callback) { callback_double.method(:call).to_proc }
let(:instance) { job.new }
subject(:perform) { instance.perform_now }
context 'invalid options' do
let(:callback) { 'not a proc' }
specify do
expect { retry_instance }.
to raise_error(ActiveJob::Retry::InvalidConfigurationError)
end
end
context 'when the job should be retried' do
before do
expect(job.backoff_strategy).to receive(:should_retry?).
with(1, instance_of(RuntimeError)).
and_return(true)
end
it 'executes callback proc on retry' do
expect(callback_double).to receive(:call)
perform
end
context 'with callback returning :halt' do
let(:callback) { proc { :halt } }
it 'it does not retry the job' do
expect(instance).not_to receive(:retry_job)
perform
end
end
context 'with callback not returning :halt' do
let(:callback) { proc { 'not halt' } }
it 'it retries the job' do
expect(instance).to receive(:retry_job)
perform
end
end
end
end
end
| ruby | MIT | 06045dd843e51bb8f0d91058f9f9874f033f3407 | 2026-01-04T17:45:33.653067Z | false |
isaacseymour/activejob-retry | https://github.com/isaacseymour/activejob-retry/blob/06045dd843e51bb8f0d91058f9f9874f033f3407/spec/spec_helper.rb | spec/spec_helper.rb | # frozen_string_literal: true
require 'active_job/retry'
require 'rspec/its'
ActiveJob::Base.queue_adapter = :test
RSpec.configure do |config|
config.expect_with :rspec do |expectations|
expectations.include_chain_clauses_in_custom_matcher_descriptions = true
end
config.mock_with :rspec do |mocks|
mocks.verify_partial_doubles = true
end
config.disable_monkey_patching!
config.warnings = true
# config.profile_examples = 10
config.order = :random
Kernel.srand config.seed
end
| ruby | MIT | 06045dd843e51bb8f0d91058f9f9874f033f3407 | 2026-01-04T17:45:33.653067Z | false |
isaacseymour/activejob-retry | https://github.com/isaacseymour/activejob-retry/blob/06045dd843e51bb8f0d91058f9f9874f033f3407/spec/retry/exponential_options_validator_spec.rb | spec/retry/exponential_options_validator_spec.rb | # frozen_string_literal: true
require 'spec_helper'
RSpec.describe ActiveJob::Retry::ExponentialOptionsValidator do
let(:validator) { described_class.new(options) }
subject(:validate!) { -> { validator.validate! } }
context 'valid options' do
context 'unlimited retries' do
let(:options) { { limit: nil, unlimited_retries: true } }
it { is_expected.to_not raise_error }
end
context 'no retries' do
let(:options) { { limit: 0 } }
it { is_expected.to_not raise_error }
end
context 'some retries' do
let(:options) { { limit: 3 } }
it { is_expected.to_not raise_error }
end
context 'fatal_exceptions' do
let(:options) { { fatal_exceptions: [RuntimeError] } }
it { is_expected.to_not raise_error }
end
context 'retryable_exceptions' do
let(:options) { { retryable_exceptions: [StandardError, NoMethodError] } }
it { is_expected.to_not raise_error }
end
context 'multiple options' do
let(:options) { { limit: 3, retryable_exceptions: [RuntimeError] } }
it { is_expected.to_not raise_error }
end
end
context 'invalid options' do
context 'bad limit' do
let(:options) { { limit: -1 } }
it { is_expected.to raise_error(ActiveJob::Retry::InvalidConfigurationError) }
end
context 'accidental infinite limit' do
let(:options) { { limit: nil } }
it { is_expected.to raise_error(ActiveJob::Retry::InvalidConfigurationError) }
end
context 'accidental finite limit' do
let(:options) { { unlimited_retries: true } }
it { is_expected.to raise_error(ActiveJob::Retry::InvalidConfigurationError) }
end
context 'delay provided' do
let(:options) { { delay: 1 } }
it { is_expected.to raise_error(ActiveJob::Retry::InvalidConfigurationError) }
end
context 'bad fatal_exceptions' do
let(:options) { { fatal_exceptions: ['StandardError'] } }
it { is_expected.to raise_error(ActiveJob::Retry::InvalidConfigurationError) }
end
context 'bad retryable_exceptions' do
let(:options) { { retryable_exceptions: [:runtime] } }
it { is_expected.to raise_error(ActiveJob::Retry::InvalidConfigurationError) }
end
context 'retry and fatal exceptions together' do
let(:options) { { fatal_exceptions: [StandardError], retryable_exceptions: [] } }
it { is_expected.to raise_error(ActiveJob::Retry::InvalidConfigurationError) }
end
end
end
| ruby | MIT | 06045dd843e51bb8f0d91058f9f9874f033f3407 | 2026-01-04T17:45:33.653067Z | false |
isaacseymour/activejob-retry | https://github.com/isaacseymour/activejob-retry/blob/06045dd843e51bb8f0d91058f9f9874f033f3407/spec/retry/constant_options_validator_spec.rb | spec/retry/constant_options_validator_spec.rb | # frozen_string_literal: true
require 'spec_helper'
RSpec.describe ActiveJob::Retry::ConstantOptionsValidator do
let(:validator) { described_class.new(options) }
subject(:validate!) { -> { validator.validate! } }
context 'valid options' do
context 'unlimited retries' do
let(:options) { { limit: nil, unlimited_retries: true } }
it { is_expected.to_not raise_error }
end
context 'no retries' do
let(:options) { { limit: 0 } }
it { is_expected.to_not raise_error }
end
context 'some retries' do
let(:options) { { limit: 3 } }
it { is_expected.to_not raise_error }
end
context 'zero delay' do
let(:options) { { delay: 0 } }
it { is_expected.to_not raise_error }
end
context 'fatal_exceptions' do
let(:options) { { fatal_exceptions: [RuntimeError] } }
it { is_expected.to_not raise_error }
end
context 'retryable_exceptions' do
let(:options) { { retryable_exceptions: [StandardError, NoMethodError] } }
it { is_expected.to_not raise_error }
end
context 'multiple options' do
let(:options) { { limit: 3, delay: 10, retryable_exceptions: [RuntimeError] } }
it { is_expected.to_not raise_error }
end
end
context 'invalid options' do
context 'bad limit' do
let(:options) { { limit: -1 } }
it { is_expected.to raise_error(ActiveJob::Retry::InvalidConfigurationError) }
end
context 'accidental infinite limit' do
let(:options) { { limit: nil } }
it { is_expected.to raise_error(ActiveJob::Retry::InvalidConfigurationError) }
end
context 'accidental finite limit' do
let(:options) { { unlimited_retries: true } }
it { is_expected.to raise_error(ActiveJob::Retry::InvalidConfigurationError) }
end
context 'bad delay' do
let(:options) { { delay: -1 } }
it { is_expected.to raise_error(ActiveJob::Retry::InvalidConfigurationError) }
end
context 'bad fatal_exceptions' do
let(:options) { { fatal_exceptions: ['StandardError'] } }
it { is_expected.to raise_error(ActiveJob::Retry::InvalidConfigurationError) }
end
context 'bad retryable_exceptions' do
let(:options) { { retryable_exceptions: [:runtime] } }
it { is_expected.to raise_error(ActiveJob::Retry::InvalidConfigurationError) }
end
context 'retry and fatal exceptions together' do
let(:options) { { fatal_exceptions: [StandardError], retryable_exceptions: [] } }
it { is_expected.to raise_error(ActiveJob::Retry::InvalidConfigurationError) }
end
end
end
| ruby | MIT | 06045dd843e51bb8f0d91058f9f9874f033f3407 | 2026-01-04T17:45:33.653067Z | false |
isaacseymour/activejob-retry | https://github.com/isaacseymour/activejob-retry/blob/06045dd843e51bb8f0d91058f9f9874f033f3407/spec/retry/constant_backoff_strategy_spec.rb | spec/retry/constant_backoff_strategy_spec.rb | # frozen_string_literal: true
require 'spec_helper'
RSpec.describe ActiveJob::Retry::ConstantBackoffStrategy do
let(:strategy) { described_class.new(options) }
describe '#should_retry?' do
subject { strategy.should_retry?(attempt, exception) }
let(:attempt) { 1 }
let(:exception) { RuntimeError.new }
context 'when the limit is infinite' do
let(:options) { { limit: nil, unlimited_retries: true } }
context '1st attempt' do
let(:attempt) { 1 }
it { is_expected.to be(true) }
end
context '99999th attempt' do
let(:attempt) { 99_999 }
it { is_expected.to be(true) }
end
end
context 'when the limit is 0' do
let(:options) { { limit: 0 } }
context '1st attempt' do
let(:attempt) { 1 }
it { is_expected.to be(false) }
end
context '99999th attempt' do
let(:attempt) { 99_999 }
it { is_expected.to be(false) }
end
end
context 'when the limit is 5' do
let(:options) { { limit: 5 } }
context '1st attempt' do
let(:attempt) { 1 }
it { is_expected.to be(true) }
end
context '4th attempt' do
let(:attempt) { 4 }
it { is_expected.to be(true) }
end
context '5th attempt' do
let(:attempt) { 5 }
it { is_expected.to be(false) }
end
end
context 'defaults (retry everything)' do
let(:options) { { limit: 10 } }
context 'Exception' do
let(:exception) { Exception.new }
it { is_expected.to be(true) }
end
context 'RuntimeError' do
let(:exception) { RuntimeError.new }
it { is_expected.to be(true) }
end
context 'subclass of RuntimeError' do
let(:exception) { Class.new(RuntimeError).new }
it { is_expected.to be(true) }
end
end
context 'with whitelist' do
let(:options) { { limit: 10, retryable_exceptions: [RuntimeError] } }
context 'Exception' do
let(:exception) { Exception.new }
it { is_expected.to be(false) }
end
context 'RuntimeError' do
let(:exception) { RuntimeError.new }
it { is_expected.to be(true) }
end
context 'subclass of RuntimeError' do
let(:exception) { Class.new(RuntimeError).new }
it { is_expected.to be(true) }
end
end
context 'with blacklist' do
let(:options) { { limit: 10, fatal_exceptions: [RuntimeError] } }
context 'Exception' do
let(:exception) { Exception.new }
it { is_expected.to be(true) }
end
context 'RuntimeError' do
let(:exception) { RuntimeError.new }
it { is_expected.to be(false) }
end
context 'subclass of RuntimeError' do
let(:exception) { Class.new(RuntimeError).new }
it { is_expected.to be(false) }
end
end
end
end
| ruby | MIT | 06045dd843e51bb8f0d91058f9f9874f033f3407 | 2026-01-04T17:45:33.653067Z | false |
isaacseymour/activejob-retry | https://github.com/isaacseymour/activejob-retry/blob/06045dd843e51bb8f0d91058f9f9874f033f3407/spec/retry/variable_backoff_strategy_spec.rb | spec/retry/variable_backoff_strategy_spec.rb | # frozen_string_literal: true
require 'spec_helper'
RSpec.describe ActiveJob::Retry::VariableBackoffStrategy do
let(:backoff_strategy) { described_class.new(options) }
describe '#should_retry?' do
subject { backoff_strategy.should_retry?(attempt, exception) }
let(:attempt) { 1 }
let(:exception) { RuntimeError.new }
context 'when the strategy is empty' do
let(:options) { { delays: [] } }
context '1st attempt' do
let(:attempt) { 1 }
it { is_expected.to be(false) }
end
context '99999th attempt' do
let(:attempt) { 99_999 }
it { is_expected.to be(false) }
end
end
context 'when the strategy has 4 delays' do
let(:options) { { delays: [0, 3, 5, 10] } }
context '1st attempt' do
let(:attempt) { 1 }
it { is_expected.to be(true) }
end
context '4th attempt' do
let(:attempt) { 4 }
it { is_expected.to be(true) }
end
context '5th attempt' do
let(:attempt) { 5 }
it { is_expected.to be(false) }
end
end
context 'defaults (retry everything)' do
let(:options) { { delays: [0, 3, 5, 10, 60] } }
context 'Exception' do
let(:exception) { Exception.new }
it { is_expected.to be(true) }
end
context 'RuntimeError' do
let(:exception) { RuntimeError.new }
it { is_expected.to be(true) }
end
context 'subclass of RuntimeError' do
let(:exception) { Class.new(RuntimeError).new }
it { is_expected.to be(true) }
end
end
context 'with whitelist' do
let(:options) { { delays: [10], retryable_exceptions: [RuntimeError] } }
context 'Exception' do
let(:exception) { Exception.new }
it { is_expected.to be(false) }
end
context 'RuntimeError' do
let(:exception) { RuntimeError.new }
it { is_expected.to be(true) }
end
context 'subclass of RuntimeError' do
let(:exception) { Class.new(RuntimeError).new }
it { is_expected.to be(true) }
end
end
context 'with blacklist' do
let(:options) { { delays: [10], fatal_exceptions: [RuntimeError] } }
context 'Exception' do
let(:exception) { Exception.new }
it { is_expected.to be(true) }
end
context 'RuntimeError' do
let(:exception) { RuntimeError.new }
it { is_expected.to be(false) }
end
context 'subclass of RuntimeError' do
let(:exception) { Class.new(RuntimeError).new }
it { is_expected.to be(false) }
end
end
end
describe '#retry_delay' do
subject { backoff_strategy.retry_delay(attempt, exception) }
let(:attempt) { 1 }
let(:exception) { RuntimeError.new }
context 'when the strategy has 4 delays' do
let(:options) { { delays: [0, 3, 5, 10] } }
context '1st attempt' do
let(:attempt) { 1 }
it { is_expected.to eq(0) }
end
context '4th attempt' do
let(:attempt) { 4 }
it { is_expected.to eq(10) }
end
end
end
end
| ruby | MIT | 06045dd843e51bb8f0d91058f9f9874f033f3407 | 2026-01-04T17:45:33.653067Z | false |
isaacseymour/activejob-retry | https://github.com/isaacseymour/activejob-retry/blob/06045dd843e51bb8f0d91058f9f9874f033f3407/spec/retry/variable_options_validator_spec.rb | spec/retry/variable_options_validator_spec.rb | # frozen_string_literal: true
require 'spec_helper'
RSpec.describe ActiveJob::Retry::VariableOptionsValidator do
let(:validator) { described_class.new(options) }
subject(:validate!) { -> { validator.validate! } }
context 'valid options' do
context 'empty delays' do
let(:options) { { delays: [] } }
it { is_expected.to_not raise_error }
end
context 'with delays' do
let(:options) { { delays: [0, 3, 6, 10_000] } }
it { is_expected.to_not raise_error }
end
context 'min and max delay multipliers' do
let(:options) do
{ delays: [0, 10, 60], min_delay_multiplier: 0.8, max_delay_multiplier: 1.2 }
end
it { is_expected.to_not raise_error }
end
context 'fatal exceptions' do
let(:options) { { delays: [0, 10, 60], fatal_exceptions: [RuntimeError] } }
it { is_expected.to_not raise_error }
end
context 'retryable_exceptions' do
let(:options) do
{ delays: [], retryable_exceptions: [StandardError, NoMethodError] }
end
it { is_expected.to_not raise_error }
end
context 'multiple options' do
let(:options) { { delays: [0, 10, 60], retryable_exceptions: [RuntimeError] } }
it { is_expected.to_not raise_error }
end
end
context 'invalid options' do
context 'without delays' do
let(:options) { {} }
it { is_expected.to raise_error(ActiveJob::Retry::InvalidConfigurationError) }
end
context 'with limit' do
let(:options) { { limit: 5 } }
it { is_expected.to raise_error(ActiveJob::Retry::InvalidConfigurationError) }
end
context 'with delay' do
let(:options) { { delay: 5 } }
it { is_expected.to raise_error(ActiveJob::Retry::InvalidConfigurationError) }
end
context 'min delay multiplier only' do
let(:options) { { min_delay_multiplier: 0.8 } }
it { is_expected.to raise_error(ActiveJob::Retry::InvalidConfigurationError) }
end
context 'max delay multiplier only' do
let(:options) { { max_delay_multiplier: 0.8 } }
it { is_expected.to raise_error(ActiveJob::Retry::InvalidConfigurationError) }
end
context 'bad fatal exceptions' do
let(:options) { { fatal_exceptions: ['StandardError'] } }
it { is_expected.to raise_error(ActiveJob::Retry::InvalidConfigurationError) }
end
context 'bad retryable_exceptions' do
let(:options) { { retryable_exceptions: [:runtime] } }
it { is_expected.to raise_error(ActiveJob::Retry::InvalidConfigurationError) }
end
context 'retry and fatal exceptions together' do
let(:options) { { fatal_exceptions: [StandardError], retryable_exceptions: [] } }
it { is_expected.to raise_error(ActiveJob::Retry::InvalidConfigurationError) }
end
end
end
| ruby | MIT | 06045dd843e51bb8f0d91058f9f9874f033f3407 | 2026-01-04T17:45:33.653067Z | false |
isaacseymour/activejob-retry | https://github.com/isaacseymour/activejob-retry/blob/06045dd843e51bb8f0d91058f9f9874f033f3407/spec/retry/exponential_backoff_strategy_spec.rb | spec/retry/exponential_backoff_strategy_spec.rb | # frozen_string_literal: true
require 'spec_helper'
RSpec.describe ActiveJob::Retry::ExponentialBackoffStrategy do
let(:strategy) { described_class.new(options) }
describe '#should_retry?' do
subject { strategy.should_retry?(attempt, exception) }
let(:attempt) { 1 }
let(:exception) { RuntimeError.new }
context 'when the limit is infinite' do
let(:options) { { limit: nil, unlimited_retries: true } }
context '1st attempt' do
let(:attempt) { 1 }
it { is_expected.to be(true) }
end
context '99999th attempt' do
let(:attempt) { 99_999 }
it { is_expected.to be(true) }
end
end
context 'when the limit is 0' do
let(:options) { { limit: 0 } }
context '1st attempt' do
let(:attempt) { 1 }
it { is_expected.to be(false) }
end
context '99999th attempt' do
let(:attempt) { 99_999 }
it { is_expected.to be(false) }
end
end
context 'when the limit is 5' do
let(:options) { { limit: 5 } }
context '1st attempt' do
let(:attempt) { 1 }
it { is_expected.to be(true) }
end
context '4th attempt' do
let(:attempt) { 4 }
it { is_expected.to be(true) }
end
context '5th attempt' do
let(:attempt) { 5 }
it { is_expected.to be(false) }
end
end
context 'defaults (retry everything)' do
let(:options) { { limit: 10 } }
context 'Exception' do
let(:exception) { Exception.new }
it { is_expected.to be(true) }
end
context 'RuntimeError' do
let(:exception) { RuntimeError.new }
it { is_expected.to be(true) }
end
context 'subclass of RuntimeError' do
let(:exception) { Class.new(RuntimeError).new }
it { is_expected.to be(true) }
end
end
context 'with whitelist' do
let(:options) { { limit: 10, retryable_exceptions: [RuntimeError] } }
context 'Exception' do
let(:exception) { Exception.new }
it { is_expected.to be(false) }
end
context 'RuntimeError' do
let(:exception) { RuntimeError.new }
it { is_expected.to be(true) }
end
context 'subclass of RuntimeError' do
let(:exception) { Class.new(RuntimeError).new }
it { is_expected.to be(true) }
end
end
context 'with blacklist' do
let(:options) { { limit: 10, fatal_exceptions: [RuntimeError] } }
context 'Exception' do
let(:exception) { Exception.new }
it { is_expected.to be(true) }
end
context 'RuntimeError' do
let(:exception) { RuntimeError.new }
it { is_expected.to be(false) }
end
context 'subclass of RuntimeError' do
let(:exception) { Class.new(RuntimeError).new }
it { is_expected.to be(false) }
end
end
end
describe '#retry_delay' do
subject { strategy.retry_delay(attempt, exception) }
let(:exception) { RuntimeError.new }
context 'limited retries' do
let(:options) { { limit: 5 } }
let(:attempt) { 1 }
let(:attempt_3_delay) { strategy.retry_delay(attempt_3, exception) }
let(:attempt_5_delay) { strategy.retry_delay(attempt_5, exception) }
let(:attempt_3) { 3 }
let(:attempt_5) { 5 }
it 'returns value greater than previous for each of the following attempts' do
expect(subject).to be < attempt_3_delay
expect(attempt_3_delay).to be < attempt_5_delay
end
end
context 'unlimited retries' do
let(:options) { { limit: nil, unlimited_retries: true } }
let(:attempt) { 1000 }
specify { expect { subject }.to_not raise_error }
end
end
end
| ruby | MIT | 06045dd843e51bb8f0d91058f9f9874f033f3407 | 2026-01-04T17:45:33.653067Z | false |
isaacseymour/activejob-retry | https://github.com/isaacseymour/activejob-retry/blob/06045dd843e51bb8f0d91058f9f9874f033f3407/lib/activejob/retry.rb | lib/activejob/retry.rb | # frozen_string_literal: true
require 'active_job/retry'
| ruby | MIT | 06045dd843e51bb8f0d91058f9f9874f033f3407 | 2026-01-04T17:45:33.653067Z | false |
isaacseymour/activejob-retry | https://github.com/isaacseymour/activejob-retry/blob/06045dd843e51bb8f0d91058f9f9874f033f3407/lib/active_job/retry.rb | lib/active_job/retry.rb | # frozen_string_literal: true
require 'active_job'
require 'active_support'
require 'active_support/core_ext' # ActiveJob uses core exts, but doesn't require it
require 'active_job/retry/version'
require 'active_job/retry/errors'
require 'active_job/retry/strategy'
unless ActiveJob::Base.method_defined?(:deserialize)
require 'active_job/retry/deserialize_monkey_patch'
end
module ActiveJob
class Retry < Module
PROBLEMATIC_ADAPTERS = [
'ActiveJob::QueueAdapters::InlineAdapter',
'ActiveJob::QueueAdapters::QuAdapter',
'ActiveJob::QueueAdapters::SneakersAdapter',
'ActiveJob::QueueAdapters::SuckerPunchAdapter'
].freeze
#################
# Configuration #
#################
def initialize(strategy: nil, callback: nil, **options)
check_adapter!
@backoff_strategy = Strategy.choose(strategy, options)
@retry_callback = callback
validate_params
end
def included(base)
klass = self
base.define_singleton_method(:inherited) do |subclass|
subclass.send(:include, klass)
end
define_backoff_strategy(base)
define_retry_attempt_tracking(base)
define_retry_method(base)
define_retry_logic(base)
define_retry_callback(base)
end
private
attr_reader :backoff_strategy, :retry_callback
def define_backoff_strategy(klass)
klass.instance_variable_set(:@backoff_strategy, @backoff_strategy)
klass.define_singleton_method(:backoff_strategy) { @backoff_strategy }
end
def define_retry_attempt_tracking(klass)
klass.instance_eval do
define_method(:serialize) do |*args|
super(*args).merge('retry_attempt' => retry_attempt)
end
define_method :deserialize do |job_data|
super(job_data)
@retry_attempt = job_data['retry_attempt']
end
define_method(:retry_attempt) { @retry_attempt ||= 1 }
end
end
def define_retry_method(klass)
klass.instance_eval do
define_method :internal_retry do |exception|
this_delay = self.class.backoff_strategy.retry_delay(retry_attempt, exception)
cb = self.class.retry_callback &&
instance_exec(exception, this_delay, &self.class.retry_callback)
return if cb == :halt
# TODO: This breaks DelayedJob and Resque for some weird ActiveSupport reason.
# logger.info("Retrying (attempt #{retry_attempt + 1}, waiting #{this_delay}s)")
@retry_attempt += 1
retry_job(wait: this_delay)
end
end
end
def define_retry_logic(klass)
klass.instance_eval do
# Override `rescue_with_handler` to make sure our catch is before callbacks,
# so `rescue_from`s will only be run after any retry attempts have been exhausted.
define_method :rescue_with_handler do |exception|
if self.class.backoff_strategy.should_retry?(retry_attempt, exception)
internal_retry(exception)
return true # Exception has been handled
else
return super(exception)
end
end
end
end
def define_retry_callback(klass)
klass.instance_variable_set(:@retry_callback, @retry_callback)
klass.define_singleton_method(:retry_callback) { @retry_callback }
end
def check_adapter!
adapter = ActiveJob::Base.queue_adapter
adapter_name =
case adapter
when Class then adapter.name
else adapter.class.name
end
if PROBLEMATIC_ADAPTERS.include?(adapter_name)
warn("#{adapter_name} does not support delayed retries, so does not work with " \
'ActiveJob::Retry. You may experience strange behaviour.')
end
end
def validate_params
if retry_callback && !retry_callback.is_a?(Proc)
raise InvalidConfigurationError, 'Callback must be a `Proc`'
end
unless backoff_strategy_valid?
raise InvalidConfigurationError,
'Backoff strategies must define `should_retry?(attempt, exception)`, ' \
'and `retry_delay(attempt, exception)`.'
end
end
def backoff_strategy_valid?
backoff_strategy.respond_to?(:should_retry?) &&
backoff_strategy.respond_to?(:retry_delay) &&
backoff_strategy.method(:should_retry?).arity == 2 &&
backoff_strategy.method(:retry_delay).arity == 2
end
end
end
| ruby | MIT | 06045dd843e51bb8f0d91058f9f9874f033f3407 | 2026-01-04T17:45:33.653067Z | false |
isaacseymour/activejob-retry | https://github.com/isaacseymour/activejob-retry/blob/06045dd843e51bb8f0d91058f9f9874f033f3407/lib/active_job/retry/version.rb | lib/active_job/retry/version.rb | # frozen_string_literal: true
module ActiveJob
class Retry < Module
VERSION = '0.6.3'
end
end
| ruby | MIT | 06045dd843e51bb8f0d91058f9f9874f033f3407 | 2026-01-04T17:45:33.653067Z | false |
isaacseymour/activejob-retry | https://github.com/isaacseymour/activejob-retry/blob/06045dd843e51bb8f0d91058f9f9874f033f3407/lib/active_job/retry/errors.rb | lib/active_job/retry/errors.rb | # frozen_string_literal: true
module ActiveJob
class Retry < Module
class InvalidConfigurationError < StandardError; end
class UnsupportedAdapterError < StandardError; end
end
end
| ruby | MIT | 06045dd843e51bb8f0d91058f9f9874f033f3407 | 2026-01-04T17:45:33.653067Z | false |
isaacseymour/activejob-retry | https://github.com/isaacseymour/activejob-retry/blob/06045dd843e51bb8f0d91058f9f9874f033f3407/lib/active_job/retry/strategy.rb | lib/active_job/retry/strategy.rb | # frozen_string_literal: true
require 'active_job/retry/constant_backoff_strategy'
require 'active_job/retry/variable_backoff_strategy'
require 'active_job/retry/exponential_backoff_strategy'
module ActiveJob
class Retry < Module
module Strategy
def self.choose(strategy, options)
case strategy
when :constant then ActiveJob::Retry::ConstantBackoffStrategy.new(options)
when :variable then ActiveJob::Retry::VariableBackoffStrategy.new(options)
when :exponential then ActiveJob::Retry::ExponentialBackoffStrategy.new(options)
else strategy
end
end
end
end
end
| ruby | MIT | 06045dd843e51bb8f0d91058f9f9874f033f3407 | 2026-01-04T17:45:33.653067Z | false |
isaacseymour/activejob-retry | https://github.com/isaacseymour/activejob-retry/blob/06045dd843e51bb8f0d91058f9f9874f033f3407/lib/active_job/retry/variable_backoff_strategy.rb | lib/active_job/retry/variable_backoff_strategy.rb | # frozen_string_literal: true
require 'active_job/retry/constant_backoff_strategy'
require 'active_job/retry/variable_options_validator'
module ActiveJob
class Retry < Module
class VariableBackoffStrategy < ConstantBackoffStrategy
def initialize(options)
super(options)
VariableOptionsValidator.new(options).validate!
@retry_limit = options.fetch(:delays).length + 1
@retry_delays = options.fetch(:delays)
@min_delay_multiplier = options.fetch(:min_delay_multiplier, 1.0)
@max_delay_multiplier = options.fetch(:max_delay_multiplier, 1.0)
end
def retry_delay(attempt, _exception)
(retry_delays[attempt - 1] * delay_multiplier).to_i
end
private
attr_reader :retry_delays, :min_delay_multiplier, :max_delay_multiplier
def random_delay?
min_delay_multiplier != max_delay_multiplier
end
def delay_multiplier
return max_delay_multiplier unless random_delay?
rand(min_delay_multiplier..max_delay_multiplier)
end
end
end
end
| ruby | MIT | 06045dd843e51bb8f0d91058f9f9874f033f3407 | 2026-01-04T17:45:33.653067Z | false |
isaacseymour/activejob-retry | https://github.com/isaacseymour/activejob-retry/blob/06045dd843e51bb8f0d91058f9f9874f033f3407/lib/active_job/retry/constant_backoff_strategy.rb | lib/active_job/retry/constant_backoff_strategy.rb | # frozen_string_literal: true
require 'active_job/retry/constant_options_validator'
module ActiveJob
class Retry < Module
class ConstantBackoffStrategy
def initialize(options)
ConstantOptionsValidator.new(options).validate!
@retry_limit = options.fetch(:limit, 1)
@retry_delay = options.fetch(:delay, 0)
@fatal_exceptions = options.fetch(:fatal_exceptions, [])
@retryable_exceptions = options.fetch(:retryable_exceptions, nil)
end
def should_retry?(attempt, exception)
return false if retry_limit_reached?(attempt)
return false unless retryable_exception?(exception)
true
end
def retry_delay(_attempt, _exception)
@retry_delay
end
private
attr_reader :retry_limit, :fatal_exceptions, :retryable_exceptions
def retry_limit_reached?(attempt)
return false unless retry_limit
attempt >= retry_limit
end
def retryable_exception?(exception)
if retryable_exceptions.nil?
!exception_blacklisted?(exception)
else
exception_whitelisted?(exception)
end
end
def exception_whitelisted?(exception)
retryable_exceptions.any? { |ex| exception.is_a?(ex) }
end
def exception_blacklisted?(exception)
fatal_exceptions.any? { |ex| exception.is_a?(ex) }
end
end
end
end
| ruby | MIT | 06045dd843e51bb8f0d91058f9f9874f033f3407 | 2026-01-04T17:45:33.653067Z | false |
isaacseymour/activejob-retry | https://github.com/isaacseymour/activejob-retry/blob/06045dd843e51bb8f0d91058f9f9874f033f3407/lib/active_job/retry/constant_options_validator.rb | lib/active_job/retry/constant_options_validator.rb | # frozen_string_literal: true
require 'active_job/retry/errors'
module ActiveJob
class Retry < Module
class ConstantOptionsValidator
def initialize(options)
@options = options
end
def validate!
validate_limit_numericality!
validate_infinite_limit!
validate_delay!
validate_not_both_exceptions!
# Fatal exceptions must be an array (cannot be nil, since then all
# exceptions would be fatal - for that just set `limit: 0`)
validate_array_of_exceptions!(:fatal_exceptions)
# Retryable exceptions must be an array of exceptions or `nil` to retry
# any exception
if options[:retryable_exceptions]
validate_array_of_exceptions!(:retryable_exceptions)
end
end
private
attr_reader :options
# Limit must be an integer >= 0, or nil
def validate_limit_numericality!
return unless options[:limit]
return if options[:limit].is_a?(Integer) && options[:limit] >= 0
raise InvalidConfigurationError,
'Limit must be an integer >= 0, or nil for unlimited retries'
end
# If no limit is supplied, you *must* set `unlimited_retries: true` and
# understand that your ops team might hurt you.
def validate_infinite_limit!
limit = options.fetch(:limit, 1)
return unless limit.nil? ^ options[:unlimited_retries] == true
if limit.nil? && options[:unlimited_retries] != true
raise InvalidConfigurationError,
'You must set `unlimited_retries: true` to use `limit: nil`'
else
raise InvalidConfigurationError,
'You must set `limit: nil` to have unlimited retries'
end
end
# Delay must be non-negative
def validate_delay!
return unless options[:delay]
return if options[:delay] >= 0
raise InvalidConfigurationError, 'Delay must be non-negative'
end
def validate_not_both_exceptions!
return unless options[:fatal_exceptions] && options[:retryable_exceptions]
raise InvalidConfigurationError,
'fatal_exceptions and retryable_exceptions cannot be used together'
end
def validate_array_of_exceptions!(key)
return unless options[key]
if options[key].is_a?(Array) &&
options[key].all? { |ex| ex.is_a?(Class) && ex <= Exception }
return
end
raise InvalidConfigurationError, "#{key} must be an array of exceptions!"
end
end
end
end
| ruby | MIT | 06045dd843e51bb8f0d91058f9f9874f033f3407 | 2026-01-04T17:45:33.653067Z | false |
isaacseymour/activejob-retry | https://github.com/isaacseymour/activejob-retry/blob/06045dd843e51bb8f0d91058f9f9874f033f3407/lib/active_job/retry/variable_options_validator.rb | lib/active_job/retry/variable_options_validator.rb | # frozen_string_literal: true
require 'active_job/retry/errors'
module ActiveJob
class Retry < Module
class VariableOptionsValidator
DELAY_MULTIPLIER_KEYS = %i[min_delay_multiplier max_delay_multiplier].freeze
def initialize(options)
@options = options
end
def validate!
validate_banned_basic_option!(:limit)
validate_banned_basic_option!(:delay)
validate_delays!
validate_delay_multipliers!
end
private
attr_reader :options, :retry_limit
def validate_banned_basic_option!(key)
return unless options[key]
raise InvalidConfigurationError, "Cannot use #{key} with VariableBackoffStrategy"
end
def validate_delays!
return if options[:delays]
raise InvalidConfigurationError,
'You must define an array of delays between attempts'
end
def validate_delay_multipliers!
validate_delay_multipliers_supplied_together!
return unless options[:min_delay_multiplier] && options[:max_delay_multiplier]
return if options[:min_delay_multiplier] <= options[:max_delay_multiplier]
raise InvalidConfigurationError,
'min_delay_multiplier must be less than or equal to max_delay_multiplier'
end
def validate_delay_multipliers_supplied_together!
supplied = DELAY_MULTIPLIER_KEYS.map { |key| options.key?(key) }
return if supplied.none? || supplied.all?
raise InvalidConfigurationError,
'If one of min/max_delay_multiplier is supplied, both are required'
end
end
end
end
| ruby | MIT | 06045dd843e51bb8f0d91058f9f9874f033f3407 | 2026-01-04T17:45:33.653067Z | false |
isaacseymour/activejob-retry | https://github.com/isaacseymour/activejob-retry/blob/06045dd843e51bb8f0d91058f9f9874f033f3407/lib/active_job/retry/exponential_backoff_strategy.rb | lib/active_job/retry/exponential_backoff_strategy.rb | # frozen_string_literal: true
require 'active_job/retry/exponential_options_validator'
module ActiveJob
class Retry < Module
class ExponentialBackoffStrategy < ConstantBackoffStrategy
def initialize(options)
ExponentialOptionsValidator.new(options).validate!
@retry_limit = options.fetch(:limit, 1)
@fatal_exceptions = options.fetch(:fatal_exceptions, [])
@retryable_exceptions = options.fetch(:retryable_exceptions, nil)
end
def retry_delay(attempt, _exception)
(attempt**4 + 15 + (rand(30) * (attempt + 1))).seconds
end
end
end
end
| ruby | MIT | 06045dd843e51bb8f0d91058f9f9874f033f3407 | 2026-01-04T17:45:33.653067Z | false |
isaacseymour/activejob-retry | https://github.com/isaacseymour/activejob-retry/blob/06045dd843e51bb8f0d91058f9f9874f033f3407/lib/active_job/retry/deserialize_monkey_patch.rb | lib/active_job/retry/deserialize_monkey_patch.rb | # frozen_string_literal: true
# In Rails 4.2, ActiveJob externally applies deserialized job ID, queue name, arguments to
# the instantiated job in `ActiveJob::Base.deserialize`, which cannot be overridden in
# subclasses. https://github.com/rails/rails/pull/18260 changes this to delegate as much
# of the deserialization as possible to the instance, i.e. `ActiveJob::Base#deserialize`,
# which can be overridden. This allows us to store extra information in the queue (i.e.
# retry_attempt), which is essential for ActiveJob::Retry.
#
# This monkey patch is automatically applied if necessary when ActiveJob::Retry is
# required.
raise 'Unnecessary monkey patch!' if ActiveJob::Base.method_defined?(:deserialize)
module ActiveJob
class Base
def self.deserialize(job_data)
job = job_data['job_class'].constantize.new
job.deserialize(job_data)
job
end
def deserialize(job_data)
self.job_id = job_data['job_id']
self.queue_name = job_data['queue_name']
self.serialized_arguments = job_data['arguments']
end
end
end
| ruby | MIT | 06045dd843e51bb8f0d91058f9f9874f033f3407 | 2026-01-04T17:45:33.653067Z | false |
isaacseymour/activejob-retry | https://github.com/isaacseymour/activejob-retry/blob/06045dd843e51bb8f0d91058f9f9874f033f3407/lib/active_job/retry/exponential_options_validator.rb | lib/active_job/retry/exponential_options_validator.rb | # frozen_string_literal: true
require 'active_job/retry/errors'
module ActiveJob
class Retry < Module
class ExponentialOptionsValidator
def initialize(options)
@options = options
end
def validate!
validate_limit_numericality!
validate_infinite_limit!
validate_delay_not_specified!
validate_not_both_exceptions!
# Fatal exceptions must be an array (cannot be nil, since then all
# exceptions would be fatal - for that just set `limit: 0`)
validate_array_of_exceptions!(:fatal_exceptions)
# Retryable exceptions must be an array of exceptions or `nil` to retry
# any exception
if options[:retryable_exceptions]
validate_array_of_exceptions!(:retryable_exceptions)
end
end
private
attr_reader :options
# Limit must be an integer >= 0, or nil
def validate_limit_numericality!
return unless options[:limit]
return if options[:limit].is_a?(Integer) && options[:limit] >= 0
raise InvalidConfigurationError,
'Limit must be an integer >= 0, or nil for unlimited retries'
end
# If no limit is supplied, you *must* set `unlimited_retries: true` and
# understand that your ops team might hurt you.
def validate_infinite_limit!
limit = options.fetch(:limit, 1)
return unless limit.nil? ^ options[:unlimited_retries] == true
if limit.nil? && options[:unlimited_retries] != true
raise InvalidConfigurationError,
'You must set `unlimited_retries: true` to use `limit: nil`'
else
raise InvalidConfigurationError,
'You must set `limit: nil` to have unlimited retries'
end
end
# Delay must not be set
def validate_delay_not_specified!
return unless options[:delay]
raise InvalidConfigurationError,
'You can`t set delay for ExponentialBackoffStrategy'
end
def validate_not_both_exceptions!
return unless options[:fatal_exceptions] && options[:retryable_exceptions]
raise InvalidConfigurationError,
'fatal_exceptions and retryable_exceptions cannot be used together'
end
def validate_array_of_exceptions!(key)
return unless options[key]
if options[key].is_a?(Array) &&
options[key].all? { |ex| ex.is_a?(Class) && ex <= Exception }
return
end
raise InvalidConfigurationError, "#{key} must be an array of exceptions!"
end
end
end
end
| ruby | MIT | 06045dd843e51bb8f0d91058f9f9874f033f3407 | 2026-01-04T17:45:33.653067Z | false |
michael/ken-rb | https://github.com/michael/ken-rb/blob/b77ce234e5ff389da433c658d5988d146a2d8be8/tasks/ken.rb | tasks/ken.rb | # desc "Explaining what the task does"
# task :ken do
# # Task goes here
# end | ruby | MIT | b77ce234e5ff389da433c658d5988d146a2d8be8 | 2026-01-04T17:45:38.274680Z | false |
michael/ken-rb | https://github.com/michael/ken-rb/blob/b77ce234e5ff389da433c658d5988d146a2d8be8/tasks/spec.rb | tasks/spec.rb | begin
gem 'rspec', '~>1.1.12'
require 'spec'
require 'spec/rake/spectask'
task :default => [ :spec ]
desc 'Run specifications'
Spec::Rake::SpecTask.new(:spec) do |t|
t.spec_opts << '--options' << 'spec/spec.opts' if File.exists?('spec/spec.opts')
t.spec_files = Pathname.glob((ROOT + 'spec/**/*_spec.rb').to_s).map { |f| f.to_s }
begin
gem 'rcov', '~>0.8'
t.rcov = JRUBY ? false : (ENV.has_key?('NO_RCOV') ? ENV['NO_RCOV'] != 'true' : true)
t.rcov_opts << '--exclude' << 'spec'
t.rcov_opts << '--text-summary'
t.rcov_opts << '--sort' << 'coverage' << '--sort-reverse'
rescue LoadError
# rcov not installed
end
end
rescue LoadError
# rspec not installed
end | ruby | MIT | b77ce234e5ff389da433c658d5988d146a2d8be8 | 2026-01-04T17:45:38.274680Z | false |
michael/ken-rb | https://github.com/michael/ken-rb/blob/b77ce234e5ff389da433c658d5988d146a2d8be8/rails/init.rb | rails/init.rb | # when used as a rails plugin
require 'ken' | ruby | MIT | b77ce234e5ff389da433c658d5988d146a2d8be8 | 2026-01-04T17:45:38.274680Z | false |
michael/ken-rb | https://github.com/michael/ken-rb/blob/b77ce234e5ff389da433c658d5988d146a2d8be8/test/test_helper.rb | test/test_helper.rb | require 'rubygems'
require 'test/unit'
require 'shoulda'
require 'pathname'
require 'json'
require 'matchy'
$LOAD_PATH.unshift(File.join(File.dirname(__FILE__), '..', 'lib'))
$LOAD_PATH.unshift(File.dirname(__FILE__))
TEST_ROOT = Pathname(__FILE__).dirname.expand_path
require TEST_ROOT.parent + 'lib/ken'
def load_fixture(fixture_name)
fname = "#{File.dirname(__FILE__)}/fixtures/#{fixture_name}.json"
unless File.exists?(fname)
open(fname, "w") do |file|
puts "WARNING: Fixtures could not be loaded."
end
end
JSON.parse open(fname,"r").read
end
class Test::Unit::TestCase
custom_matcher :be_nil do |receiver, matcher, args|
matcher.positive_failure_message = "Expected #{receiver} to be nil but it wasn't"
matcher.negative_failure_message = "Expected #{receiver} not to be nil but it was"
receiver.nil?
end
custom_matcher :have do |receiver, matcher, args|
count = args[0]
something = matcher.chained_messages[0].name
actual = receiver.send(something).size
actual == count
end
custom_matcher :be_true do |receiver, matcher, args|
matcher.positive_failure_message = "Expected #{receiver} to be true but it wasn't"
matcher.negative_failure_message = "Expected #{receiver} not to be true but it was"
receiver.eql?(true)
end
custom_matcher :be_false do |receiver, matcher, args|
matcher.positive_failure_message = "Expected #{receiver} to be false but it wasn't"
matcher.negative_failure_message = "Expected #{receiver} not to be false but it was"
receiver.eql?(false)
end
end
class Object
# nice for debugging
# usage: print_call_stack(:method_name, 2, 10)
def print_call_stack(from = 2, to = nil, html = false)
(from..(to ? to : caller.length)).each do |idx|
p "[#{idx}]: #{caller[idx]}#{html ? '<br />' : ''}"
end
end
end
| ruby | MIT | b77ce234e5ff389da433c658d5988d146a2d8be8 | 2026-01-04T17:45:38.274680Z | false |
michael/ken-rb | https://github.com/michael/ken-rb/blob/b77ce234e5ff389da433c658d5988d146a2d8be8/test/integration/ken_test.rb | test/integration/ken_test.rb | require 'test_helper'
class KenTest < Test::Unit::TestCase
context "Ken.get" do
setup do
Ken::Session.new('http://www.freebase.com', 'ma', 'xxxxx')
end
should 'return a Ken::Resource' do
the_police = Ken.get("/en/the_police")
the_police.should be_kind_of(Ken::Resource)
end
should 'raise a Ken::ResourceNotFound error if id does not exist' do
lambda { Ken.get("/en/non_existent_resource") }.should raise_error(Ken::ResourceNotFound)
end
end
context "Ken.all" do
should "return a Ken::Collection of Ken::Resources" do
resources = Ken.all(:name => "Apple")
resources.should be_kind_of(Ken::Collection)
resources.first.should be_kind_of(Ken::Resource)
end
should "work with a limit specified" do
resources = Ken.all(:name => "Apple", :limit => 3)
resources.length.should == 3
end
should "be able to return more than 100 resources (using cursored queries) " do
Ken.all({:type => '/chemistry/chemical_element'}).length.should > 100
end
should "work with a type specified" do
resources = Ken.all(:name => "Apple", :type => "/music/album")
resources.length.should >= 1
resources.each {|r| r.types.select {|t| t.id == "/music/album"}.length.should == 1 }
end
should "understand nested queries" do
query = {
:directed_by => "George Lucas",
:starring => [
{
:actor => "Harrison Ford"
}
],
:type => "/film/film"
}
resources = Ken.all(query)
resources.length.should == 3
resources.first.name.should == "Star Wars Episode IV: A New Hope"
resources.last.name.should == "The Star Wars Holiday Special"
end
end
context "A Ken::Resource Instance" do
setup do
@the_police = Ken.get("/en/the_police")
end
should "provide attributes" do
@the_police.attributes.length.should >= 1
@the_police.attributes.first.should be_kind_of(Ken::Attribute)
end
should "have views" do
@the_police.views.length.should >= 1
@the_police.views.first.should be_kind_of(Ken::View)
@the_police.views.first.type.should be_kind_of(Ken::Type)
end
end
end | ruby | MIT | b77ce234e5ff389da433c658d5988d146a2d8be8 | 2026-01-04T17:45:38.274680Z | false |
michael/ken-rb | https://github.com/michael/ken-rb/blob/b77ce234e5ff389da433c658d5988d146a2d8be8/test/unit/session_test.rb | test/unit/session_test.rb | require 'test_helper'
class SessionTest < Test::Unit::TestCase
context "A Session instance" do
setup do
# Ken::Logger.new(STDOUT, :info)
Ken::Session.new('http://www.freebase.com', 'ma', 'xxxxx')
end
should 'return the correct set of types' do
result = Ken.session.mqlread({:id => "/en/the_police", :type => []})
result['type'].length.should >= 1
end
should 'raise a Ken::MqlReadError if node does not exist' do
lambda { Ken.session.mqlread({:id => "/en/the_police", :evil_property => []}) }.should raise_error(Ken::ReadError)
end
should 'do uncursored queries' do
Ken.session.mqlread([{:type => '/chemistry/chemical_element'}]).length == 100
end
should 'do cursored queries' do
Ken.session.mqlread([{:type => '/chemistry/chemical_element'}], :cursor => true).length.should >= 117
end
should 'do raw content requests' do
Ken.session.raw_content("/guid/9202a8c04000641f800000000002c4f3").length.should >= 50
end
should 'do blurb content requests' do
Ken.session.blurb_content("/guid/9202a8c04000641f800000000002c4f3", :maxlength => 200).length.should >= 50
end
should 'do topic requests' do
Ken.session.topic("/en/the_police")
end
should 'do search requests' do
Ken.session.search("the police").length.should >= 1
end
end # context
end # SessionTest | ruby | MIT | b77ce234e5ff389da433c658d5988d146a2d8be8 | 2026-01-04T17:45:38.274680Z | false |
michael/ken-rb | https://github.com/michael/ken-rb/blob/b77ce234e5ff389da433c658d5988d146a2d8be8/test/unit/resource_test.rb | test/unit/resource_test.rb | require 'test_helper'
class ResourceTest < Test::Unit::TestCase
context "A Resource instance" do
setup do
data = load_fixture('the_police')
@the_police = Ken::Resource.new(data)
end
should "have types" do
@the_police.should have(6).types
@the_police.types.first.should be_kind_of(Ken::Type)
end
should "have views" do
@the_police.should have(6).views
@the_police.views.first.should be_kind_of(Ken::View)
@the_police.views.first.type.should be_kind_of(Ken::Type)
end
should "return individual view based requested type id" do
@the_police.view('/music/artist').should be_kind_of(Ken::View)
@the_police.view('/location/location').should be_nil # not existent view
end
should "return individual type based requested type id" do
@the_police.type('/music/artist').should be_kind_of(Ken::Type)
@the_police.type('/location/location').should be_nil # not existent type
end
should 'have a full set of attributes' do
@the_police.attributes.should_not be_nil
end
should "have id and name properties" do
@the_police.id.should be_kind_of(String)
@the_police.name.should be_kind_of(String)
end
should 'load attributes only on demand' do
@the_police.attributes_loaded?.should == false
@the_police.attributes
@the_police.attributes_loaded?.should == true
end
should 'load schema only on demand when calling types' do
@the_police.schema_loaded?.should == false
@the_police.types
@the_police.schema_loaded?.should == true
end
should 'load schema only on demand when calling views' do
@the_police.schema_loaded?.should == false
@the_police.views
@the_police.schema_loaded?.should == true
end
end # context
end # ResourceTest | ruby | MIT | b77ce234e5ff389da433c658d5988d146a2d8be8 | 2026-01-04T17:45:38.274680Z | false |
michael/ken-rb | https://github.com/michael/ken-rb/blob/b77ce234e5ff389da433c658d5988d146a2d8be8/test/unit/type_test.rb | test/unit/type_test.rb | require 'test_helper'
class TypeTest < Test::Unit::TestCase
context "A Session instance" do
setup do
data = load_fixture('the_police')
@type = Ken::Resource.new(data).types.first
end
should 'have an id and a name' do
@type.id.should be_kind_of(String)
@type.name.should be_kind_of(String)
end
should 'have properties' do
@type.should have(16).properties
end
context "when accessing a property directly" do
setup do
@genre = @type.genre
@album = @type.album
end
should "be kind of Ken::Property" do
@genre.should be_kind_of(Ken::Property)
@album.should be_kind_of(Ken::Property)
end
should "raise AttributeNotFound when invalid propertyname is supplied" do
lambda { @type.not_existing_property }.should raise_error(Ken::PropertyNotFound)
end
end # context
end # context
end # TypeTest | ruby | MIT | b77ce234e5ff389da433c658d5988d146a2d8be8 | 2026-01-04T17:45:38.274680Z | false |
michael/ken-rb | https://github.com/michael/ken-rb/blob/b77ce234e5ff389da433c658d5988d146a2d8be8/test/unit/attribute_test.rb | test/unit/attribute_test.rb | require 'test_helper'
class AttributeTest < Test::Unit::TestCase
context "An Attribute instance" do
setup do
data = load_fixture('the_police')
@the_police = Ken::Resource.new(data)
@attribute = @unique_value_attribute = @the_police.views[0].active_start
@unique_object_attribute = @the_police.views[0].origin
@unique_object_attribute.unique?
@non_unique_value_attribute = @the_police.views[1].alias
@non_unique_object_attribute = @the_police.views[0].album
end
should "should have values" do
@attribute.should have(1).values
@non_unique_object_attribute.should have(14).values
end
context "with unique value type" do
should "be unique and no object_type" do
@unique_value_attribute.unique?.should == true
@unique_value_attribute.object_type?.should == false
end
end
context "with unique object type" do
should "be unique and an object type" do
@unique_object_attribute.unique?.should == true
@unique_object_attribute.object_type?.should == true
end
end
context "with non-unique value type" do
should "not be unique and not an object type" do
@non_unique_value_attribute.unique?.should == false
@non_unique_value_attribute.object_type?.should == false
end
end
context "with non-unique object type" do
should "be unique and an object type" do
@non_unique_object_attribute.unique?.should == false
@non_unique_object_attribute.object_type?.should == true
end
end
end # context
end # AttributeTest | ruby | MIT | b77ce234e5ff389da433c658d5988d146a2d8be8 | 2026-01-04T17:45:38.274680Z | false |
michael/ken-rb | https://github.com/michael/ken-rb/blob/b77ce234e5ff389da433c658d5988d146a2d8be8/test/unit/topic_test.rb | test/unit/topic_test.rb | require 'test_helper'
class TopicTest < Test::Unit::TestCase
context "A Topic instance" do
setup do
data = load_fixture('the_police_topic')
@the_police = Ken::Topic.new(data)
end
should "have an id" do
@the_police.id.should == "/en/the_police"
end
should "have aliases" do
@the_police.aliases.length.should >= 1
end
should "have a text/name" do
@the_police.text.should == "The Police"
@the_police.name.should == "The Police"
end
should "have a thumbnail" do
@the_police.thumbnail.should == "http://api.freebase.com/api/trans/image_thumb/en/the_police"
end
should "have webpages" do
@the_police.webpages.length.should == 5
end
should "have types" do
@the_police.types.length.should == 7
@the_police.types.first.should be_kind_of(Ken::Type)
end
should "have properties" do
@the_police.properties.length.should >= 1
@the_police.properties.first.should be_kind_of(Ken::Property)
end
should "have attributes" do
@the_police.attributes.first.should be_kind_of(Ken::Attribute)
# TODO support mediator properties (CVT's)
# @the_police.attributes.length.should == @the_police.properties.length
end
should "have views" do
@the_police.should have(7).views
@the_police.views.first.should be_kind_of(Ken::View)
@the_police.views.first.type.should be_kind_of(Ken::Type)
end
should "return individual view based requested type id" do
@the_police.view('/music/artist').should be_kind_of(Ken::View)
@the_police.view('/music/artist').attributes.length.should == 9
@the_police.view('/location/location').should be_nil # not existent view
end
should "return individual type based requested type id" do
@the_police.type('/music/artist').should be_kind_of(Ken::Type)
@the_police.type('/location/location').should be_nil # not existent type
end
should 'have a full set of attributes' do
@the_police.attributes.should_not be_nil
end
should "have id and name properties" do
@the_police.id.should be_kind_of(String)
@the_police.name.should be_kind_of(String)
end
should 'load attributes only on demand' do
@the_police.attributes_loaded?.should == false
@the_police.attributes
@the_police.attributes_loaded?.should == true
end
should 'load schema only on demand when calling types' do
@the_police.schema_loaded?.should == false
@the_police.types
@the_police.schema_loaded?.should == true
end
should 'load schema only on demand when calling views' do
@the_police.schema_loaded?.should == false
@the_police.views
@the_police.schema_loaded?.should == true
end
end # context
end # TopicTest | ruby | MIT | b77ce234e5ff389da433c658d5988d146a2d8be8 | 2026-01-04T17:45:38.274680Z | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.