module PgCtrl module Utils def set_opts(opts, *attrs) attrs.map { |a| self.instance_variable_set("@#{a}", opts[a]) } end end class RDBMSObjectSet def initialize @by_name = {} @by_oid = {} end def size() @by_name.size end def empty?() @by_name.empty? end def [](key) Fixnum === key ? @by_oid[key] : @by_name[key] end def add(value) @by_oid[value.oid] = @by_name[value.name] = value end def keys() @by_name.keys end def values() @by_name.values end def each(&block) @by_name.each(&block) end def map(&block) @by_name.map(&block) end end class RDBMS LOAD_USERS_QUERY = %( select oid as OID, rolname as NAME, rolsuper as IS_SUPERUSER, rolcreaterole as CAN_CREATE_ROLE, rolcreatedb as CAN_CREATE_DB, rolcanlogin as CAN_LOGIN, case when rolname = current_user then true else false end as IS_CURRENT_USER from pg_roles ) def load_users @connection.each_hash(LOAD_USERS_QUERY) { |r| @users.add User.new(self, r[:oid], r[:name], r) @user = @users[r[:name]] if r[:is_current_user] } end LOAD_DATABASES_QUERY = %( select pg_database.oid as OID, datname as NAME, rolname as OWNER, pg_encoding_to_char(encoding) as ENCODING, datcollate as LC_COLLATE, datctype as LC_CTYPE, datistemplate as IS_TEMPLATE, datallowconn as CAN_CONNECT, datacl as ACL, case when datname = current_database() then true else false end as IS_CURRENT_DATABASE from pg_database join pg_roles on datdba = pg_roles.oid ) def load_databases @connection.each_hash(LOAD_DATABASES_QUERY) { |r| @databases.add \ Database.new(self, r[:oid], r[:name], @users[r[:owner]], r) @database = @databases[r[:name]] if r[:is_current_database] } end def load_data @users = RDBMSObjectSet.new @databases = RDBMSObjectSet.new load_users load_databases end end end