Postgredis

 view release on metacpan or  search on metacpan

lib/Postgredis.pm  view on Meta::CPAN

package Postgredis;

use Mojo::Pg;
use v5.20;
use experimental 'signatures';
use strict;

our $VERSION=0.03;

sub new {
    my $s = shift;
    my @a = @_;
    my %args;
    %args = ( namespace => $_[0] ) if @_==1;
    bless \%args, $s;
}

sub namespace($s,$new=undef) {
    $s->{namespace} = $new if @_==2;
    $s->{namespace};
}

sub _pg($s) {
    state $db;
    return $db if defined($db);
    $db = Mojo::Pg->new;
    $ENV{PG_CONNECT_STR} and do { $db = $db->from_string( $ENV{PG_CONNECT_STR} ) };
    $ENV{PG_CONNECT_DSN} and do { $db = $db->dsn($ENV{PG_CONNECT_DSN}) };
    $db;
}

sub pg($s) { $s->_pg->db; }

sub _create_tables($s) {
    my $table = $s->namespace;
    $s->_query(<<DONE);
    create table $table (
        k varchar not null primary key,
        v jsonb
    )
DONE
    $s->_query(<<DONE);
    create table $table\_sorted (
        k varchar not null,
        v jsonb not null,
        score real not null,
    primary key (k, v)
    )
DONE
    $s->_query(<<DONE);
    create index on $table\_sorted (k,score)
DONE
}

sub _drop_tables($s) {
    my $table = $s->namespace;
    $s->_query("drop table if exists $table");
    $s->_query("drop table if exists $table\_sorted");
}

sub _tables_exist($s) {
    my $res = $s->_query(q[select 1 from information_schema.tables where table_name = ?],
		$s->namespace);
	return $res->rows > 0;
}

sub _query($s,$str, @more) {
    my $namespace = $s->namespace;
    $str =~ s/\bredis\b/$namespace/;
    $str =~ s/\bredis_sorted\b/$namespace\_sorted/;
    return $s->pg->query($str, @more);
}

sub maybe_init($s) {
	$s->flushdb unless $s->_tables_exist;
    $s;
}

sub flushdb($s) {
    $s->_drop_tables if $s->_tables_exist;
    $s->_create_tables;
    return $s;
}

sub default_ttl { }

sub set($s,$key,$value) {
  my $res;
  $res = $s->_query("update redis set v = ?::jsonb where k = ?", { json => $value }, $key);
  return 1 if $res->rows > 0;
  $s->_query("insert into redis (k, v) values (?,?::jsonb)", $key, { json => $value } );
  return 1;



( run in 1.956 second using v1.01-cache-2.11-cpan-5c0b1e786e0 )