Giter VIP home page Giter VIP logo

rdbms's Introduction

RDBMS support for the XP Framework

Build status on GitHub Build status on AppVeyor XP Framework Module BSD Licence Requires PHP 7.0+ Supports PHP 8.0+ Latest Stable Version

RDBMS access APIs, connection manager, reverse engineering, O/R mapping.

The DriverManager model

To retrieve a connection class from the driver manager, you need to use the rdbms.DriverManager class.

use rdbms\DriverManager;

$conn= DriverManager::getConnection('sybase://user:pass@server/NICOTINE');

The DriverManager class expects a unified connection string (we call it DSN).

Supported drivers

The DriverManager will select an appropriate driver from the DSN string via its name. This will load an implemenation class which is either based on a PHP extension or implements the protocol to communicate with the database system in userland code. For the latter case, you need not do anything to your PHP setup; if there's a hard dependency on a PHP extension, you need to install that before you can use the driver.

Database system DSN name PHP Extensions Userland driver
MySQL mysql ext/mysql or ext/mysqli
PostgreSQL pgsql ext/pgsql
SQLite3 sqlite ext/sqlite3
Interbase/FireBird ibase ext/interbase
Sybase sybase ext/sybase-ct
MSSQL mssql ext/mssql or ext/sqlsrv

Basics

Once we have fetched a specific database connection class, we can now invoke a number of methods on it.

Selecting

Selecting can be done with the "one-stop" method select() which will return all results into an array. Alternatively, the query() method allows iterative fetching.

$news= $conn->select('news_id, caption, author_id from news');
// $news= [
//   [
//     'news_id'   => 12,
//     'caption'   => 'Hello World',
//     'author_id' => 1549
//   ]
// ]

$q= $conn->query('select news_id, caption, author_id from news');
while ($record= $q->next()) {
  // $record= [
  //   'news_id'   => 12,
  //   'caption'   => 'Hello World',
  //   'author_id' => 1549
  // ]
}

Inserting

To "bind" parameters to an SQL query, the query, select, update, delete and insert methods offer a printf style tokenizer and support varargs syntax. These take care of NULL, type handling and proper escaping for you.

$conn->insert('
  into news (
    caption, author_id, body, extended, created_at
  ) values (
    %s, -- caption
    %d, -- author_id
    %s, -- body
    %s, -- extended
    %s  -- created_at
  )',
  $caption,
  $authorId,
  $body,
  $extended,
  Date::now()
);

Updating

The update() and delete() methods will return the number of affected rows, in case you're interested.

$conn->update('news set author_id= %d where author_id is null', $authorId);

Deleting

Even if your RDBMS requires you to use single quotes (or what-else), the API will take care of rewriting string literals for you.

$conn->delete('from news where caption = "[DELETE]"');

Exceptions

All of the above methods will throw exceptions for failed SQL queries, syntax errors, connection failure etc. All these exceptions are subclasses of rdbms.SQLException, so to catch all possible errors, use it in the catch clause:

+ rdbms.SQLException
|-- rdbms.ConnectionNotRegisteredException
|-- rdbms.SQLConnectException
|-- rdbms.SQLStateException
`-- rdbms.SQLStatementFailedException
    |-- rdbms.SQLConnectionClosedException
    `-- rdbms.SQLDeadlockException

Transactions

To start a transaction, you can use the connection's begin(), commit() and rollback() methods as follows:

public function createAuthor(...) {
  $tran= $conn->begin(new Transaction('create_author'));

  try {
    $id= $conn->insert('into author ...');
    $conn->insert('into notify ...');

    $tran->commit();
    return $id;
  } catch (SQLException $e) {
    $tran->rollback();
    throw $e;
  }
}

Note: Not all database systems support transactions, and of those that do, not all support nested transactions. Be sure to read the manual pages of the RDBMS you are accessing.

rdbms's People

Contributors

andstefiul avatar beorgler avatar guel1973 avatar johannes85 avatar kiesel avatar kusnier avatar ohinckel avatar ppetermann avatar stormwind avatar thekid avatar treuter avatar

Stargazers

 avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar

rdbms's Issues

Integration tests failing on HHVM

See https://travis-ci.org/xp-framework/rdbms/jobs/135264912:

F unittest.TestWarning(test= rdbms.unittest.integration.MySQLIntegrationTest::connectFailedThrowsException, time= 0.134 seconds) {
  [""mysql_connect(): Access denied for user 'wrong-user'@'localhost' (using password: YES)" in mysqli::hh_real_connect() (, line 0, occured once)"]
 }

×: 45/104 run (59 skipped), 44 succeeded, 1 failed
Memory used: 2048.00 kB (2048.00 kB peak)
Time taken: 5.856 seconds

No SQLiteDBAdapter available

In commit 1101dca, all of the sqlite package was removed in favor of the sqlite3 package. That package, however, does not have an SQLiteDBAdapter, so we cannot do reflection on these kinds of databases any more.

Furthermore, we're now having an unresolved dependency in xp.codegen.dataset.Generator.

I suggest to extract the removed class from the referenced commit and add it to the sqlite3 package.

Expose mock implementation?

The rdbms.unittest.mock package has been picked by several of our libraries to emulate certain result sets.

With the current location with the mock package being within src/test, a library cannot pick it any more. Should we expose it to src/main, possibly as rdbms.mock package?

Missing default value for lenth field in MySQLi implementation

The tableAttributeFrom function in rdbms.mysqli.MySQLiDBAdapter enforces the Type of a record to have a length. For example the type text does not have this field, so it fails with

Uncaught exception: Exception lang.IndexOutOfBoundsException (Undefined offset: 3)
  at <main>::__error(8, (0x13)'Undefined offset: 3', (0x69)'/home/idev/dev/temp/codegen/vendor/xp-framework/rdbms/src/main/p', 108, array[2]) [line 108 of MySQLiDBAdapter.class.php]

In the MySQL implementation this is fixed with a default value

  public static function tableAttributeFrom($record) {
    preg_match('#^([a-z]+)(\(([0-9,]+)\))?#', $record['Type'], $regs);
    return new DBTableAttribute(
      $record['Field'],                                         // name
      self::$map[$regs[1]],                                     // type
      false !== strpos($record['Extra'], 'auto_increment'),     // identity
      !(empty($record['Null']) || ('NO' == $record['Null'])),   // nullable
      (int)(isset($regs[3]) ? $regs[3] : 0),                    // length
      0,                                                        // precision
      0                                                         // scale
    );
  }

Fix HHVM

  • Fatal error: Unable to open database: unable to open database file - see https://travis-ci.org/xp-framework/rdbms/jobs/63626399
  • Fatal error: Declaration of rdbms\criterion\SimpleProjection::asSql() must be compatible with that of rdbms\SQLRenderable::asSql() in /home/travis/build/xp-framework/rdbms/src/main/php/rdbms/criterion/SimpleProjection.class.php on line 14 - see https://travis-ci.org/xp-framework/rdbms/jobs/64997716
  • unittest.AssertionFailedError{ expected [lang.types.Bytes(8)@{UAXNPP\O}] but was [lang.types.Bytes(8)@{@@@@@@@@}] using: 'equals' } in rdbms.unittest.mysql.MySqlPasswordTest::protocol40

Dataset generator doesn't detect PK in postgresql

When creating dataset classes with the framework's generator the primary keys doesn't get detected for postgresql databases. Therefore no getBy() methods are created and after saving a new row the value of the auto increment column remains unset in the object.

Close connection when packet no. out of order

The connection should be reset when packet no. out of order as the connection is unusable!

Reproduce

  1. Open connection (e.g. using ISQL)
  2. Restart MariaDB server (using kill will not do the job!)
  3. Wait, then issue a query: *** Exception rdbms.SQLStatementFailedException (errorcode -1: Packet no. out of order, have 0, expecting 1
  4. Issue another query: *** Exception rdbms.SQLStatementFailedException (errorcode -1: Packet no. out of order, have 35, expecting 1)
  5. etcetera...

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.