Github.com anton terekhov-orientdb-php

1,016 views

Published on

Published in: Education, Technology
  • Be the first to comment

  • Be the first to like this

Github.com anton terekhov-orientdb-php

  1. 1. commit 07b69f4a45 Latest commit to the maste r branch Bumped to r4606 Ant onTerekhov authored January 18, 2012 Tags Downloads AntonTerekhov AntonTerekhov // OrientDB-PHP OrientDB-PHP Files Commits Branches 28 3 CodeCode Net workNet work Pull Request sPull Request s IssuesIssues St at s & GraphsSt at s & Graphs00 33 HTTPHTTP Git Re ad-OnlyGit Re ad-Only https://github.com/AntonTerekhov/OrientDB-PHP.git Re ad-Only access Binary protocol for OrientDB for PHP applications (Beta) — Read more http://code.google.com/p/orient/wiki/NetworkBinaryProtocol ZIPZIP 21mast ermast er 3 historyhistorynamename ageage messagemessage OrientDB January 17, 2012 Changed code to be compatible with protocol version 7 support. RECORD… [AntonTerekhov] SpeedTest November 29, 2011 New methods $record->reset() for reset all record fields and $record-… [AntonTerekhov] Tests January 18, 2012 Test aligned with r4597 [AntonTerekhov] .gitignore April 19, 2011 Added .gitignore [AntonTerekhov] LICENSE April 19, 2011 License file word-wrapped [AntonTerekhov] example.php May 16, 2011 Huge addition on PHPDoc blocks [AntonTerekhov] OrientDB-PHP / Signup and PricingSignup and Pricing Explore GitHubExplore GitHub FeaturesFeatures BlogBlog LoginLogin PDFmyURL.com
  2. 2. phpunit.xml November 29, 2011 Made PHPUnit verbose [AntonTerekhov] readme.markdown January 18, 2012 Bumped to r4606 [AntonTerekhov] speedtest.php May 16, 2011 Huge addition on PHPDoc blocks [AntonTerekhov] readme.markdownreadme.markdown OrientDB-PHP A plain PHP driver to OrientDB graph database using its binary protocol. Description Current status is: Beta. Code is licensed under New BSD License and provided "as is". For complete license inf ormation see f ile LICENSE . Current OrientDB version to work with is: 1.0rc8 (revision 4606). It can be downloaded f rom OrientDB's Downloads page. Code compatible to previous binary releases of OrientDB can be f ound in repository's tags or in Downloads section. Requirements This library requires: PHP 5.3.x spl extension (since PHP 5.3.0 this extension is always available) PCRE extension (as of PHP 5.3.0 this extension cannot be disabled and is theref ore always present) bcmath extension (Since PHP 4.0.4, libbcmath is bundled with PHP. These f unctions are only available if PHP was conf igured with --enable-bcmath .). Used on 32bit systems f or dealing with 64bit long. PDFmyURL.com
  3. 3. If PHP 5.3.x is a concern, you can try to run this code in version 5.2.x, however, this is not supported. Installing OrientDB-PHP Main public repository of OrientDB-PHP is hosted at https://github.com/AntonTerekhov/OrientDB-PHP. To install most recent version of library, just type git clone git://github.com/AntonTerekhov/OrientDB-PHP.git where you want its f ile to be located. You can also want to get latest stable version, so check out Downloads section. Stables are marked with tags including this library version and OrientDB version. Using OrientDB-PHP OrientDB-PHP uses autoload f unctionality, so you only need to include OrientDB.php f ile. require 'OrientDB/OrientDB.php'; For a complex usage example see f ile example.php . Testing OrientDB-PHP OrientDB-PHP is covered with automatic tests by phpUnit. Tests are located in Tests/ directory. You can always re-test the whole library by typing phpunit Tests/ Function list PDFmyURL.com
  4. 4. Some f unctions requires to be already connected to OrientDB server (using connect() ) or to have database opened (using DBOpen() ). This can be ref erenced at protocol description. If sequence is wrong - exception OrientDBWrongCommandException will be thrown and no interaction with server will be made. Create a new instance of OrientDB class $db = new OrientDB(string $host, int $port[, int $connectTimeout]); Example: $db = new OrientDB('localhost', 2424); Connect to server Connects to OrientDB server (not database) with user and password specif ied. Returns true on success or throws exception. bool $db->connect(string $userName, string $password); Example: $connected = $db->connect('root', 'passwd'); Database functions DBOpen Open database f or work with or throws exception on f ailure (non-existent DB, wrong login or password). Return array consist of cluster inf ormation and conf ig. array $db->DBOpen(string $dbName, string $userName, string $password); Example: PDFmyURL.com
  5. 5. $config = $db->DBOpen('demo', 'writer', 'writer'); DBClose Closes currently opened database. Silently closes currently opened database, if any. Socket to OrientDB server is closed, and no f urther commands are possible. Will throw an exception if no database are open on OrientDB instance. void $db->DBClose(); DBCreate Creates new database. Return true on success or throw an exception. bool $db->DBCreate(string $dbName, string $dbType); Available types is: OrientDB::DB_TYPE_MEMORY f or in memory database OrientDB::DB_TYPE_LOCAL f or physical database For dif f erence see of f icial OrientDB docs. Example: $isCreated = $db->DBCreate('mydb', OrientDB::DB_TYPE_LOCAL); DBDelete Delete database with name provided. Always return true . bool $db->DBDelete(string $dbName); PDFmyURL.com
  6. 6. Example: $result = $db->DBDelete('testdb'); DBExists Checks if database with name provided is exists. Return true on success, false is no database exists or throws an exception. bool $db->DBExists(string $dbName); Example: $isExists = $db->DBExists('demo'); Record manipulation functions recordCreate Create record in specif ied cluster with content and type. Returns record position in cluster. int $db->recordCreate( int $clusterID, string|OrientDBRecord $recordContent[, string $recordType]); Available record types are: OrientDB::RECORD_TYPE_BYTES OrientDB::RECORD_TYPE_DOCUMENT OrientDB::RECORD_TYPE_FLAT Def ault type used is OrientDB::RECORD_TYPE_DOCUMENT . Example 1: PDFmyURL.com
  7. 7. $recordPos = $db->recordCreate(1, 'name:"John"'); You can, however, use instance of class OrientDBRecord to create new entry in OrientDB server. If so, some of this instance properties ( clusterID , recordPos , recordID , version ) will be f illed with correct values. See example below: Example 2: $record = new OrientDBRecord(); $record->data->name = 'John'; $recordPos = $db->recordCreate(1, $record); echo $record->recordPos . PHP_EOL; echo $record->clusterID . PHP_EOL; echo $record->recordID . PHP_EOL; echo $record->version . PHP_EOL; Can produce something like: 1 5 1:5 0 Due to PHP's behavior, objects are always passed by ref erence instead of int, f or example. This, if automatically updating of record f ields is not an option, can get you in trouble. So, in that case you should see example below: Example 3: $record = new OrientDBRecord(); $record->data->name = 'John'; $recordPos = $db->recordCreate(1, (string) $record); Please, note, that using OrientDBRecord instance doesn't automatically f ill up other f unction parameters. PDFmyURL.com
  8. 8. recordDelete Delete record with specif ied recordID and optionally, version. Returns true on success, false otherwise or throws an exception. bool $db->recordDelete(string $recordID[, int $recordVersion]); Def ault version is -1 . This means no version check will be done. Example: $result = $db->recordDelete('1:1'); $result = $db->recordDelete('1:1', 1); recordLoad Load record by recordID and, optionally, f etchplan. Returns record or false . In some cases (e.g. recordPos is out of f ile bounds) can throw an exception OrientDBRecord $db->recordLoad(string $recordID[, string $fetchPlan]); Def ault f etchplan is *:0 , which mean load only record specif ied. Example: $record = $db->recordLoad('1:1'); If f etchplan is explicit and there are some records returned by OrientDB, they located in $db->cachedRecords as associative array with keys f rom recordIDs and values are record themselves. This example PDFmyURL.com
  9. 9. $record = $db->recordLoad('1:1', '*:-1'); var_dump($db->cachedRecords); Will produce something like this: array(2) { ["11:0"]=> object(OrientDBRecord)#178 (8) { ... During next call to any method which is able to populate $db->cachedRecords (e.g. recordLoad() or command() ) this array will be reset. recordUpdate Update record with specif ied recordID and, optionally, version. Returns new record version on success, -1 otherwise or throws an exception. int $db->recordUpdate(string $recordID, string|OrientDBRecord $recordContent[, int $recordVersion[, string $recordType]]); Def ault version is -1 . This means no version check will be done. Available record types are: OrientDB::RECORD_TYPE_BYTES OrientDB::RECORD_TYPE_DOCUMENT OrientDB::RECORD_TYPE_FLAT Def ault type used is OrientDB::RECORD_TYPE_DOCUMENT . Examples 1: $version = $db->recordUpdate('1:1', 'Name:"Bob"'); PDFmyURL.com
  10. 10. $version = $db->recordUpdate('1:1', 'Name:"Sam"', 1, OrientDB::RECORD_TYPE_DOCUMENT); You can, however, use instance of class OrientDBRecord to update record in OrientDB server. If so, some of this instance properties ( clusterID , recordPos , recordID , version ) will be f illed with correct values. See example below: Example 2: $record = new OrientDBRecord(); $record->data->name = 'John'; $recordPos = $db->recordUpdate('1:1', $record); echo $record->recordPos . PHP_EOL; echo $record->clusterID . PHP_EOL; echo $record->recordID . PHP_EOL; echo $record->version . PHP_EOL; Can produce something like: 1 1 1:1 3 Due to PHP's behavior, objects are always passed by ref erence instead of int, f or example. This, if automatically updating of record f ields is not an option, can get you in trouble. So, in that case you should see example below: Example 3: $record = new OrientDBRecord(); $record->data->name = 'John'; $recordPos = $db->recordUpdate('1:1', (string) $record); Please, note, that using OrientDBRecord instance doesn't automatically f ill up other f unction parameters. PDFmyURL.com
  11. 11. Config commands configList Get list of conf igurable options. Returns associative array with keys f rom option names and values themselves. array $db->configList(); Example: $options = $db->configList(); configGet Get value f or conf ig option. Returns value as string . If option name not f ound returns empty string . string $db->configGet(string $optionName); Example: $value = $db->configGet('log.console.level'); configSet Set value f or conf ig option. Returns true on success or throws an exception. bool $db->configSet(string $optionName, string $optionValue); Example: $result = $db->configSet('log.console.level', 'info'); PDFmyURL.com
  12. 12. Datacluster commands dataclusterAdd Add new datacluster with specif ied name and type. Returns new cluster ID or throws an exception. int $db->dataclusterAdd(string $clusterName, string $clusterType); Cluster types available are: OrientDB::DATACLUSTER_TYPE_LOGICAL OrientDB::DATACLUSTER_TYPE_PHYSICAL OrientDB::DATACLUSTER_TYPE_MEMORY Example: $clusterID = $db->dataclusterAdd('testcluster', OrientDB::DATACLUSTER_TYPE_PHYSICAL); dataclusterRemove Removes datacluster by its ID. Returns true on success or throws an exception. bool $db->dataclusterRemove(int $clusterID); Example: $result = $db->dataclusterRemove(10); dataclusterCount Counts elements in clusters specif ied by cluster IDs. Returns count or throws an exception. int $db->dataclusterCount(array $clusterIDs); PDFmyURL.com
  13. 13. Example: $count = $db->dataclusterCount(array(1, 2)); dataclusterDatarange Returns datarange f or specif ied cluster ID. Returns array of start and end positions or throws an exception. array $db->dataclusterDatarange(int $clusterID); Example: $data = $db->dataclusterDatarange(int $clusterID); array(2) { ["start"]=> int(0) ["end"]=> int(126) } commit Commits a transaction. Not yet implemented. count Get count of records in cluster specif ied by clusterName. Returns int or throws an exception. int $db->count(string $clusterName); Example: PDFmyURL.com
  14. 14. $newcount = $db->count('default'); Querying server command This command provide an ability to execute remote SQL commands. Returns mixed or throws an exception. mixed $db->command(int $commandMode, string $query[, string $fetchplan]); Command mode is required to be properly match with query text. Command modes available are: OrientDB::COMMAND_QUERY - f or general queries, including INSERT , UPDATE , DELETE , FIND REFERENCES , etc. OrientDB::COMMAND_SELECT_SYNC - only f or SELECT in synchronous mode OrientDB::COMMAND_SELECT_ASYNC - only f or SELECT in asynchronous mode Fetchplan is used to pre-f etch some records. Fetchplan is only available in OrientDB::COMMAND_SELECT_ASYNC mode. Using f etchplan will populate $db->cachedRecords array as f or recordLoad() . Def ault f etchplan is *:0 . Examples: $records = $db->command(OrientDB::COMMAND_SELECT_ASYNC, 'select * from city limit 7'); $records = $db->command(OrientDB::COMMAND_SELECT_ASYNC, 'select from city traverse( any() )', '*:-1'); $false = $db->command(OrientDB::COMMAND_SELECT_SYNC, 'select from 11:4 where any() traverse(0,10) (address.city = "Rome")'); $links = $db->command(OrientDB::COMMAND_QUERY, 'find references 14:1'); $record = $db->command(OrientDB::COMMAND_QUERY, 'insert into city (name, country) values ("Potenza", #14:1)'); $updatedCount = $db->command(OrientDB::COMMAND_QUERY, 'update city set name = "Taranto" where name = "Potenza"'); $deletedCount = $this->db->command(OrientDB::COMMAND_QUERY, 'delete from city where name = "Taranto"'); PDFmyURL.com
  15. 15. select Is an alias f or command(OrientDB::COMMAND_SELECT_SYNC, string $query). mixed $db->select(string $query); Example: $records = $db->select('select from city traverse( any() )'); selectAsync Is an alias f or command(OrientDB::COMMAND_SELECT_ASYNC, string $query[, string $f etchplan]). mixed $db->selectAsync(string $query[, string $fetchplan]); Example: $records = $db->selectAsync('select * from city limit 7', '*:-1'); query Is an alias f or command(OrientDB::COMMAND_QUERY, string $query). mixed $db->query(string $query); Example: $records = $db->query('insert into city (name, country) values ("Potenza", #14:1) '); shutdown PDFmyURL.com
  16. 16. Remotely shutdown OrientDB server. Require valid user name and password. See manual f or details. Returns nothing on success or throws an exception. void $db->shutdown(string $userName, string $password); Example: $db->shutdown('root', 'password'); Exceptions list For present moment OrientDB-PHP is using this list of exceptions: OrientDBException - base exception, all exceptions listed below are extending this class. This class used as general error class (in case of OrientDB problems). OrientDBConnectException - thrown on connect errors. OrientDBDeSerializeException - thrown on de-serialization errors. OrientDBWrongCommandException - wrong command sequence exception, f or example thrown on call recordLoad() if DB is not opened yet. OrientDBWrongParamsException - wrong params count or other param-related issues. OrientDBRecord This class is representing OrientDB record. Class is holding as much inf ormation f rom OrientDB as we received. Class fields Class f ields are: className - Class name f rom OrientDB. PDFmyURL.com
  17. 17. type - Document type f rom OrientDB. E.g. OrientDB::RECORD_TYPE_DOCUMENT . clusterID - Cluster ID, f rom which record was loaded. recordPos - Record position in cluster. recordID - Fully qualif ied record ID in f ormat clusterID:recordPos . version - Document version f rom OrientDB. content - Document content as string in OrientDB's representation. data - placeholder where data, deserialized f rom content , is stored. Developer should manipulate this data in applications. For complete inf ormation on f ields data types see PHPDoc in class. At this point some class fields are public. Please, be careful. However, class f ields content , clusterID , recordPos , recordID and className are using magic methods. All of them are available f or reading, while f ields clusterID , recordPos and className only f or writing. Class methods Class methods are: parse() - can be called af ter maximum amount of f ields was populated. Parses content and f ill up f ields data and className . Field recordPos are f illed up automatically on setting recordID or clusterID via magic method __set() . In general, there is no need to call this method directly f rom user code, as record content is parsed automatically on request to any data or className f ields. This is done via OrientDBRecordData class. This magic parsing only done once, until new content is assigned. setParsed() - f orces that record was already parsed. __toString() - serialize back all f ields f rom data . Return a string. Also can be called implicitly as type casting, e.g. (string) $record . reset() - f ully reset class f ields, equals to new resetData() - will reset class data, except f or clusterID and className . PDFmyURL.com
  18. 18. Class is able to parse almost any record f ormat as received f rom OrientDB server. However, there are some limitations about f ew Java primitive data types, e.g. short. This is a planned TODO. Examples recordLoad: $record = $db->recordLoad('12:1', '*:2'); var_dump($record); will produce object(OrientDBRecord)#197 (9) { ["className"]=> string(7) "Address" ["type"]=> string(1) "d" ["clusterID"]=> int(12) ["recordPos"]=> int(1) ["recordID"]=> string(4) "12:1" ["version"]=> int(0) ["content"]=> string(61) "Address@street:"Piazza Navona, 1",type:"Residence",city:#13:0" ["data"]=> object(stdClass)#172 (3) { ["street"]=> string(16) "Piazza Navona, 1" ["type"]=> string(9) "Residence" ["city"]=> object(OrientDBTypeLink)#195 (1) { ["link":"OrientDBTypeLink":private]=> PDFmyURL.com
  19. 19. ["link":"OrientDBTypeLink":private]=> string(4) "13:0" } } } recordCreate $record = new OrientDBRecord(); $record->data->FirstName = 'Bruce'; $record->data->LastName = 'Wayne'; $record->data->appearance = 1939; $recordPos = $db->recordCreate($clusterID, (string) $record); var_dump($db->recordLoad($clusterID . ':' . $recordPos)); will produce object(OrientDBRecord)#176 (9) { ["className"]=> NULL ["type"]=> string(1) "d" ["clusterID"]=> int(1) ["recordPos"]=> int(138) ["recordID"]=> string(5) "1:138" ["version"]=> int(0) ["content"]=> string(50) "FirstName:"Bruce",LastName:"Wayne",appearance:1939" ["data"]=> object(stdClass)#179 (3) { ["FirstName"]=> string(5) "Bruce" PDFmyURL.com
  20. 20. ["LastName"]=> string(5) "Wayne" ["appearance"]=> int(1939) } } Datatypes Due to small quantity of PHP's built-in datatypes, this library is introducing some own datatypes. OrientDBLink Used to link records with each other. Two variants of constructing new instance is available: OrientDBTypeLink(string $value); String value can be def ined with or without leading hash sign. OrientDBTypeLink(int $clusterID, int $recordPos); Example 1: String with hash sign $link = new OrientDBTypeLink('#100:99'); echo $link . PHP_EOL; echo $link->getHash() . PHP_EOL; echo $link->get() . PHP_EOL; echo $link->clusterID . PHP_EOL; echo $link->recordPos . PHP_EOL; Example 2: String without hash sign PDFmyURL.com
  21. 21. $link2 = new OrientDBTypeLink('100:99'); echo $link2 . PHP_EOL; echo $link2->getHash() . PHP_EOL; echo $link2->get() . PHP_EOL; echo $link->clusterID . PHP_EOL; echo $link->recordPos . PHP_EOL; Example 3: Two integers $link3 = new OrientDBTypeLink(100, 99); echo $link2 . PHP_EOL; echo $link2->getHash() . PHP_EOL; echo $link2->get() . PHP_EOL; echo $link->clusterID . PHP_EOL; echo $link->recordPos . PHP_EOL; Output of all these examples would be the same: #100:99 #100:99 100:99 100 99 OrientDBTypeTime Used to store OrientDB date f ormat with timestamps. OrientDBTypeLink(mixed $value); Example: $date = new OrientDBTypeDate('1302631023t'); $date2 = new OrientDBTypeDate(1302631023); PDFmyURL.com
  22. 22. echo (string) $date . PHP_EOL; echo $date->getValue() . PHP_EOL; echo $date->getTime() . PHP_EOL; Both $date and $date2 will output the same: 1302631023t 1302631023t 1302631023 Debugging with OrientDB-PHP For debug purposes you can enable or disable debug output at anytime. Example: $db->DBOpen('demo', 'writer', 'writer'); $recordPos = $db->recordCreate($clusterID, $recordContent); $this->db->setDebug(true); $record = $db->recordLoad($clusterID . ':' . $recordPos); $this->db->setDebug(false); $result = $db->recordDelete($clusterID . ':' . $recordPos); The above example will output debug messages only f or recordLoad() to standard output stream (browser or console) in this manner: 0 : 1e 00 00 00 04 00 01 00 00 00 00 00 00 00 8f 00 [................] 10 : 00 00 03 2a 3a 30 [...*:0] >request_status 0 : 00 [.] >TransactionID 0 : 00 00 00 04 [....] >record_status_first PDFmyURL.com
  23. 23. 0 : 01 [.] >record_content 0 : 00 00 00 0c [....] 0 : 74 65 73 74 72 65 63 6f 72 64 3a 30 [testrecord:0] >record_version 0 : 00 00 00 00 [....] >record_type 0 : 64 [d] >record_status_cache 0 : 00 [.] Planned TODOs Full support on Java primitive data types, e.g. short or byte. Possible more OOP-style work with OrientDBRecord. Possible using libevent f or selectAsync(). Support f or async mode f or RECORD_CREATE, RECORD_UPDATE, RECORD_DELETE Support f or converting string 'true' to actual boolean true (and other values) in SQL Known bugs Connecting to OrientDB instance, which is listening 0.0.0.0 (def ault f or OrientDB) can cause errors. Change to 127.0.0.1 in Orient's conf iguration. See issue If you found a bug If you f ound a bug - f eel f ree to contact me via gitHub, email, or open a new issue. PDFmyURL.com
  24. 24. Git Hub About Blog Features Contact & Support Training GitHub Enterprise Site Status Tools Gauges:Analyze web traffic Speaker Deck: Presentations Gist: Code snippets GitHub for Mac Issues for iPhone Job Board Ext ras GitHub Shop The Octodex Document at ion GitHub Help Developer API GitHub Flavored Markdown GitHub Pages Terms of Service Privacy Security © 2012 GitHub Inc.All rights reserved. Powered by the Dedicated Servers and Cloud Computing of Rackspace Hosting® PDFmyURL.com

×