Last active
July 27, 2016 17:30
-
-
Save mfilej/481f1d48484fa1cd568b1e601c4f5346 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env ruby | |
# Assumes `psql` is able to run without additional arguments on your machine. | |
# This usually means you need to have a database name that matches your | |
# username. | |
Prefixes = %w[k M G] | |
Prefix = Struct.new :to_s do | |
def <=>(other) | |
Prefixes.index(to_s) <=> Prefixes.index(other.to_s) | |
end | |
end | |
Db = Struct.new :name, :size, :unit do | |
def initialize(name, size) | |
super name, size.to_i, Prefix.new(size[-2]) | |
end | |
def valid? | |
size.nonzero? | |
end | |
def <=>(other) | |
unit_comparison = unit <=> other.unit | |
if unit_comparison.zero? | |
size <=> other.size | |
else | |
unit_comparison | |
end | |
end | |
def to_s | |
"#{name.ljust(30)} #{size.to_s.rjust(5)} #{unit}B" | |
end | |
end | |
line_to_db = ->(line) { | |
name, size = line.split("|").map(&:strip).values_at(0, 6) | |
Db.new(name, size) | |
} | |
parse_psql_output = ->(_) { | |
_ | |
.each_line | |
.drop_while { |l| !l.start_with? "---" } | |
.drop(1) | |
.take_while { |l| !l.start_with? "(" } | |
.map(&line_to_db) | |
.select(&:valid?) | |
.sort | |
.reverse | |
} | |
puts IO.popen('psql -c "\l+"', &parse_psql_output) |
Author
mfilej
commented
Jul 27, 2016
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment