Skip to content

Instantly share code, notes, and snippets.

@jorol
Forked from mbeijen/jsonb.pl
Last active August 29, 2015 14:22
Show Gist options
  • Save jorol/4ff8af8dd1c4f683e0b3 to your computer and use it in GitHub Desktop.
Save jorol/4ff8af8dd1c4f683e0b3 to your computer and use it in GitHub Desktop.
#!/usr/bin/perl
use strict;
use warnings;
use Data::Dumper;
use DBD::Pg 3.5.0;
my $dbh = DBI->connect("dbi:Pg:", '', '',
{
AutoCommit => 1,
RaiseError => 1,
PrintError => 1,
}) || die "Can't connect: $!\n";
if ( $dbh->{pg_server_version} < 90400 ) {
die "Please use against Postgresql 9.4 or later!\n";
}
$dbh->do('
CREATE TEMPORARY TABLE book (
title text not null,
info jsonb not null
);'
);
my $insert = "INSERT INTO book (title, info) VALUES (?, ?)";
my $sth = $dbh->prepare($insert);
$sth->execute('Our Uncle', '{"year": 1985, "category": "novel", "author": "Arnon Grunberg" }');
$sth->execute('The Wild Things', '{"year": 1999, "author": "Dave Eggers"}');
# get all book s that have a category set
my $res = $dbh->selectall_arrayref(
# first ? is 'exists' operator, second is bind parameter
'SELECT title FROM book WHERE info::jsonb \? ?',
# add a bind value
undef, 'category');
print Dumper ($res);
$dbh->disconnect;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment