mojolicious / mojo-pg

Mojolicious :heart: PostgreSQL
https://metacpan.org/release/Mojo-Pg
Artistic License 2.0
99 stars 46 forks source link

[feature or bug request] specify the data type of params #30

Closed Logioniz closed 8 years ago

Logioniz commented 8 years ago

I write test where need to specify type to correctly save data

#!/usr/bin/perl
use Mojo::Base -strict;

use Test::More;
use Mojo::Pg;

my $db = Mojo::Pg->new('postgresql://logioniz@/test')->db;

$db->query('drop table if exists test');
$db->query('create table test(data bytea)');

my $data_hex = '255044462d312e340a25d3f4cce10a312030206f626a0a3c3c0a2f4372656174696f6e4461746528443a32303136303232303030333135382b30332730302729';
my $data = pack 'H*', $data_hex;

$db->query('insert into test values (?)', $data);

my $data2 = $db->query('select * from test')->hash->{data};
my $data2_hex = join '', unpack 'H*', $data2;

is $data2_hex, $data_hex;

$db->query('truncate test');

######### Correct code below  ##########

my $dbh = $db->dbh;
my $sth = $dbh->prepare(q{insert into test values (?)});
$sth->bind_param(1, $data, {pg_type => DBD::Pg::PG_BYTEA});
$sth->execute;

$data2 = $db->query('select * from test')->hash->{data};
$data2_hex = join '', unpack 'H*', $data2;

is $data2_hex, $data_hex;

done_testing;

Expected behavior

I think that need to specify the type of the passed parameters. May be as json type something like this

$db->query('insert into test values (?)', {param => $data, type => DBD::Pg::PG_BYTEA});
kraih commented 8 years ago

Pretty sure PostgreSQL type annotations can already do the job just fine.

Logioniz commented 8 years ago

Sorry, can't understand. Can you show a working example of usage?

kraih commented 8 years ago

This question really should have been asked on the mailing-list or IRC, so i will not go into great detail here. But the right query should look something like insert into test values (?::bytea).

Logioniz commented 8 years ago

Thanks :+1: