Cassan...:Client(3pm)

🌸 Cassan...:Client(3pm) 🌸

okay bestie, come SIT. this is the manual page for Cassandra::Client, from the User Contributed Perl Documentation set β€” you'll see it filed as Cassan...:Client(3pm) on your system, which is just the terminal being dramatic and cutting the name off. it's the whole vibe, we move.


✨ NAME ✨

Cassandra::Client β€” a Perl library that talks to Cassandra through its binary network protocol. yes, the native one. no cap. πŸ’…


πŸŽ€ VERSION πŸŽ€

version 0.21 β€” she's grown, she's thriving 🫢


πŸ’– DESCRIPTION πŸ’–

Cassandra::Client is a Perl library that hands you access to the Cassandra database through the native protocol. both synchronous and asynchronous querying are supported, and there's a whole wardrobe of common calling styles to pick from. it's giving options. it's giving flexibility. obsessed. ✨


πŸ¦‹ EXAMPLE πŸ¦‹

here's the whole thing in one screenshot of a vibe:

use Cassandra::Client;
my $client= Cassandra::Client->new(
    contact_points => [ '127.0.0.1', '192.168.0.1' ],
    username => "my_user",
    password => "my_password",
    keyspace => "my_keyspace",
);
$client->connect;

$client->each_page("SELECT id, column FROM my_table WHERE id=?", [ 5 ], undef, sub {
    for my $row (@{shift->rows}) {
        my ($id, $column)= @$row;
        say "$id: $column";
    }
});

see how easy that was?? we love a low-effort slay 🌈


πŸ‘‘ METHODS πŸ‘‘

πŸ’œ Cassandra::Client->new(%options)

makes you a brand-new Cassandra::Client instance with the options you passed. here's the menu, and yes you should read all of it, i'm not summarising, that's not the kind of friend i am:

  • contact_points β€” Required. an arrayref of seed hosts to use when connecting. specify more than one for increased reliability. the array gets shuffled before use, so that random hosts are picked from it. sneaky. iconic.
  • keyspace β€” the default keyspace to use on all underlying connections. can be overridden by querying for specific keyspaces, e.g. SELECT * FROM system.peers.
  • anyevent β€” should our internal event loop be based on AnyEvent, or should we just use our own? a true value means enable AnyEvent. needed for promises to work. iykyk.
  • port β€” port number to use. defaults to 9042.
  • cql_version β€” CQL version to use. defaults to the version the server is running. only override this if your client has specific CQL requirements. don't be a hero.
  • compression β€” compression method to use. defaults to the best available version, based on server and client support. possible values are "snappy", "lz4", and "none".
  • default_consistency β€” default consistency level to use. defaults to "one". can also be overridden on a query basis, by passing a "consistency" attribute.
  • default_idempotency β€” the default value of the "idempotent" query attribute, which indicates whether a write query may be retried without harm. it defaults to false.
  • max_page_size β€” the default max page size to pass to the server. this defaults to 5000. note that large values can cause trouble on Cassandra. can be overridden by passing "page_size" in query attributes.
  • max_connections β€” the maximum amount of connections to keep open in the Cassandra connection pool. defaults to 2 for historical reasons, so raise this if it's appropriate for you. do her a favour πŸ’…
  • timer_granularity β€” the timer granularity used for timeouts. defaults to 0.1 (that's 100ms). change this if you're setting timeouts to values lower than a second.
  • request_timeout β€” the maximum time to wait for a query, in seconds. defaults to 11.
  • warmup β€” whether to connect to the full cluster in connect(), or delay that until queries come in.
  • protocol_version β€” the Cassandra protocol version to use. currently defaults to 4, and can also be set to 3 for compatibility with older versions of Cassandra.

🌟 $client->batch($queries[, $attributes])

run one or more queries, in a batch, on Cassandra. queries must be specified as an arrayref of [$query, \@bind] pairs. yes, pairs. nested. we contain multitudes.

it defaults to a logged batch, which can be overridden by passing "logged", "unlogged" or "counter" as the "batch_type" attribute.

$client->batch([
    [ "INSERT INTO my_table (a, b) VALUES (?, ?)", [ $row1_a, $row1_b ] ],
    [ "INSERT INTO my_table (a, b) VALUES (?, ?)", [ $row2_a, $row2_b ] ],
], { batch_type => "unlogged" });

🌸 $client->execute($query[, $bound_parameters[, $attributes]])

executes a single query on Cassandra and fetches the results (if there are any).

okay but listen: for queries that have large amounts of result rows and end up spanning multiple pages, each_page is the function you need. execute does not handle pagination, and may end up missing rows unless pagination is implemented by its user through the "page" attribute. do not ignore me on this one bestie 😭
$client->execute(
    "UPDATE my_table SET column=:new_column WHERE id=:id",
    { new_column => 2, id => 5 },
    { consistency => "quorum" },
);

the "idempotent" attribute indicates that the query is idempotent and may be retried without harm. love a query that can survive a little tumble 🫢

🧚 $client->each_page($query, $bound_parameters, $attributes, $page_callback)

executes a query and invokes $page_callback with each page of the results, represented as Cassandra::Client::ResultSet objects.

# Downloads the entire table from the database, even if it's terabytes in size
$client->each_page( "SELECT id, column FROM my_table", undef, undef, sub {
    my $page= shift;
    for my $row (@{$page->rows}) {
        say $row->[0];
    }
});

the way that comment says "even if it's terabytes in size" and just... means it. πŸ’€

⭐ $client->prepare($query)

prepares a query on the server. execute and each_page already do this internally, so this method is only useful for preloading purposes (and to check whether queries even compile, i guess). shutting the front door after the party, but make it valid.

πŸŽ€ $client->shutdown()

disconnect all connections and abort all current queries. after this, the Cassandra::Client object considers itself shut down and must be reconstructed with new(). she's gone, she's not coming back, you need a whole new her 🫢

πŸ’« $client->wait_for_schema_agreement()

wait until all nodes agree on the schema version. useful after changing table or keyspace definitions. it's giving "are we all on the same page? good." ✨


🌈 (A?)SYNCHRONOUS 🌈

it's up to you, the user, to choose which calling style to use: synchronous, asynchronous with promises, or through returned coderefs. pick your fighter πŸ’…

πŸ’– Synchronous

all Cassandra::Client methods are available as synchronous methods by using their normal names. for example, $client->connect(); will block until the client has connected. similarly, $client->execute($query) will wait for the query response. these are arguably not the fastest variants (there's no parallelism in queries) but certainly the most convenient. it's giving comfy.

my $client= Cassandra::Client->new( ... );
$client->connect;
$client->execute("INSERT INTO my_table (id, value) VALUES (?, ?) USING TTL ?",
    [ 1, "test", 86400 ],
    { consistency => "quorum" });

✨ Promises

Cassandra::Client methods are also available as promises (see perldoc AnyEvent::XSPromises). this integrates well with other libraries that deal with promises or asynchronous callbacks. note that for promises to work, AnyEvent is required, and needs to be enabled by passing anyevent => 1 to Cassandra::Client->new().

promise variants are available by prefixing method names with async_, e.g. async_connect, async_execute, etc. the usual result of the method is passed to the promise's success handler, or to the failure handler if there was an error.

# Asynchronously pages through the result set, processing data as it comes in.
my $promise= $client->async_each_page("SELECT id, column FROM my_table WHERE id=?", [ 5 ], undef, sub {
    for my $row (@{shift->rows}) {
        my ($id, $column)= @$row;
        say "Row: $id $column";
    }
})->then(sub {
    say "We finished paging through all the rows";
}, sub {
    my $error= shift;
});

promises normally get resolved from event loops, so for this to work you need one. normally you would deal with that by collecting all your promises and then waiting for that:

use AnyEvent::XSPromises qw/collect/;
use AnyEvent;

my @promises= ( ... ); # See other examples
my $condvar= AnyEvent->condvar;

collect(@promises)->then(sub {
    $condvar->send;
}, sub {
    my $error= shift;
    warn "Unhandled error! $error";
    $condvar->send;
});
$condvar->recv; # Wait for the promsie to resolve or fail

how you integrate this into your infrastructure is of course up to you, and beyond the scope of the Cassandra::Client documentation. that's a you problem, gorgeous πŸ’œ

πŸ¦‹ Coderefs

these are the simplest form of asynchronous querying in Cassandra::Client. instead of dealing with complex callback resolution, the client simply returns a coderef that, once invoked, returns what the original method would have retruned.

the variants are available by prefixing method names with future_, e.g. future_connect, future_execute, etc. these methods return a coderef.

my $coderef= $client->future_execute("INSERT INTO table (id, value) VALUES (?, ?), [ $id, $value ]);

# Do other things
...

# Wait for the query to finish
$coderef->();

upon errors, the coderef will die, just like the synchronous methods would. because of this, invoking the coderef immediately after getting it is equal to using the synchronous methods:

# This :
$client->connect;

# Is the same as :
$client->future_connect->();

when used properly, coderefs can give a modest performance boost, but their real value is in the ease of use compared to promises. lowkey the chill one of the group 🌸


πŸ’€ CAVEATS, BUGS, TODO πŸ’€

  • thread support is untested. use at your own risk. πŸ™ˆ
  • the "timestamp" format is implemented naively by returning milliseconds since the UNIX epoch. in Perl you get this number through time() * 1000. trying to save times as DateTime objects or strings will not work, and will likely result in warnings and unexpected behavior.

πŸ‘‘ AUTHOR πŸ‘‘

Tom van der Woerdt <tvdw@cpan.org> β€” thank you for your service, king 🫢


this software is copyright (c) 2023 by Tom van der Woerdt.

this is free software; you can redistribute it and/or modify it under the same terms as the Perl 5 programming language system itself. free as in go off πŸ’…


and that's the whole page, bestie. this one's filed under perl v5.42.3, dated 2026-08-22, in the Cassan...:Client(3pm) manual. go forth and query responsibly. periodt. πŸ’–βœ¨

πŸ“¦ where this page comes from