CREATE TABLE students (
name TEXT NOT NULL PRIMARY KEY,
hometown TEXT NOT NULL,
grade TEXT,
data JSONB NOT NULL DEFAULT '{}'::jsonb
);
####
use Mojo::Pg;
my $pg = Mojo::Pg->new('postgres://localhost:54321/testing')
->password('BarFoo');
$pg->db->insert('students', {
name => 'Bob Kowalski',
hometown => 'Vero Beach, FL',
data => { -json => {
hobbies => [ 'ham radio', 'Python programming', 'running' ],
} },
});
$pg->db->insert('students', {
name => 'Kranessa Evans',
hometown => 'Dallas, TX',
data => { -json => {
hobbies => [ 'Perl programming', 'writing', 'polo' ],
} },
});
my $res = $pg->db->select('students')->expand;
while ( my $rec = $res->hash ) {
if ( grep {/perl/i} @{ $rec->{data}{hobbies} } ) {
$pg->db->update('students', { grade=>'A' },
{ name=>$rec->{name} } );
}
}
$res->finish;
##
##
$ docker run --rm -p54321:5432 --name pgtestdb -e POSTGRES_PASSWORD=FooBar -d postgres:13
# wait a few seconds for it to start
$ echo "CREATE USER $USER PASSWORD 'BarFoo'; CREATE DATABASE testing; GRANT ALL PRIVILEGES ON DATABASE testing TO $USER;" | psql postgresql://postgres:FooBar@localhost:54321
$ psql postgres://localhost:54321/testing
# log in and create the above table
# run the above Perl script
$ PGPASSWORD=BarFoo psql postgres://localhost:54321/testing -c 'SELECT * FROM students'
$ docker stop pgtestdb