App-Environ-ClickHouse-Proxy

 view release on metacpan or  search on metacpan

lib/App/Environ/ClickHouse/Proxy.pm  view on Meta::CPAN

package App::Environ::ClickHouse::Proxy;

our $VERSION = '0.5';

use strict;
use warnings;
use v5.10;
use utf8;

use App::Environ;
use App::Environ::Config;
use Carp qw( carp croak );
use Cpanel::JSON::XS;
use IO::Socket;

my $INSTANCE;

my $JSON = Cpanel::JSON::XS->new->utf8;

App::Environ::Config->register(qw(clickhouse_proxy.yml));

sub instance {
  my $class = shift;

  unless ($INSTANCE) {
    my $config = App::Environ::Config->instance;

    my $sock = IO::Socket::INET->new(
      Proto    => 'udp',
      PeerAddr => $config->{clickhouse_proxy}{host},
      PeerPort => $config->{clickhouse_proxy}{port},
    ) or croak("Could not create socket: $!");

    $INSTANCE = bless { sock => $sock }, $class;
  }

  return $INSTANCE;
}

sub send {
  my __PACKAGE__ $self = shift;
  my $query = shift;

  no warnings 'numeric';

  my @types;
  foreach (@_) {
    if ( defined($_)
      && length( ( my $dummy = '' ) & $_ )
      && 0 + $_ eq $_
      && $_ * 0 == 0 )
    {
      if (/^[+-]?\d+\z/) {
        push @types, 'int';
      }
      else {
        push @types, 'float';
      }
    }
    else {
      push @types, 'string';
    }
  }

  use warnings 'numeric';

  my %val = (
    query   => $query,
    data    => \@_,
    types   => \@types,
    version => 1,
  );

  $self->{sock}->send( $JSON->encode( \%val ) ) or carp("Send error: $!");

  return;
}



( run in 0.872 second using v1.01-cache-2.11-cpan-39bf76dae61 )