code
stringlengths
26
124k
docstring
stringlengths
23
125k
func_name
stringlengths
1
98
language
stringclasses
1 value
repo
stringlengths
5
53
path
stringlengths
7
151
url
stringlengths
50
211
license
stringclasses
7 values
def _stream_read_remote_write_local(channel) data = self.lsock.sysread(16384) self.on_print_proc.call(data.strip) if self.on_print_proc user_output.print(data) end
Reads from the channel and writes locally.
_stream_read_remote_write_local
ruby
hahwul/mad-metasploit
mad-metasploit-plugins/meta_ssh/lib/rex/post/meta_ssh/ui/console/interactive_channel.rb
https://github.com/hahwul/mad-metasploit/blob/master/mad-metasploit-plugins/meta_ssh/lib/rex/post/meta_ssh/ui/console/interactive_channel.rb
MIT
def initialize(shell) super self.extensions = [] self.bgjobs = [] self.bgjob_id = 0 end
Initializes an instance of the core command set using the supplied shell for interactivity.
initialize
ruby
hahwul/mad-metasploit
mad-metasploit-plugins/meta_ssh/lib/rex/post/meta_ssh/ui/console/command_dispatcher/core.rb
https://github.com/hahwul/mad-metasploit/blob/master/mad-metasploit-plugins/meta_ssh/lib/rex/post/meta_ssh/ui/console/command_dispatcher/core.rb
MIT
def cmd_channel(*args) if args.include?("-h") or args.include?("--help") or args.length==0 cmd_channel_help return end mode = nil chan = nil data = [] # Parse options @@channel_opts.parse(args) { |opt, idx, val| case opt when "-l" mode = :list when "-c" mode = :close chan = val when "-i" mode = :interact chan = val end if @@channel_opts.arg_required?(opt) unless chan print_error("Channel ID required") return end end } case mode when :list tbl = Rex::Ui::Text::Table.new( 'Indent' => 4, 'Columns' => [ 'Id', 'Type', 'Info' ]) items = 0 client.channels.each_pair { |cid, channel| tbl << [ cid, channel.type, channel.info ] items += 1 } if (items == 0) print_line("No active channels.") else print("\n" + tbl.to_s + "\n") end when :close cmd_close(chan) when :interact cmd_interact(chan) else # No mode, no service. return true end end
Performs operations on the supplied channel.
cmd_channel
ruby
hahwul/mad-metasploit
mad-metasploit-plugins/meta_ssh/lib/rex/post/meta_ssh/ui/console/command_dispatcher/core.rb
https://github.com/hahwul/mad-metasploit/blob/master/mad-metasploit-plugins/meta_ssh/lib/rex/post/meta_ssh/ui/console/command_dispatcher/core.rb
MIT
def cmd_run(*args) if args.length == 0 cmd_run_help return true end # Get the script name begin script_name = args.shift # First try it as a Post module if we have access to the Metasploit # Framework instance. If we don't, or if no such module exists, # fall back to using the scripting interface. if (msf_loaded? and mod = client.framework.modules.create(script_name)) omod = mod mod = client.framework.modules.reload_module(mod) if (not mod) print_error("Failed to reload module: #{client.framework.modules.failed[omod.file_path]}") return end opts = (args + [ "SESSION=#{client.sid}" ]).join(',') # monkeypatch the mod to use our cmd_exec etc mod=mod.dup mod.extend(Msf::Scripts::MetaSSH::Common) mod.extend(Msf::Simple::Post) mod.run_simple( #'RunAsJob' => true, 'LocalInput' => shell.input, 'LocalOutput' => shell.output, 'OptionStr' => opts ) else # the rest of the arguments get passed in through the binding client.execute_script(script_name, args) end rescue print_error("Error in script: #{$!.class} #{$!}") elog("Error in script: #{$!.class} #{$!}") dlog("Callstack: #{[email protected]("\n")}") end end
Executes a script in the context of the meterpreter session.
cmd_run
ruby
hahwul/mad-metasploit
mad-metasploit-plugins/meta_ssh/lib/rex/post/meta_ssh/ui/console/command_dispatcher/core.rb
https://github.com/hahwul/mad-metasploit/blob/master/mad-metasploit-plugins/meta_ssh/lib/rex/post/meta_ssh/ui/console/command_dispatcher/core.rb
MIT
def cmd_bgrun(*args) if args.length == 0 print_line( "Usage: bgrun <script> [arguments]\n\n" + "Executes a ruby script in the context of the metaSSH session.") return true end jid = self.bgjob_id self.bgjob_id += 1 # Get the script name self.bgjobs[jid] = Rex::ThreadFactory.spawn("SshBGRun(#{args[0]})-#{jid}", false, jid, args) do |myjid,xargs| ::Thread.current[:args] = xargs.dup begin # the rest of the arguments get passed in through the binding client.execute_script(args.shift, args) rescue ::Exception print_error("Error in script: #{$!.class} #{$!}") elog("Error in script: #{$!.class} #{$!}") dlog("Callstack: #{[email protected]("\n")}") end self.bgjobs[myjid] = nil print_status("Background script with Job ID #{myjid} has completed (#{::Thread.current[:args].inspect})") end print_status("Executed metaSSH with Job ID #{jid}") end
Executes a script in the context of the meterpreter session in the background
cmd_bgrun
ruby
hahwul/mad-metasploit
mad-metasploit-plugins/meta_ssh/lib/rex/post/meta_ssh/ui/console/command_dispatcher/core.rb
https://github.com/hahwul/mad-metasploit/blob/master/mad-metasploit-plugins/meta_ssh/lib/rex/post/meta_ssh/ui/console/command_dispatcher/core.rb
MIT
def cmd_info(*args) return unless msf_loaded? if args.length != 1 or args.include?("-h") cmd_info_help return end module_name = args.shift mod = client.framework.modules.create(module_name); if mod.nil? print_error 'Invalid module: ' << module_name end if (mod) print_line(::Msf::Serializer::ReadableText.dump_module(mod)) mod_opt = ::Msf::Serializer::ReadableText.dump_options(mod, ' ') print_line("\nModule options (#{mod.fullname}):\n\n#{mod_opt}") if (mod_opt and mod_opt.length > 0) end end
Show info for a given Post module. See also +cmd_info+ in lib/msf/ui/console/command_dispatcher/core.rb
cmd_info
ruby
hahwul/mad-metasploit
mad-metasploit-plugins/meta_ssh/lib/rex/post/meta_ssh/ui/console/command_dispatcher/core.rb
https://github.com/hahwul/mad-metasploit/blob/master/mad-metasploit-plugins/meta_ssh/lib/rex/post/meta_ssh/ui/console/command_dispatcher/core.rb
MIT
def add_extension_client(mod) loaded = false klass = nil self.class.client_extension_search_paths.each do |path| path = ::File.join(path, "#{mod}.rb") klass = CommDispatcher.check_hash(path) if (klass == nil) old = CommDispatcher.constants next unless ::File.exist? path if (require(path)) new = CommDispatcher.constants diff = new - old next if (diff.empty?) klass = CommDispatcher.const_get(diff[0]) CommDispatcher.set_hash(path, klass) loaded = true break else print_error("Failed to load client script file: #{path}") return false end else # the klass is already loaded, from a previous invocation loaded = true break end end unless loaded print_error("Failed to load client portion of #{mod}.") return false end # Enstack the dispatcher self.shell.enstack_dispatcher(klass) # Insert the module into the list of extensions self.extensions << mod end
Loads the client extension specified in mod
add_extension_client
ruby
hahwul/mad-metasploit
mad-metasploit-plugins/meta_ssh/lib/rex/post/meta_ssh/ui/console/command_dispatcher/core.rb
https://github.com/hahwul/mad-metasploit/blob/master/mad-metasploit-plugins/meta_ssh/lib/rex/post/meta_ssh/ui/console/command_dispatcher/core.rb
MIT
def initialize(shell) super Dispatchers.each { |d| shell.enstack_dispatcher(d) } end
Initializes an instance of the stdapi command interaction.
initialize
ruby
hahwul/mad-metasploit
mad-metasploit-plugins/meta_ssh/lib/rex/post/meta_ssh/ui/console/command_dispatcher/stdapi.rb
https://github.com/hahwul/mad-metasploit/blob/master/mad-metasploit-plugins/meta_ssh/lib/rex/post/meta_ssh/ui/console/command_dispatcher/stdapi.rb
MIT
def cmd_cat(*args) if (args.length == 0) print_line("Usage: cat file") return true end begin fd = client.fs.file.new(args[0], "rb") until fd.eof? print(fd.read) end fd.close rescue Errno::ENOENT print_error("File does not exist") return false end true end
Reads the contents of a file and prints them to the screen.
cmd_cat
ruby
hahwul/mad-metasploit
mad-metasploit-plugins/meta_ssh/lib/rex/post/meta_ssh/ui/console/command_dispatcher/stdapi/fs.rb
https://github.com/hahwul/mad-metasploit/blob/master/mad-metasploit-plugins/meta_ssh/lib/rex/post/meta_ssh/ui/console/command_dispatcher/stdapi/fs.rb
MIT
def cmd_download(*args) if (args.empty? or args.include? "-h") cmd_download_help return true end recursive = false src_items = [] last = nil dest = nil @@download_opts.parse(args) { |opt, idx, val| case opt when "-r" recursive = true when nil src_items << last if (last) last = val end } # No files given, nothing to do if not last cmd_download_help return true end # Source and destination will be the same if src_items.empty? src_items << last # Use the basename of the remote filename so we don't end up with # a file named c:\\boot.ini in linux dest = ::Rex::Post::MetaSSH::Extensions::Stdapi::Fs::File.basename(last) else dest = last end # Go through each source item and download them src_items.each { |src| stat = client.fs.file.stat(src) if (stat.directory?) client.fs.dir.download(dest, src, recursive, true) { |step, src, dst| print_status("#{step.ljust(11)}: #{src} -> #{dst}") client.framework.events.on_session_download(client, src, dest) if msf_loaded? } elsif (stat.file?) client.fs.file.download(dest, src) { |step, src, dst| print_status("#{step.ljust(11)}: #{src} -> #{dst}") client.framework.events.on_session_download(client, src, dest) if msf_loaded? } end } return true end
Downloads a file or directory from the remote machine to the local machine.
cmd_download
ruby
hahwul/mad-metasploit
mad-metasploit-plugins/meta_ssh/lib/rex/post/meta_ssh/ui/console/command_dispatcher/stdapi/fs.rb
https://github.com/hahwul/mad-metasploit/blob/master/mad-metasploit-plugins/meta_ssh/lib/rex/post/meta_ssh/ui/console/command_dispatcher/stdapi/fs.rb
MIT
def cmd_edit(*args) if (args.length == 0) print_line("Usage: edit file") return true end # Get a temporary file path meterp_temp = Tempfile.new('metassh') meterp_temp.binmode temp_path = meterp_temp.path begin # Download the remote file to the temporary file client.fs.file.download_file(temp_path, args[0]) rescue RequestError => re # If the file doesn't exist, then it's okay. Otherwise, throw the # error. if re.result != 2 raise $! end end # Spawn the editor (default to vi) editor = Rex::Compat.getenv('EDITOR') || 'vi' # If it succeeds, upload it to the remote side. if (system("#{editor} #{temp_path}") == true) client.fs.file.upload_file(args[0], temp_path) end # Get rid of that pesky temporary file temp_path.close(true) end
Downloads a file to a temporary file, spawns and editor, and then uploads the contents to the remote machine after completion.
cmd_edit
ruby
hahwul/mad-metasploit
mad-metasploit-plugins/meta_ssh/lib/rex/post/meta_ssh/ui/console/command_dispatcher/stdapi/fs.rb
https://github.com/hahwul/mad-metasploit/blob/master/mad-metasploit-plugins/meta_ssh/lib/rex/post/meta_ssh/ui/console/command_dispatcher/stdapi/fs.rb
MIT
def cmd_ls(*args) path = args[0] || client.fs.dir.getwd tbl = Rex::Ui::Text::Table.new( 'Header' => "Listing: #{path}", 'Columns' => [ 'Mode', 'Size', 'Type', 'Last modified', 'Name', ]) items = 0 # Enumerate each item... client.fs.dir.entries_with_info(path).sort { |a,b| a['FileName'] <=> b['FileName'] }.each { |p| tbl << [ p['StatBuf'] ? p['StatBuf'].prettymode : '', p['StatBuf'] ? p['StatBuf'].size : '', p['StatBuf'] ? p['StatBuf'].ftype[0,3] : '', p['StatBuf'] ? p['StatBuf'].mtime : '', p['FileName'] || 'unknown' ] items += 1 } if (items > 0) print("\n" + tbl.to_s + "\n") else print_line("No entries exist in #{path}") end return true end
Lists files TODO: make this more useful
cmd_ls
ruby
hahwul/mad-metasploit
mad-metasploit-plugins/meta_ssh/lib/rex/post/meta_ssh/ui/console/command_dispatcher/stdapi/fs.rb
https://github.com/hahwul/mad-metasploit/blob/master/mad-metasploit-plugins/meta_ssh/lib/rex/post/meta_ssh/ui/console/command_dispatcher/stdapi/fs.rb
MIT
def cmd_rmdir(*args) if (args.length == 0 or args.include?("-h")) print_line("Usage: rmdir dir1 dir2 dir3 ...") return true end args.each { |dir| print_line("Removing directory: #{dir}") client.fs.dir.rmdir(dir) } return true end
Removes one or more directory if it's empty.
cmd_rmdir
ruby
hahwul/mad-metasploit
mad-metasploit-plugins/meta_ssh/lib/rex/post/meta_ssh/ui/console/command_dispatcher/stdapi/fs.rb
https://github.com/hahwul/mad-metasploit/blob/master/mad-metasploit-plugins/meta_ssh/lib/rex/post/meta_ssh/ui/console/command_dispatcher/stdapi/fs.rb
MIT
def cmd_upload(*args) if (args.empty? or args.include?("-h")) cmd_upload_help return true end recursive = false src_items = [] last = nil dest = nil @@upload_opts.parse(args) { |opt, idx, val| case opt when "-r" recursive = true when nil if (last) src_items << last end last = val end } return true if not last # Source and destination will be the same src_items << last if src_items.empty? dest = last # Go through each source item and upload them src_items.each { |src| stat = ::File.stat(src) if (stat.directory?) client.fs.dir.upload(dest, src, recursive) { |step, src, dst| print_status("#{step.ljust(11)}: #{src} -> #{dst}") client.framework.events.on_session_upload(client, src, dest) if msf_loaded? } elsif (stat.file?) client.fs.file.upload(dest, src) { |step, src, dst| print_status("#{step.ljust(11)}: #{src} -> #{dst}") client.framework.events.on_session_upload(client, src, dest) if msf_loaded? } end } return true end
Uploads a file or directory to the remote machine from the local machine.
cmd_upload
ruby
hahwul/mad-metasploit
mad-metasploit-plugins/meta_ssh/lib/rex/post/meta_ssh/ui/console/command_dispatcher/stdapi/fs.rb
https://github.com/hahwul/mad-metasploit/blob/master/mad-metasploit-plugins/meta_ssh/lib/rex/post/meta_ssh/ui/console/command_dispatcher/stdapi/fs.rb
MIT
def cmd_shell(*args) path = "/bin/bash -i" cmd_execute("-f", path, "-c", "-i") end
Drop into a system shell as specified by %COMSPEC% or as appropriate for the host.
cmd_shell
ruby
hahwul/mad-metasploit
mad-metasploit-plugins/meta_ssh/lib/rex/post/meta_ssh/ui/console/command_dispatcher/stdapi/sys.rb
https://github.com/hahwul/mad-metasploit/blob/master/mad-metasploit-plugins/meta_ssh/lib/rex/post/meta_ssh/ui/console/command_dispatcher/stdapi/sys.rb
MIT
def pool @pool || raise(Error, "Que connection not established!") end
How to actually access Que's established connection pool.
pool
ruby
que-rb/que
lib/que.rb
https://github.com/que-rb/que/blob/master/lib/que.rb
MIT
def parse( args:, output:, default_require_file: RAILS_ENVIRONMENT_FILE ) options = {} queues = [] log_level = 'info' log_internals = false poll_interval = 5 connection_url = nil worker_count = nil worker_priorities = nil parser = OptionParser.new do |opts| opts.banner = 'usage: que [options] [file/to/require] ...' opts.on( '-h', '--help', "Show this help text.", ) do output.puts opts.help return 0 end opts.on( '-i', '--poll-interval [INTERVAL]', Float, "Set maximum interval between polls for available jobs, " \ "in seconds (default: 5)", ) do |i| poll_interval = i end opts.on( '--listen [LISTEN]', String, "Set to false to disable listen mode (default: true)" ) do |listen| options[:listen] = listen != "false" end opts.on( '-l', '--log-level [LEVEL]', String, "Set level at which to log to STDOUT " \ "(debug, info, warn, error, fatal) (default: info)", ) do |l| log_level = l end opts.on( '-p', '--worker-priorities [LIST]', Array, "List of priorities to assign to workers (default: 10,30,50,any,any,any)", ) do |priority_array| worker_priorities = priority_array.map do |p| case p when /\Aany\z/i nil when /\A\d+\z/ Integer(p) else output.puts "Invalid priority option: '#{p}'. Please use an integer or the word 'any'." return 1 end end end opts.on( '-q', '--queue-name [NAME]', String, "Set a queue name to work jobs from. " \ "Can be passed multiple times. " \ "(default: the default queue only)", ) do |queue_name| queues << queue_name end opts.on( '-w', '--worker-count [COUNT]', Integer, "Set number of workers in process (default: 6)", ) do |w| worker_count = w end opts.on( '-v', '--version', "Print Que version and exit.", ) do require 'que' output.puts "Que version #{Que::VERSION}" return 0 end opts.on( '--connection-url [URL]', String, "Set a custom database url to connect to for locking purposes.", ) do |url| options[:connection_url] = url end opts.on( '--log-internals', "Log verbosely about Que's internal state. " \ "Only recommended for debugging issues", ) do |l| log_internals = true end opts.on( '--maximum-buffer-size [SIZE]', Integer, "Set maximum number of jobs to be locked and held in this " \ "process awaiting a worker (default: 8)", ) do |s| options[:maximum_buffer_size] = s end opts.on( '--minimum-buffer-size [SIZE]', Integer, "Unused (deprecated)", ) do |s| warn "The --minimum-buffer-size SIZE option has been deprecated and will be removed in v2.0 (it's actually been unused since v1.0.0.beta4)" end opts.on( '--wait-period [PERIOD]', Float, "Set maximum interval between checks of the in-memory job queue, " \ "in milliseconds (default: 50)", ) do |p| options[:wait_period] = p end opts.on( '--pidfile [PATH]', String, "Write the PID of this process to the specified file.", ) do |p| options[:pidfile] = File.expand_path(p) end end parser.parse!(args) options[:worker_priorities] = if worker_count && worker_priorities worker_priorities.values_at(0...worker_count) elsif worker_priorities worker_priorities elsif worker_count Array.new(worker_count) { nil } else [10, 30, 50, nil, nil, nil] end if args.length.zero? if File.exist?(default_require_file) args << default_require_file else output.puts <<-OUTPUT You didn't include any Ruby files to require! Que needs to be able to load your application before it can process jobs. (Or use `que -h` for a list of options) OUTPUT return 1 end end args.each do |file| begin require file rescue LoadError => e output.puts "Could not load file '#{file}': #{e}" return 1 end end Que.logger ||= Logger.new(STDOUT) if log_internals Que.internal_logger = Que.logger end begin Que.get_logger.level = Logger.const_get(log_level.upcase) rescue NameError output.puts "Unsupported logging level: #{log_level} (try debug, info, warn, error, or fatal)" return 1 end if queues.any? queues_hash = {} queues.each do |queue| name, interval = queue.split('=') p = interval ? Float(interval) : poll_interval Que.assert(p > 0.01) { "Poll intervals can't be less than 0.01 seconds!" } queues_hash[name] = p end options[:queues] = queues_hash end options[:poll_interval] = poll_interval locker = begin Que::Locker.new(**options) rescue => e output.puts(e.message) return 1 end # It's a bit sloppy to use a global for this when a local variable would # do, but we want to stop the locker from the CLI specs, so... $stop_que_executable = false %w[INT TERM].each { |signal| trap(signal) { $stop_que_executable = true } } output.puts( <<~STARTUP Que #{Que::VERSION} started worker process with: Worker threads: #{locker.workers.length} (priorities: #{locker.workers.map { |w| w.priority || 'any' }.join(', ')}) Buffer size: #{locker.job_buffer.maximum_size} Queues: #{locker.queues.map { |queue, interval| " - #{queue} (poll interval: #{interval}s)" }.join("\n")} Que waiting for jobs... STARTUP ) loop do sleep 0.01 break if $stop_que_executable || locker.stopping? end output.puts "\nFinishing Que's current jobs before exiting..." locker.stop! output.puts "Que's jobs finished, exiting..." return 0 end
Need to rely on dependency injection a bit to make this method cleanly testable :/
parse
ruby
que-rb/que
lib/que/command_line_interface.rb
https://github.com/que-rb/que/blob/master/lib/que/command_line_interface.rb
MIT
def initialize( maximum_size:, priorities: ) @maximum_size = Que.assert(Integer, maximum_size) Que.assert(maximum_size >= 0) { "maximum_size for a JobBuffer must be at least zero!" } @stop = false @array = [] @mutex = Mutex.new @priority_queues = Hash[ # Make sure that priority = nil sorts highest. priorities.sort_by{|p| p || MAXIMUM_PRIORITY}.map do |p| [p, PriorityQueue.new(priority: p, job_buffer: self)] end ].freeze end
Since we use a mutex, which is not reentrant, we have to be a little careful to not call a method that locks the mutex when we've already locked it. So, as a general rule, public methods handle locking the mutex when necessary, while private methods handle the actual underlying data changes. This lets us reuse those private methods without running into locking issues.
initialize
ruby
que-rb/que
lib/que/job_buffer.rb
https://github.com/que-rb/que/blob/master/lib/que/job_buffer.rb
MIT
def _run(args: nil, kwargs: nil, reraise_errors: false) if args.nil? && que_target args = que_target.que_attrs.fetch(:args) end if kwargs.nil? && que_target kwargs = que_target.que_attrs.fetch(:kwargs) end run(*args, **kwargs) default_resolve_action if que_target && !que_target.que_resolved rescue => error raise error unless que_target que_target.que_error = error run_error_notifier = begin handle_error(error) rescue => error_2 Que.notify_error(error_2, que_target.que_attrs) true end Que.notify_error(error, que_target.que_attrs) if run_error_notifier retry_in_default_interval unless que_target.que_resolved raise error if reraise_errors end
Note that we delegate almost all methods to the result of the que_target method, which could be one of a few things, depending on the circumstance. Run the job with error handling and cleanup logic. Optionally support overriding the args, because it's necessary when jobs are invoked from ActiveJob.
_run
ruby
que-rb/que
lib/que/job_methods.rb
https://github.com/que-rb/que/blob/master/lib/que/job_methods.rb
MIT
def que_target raise NotImplementedError end
This method defines the object on which the various job helper methods are acting. When using Que in the default configuration this will just be self, but when using the Que adapter for ActiveJob it'll be the actual underlying job object. When running an ActiveJob::Base subclass that includes this module through a separate adapter this will be nil - hence, the defensive coding in every method that no-ops if que_target is falsy.
que_target
ruby
que-rb/que
lib/que/job_methods.rb
https://github.com/que-rb/que/blob/master/lib/que/job_methods.rb
MIT
def retry_in(period) return unless que_target if id = que_target.que_attrs[:id] values = [period] if e = que_target.que_error values << "#{e.class}: #{e.message}".slice(0, 500) << e.backtrace.join("\n").slice(0, 10000) else values << nil << nil end Que.execute :set_error, values << id end que_target.que_resolved = true end
Explicitly check for the job id in these helpers, because it won't exist if we're running synchronously.
retry_in
ruby
que-rb/que
lib/que/job_methods.rb
https://github.com/que-rb/que/blob/master/lib/que/job_methods.rb
MIT
def _raise_db_version_comment_missing_error raise Error, <<~ERROR Cannot determine Que DB schema version. The que_jobs table is missing its comment recording the Que DB schema version. This is likely due to a bug in Rails schema dump in Rails 7 versions prior to 7.0.3, omitting comments - see https://github.com/que-rb/que/issues/363. Please determine the appropriate schema version from your migrations and record it manually by running the following SQL (replacing version as appropriate): COMMENT ON TABLE que_jobs IS 'version'; ERROR end
The que_jobs table could be missing the schema version comment either due to: - Being created before the migration system existed; or - A bug in Rails schema dump in some versions of Rails The former is the case on Que versions prior to v0.5.0 (2014-01-14). Upgrading directly from there is unsupported, so we just raise in all cases of the comment being missing
_raise_db_version_comment_missing_error
ruby
que-rb/que
lib/que/migrations.rb
https://github.com/que-rb/que/blob/master/lib/que/migrations.rb
MIT
def setup(connection) connection.execute <<-SQL -- Temporary composite type we need for our queries to work. CREATE TYPE pg_temp.que_query_result AS ( locked boolean, remaining_priorities jsonb ); CREATE FUNCTION pg_temp.lock_and_update_priorities(priorities jsonb, job que_jobs) RETURNS pg_temp.que_query_result AS $$ WITH -- Take the lock in a CTE because we want to use the result -- multiple times while only taking the lock once. lock_taken AS ( SELECT pg_try_advisory_lock((job).id) AS taken ), relevant AS ( SELECT priority, count FROM ( SELECT key::smallint AS priority, value::text::integer AS count FROM jsonb_each(priorities) ) t1 WHERE priority >= (job).priority ORDER BY priority ASC LIMIT 1 ) SELECT (SELECT taken FROM lock_taken), -- R CASE (SELECT taken FROM lock_taken) WHEN false THEN -- Simple case - we couldn't lock the job, so don't update the -- priorities hash. priorities WHEN true THEN CASE count WHEN 1 THEN -- Remove the priority from the JSONB doc entirely, rather -- than leaving a zero entry in it. priorities - priority::text ELSE -- Decrement the value in the JSONB doc. jsonb_set( priorities, ARRAY[priority::text], to_jsonb(count - 1) ) END END FROM relevant $$ STABLE LANGUAGE SQL; CREATE FUNCTION pg_temp.que_highest_remaining_priority(priorities jsonb) RETURNS smallint AS $$ SELECT max(key::smallint) FROM jsonb_each(priorities) $$ STABLE LANGUAGE SQL; SQL end
Manage some temporary infrastructure (specific to the connection) that we'll use for polling. These could easily be created permanently in a migration, but that'd require another migration if we wanted to tweak them later.
setup
ruby
que-rb/que
lib/que/poller.rb
https://github.com/que-rb/que/blob/master/lib/que/poller.rb
MIT
def que_filter_args(thing) case thing when Array thing.map { |t| que_filter_args(t) } when Hash thing.each_with_object({}) do |(k, v), hash| hash[k] = que_filter_args(v) unless k == :_aj_symbol_keys end else thing end end
Filter out :_aj_symbol_keys constructs so that keywords work as expected.
que_filter_args
ruby
que-rb/que
lib/que/active_job/extensions.rb
https://github.com/que-rb/que/blob/master/lib/que/active_job/extensions.rb
MIT
def enqueue(args, priority:, queue:, run_at: nil) super(args, job_options: { priority: priority, queue: queue, run_at: run_at }) end
We've dropped support for job options supplied as top-level keywords, but ActiveJob's QueAdapter still uses them. So we have to move them into the job_options hash ourselves.
enqueue
ruby
que-rb/que
lib/que/active_job/extensions.rb
https://github.com/que-rb/que/blob/master/lib/que/active_job/extensions.rb
MIT
def attrs {"job_id" => que_attrs[:id]} end
The Rails adapter (built against a pre-1.0 version of this gem) assumes that it can access a job's id via job.attrs["job_id"]. So, oblige it.
attrs
ruby
que-rb/que
lib/que/active_job/extensions.rb
https://github.com/que-rb/que/blob/master/lib/que/active_job/extensions.rb
MIT
def checkout wrap_in_rails_executor do ::ActiveRecord::Base.connection_pool.with_connection do |conn| yield conn.raw_connection end end end
Check out a PG::Connection object from ActiveRecord's pool.
checkout
ruby
que-rb/que
lib/que/active_record/connection.rb
https://github.com/que-rb/que/blob/master/lib/que/active_record/connection.rb
MIT
def wrap_in_rails_executor(&block) if defined?(::Rails.application.executor) ::Rails.application.executor.wrap(&block) else yield end end
Use Rails' executor (if present) to make sure that the connection we're using isn't taken from us while the block runs. See https://github.com/que-rb/que/issues/166#issuecomment-274218910
wrap_in_rails_executor
ruby
que-rb/que
lib/que/active_record/connection.rb
https://github.com/que-rb/que/blob/master/lib/que/active_record/connection.rb
MIT
def _check_assertion_args(first, second = (second_omitted = true; nil)) if second_omitted comparison = nil object = first else comparison = first object = second end pass = if second_omitted object elsif comparison.is_a?(Array) comparison.any? { |k| k === object } else comparison === object end [comparison, object, pass] end
Want to support: assert(x) # Truthiness. assert(thing, other) # Trip-equals. assert([thing1, thing2], other) # Multiple Trip-equals.
_check_assertion_args
ruby
que-rb/que
lib/que/utils/assertions.rb
https://github.com/que-rb/que/blob/master/lib/que/utils/assertions.rb
MIT
def notify_error_async(*args) # We don't synchronize around the size check and the push, so there's a # race condition where the queue could grow to more than the maximum # number of errors, but no big deal if it does. The size check is mainly # here to ensure that the error queue doesn't grow unboundedly large in # pathological cases. if ASYNC_QUEUE.size < MAX_QUEUE_SIZE ASYNC_QUEUE.push(args) # Puma raises some ugly warnings if you start up a new thread in the # background during initialization, so start the async error-reporting # thread lazily. async_error_thread true else false end end
Helper method to notify errors asynchronously. For use in high-priority code, where we don't want to be held up by whatever I/O the error notification proc contains.
notify_error_async
ruby
que-rb/que
lib/que/utils/error_notification.rb
https://github.com/que-rb/que/blob/master/lib/que/utils/error_notification.rb
MIT
def internal_log(event, object = nil) if l = get_logger(internal: true) data = _default_log_data data[:internal_event] = Que.assert(Symbol, event) data[:object_id] = object.object_id if object data[:t] = Time.now.utc.iso8601(6) additional = Que.assert(Hash, yield) # Make sure that none of our log contents accidentally overwrite our # default data contents. expected_length = data.length + additional.length data.merge!(additional) Que.assert(expected_length == data.length) do "Bad internal logging keys in: #{additional.keys.inspect}" end l.info(JSON.dump(data)) end end
Logging method used specifically to instrument Que's internals. There's usually not an internal logger set up, so this method is generally a no- op unless the specs are running or someone turns on internal logging so we can debug an issue.
internal_log
ruby
que-rb/que
lib/que/utils/logging.rb
https://github.com/que-rb/que/blob/master/lib/que/utils/logging.rb
MIT
def sleep_until_equal(expected, timeout: SLEEP_UNTIL_TIMEOUT) actual = nil sleep_until?(timeout: timeout) do actual = yield actual == expected end || raise("sleep_until_equal: expected #{expected.inspect}, got #{actual.inspect}") end
Sleep helpers for testing threaded code.
sleep_until_equal
ruby
que-rb/que
spec/spec_helper.rb
https://github.com/que-rb/que/blob/master/spec/spec_helper.rb
MIT
def save_point saved = new_mark column = @goal_column @save_point_level += 1 begin yield(saved) ensure point_to_mark(saved) saved.delete @goal_column = column @save_point_level -= 1 end end
The buffer should not be modified in the given block because current_line/current_column is not updated in save_point.
save_point
ruby
shugo/textbringer
lib/textbringer/buffer.rb
https://github.com/shugo/textbringer/blob/master/lib/textbringer/buffer.rb
MIT
def push_mark(pos = @point) @mark = new_mark @mark.location = pos @mark_ring.push(@mark) if self != Buffer.minibuffer global_mark_ring = Buffer.global_mark_ring if global_mark_ring.empty? || global_mark_ring.current.buffer != self push_global_mark(pos) end end end
Set mark at pos, and push the mark on the mark ring. Unlike Emacs, the new mark is pushed on the mark ring instead of the old one.
push_mark
ruby
shugo/textbringer
lib/textbringer/buffer.rb
https://github.com/shugo/textbringer/blob/master/lib/textbringer/buffer.rb
MIT
def read_file(filename, basename) # Add error checking for failed file read? (comments, data) = IO.read(filename).split(/#{basename}:\s*\n/) return comments, create_hash(data) end
Retrieve comments, translation data in hash form
read_file
ruby
spree-contrib/spree_i18n
lib/spree/i18n_utils.rb
https://github.com/spree-contrib/spree_i18n/blob/master/lib/spree/i18n_utils.rb
BSD-3-Clause
def write_file(filename, basename, _comments, words, comment_values = true, _fallback_values = {}) File.open(filename, 'w') do |log| log.puts(basename + ": \n") words.sort.each do |k, v| keys = k.split(':') # Add indentation for children keys (keys.size - 1).times do keys[keys.size - 1] = ' ' + keys[keys.size - 1] end value = v.strip value = ('#' + value) if comment_values && !value.blank? log.puts "#{keys[keys.size - 1]}: #{value}\n" end end end
Writes to file from translation data hash structure
write_file
ruby
spree-contrib/spree_i18n
lib/spree/i18n_utils.rb
https://github.com/spree-contrib/spree_i18n/blob/master/lib/spree/i18n_utils.rb
BSD-3-Clause
def version Gem::Version.new Version::STRING end
Returns the version of the currently loaded SpreeI18n as a <tt>Gem::Version</tt>.
version
ruby
spree-contrib/spree_i18n
lib/spree_i18n/version.rb
https://github.com/spree-contrib/spree_i18n/blob/master/lib/spree_i18n/version.rb
BSD-3-Clause
def reset_query_stats success = if @database.server_version_num >= 120000 @database.reset_query_stats else @database.reset_instance_query_stats end if success redirect_backward notice: "Query stats reset" else redirect_backward alert: "The database user does not have permission to reset query stats" end end
TODO disable if historical query stats enabled?
reset_query_stats
ruby
ankane/pghero
app/controllers/pg_hero/home_controller.rb
https://github.com/ankane/pghero/blob/master/app/controllers/pg_hero/home_controller.rb
MIT
def rescue_timeout(default) [yield, false] rescue ActiveRecord::LockWaitTimeout, ActiveRecord::QueryCanceled [default, true] end
rescue QueryCanceled for case when statement timeout is less than lock timeout
rescue_timeout
ruby
ankane/pghero
app/controllers/pg_hero/home_controller.rb
https://github.com/ankane/pghero/blob/master/app/controllers/pg_hero/home_controller.rb
MIT
def username @username ||= (file_config || {})["username"] || ENV["PGHERO_USERNAME"] end
use method instead of attr_accessor to ensure this works if variable set after PgHero is loaded
username
ruby
ankane/pghero
lib/pghero.rb
https://github.com/ankane/pghero/blob/master/lib/pghero.rb
MIT
def password @password ||= (file_config || {})["password"] || ENV["PGHERO_PASSWORD"] end
use method instead of attr_accessor to ensure this works if variable set after PgHero is loaded
password
ruby
ankane/pghero
lib/pghero.rb
https://github.com/ankane/pghero/blob/master/lib/pghero.rb
MIT
def stats_database_url @stats_database_url ||= (file_config || {})["stats_database_url"] || ENV["PGHERO_STATS_DATABASE_URL"] end
config pattern for https://github.com/ankane/pghero/issues/424
stats_database_url
ruby
ankane/pghero
lib/pghero.rb
https://github.com/ankane/pghero/blob/master/lib/pghero.rb
MIT
def databases unless defined?(@databases) # only use mutex on initialization MUTEX.synchronize do # return if another process initialized while we were waiting return @databases if defined?(@databases) @databases = config["databases"].map { |id, c| [id.to_sym, Database.new(id, c)] }.to_h end end @databases end
ensure we only have one copy of databases so there's only one connection pool per database
databases
ruby
ankane/pghero
lib/pghero.rb
https://github.com/ankane/pghero/blob/master/lib/pghero.rb
MIT
def clean_query_stats(before: nil) each_database do |database| database.clean_query_stats(before: before) end end
delete previous stats go database by database to use an index stats for old databases are not cleaned up since we can't use an index
clean_query_stats
ruby
ankane/pghero
lib/pghero.rb
https://github.com/ankane/pghero/blob/master/lib/pghero.rb
MIT
def aws_db_instance_identifier @aws_db_instance_identifier ||= config["aws_db_instance_identifier"] || config["db_instance_identifier"] end
environment variable is only used if no config file
aws_db_instance_identifier
ruby
ankane/pghero
lib/pghero/database.rb
https://github.com/ankane/pghero/blob/master/lib/pghero/database.rb
MIT
def gcp_database_id @gcp_database_id ||= config["gcp_database_id"] end
environment variable is only used if no config file
gcp_database_id
ruby
ankane/pghero
lib/pghero/database.rb
https://github.com/ankane/pghero/blob/master/lib/pghero/database.rb
MIT
def azure_resource_id @azure_resource_id ||= config["azure_resource_id"] end
environment variable is only used if no config file
azure_resource_id
ruby
ankane/pghero
lib/pghero/database.rb
https://github.com/ankane/pghero/blob/master/lib/pghero/database.rb
MIT
def build_connection_model url = config["url"] # resolve spec if !url && config["spec"] config_options = {env_name: PgHero.env, PgHero.spec_name_key => config["spec"], PgHero.include_replicas_key => true} resolved = ActiveRecord::Base.configurations.configs_for(**config_options) raise Error, "Spec not found: #{config["spec"]}" unless resolved url = resolved.configuration_hash end url = url.dup Class.new(PgHero::Connection) do def self.name "PgHero::Connection::Database#{object_id}" end case url when String url = "#{url}#{url.include?("?") ? "&" : "?"}connect_timeout=5" unless url.include?("connect_timeout=") when Hash url[:connect_timeout] ||= 5 end establish_connection url if url end end
just return the model do not start a connection
build_connection_model
ruby
ankane/pghero
lib/pghero/database.rb
https://github.com/ankane/pghero/blob/master/lib/pghero/database.rb
MIT
def invalid_constraints select_all <<~SQL SELECT nsp.nspname AS schema, rel.relname AS table, con.conname AS name, fnsp.nspname AS referenced_schema, frel.relname AS referenced_table FROM pg_catalog.pg_constraint con INNER JOIN pg_catalog.pg_class rel ON rel.oid = con.conrelid LEFT JOIN pg_catalog.pg_class frel ON frel.oid = con.confrelid LEFT JOIN pg_catalog.pg_namespace nsp ON nsp.oid = con.connamespace LEFT JOIN pg_catalog.pg_namespace fnsp ON fnsp.oid = frel.relnamespace WHERE con.convalidated = 'f' SQL end
referenced fields can be nil as not all constraints are foreign keys
invalid_constraints
ruby
ankane/pghero
lib/pghero/methods/constraints.rb
https://github.com/ankane/pghero/blob/master/lib/pghero/methods/constraints.rb
MIT
def explain(sql) sql = squish(sql) explanation = nil # use transaction for safety with_transaction(statement_timeout: (explain_timeout_sec * 1000).round, rollback: true) do if (sql.delete_suffix(";").include?(";") || sql.upcase.include?("COMMIT")) && !explain_safe? raise ActiveRecord::StatementInvalid, "Unsafe statement" end explanation = execute("EXPLAIN #{sql}").map { |v| v["QUERY PLAN"] }.join("\n") end explanation end
TODO remove in 4.0 note: this method is not affected by the explain option
explain
ruby
ankane/pghero
lib/pghero/methods/explain.rb
https://github.com/ankane/pghero/blob/master/lib/pghero/methods/explain.rb
MIT
def explain_v2(sql, analyze: nil, verbose: nil, costs: nil, settings: nil, generic_plan: nil, buffers: nil, wal: nil, timing: nil, summary: nil, format: "text") options = [] add_explain_option(options, "ANALYZE", analyze) add_explain_option(options, "VERBOSE", verbose) add_explain_option(options, "SETTINGS", settings) add_explain_option(options, "GENERIC_PLAN", generic_plan) add_explain_option(options, "COSTS", costs) add_explain_option(options, "BUFFERS", buffers) add_explain_option(options, "WAL", wal) add_explain_option(options, "TIMING", timing) add_explain_option(options, "SUMMARY", summary) options << "FORMAT #{explain_format(format)}" explain("(#{options.join(", ")}) #{sql}") end
TODO rename to explain in 4.0 note: this method is not affected by the explain option
explain_v2
ruby
ankane/pghero
lib/pghero/methods/explain.rb
https://github.com/ankane/pghero/blob/master/lib/pghero/methods/explain.rb
MIT
def explain_format(format) if ["text", "xml", "json", "yaml"].include?(format) format.upcase else raise ArgumentError, "Unknown format" end end
important! validate format to prevent injection
explain_format
ruby
ankane/pghero
lib/pghero/methods/explain.rb
https://github.com/ankane/pghero/blob/master/lib/pghero/methods/explain.rb
MIT
def indexes indexes = select_all(<<~SQL SELECT schemaname AS schema, t.relname AS table, ix.relname AS name, regexp_replace(pg_get_indexdef(i.indexrelid), '^[^\\(]*\\((.*)\\)$', '\\1') AS columns, regexp_replace(pg_get_indexdef(i.indexrelid), '.* USING ([^ ]*) \\(.*', '\\1') AS using, indisunique AS unique, indisprimary AS primary, indisvalid AS valid, indexprs::text, indpred::text, pg_get_indexdef(i.indexrelid) AS definition FROM pg_index i INNER JOIN pg_class t ON t.oid = i.indrelid INNER JOIN pg_class ix ON ix.oid = i.indexrelid LEFT JOIN pg_stat_user_indexes ui ON ui.indexrelid = i.indexrelid WHERE schemaname IS NOT NULL ORDER BY 1, 2 SQL ).map { |v| v[:columns] = v[:columns].sub(") WHERE (", " WHERE ").split(", ").map { |c| unquote(c) }; v } # determine if any invalid indexes being created # hacky, but works for simple cases # can be a race condition, but that's fine invalid_indexes = indexes.select { |i| !i[:valid] } if invalid_indexes.any? create_index_queries = running_queries.select { |q| /\s*CREATE\s+INDEX\s+CONCURRENTLY\s+/i.match(q[:query]) } invalid_indexes.each do |index| index[:creating] = create_index_queries.any? { |q| q[:query].include?(index[:table]) && index[:columns].all? { |c| q[:query].include?(c) } } end end indexes end
TODO parse array properly https://stackoverflow.com/questions/2204058/list-columns-with-indexes-in-postgresql
indexes
ruby
ankane/pghero
lib/pghero/methods/indexes.rb
https://github.com/ankane/pghero/blob/master/lib/pghero/methods/indexes.rb
MIT
def index_bloat(min_size: nil) min_size ||= index_bloat_bytes select_all <<~SQL WITH btree_index_atts AS ( SELECT nspname, relname, reltuples, relpages, indrelid, relam, regexp_split_to_table(indkey::text, ' ')::smallint AS attnum, indexrelid as index_oid FROM pg_index JOIN pg_class ON pg_class.oid = pg_index.indexrelid JOIN pg_namespace ON pg_namespace.oid = pg_class.relnamespace JOIN pg_am ON pg_class.relam = pg_am.oid WHERE pg_am.amname = 'btree' ), index_item_sizes AS ( SELECT i.nspname, i.relname, i.reltuples, i.relpages, i.relam, (quote_ident(s.schemaname) || '.' || quote_ident(s.tablename))::regclass AS starelid, a.attrelid AS table_oid, index_oid, current_setting('block_size')::numeric AS bs, /* MAXALIGN: 4 on 32bits, 8 on 64bits (and mingw32 ?) */ CASE WHEN version() ~ 'mingw32' OR version() ~ '64-bit' THEN 8 ELSE 4 END AS maxalign, 24 AS pagehdr, /* per tuple header: add index_attribute_bm if some cols are null-able */ CASE WHEN max(coalesce(s.null_frac,0)) = 0 THEN 2 ELSE 6 END AS index_tuple_hdr, /* data len: we remove null values save space using it fractionnal part from stats */ sum( (1-coalesce(s.null_frac, 0)) * coalesce(s.avg_width, 2048) ) AS nulldatawidth FROM pg_attribute AS a JOIN pg_stats AS s ON (quote_ident(s.schemaname) || '.' || quote_ident(s.tablename))::regclass=a.attrelid AND s.attname = a.attname JOIN btree_index_atts AS i ON i.indrelid = a.attrelid AND a.attnum = i.attnum WHERE a.attnum > 0 GROUP BY 1, 2, 3, 4, 5, 6, 7, 8, 9 ), index_aligned AS ( SELECT maxalign, bs, nspname, relname AS index_name, reltuples, relpages, relam, table_oid, index_oid, ( 2 + maxalign - CASE /* Add padding to the index tuple header to align on MAXALIGN */ WHEN index_tuple_hdr%maxalign = 0 THEN maxalign ELSE index_tuple_hdr%maxalign END + nulldatawidth + maxalign - CASE /* Add padding to the data to align on MAXALIGN */ WHEN nulldatawidth::integer%maxalign = 0 THEN maxalign ELSE nulldatawidth::integer%maxalign END )::numeric AS nulldatahdrwidth, pagehdr FROM index_item_sizes AS s1 ), otta_calc AS ( SELECT bs, nspname, table_oid, index_oid, index_name, relpages, coalesce( ceil((reltuples*(4+nulldatahdrwidth))/(bs-pagehdr::float)) + CASE WHEN am.amname IN ('hash','btree') THEN 1 ELSE 0 END , 0 /* btree and hash have a metadata reserved block */ ) AS otta FROM index_aligned AS s2 LEFT JOIN pg_am am ON s2.relam = am.oid ), raw_bloat AS ( SELECT nspname, c.relname AS table_name, index_name, bs*(sub.relpages)::bigint AS totalbytes, CASE WHEN sub.relpages <= otta THEN 0 ELSE bs*(sub.relpages-otta)::bigint END AS wastedbytes, CASE WHEN sub.relpages <= otta THEN 0 ELSE bs*(sub.relpages-otta)::bigint * 100 / (bs*(sub.relpages)::bigint) END AS realbloat, pg_relation_size(sub.table_oid) as table_bytes, stat.idx_scan as index_scans, stat.indexrelid FROM otta_calc AS sub JOIN pg_class AS c ON c.oid=sub.table_oid JOIN pg_stat_user_indexes AS stat ON sub.index_oid = stat.indexrelid ) SELECT nspname AS schema, table_name AS table, index_name AS index, wastedbytes AS bloat_bytes, totalbytes AS index_bytes, pg_get_indexdef(rb.indexrelid) AS definition, indisprimary AS primary FROM raw_bloat rb INNER JOIN pg_index i ON i.indexrelid = rb.indexrelid WHERE wastedbytes >= #{min_size.to_i} ORDER BY wastedbytes DESC, index_name SQL end
https://gist.github.com/mbanck/9976015/71888a24e464e2f772182a7eb54f15a125edf398 thanks @jberkus and @mbanck
index_bloat
ruby
ankane/pghero
lib/pghero/methods/indexes.rb
https://github.com/ankane/pghero/blob/master/lib/pghero/methods/indexes.rb
MIT
def transaction_id_danger(threshold: 10000000, max_value: 2146483648) max_value = max_value.to_i threshold = threshold.to_i select_all <<~SQL SELECT n.nspname AS schema, c.relname AS table, #{quote(max_value)} - GREATEST(AGE(c.relfrozenxid), AGE(t.relfrozenxid)) AS transactions_left FROM pg_class c INNER JOIN pg_catalog.pg_namespace n ON n.oid = c.relnamespace LEFT JOIN pg_class t ON c.reltoastrelid = t.oid WHERE c.relkind = 'r' AND (#{quote(max_value)} - GREATEST(AGE(c.relfrozenxid), AGE(t.relfrozenxid))) < #{quote(threshold)} ORDER BY 3, 1, 2 SQL end
https://www.postgresql.org/docs/current/routine-vacuuming.html#VACUUM-FOR-WRAPAROUND "the system will shut down and refuse to start any new transactions once there are fewer than 1 million transactions left until wraparound" warn when 10,000,000 transactions left
transaction_id_danger
ruby
ankane/pghero
lib/pghero/methods/maintenance.rb
https://github.com/ankane/pghero/blob/master/lib/pghero/methods/maintenance.rb
MIT
def blocked_queries query = <<~SQL SELECT COALESCE(blockingl.relation::regclass::text,blockingl.locktype) as locked_item, blockeda.pid AS blocked_pid, blockeda.usename AS blocked_user, blockeda.query as blocked_query, age(now(), blockeda.query_start) AS blocked_duration, blockedl.mode as blocked_mode, blockinga.pid AS blocking_pid, blockinga.usename AS blocking_user, blockinga.state AS state_of_blocking_process, blockinga.query AS current_or_recent_query_in_blocking_process, age(now(), blockinga.query_start) AS blocking_duration, blockingl.mode as blocking_mode FROM pg_catalog.pg_locks blockedl LEFT JOIN pg_stat_activity blockeda ON blockedl.pid = blockeda.pid LEFT JOIN pg_catalog.pg_locks blockingl ON blockedl.pid != blockingl.pid AND ( blockingl.transactionid = blockedl.transactionid OR (blockingl.relation = blockedl.relation AND blockingl.locktype = blockedl.locktype) ) LEFT JOIN pg_stat_activity blockinga ON blockingl.pid = blockinga.pid AND blockinga.datid = blockeda.datid WHERE NOT blockedl.granted AND blockeda.query <> '<insufficient privilege>' AND blockeda.datname = current_database() ORDER BY blocked_duration DESC SQL select_all(query, query_columns: [:blocked_query, :current_or_recent_query_in_blocking_process]) end
from https://wiki.postgresql.org/wiki/Lock_Monitoring and https://big-elephants.com/2013-09/exploring-query-locks-in-postgres/
blocked_queries
ruby
ankane/pghero
lib/pghero/methods/queries.rb
https://github.com/ankane/pghero/blob/master/lib/pghero/methods/queries.rb
MIT
def reset_instance_query_stats(database: nil, user: nil, query_hash: nil, raise_errors: false) if database || user || query_hash raise PgHero::Error, "Requires PostgreSQL 12+" if server_version_num < 120000 if database database_id = execute("SELECT oid FROM pg_database WHERE datname = #{quote(database)}").first.try(:[], "oid") raise PgHero::Error, "Database not found: #{database}" unless database_id else database_id = 0 end if user user_id = execute("SELECT usesysid FROM pg_user WHERE usename = #{quote(user)}").first.try(:[], "usesysid") raise PgHero::Error, "User not found: #{user}" unless user_id else user_id = 0 end if query_hash query_id = query_hash.to_i # may not be needed # but not intuitive that all query hashes are reset with 0 raise PgHero::Error, "Invalid query hash: #{query_hash}" if query_id == 0 else query_id = 0 end execute("SELECT pg_stat_statements_reset(#{quote(user_id.to_i)}, #{quote(database_id.to_i)}, #{quote(query_id.to_i)})") else execute("SELECT pg_stat_statements_reset()") end true rescue ActiveRecord::StatementInvalid => e raise e if raise_errors false end
resets query stats for the entire instance it's possible to reset stats for a specific database, user or query hash in Postgres 12+
reset_instance_query_stats
ruby
ankane/pghero
lib/pghero/methods/query_stats.rb
https://github.com/ankane/pghero/blob/master/lib/pghero/methods/query_stats.rb
MIT
def historical_query_stats_enabled? # TODO use schema from config # make sure primary database is PostgreSQL first query_stats_table_exists? && capture_query_stats? && !missing_query_stats_columns.any? end
https://stackoverflow.com/questions/20582500/how-to-check-if-a-table-exists-in-a-given-schema
historical_query_stats_enabled?
ruby
ankane/pghero
lib/pghero/methods/query_stats.rb
https://github.com/ankane/pghero/blob/master/lib/pghero/methods/query_stats.rb
MIT
def capture_query_stats(raise_errors: false) return if config["capture_query_stats"] && config["capture_query_stats"] != true # get all databases that use same query stats and build mapping mapping = {id => database_name} PgHero.databases.select { |_, d| d.config["capture_query_stats"] == id }.each do |_, d| mapping[d.id] = d.database_name end now = Time.now query_stats = {} mapping.each do |database_id, database_name| query_stats[database_id] = query_stats(limit: 1000000, database: database_name) end query_stats = query_stats.select { |_, v| v.any? } # nothing to do return if query_stats.empty? # reset individual databases for Postgres 12+ instance if server_version_num >= 120000 query_stats.each do |db_id, db_query_stats| if reset_instance_query_stats(database: mapping[db_id], raise_errors: raise_errors) insert_query_stats(db_id, db_query_stats, now) end end else if reset_instance_query_stats(raise_errors: raise_errors) query_stats.each do |db_id, db_query_stats| insert_query_stats(db_id, db_query_stats, now) end end end end
resetting query stats will reset across the entire Postgres instance in Postgres < 12 this is problematic if multiple PgHero databases use the same Postgres instance to get around this, we capture queries for every Postgres database before we reset query stats for the Postgres instance with the `capture_query_stats` option
capture_query_stats
ruby
ankane/pghero
lib/pghero/methods/query_stats.rb
https://github.com/ankane/pghero/blob/master/lib/pghero/methods/query_stats.rb
MIT
def current_query_stats(limit: nil, sort: nil, database: nil, query_hash: nil, user: nil, origin: false) if query_stats_enabled? limit ||= 100 sort ||= "total_minutes" total_time = server_version_num >= 130000 ? "(total_plan_time + total_exec_time)" : "total_time" query = <<~SQL WITH query_stats AS ( SELECT LEFT(query, 10000) AS query, #{supports_query_hash? ? "queryid" : "md5(query)"} AS query_hash, rolname AS user, (#{total_time} / 1000 / 60) AS total_minutes, (#{total_time} / calls) AS average_time, calls FROM pg_stat_statements INNER JOIN pg_database ON pg_database.oid = pg_stat_statements.dbid INNER JOIN pg_roles ON pg_roles.oid = pg_stat_statements.userid WHERE calls > 0 AND pg_database.datname = #{database ? quote(database) : "current_database()"} #{query_hash ? "AND queryid = #{quote(query_hash)}" : nil} #{user ? "AND rolname = #{quote(user)}" : nil} ) SELECT query, query AS explainable_query, #{origin ? "(SELECT regexp_matches(query, '.*/\\*(.+?)\\*/'))[1] AS origin," : nil} query_hash, query_stats.user, total_minutes, average_time, calls, total_minutes * 100.0 / (SELECT SUM(total_minutes) FROM query_stats) AS total_percent, (SELECT SUM(total_minutes) FROM query_stats) AS all_queries_total_minutes FROM query_stats ORDER BY #{quote_column_name(sort)} DESC LIMIT #{limit.to_i} SQL # we may be able to skip query_columns # in more recent versions of Postgres # as pg_stat_statements should be already normalized select_all(query, query_columns: [:query, :explainable_query]) else raise NotEnabled, "Query stats not enabled" end end
http://www.craigkerstiens.com/2013/01/10/more-on-postgres-performance/
current_query_stats
ruby
ankane/pghero
lib/pghero/methods/query_stats.rb
https://github.com/ankane/pghero/blob/master/lib/pghero/methods/query_stats.rb
MIT
def replication_lag with_feature_support(:replication_lag) do lag_condition = if server_version_num >= 100000 "pg_last_wal_receive_lsn() = pg_last_wal_replay_lsn()" else "pg_last_xlog_receive_location() = pg_last_xlog_replay_location()" end select_one <<~SQL SELECT CASE WHEN NOT pg_is_in_recovery() OR #{lag_condition} THEN 0 ELSE EXTRACT (EPOCH FROM NOW() - pg_last_xact_replay_timestamp()) END AS replication_lag SQL end end
https://www.postgresql.org/message-id/CADKbJJWz9M0swPT3oqe8f9+tfD4-F54uE6Xtkh4nERpVsQnjnw@mail.gmail.com
replication_lag
ruby
ankane/pghero
lib/pghero/methods/replication.rb
https://github.com/ankane/pghero/blob/master/lib/pghero/methods/replication.rb
MIT
def parse_default_value(default_value) m = /^nextval\('(.+)'\:\:regclass\)$/.match(default_value) m = /^nextval\(\('(.+)'\:\:text\)\:\:regclass\)$/.match(default_value) unless m if m unquote_ident(m[1]) else [] end end
can parse nextval('id_seq'::regclass) nextval(('id_seq'::text)::regclass)
parse_default_value
ruby
ankane/pghero
lib/pghero/methods/sequences.rb
https://github.com/ankane/pghero/blob/master/lib/pghero/methods/sequences.rb
MIT
def add_sequence_attributes(sequences) # fetch data sequence_attributes = select_all <<~SQL SELECT n.nspname AS schema, c.relname AS sequence, has_sequence_privilege(c.oid, 'SELECT') AS readable FROM pg_class c INNER JOIN pg_catalog.pg_namespace n ON n.oid = c.relnamespace WHERE c.relkind = 'S' AND n.nspname NOT IN ('pg_catalog', 'information_schema') SQL # first populate missing schemas missing_schema = sequences.select { |s| s[:schema].nil? && s[:sequence] } if missing_schema.any? sequence_schemas = sequence_attributes.group_by { |s| s[:sequence] } missing_schema.each do |sequence| schemas = sequence_schemas[sequence[:sequence]] || [] if schemas.size == 1 sequence[:schema] = schemas[0][:schema] end # otherwise, do nothing, will be marked as unreadable # TODO better message for multiple schemas end end # then populate attributes readable = sequence_attributes.to_h { |s| [[s[:schema], s[:sequence]], s[:readable]] } sequences.each do |sequence| sequence[:readable] = readable[[sequence[:schema], sequence[:sequence]]] || false end end
adds readable attribute to all sequences also adds schema if missing
add_sequence_attributes
ruby
ankane/pghero
lib/pghero/methods/sequences.rb
https://github.com/ankane/pghero/blob/master/lib/pghero/methods/sequences.rb
MIT
def row_estimates(stats, total_rows, rows_left, op) case op when "null" rows_left * stats[:null_frac].to_f when "not_null" rows_left * (1 - stats[:null_frac].to_f) else rows_left *= (1 - stats[:null_frac].to_f) ret = if stats[:n_distinct].to_f == 0 0 elsif stats[:n_distinct].to_f < 0 if total_rows > 0 (-1 / stats[:n_distinct].to_f) * (rows_left / total_rows.to_f) else 0 end else rows_left / stats[:n_distinct].to_f end case op when ">", ">=", "<", "<=", "~~", "~~*", "BETWEEN" (rows_left + ret) / 10.0 # TODO better approximation when "<>" rows_left - ret else ret end end end
TODO better row estimation https://www.postgresql.org/docs/current/static/row-estimation-examples.html
row_estimates
ruby
ankane/pghero
lib/pghero/methods/suggested_indexes.rb
https://github.com/ankane/pghero/blob/master/lib/pghero/methods/suggested_indexes.rb
MIT
def free_space(quota, used) data = {} quota.each do |k, v| data[k] = v - used[k] if v && used[k] end data end
only use data points included in both series this also eliminates need to align Time.now
free_space
ruby
ankane/pghero
lib/pghero/methods/system.rb
https://github.com/ankane/pghero/blob/master/lib/pghero/methods/system.rb
MIT
def create_user(user, password: nil, schema: "public", database: nil, readonly: false, tables: nil) password ||= random_password database ||= PgHero.connection_config(connection_model)[:database] user = quote_ident(user) schema = quote_ident(schema) database = quote_ident(database) commands = [ "CREATE ROLE #{user} LOGIN PASSWORD #{quote(password)}", "GRANT CONNECT ON DATABASE #{database} TO #{user}", "GRANT USAGE ON SCHEMA #{schema} TO #{user}" ] if readonly if tables commands.concat table_grant_commands("SELECT", tables, user) else commands << "GRANT SELECT ON ALL TABLES IN SCHEMA #{schema} TO #{user}" commands << "ALTER DEFAULT PRIVILEGES IN SCHEMA #{schema} GRANT SELECT ON TABLES TO #{user}" end else if tables commands.concat table_grant_commands("ALL PRIVILEGES", tables, user) else commands << "GRANT ALL PRIVILEGES ON ALL TABLES IN SCHEMA #{schema} TO #{user}" commands << "GRANT ALL PRIVILEGES ON ALL SEQUENCES IN SCHEMA #{schema} TO #{user}" commands << "ALTER DEFAULT PRIVILEGES IN SCHEMA #{schema} GRANT ALL PRIVILEGES ON TABLES TO #{user}" commands << "ALTER DEFAULT PRIVILEGES IN SCHEMA #{schema} GRANT ALL PRIVILEGES ON SEQUENCES TO #{user}" end end # run commands connection_model.transaction do commands.each do |command| execute command end end {password: password} end
documented as unsafe to pass user input identifiers are now quoted, but still not officially supported
create_user
ruby
ankane/pghero
lib/pghero/methods/users.rb
https://github.com/ankane/pghero/blob/master/lib/pghero/methods/users.rb
MIT
def drop_user(user, schema: "public", database: nil) database ||= PgHero.connection_config(connection_model)[:database] user = quote_ident(user) schema = quote_ident(schema) database = quote_ident(database) # thanks shiftb commands = [ "REVOKE CONNECT ON DATABASE #{database} FROM #{user}", "REVOKE USAGE ON SCHEMA #{schema} FROM #{user}", "REVOKE ALL PRIVILEGES ON ALL TABLES IN SCHEMA #{schema} FROM #{user}", "REVOKE ALL PRIVILEGES ON ALL SEQUENCES IN SCHEMA #{schema} FROM #{user}", "ALTER DEFAULT PRIVILEGES IN SCHEMA #{schema} REVOKE SELECT ON TABLES FROM #{user}", "ALTER DEFAULT PRIVILEGES IN SCHEMA #{schema} REVOKE SELECT ON SEQUENCES FROM #{user}", "ALTER DEFAULT PRIVILEGES IN SCHEMA #{schema} REVOKE ALL ON SEQUENCES FROM #{user}", "ALTER DEFAULT PRIVILEGES IN SCHEMA #{schema} REVOKE ALL ON TABLES FROM #{user}", "DROP ROLE #{user}" ] # run commands connection_model.transaction do commands.each do |command| execute command end end true end
documented as unsafe to pass user input identifiers are now quoted, but still not officially supported
drop_user
ruby
ankane/pghero
lib/pghero/methods/users.rb
https://github.com/ankane/pghero/blob/master/lib/pghero/methods/users.rb
MIT
def test_reset_query_stats post pg_hero.reset_query_stats_path assert_redirected_to "/" end
prevent warning for now def test_kill post pg_hero.kill_path(pid: 1_000_000_000) assert_redirected_to "/" end
test_reset_query_stats
ruby
ankane/pghero
test/controller_test.rb
https://github.com/ankane/pghero/blob/master/test/controller_test.rb
MIT
def initialize @redirect_limit = 3 @user_agent = 'link_thumbnailer' @verify_ssl = true @http_open_timeout = 5 @http_read_timeout = 5 @blacklist_urls = [ %r{^http://ad\.doubleclick\.net/}, %r{^http://b\.scorecardresearch\.com/}, %r{^http://pixel\.quantserve\.com/}, %r{^http://s7\.addthis\.com/} ] @attributes = [:title, :images, :description, :videos, :favicon, :body] @graders = [ ->(description) { ::LinkThumbnailer::Graders::Length.new(description) }, ->(description) { ::LinkThumbnailer::Graders::HtmlAttribute.new(description, :class) }, ->(description) { ::LinkThumbnailer::Graders::HtmlAttribute.new(description, :id) }, ->(description) { ::LinkThumbnailer::Graders::Position.new(description, weigth: 3) }, ->(description) { ::LinkThumbnailer::Graders::LinkDensity.new(description) }, ] @description_min_length = 50 @positive_regex = /article|body|content|entry|hentry|main|page|pagination|post|text|blog|story/i @negative_regex = /combx|comment|com-|contact|foot|footer|footnote|masthead|media|meta|outbrain|promo|related|scroll|shoutbox|sidebar|sponsor|shopping|tags|tool|widget|modal/i @image_limit = 5 @image_stats = true @raise_on_invalid_format = false @max_concurrency = 20 @scrapers = [:opengraph, :default] @http_override_headers = { 'Accept-Encoding' => 'none' } @download_size_limit = 10 * 1024 * 1024 @encoding = 'utf-8' end
Create a new instance. @return [LinkThumbnailer::Configuration]
initialize
ruby
gottfrois/link_thumbnailer
lib/link_thumbnailer/configuration.rb
https://github.com/gottfrois/link_thumbnailer/blob/master/lib/link_thumbnailer/configuration.rb
MIT
def call probability = 1.0 graders.each do |lambda| instance = lambda.call(description) probability *= instance.call.to_f ** instance.weight end probability end
For given description, computes probabilities returned by each graders by multipying them together. @return [Float] the probability for the given description to be considered good
call
ruby
gottfrois/link_thumbnailer
lib/link_thumbnailer/grader.rb
https://github.com/gottfrois/link_thumbnailer/blob/master/lib/link_thumbnailer/grader.rb
MIT
def vimeo? website.url.host =~ /vimeo/ end
Vimeo uses a SWF file for its og:video property which doesn't provide any metadata for the VideoInfo gem downstream. Using og:url means VideoInfo is passed a webpage URL with metadata it can parse.
vimeo?
ruby
gottfrois/link_thumbnailer
lib/link_thumbnailer/scrapers/opengraph/video.rb
https://github.com/gottfrois/link_thumbnailer/blob/master/lib/link_thumbnailer/scrapers/opengraph/video.rb
MIT
def attributes attributes_map { |name| send name } end
Returns a Hash of all attributes @example Get attributes person.attributes # => {"name"=>"Ben Poweski"} @return [Hash{String => Object}] The Hash of all attributes @since 0.2.0
attributes
ruby
cgriego/active_attr
lib/active_attr/attributes.rb
https://github.com/cgriego/active_attr/blob/master/lib/active_attr/attributes.rb
MIT
def inspect inspection_filter = PARAMETER_FILTER.new(filter_attributes) original_attributes = attributes filtered_attributes = inspection_filter.filter(original_attributes) attribute_descriptions = filtered_attributes.sort.map { |key, value| inspect_value = case when original_attributes[key].nil? then nil.inspect when value == FILTERED then FILTERED else value.inspect end "#{key}: #{inspect_value}" }.join(", ") separator = " " unless attribute_descriptions.empty? "#<#{self.class.name}#{separator}#{attribute_descriptions}>" end
Returns the class name plus its attributes @example Inspect the model. person.inspect @return [String] Human-readable presentation of the attribute definitions @since 0.2.0
inspect
ruby
cgriego/active_attr
lib/active_attr/attributes.rb
https://github.com/cgriego/active_attr/blob/master/lib/active_attr/attributes.rb
MIT
def read_attribute(name) if respond_to? name send name.to_s else raise UnknownAttributeError, "unknown attribute: #{name}" end end
Read a value from the model's attributes. @example Read an attribute with read_attribute person.read_attribute(:name) @example Rean an attribute with bracket syntax person[:name] @param [String, Symbol, #to_s] name The name of the attribute to get. @return [Object] The value of the attribute. @raise [UnknownAttributeError] if the attribute is unknown @since 0.2.0
read_attribute
ruby
cgriego/active_attr
lib/active_attr/attributes.rb
https://github.com/cgriego/active_attr/blob/master/lib/active_attr/attributes.rb
MIT
def write_attribute(name, value) if respond_to? "#{name}=" send "#{name}=", value else raise UnknownAttributeError, "unknown attribute: #{name}" end end
Write a single attribute to the model's attribute hash. @example Write the attribute with write_attribute person.write_attribute(:name, "Benjamin") @example Write an attribute with bracket syntax person[:name] = "Benjamin" @param [String, Symbol, #to_s] name The name of the attribute to update. @param [Object] value The value to set for the attribute. @raise [UnknownAttributeError] if the attribute is unknown @since 0.2.0
write_attribute
ruby
cgriego/active_attr
lib/active_attr/attributes.rb
https://github.com/cgriego/active_attr/blob/master/lib/active_attr/attributes.rb
MIT
def attribute(name) @attributes ||= {} @attributes[name] end
Read an attribute from the attributes hash @since 0.2.1
attribute
ruby
cgriego/active_attr
lib/active_attr/attributes.rb
https://github.com/cgriego/active_attr/blob/master/lib/active_attr/attributes.rb
MIT
def attributes_map self.class.attribute_names.each_with_object({}) do |name, hash| hash[name] = yield(name) end end
Maps all attributes using the given block @example Stringify attributes person.attributes_map { |name| send(name).to_s } @yield [name] block called to return hash value @yieldparam [String] name The name of the attribute to map. @return [Hash{String => Object}] The Hash of mapped attributes @since 0.7.0
attributes_map
ruby
cgriego/active_attr
lib/active_attr/attributes.rb
https://github.com/cgriego/active_attr/blob/master/lib/active_attr/attributes.rb
MIT
def attribute(name, options={}) if dangerous_attribute_method_name = dangerous_attribute?(name) raise DangerousAttributeError, %{an attribute method named "#{dangerous_attribute_method_name}" would conflict with an existing method} else attribute! name, options end end
Defines an attribute For each attribute that is defined, a getter and setter will be added as an instance method to the model. An {AttributeDefinition} instance will be added to result of the attributes class method. @example Define an attribute. attribute :name @param (see AttributeDefinition#initialize) @raise [DangerousAttributeError] if the attribute name conflicts with existing methods @return [AttributeDefinition] Attribute's definition @since 0.2.0
attribute
ruby
cgriego/active_attr
lib/active_attr/attributes.rb
https://github.com/cgriego/active_attr/blob/master/lib/active_attr/attributes.rb
MIT
def attribute!(name, options={}) AttributeDefinition.new(name, options).tap do |attribute_definition| attribute_name = attribute_definition.name.to_s # Force active model to generate attribute methods remove_instance_variable("@attribute_methods_generated") if instance_variable_defined?("@attribute_methods_generated") define_attribute_methods([attribute_definition.name]) unless attribute_names.include? attribute_name remove_instance_variable("@attribute_names") if instance_variable_defined?("@attribute_names") attributes[attribute_name] = attribute_definition end end
Defines an attribute without checking for conflicts Allows you to define an attribute whose methods will conflict with an existing method. For example, Ruby's Timeout library adds a timeout method to Object. Attempting to define a timeout attribute using .attribute will raise a {DangerousAttributeError}, but .attribute! will not. @example Define a dangerous attribute. attribute! :timeout @param (see AttributeDefinition#initialize) @return [AttributeDefinition] Attribute's definition @since 0.6.0
attribute!
ruby
cgriego/active_attr
lib/active_attr/attributes.rb
https://github.com/cgriego/active_attr/blob/master/lib/active_attr/attributes.rb
MIT
def attribute_names @attribute_names ||= attributes.keys end
Returns an Array of attribute names as Strings @example Get attribute names Person.attribute_names @return [Array<String>] The attribute names @since 0.5.0
attribute_names
ruby
cgriego/active_attr
lib/active_attr/attributes.rb
https://github.com/cgriego/active_attr/blob/master/lib/active_attr/attributes.rb
MIT
def attributes @attributes ||= ActiveSupport::HashWithIndifferentAccess.new end
Returns a Hash of AttributeDefinition instances @example Get attribute definitions Person.attributes @return [ActiveSupport::HashWithIndifferentAccess{String => ActiveAttr::AttributeDefinition}] The Hash of AttributeDefinition instances @since 0.2.0
attributes
ruby
cgriego/active_attr
lib/active_attr/attributes.rb
https://github.com/cgriego/active_attr/blob/master/lib/active_attr/attributes.rb
MIT
def dangerous_attribute?(name) attribute_methods(name).detect do |method_name| allocate.respond_to?(method_name, true) end unless attribute_names.include? name.to_s end
Determine if a given attribute name is dangerous Some attribute names can cause conflicts with existing methods on an object. For example, an attribute named "timeout" would conflict with the timeout method that Ruby's Timeout library mixes into Object. @example Testing a harmless attribute Person.dangerous_attribute? :name #=> false @example Testing a dangerous attribute Person.dangerous_attribute? :nil #=> "nil?" @param name Attribute name @return [false, String] False or the conflicting method name @since 0.6.0
dangerous_attribute?
ruby
cgriego/active_attr
lib/active_attr/attributes.rb
https://github.com/cgriego/active_attr/blob/master/lib/active_attr/attributes.rb
MIT
def inspect inspected_attributes = attribute_names.sort attributes_list = "(#{inspected_attributes.join(", ")})" unless inspected_attributes.empty? "#{name}#{attributes_list}" end
Returns the class name plus its attribute names @example Inspect the model's definition. Person.inspect @return [String] Human-readable presentation of the attributes @since 0.2.0
inspect
ruby
cgriego/active_attr
lib/active_attr/attributes.rb
https://github.com/cgriego/active_attr/blob/master/lib/active_attr/attributes.rb
MIT
def attribute_methods(name) attribute_method_patterns.map { |matcher| matcher.method_name name } end
Expand an attribute name into its generated methods names @since 0.6.0
attribute_methods
ruby
cgriego/active_attr
lib/active_attr/attributes.rb
https://github.com/cgriego/active_attr/blob/master/lib/active_attr/attributes.rb
MIT
def inherited(subclass) super subclass.attributes = attributes.dup end
Ruby inherited hook to assign superclass attributes to subclasses @since 0.2.2
inherited
ruby
cgriego/active_attr
lib/active_attr/attributes.rb
https://github.com/cgriego/active_attr/blob/master/lib/active_attr/attributes.rb
MIT
def apply_defaults(defaults=attribute_defaults) @attributes ||= {} defaults.each do |name, value| # instance variable is used here to avoid any dirty tracking in attribute setter methods @attributes[name] = value unless @attributes.has_key? name end end
Applies the attribute defaults Applies all the default values to any attributes not yet set, avoiding any attribute setter logic, such as dirty tracking. @example Usage class Person include ActiveAttr::AttributeDefaults attribute :first_name, :default => "John" def reset! @attributes = {} apply_defaults end end person = Person.new(:first_name => "Chris") person.reset! person.first_name #=> "John" @param [Hash{String => Object}, #each] defaults The defaults to apply @since 0.5.0
apply_defaults
ruby
cgriego/active_attr
lib/active_attr/attribute_defaults.rb
https://github.com/cgriego/active_attr/blob/master/lib/active_attr/attribute_defaults.rb
MIT
def attribute_defaults attributes_map { |name| _attribute_default name } end
Calculates the attribute defaults from the attribute definitions @example Usage class Person include ActiveAttr::AttributeDefaults attribute :first_name, :default => "John" end Person.new.attribute_defaults #=> {"first_name"=>"John"} @return [Hash{String => Object}] the attribute defaults @since 0.5.0
attribute_defaults
ruby
cgriego/active_attr
lib/active_attr/attribute_defaults.rb
https://github.com/cgriego/active_attr/blob/master/lib/active_attr/attribute_defaults.rb
MIT
def _attribute_default(attribute_name) default = self.class.attributes[attribute_name][:default] case when default.respond_to?(:call) then instance_exec(&default) when default.duplicable? then default.dup else default end end
Calculates an attribute default @private @since 0.5.0
_attribute_default
ruby
cgriego/active_attr
lib/active_attr/attribute_defaults.rb
https://github.com/cgriego/active_attr/blob/master/lib/active_attr/attribute_defaults.rb
MIT
def initialize(name, options={}) raise TypeError, "can't convert #{name.class} into Symbol" unless name.respond_to? :to_sym @name = name.to_sym @options = options end
Creates a new AttributeDefinition @example Create an attribute defintion AttributeDefinition.new(:amount) @param [Symbol, String, #to_sym] name attribute name @param [Hash{Symbol => Object}] options attribute options @return [ActiveAttr::AttributeDefinition] @since 0.2.0
initialize
ruby
cgriego/active_attr
lib/active_attr/attribute_definition.rb
https://github.com/cgriego/active_attr/blob/master/lib/active_attr/attribute_definition.rb
MIT
def inspect options_description = options.map { |key, value| "#{key.inspect} => #{value.inspect}" }.sort.join(", ") inspected_options = ", #{options_description}" unless options_description.empty? "attribute :#{name}#{inspected_options}" end
Returns the code that would generate the attribute definition @example Inspect the attribute definition attribute.inspect @return [String] Human-readable presentation of the attribute definition @since 0.6.0
inspect
ruby
cgriego/active_attr
lib/active_attr/attribute_definition.rb
https://github.com/cgriego/active_attr/blob/master/lib/active_attr/attribute_definition.rb
MIT
def initialize(*) super yield self if block_given? end
Initialize a model and build via a block @example person = Person.new do |p| p.first_name = "Chris" p.last_name = "Griego" end person.first_name #=> "Chris" person.last_name #=> "Griego" @since 0.3.0
initialize
ruby
cgriego/active_attr
lib/active_attr/block_initialization.rb
https://github.com/cgriego/active_attr/blob/master/lib/active_attr/block_initialization.rb
MIT
def append_features(base) if base.respond_to? :superclass base = base.superclass while !BASE_OBJECTS.include? base.superclass end super end
Only append the features of this module to the class that inherits directly from one of the BASE_OBJECTS @private
append_features
ruby
cgriego/active_attr
lib/active_attr/chainable_initialization.rb
https://github.com/cgriego/active_attr/blob/master/lib/active_attr/chainable_initialization.rb
MIT
def assign_attributes(new_attributes, options={}) sanitized_new_attributes = sanitize_for_mass_assignment_if_sanitizer new_attributes, options sanitized_new_attributes.each do |name, value| writer = "#{name}=" send writer, value if respond_to? writer end if sanitized_new_attributes end
Mass update a model's attributes @example Assigning a hash person.assign_attributes(:first_name => "Chris", :last_name => "Griego") person.first_name #=> "Chris" person.last_name #=> "Griego" @param [Hash{#to_s => Object}, #each] new_attributes Attributes used to populate the model @param [Hash, #[]] options Options that affect mass assignment @option options [Symbol] :as (:default) Mass assignment role @option options [true, false] :without_protection (false) Bypass mass assignment security if true @since 0.1.0
assign_attributes
ruby
cgriego/active_attr
lib/active_attr/mass_assignment.rb
https://github.com/cgriego/active_attr/blob/master/lib/active_attr/mass_assignment.rb
MIT
def initialize(attributes=nil, options={}) assign_attributes attributes, options super end
Initialize a model with a set of attributes @example Initializing with a hash person = Person.new(:first_name => "Chris", :last_name => "Griego") person.first_name #=> "Chris" person.last_name #=> "Griego" @param (see #assign_attributes) @since 0.1.0
initialize
ruby
cgriego/active_attr
lib/active_attr/mass_assignment.rb
https://github.com/cgriego/active_attr/blob/master/lib/active_attr/mass_assignment.rb
MIT
def sanitize_for_mass_assignment_with_or_without_role(new_attributes, options) if method(:sanitize_for_mass_assignment).arity.abs > 1 sanitize_for_mass_assignment new_attributes, options[:as] || :default else sanitize_for_mass_assignment new_attributes end end
Rails 3.0 and 4.0 do not take a role argument for the sanitizer @since 0.7.0
sanitize_for_mass_assignment_with_or_without_role
ruby
cgriego/active_attr
lib/active_attr/mass_assignment.rb
https://github.com/cgriego/active_attr/blob/master/lib/active_attr/mass_assignment.rb
MIT
def query_attribute(name) if respond_to? "#{name}?" send "#{name}?" else raise UnknownAttributeError, "unknown attribute: #{name}" end end
Test the presence of an attribute See {Typecasting::BooleanTypecaster#call} for more details. @example Query an attribute person.query_attribute(:name) @param [String, Symbol, #to_s] name The name of the attribute to query @return [true, false] The presence of the attribute @raise [UnknownAttributeError] if the attribute is unknown @since 0.3.0
query_attribute
ruby
cgriego/active_attr
lib/active_attr/query_attributes.rb
https://github.com/cgriego/active_attr/blob/master/lib/active_attr/query_attributes.rb
MIT
def attribute_before_type_cast(name) @attributes ||= {} @attributes[name.to_s] end
Read the raw attribute value @example Reading a raw age value person.age = "29" person.attribute_before_type_cast(:age) #=> "29" @param [String, Symbol, #to_s] name Attribute name @return [Object, nil] The attribute value before typecasting @since 0.5.0
attribute_before_type_cast
ruby
cgriego/active_attr
lib/active_attr/typecasted_attributes.rb
https://github.com/cgriego/active_attr/blob/master/lib/active_attr/typecasted_attributes.rb
MIT
def attribute(name) typecast_attribute(_attribute_typecaster(name), super) end
Reads the attribute and typecasts the result @since 0.5.0
attribute
ruby
cgriego/active_attr
lib/active_attr/typecasted_attributes.rb
https://github.com/cgriego/active_attr/blob/master/lib/active_attr/typecasted_attributes.rb
MIT
def _attribute_typecaster(attribute_name) type = _attribute_type(attribute_name) self.class.attributes[attribute_name][:typecaster] || typecaster_for(type) or raise UnknownTypecasterError, "Unable to cast to type #{type}" end
Resolve an attribute typecaster @private @since 0.6.0
_attribute_typecaster
ruby
cgriego/active_attr
lib/active_attr/typecasted_attributes.rb
https://github.com/cgriego/active_attr/blob/master/lib/active_attr/typecasted_attributes.rb
MIT
def inspect inspected_attributes = attribute_names.sort.map { |name| "#{name}: #{_attribute_type(name)}" } attributes_list = "(#{inspected_attributes.join(", ")})" unless inspected_attributes.empty? "#{name}#{attributes_list}" end
Returns the class name plus its attribute names and types @example Inspect the model's definition. Person.inspect @return [String] Human-readable presentation of the attributes @since 0.5.0
inspect
ruby
cgriego/active_attr
lib/active_attr/typecasted_attributes.rb
https://github.com/cgriego/active_attr/blob/master/lib/active_attr/typecasted_attributes.rb
MIT