Code Monkey home page Code Monkey logo

php-cassandra's Introduction

duoshuo duoshuo.com apis npm

a duoshuo SDK in Node.js

How to install

$ npm install duoshuo

Example

var Duoshuo = require('duoshuo')

var duoshuo = new Duoshuo({
  short_name: 'abc', // 站点申请的多说二级域名。
  secret: 'xxx' // 站点密钥
})

// Auth
duoshuo
  .auth(code)
  .then(function(access_token){
    console.log(access_token)
  })
  .catch(function(err){
    console.error(err)
  })

// 通过duoshuo.auth获得的access_token
var access_token = 'xxxxxxxxxxxxxxxxxx'
var client = duoshuo.getClient(access_token)

// Join local user to duoshuo.com
client.join({
  user: {},
}).then(function(user) {
  console.log(user)
}).catch(function(err){
  console.log(err)
})

// Fetch top articles
client.tops({
  range: 'daily' // 获取本日,详见:http://dev.duoshuo.com/docs/50398b4b8551ece011000023
  num_items: 10 // 获取10篇
}).then(function(err, threads) {
  console.log(threads)
})

// Push comments to duoshuo.com
client.comment({
  message: '我的一条新匿名评论'   
}).then(function(err, comment) {
  console.log(comment)
})

Tests

$ npm test

php-cassandra's People

Contributors

13leaf avatar evseevnn avatar flexbed avatar maliemin-mstar avatar mikicaivosevic avatar perfect-web avatar sebastiankalwa avatar shen2 avatar steambao avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

php-cassandra's Issues

Consistency for authentification

It looks like it's impossible to authenticate with a different consistency except QUORUM.
Bad credentials: org.apache.cassandra.exceptions.UnavailableException: Cannot achieve consistency level QUORUM.

To avoid all headaches, I suggest setting default consistency to ONE instead of QUORUM.

Tag new version

I do not want to use dev-master version in composer but I'd like to get these fixes b41598e

Is it about time for v0.6.0?

Write_timeout

I met this issue when I run a php thread with Cassandra:

Write_timeout. Error data: array (
'consistency' => 3166064,
'node' => 1701994868,
'replica' => 1768910368,
'writeType' => 'med out - received only 0 responses.' . "\0" . '' . "\0" . '' . "\0" . '' . "\0" . '' . "\0" . '' . "\0" . '' . "\0" . '' . "\0" . '' . "\0" . 'BATCH',
)

Can you explain why and how to fix it?

Array host

I use Cassandra with PasswordAuthenticator. When I try to connect to localhost with credentials ...

$nodes = array(
    array(
        'host'      => '127.0.0.1',
        'port'      => 9042,
        'username'  => 'cassandra',
        'password'  => 'cassandra',
        'socket'    => array(
            SO_RCVTIMEO => array("sec" => 3, "usec" => 0),
        )
    )
);

$connection = new Cassandra\Connection($nodes, 'system');

$response = $connection->querySync('SELECT * FROM schema_keyspace');

var_dump($response);

and I got a exception

PHP Warning:  socket_set_option(): unable to set socket option [92]: Protocol not available in /home/tarik/Desktop/cass/vendor/duoshuo/php-cassandra/src/Connection/Node.php on line 56
PHP Warning:  socket_connect() expects parameter 2 to be string, array given in /home/tarik/Desktop/cass/vendor/duoshuo/php-cassandra/src/Connection/Node.php on line 58
PHP Notice:  Array to string conversion in /home/tarik/Desktop/cass/vendor/duoshuo/php-cassandra/src/Connection/Node.php on line 59
PHP Notice:  Array to string conversion in /home/tarik/Desktop/cass/vendor/duoshuo/php-cassandra/src/Connection/Node.php on line 59
PHP Fatal error:  Uncaught exception 'Cassandra\Exception' with message 'Unable to connect to all Cassandra nodes.' in /home/tarik/Desktop/cass/vendor/duoshuo/php-cassandra/src/Connection.php:81
Stack trace:
#0 /home/tarik/Desktop/cass/vendor/duoshuo/php-cassandra/src/Connection.php(204): Cassandra\Connection->_connect()
#1 /home/tarik/Desktop/cass/vendor/duoshuo/php-cassandra/src/Connection.php(225): Cassandra\Connection->connect()
#2 /home/tarik/Desktop/cass/vendor/duoshuo/php-cassandra/src/Connection.php(319): Cassandra\Connection->syncRequest(Object(Cassandra\Request\Query))
#3 /home/tarik/Desktop/cass/index.php(18): Cassandra\Connection->querySync('SELECT * FROM s...')
#4 {main}
  thrown in /home/tarik/Desktop/cass/vendor/duoshuo/php-cassandra/src/Connection.php on line 81

PHP Fatal error: Class Cassandra\Type\Exception cannot extend from interface Cassandra\Exception

PHP Fatal error: Class Cassandra\Type\Exception cannot extend from interface Cassandra\Exception in vendor/duoshuo/php-cassandra/src/Type/Exception.php on line 4
PHP Stack trace:

PHP 13. Cassandra\Request\Request::valuesBinary( )vendor/duoshuo/php-cassandra/src/Request/Batch.php:67
PHP 14. spl_autoload_call() vendor/duoshuo/php-cassandra/src/Request/Batch.php:129
PHP 15. Composer\Autoload\ClassLoader->loadClass() vendor/duoshuo/php-cassandra/src/Request/Batch.php:0
PHP 16. Composer\Autoload\includeFile() vendor/composer/ClassLoader.php:301

minor bugs

  1. In src/Request/Batch.php, _cconstruct():
    should be:
    $this->_batchType = $type === null ? Batch::TYPE_LOGGED : $type;
  2. In src/Response/Result.php, fetchCol(), $columns seams undefined:
    foreach($columns as $j => $column){
    should be:
    foreach($this->_metadata['columns'] as $j => $column){
  3. In README.md, USING BATCH:
    Batch should require at least 2 queries. The example only shows 1 query. How should one set $preparedData['id'], $strictValues, and $batch (typo?)

About Blob

Hi All and Shen2

I downloaded this library months ago and have been using it since then. I decided to get new updates. Everything seems working well except blob column values returns NULL.

I realized that getValue function in Type\Blob.php returns NULL since the blob data is in $this->_binary variable not in $this->_value.

ORJINAL FUCNTION which returns NULL:
public function getValue(){
return $this->_value;
}

AFTER CHANGING (returns actual blob data):
public function getValue(){
return $this->_binary;
}

What is wrong here ? Am I wrong ?

Thanks in advance

socket_write result is not checked - partial write is possible

This issue is continue of SSL discussion #20

Currently functions _(a)syncRequest_ just do socket_write($this->connection, $request); without test return value, assuming that all data is always sent. This can lead to partial send.

Try following test:

$str ='';
for ($i=0;$i<10000000;$i++) $str .= '#';

$s = socket_create(AF_INET,SOCK_STREAM, SOL_TCP);
socket_set_option($s, SOL_SOCKET, SO_SNDTIMEO, ["sec" => 5, "usec" => 0]);

socket_connect($s,"php.net",80);
//socket_set_nonblock($s);

$sent = socket_write($s,$str);
echo "Sent ".$sent ." bytes\n";

If network upload is slow (I set limitation in virtual machine to 28 kbps) socket_write is returns after several seconds and $sent is about 50K. If socket_set_nonblock is uncommented socket_write is returned immediately and only 18K is sent.

The same happens in current php-cassandra code. Connect to remote server with slow connection, make _syncReqest_ and test socket_write result. It's extreme case, but if you send many long request via slow connection it can happen.

Now no non-blocking mode is used (and can not be used without usage some real async I/O mechanism, like dedicated I/O thread with socket_select) in php-cassandra, but partial send should be handled anyway, something like this:

    $reqstr = (string)$request;

    while(strlen($reqstr) >0)
    {
        $res = socket_write($this->connection, $reqstr);

        if ($res === false)
            throw new Exception(socket_strerror(socket_last_error()));

        $reqstr = substr($reqstr,$res);
    }

Basing on this I suggest to adopt my SSL addition with above fix. Stream performance is not issue at all.

Thanks.

32-bit PHP

I tried to use php-cassandra on Windows/XAMPP which only supports 32-bit PHP and the (de-)serialzation doesn't work. PHPCassa does a lot of bit-shift magic to support 32-bit - maybe you can reuse some of their findings?

Resource temporarily unavailable

I'm trying to connect to a cassandra cluster over internet, and no matter what i do i get this error
`Cassandra\Connection\Exception

Resource temporarily unavailable`

I'm trying to connect from my terminal via cqlsh as well and works
PS: port 9042 and 9160

Batch with prepared queries

Whenever I'm trying to use prepared queries in a batch, I get this error:

Exception in Error.php line 123:
Server error: java.lang.IndexOutOfBoundsException: index: 28, length: 749941 (expected: range(0, 137))

Here's what I'm executing:

$batchRequest = new Cassandra\Request\Batch(null, null, [
        'names_for_values' => true,
 ]);
$preparedData = $connection->prepare('INSERT INTO table (qid, rid, value, tsr, tsa)
VALUES (:qid,:rid,:value,:tsr,:tsa)');

$values = [
    'qid' => '1',
    'rid' => '1',
    'value' => '55',
    'tsr' => 1427225763000,
    'tsa' => 1427225763000,
];

$batchRequest->appendQueryId($preparedData['id'],
            Cassandra\Request\Request::strictTypeValues($values, $preparedData['metadata']['columns']));

$connection->syncRequest($batchRequest);

Am I missing something or is there an issue?

AuthResponse not handled when user is empty

When connecting to C* with password authentication configured but not providing user/password following message is thrown:

PHP Fatal error:  Uncaught exception 'Cassandra\Response\Exception' with message 'Server error: java.lang.AssertionError: org.apache.cassandra.exceptions.InvalidRequestException: Key may not be empty' in /root/workspace/cassandra/domain/drivers/php/php-cassandra/src/Response/Error.php:123

Actually _getResponse gets Frame::OPCODE_AUTHENTICATE, but doesn't handle it.

cqlsh shows
_Connection error: ('Unable to connect to any servers', {'127.0.0.1': AuthenticationFailed('Remote end requires authentication.',)})_ message

CONSISTENCY_ANY is not handle properly

In multiple files:
"$this->_consistency = $consistency ?: Request::CONSISTENCY_QUORUM;"

$this->_consistency will evaluate to CONSISTENCY_QUORUM when $consistency is CONSISTENCY_ANY (0).

One possible fix:
$this->_consistency = !is_null($consistency) ? $consistency : Request::CONSISTENCY_QUORUM

Question about blob size inserted at the beginning of a blob

We're having issues with inserting and retrieving blobs.

When blobs are inserted, the data size is added as a prefix in form of an 4 byte integer value is. This can be found here:

return pack('N', strlen($this->_value)) . $this->_value;

When data is retrieved from cassandra, this 4 bytes is present, and to make the content identical to what I insert, I will need to strip away the content substr($data, 4).

It seems likely to us that the correct behaviour should be to not prefix the data with the length, at least when we insert blobs with other (non-php) libraries the content is not prefixed.

I can send a pull request, but I wanted to ask about it first. Looking forwards to hear others opinions / experiences with this.

Please provide hints about how to use the Timestamp type

In the readme, the only example usage of Timestamp is this:

new Cassandra\Type\Timestamp(1409830696263000);

In my testing, this fails. Fails in a way that makes my cqlsh crash:

cqlsh:feideconnect> select * from oauth_tokens where access_token = cd9f4f86-0c96-4481-8ca6-abd1df3d2837
                ... ;
Traceback (most recent call last):
  File "/usr/bin/cqlsh", line 960, in perform_simple_statement
    rows = self.session.execute(statement, trace=self.tracing_enabled)
  File "/usr/share/cassandra/lib/cassandra-driver-internal-only-2.1.2.zip/cassandra-driver-2.1.2/cassandra/cluster.py", line 1294, in execute
    result = future.result(timeout)
  File "/usr/share/cassandra/lib/cassandra-driver-internal-only-2.1.2.zip/cassandra-driver-2.1.2/cassandra/cluster.py", line 2788, in result
    raise self._final_exception
ValueError: year is out of range

Reading the code, it seemed to me to be worth an attempt to use:

new Cassandra\Type\Timestamp(microtime(true));

This did not work properly. I got timestamps like this 1970-01-17 13:14:07+0100.

Next step then became:

new Cassandra\Type\Timestamp(microtime(true)*1000);
// Similar to 1426447763149.6

This is in fact providing milliseconds (as a float). Doc says microsecond, which would have been *1000000.

It is OK to me to work with milliseconds (even if not my first choice), however I am afraid it might change in the future. I also think it is inconsistent with the doc.

Resource temporarily unavailable

I got this exception when trying to execute query in BATCH mode with more than 5000 queries or sometime just a quey INSERT/UPDATE.

fetchData is hanging

I tried executing a simple query, but the socket_read is returning an empty string, which makes the remainder - strlen($readData) always equal 9, therefore the while loop is infinite.

For some reason the socket read is retuning always empty strings. I tested the same query with pdo_cassandra.so extension and it is working, I know it is not a subject of comparison but there is definitely a bug that I can't figure out in the package.

Type safety for int / float values

At the moment php-cassandra accepts \Cassandra\Type\Float() for an INT field and \Cassandra\Type\Int() for a FLOAT field. Passing value of the wrong type silently corrupts the data. For example:

  • \Cassandra\Type\Float(1.0) inserted to an INT field gives "1065353216"
  • \Cassandra\Type\Int(1) inserted to a FLOAT field gives "1.4013e-45"

Is there any way to check the types of the values inserted using the binary protocol?

Issue with connecting to 127.0.0.1 on Travis CI

I am very happy with the library so far, but I have a connection issue with Travis-CI where I'm having troubles understanding what is wrong.

Using sockets

When using duoshuo (with sockets) to connect to 127.0.0.1 on Travis-CI, it stalls forever :(

$keyspace = 'feideconnect';
$nodes = ['127.0.0.1'];

echo("connecting to nodes"); 
$db = new \Cassandra\Connection($nodes, $keyspace);

echo "Constructor done\n";
$db->connect();

echo "Connected done\n";

It is the connect() method that stalls.

Using stream

As an alternative, I tried with Stream instead of sockets, and instead of stalling/hanging, I get this:

PHP Fatal error:  Uncaught exception 'Cassandra\Connection\StreamException' with message 'Connection reset by peer' in /home/travis/build/andreassolberg/cassa-test/vendor/duoshuo/php-cassandra/src/Connection/Stream.php:70
Stack trace:
#0 /home/travis/build/andreassolberg/cassa-test/vendor/duoshuo/php-cassandra/src/Connection.php(149): Cassandra\Connection\Stream->read(12288)
#1 /home/travis/build/andreassolberg/cassa-test/vendor/duoshuo/php-cassandra/src/Connection.php(134): Cassandra\Connection->_getResponse()
#2 /home/travis/build/andreassolberg/cassa-test/vendor/duoshuo/php-cassandra/src/Connection.php(239): Cassandra\Connection->getResponse()
#3 /home/travis/build/andreassolberg/cassa-test/vendor/duoshuo/php-cassandra/src/Connection.php(211): Cassandra\Connection->syncRequest(Object(Cassandra\Request\Startup))
#4 /home/travis/build/andreassolberg/cassa-test/bin/duoshuo-stream.php(24): Cassandra\Connection->connect()
#5 {main}
  thrown in /home/travis/build/andreassolberg/cassa-test/vendor/duoshuo/php-cassandra/src/Connection/Stream.php on line 70

It is the feof($this->_stream) that returns true.

Connection\Stream.php:

        $readData = fread($this->_stream, $length);

        if (feof($this->_stream))
            throw new StreamException('Connection reset by peer');

In cases where connection is rejected at port 9042 because no service is listening, the code fails earlier on the fsockopen().

Using the evseevnn library

For comparison, I earlier used evseevnn, which works connecting to the same 127.0.0.1 on Travis CI.

$keyspace = 'feideconnect';
$nodes = ['127.0.0.1'];

echo("connecting to nodes"); 
$db = new \evseevnn\Cassandra\Database($nodes, $keyspace);

echo "Constructor done\n";
$db->connect();
echo "Connected done\n";

Test case running at Travis CI.

I have constructed a dedicated git repo to reconstruct this problem on Travis CI:

There is four scripts:

  • bin/duoshuo-socket.php - Duoshuo with socket Stalls / hangs
  • bin/duoshuo-stream.php - Duoshuo with stream Throws exception
  • bin/duoshuo-stream-persistent.php - Duoshuo with stream (persistent). Throws exception
  • bin/evseevnn.php - Evseevnn library. Works OK

Any ideas – of how to proceed debugging what is wrong?

Error connection

i'm using Google Cloud for Cassandra and when I'm trying to connect there is an error:
An existing connection was forcibly closed by the remote host.

I've open the Firewall so why the connection been closed?

Thanks!

Issue with unpacking decimal columns

When I try to select a column of type "decimal" I receive the an error when calling fetchAll() on the response relating to unpack().

$connection = new Cassandra\Connection($nodes, 'adapter_test');
$response = $connection->querySync('SELECT val_decimal FROM test_table WHERE id = ?;', ['abc']); 
var_dump($response->fetchAll());

unpack(): Type N: not enough input, need 4, have 2|/data/istock/vendor/duoshuo/php-cassandra/src/Response/StreamReader.php(251)

The table selected from...

CREATE TABLE adapter_test.test_table (
    id text PRIMARY KEY,
    val_bool boolean,
    val_decimal decimal,
    val_double double,
    val_float float,
    val_int int,
    val_text text,
    val_timestamp timestamp,
    val_timeuuid timeuuid,
    val_uuid uuid
) WITH bloom_filter_fp_chance = 0.01
    AND caching = '{"keys":"ALL", "rows_per_partition":"NONE"}'
    AND comment = ''
    AND compaction = {'min_threshold': '4', 'class': 'org.apache.cassandra.db.compaction.SizeTieredCompactionStrategy', 'max_threshold': '32'}
    AND compression = {'sstable_compression': 'org.apache.cassandra.io.compress.LZ4Compressor'}
    AND dclocal_read_repair_chance = 0.1
    AND default_time_to_live = 0
    AND gc_grace_seconds = 864000
    AND max_index_interval = 2048
    AND memtable_flush_period_in_ms = 0
    AND min_index_interval = 128
    AND read_repair_chance = 0.0
    AND speculative_retry = '99.0PERCENTILE';

Output from CQLSH...

cqlsh:adapter_test> SELECT val_decimal FROM test_table WHERE id = 'abc';

 val_decimal
-------------
       1.234

(1 rows)

Unable to run

Hi,
I am new to cassandra. I am trying to set up a connection to cassandra by php.
Although I am assigning username and password, still throws an exception i.e. Username and password required.

documentation

you forgot a quote here : 'connectTimeout => 10, // connection timeout, default 5, stream transport only

PLEASE!!! FIX RETURNED DATA TYPES!

    /**
     * 
     * @param string $cql
     * @param array $values
     * @param int $consistency
     * @param array $options
     * @throws Exception
     * @return Response\Response
     */
    public function querySync($cql, array $values = [], $consistency = null, array $options = []){
        $request = new Request\Query($cql, $values, $consistency === null ? $this->_consistency : $consistency, $options);

        return $this->syncRequest($request);
    }

Why there is Response\Response as return???
When there should be Response\Result !?!

Collection SET is broken

  1. Typo in src/Type/CollectionList.php:19
    $values should be $value
  2. Reading a non null column of type SET<> will return an empty array.
    • quick and dirty fix in src/Response/StreamReader.php:
      public function readList($valueType) {
      $list = [];
      $count = 4 * $this->readInt();
      for ($i = 0; $i < $count; $i += 2) {
      $x = $this->readByType($valueType, true);
      if (strlen($x) > 0) {
      $list[] = $x;
      }
      }
      return $list;
      }
      This will probably brake LIST. A more proper fix is required.
  3. It seams impossible to INSERT/UPDATE a collection SET.
    new Cassandra\Type\CollectionSet([1, 2, 3], Cassandra\Type\Base::INT); (as stated in Readme) most likely will never work as SET will allow only strings as part of collection.

PS:
I haven't tested MAP and LIST collections yet.

How to get data from last inserted row?

Trying to insert row with this cql: $cql='INSERT INTO test.posts (uuid, text, title) VALUES (now(), :text, :title)';
Trying to insert this through executeSync and querySync and want to get generated by Cassandra timeUUID by now() function. Is this possible? If not how can this achieved?

Cannot bind server configuration

I use version 0.5.2 and I cannot connect with the config below:

// Get config
$nodes = array(
    'host'     => '127.0.0.1',
    'port'     => 9042,
);

// Create a connection.
$this->_connection = new Cassandra\Connection($nodes, 'mykeyspace');

I spent 2 hours and find out the issue from this line:

if (is_array($nodes))
    shuffle($nodes);

in src\Connection.php

Cassandra uses milliseconds, not microseconds, as a unit for TIMESTAMPs

The https://github.com/duoshuo/php-cassandra/blob/master/README.md file says:

//  Timestamp (unit: microseconds)
new Cassandra\Type\Timestamp((int) (microtime(true) * 1000000));
new Cassandra\Type\Timestamp(1409830696263000);

But Cassandra uses milliseconds (1/1000), not microseconds (1/1000000):

http://docs.datastax.com/en/cql/3.1/cql/cql_reference/timestamp_type_r.html

"Values for the timestamp type are encoded as 64-bit signed integers representing a number of milliseconds since the standard base time known as the epoch: January 1 1970 at 00:00:00 GMT."

When I put a value in microseconds in a TIMESTAMP field, I get the following error when trying to read the fields value in cqlsh:

Traceback (most recent call last):
  File "/opt/cassandra/bin/cqlsh", line 997, in perform_simple_statement
    rows = self.session.execute(statement, trace=self.tracing_enabled)
  File "/opt/cassandra/bin/../lib/cassandra-driver-internal-only-2.1.3.post.zip/cassandra-driver-2.1.3.post/cassandra/cluster.py", line 1337, in execute
    result = future.result(timeout)
  File "/opt/cassandra/bin/../lib/cassandra-driver-internal-only-2.1.3.post.zip/cassandra-driver-2.1.3.post/cassandra/cluster.py", line 2861, in result
    raise self._final_exception
ValueError: year is out of range

Changing the value to milliseconds gives correct results.

Timestamp type column value is always "1970-..."

I'm trying to use the timestamp type, but I have always the value 1970-xx-xx xx:xx:xx.
Here my tests :

new Cassandra\Type\Timestamp(1409830696263000);
new Cassandra\Type\Timestamp(microtime(true)*1000);

But always got "1970..." date.
Here the info about versions & table :

[cqlsh 5.0.1 | Cassandra 2.1.3 | CQL spec 3.2.0 | Native protocol v3]

CREATE TABLE bar.foo_bar (
    user_id uuid,
    foo_id int,
    created_at timestamp,
    updated_at timestamp,
    PRIMARY KEY (user_id, foo_id)
) WITH CLUSTERING ORDER BY (foo_id ASC)
    AND bloom_filter_fp_chance = 0.01
    AND caching = '{"keys":"ALL", "rows_per_partition":"NONE"}'
    AND comment = ''
    AND compaction = {'min_threshold': '4', 'class': 'org.apache.cassandra.db.compaction.SizeTieredCompactionStrategy', 'max_threshold': '32'}
    AND compression = {'sstable_compression': 'org.apache.cassandra.io.compress.LZ4Compressor'}
    AND dclocal_read_repair_chance = 0.1
    AND default_time_to_live = 0
    AND gc_grace_seconds = 864000
    AND max_index_interval = 2048
    AND memtable_flush_period_in_ms = 0
    AND min_index_interval = 128
    AND read_repair_chance = 0.0
    AND speculative_retry = '99.0PERCENTILE';

How can I have a good value ?

Thanks :)

UDTs which have a field of type Set<UDT> throw exception 'Unknown type.' in Cassandra\Type\Base.php when running INSERT CQL

I have a UDT which has a SET of another type of UDT.

Example CQL:

CREATE TYPE part (
    name text,
    color text
);
CREATE TYPE car (
    make text,
    model text,
    parts set<frozen<part>>
);
CREATE TABLE IF NOT EXISTS cars(
    id timeuuid,
    data frozen<car>,
    PRIMARY KEY (id)
);

When running INSERT CQL, Notice: Unknown type. in Cassandra\Type\Base.php on line 140 is thrown (which then causes Fatal error: Call to a member function getBinary() on a non-object in Cassandra\Type\CollectionList.php on line 28).

I also tested UDT with a SET and a UDT with a single nested UDT, and these do not cause any issue... thus, I believe this only occurs with a nested set of UDTs (and possibly maps too)

[Edit] A set of UDTs causes the error regardless if nested or not.
[Edit] See my fix in pull request below

Cannot submit null value to strictTypeValues()

When binding, a query with a null valued parameter like this will fail:

$preparedData = $connection->prepare('INSERT INTO user(username, email) VALUES(:username, :email)');

        $strictValues = Request::strictTypeValues(
            [
                'username' => 'jsmith',
                'email' => null,
            ],
            $preparedData['metadata']['columns']
        );

$response = $connection->executeSync(
            $preparedData['id'],
            $strictValues,
            Request::CONSISTENCY_QUORUM,
            [
                'page_size' => 100,
                'names_for_values' => true,
                'skip_metadata' => true,
            ]
        );

The error reads:
'Invalid: there were 2 markers(?) in CQL but 1 bound variables'

This is because public static function strictTypeValues(array $values, array $columns) assigns the index as the key name in $values, rather than the associated name.

I have fixed this issue in my fork, see 7b02cc6

All string type columns return NULL

When i read back string columns (ascii, varchar, text) php-cassandra give back NULL values.

My test database:

cqlsh:testdb> CREATE TABLE strings (row_id timeuuid, t_ascii ascii, t_varchar varchar, t_text text, primary key (row_id));
cqlsh:testdb> INSERT INTO strings (row_id, t_ascii, t_varchar, t_text) VALUES ( now(), 'string 1', 'string 1', 'string 1');
cqlsh:testdb> INSERT INTO strings (row_id, t_ascii, t_varchar, t_text) VALUES ( now(), 'string 2', 'string 2', 'string 2');
cqlsh:testdb> INSERT INTO strings (row_id, t_ascii, t_varchar, t_text) VALUES ( now(), 'string 3', 'string 3', 'string 3');

My test php app:

<?php
require __DIR__ . '/vendor/autoload.php';
use \Cassandra\Request\Request;
use \Cassandra\Response\Result;

$nodes = [ '127.0.0.1','127.0.0.2','127.0.0.3'];

// Create a connection.
$connection = new Cassandra\Connection ( $nodes, 'testdb' );

// Connect
try {
    $connection->connect ();
} catch ( Cassandra\Exception $e ) {
    echo 'Caught exception: ', $e->getMessage (), "\n";
    exit (); // if connect failed it may be good idea not to continue
}

$connection->setConsistency ( Request::CONSISTENCY_LOCAL_QUORUM );

try {
    $response = $connection->querySync ( 'SELECT * FROM strings' );
} catch ( Cassandra\Exception $e ) {
}

// Return a SplFixedArray containing all of the result set.
$rows = $response->fetchAll();      // SplFixedArray

foreach ($rows as $row) {
    var_dump($row);
}

And the output is:

array(4) {
  ["row_id"]=>
  string(36) "af0e5d40-167f-11e5-9162-63ff094c156d"
  ["t_ascii"]=>
  NULL
  ["t_text"]=>
  NULL
  ["t_varchar"]=>
  NULL
}
array(4) {
  ["row_id"]=>
  string(36) "b533b2b0-167f-11e5-9162-63ff094c156d"
  ["t_ascii"]=>
  NULL
  ["t_text"]=>
  NULL
  ["t_varchar"]=>
  NULL
}
array(4) {
  ["row_id"]=>
  string(36) "b2353fc0-167f-11e5-9162-63ff094c156d"
  ["t_ascii"]=>
  NULL
  ["t_text"]=>
  NULL
  ["t_varchar"]=>
  NULL
}

Am I doing something wrong?

cassandra 2.1.3
PHP 5.5.24
OSX Yosemite 64bit

[RFC] Use datastax/php-driver as underlying communication layer

Hi,

Since DataStax now provide a native PHP extension for Cassandra ( github.com/datastax/php-driver ) - it could be nice if this library either deprecate itself, or start the official client as transport, and act as a compat layer to the new supported extension.

Any thoughts? :)

Getting PHP Warning: Declaration of Cassandra\Request\Batch::queryParameters($consistency, array $options = Array) should be compatible with Cassandra\Request\Request::queryParameters($consistency, array $values = Array, array $options = Array) in /var/www/html/php-cassandra/src/Request/Batch.php on line 122 for PHP7

PHP Warning: Declaration of Cassandra\Request\Batch::queryParameters($consistency, array $options = Array) should be compatible with Cassandra\Request\Request::queryParameters($consistency, array $values = Array, array $options = Array) in /var/www/html/php-cassandra/src/Request/Batch.php on line 122

Unexpected result

I have this table:

create table user (
    user_id uuid,
    user_activation_token uuid,
    user_status int,
    user_email varchar,
    user_timezone varchar,
    user_time_created timestamp,
    user_time_updated timestamp,
    user_time_last_login timestamp,
    primary key (user_id)
);

INSERT INTO user(
    user_id,
    user_activation_token,
    user_email,
    user_status,
    user_time_created,
    user_time_last_login,
    user_time_updated,
    user_timezone
)
 VALUES (
    798fc0e0-0b0e-11e5-9e5d-13eed59f735d,
    7f4fcc19-65c8-440f-8942-ed45c524dbc2,
    '[email protected]',
    0,
    1433710209253,
    0,
    0,
    'Europe/Prague'
);

but...

when I call "fetchRow()" I see this result:

array (size=8)
  'user_id' => string '798fc0e0-0b0e-11e5-9e5d-13eed59f735d' (length=36)
  'user_activation_token' => string '7f4fcc19-65c8-440f-8942-ed45c524dbc2' (length=36)
  'user_email' => string '[email protected]' (length=13)
  'user_status' => int 0
  'user_time_created' => int -808867347
  'user_time_last_login' => int 0
  'user_time_updated' => int 0
  'user_timezone' => string 'Europe/Prague' (length=13)

I try v0.5.2 and dev-master...

Support newer versions of Cassandra

In the README it says:

"Using Protocol v3 (Cassandra 2.1)"

Does it mean that the driver won't work with Casssandra 3.x? The 2.x line is supported only until November 2016.

Querying performance with synced prepared query

Hello,

I'm running a benchmark with your lib, and it is pretty good 👍
But, I have some performance issues with synced prepared queries :

// running this x10000, with random key value
$connection->querySync("SELECT * FROM keyspace.columnFamily where key = 'foo'");
// got response ~ 6.255 sec

and, from your example :

// running this x10000, with random key value, I known it's stupid to put the parameter directly in the query
$preparedData = $connection->prepare("SELECT * FROM keyspace.columnFamily where key = :keyValue");
$strictValues = [...];
$response = $con->executeSync($preparedData['id'], $strictValues, Cassandra\Request\Request::CONSISTENCY_ONE, [
    'page_size' => 100,
    'names_for_values' => true,
    'skip_metadata' => true,
]);
// got response ~ 23.331 sec

Why this difference ?

TL;DR: got 6.255 sec with querySync() and 23.331 sec with executeSync() on a x10000 loop for a single SELECT.

Thanks :)

Call to a member function readOnce() on null

When Cassandra instance stops responding in the middle of a connection, the following PHP error is generated:

PHP Fatal error: Call to a member function readOnce() on null in /www/vendor/duoshuo/php-cassandra/src/Response/StreamReader.php on line 52

Problematic line:

$this->data .= $received = $this->source->readOnce($this->totalLength - $this->dataLength);

Is it possible to handle this case by throwing an exception? Something like:

if($this->source === NULL) {
  throw new CassandraException('The source object is NULL - the connection to Cassandra is broken.');
}

Otherwise we can't catch this error and retry the request against a different Cassandra node.

names_for_values

php-cassandra relies on the user for specifying whether the query contains named parameters (rather than positional parameters): If the query option names_for_values is not set, names are ignored, and parameters are bound by their position in the array.

The following example results in a user with email and name exchanged in the table, because the parameters are not specified in the same order than in the VALUES clause:

<?php
$connection->querySync("
    INSERT INTO users (name, email) VALUES (:name, :email)
", array(
    "email" => $email,
    "name" => $name,
));

Could php-cassandra just detect that the passed array is associative ?

problem with running IN in where clause with array

I have table structure like this

CREATE TABLE mycdb.emp_details (
    id uuid PRIMARY KEY,
    age int,
    name text
)

and try to run CQL ad below

$ids = ['388caf5e-fdef-4922-9b73-88363a28140f', '0f6a5834-7194-45a7-9755-e28b20351af7']
$rs = $connection->querySync('select * from emp_details where id in(:ids)', ['ids' => $ids]);

its throw
Cassandra\Type\Exception with message '$values should be an sequential array, associative array given. Or you can set "names_for_values" option to true.'

correct me if i am wrong right now there is no any possibility to pass array in IN clause if not could we improve that.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.