pax_global_header 0000666 0000000 0000000 00000000064 12703724304 0014514 g ustar 00root root 0000000 0000000 52 comment=c9fa8fdab194093fff58e4f1180c7e15d80a2cb5
zend-db-release-2.8.1/ 0000775 0000000 0000000 00000000000 12703724304 0014465 5 ustar 00root root 0000000 0000000 zend-db-release-2.8.1/CHANGELOG.md 0000664 0000000 0000000 00000014401 12703724304 0016276 0 ustar 00root root 0000000 0000000 # Changelog
All notable changes to this project will be documented in this file, in reverse chronological order by release.
## 2.8.1 - 2016-04-14
### Added
- Nothing.
### Deprecated
- Nothing.
### Removed
- Nothing.
### Fixed
- [#100](https://github.com/zendframework/zend-db/pull/100) fixes the JOIN
behavior to re-allow selecting an empty column set from the joined table.
- [#106](https://github.com/zendframework/zend-db/pull/106) fixes an issue in
the test suite when ext/pgsql is enabled, but no databases are avaiable.
## 2.8.0 - 2016-04-12
### Added
- [#92](https://github.com/zendframework/zend-db/pull/92) adds the class
`Zend\Db\Sql\Join` for creating and aggregating JOIN specifications. This is
now consumed by all `Zend\Db\Sql` implementations in order to represent JOIN
statements.
- [#92](https://github.com/zendframework/zend-db/pull/92) adds support for JOIN
operations to UPDATE statements.
- [#92](https://github.com/zendframework/zend-db/pull/92) adds support for joins
to `AbstractTableGateway::update`; you can now pass an array of
specifications via a third argument to the method.
- [#96](https://github.com/zendframework/zend-db/pull/96) exposes the package as
config-provider/component, but adding:
- `Zend\Db\ConfigProvider`, which maps the `AdapterInterface` to the
`AdapterServiceFactory`, and enables the `AdapterAbstractServiceFactory`.
- `Zend\Db\Module`, which does the same, for a zend-mvc context.
### Deprecated
- Nothing.
### Removed
- Nothing.
### Fixed
- Nothing.
## 2.7.1 - 2016-04-12
### Added
- Nothing.
### Deprecated
- Nothing.
### Removed
- Nothing.
### Fixed
- [#71](https://github.com/zendframework/zend-db/pull/71) updates the `Pgsql`
adapter to allow passing the connection charset; this can be done with the
`charset` option when creating your adapter.
- [#76](https://github.com/zendframework/zend-db/pull/76) fixes the behavior of
`Zend\Db\Sql\Insert` when an array of names is used for columns to ensure the
string names are used, and not the array indices.
- [#91](https://github.com/zendframework/zend-db/pull/91) fixes the behavior of
the `Oci8` adapter when initializing a result set; previously, it was
improperly assigning the count of affected rows to the generated value.
- [#95](https://github.com/zendframework/zend-db/pull/95) fixes the `IbmDb2`
platform's `quoteIdentifier()` method to properly allow `#` characters in
identifiers (as they are commonly used on that platform).
## 2.7.0 - 2016-02-22
### Added
- Nothing.
### Deprecated
- Nothing.
### Removed
- Nothing.
### Fixed
- [#85](https://github.com/zendframework/zend-db/pull/85) and
[#87](https://github.com/zendframework/zend-db/pull/87) update the code base
to be forwards compatible with:
- zend-eventmanager v3
- zend-hydrator v2.1
- zend-servicemanager v3
- zend-stdlib v3
## 2.6.2 - 2015-12-09
### Added
- [#49](https://github.com/zendframework/zend-db/pull/49) Add docbook
documentation.
### Deprecated
- Nothing.
### Removed
- Nothing.
### Fixed
- [#55](https://github.com/zendframework/zend-db/pull/55) Implement FeatureSet
canCallMagicCall and callMagicCall methods
- [#56](https://github.com/zendframework/zend-db/pull/56)
AbstractResultSet::current now does validation to ensure an array.
- [#58](https://github.com/zendframework/zend-db/pull/58) Fix unbuffered result
on MySQLi.
- [#59](https://github.com/zendframework/zend-db/pull/59) Allow unix_socket
parameter
## 2.6.1 - 2015-10-14
### Added
- Nothing.
### Deprecated
- Nothing.
### Removed
- Nothing.
### Fixed
- [#31](https://github.com/zendframework/zend-db/pull/31) fixes table gateway
update when there is a table alias utilized.
## 2.6.1 - 2015-10-14
### Added
- Nothing.
### Deprecated
- Nothing.
### Removed
- Nothing.
### Fixed
- [#43](https://github.com/zendframework/zend-db/pull/43) unset and get during
an insert operation would throw an InvalidArgumentException during an insert.
## 2.6.0 - 2015-09-22
### Added
- [#42](https://github.com/zendframework/zend-db/pull/42) updates the component
to use zend-hydrator for hydrator functionality; this provides forward
compatibility with zend-hydrator, and backwards compatibility with
hydrators from older versions of zend-stdlib.
- [#15](https://github.com/zendframework/zend-db/pull/15) adds a new predicate,
`Zend\Db\Sql\Predicate\NotBetween`, which can be invoked via `Sql`
instances: `$sql->notBetween($field, $min, $max)`.
- [#22](https://github.com/zendframework/zend-db/pull/22) extracts a factory,
`Zend\Db\Metadata\Source\Factory`, from `Zend\Db\Metadata\Metadata`,
removing the (non-public) `createSourceFromAdapter()` method from that
class. Additionally, it extracts `Zend\Db\Metadata\MetadataInterface`, to
allow creating alternate implementations.
### Deprecated
- [#27](https://github.com/zendframework/zend-db/pull/27) deprecates the
constants `JOIN_OUTER_LEFT` and `JOIN_OUTER_RIGHT` in favor of
`JOIN_LEFT_OUTER` and `JOIN_RIGHT_OUTER`.
### Removed
- Nothing.
### Fixed
- Nothing.
## 2.5.2 - 2015-09-22
### Added
- Nothing.
### Deprecated
- Nothing.
### Removed
- [#29](https://github.com/zendframework/zend-db/pull/29) removes the required
second argument to `Zend\Db\Predicate\Predicate::expression()`, allowing it to
be nullable, and mirroring the constructor of `Zend\Db\Predicate\Expression`.
### Fixed
- [#40](https://github.com/zendframework/zend-db/pull/40) updates the
zend-stdlib dependency to reference `>=2.5.0,<2.7.0` to ensure hydrators
will work as expected following extraction of hydrators to the zend-hydrator
repository.
- [#34](https://github.com/zendframework/zend-db/pull/34) fixes retrieval of
constraint metadata in the Oracle adapter.
- [#41](https://github.com/zendframework/zend-db/pull/41) removes hard dependency
on EventManager in AbstractTableGateway.
- [#17](https://github.com/zendframework/zend-db/pull/17) removes an executable
bit on a regular file.
- [#3](https://github.com/zendframework/zend-db/pull/3) updates the code to use
closure binding (now that we're on 5.5+, this is possible).
- [#9](https://github.com/zendframework/zend-db/pull/9) thoroughly audits the
OCI8 (Oracle) driver, ensuring it provides feature parity with other drivers,
and fixes issues with subselects, limits, and offsets.
zend-db-release-2.8.1/CONDUCT.md 0000664 0000000 0000000 00000004512 12703724304 0016110 0 ustar 00root root 0000000 0000000 # Contributor Code of Conduct
The Zend Framework project adheres to [The Code Manifesto](http://codemanifesto.com)
as its guidelines for contributor interactions.
## The Code Manifesto
We want to work in an ecosystem that empowers developers to reach their
potential — one that encourages growth and effective collaboration. A space that
is safe for all.
A space such as this benefits everyone that participates in it. It encourages
new developers to enter our field. It is through discussion and collaboration
that we grow, and through growth that we improve.
In the effort to create such a place, we hold to these values:
1. **Discrimination limits us.** This includes discrimination on the basis of
race, gender, sexual orientation, gender identity, age, nationality, technology
and any other arbitrary exclusion of a group of people.
2. **Boundaries honor us.** Your comfort levels are not everyone’s comfort
levels. Remember that, and if brought to your attention, heed it.
3. **We are our biggest assets.** None of us were born masters of our trade.
Each of us has been helped along the way. Return that favor, when and where
you can.
4. **We are resources for the future.** As an extension of #3, share what you
know. Make yourself a resource to help those that come after you.
5. **Respect defines us.** Treat others as you wish to be treated. Make your
discussions, criticisms and debates from a position of respectfulness. Ask
yourself, is it true? Is it necessary? Is it constructive? Anything less is
unacceptable.
6. **Reactions require grace.** Angry responses are valid, but abusive language
and vindictive actions are toxic. When something happens that offends you,
handle it assertively, but be respectful. Escalate reasonably, and try to
allow the offender an opportunity to explain themselves, and possibly correct
the issue.
7. **Opinions are just that: opinions.** Each and every one of us, due to our
background and upbringing, have varying opinions. The fact of the matter, is
that is perfectly acceptable. Remember this: if you respect your own
opinions, you should respect the opinions of others.
8. **To err is human.** You might not intend it, but mistakes do happen and
contribute to build experience. Tolerate honest mistakes, and don't hesitate
to apologize if you make one yourself.
zend-db-release-2.8.1/CONTRIBUTING.md 0000664 0000000 0000000 00000022261 12703724304 0016721 0 ustar 00root root 0000000 0000000 # CONTRIBUTING
## RESOURCES
If you wish to contribute to Zend Framework, please be sure to
read/subscribe to the following resources:
- [Coding Standards](https://github.com/zendframework/zf2/wiki/Coding-Standards)
- [Contributor's Guide](http://framework.zend.com/participate/contributor-guide)
- ZF Contributor's mailing list:
Archives: http://zend-framework-community.634137.n4.nabble.com/ZF-Contributor-f680267.html
Subscribe: zf-contributors-subscribe@lists.zend.com
- ZF Contributor's IRC channel:
#zftalk.dev on Freenode.net
If you are working on new features or refactoring [create a proposal](https://github.com/zendframework/zend-db/issues/new).
## Reporting Potential Security Issues
If you have encountered a potential security vulnerability, please **DO NOT** report it on the public
issue tracker: send it to us at [zf-security@zend.com](mailto:zf-security@zend.com) instead.
We will work with you to verify the vulnerability and patch it as soon as possible.
When reporting issues, please provide the following information:
- Component(s) affected
- A description indicating how to reproduce the issue
- A summary of the security vulnerability and impact
We request that you contact us via the email address above and give the project
contributors a chance to resolve the vulnerability and issue a new release prior
to any public exposure; this helps protect users and provides them with a chance
to upgrade and/or update in order to protect their applications.
For sensitive email communications, please use [our PGP key](http://framework.zend.com/zf-security-pgp-key.asc).
## RUNNING TESTS
> ### Note: testing versions prior to 2.4
>
> This component originates with Zend Framework 2. During the lifetime of ZF2,
> testing infrastructure migrated from PHPUnit 3 to PHPUnit 4. In most cases, no
> changes were necessary. However, due to the migration, tests may not run on
> versions < 2.4. As such, you may need to change the PHPUnit dependency if
> attempting a fix on such a version.
To run tests:
- Clone the repository:
```console
$ git clone git@github.com:zendframework/zend-db.git
$ cd
```
- Install dependencies via composer:
```console
$ curl -sS https://getcomposer.org/installer | php --
$ ./composer.phar install
```
If you don't have `curl` installed, you can also download `composer.phar` from https://getcomposer.org/
- Run the tests via `phpunit` and the provided PHPUnit config, like in this example:
```console
$ ./vendor/bin/phpunit
```
You can turn on conditional tests with the phpunit.xml file.
To do so:
- Copy `phpunit.xml.dist` file to `phpunit.xml`
- Edit `phpunit.xml` to enable any specific functionality you
want to test, as well as to provide test values to utilize.
### Execute tests against real database servers
This projects provides a [Vagrant](https://www.vagrantup.com/) virtual machine definition with a
MySQL and PostgreSQL servers installed and configured.
For to execute the tests against this server do the following steps (assume you have Vagrant > 1.6 installed)
1. Run the virtual machine: `vagrant up`
2. Copy `phpunit.xml.dist` file to `phpunit.xml`.
3. Enable online tests by setting the following config options:
* `TESTS_ZEND_DB_ADAPTER_DRIVER_MYSQL_HOSTNAME` value to `localhost`
* `TESTS_ZEND_DB_ADAPTER_DRIVER_PGSQL_HOSTNAME` value to `localhost`
4. Run `./vendor/bin/phpunit`.
When done, you can halt the test servers using `vagrant halt`.
> ### Alternate ports
>
> Pay attention to the output from your `vagrant up` command. If you have MySQL or PostgreSQL
> running locally, Vagrant will detect that the port is in use, and forward an alternate port to the
> virtual machine's database server(s). You'll likely see output like the following:
>
> ```
> ==> default: Forwarding ports...
> default: 3306 => 2200 (adapter 1)
> default: 5432 => 5432 (adapter 1)
> default: 22 => 2222 (adapter 1)
> ```
>
> In the above example, local port 2200 is forwarded to guest 3306; in other words, for testing
> MySQL, port 2200 should be used.
>
> To specify the alternate port, append it to the hostname, separated by a colon: `localhost:2200`.
> ### Alternate testing approach
>
> The PHPUnit config file defines environment variables, which allows users on unix-like systems to
> simplify steps 2-4 to:
>
> ```console
> $ TESTS_ZEND_DB_ADAPTER_DRIVER_MYSQL_HOSTNAME=localhost \
> > TESTS_ZEND_DB_ADAPTER_DRIVER_PGSQL_HOSTNAME=localhost \
> > ./vendor/bin/phpunit
> ```
## Running Coding Standards Checks
This component uses [php-cs-fixer](http://cs.sensiolabs.org/) for coding
standards checks, and provides configuration for our selected checks.
`php-cs-fixer` is installed by default via Composer.
To run checks only:
```console
$ ./vendor/bin/php-cs-fixer fix . -v --diff --dry-run --config-file=.php_cs
```
To have `php-cs-fixer` attempt to fix problems for you, omit the `--dry-run`
flag:
```console
$ ./vendor/bin/php-cs-fixer fix . -v --diff --config-file=.php_cs
```
If you allow php-cs-fixer to fix CS issues, please re-run the tests to ensure
they pass, and make sure you add and commit the changes after verification.
## Recommended Workflow for Contributions
Your first step is to establish a public repository from which we can
pull your work into the master repository. We recommend using
[GitHub](https://github.com), as that is where the component is already hosted.
1. Setup a [GitHub account](http://github.com/), if you haven't yet
2. Fork the repository (http://github.com/zendframework/zend-db)
3. Clone the canonical repository locally and enter it.
```console
$ git clone git://github.com:zendframework/zend-db.git
$ cd zend-db
```
4. Add a remote to your fork; substitute your GitHub username in the command
below.
```console
$ git remote add {username} git@github.com:{username}/zend-db.git
$ git fetch {username}
```
### Keeping Up-to-Date
Periodically, you should update your fork or personal repository to
match the canonical ZF repository. Assuming you have setup your local repository
per the instructions above, you can do the following:
```console
$ git checkout master
$ git fetch origin
$ git rebase origin/master
# OPTIONALLY, to keep your remote up-to-date -
$ git push {username} master:master
```
If you're tracking other branches -- for example, the "develop" branch, where
new feature development occurs -- you'll want to do the same operations for that
branch; simply substitute "develop" for "master".
### Working on a patch
We recommend you do each new feature or bugfix in a new branch. This simplifies
the task of code review as well as the task of merging your changes into the
canonical repository.
A typical workflow will then consist of the following:
1. Create a new local branch based off either your master or develop branch.
2. Switch to your new local branch. (This step can be combined with the
previous step with the use of `git checkout -b`.)
3. Do some work, commit, repeat as necessary.
4. Push the local branch to your remote repository.
5. Send a pull request.
The mechanics of this process are actually quite trivial. Below, we will
create a branch for fixing an issue in the tracker.
```console
$ git checkout -b hotfix/9295
Switched to a new branch 'hotfix/9295'
```
... do some work ...
```console
$ git commit
```
... write your log message ...
```console
$ git push {username} hotfix/9295:hotfix/9295
Counting objects: 38, done.
Delta compression using up to 2 threads.
Compression objects: 100% (18/18), done.
Writing objects: 100% (20/20), 8.19KiB, done.
Total 20 (delta 12), reused 0 (delta 0)
To ssh://git@github.com/{username}/zend-db.git
b5583aa..4f51698 HEAD -> master
```
To send a pull request, you have two options.
If using GitHub, you can do the pull request from there. Navigate to
your repository, select the branch you just created, and then select the
"Pull Request" button in the upper right. Select the user/organization
"zendframework" as the recipient.
If using your own repository - or even if using GitHub - you can use `git
format-patch` to create a patchset for us to apply; in fact, this is
**recommended** for security-related patches. If you use `format-patch`, please
send the patches as attachments to:
- zf-devteam@zend.com for patches without security implications
- zf-security@zend.com for security patches
#### What branch to issue the pull request against?
Which branch should you issue a pull request against?
- For fixes against the stable release, issue the pull request against the
"master" branch.
- For new features, or fixes that introduce new elements to the public API (such
as new public methods or properties), issue the pull request against the
"develop" branch.
### Branch Cleanup
As you might imagine, if you are a frequent contributor, you'll start to
get a ton of branches both locally and on your remote.
Once you know that your changes have been accepted to the master
repository, we suggest doing some cleanup of these branches.
- Local branch cleanup
```console
$ git branch -d
* Return the current element
* @link http://php.net/manual/en/iterator.current.php
* @return mixed Can return any type.
*/
public function current()
{
if ($this->currentComplete) {
return $this->currentData;
}
$this->currentData = db2_fetch_assoc($this->resource);
return $this->currentData;
}
/**
* @return mixed
*/
public function next()
{
$this->currentData = db2_fetch_assoc($this->resource);
$this->currentComplete = true;
$this->position++;
return $this->currentData;
}
/**
* @return int|string
*/
public function key()
{
return $this->position;
}
/**
* @return bool
*/
public function valid()
{
return ($this->currentData !== false);
}
/**
* (PHP 5 >= 5.0.0)
* Rewind the Iterator to the first element
* @link http://php.net/manual/en/iterator.rewind.php
* @return void Any returned value is ignored.
*/
public function rewind()
{
if ($this->position > 0) {
throw new Exception\RuntimeException(
'This result is a forward only result set, calling rewind() after moving forward is not supported'
);
}
$this->currentData = db2_fetch_assoc($this->resource);
$this->currentComplete = true;
$this->position = 1;
}
/**
* Force buffering
*
* @return void
*/
public function buffer()
{
return;
}
/**
* Check if is buffered
*
* @return bool|null
*/
public function isBuffered()
{
return false;
}
/**
* Is query result?
*
* @return bool
*/
public function isQueryResult()
{
return (db2_num_fields($this->resource) > 0);
}
/**
* Get affected rows
*
* @return int
*/
public function getAffectedRows()
{
return db2_num_rows($this->resource);
}
/**
* Get generated value
*
* @return mixed|null
*/
public function getGeneratedValue()
{
return $this->generatedValue;
}
/**
* Get the resource
*
* @return mixed
*/
public function getResource()
{
return $this->resource;
}
/**
* Get field count
*
* @return int
*/
public function getFieldCount()
{
return db2_num_fields($this->resource);
}
/**
* @return null|int
*/
public function count()
{
return;
}
}
zend-db-release-2.8.1/src/Adapter/Driver/IbmDb2/Statement.php 0000664 0000000 0000000 00000012324 12703724304 0023605 0 ustar 00root root 0000000 0000000 db2 = $resource;
return $this;
}
/**
* @param IbmDb2 $driver
* @return Statement
*/
public function setDriver(IbmDb2 $driver)
{
$this->driver = $driver;
return $this;
}
/**
* @param Profiler\ProfilerInterface $profiler
* @return Statement
*/
public function setProfiler(Profiler\ProfilerInterface $profiler)
{
$this->profiler = $profiler;
return $this;
}
/**
* @return null|Profiler\ProfilerInterface
*/
public function getProfiler()
{
return $this->profiler;
}
/**
* Set sql
*
* @param $sql
* @return mixed
*/
public function setSql($sql)
{
$this->sql = $sql;
return $this;
}
/**
* Get sql
*
* @return mixed
*/
public function getSql()
{
return $this->sql;
}
/**
* Set parameter container
*
* @param ParameterContainer $parameterContainer
* @return mixed
*/
public function setParameterContainer(ParameterContainer $parameterContainer)
{
$this->parameterContainer = $parameterContainer;
return $this;
}
/**
* Get parameter container
*
* @return mixed
*/
public function getParameterContainer()
{
return $this->parameterContainer;
}
/**
* @param $resource
* @throws \Zend\Db\Adapter\Exception\InvalidArgumentException
*/
public function setResource($resource)
{
if (get_resource_type($resource) !== 'DB2 Statement') {
throw new Exception\InvalidArgumentException('Resource must be of type DB2 Statement');
}
$this->resource = $resource;
}
/**
* Get resource
*
* @return resource
*/
public function getResource()
{
return $this->resource;
}
/**
* Prepare sql
*
* @param string|null $sql
* @return Statement
*/
public function prepare($sql = null)
{
if ($this->isPrepared) {
throw new Exception\RuntimeException('This statement has been prepared already');
}
if ($sql === null) {
$sql = $this->sql;
}
$this->resource = db2_prepare($this->db2, $sql);
if ($this->resource === false) {
throw new Exception\RuntimeException(db2_stmt_errormsg(), db2_stmt_error());
}
$this->isPrepared = true;
return $this;
}
/**
* Check if is prepared
*
* @return bool
*/
public function isPrepared()
{
return $this->isPrepared;
}
/**
* Execute
*
* @param null|array|ParameterContainer $parameters
* @return Result
*/
public function execute($parameters = null)
{
if (!$this->isPrepared) {
$this->prepare();
}
/** START Standard ParameterContainer Merging Block */
if (!$this->parameterContainer instanceof ParameterContainer) {
if ($parameters instanceof ParameterContainer) {
$this->parameterContainer = $parameters;
$parameters = null;
} else {
$this->parameterContainer = new ParameterContainer();
}
}
if (is_array($parameters)) {
$this->parameterContainer->setFromArray($parameters);
}
/** END Standard ParameterContainer Merging Block */
if ($this->profiler) {
$this->profiler->profilerStart($this);
}
set_error_handler(function () {}, E_WARNING); // suppress warnings
$response = db2_execute($this->resource, $this->parameterContainer->getPositionalArray());
restore_error_handler();
if ($this->profiler) {
$this->profiler->profilerFinish();
}
if ($response === false) {
throw new Exception\RuntimeException(db2_stmt_errormsg($this->resource));
}
$result = $this->driver->createResult($this->resource);
return $result;
}
}
zend-db-release-2.8.1/src/Adapter/Driver/Mysqli/ 0000775 0000000 0000000 00000000000 12703724304 0021345 5 ustar 00root root 0000000 0000000 zend-db-release-2.8.1/src/Adapter/Driver/Mysqli/Connection.php 0000664 0000000 0000000 00000014420 12703724304 0024156 0 ustar 00root root 0000000 0000000 setConnectionParameters($connectionInfo);
} elseif ($connectionInfo instanceof \mysqli) {
$this->setResource($connectionInfo);
} elseif (null !== $connectionInfo) {
throw new Exception\InvalidArgumentException('$connection must be an array of parameters, a mysqli object or null');
}
}
/**
* @param Mysqli $driver
* @return self
*/
public function setDriver(Mysqli $driver)
{
$this->driver = $driver;
return $this;
}
/**
* {@inheritDoc}
*/
public function getCurrentSchema()
{
if (!$this->isConnected()) {
$this->connect();
}
/** @var $result \mysqli_result */
$result = $this->resource->query('SELECT DATABASE()');
$r = $result->fetch_row();
return $r[0];
}
/**
* Set resource
*
* @param \mysqli $resource
* @return self
*/
public function setResource(\mysqli $resource)
{
$this->resource = $resource;
return $this;
}
/**
* {@inheritDoc}
*/
public function connect()
{
if ($this->resource instanceof \mysqli) {
return $this;
}
// localize
$p = $this->connectionParameters;
// given a list of key names, test for existence in $p
$findParameterValue = function (array $names) use ($p) {
foreach ($names as $name) {
if (isset($p[$name])) {
return $p[$name];
}
}
return;
};
$hostname = $findParameterValue(['hostname', 'host']);
$username = $findParameterValue(['username', 'user']);
$password = $findParameterValue(['password', 'passwd', 'pw']);
$database = $findParameterValue(['database', 'dbname', 'db', 'schema']);
$port = (isset($p['port'])) ? (int) $p['port'] : null;
$socket = (isset($p['socket'])) ? $p['socket'] : null;
$this->resource = new \mysqli();
$this->resource->init();
if (!empty($p['driver_options'])) {
foreach ($p['driver_options'] as $option => $value) {
if (is_string($option)) {
$option = strtoupper($option);
if (!defined($option)) {
continue;
}
$option = constant($option);
}
$this->resource->options($option, $value);
}
}
$this->resource->real_connect($hostname, $username, $password, $database, $port, $socket);
if ($this->resource->connect_error) {
throw new Exception\RuntimeException(
'Connection error',
null,
new Exception\ErrorException($this->resource->connect_error, $this->resource->connect_errno)
);
}
if (!empty($p['charset'])) {
$this->resource->set_charset($p['charset']);
}
return $this;
}
/**
* {@inheritDoc}
*/
public function isConnected()
{
return ($this->resource instanceof \mysqli);
}
/**
* {@inheritDoc}
*/
public function disconnect()
{
if ($this->resource instanceof \mysqli) {
$this->resource->close();
}
$this->resource = null;
}
/**
* {@inheritDoc}
*/
public function beginTransaction()
{
if (!$this->isConnected()) {
$this->connect();
}
$this->resource->autocommit(false);
$this->inTransaction = true;
return $this;
}
/**
* {@inheritDoc}
*/
public function commit()
{
if (!$this->isConnected()) {
$this->connect();
}
$this->resource->commit();
$this->inTransaction = false;
$this->resource->autocommit(true);
return $this;
}
/**
* {@inheritDoc}
*/
public function rollback()
{
if (!$this->isConnected()) {
throw new Exception\RuntimeException('Must be connected before you can rollback.');
}
if (!$this->inTransaction) {
throw new Exception\RuntimeException('Must call beginTransaction() before you can rollback.');
}
$this->resource->rollback();
$this->resource->autocommit(true);
$this->inTransaction = false;
return $this;
}
/**
* {@inheritDoc}
*
* @throws Exception\InvalidQueryException
*/
public function execute($sql)
{
if (!$this->isConnected()) {
$this->connect();
}
if ($this->profiler) {
$this->profiler->profilerStart($sql);
}
$resultResource = $this->resource->query($sql);
if ($this->profiler) {
$this->profiler->profilerFinish($sql);
}
// if the returnValue is something other than a mysqli_result, bypass wrapping it
if ($resultResource === false) {
throw new Exception\InvalidQueryException($this->resource->error);
}
$resultPrototype = $this->driver->createResult(($resultResource === true) ? $this->resource : $resultResource);
return $resultPrototype;
}
/**
* {@inheritDoc}
*/
public function getLastGeneratedValue($name = null)
{
return $this->resource->insert_id;
}
}
zend-db-release-2.8.1/src/Adapter/Driver/Mysqli/Mysqli.php 0000664 0000000 0000000 00000014375 12703724304 0023346 0 ustar 00root root 0000000 0000000 false
];
/**
* Constructor
*
* @param array|Connection|\mysqli $connection
* @param null|Statement $statementPrototype
* @param null|Result $resultPrototype
* @param array $options
*/
public function __construct($connection, Statement $statementPrototype = null, Result $resultPrototype = null, array $options = [])
{
if (!$connection instanceof Connection) {
$connection = new Connection($connection);
}
$options = array_intersect_key(array_merge($this->options, $options), $this->options);
$this->registerConnection($connection);
$this->registerStatementPrototype(($statementPrototype) ?: new Statement($options['buffer_results']));
$this->registerResultPrototype(($resultPrototype) ?: new Result());
}
/**
* @param Profiler\ProfilerInterface $profiler
* @return Mysqli
*/
public function setProfiler(Profiler\ProfilerInterface $profiler)
{
$this->profiler = $profiler;
if ($this->connection instanceof Profiler\ProfilerAwareInterface) {
$this->connection->setProfiler($profiler);
}
if ($this->statementPrototype instanceof Profiler\ProfilerAwareInterface) {
$this->statementPrototype->setProfiler($profiler);
}
return $this;
}
/**
* @return null|Profiler\ProfilerInterface
*/
public function getProfiler()
{
return $this->profiler;
}
/**
* Register connection
*
* @param Connection $connection
* @return Mysqli
*/
public function registerConnection(Connection $connection)
{
$this->connection = $connection;
$this->connection->setDriver($this); // needs access to driver to createStatement()
return $this;
}
/**
* Register statement prototype
*
* @param Statement $statementPrototype
*/
public function registerStatementPrototype(Statement $statementPrototype)
{
$this->statementPrototype = $statementPrototype;
$this->statementPrototype->setDriver($this); // needs access to driver to createResult()
}
/**
* Get statement prototype
*
* @return null|Statement
*/
public function getStatementPrototype()
{
return $this->statementPrototype;
}
/**
* Register result prototype
*
* @param Result $resultPrototype
*/
public function registerResultPrototype(Result $resultPrototype)
{
$this->resultPrototype = $resultPrototype;
}
/**
* @return null|Result
*/
public function getResultPrototype()
{
return $this->resultPrototype;
}
/**
* Get database platform name
*
* @param string $nameFormat
* @return string
*/
public function getDatabasePlatformName($nameFormat = self::NAME_FORMAT_CAMELCASE)
{
if ($nameFormat == self::NAME_FORMAT_CAMELCASE) {
return 'Mysql';
}
return 'MySQL';
}
/**
* Check environment
*
* @throws Exception\RuntimeException
* @return void
*/
public function checkEnvironment()
{
if (!extension_loaded('mysqli')) {
throw new Exception\RuntimeException('The Mysqli extension is required for this adapter but the extension is not loaded');
}
}
/**
* Get connection
*
* @return Connection
*/
public function getConnection()
{
return $this->connection;
}
/**
* Create statement
*
* @param string $sqlOrResource
* @return Statement
*/
public function createStatement($sqlOrResource = null)
{
/**
* @todo Resource tracking
if (is_resource($sqlOrResource) && !in_array($sqlOrResource, $this->resources, true)) {
$this->resources[] = $sqlOrResource;
}
*/
$statement = clone $this->statementPrototype;
if ($sqlOrResource instanceof mysqli_stmt) {
$statement->setResource($sqlOrResource);
} else {
if (is_string($sqlOrResource)) {
$statement->setSql($sqlOrResource);
}
if (!$this->connection->isConnected()) {
$this->connection->connect();
}
$statement->initialize($this->connection->getResource());
}
return $statement;
}
/**
* Create result
*
* @param resource $resource
* @param null|bool $isBuffered
* @return Result
*/
public function createResult($resource, $isBuffered = null)
{
$result = clone $this->resultPrototype;
$result->initialize($resource, $this->connection->getLastGeneratedValue(), $isBuffered);
return $result;
}
/**
* Get prepare type
*
* @return string
*/
public function getPrepareType()
{
return self::PARAMETERIZATION_POSITIONAL;
}
/**
* Format parameter name
*
* @param string $name
* @param mixed $type
* @return string
*/
public function formatParameterName($name, $type = null)
{
return '?';
}
/**
* Get last generated value
*
* @return mixed
*/
public function getLastGeneratedValue()
{
return $this->getConnection()->getLastGeneratedValue();
}
}
zend-db-release-2.8.1/src/Adapter/Driver/Mysqli/Result.php 0000664 0000000 0000000 00000020051 12703724304 0023332 0 ustar 00root root 0000000 0000000 null, 'values' => []];
/**
* @var mixed
*/
protected $generatedValue = null;
/**
* Initialize
*
* @param mixed $resource
* @param mixed $generatedValue
* @param bool|null $isBuffered
* @throws Exception\InvalidArgumentException
* @return Result
*/
public function initialize($resource, $generatedValue, $isBuffered = null)
{
if (!$resource instanceof \mysqli && !$resource instanceof \mysqli_result && !$resource instanceof \mysqli_stmt) {
throw new Exception\InvalidArgumentException('Invalid resource provided.');
}
if ($isBuffered !== null) {
$this->isBuffered = $isBuffered;
} else {
if ($resource instanceof \mysqli || $resource instanceof \mysqli_result
|| $resource instanceof \mysqli_stmt && $resource->num_rows != 0) {
$this->isBuffered = true;
}
}
$this->resource = $resource;
$this->generatedValue = $generatedValue;
return $this;
}
/**
* Force buffering
*
* @throws Exception\RuntimeException
*/
public function buffer()
{
if ($this->resource instanceof \mysqli_stmt && $this->isBuffered !== true) {
if ($this->position > 0) {
throw new Exception\RuntimeException('Cannot buffer a result set that has started iteration.');
}
$this->resource->store_result();
$this->isBuffered = true;
}
}
/**
* Check if is buffered
*
* @return bool|null
*/
public function isBuffered()
{
return $this->isBuffered;
}
/**
* Return the resource
*
* @return mixed
*/
public function getResource()
{
return $this->resource;
}
/**
* Is query result?
*
* @return bool
*/
public function isQueryResult()
{
return ($this->resource->field_count > 0);
}
/**
* Get affected rows
*
* @return int
*/
public function getAffectedRows()
{
if ($this->resource instanceof \mysqli || $this->resource instanceof \mysqli_stmt) {
return $this->resource->affected_rows;
}
return $this->resource->num_rows;
}
/**
* Current
*
* @return mixed
*/
public function current()
{
if ($this->currentComplete) {
return $this->currentData;
}
if ($this->resource instanceof \mysqli_stmt) {
$this->loadDataFromMysqliStatement();
return $this->currentData;
} else {
$this->loadFromMysqliResult();
return $this->currentData;
}
}
/**
* Mysqli's binding and returning of statement values
*
* Mysqli requires you to bind variables to the extension in order to
* get data out. These values have to be references:
* @see http://php.net/manual/en/mysqli-stmt.bind-result.php
*
* @throws Exception\RuntimeException
* @return bool
*/
protected function loadDataFromMysqliStatement()
{
// build the default reference based bind structure, if it does not already exist
if ($this->statementBindValues['keys'] === null) {
$this->statementBindValues['keys'] = [];
$resultResource = $this->resource->result_metadata();
foreach ($resultResource->fetch_fields() as $col) {
$this->statementBindValues['keys'][] = $col->name;
}
$this->statementBindValues['values'] = array_fill(0, count($this->statementBindValues['keys']), null);
$refs = [];
foreach ($this->statementBindValues['values'] as $i => &$f) {
$refs[$i] = &$f;
}
call_user_func_array([$this->resource, 'bind_result'], $this->statementBindValues['values']);
}
if (($r = $this->resource->fetch()) === null) {
if (!$this->isBuffered) {
$this->resource->close();
}
return false;
} elseif ($r === false) {
throw new Exception\RuntimeException($this->resource->error);
}
// dereference
for ($i = 0, $count = count($this->statementBindValues['keys']); $i < $count; $i++) {
$this->currentData[$this->statementBindValues['keys'][$i]] = $this->statementBindValues['values'][$i];
}
$this->currentComplete = true;
$this->nextComplete = true;
$this->position++;
return true;
}
/**
* Load from mysqli result
*
* @return bool
*/
protected function loadFromMysqliResult()
{
$this->currentData = null;
if (($data = $this->resource->fetch_assoc()) === null) {
return false;
}
$this->position++;
$this->currentData = $data;
$this->currentComplete = true;
$this->nextComplete = true;
$this->position++;
return true;
}
/**
* Next
*
* @return void
*/
public function next()
{
$this->currentComplete = false;
if ($this->nextComplete == false) {
$this->position++;
}
$this->nextComplete = false;
}
/**
* Key
*
* @return mixed
*/
public function key()
{
return $this->position;
}
/**
* Rewind
*
* @throws Exception\RuntimeException
* @return void
*/
public function rewind()
{
if ($this->position !== 0) {
if ($this->isBuffered === false) {
throw new Exception\RuntimeException('Unbuffered results cannot be rewound for multiple iterations');
}
}
$this->resource->data_seek(0); // works for both mysqli_result & mysqli_stmt
$this->currentComplete = false;
$this->position = 0;
}
/**
* Valid
*
* @return bool
*/
public function valid()
{
if ($this->currentComplete) {
return true;
}
if ($this->resource instanceof \mysqli_stmt) {
return $this->loadDataFromMysqliStatement();
}
return $this->loadFromMysqliResult();
}
/**
* Count
*
* @throws Exception\RuntimeException
* @return int
*/
public function count()
{
if ($this->isBuffered === false) {
throw new Exception\RuntimeException('Row count is not available in unbuffered result sets.');
}
return $this->resource->num_rows;
}
/**
* Get field count
*
* @return int
*/
public function getFieldCount()
{
return $this->resource->field_count;
}
/**
* Get generated value
*
* @return mixed|null
*/
public function getGeneratedValue()
{
return $this->generatedValue;
}
}
zend-db-release-2.8.1/src/Adapter/Driver/Mysqli/Statement.php 0000664 0000000 0000000 00000016317 12703724304 0024032 0 ustar 00root root 0000000 0000000 bufferResults = (bool) $bufferResults;
}
/**
* Set driver
*
* @param Mysqli $driver
* @return Statement
*/
public function setDriver(Mysqli $driver)
{
$this->driver = $driver;
return $this;
}
/**
* @param Profiler\ProfilerInterface $profiler
* @return Statement
*/
public function setProfiler(Profiler\ProfilerInterface $profiler)
{
$this->profiler = $profiler;
return $this;
}
/**
* @return null|Profiler\ProfilerInterface
*/
public function getProfiler()
{
return $this->profiler;
}
/**
* Initialize
*
* @param \mysqli $mysqli
* @return Statement
*/
public function initialize(\mysqli $mysqli)
{
$this->mysqli = $mysqli;
return $this;
}
/**
* Set sql
*
* @param string $sql
* @return Statement
*/
public function setSql($sql)
{
$this->sql = $sql;
return $this;
}
/**
* Set Parameter container
*
* @param ParameterContainer $parameterContainer
* @return Statement
*/
public function setParameterContainer(ParameterContainer $parameterContainer)
{
$this->parameterContainer = $parameterContainer;
return $this;
}
/**
* Get resource
*
* @return mixed
*/
public function getResource()
{
return $this->resource;
}
/**
* Set resource
*
* @param \mysqli_stmt $mysqliStatement
* @return Statement
*/
public function setResource(\mysqli_stmt $mysqliStatement)
{
$this->resource = $mysqliStatement;
$this->isPrepared = true;
return $this;
}
/**
* Get sql
*
* @return string
*/
public function getSql()
{
return $this->sql;
}
/**
* Get parameter count
*
* @return ParameterContainer
*/
public function getParameterContainer()
{
return $this->parameterContainer;
}
/**
* Is prepared
*
* @return bool
*/
public function isPrepared()
{
return $this->isPrepared;
}
/**
* Prepare
*
* @param string $sql
* @throws Exception\InvalidQueryException
* @throws Exception\RuntimeException
* @return Statement
*/
public function prepare($sql = null)
{
if ($this->isPrepared) {
throw new Exception\RuntimeException('This statement has already been prepared');
}
$sql = ($sql) ?: $this->sql;
$this->resource = $this->mysqli->prepare($sql);
if (!$this->resource instanceof \mysqli_stmt) {
throw new Exception\InvalidQueryException(
'Statement couldn\'t be produced with sql: ' . $sql,
null,
new Exception\ErrorException($this->mysqli->error, $this->mysqli->errno)
);
}
$this->isPrepared = true;
return $this;
}
/**
* Execute
*
* @param null|array|ParameterContainer $parameters
* @throws Exception\RuntimeException
* @return mixed
*/
public function execute($parameters = null)
{
if (!$this->isPrepared) {
$this->prepare();
}
/** START Standard ParameterContainer Merging Block */
if (!$this->parameterContainer instanceof ParameterContainer) {
if ($parameters instanceof ParameterContainer) {
$this->parameterContainer = $parameters;
$parameters = null;
} else {
$this->parameterContainer = new ParameterContainer();
}
}
if (is_array($parameters)) {
$this->parameterContainer->setFromArray($parameters);
}
if ($this->parameterContainer->count() > 0) {
$this->bindParametersFromContainer();
}
/** END Standard ParameterContainer Merging Block */
if ($this->profiler) {
$this->profiler->profilerStart($this);
}
$return = $this->resource->execute();
if ($this->profiler) {
$this->profiler->profilerFinish();
}
if ($return === false) {
throw new Exception\RuntimeException($this->resource->error);
}
if ($this->bufferResults === true) {
$this->resource->store_result();
$this->isPrepared = false;
$buffered = true;
} else {
$buffered = false;
}
$result = $this->driver->createResult($this->resource, $buffered);
return $result;
}
/**
* Bind parameters from container
*
* @return void
*/
protected function bindParametersFromContainer()
{
$parameters = $this->parameterContainer->getNamedArray();
$type = '';
$args = [];
foreach ($parameters as $name => &$value) {
if ($this->parameterContainer->offsetHasErrata($name)) {
switch ($this->parameterContainer->offsetGetErrata($name)) {
case ParameterContainer::TYPE_DOUBLE:
$type .= 'd';
break;
case ParameterContainer::TYPE_NULL:
$value = null; // as per @see http://www.php.net/manual/en/mysqli-stmt.bind-param.php#96148
case ParameterContainer::TYPE_INTEGER:
$type .= 'i';
break;
case ParameterContainer::TYPE_STRING:
default:
$type .= 's';
break;
}
} else {
$type .= 's';
}
$args[] = &$value;
}
if ($args) {
array_unshift($args, $type);
call_user_func_array([$this->resource, 'bind_param'], $args);
}
}
}
zend-db-release-2.8.1/src/Adapter/Driver/Oci8/ 0000775 0000000 0000000 00000000000 12703724304 0020671 5 ustar 00root root 0000000 0000000 zend-db-release-2.8.1/src/Adapter/Driver/Oci8/Connection.php 0000664 0000000 0000000 00000015557 12703724304 0023516 0 ustar 00root root 0000000 0000000 setConnectionParameters($connectionInfo);
} elseif ($connectionInfo instanceof \oci8) {
$this->setResource($connectionInfo);
} elseif (null !== $connectionInfo) {
throw new Exception\InvalidArgumentException('$connection must be an array of parameters, an oci8 resource or null');
}
}
/**
* @param Oci8 $driver
* @return self
*/
public function setDriver(Oci8 $driver)
{
$this->driver = $driver;
return $this;
}
/**
* {@inheritDoc}
*/
public function getCurrentSchema()
{
if (!$this->isConnected()) {
$this->connect();
}
$query = "SELECT sys_context('USERENV', 'CURRENT_SCHEMA') as \"current_schema\" FROM DUAL";
$stmt = oci_parse($this->resource, $query);
oci_execute($stmt);
$dbNameArray = oci_fetch_array($stmt, OCI_ASSOC);
return $dbNameArray['current_schema'];
}
/**
* Set resource
*
* @param resource $resource
* @return self
*/
public function setResource($resource)
{
if (!is_resource($resource) || get_resource_type($resource) !== 'oci8 connection') {
throw new Exception\InvalidArgumentException('A resource of type "oci8 connection" was expected');
}
$this->resource = $resource;
return $this;
}
/**
* {@inheritDoc}
*/
public function connect()
{
if (is_resource($this->resource)) {
return $this;
}
// localize
$p = $this->connectionParameters;
// given a list of key names, test for existence in $p
$findParameterValue = function (array $names) use ($p) {
foreach ($names as $name) {
if (isset($p[$name])) {
return $p[$name];
}
}
return;
};
// http://www.php.net/manual/en/function.oci-connect.php
$username = $findParameterValue(['username']);
$password = $findParameterValue(['password']);
$connectionString = $findParameterValue(['connection_string', 'connectionstring', 'connection', 'hostname', 'instance']);
$characterSet = $findParameterValue(['character_set', 'charset', 'encoding']);
$sessionMode = $findParameterValue(['session_mode']);
// connection modifiers
$isUnique = $findParameterValue(['unique']);
$isPersistent = $findParameterValue(['persistent']);
if ($isUnique == true) {
$this->resource = oci_new_connect($username, $password, $connectionString, $characterSet, $sessionMode);
} elseif ($isPersistent == true) {
$this->resource = oci_pconnect($username, $password, $connectionString, $characterSet, $sessionMode);
} else {
$this->resource = oci_connect($username, $password, $connectionString, $characterSet, $sessionMode);
}
if (!$this->resource) {
$e = oci_error();
throw new Exception\RuntimeException(
'Connection error',
null,
new Exception\ErrorException($e['message'], $e['code'])
);
}
return $this;
}
/**
* {@inheritDoc}
*/
public function isConnected()
{
return (is_resource($this->resource));
}
/**
* {@inheritDoc}
*/
public function disconnect()
{
if (is_resource($this->resource)) {
oci_close($this->resource);
}
}
/**
* {@inheritDoc}
*/
public function beginTransaction()
{
if (!$this->isConnected()) {
$this->connect();
}
// A transaction begins when the first SQL statement that changes data is executed with oci_execute() using the OCI_NO_AUTO_COMMIT flag.
$this->inTransaction = true;
return $this;
}
/**
* {@inheritDoc}
*/
public function commit()
{
if (!$this->isConnected()) {
$this->connect();
}
if ($this->inTransaction()) {
$valid = oci_commit($this->resource);
if ($valid === false) {
$e = oci_error($this->resource);
throw new Exception\InvalidQueryException($e['message'], $e['code']);
}
$this->inTransaction = false;
}
return $this;
}
/**
* {@inheritDoc}
*/
public function rollback()
{
if (!$this->isConnected()) {
throw new Exception\RuntimeException('Must be connected before you can rollback.');
}
if (!$this->inTransaction()) {
throw new Exception\RuntimeException('Must call commit() before you can rollback.');
}
$valid = oci_rollback($this->resource);
if ($valid === false) {
$e = oci_error($this->resource);
throw new Exception\InvalidQueryException($e['message'], $e['code']);
}
$this->inTransaction = false;
return $this;
}
/**
* {@inheritDoc}
*/
public function execute($sql)
{
if (!$this->isConnected()) {
$this->connect();
}
if ($this->profiler) {
$this->profiler->profilerStart($sql);
}
$ociStmt = oci_parse($this->resource, $sql);
if ($this->inTransaction) {
$valid = @oci_execute($ociStmt, OCI_NO_AUTO_COMMIT);
} else {
$valid = @oci_execute($ociStmt, OCI_COMMIT_ON_SUCCESS);
}
if ($this->profiler) {
$this->profiler->profilerFinish($sql);
}
if ($valid === false) {
$e = oci_error($ociStmt);
throw new Exception\InvalidQueryException($e['message'], $e['code']);
}
$resultPrototype = $this->driver->createResult($ociStmt);
return $resultPrototype;
}
/**
* {@inheritDoc}
*/
public function getLastGeneratedValue($name = null)
{
// @todo Get Last Generated Value in Connection (this might not apply)
return;
}
}
zend-db-release-2.8.1/src/Adapter/Driver/Oci8/Feature/ 0000775 0000000 0000000 00000000000 12703724304 0022264 5 ustar 00root root 0000000 0000000 zend-db-release-2.8.1/src/Adapter/Driver/Oci8/Feature/RowCounter.php 0000664 0000000 0000000 00000004117 12703724304 0025107 0 ustar 00root root 0000000 0000000 getSql();
if ($sql == '' || stripos(strtolower($sql), 'select') === false) {
return;
}
$countSql = 'SELECT COUNT(*) as "count" FROM (' . $sql . ')';
$countStmt->prepare($countSql);
$result = $countStmt->execute();
$countRow = $result->current();
return $countRow['count'];
}
/**
* @param string $sql
* @return null|int
*/
public function getCountForSql($sql)
{
if (stripos(strtolower($sql), 'select') === false) {
return;
}
$countSql = 'SELECT COUNT(*) as "count" FROM (' . $sql . ')';
$result = $this->driver->getConnection()->execute($countSql);
$countRow = $result->current();
return $countRow['count'];
}
/**
* @param \Zend\Db\Adapter\Driver\Oci8\Statement|string $context
* @return callable
*/
public function getRowCountClosure($context)
{
$rowCounter = $this;
return function () use ($rowCounter, $context) {
/** @var $rowCounter RowCounter */
return ($context instanceof Statement)
? $rowCounter->getCountForStatement($context)
: $rowCounter->getCountForSql($context);
};
}
}
zend-db-release-2.8.1/src/Adapter/Driver/Oci8/Oci8.php 0000664 0000000 0000000 00000017213 12703724304 0022210 0 ustar 00root root 0000000 0000000 options, $options), $this->options);
$this->registerConnection($connection);
$this->registerStatementPrototype(($statementPrototype) ?: new Statement());
$this->registerResultPrototype(($resultPrototype) ?: new Result());
if (is_array($features)) {
foreach ($features as $name => $feature) {
$this->addFeature($name, $feature);
}
} elseif ($features instanceof AbstractFeature) {
$this->addFeature($features->getName(), $features);
} elseif ($features === self::FEATURES_DEFAULT) {
$this->setupDefaultFeatures();
}
}
/**
* @param Profiler\ProfilerInterface $profiler
* @return Oci8
*/
public function setProfiler(Profiler\ProfilerInterface $profiler)
{
$this->profiler = $profiler;
if ($this->connection instanceof Profiler\ProfilerAwareInterface) {
$this->connection->setProfiler($profiler);
}
if ($this->statementPrototype instanceof Profiler\ProfilerAwareInterface) {
$this->statementPrototype->setProfiler($profiler);
}
return $this;
}
/**
* @return null|Profiler\ProfilerInterface
*/
public function getProfiler()
{
return $this->profiler;
}
/**
* Register connection
*
* @param Connection $connection
* @return Oci8
*/
public function registerConnection(Connection $connection)
{
$this->connection = $connection;
$this->connection->setDriver($this); // needs access to driver to createStatement()
return $this;
}
/**
* Register statement prototype
*
* @param Statement $statementPrototype
* @return Oci8
*/
public function registerStatementPrototype(Statement $statementPrototype)
{
$this->statementPrototype = $statementPrototype;
$this->statementPrototype->setDriver($this); // needs access to driver to createResult()
return $this;
}
/**
* @return null|Statement
*/
public function getStatementPrototype()
{
return $this->statementPrototype;
}
/**
* Register result prototype
*
* @param Result $resultPrototype
* @return Oci8
*/
public function registerResultPrototype(Result $resultPrototype)
{
$this->resultPrototype = $resultPrototype;
return $this;
}
/**
* @return null|Result
*/
public function getResultPrototype()
{
return $this->resultPrototype;
}
/**
* Add feature
*
* @param string $name
* @param AbstractFeature $feature
* @return self
*/
public function addFeature($name, $feature)
{
if ($feature instanceof AbstractFeature) {
$name = $feature->getName(); // overwrite the name, just in case
$feature->setDriver($this);
}
$this->features[$name] = $feature;
return $this;
}
/**
* Setup the default features for Pdo
*
* @return self
*/
public function setupDefaultFeatures()
{
$this->addFeature(null, new Feature\RowCounter());
return $this;
}
/**
* Get feature
*
* @param string $name
* @return AbstractFeature|false
*/
public function getFeature($name)
{
if (isset($this->features[$name])) {
return $this->features[$name];
}
return false;
}
/**
* Get database platform name
*
* @param string $nameFormat
* @return string
*/
public function getDatabasePlatformName($nameFormat = self::NAME_FORMAT_CAMELCASE)
{
return 'Oracle';
}
/**
* Check environment
*/
public function checkEnvironment()
{
if (!extension_loaded('oci8')) {
throw new Exception\RuntimeException(
'The Oci8 extension is required for this adapter but the extension is not loaded'
);
}
}
/**
* @return Connection
*/
public function getConnection()
{
return $this->connection;
}
/**
* @param string $sqlOrResource
* @return Statement
*/
public function createStatement($sqlOrResource = null)
{
$statement = clone $this->statementPrototype;
if (is_resource($sqlOrResource) && get_resource_type($sqlOrResource) == 'oci8 statement') {
$statement->setResource($sqlOrResource);
} else {
if (is_string($sqlOrResource)) {
$statement->setSql($sqlOrResource);
} elseif ($sqlOrResource !== null) {
throw new Exception\InvalidArgumentException(
'Oci8 only accepts an SQL string or an oci8 resource in ' . __FUNCTION__
);
}
if (!$this->connection->isConnected()) {
$this->connection->connect();
}
$statement->initialize($this->connection->getResource());
}
return $statement;
}
/**
* @param resource $resource
* @param null $context
* @return Result
*/
public function createResult($resource, $context = null)
{
$result = clone $this->resultPrototype;
$rowCount = null;
// special feature, oracle Oci counter
if ($context && ($rowCounter = $this->getFeature('RowCounter')) && oci_num_fields($resource) > 0) {
$rowCount = $rowCounter->getRowCountClosure($context);
}
$result->initialize($resource, null, $rowCount);
return $result;
}
/**
* @return string
*/
public function getPrepareType()
{
return self::PARAMETERIZATION_NAMED;
}
/**
* @param string $name
* @param mixed $type
* @return string
*/
public function formatParameterName($name, $type = null)
{
return ':' . $name;
}
/**
* @return mixed
*/
public function getLastGeneratedValue()
{
return $this->getConnection()->getLastGeneratedValue();
}
}
zend-db-release-2.8.1/src/Adapter/Driver/Oci8/Result.php 0000664 0000000 0000000 00000011012 12703724304 0022653 0 ustar 00root root 0000000 0000000 null, 'values' => []];
/**
* @var mixed
*/
protected $generatedValue = null;
/**
* Initialize
* @param resource $resource
* @param null|int $generatedValue
* @param null|int $rowCount
* @return Result
*/
public function initialize($resource, $generatedValue = null, $rowCount = null)
{
if (!is_resource($resource) && get_resource_type($resource) !== 'oci8 statement') {
throw new Exception\InvalidArgumentException('Invalid resource provided.');
}
$this->resource = $resource;
$this->generatedValue = $generatedValue;
$this->rowCount = $rowCount;
return $this;
}
/**
* Force buffering at driver level
*
* Oracle does not support this, to my knowledge (@ralphschindler)
*
* @throws Exception\RuntimeException
*/
public function buffer()
{
return;
}
/**
* Is the result buffered?
*
* @return bool
*/
public function isBuffered()
{
return false;
}
/**
* Return the resource
* @return mixed
*/
public function getResource()
{
return $this->resource;
}
/**
* Is query result?
*
* @return bool
*/
public function isQueryResult()
{
return (oci_num_fields($this->resource) > 0);
}
/**
* Get affected rows
* @return int
*/
public function getAffectedRows()
{
return oci_num_rows($this->resource);
}
/**
* Current
* @return mixed
*/
public function current()
{
if ($this->currentComplete == false) {
if ($this->loadData() === false) {
return false;
}
}
return $this->currentData;
}
/**
* Load from oci8 result
*
* @return bool
*/
protected function loadData()
{
$this->currentComplete = true;
$this->currentData = oci_fetch_assoc($this->resource);
if ($this->currentData !== false) {
$this->position++;
return true;
}
return false;
}
/**
* Next
*/
public function next()
{
return $this->loadData();
}
/**
* Key
* @return mixed
*/
public function key()
{
return $this->position;
}
/**
* Rewind
*/
public function rewind()
{
if ($this->position > 0) {
throw new Exception\RuntimeException('Oci8 results cannot be rewound for multiple iterations');
}
}
/**
* Valid
* @return bool
*/
public function valid()
{
if ($this->currentComplete) {
return ($this->currentData !== false);
}
return $this->loadData();
}
/**
* Count
* @return null|int
*/
public function count()
{
if (is_int($this->rowCount)) {
return $this->rowCount;
}
if (is_callable($this->rowCount)) {
$this->rowCount = (int) call_user_func($this->rowCount);
return $this->rowCount;
}
return;
}
/**
* @return int
*/
public function getFieldCount()
{
return oci_num_fields($this->resource);
}
/**
* @return null
*/
public function getGeneratedValue()
{
// @todo OCI8 generated value in Driver Result
return;
}
}
zend-db-release-2.8.1/src/Adapter/Driver/Oci8/Statement.php 0000664 0000000 0000000 00000020022 12703724304 0023342 0 ustar 00root root 0000000 0000000 driver = $driver;
return $this;
}
/**
* @param Profiler\ProfilerInterface $profiler
* @return Statement
*/
public function setProfiler(Profiler\ProfilerInterface $profiler)
{
$this->profiler = $profiler;
return $this;
}
/**
* @return null|Profiler\ProfilerInterface
*/
public function getProfiler()
{
return $this->profiler;
}
/**
* Initialize
*
* @param resource $oci8
* @return Statement
*/
public function initialize($oci8)
{
$this->oci8 = $oci8;
return $this;
}
/**
* Set sql
*
* @param string $sql
* @return Statement
*/
public function setSql($sql)
{
$this->sql = $sql;
return $this;
}
/**
* Set Parameter container
*
* @param ParameterContainer $parameterContainer
* @return Statement
*/
public function setParameterContainer(ParameterContainer $parameterContainer)
{
$this->parameterContainer = $parameterContainer;
return $this;
}
/**
* Get resource
*
* @return mixed
*/
public function getResource()
{
return $this->resource;
}
/**
* Set resource
*
* @param resource $oci8Statement
* @return Statement
*/
public function setResource($oci8Statement)
{
$type = oci_statement_type($oci8Statement);
if (false === $type || 'UNKNOWN' == $type) {
throw new Exception\InvalidArgumentException(sprintf(
'Invalid statement provided to %s',
__METHOD__
));
}
$this->resource = $oci8Statement;
$this->isPrepared = true;
return $this;
}
/**
* Get sql
*
* @return string
*/
public function getSql()
{
return $this->sql;
}
/**
* @return ParameterContainer
*/
public function getParameterContainer()
{
return $this->parameterContainer;
}
/**
* @return bool
*/
public function isPrepared()
{
return $this->isPrepared;
}
/**
* @param string $sql
* @return Statement
*/
public function prepare($sql = null)
{
if ($this->isPrepared) {
throw new Exception\RuntimeException('This statement has already been prepared');
}
$sql = ($sql) ?: $this->sql;
// get oci8 statement resource
$this->resource = oci_parse($this->oci8, $sql);
if (!$this->resource) {
$e = oci_error($this->oci8);
throw new Exception\InvalidQueryException(
'Statement couldn\'t be produced with sql: ' . $sql,
null,
new Exception\ErrorException($e['message'], $e['code'])
);
}
$this->isPrepared = true;
return $this;
}
/**
* Execute
*
* @param null|array|ParameterContainer $parameters
* @return mixed
*/
public function execute($parameters = null)
{
if (!$this->isPrepared) {
$this->prepare();
}
/** START Standard ParameterContainer Merging Block */
if (!$this->parameterContainer instanceof ParameterContainer) {
if ($parameters instanceof ParameterContainer) {
$this->parameterContainer = $parameters;
$parameters = null;
} else {
$this->parameterContainer = new ParameterContainer();
}
}
if (is_array($parameters)) {
$this->parameterContainer->setFromArray($parameters);
}
if ($this->parameterContainer->count() > 0) {
$this->bindParametersFromContainer();
}
/** END Standard ParameterContainer Merging Block */
if ($this->profiler) {
$this->profiler->profilerStart($this);
}
if ($this->driver->getConnection()->inTransaction()) {
$ret = @oci_execute($this->resource, OCI_NO_AUTO_COMMIT);
} else {
$ret = @oci_execute($this->resource, OCI_COMMIT_ON_SUCCESS);
}
if ($this->profiler) {
$this->profiler->profilerFinish();
}
if ($ret === false) {
$e = oci_error($this->resource);
throw new Exception\RuntimeException($e['message'], $e['code']);
}
$result = $this->driver->createResult($this->resource, $this);
return $result;
}
/**
* Bind parameters from container
*
* @param ParameterContainer $pContainer
*/
protected function bindParametersFromContainer()
{
$parameters = $this->parameterContainer->getNamedArray();
foreach ($parameters as $name => &$value) {
if ($this->parameterContainer->offsetHasErrata($name)) {
switch ($this->parameterContainer->offsetGetErrata($name)) {
case ParameterContainer::TYPE_NULL:
$type = null;
$value = null;
break;
case ParameterContainer::TYPE_DOUBLE:
case ParameterContainer::TYPE_INTEGER:
$type = SQLT_INT;
if (is_string($value)) {
$value = (int) $value;
}
break;
case ParameterContainer::TYPE_BINARY:
$type = SQLT_BIN;
break;
case ParameterContainer::TYPE_LOB:
$type = OCI_B_CLOB;
$clob = oci_new_descriptor($this->driver->getConnection()->getResource(), OCI_DTYPE_LOB);
$clob->writetemporary($value, OCI_TEMP_CLOB);
$value = $clob;
break;
case ParameterContainer::TYPE_STRING:
default:
$type = SQLT_CHR;
break;
}
} else {
$type = SQLT_CHR;
}
$maxLength = -1;
if ($this->parameterContainer->offsetHasMaxLength($name)) {
$maxLength = $this->parameterContainer->offsetGetMaxLength($name);
}
oci_bind_by_name($this->resource, $name, $value, $maxLength, $type);
}
}
/**
* Perform a deep clone
*/
public function __clone()
{
$this->isPrepared = false;
$this->parametersBound = false;
$this->resource = null;
if ($this->parameterContainer) {
$this->parameterContainer = clone $this->parameterContainer;
}
}
}
zend-db-release-2.8.1/src/Adapter/Driver/Pdo/ 0000775 0000000 0000000 00000000000 12703724304 0020611 5 ustar 00root root 0000000 0000000 zend-db-release-2.8.1/src/Adapter/Driver/Pdo/Connection.php 0000664 0000000 0000000 00000027172 12703724304 0023432 0 ustar 00root root 0000000 0000000 setConnectionParameters($connectionParameters);
} elseif ($connectionParameters instanceof \PDO) {
$this->setResource($connectionParameters);
} elseif (null !== $connectionParameters) {
throw new Exception\InvalidArgumentException(
'$connection must be an array of parameters, a PDO object or null'
);
}
}
/**
* Set driver
*
* @param Pdo $driver
* @return self
*/
public function setDriver(Pdo $driver)
{
$this->driver = $driver;
return $this;
}
/**
* {@inheritDoc}
*/
public function setConnectionParameters(array $connectionParameters)
{
$this->connectionParameters = $connectionParameters;
if (isset($connectionParameters['dsn'])) {
$this->driverName = substr(
$connectionParameters['dsn'],
0,
strpos($connectionParameters['dsn'], ':')
);
} elseif (isset($connectionParameters['pdodriver'])) {
$this->driverName = strtolower($connectionParameters['pdodriver']);
} elseif (isset($connectionParameters['driver'])) {
$this->driverName = strtolower(substr(
str_replace(['-', '_', ' '], '', $connectionParameters['driver']),
3
));
}
}
/**
* Get the dsn string for this connection
* @throws \Zend\Db\Adapter\Exception\RunTimeException
* @return string
*/
public function getDsn()
{
if (!$this->dsn) {
throw new Exception\RunTimeException(
'The DSN has not been set or constructed from parameters in connect() for this Connection'
);
}
return $this->dsn;
}
/**
* {@inheritDoc}
*/
public function getCurrentSchema()
{
if (!$this->isConnected()) {
$this->connect();
}
switch ($this->driverName) {
case 'mysql':
$sql = 'SELECT DATABASE()';
break;
case 'sqlite':
return 'main';
case 'sqlsrv':
case 'dblib':
$sql = 'SELECT SCHEMA_NAME()';
break;
case 'pgsql':
default:
$sql = 'SELECT CURRENT_SCHEMA';
break;
}
/** @var $result \PDOStatement */
$result = $this->resource->query($sql);
if ($result instanceof \PDOStatement) {
return $result->fetchColumn();
}
return false;
}
/**
* Set resource
*
* @param \PDO $resource
* @return self
*/
public function setResource(\PDO $resource)
{
$this->resource = $resource;
$this->driverName = strtolower($this->resource->getAttribute(\PDO::ATTR_DRIVER_NAME));
return $this;
}
/**
* {@inheritDoc}
*
* @throws Exception\InvalidConnectionParametersException
* @throws Exception\RuntimeException
*/
public function connect()
{
if ($this->resource) {
return $this;
}
$dsn = $username = $password = $hostname = $database = null;
$options = [];
foreach ($this->connectionParameters as $key => $value) {
switch (strtolower($key)) {
case 'dsn':
$dsn = $value;
break;
case 'driver':
$value = strtolower((string) $value);
if (strpos($value, 'pdo') === 0) {
$pdoDriver = str_replace(['-', '_', ' '], '', $value);
$pdoDriver = substr($pdoDriver, 3) ?: '';
$pdoDriver = strtolower($pdoDriver);
}
break;
case 'pdodriver':
$pdoDriver = (string) $value;
break;
case 'user':
case 'username':
$username = (string) $value;
break;
case 'pass':
case 'password':
$password = (string) $value;
break;
case 'host':
case 'hostname':
$hostname = (string) $value;
break;
case 'port':
$port = (int) $value;
break;
case 'database':
case 'dbname':
$database = (string) $value;
break;
case 'charset':
$charset = (string) $value;
break;
case 'unix_socket':
$unix_socket = (string) $value;
break;
case 'driver_options':
case 'options':
$value = (array) $value;
$options = array_diff_key($options, $value) + $value;
break;
default:
$options[$key] = $value;
break;
}
}
if (isset($hostname) && isset($unix_socket)) {
throw new Exception\InvalidConnectionParametersException(
'Ambiguous connection parameters, both hostname and unix_socket parameters were set',
$this->connectionParameters
);
}
if (!isset($dsn) && isset($pdoDriver)) {
$dsn = [];
switch ($pdoDriver) {
case 'sqlite':
$dsn[] = $database;
break;
case 'sqlsrv':
if (isset($database)) {
$dsn[] = "database={$database}";
}
if (isset($hostname)) {
$dsn[] = "server={$hostname}";
}
break;
default:
if (isset($database)) {
$dsn[] = "dbname={$database}";
}
if (isset($hostname)) {
$dsn[] = "host={$hostname}";
}
if (isset($port)) {
$dsn[] = "port={$port}";
}
if (isset($charset) && $pdoDriver != 'pgsql') {
$dsn[] = "charset={$charset}";
}
if (isset($unix_socket)) {
$dsn[] = "unix_socket={$unix_socket}";
}
break;
}
$dsn = $pdoDriver . ':' . implode(';', $dsn);
} elseif (!isset($dsn)) {
throw new Exception\InvalidConnectionParametersException(
'A dsn was not provided or could not be constructed from your parameters',
$this->connectionParameters
);
}
$this->dsn = $dsn;
try {
$this->resource = new \PDO($dsn, $username, $password, $options);
$this->resource->setAttribute(\PDO::ATTR_ERRMODE, \PDO::ERRMODE_EXCEPTION);
if (isset($charset) && $pdoDriver == 'pgsql') {
$this->resource->exec('SET NAMES ' . $this->resource->quote($charset));
}
$this->driverName = strtolower($this->resource->getAttribute(\PDO::ATTR_DRIVER_NAME));
} catch (\PDOException $e) {
$code = $e->getCode();
if (!is_long($code)) {
$code = null;
}
throw new Exception\RuntimeException('Connect Error: ' . $e->getMessage(), $code, $e);
}
return $this;
}
/**
* {@inheritDoc}
*/
public function isConnected()
{
return ($this->resource instanceof \PDO);
}
/**
* {@inheritDoc}
*/
public function beginTransaction()
{
if (!$this->isConnected()) {
$this->connect();
}
if (0 === $this->nestedTransactionsCount) {
$this->resource->beginTransaction();
$this->inTransaction = true;
}
$this->nestedTransactionsCount ++;
return $this;
}
/**
* {@inheritDoc}
*/
public function commit()
{
if (!$this->isConnected()) {
$this->connect();
}
if ($this->inTransaction) {
$this->nestedTransactionsCount -= 1;
}
/*
* This shouldn't check for being in a transaction since
* after issuing a SET autocommit=0; we have to commit too.
*/
if (0 === $this->nestedTransactionsCount) {
$this->resource->commit();
$this->inTransaction = false;
}
return $this;
}
/**
* {@inheritDoc}
*
* @throws Exception\RuntimeException
*/
public function rollback()
{
if (!$this->isConnected()) {
throw new Exception\RuntimeException('Must be connected before you can rollback');
}
if (!$this->inTransaction()) {
throw new Exception\RuntimeException('Must call beginTransaction() before you can rollback');
}
$this->resource->rollBack();
$this->inTransaction = false;
$this->nestedTransactionsCount = 0;
return $this;
}
/**
* {@inheritDoc}
*
* @throws Exception\InvalidQueryException
*/
public function execute($sql)
{
if (!$this->isConnected()) {
$this->connect();
}
if ($this->profiler) {
$this->profiler->profilerStart($sql);
}
$resultResource = $this->resource->query($sql);
if ($this->profiler) {
$this->profiler->profilerFinish($sql);
}
if ($resultResource === false) {
$errorInfo = $this->resource->errorInfo();
throw new Exception\InvalidQueryException($errorInfo[2]);
}
$result = $this->driver->createResult($resultResource, $sql);
return $result;
}
/**
* Prepare
*
* @param string $sql
* @return Statement
*/
public function prepare($sql)
{
if (!$this->isConnected()) {
$this->connect();
}
$statement = $this->driver->createStatement($sql);
return $statement;
}
/**
* {@inheritDoc}
*
* @param string $name
* @return string|null|false
*/
public function getLastGeneratedValue($name = null)
{
if ($name === null && $this->driverName == 'pgsql') {
return;
}
try {
return $this->resource->lastInsertId($name);
} catch (\Exception $e) {
// do nothing
}
return false;
}
}
zend-db-release-2.8.1/src/Adapter/Driver/Pdo/Feature/ 0000775 0000000 0000000 00000000000 12703724304 0022204 5 ustar 00root root 0000000 0000000 zend-db-release-2.8.1/src/Adapter/Driver/Pdo/Feature/OracleRowCounter.php 0000664 0000000 0000000 00000004065 12703724304 0026157 0 ustar 00root root 0000000 0000000 getSql();
if ($sql == '' || stripos($sql, 'select') === false) {
return;
}
$countSql = 'SELECT COUNT(*) as "count" FROM (' . $sql . ')';
$countStmt->prepare($countSql);
$result = $countStmt->execute();
$countRow = $result->getResource()->fetch(\PDO::FETCH_ASSOC);
unset($statement, $result);
return $countRow['count'];
}
/**
* @param $sql
* @return null|int
*/
public function getCountForSql($sql)
{
if (stripos($sql, 'select') === false) {
return;
}
$countSql = 'SELECT COUNT(*) as count FROM (' . $sql . ')';
/** @var $pdo \PDO */
$pdo = $this->driver->getConnection()->getResource();
$result = $pdo->query($countSql);
$countRow = $result->fetch(\PDO::FETCH_ASSOC);
return $countRow['count'];
}
/**
* @param $context
* @return \Closure
*/
public function getRowCountClosure($context)
{
return function () use ($context) {
return ($context instanceof Pdo\Statement)
? $this->getCountForStatement($context)
: $this->getCountForSql($context);
};
}
}
zend-db-release-2.8.1/src/Adapter/Driver/Pdo/Feature/SqliteRowCounter.php 0000664 0000000 0000000 00000004065 12703724304 0026213 0 ustar 00root root 0000000 0000000 getSql();
if ($sql == '' || stripos($sql, 'select') === false) {
return;
}
$countSql = 'SELECT COUNT(*) as "count" FROM (' . $sql . ')';
$countStmt->prepare($countSql);
$result = $countStmt->execute();
$countRow = $result->getResource()->fetch(\PDO::FETCH_ASSOC);
unset($statement, $result);
return $countRow['count'];
}
/**
* @param $sql
* @return null|int
*/
public function getCountForSql($sql)
{
if (stripos($sql, 'select') === false) {
return;
}
$countSql = 'SELECT COUNT(*) as count FROM (' . $sql . ')';
/** @var $pdo \PDO */
$pdo = $this->driver->getConnection()->getResource();
$result = $pdo->query($countSql);
$countRow = $result->fetch(\PDO::FETCH_ASSOC);
return $countRow['count'];
}
/**
* @param $context
* @return \Closure
*/
public function getRowCountClosure($context)
{
return function () use ($context) {
return ($context instanceof Pdo\Statement)
? $this->getCountForStatement($context)
: $this->getCountForSql($context);
};
}
}
zend-db-release-2.8.1/src/Adapter/Driver/Pdo/Pdo.php 0000664 0000000 0000000 00000020660 12703724304 0022050 0 ustar 00root root 0000000 0000000 registerConnection($connection);
$this->registerStatementPrototype(($statementPrototype) ?: new Statement());
$this->registerResultPrototype(($resultPrototype) ?: new Result());
if (is_array($features)) {
foreach ($features as $name => $feature) {
$this->addFeature($name, $feature);
}
} elseif ($features instanceof AbstractFeature) {
$this->addFeature($features->getName(), $features);
} elseif ($features === self::FEATURES_DEFAULT) {
$this->setupDefaultFeatures();
}
}
/**
* @param Profiler\ProfilerInterface $profiler
* @return Pdo
*/
public function setProfiler(Profiler\ProfilerInterface $profiler)
{
$this->profiler = $profiler;
if ($this->connection instanceof Profiler\ProfilerAwareInterface) {
$this->connection->setProfiler($profiler);
}
if ($this->statementPrototype instanceof Profiler\ProfilerAwareInterface) {
$this->statementPrototype->setProfiler($profiler);
}
return $this;
}
/**
* @return null|Profiler\ProfilerInterface
*/
public function getProfiler()
{
return $this->profiler;
}
/**
* Register connection
*
* @param Connection $connection
* @return Pdo
*/
public function registerConnection(Connection $connection)
{
$this->connection = $connection;
$this->connection->setDriver($this);
return $this;
}
/**
* Register statement prototype
*
* @param Statement $statementPrototype
*/
public function registerStatementPrototype(Statement $statementPrototype)
{
$this->statementPrototype = $statementPrototype;
$this->statementPrototype->setDriver($this);
}
/**
* Register result prototype
*
* @param Result $resultPrototype
*/
public function registerResultPrototype(Result $resultPrototype)
{
$this->resultPrototype = $resultPrototype;
}
/**
* Add feature
*
* @param string $name
* @param AbstractFeature $feature
* @return Pdo
*/
public function addFeature($name, $feature)
{
if ($feature instanceof AbstractFeature) {
$name = $feature->getName(); // overwrite the name, just in case
$feature->setDriver($this);
}
$this->features[$name] = $feature;
return $this;
}
/**
* Setup the default features for Pdo
*
* @return Pdo
*/
public function setupDefaultFeatures()
{
$driverName = $this->connection->getDriverName();
if ($driverName == 'sqlite') {
$this->addFeature(null, new Feature\SqliteRowCounter);
} elseif ($driverName == 'oci') {
$this->addFeature(null, new Feature\OracleRowCounter);
}
return $this;
}
/**
* Get feature
*
* @param $name
* @return AbstractFeature|false
*/
public function getFeature($name)
{
if (isset($this->features[$name])) {
return $this->features[$name];
}
return false;
}
/**
* Get database platform name
*
* @param string $nameFormat
* @return string
*/
public function getDatabasePlatformName($nameFormat = self::NAME_FORMAT_CAMELCASE)
{
$name = $this->getConnection()->getDriverName();
if ($nameFormat == self::NAME_FORMAT_CAMELCASE) {
switch ($name) {
case 'pgsql':
return 'Postgresql';
case 'oci':
return 'Oracle';
case 'dblib':
case 'sqlsrv':
return 'SqlServer';
default:
return ucfirst($name);
}
} else {
switch ($name) {
case 'sqlite':
return 'SQLite';
case 'mysql':
return 'MySQL';
case 'pgsql':
return 'PostgreSQL';
case 'oci':
return 'Oracle';
case 'dblib':
case 'sqlsrv':
return 'SQLServer';
default:
return ucfirst($name);
}
}
}
/**
* Check environment
*/
public function checkEnvironment()
{
if (!extension_loaded('PDO')) {
throw new Exception\RuntimeException('The PDO extension is required for this adapter but the extension is not loaded');
}
}
/**
* @return Connection
*/
public function getConnection()
{
return $this->connection;
}
/**
* @param string|PDOStatement $sqlOrResource
* @return Statement
*/
public function createStatement($sqlOrResource = null)
{
$statement = clone $this->statementPrototype;
if ($sqlOrResource instanceof PDOStatement) {
$statement->setResource($sqlOrResource);
} else {
if (is_string($sqlOrResource)) {
$statement->setSql($sqlOrResource);
}
if (!$this->connection->isConnected()) {
$this->connection->connect();
}
$statement->initialize($this->connection->getResource());
}
return $statement;
}
/**
* @param resource $resource
* @param mixed $context
* @return Result
*/
public function createResult($resource, $context = null)
{
$result = clone $this->resultPrototype;
$rowCount = null;
// special feature, sqlite PDO counter
if ($this->connection->getDriverName() == 'sqlite'
&& ($sqliteRowCounter = $this->getFeature('SqliteRowCounter'))
&& $resource->columnCount() > 0) {
$rowCount = $sqliteRowCounter->getRowCountClosure($context);
}
// special feature, oracle PDO counter
if ($this->connection->getDriverName() == 'oci'
&& ($oracleRowCounter = $this->getFeature('OracleRowCounter'))
&& $resource->columnCount() > 0) {
$rowCount = $oracleRowCounter->getRowCountClosure($context);
}
$result->initialize($resource, $this->connection->getLastGeneratedValue(), $rowCount);
return $result;
}
/**
* @return string
*/
public function getPrepareType()
{
return self::PARAMETERIZATION_NAMED;
}
/**
* @param string $name
* @param string|null $type
* @return string
*/
public function formatParameterName($name, $type = null)
{
if ($type === null && !is_numeric($name) || $type == self::PARAMETERIZATION_NAMED) {
return ':' . $name;
}
return '?';
}
/**
* @return mixed
*/
public function getLastGeneratedValue($name = null)
{
return $this->connection->getLastGeneratedValue($name);
}
}
zend-db-release-2.8.1/src/Adapter/Driver/Pdo/Result.php 0000664 0000000 0000000 00000012051 12703724304 0022577 0 ustar 00root root 0000000 0000000 resource = $resource;
$this->generatedValue = $generatedValue;
$this->rowCount = $rowCount;
return $this;
}
/**
* @return null
*/
public function buffer()
{
return;
}
/**
* @return bool|null
*/
public function isBuffered()
{
return false;
}
/**
* @param int $fetchMode
* @throws Exception\InvalidArgumentException on invalid fetch mode
*/
public function setFetchMode($fetchMode)
{
if ($fetchMode < 1 || $fetchMode > 10) {
throw new Exception\InvalidArgumentException(
'The fetch mode must be one of the PDO::FETCH_* constants.'
);
}
$this->fetchMode = (int) $fetchMode;
}
/**
* @return int
*/
public function getFetchMode()
{
return $this->fetchMode;
}
/**
* Get resource
*
* @return mixed
*/
public function getResource()
{
return $this->resource;
}
/**
* Get the data
* @return array
*/
public function current()
{
if ($this->currentComplete) {
return $this->currentData;
}
$this->currentData = $this->resource->fetch($this->fetchMode);
$this->currentComplete = true;
return $this->currentData;
}
/**
* Next
*
* @return mixed
*/
public function next()
{
$this->currentData = $this->resource->fetch($this->fetchMode);
$this->currentComplete = true;
$this->position++;
return $this->currentData;
}
/**
* Key
*
* @return mixed
*/
public function key()
{
return $this->position;
}
/**
* @throws Exception\RuntimeException
* @return void
*/
public function rewind()
{
if ($this->statementMode == self::STATEMENT_MODE_FORWARD && $this->position > 0) {
throw new Exception\RuntimeException(
'This result is a forward only result set, calling rewind() after moving forward is not supported'
);
}
$this->currentData = $this->resource->fetch($this->fetchMode);
$this->currentComplete = true;
$this->position = 0;
}
/**
* Valid
*
* @return bool
*/
public function valid()
{
return ($this->currentData !== false);
}
/**
* Count
*
* @return int
*/
public function count()
{
if (is_int($this->rowCount)) {
return $this->rowCount;
}
if ($this->rowCount instanceof \Closure) {
$this->rowCount = (int) call_user_func($this->rowCount);
} else {
$this->rowCount = (int) $this->resource->rowCount();
}
return $this->rowCount;
}
/**
* @return int
*/
public function getFieldCount()
{
return $this->resource->columnCount();
}
/**
* Is query result
*
* @return bool
*/
public function isQueryResult()
{
return ($this->resource->columnCount() > 0);
}
/**
* Get affected rows
*
* @return int
*/
public function getAffectedRows()
{
return $this->resource->rowCount();
}
/**
* @return mixed|null
*/
public function getGeneratedValue()
{
return $this->generatedValue;
}
}
zend-db-release-2.8.1/src/Adapter/Driver/Pdo/Statement.php 0000664 0000000 0000000 00000016151 12703724304 0023272 0 ustar 00root root 0000000 0000000 driver = $driver;
return $this;
}
/**
* @param Profiler\ProfilerInterface $profiler
* @return Statement
*/
public function setProfiler(Profiler\ProfilerInterface $profiler)
{
$this->profiler = $profiler;
return $this;
}
/**
* @return null|Profiler\ProfilerInterface
*/
public function getProfiler()
{
return $this->profiler;
}
/**
* Initialize
*
* @param \PDO $connectionResource
* @return Statement
*/
public function initialize(\PDO $connectionResource)
{
$this->pdo = $connectionResource;
return $this;
}
/**
* Set resource
*
* @param \PDOStatement $pdoStatement
* @return Statement
*/
public function setResource(\PDOStatement $pdoStatement)
{
$this->resource = $pdoStatement;
return $this;
}
/**
* Get resource
*
* @return mixed
*/
public function getResource()
{
return $this->resource;
}
/**
* Set sql
*
* @param string $sql
* @return Statement
*/
public function setSql($sql)
{
$this->sql = $sql;
return $this;
}
/**
* Get sql
*
* @return string
*/
public function getSql()
{
return $this->sql;
}
/**
* @param ParameterContainer $parameterContainer
* @return Statement
*/
public function setParameterContainer(ParameterContainer $parameterContainer)
{
$this->parameterContainer = $parameterContainer;
return $this;
}
/**
* @return ParameterContainer
*/
public function getParameterContainer()
{
return $this->parameterContainer;
}
/**
* @param string $sql
* @throws Exception\RuntimeException
*/
public function prepare($sql = null)
{
if ($this->isPrepared) {
throw new Exception\RuntimeException('This statement has been prepared already');
}
if ($sql === null) {
$sql = $this->sql;
}
$this->resource = $this->pdo->prepare($sql);
if ($this->resource === false) {
$error = $this->pdo->errorInfo();
throw new Exception\RuntimeException($error[2]);
}
$this->isPrepared = true;
}
/**
* @return bool
*/
public function isPrepared()
{
return $this->isPrepared;
}
/**
* @param null|array|ParameterContainer $parameters
* @throws Exception\InvalidQueryException
* @return Result
*/
public function execute($parameters = null)
{
if (!$this->isPrepared) {
$this->prepare();
}
/** START Standard ParameterContainer Merging Block */
if (!$this->parameterContainer instanceof ParameterContainer) {
if ($parameters instanceof ParameterContainer) {
$this->parameterContainer = $parameters;
$parameters = null;
} else {
$this->parameterContainer = new ParameterContainer();
}
}
if (is_array($parameters)) {
$this->parameterContainer->setFromArray($parameters);
}
if ($this->parameterContainer->count() > 0) {
$this->bindParametersFromContainer();
}
/** END Standard ParameterContainer Merging Block */
if ($this->profiler) {
$this->profiler->profilerStart($this);
}
try {
$this->resource->execute();
} catch (\PDOException $e) {
if ($this->profiler) {
$this->profiler->profilerFinish();
}
throw new Exception\InvalidQueryException(
'Statement could not be executed (' . implode(' - ', $this->resource->errorInfo()) . ')',
null,
$e
);
}
if ($this->profiler) {
$this->profiler->profilerFinish();
}
$result = $this->driver->createResult($this->resource, $this);
return $result;
}
/**
* Bind parameters from container
*/
protected function bindParametersFromContainer()
{
if ($this->parametersBound) {
return;
}
$parameters = $this->parameterContainer->getNamedArray();
foreach ($parameters as $name => &$value) {
if (is_bool($value)) {
$type = \PDO::PARAM_BOOL;
} elseif (is_int($value)) {
$type = \PDO::PARAM_INT;
} else {
$type = \PDO::PARAM_STR;
}
if ($this->parameterContainer->offsetHasErrata($name)) {
switch ($this->parameterContainer->offsetGetErrata($name)) {
case ParameterContainer::TYPE_INTEGER:
$type = \PDO::PARAM_INT;
break;
case ParameterContainer::TYPE_NULL:
$type = \PDO::PARAM_NULL;
break;
case ParameterContainer::TYPE_LOB:
$type = \PDO::PARAM_LOB;
break;
}
}
// parameter is named or positional, value is reference
$parameter = is_int($name) ? ($name + 1) : $name;
$this->resource->bindParam($parameter, $value, $type);
}
}
/**
* Perform a deep clone
* @return Statement A cloned statement
*/
public function __clone()
{
$this->isPrepared = false;
$this->parametersBound = false;
$this->resource = null;
if ($this->parameterContainer) {
$this->parameterContainer = clone $this->parameterContainer;
}
}
}
zend-db-release-2.8.1/src/Adapter/Driver/Pgsql/ 0000775 0000000 0000000 00000000000 12703724304 0021155 5 ustar 00root root 0000000 0000000 zend-db-release-2.8.1/src/Adapter/Driver/Pgsql/Connection.php 0000664 0000000 0000000 00000017031 12703724304 0023767 0 ustar 00root root 0000000 0000000 setConnectionParameters($connectionInfo);
} elseif (is_resource($connectionInfo)) {
$this->setResource($connectionInfo);
}
}
/**
* Set resource
*
* @param resource $resource
* @return self
*/
public function setResource($resource)
{
$this->resource = $resource;
return $this;
}
/**
* Set driver
*
* @param Pgsql $driver
* @return self
*/
public function setDriver(Pgsql $driver)
{
$this->driver = $driver;
return $this;
}
/**
* @param int|null $type
* @return self
*/
public function setType($type)
{
$invalidConectionType = ($type !== PGSQL_CONNECT_FORCE_NEW);
// Compatibility with PHP < 5.6
if ($invalidConectionType && defined('PGSQL_CONNECT_ASYNC')) {
$invalidConectionType = ($type !== PGSQL_CONNECT_ASYNC);
}
if ($invalidConectionType) {
throw new Exception\InvalidArgumentException('Connection type is not valid. (See: http://php.net/manual/en/function.pg-connect.php)');
}
$this->type = $type;
return $this;
}
/**
* {@inheritDoc}
*
* @return null|string
*/
public function getCurrentSchema()
{
if (!$this->isConnected()) {
$this->connect();
}
$result = pg_query($this->resource, 'SELECT CURRENT_SCHEMA AS "currentschema"');
if ($result == false) {
return;
}
return pg_fetch_result($result, 0, 'currentschema');
}
/**
* {@inheritDoc}
*
* @throws Exception\RuntimeException on failure
*/
public function connect()
{
if (is_resource($this->resource)) {
return $this;
}
$connection = $this->getConnectionString();
set_error_handler(function ($number, $string) {
throw new Exception\RuntimeException(
__METHOD__ . ': Unable to connect to database',
null,
new Exception\ErrorException($string, $number)
);
});
$this->resource = pg_connect($connection);
restore_error_handler();
if ($this->resource === false) {
throw new Exception\RuntimeException(sprintf(
'%s: Unable to connect to database',
__METHOD__
));
}
$p = $this->connectionParameters;
if (!empty($p['charset'])) {
if (-1 === pg_set_client_encoding($this->resource, $p['charset'])) {
throw new Exception\RuntimeException(sprintf(
"%s: Unable to set client encoding '%s'",
__METHOD__,
$p['charset']
));
}
}
return $this;
}
/**
* {@inheritDoc}
*/
public function isConnected()
{
return (is_resource($this->resource));
}
/**
* {@inheritDoc}
*/
public function disconnect()
{
pg_close($this->resource);
return $this;
}
/**
* {@inheritDoc}
*/
public function beginTransaction()
{
if ($this->inTransaction()) {
throw new Exception\RuntimeException('Nested transactions are not supported');
}
if (!$this->isConnected()) {
$this->connect();
}
pg_query($this->resource, 'BEGIN');
$this->inTransaction = true;
return $this;
}
/**
* {@inheritDoc}
*/
public function commit()
{
if (!$this->isConnected()) {
$this->connect();
}
if (!$this->inTransaction()) {
return; // We ignore attempts to commit non-existing transaction
}
pg_query($this->resource, 'COMMIT');
$this->inTransaction = false;
return $this;
}
/**
* {@inheritDoc}
*/
public function rollback()
{
if (!$this->isConnected()) {
throw new Exception\RuntimeException('Must be connected before you can rollback');
}
if (!$this->inTransaction()) {
throw new Exception\RuntimeException('Must call beginTransaction() before you can rollback');
}
pg_query($this->resource, 'ROLLBACK');
$this->inTransaction = false;
return $this;
}
/**
* {@inheritDoc}
*
* @throws Exception\InvalidQueryException
* @return resource|\Zend\Db\ResultSet\ResultSetInterface
*/
public function execute($sql)
{
if (!$this->isConnected()) {
$this->connect();
}
if ($this->profiler) {
$this->profiler->profilerStart($sql);
}
$resultResource = pg_query($this->resource, $sql);
if ($this->profiler) {
$this->profiler->profilerFinish($sql);
}
// if the returnValue is something other than a pg result resource, bypass wrapping it
if ($resultResource === false) {
throw new Exception\InvalidQueryException(pg_errormessage());
}
$resultPrototype = $this->driver->createResult(($resultResource === true) ? $this->resource : $resultResource);
return $resultPrototype;
}
/**
* {@inheritDoc}
*
* @return string
*/
public function getLastGeneratedValue($name = null)
{
if ($name === null) {
return;
}
$result = pg_query($this->resource, 'SELECT CURRVAL(\'' . str_replace('\'', '\\\'', $name) . '\') as "currval"');
return pg_fetch_result($result, 0, 'currval');
}
/**
* Get Connection String
*
* @return string
*/
private function getConnectionString()
{
// localize
$p = $this->connectionParameters;
// given a list of key names, test for existence in $p
$findParameterValue = function (array $names) use ($p) {
foreach ($names as $name) {
if (isset($p[$name])) {
return $p[$name];
}
}
return;
};
$connectionParameters = [
'host' => $findParameterValue(['hostname', 'host']),
'user' => $findParameterValue(['username', 'user']),
'password' => $findParameterValue(['password', 'passwd', 'pw']),
'dbname' => $findParameterValue(['database', 'dbname', 'db', 'schema']),
'port' => isset($p['port']) ? (int) $p['port'] : null,
'socket' => isset($p['socket']) ? $p['socket'] : null,
];
return urldecode(http_build_query(array_filter($connectionParameters), null, ' '));
}
}
zend-db-release-2.8.1/src/Adapter/Driver/Pgsql/Pgsql.php 0000664 0000000 0000000 00000012521 12703724304 0022755 0 ustar 00root root 0000000 0000000 false
];
/**
* Constructor
*
* @param array|Connection|resource $connection
* @param null|Statement $statementPrototype
* @param null|Result $resultPrototype
* @param array $options
*/
public function __construct($connection, Statement $statementPrototype = null, Result $resultPrototype = null, $options = null)
{
if (!$connection instanceof Connection) {
$connection = new Connection($connection);
}
$this->registerConnection($connection);
$this->registerStatementPrototype(($statementPrototype) ?: new Statement());
$this->registerResultPrototype(($resultPrototype) ?: new Result());
}
public function setProfiler(Profiler\ProfilerInterface $profiler)
{
$this->profiler = $profiler;
if ($this->connection instanceof Profiler\ProfilerAwareInterface) {
$this->connection->setProfiler($profiler);
}
if ($this->statementPrototype instanceof Profiler\ProfilerAwareInterface) {
$this->statementPrototype->setProfiler($profiler);
}
return $this;
}
/**
* @return null|Profiler\ProfilerInterface
*/
public function getProfiler()
{
return $this->profiler;
}
/**
* Register connection
*
* @param Connection $connection
* @return Pgsql
*/
public function registerConnection(Connection $connection)
{
$this->connection = $connection;
$this->connection->setDriver($this);
return $this;
}
/**
* Register statement prototype
*
* @param Statement $statement
* @return Pgsql
*/
public function registerStatementPrototype(Statement $statement)
{
$this->statementPrototype = $statement;
$this->statementPrototype->setDriver($this); // needs access to driver to createResult()
return $this;
}
/**
* Register result prototype
*
* @param Result $result
* @return Pgsql
*/
public function registerResultPrototype(Result $result)
{
$this->resultPrototype = $result;
return $this;
}
/**
* Get database platform name
*
* @param string $nameFormat
* @return string
*/
public function getDatabasePlatformName($nameFormat = self::NAME_FORMAT_CAMELCASE)
{
if ($nameFormat == self::NAME_FORMAT_CAMELCASE) {
return 'Postgresql';
}
return 'PostgreSQL';
}
/**
* Check environment
*
* @throws Exception\RuntimeException
* @return bool
*/
public function checkEnvironment()
{
if (!extension_loaded('pgsql')) {
throw new Exception\RuntimeException('The PostgreSQL (pgsql) extension is required for this adapter but the extension is not loaded');
}
}
/**
* Get connection
*
* @return Connection
*/
public function getConnection()
{
return $this->connection;
}
/**
* Create statement
*
* @param string|null $sqlOrResource
* @return Statement
*/
public function createStatement($sqlOrResource = null)
{
$statement = clone $this->statementPrototype;
if (is_string($sqlOrResource)) {
$statement->setSql($sqlOrResource);
}
if (!$this->connection->isConnected()) {
$this->connection->connect();
}
$statement->initialize($this->connection->getResource());
return $statement;
}
/**
* Create result
*
* @param resource $resource
* @return Result
*/
public function createResult($resource)
{
$result = clone $this->resultPrototype;
$result->initialize($resource, $this->connection->getLastGeneratedValue());
return $result;
}
/**
* Get prepare Type
*
* @return string
*/
public function getPrepareType()
{
return self::PARAMETERIZATION_POSITIONAL;
}
/**
* Format parameter name
*
* @param string $name
* @param mixed $type
* @return string
*/
public function formatParameterName($name, $type = null)
{
return '$#';
}
/**
* Get last generated value
*
* @param string $name
* @return mixed
*/
public function getLastGeneratedValue($name = null)
{
return $this->connection->getLastGeneratedValue($name);
}
}
zend-db-release-2.8.1/src/Adapter/Driver/Pgsql/Result.php 0000664 0000000 0000000 00000006626 12703724304 0023156 0 ustar 00root root 0000000 0000000 resource = $resource;
$this->count = pg_num_rows($this->resource);
$this->generatedValue = $generatedValue;
}
/**
* Current
*
* @return array|bool|mixed
*/
public function current()
{
if ($this->count === 0) {
return false;
}
return pg_fetch_assoc($this->resource, $this->position);
}
/**
* Next
*
* @return void
*/
public function next()
{
$this->position++;
}
/**
* Key
*
* @return int|mixed
*/
public function key()
{
return $this->position;
}
/**
* Valid
*
* @return bool
*/
public function valid()
{
return ($this->position < $this->count);
}
/**
* Rewind
*
* @return void
*/
public function rewind()
{
$this->position = 0;
}
/**
* Buffer
*
* @return null
*/
public function buffer()
{
return;
}
/**
* Is buffered
*
* @return false
*/
public function isBuffered()
{
return false;
}
/**
* Is query result
*
* @return bool
*/
public function isQueryResult()
{
return (pg_num_fields($this->resource) > 0);
}
/**
* Get affected rows
*
* @return int
*/
public function getAffectedRows()
{
return pg_affected_rows($this->resource);
}
/**
* Get generated value
*
* @return mixed|null
*/
public function getGeneratedValue()
{
return $this->generatedValue;
}
/**
* Get resource
*/
public function getResource()
{
// TODO: Implement getResource() method.
}
/**
* Count
*
* (PHP 5 >= 5.1.0)
* Count elements of an object
* @link http://php.net/manual/en/countable.count.php
* @return int The custom count as an integer.
*
* The return value is cast to an integer.
*/
public function count()
{
return $this->count;
}
/**
* Get field count
*
* @return int
*/
public function getFieldCount()
{
return pg_num_fields($this->resource);
}
}
zend-db-release-2.8.1/src/Adapter/Driver/Pgsql/Statement.php 0000664 0000000 0000000 00000012511 12703724304 0023632 0 ustar 00root root 0000000 0000000 driver = $driver;
return $this;
}
/**
* @param Profiler\ProfilerInterface $profiler
* @return Statement
*/
public function setProfiler(Profiler\ProfilerInterface $profiler)
{
$this->profiler = $profiler;
return $this;
}
/**
* @return null|Profiler\ProfilerInterface
*/
public function getProfiler()
{
return $this->profiler;
}
/**
* Initialize
*
* @param resource $pgsql
* @return void
* @throws Exception\RuntimeException for invalid or missing postgresql connection
*/
public function initialize($pgsql)
{
if (!is_resource($pgsql) || get_resource_type($pgsql) !== 'pgsql link') {
throw new Exception\RuntimeException(sprintf(
'%s: Invalid or missing postgresql connection; received "%s"',
__METHOD__,
get_resource_type($pgsql)
));
}
$this->pgsql = $pgsql;
}
/**
* Get resource
*
* @return resource
*/
public function getResource()
{
// TODO: Implement getResource() method.
}
/**
* Set sql
*
* @param string $sql
* @return Statement
*/
public function setSql($sql)
{
$this->sql = $sql;
return $this;
}
/**
* Get sql
*
* @return string
*/
public function getSql()
{
return $this->sql;
}
/**
* Set parameter container
*
* @param ParameterContainer $parameterContainer
* @return Statement
*/
public function setParameterContainer(ParameterContainer $parameterContainer)
{
$this->parameterContainer = $parameterContainer;
return $this;
}
/**
* Get parameter container
*
* @return ParameterContainer
*/
public function getParameterContainer()
{
return $this->parameterContainer;
}
/**
* Prepare
*
* @param string $sql
*/
public function prepare($sql = null)
{
$sql = ($sql) ?: $this->sql;
$pCount = 1;
$sql = preg_replace_callback(
'#\$\##', function () use (&$pCount) {
return '$' . $pCount++;
},
$sql
);
$this->sql = $sql;
$this->statementName = 'statement' . ++static::$statementIndex;
$this->resource = pg_prepare($this->pgsql, $this->statementName, $sql);
}
/**
* Is prepared
*
* @return bool
*/
public function isPrepared()
{
return isset($this->resource);
}
/**
* Execute
*
* @param null|array|ParameterContainer $parameters
* @throws Exception\InvalidQueryException
* @return Result
*/
public function execute($parameters = null)
{
if (!$this->isPrepared()) {
$this->prepare();
}
/** START Standard ParameterContainer Merging Block */
if (!$this->parameterContainer instanceof ParameterContainer) {
if ($parameters instanceof ParameterContainer) {
$this->parameterContainer = $parameters;
$parameters = null;
} else {
$this->parameterContainer = new ParameterContainer();
}
}
if (is_array($parameters)) {
$this->parameterContainer->setFromArray($parameters);
}
if ($this->parameterContainer->count() > 0) {
$parameters = $this->parameterContainer->getPositionalArray();
}
/** END Standard ParameterContainer Merging Block */
if ($this->profiler) {
$this->profiler->profilerStart($this);
}
$resultResource = pg_execute($this->pgsql, $this->statementName, (array) $parameters);
if ($this->profiler) {
$this->profiler->profilerFinish();
}
if ($resultResource === false) {
throw new Exception\InvalidQueryException(pg_last_error());
}
$result = $this->driver->createResult($resultResource);
return $result;
}
}
zend-db-release-2.8.1/src/Adapter/Driver/ResultInterface.php 0000664 0000000 0000000 00000002241 12703724304 0023676 0 ustar 00root root 0000000 0000000 setConnectionParameters($connectionInfo);
} elseif (is_resource($connectionInfo)) {
$this->setResource($connectionInfo);
} else {
throw new Exception\InvalidArgumentException('$connection must be an array of parameters or a resource');
}
}
/**
* Set driver
*
* @param Sqlsrv $driver
* @return self
*/
public function setDriver(Sqlsrv $driver)
{
$this->driver = $driver;
return $this;
}
/**
* {@inheritDoc}
*/
public function getCurrentSchema()
{
if (!$this->isConnected()) {
$this->connect();
}
$result = sqlsrv_query($this->resource, 'SELECT SCHEMA_NAME()');
$r = sqlsrv_fetch_array($result);
return $r[0];
}
/**
* Set resource
*
* @param resource $resource
* @throws Exception\InvalidArgumentException
* @return self
*/
public function setResource($resource)
{
if (get_resource_type($resource) !== 'SQL Server Connection') {
throw new Exception\InvalidArgumentException('Resource provided was not of type SQL Server Connection');
}
$this->resource = $resource;
return $this;
}
/**
* {@inheritDoc}
*
* @throws Exception\RuntimeException
*/
public function connect()
{
if ($this->resource) {
return $this;
}
$serverName = '.';
$params = [
'ReturnDatesAsStrings' => true
];
foreach ($this->connectionParameters as $key => $value) {
switch (strtolower($key)) {
case 'hostname':
case 'servername':
$serverName = (string) $value;
break;
case 'username':
case 'uid':
$params['UID'] = (string) $value;
break;
case 'password':
case 'pwd':
$params['PWD'] = (string) $value;
break;
case 'database':
case 'dbname':
$params['Database'] = (string) $value;
break;
case 'charset':
$params['CharacterSet'] = (string) $value;
break;
case 'driver_options':
case 'options':
$params = array_merge($params, (array) $value);
break;
}
}
$this->resource = sqlsrv_connect($serverName, $params);
if (!$this->resource) {
throw new Exception\RuntimeException(
'Connect Error',
null,
new ErrorException(sqlsrv_errors())
);
}
return $this;
}
/**
* {@inheritDoc}
*/
public function isConnected()
{
return (is_resource($this->resource));
}
/**
* {@inheritDoc}
*/
public function disconnect()
{
sqlsrv_close($this->resource);
$this->resource = null;
}
/**
* {@inheritDoc}
*/
public function beginTransaction()
{
if (!$this->isConnected()) {
$this->connect();
}
if (sqlsrv_begin_transaction($this->resource) === false) {
throw new Exception\RuntimeException(
new ErrorException(sqlsrv_errors())
);
}
$this->inTransaction = true;
return $this;
}
/**
* {@inheritDoc}
*/
public function commit()
{
// http://msdn.microsoft.com/en-us/library/cc296194.aspx
if (!$this->isConnected()) {
$this->connect();
}
sqlsrv_commit($this->resource);
$this->inTransaction = false;
return $this;
}
/**
* {@inheritDoc}
*/
public function rollback()
{
// http://msdn.microsoft.com/en-us/library/cc296176.aspx
if (!$this->isConnected()) {
throw new Exception\RuntimeException('Must be connected before you can rollback.');
}
sqlsrv_rollback($this->resource);
$this->inTransaction = false;
return $this;
}
/**
* {@inheritDoc}
*
* @throws Exception\RuntimeException
*/
public function execute($sql)
{
if (!$this->isConnected()) {
$this->connect();
}
if (!$this->driver instanceof Sqlsrv) {
throw new Exception\RuntimeException('Connection is missing an instance of Sqlsrv');
}
if ($this->profiler) {
$this->profiler->profilerStart($sql);
}
$returnValue = sqlsrv_query($this->resource, $sql);
if ($this->profiler) {
$this->profiler->profilerFinish($sql);
}
// if the returnValue is something other than a Sqlsrv_result, bypass wrapping it
if ($returnValue === false) {
$errors = sqlsrv_errors();
// ignore general warnings
if ($errors[0]['SQLSTATE'] != '01000') {
throw new Exception\RuntimeException(
'An exception occurred while trying to execute the provided $sql',
null,
new ErrorException($errors)
);
}
}
$result = $this->driver->createResult($returnValue);
return $result;
}
/**
* Prepare
*
* @param string $sql
* @return string
*/
public function prepare($sql)
{
if (!$this->isConnected()) {
$this->connect();
}
$statement = $this->driver->createStatement($sql);
return $statement;
}
/**
* {@inheritDoc}
*
* @return mixed
*/
public function getLastGeneratedValue($name = null)
{
if (!$this->resource) {
$this->connect();
}
$sql = 'SELECT @@IDENTITY as Current_Identity';
$result = sqlsrv_query($this->resource, $sql);
$row = sqlsrv_fetch_array($result);
return $row['Current_Identity'];
}
}
zend-db-release-2.8.1/src/Adapter/Driver/Sqlsrv/Exception/ 0000775 0000000 0000000 00000000000 12703724304 0023317 5 ustar 00root root 0000000 0000000 zend-db-release-2.8.1/src/Adapter/Driver/Sqlsrv/Exception/ErrorException.php 0000664 0000000 0000000 00000001400 12703724304 0026773 0 ustar 00root root 0000000 0000000 errors = ($errors === false) ? sqlsrv_errors() : $errors;
}
}
zend-db-release-2.8.1/src/Adapter/Driver/Sqlsrv/Exception/ExceptionInterface.php 0000664 0000000 0000000 00000000720 12703724304 0027606 0 ustar 00root root 0000000 0000000 resource = $resource;
$this->generatedValue = $generatedValue;
return $this;
}
/**
* @return null
*/
public function buffer()
{
return;
}
/**
* @return bool
*/
public function isBuffered()
{
return false;
}
/**
* Get resource
*
* @return resource
*/
public function getResource()
{
return $this->resource;
}
/**
* Current
*
* @return mixed
*/
public function current()
{
if ($this->currentComplete) {
return $this->currentData;
}
$this->load();
return $this->currentData;
}
/**
* Next
*
* @return bool
*/
public function next()
{
$this->load();
return true;
}
/**
* Load
*
* @param int $row
* @return mixed
*/
protected function load($row = SQLSRV_SCROLL_NEXT)
{
$this->currentData = sqlsrv_fetch_array($this->resource, SQLSRV_FETCH_ASSOC, $row);
$this->currentComplete = true;
$this->position++;
return $this->currentData;
}
/**
* Key
*
* @return mixed
*/
public function key()
{
return $this->position;
}
/**
* Rewind
*
* @return bool
*/
public function rewind()
{
$this->position = 0;
$this->load(SQLSRV_SCROLL_FIRST);
return true;
}
/**
* Valid
*
* @return bool
*/
public function valid()
{
if ($this->currentComplete && $this->currentData) {
return true;
}
return $this->load();
}
/**
* Count
*
* @return int
*/
public function count()
{
return sqlsrv_num_rows($this->resource);
}
/**
* @return bool|int
*/
public function getFieldCount()
{
return sqlsrv_num_fields($this->resource);
}
/**
* Is query result
*
* @return bool
*/
public function isQueryResult()
{
if (is_bool($this->resource)) {
return false;
}
return (sqlsrv_num_fields($this->resource) > 0);
}
/**
* Get affected rows
*
* @return int
*/
public function getAffectedRows()
{
return sqlsrv_rows_affected($this->resource);
}
/**
* @return mixed|null
*/
public function getGeneratedValue()
{
return $this->generatedValue;
}
}
zend-db-release-2.8.1/src/Adapter/Driver/Sqlsrv/Sqlsrv.php 0000664 0000000 0000000 00000012540 12703724304 0023366 0 ustar 00root root 0000000 0000000 registerConnection($connection);
$this->registerStatementPrototype(($statementPrototype) ?: new Statement());
$this->registerResultPrototype(($resultPrototype) ?: new Result());
}
/**
* @param Profiler\ProfilerInterface $profiler
* @return Sqlsrv
*/
public function setProfiler(Profiler\ProfilerInterface $profiler)
{
$this->profiler = $profiler;
if ($this->connection instanceof Profiler\ProfilerAwareInterface) {
$this->connection->setProfiler($profiler);
}
if ($this->statementPrototype instanceof Profiler\ProfilerAwareInterface) {
$this->statementPrototype->setProfiler($profiler);
}
return $this;
}
/**
* @return null|Profiler\ProfilerInterface
*/
public function getProfiler()
{
return $this->profiler;
}
/**
* Register connection
*
* @param Connection $connection
* @return Sqlsrv
*/
public function registerConnection(Connection $connection)
{
$this->connection = $connection;
$this->connection->setDriver($this);
return $this;
}
/**
* Register statement prototype
*
* @param Statement $statementPrototype
* @return Sqlsrv
*/
public function registerStatementPrototype(Statement $statementPrototype)
{
$this->statementPrototype = $statementPrototype;
$this->statementPrototype->setDriver($this);
return $this;
}
/**
* Register result prototype
*
* @param Result $resultPrototype
* @return Sqlsrv
*/
public function registerResultPrototype(Result $resultPrototype)
{
$this->resultPrototype = $resultPrototype;
return $this;
}
/**
* Get database paltform name
*
* @param string $nameFormat
* @return string
*/
public function getDatabasePlatformName($nameFormat = self::NAME_FORMAT_CAMELCASE)
{
if ($nameFormat == self::NAME_FORMAT_CAMELCASE) {
return 'SqlServer';
}
return 'SQLServer';
}
/**
* Check environment
*
* @throws Exception\RuntimeException
* @return void
*/
public function checkEnvironment()
{
if (!extension_loaded('sqlsrv')) {
throw new Exception\RuntimeException('The Sqlsrv extension is required for this adapter but the extension is not loaded');
}
}
/**
* @return Connection
*/
public function getConnection()
{
return $this->connection;
}
/**
* @param string|resource $sqlOrResource
* @return Statement
*/
public function createStatement($sqlOrResource = null)
{
$statement = clone $this->statementPrototype;
if (is_resource($sqlOrResource)) {
$statement->initialize($sqlOrResource);
} else {
if (!$this->connection->isConnected()) {
$this->connection->connect();
}
$statement->initialize($this->connection->getResource());
if (is_string($sqlOrResource)) {
$statement->setSql($sqlOrResource);
} elseif ($sqlOrResource !== null) {
throw new Exception\InvalidArgumentException('createStatement() only accepts an SQL string or a Sqlsrv resource');
}
}
return $statement;
}
/**
* @param resource $resource
* @return Result
*/
public function createResult($resource)
{
$result = clone $this->resultPrototype;
$result->initialize($resource, $this->connection->getLastGeneratedValue());
return $result;
}
/**
* @return string
*/
public function getPrepareType()
{
return self::PARAMETERIZATION_POSITIONAL;
}
/**
* @param string $name
* @param mixed $type
* @return string
*/
public function formatParameterName($name, $type = null)
{
return '?';
}
/**
* @return mixed
*/
public function getLastGeneratedValue()
{
return $this->getConnection()->getLastGeneratedValue();
}
}
zend-db-release-2.8.1/src/Adapter/Driver/Sqlsrv/Statement.php 0000664 0000000 0000000 00000016224 12703724304 0024043 0 ustar 00root root 0000000 0000000 driver = $driver;
return $this;
}
/**
* @param Profiler\ProfilerInterface $profiler
* @return Statement
*/
public function setProfiler(Profiler\ProfilerInterface $profiler)
{
$this->profiler = $profiler;
return $this;
}
/**
* @return null|Profiler\ProfilerInterface
*/
public function getProfiler()
{
return $this->profiler;
}
/**
*
* One of two resource types will be provided here:
* a) "SQL Server Connection" when a prepared statement needs to still be produced
* b) "SQL Server Statement" when a prepared statement has been already produced
* (there will need to already be a bound param set if it applies to this query)
*
* @param resource $resource
* @throws Exception\InvalidArgumentException
* @return Statement
*/
public function initialize($resource)
{
$resourceType = get_resource_type($resource);
if ($resourceType == 'SQL Server Connection') {
$this->sqlsrv = $resource;
} elseif ($resourceType == 'SQL Server Statement') {
$this->resource = $resource;
$this->isPrepared = true;
} else {
throw new Exception\InvalidArgumentException('Invalid resource provided to ' . __CLASS__);
}
return $this;
}
/**
* Set parameter container
*
* @param ParameterContainer $parameterContainer
* @return Statement
*/
public function setParameterContainer(ParameterContainer $parameterContainer)
{
$this->parameterContainer = $parameterContainer;
return $this;
}
/**
* @return ParameterContainer
*/
public function getParameterContainer()
{
return $this->parameterContainer;
}
/**
* @param $resource
* @return Statement
*/
public function setResource($resource)
{
$this->resource = $resource;
return $this;
}
/**
* Get resource
*
* @return resource
*/
public function getResource()
{
return $this->resource;
}
/**
* @param string $sql
* @return Statement
*/
public function setSql($sql)
{
$this->sql = $sql;
return $this;
}
/**
* Get sql
*
* @return string
*/
public function getSql()
{
return $this->sql;
}
/**
* @param string $sql
* @param array $options
* @throws Exception\RuntimeException
* @return Statement
*/
public function prepare($sql = null, array $options = [])
{
if ($this->isPrepared) {
throw new Exception\RuntimeException('Already prepared');
}
$sql = ($sql) ?: $this->sql;
$options = ($options) ?: $this->prepareOptions;
$pRef = &$this->parameterReferences;
for ($position = 0, $count = substr_count($sql, '?'); $position < $count; $position++) {
if (!isset($this->prepareParams[$position])) {
$pRef[$position] = ['', SQLSRV_PARAM_IN, null, null];
} else {
$pRef[$position] = &$this->prepareParams[$position];
}
}
$this->resource = sqlsrv_prepare($this->sqlsrv, $sql, $pRef, $options);
$this->isPrepared = true;
return $this;
}
/**
* @return bool
*/
public function isPrepared()
{
return $this->isPrepared;
}
/**
* Execute
*
* @param null|array|ParameterContainer $parameters
* @throws Exception\RuntimeException
* @return Result
*/
public function execute($parameters = null)
{
/** END Standard ParameterContainer Merging Block */
if (!$this->isPrepared) {
$this->prepare();
}
/** START Standard ParameterContainer Merging Block */
if (!$this->parameterContainer instanceof ParameterContainer) {
if ($parameters instanceof ParameterContainer) {
$this->parameterContainer = $parameters;
$parameters = null;
} else {
$this->parameterContainer = new ParameterContainer();
}
}
if (is_array($parameters)) {
$this->parameterContainer->setFromArray($parameters);
}
if ($this->parameterContainer->count() > 0) {
$this->bindParametersFromContainer();
}
if ($this->profiler) {
$this->profiler->profilerStart($this);
}
$resultValue = sqlsrv_execute($this->resource);
if ($this->profiler) {
$this->profiler->profilerFinish();
}
if ($resultValue === false) {
$errors = sqlsrv_errors();
// ignore general warnings
if ($errors[0]['SQLSTATE'] != '01000') {
throw new Exception\RuntimeException($errors[0]['message']);
}
}
$result = $this->driver->createResult($this->resource);
return $result;
}
/**
* Bind parameters from container
*
*/
protected function bindParametersFromContainer()
{
$values = $this->parameterContainer->getPositionalArray();
$position = 0;
foreach ($values as $value) {
$this->parameterReferences[$position++][0] = $value;
}
}
/**
* @param array $prepareParams
*/
public function setPrepareParams(array $prepareParams)
{
$this->prepareParams = $prepareParams;
}
/**
* @param array $prepareOptions
*/
public function setPrepareOptions(array $prepareOptions)
{
$this->prepareOptions = $prepareOptions;
}
}
zend-db-release-2.8.1/src/Adapter/Driver/StatementInterface.php 0000664 0000000 0000000 00000001746 12703724304 0024375 0 ustar 00root root 0000000 0000000 parameters = $parameters;
}
}
zend-db-release-2.8.1/src/Adapter/Exception/InvalidQueryException.php 0000664 0000000 0000000 00000000673 12703724304 0025604 0 ustar 00root root 0000000 0000000 setFromArray($data);
}
}
/**
* Offset exists
*
* @param string $name
* @return bool
*/
public function offsetExists($name)
{
return (isset($this->data[$name]));
}
/**
* Offset get
*
* @param string $name
* @return mixed
*/
public function offsetGet($name)
{
return (isset($this->data[$name])) ? $this->data[$name] : null;
}
/**
* @param $name
* @param $from
*/
public function offsetSetReference($name, $from)
{
$this->data[$name] =& $this->data[$from];
}
/**
* Offset set
*
* @param string|int $name
* @param mixed $value
* @param mixed $errata
* @param mixed $maxLength
* @throws Exception\InvalidArgumentException
*/
public function offsetSet($name, $value, $errata = null, $maxLength = null)
{
$position = false;
// if integer, get name for this position
if (is_int($name)) {
if (isset($this->positions[$name])) {
$position = $name;
$name = $this->positions[$name];
} else {
$name = (string) $name;
}
} elseif (is_string($name)) {
// is a string:
$position = array_key_exists($name, $this->data);
} elseif ($name === null) {
$name = (string) count($this->data);
} else {
throw new Exception\InvalidArgumentException('Keys must be string, integer or null');
}
if ($position === false) {
$this->positions[] = $name;
}
$this->data[$name] = $value;
if ($errata) {
$this->offsetSetErrata($name, $errata);
}
if ($maxLength) {
$this->offsetSetMaxLength($name, $maxLength);
}
}
/**
* Offset unset
*
* @param string $name
* @return ParameterContainer
*/
public function offsetUnset($name)
{
if (is_int($name) && isset($this->positions[$name])) {
$name = $this->positions[$name];
}
unset($this->data[$name]);
return $this;
}
/**
* Set from array
*
* @param array $data
* @return ParameterContainer
*/
public function setFromArray(array $data)
{
foreach ($data as $n => $v) {
$this->offsetSet($n, $v);
}
return $this;
}
/**
* Offset set max length
*
* @param string|int $name
* @param mixed $maxLength
*/
public function offsetSetMaxLength($name, $maxLength)
{
if (is_int($name)) {
$name = $this->positions[$name];
}
$this->maxLength[$name] = $maxLength;
}
/**
* Offset get max length
*
* @param string|int $name
* @throws Exception\InvalidArgumentException
* @return mixed
*/
public function offsetGetMaxLength($name)
{
if (is_int($name)) {
$name = $this->positions[$name];
}
if (!array_key_exists($name, $this->data)) {
throw new Exception\InvalidArgumentException('Data does not exist for this name/position');
}
return $this->maxLength[$name];
}
/**
* Offset has max length
*
* @param string|int $name
* @return bool
*/
public function offsetHasMaxLength($name)
{
if (is_int($name)) {
$name = $this->positions[$name];
}
return (isset($this->maxLength[$name]));
}
/**
* Offset unset max length
*
* @param string|int $name
* @throws Exception\InvalidArgumentException
*/
public function offsetUnsetMaxLength($name)
{
if (is_int($name)) {
$name = $this->positions[$name];
}
if (!array_key_exists($name, $this->maxLength)) {
throw new Exception\InvalidArgumentException('Data does not exist for this name/position');
}
$this->maxLength[$name] = null;
}
/**
* Get max length iterator
*
* @return \ArrayIterator
*/
public function getMaxLengthIterator()
{
return new \ArrayIterator($this->maxLength);
}
/**
* Offset set errata
*
* @param string|int $name
* @param mixed $errata
*/
public function offsetSetErrata($name, $errata)
{
if (is_int($name)) {
$name = $this->positions[$name];
}
$this->errata[$name] = $errata;
}
/**
* Offset get errata
*
* @param string|int $name
* @throws Exception\InvalidArgumentException
* @return mixed
*/
public function offsetGetErrata($name)
{
if (is_int($name)) {
$name = $this->positions[$name];
}
if (!array_key_exists($name, $this->data)) {
throw new Exception\InvalidArgumentException('Data does not exist for this name/position');
}
return $this->errata[$name];
}
/**
* Offset has errata
*
* @param string|int $name
* @return bool
*/
public function offsetHasErrata($name)
{
if (is_int($name)) {
$name = $this->positions[$name];
}
return (isset($this->errata[$name]));
}
/**
* Offset unset errata
*
* @param string|int $name
* @throws Exception\InvalidArgumentException
*/
public function offsetUnsetErrata($name)
{
if (is_int($name)) {
$name = $this->positions[$name];
}
if (!array_key_exists($name, $this->errata)) {
throw new Exception\InvalidArgumentException('Data does not exist for this name/position');
}
$this->errata[$name] = null;
}
/**
* Get errata iterator
*
* @return \ArrayIterator
*/
public function getErrataIterator()
{
return new \ArrayIterator($this->errata);
}
/**
* getNamedArray
*
* @return array
*/
public function getNamedArray()
{
return $this->data;
}
/**
* getNamedArray
*
* @return array
*/
public function getPositionalArray()
{
return array_values($this->data);
}
/**
* count
*
* @return int
*/
public function count()
{
return count($this->data);
}
/**
* Current
*
* @return mixed
*/
public function current()
{
return current($this->data);
}
/**
* Next
*
* @return mixed
*/
public function next()
{
return next($this->data);
}
/**
* Key
*
* @return mixed
*/
public function key()
{
return key($this->data);
}
/**
* Valid
*
* @return bool
*/
public function valid()
{
return (current($this->data) !== false);
}
/**
* Rewind
*/
public function rewind()
{
reset($this->data);
}
/**
* @param array|ParameterContainer $parameters
* @throws Exception\InvalidArgumentException
* @return ParameterContainer
*/
public function merge($parameters)
{
if (!is_array($parameters) && !$parameters instanceof ParameterContainer) {
throw new Exception\InvalidArgumentException('$parameters must be an array or an instance of ParameterContainer');
}
if (count($parameters) == 0) {
return $this;
}
if ($parameters instanceof ParameterContainer) {
$parameters = $parameters->getNamedArray();
}
foreach ($parameters as $key => $value) {
if (is_int($key)) {
$key = null;
}
$this->offsetSet($key, $value);
}
return $this;
}
}
zend-db-release-2.8.1/src/Adapter/Platform/ 0000775 0000000 0000000 00000000000 12703724304 0020420 5 ustar 00root root 0000000 0000000 zend-db-release-2.8.1/src/Adapter/Platform/AbstractPlatform.php 0000664 0000000 0000000 00000006303 12703724304 0024403 0 ustar 00root root 0000000 0000000 quoteIdentifiers) {
return $identifier;
}
$safeWordsInt = ['*' => true, ' ' => true, '.' => true, 'as' => true];
foreach ($safeWords as $sWord) {
$safeWordsInt[strtolower($sWord)] = true;
}
$parts = preg_split(
'/([^0-9,a-z,A-Z$_:])/i',
$identifier,
-1,
PREG_SPLIT_DELIM_CAPTURE | PREG_SPLIT_NO_EMPTY
);
$identifier = '';
foreach ($parts as $part) {
$identifier .= isset($safeWordsInt[strtolower($part)])
? $part
: $this->quoteIdentifier[0]
. str_replace($this->quoteIdentifier[0], $this->quoteIdentifierTo, $part)
. $this->quoteIdentifier[1];
}
return $identifier;
}
/**
* {@inheritDoc}
*/
public function quoteIdentifier($identifier)
{
if (! $this->quoteIdentifiers) {
return $identifier;
}
return $this->quoteIdentifier[0]
. str_replace($this->quoteIdentifier[0], $this->quoteIdentifierTo, $identifier)
. $this->quoteIdentifier[1];
}
/**
* {@inheritDoc}
*/
public function quoteIdentifierChain($identifierChain)
{
return '"' . implode('"."', (array) str_replace('"', '\\"', $identifierChain)) . '"';
}
/**
* {@inheritDoc}
*/
public function getQuoteIdentifierSymbol()
{
return $this->quoteIdentifier[0];
}
/**
* {@inheritDoc}
*/
public function getQuoteValueSymbol()
{
return '\'';
}
/**
* {@inheritDoc}
*/
public function quoteValue($value)
{
trigger_error(
'Attempting to quote a value in ' . get_class($this) .
' without extension/driver support can introduce security vulnerabilities in a production environment'
);
return '\'' . addcslashes((string) $value, "\x00\n\r\\'\"\x1a") . '\'';
}
/**
* {@inheritDoc}
*/
public function quoteTrustedValue($value)
{
return '\'' . addcslashes((string) $value, "\x00\n\r\\'\"\x1a") . '\'';
}
/**
* {@inheritDoc}
*/
public function quoteValueList($valueList)
{
return implode(', ', array_map([$this, 'quoteValue'], (array) $valueList));
}
/**
* {@inheritDoc}
*/
public function getIdentifierSeparator()
{
return '.';
}
}
zend-db-release-2.8.1/src/Adapter/Platform/IbmDb2.php 0000664 0000000 0000000 00000006610 12703724304 0022173 0 ustar 00root root 0000000 0000000 quoteIdentifiers = false;
}
if (isset($options['identifier_separator'])) {
$this->identifierSeparator = $options['identifier_separator'];
}
}
/**
* {@inheritDoc}
*/
public function getName()
{
return 'IBM DB2';
}
/**
* {@inheritDoc}
*/
public function quoteIdentifierInFragment($identifier, array $safeWords = [])
{
if (! $this->quoteIdentifiers) {
return $identifier;
}
$safeWordsInt = ['*' => true, ' ' => true, '.' => true, 'as' => true];
foreach ($safeWords as $sWord) {
$safeWordsInt[strtolower($sWord)] = true;
}
$parts = preg_split(
'/([^0-9,a-z,A-Z$#_:])/i',
$identifier,
-1,
PREG_SPLIT_DELIM_CAPTURE | PREG_SPLIT_NO_EMPTY
);
$identifier = '';
foreach ($parts as $part) {
$identifier .= isset($safeWordsInt[strtolower($part)])
? $part
: $this->quoteIdentifier[0]
. str_replace($this->quoteIdentifier[0], $this->quoteIdentifierTo, $part)
. $this->quoteIdentifier[1];
}
return $identifier;
}
/**
* {@inheritDoc}
*/
public function quoteIdentifierChain($identifierChain)
{
if ($this->quoteIdentifiers === false) {
return (is_array($identifierChain)) ? implode($this->identifierSeparator, $identifierChain) : $identifierChain;
}
$identifierChain = str_replace('"', '\\"', $identifierChain);
if (is_array($identifierChain)) {
$identifierChain = implode('"' . $this->identifierSeparator . '"', $identifierChain);
}
return '"' . $identifierChain . '"';
}
/**
* {@inheritDoc}
*/
public function quoteValue($value)
{
if (function_exists('db2_escape_string')) {
return '\'' . db2_escape_string($value) . '\'';
}
trigger_error(
'Attempting to quote a value in ' . __CLASS__ . ' without extension/driver support '
. 'can introduce security vulnerabilities in a production environment.'
);
return '\'' . str_replace("'", "''", $value) . '\'';
}
/**
* {@inheritDoc}
*/
public function quoteTrustedValue($value)
{
if (function_exists('db2_escape_string')) {
return '\'' . db2_escape_string($value) . '\'';
}
return '\'' . str_replace("'", "''", $value) . '\'';
}
/**
* {@inheritDoc}
*/
public function getIdentifierSeparator()
{
return $this->identifierSeparator;
}
}
zend-db-release-2.8.1/src/Adapter/Platform/Mysql.php 0000664 0000000 0000000 00000006230 12703724304 0022237 0 ustar 00root root 0000000 0000000 setDriver($driver);
}
}
/**
* @param \Zend\Db\Adapter\Driver\Mysqli\Mysqli|\Zend\Db\Adapter\Driver\Pdo\Pdo|\mysqli|\PDO $driver
* @throws \Zend\Db\Adapter\Exception\InvalidArgumentException
*
* @return self
*/
public function setDriver($driver)
{
// handle Zend\Db drivers
if ($driver instanceof Mysqli\Mysqli
|| ($driver instanceof Pdo\Pdo && $driver->getDatabasePlatformName() == 'Mysql')
|| ($driver instanceof \mysqli)
|| ($driver instanceof \PDO && $driver->getAttribute(\PDO::ATTR_DRIVER_NAME) == 'mysql')
) {
$this->resource = $driver;
return $this;
}
throw new Exception\InvalidArgumentException('$driver must be a Mysqli or Mysql PDO Zend\Db\Adapter\Driver, Mysqli instance or MySQL PDO instance');
}
/**
* {@inheritDoc}
*/
public function getName()
{
return 'MySQL';
}
/**
* {@inheritDoc}
*/
public function quoteIdentifierChain($identifierChain)
{
return '`' . implode('`.`', (array) str_replace('`', '``', $identifierChain)) . '`';
}
/**
* {@inheritDoc}
*/
public function quoteValue($value)
{
if ($this->resource instanceof DriverInterface) {
$this->resource = $this->resource->getConnection()->getResource();
}
if ($this->resource instanceof \mysqli) {
return '\'' . $this->resource->real_escape_string($value) . '\'';
}
if ($this->resource instanceof \PDO) {
return $this->resource->quote($value);
}
return parent::quoteValue($value);
}
/**
* {@inheritDoc}
*/
public function quoteTrustedValue($value)
{
if ($this->resource instanceof DriverInterface) {
$this->resource = $this->resource->getConnection()->getResource();
}
if ($this->resource instanceof \mysqli) {
return '\'' . $this->resource->real_escape_string($value) . '\'';
}
if ($this->resource instanceof \PDO) {
return $this->resource->quote($value);
}
return parent::quoteTrustedValue($value);
}
}
zend-db-release-2.8.1/src/Adapter/Platform/Oracle.php 0000664 0000000 0000000 00000007034 12703724304 0022342 0 ustar 00root root 0000000 0000000 quoteIdentifiers = false;
}
if ($driver) {
$this->setDriver($driver);
}
}
/**
* @param Pdo|Oci8 $driver
* @throws InvalidArgumentException
* @return $this
*/
public function setDriver($driver)
{
if ($driver instanceof Oci8
|| ($driver instanceof Pdo && $driver->getDatabasePlatformName() == 'Oracle')
|| ($driver instanceof Pdo && $driver->getDatabasePlatformName() == 'Sqlite')
|| ($driver instanceof \oci8)
|| ($driver instanceof PDO && $driver->getAttribute(PDO::ATTR_DRIVER_NAME) == 'oci')
) {
$this->resource = $driver;
return $this;
}
throw new InvalidArgumentException(
'$driver must be a Oci8 or Oracle PDO Zend\Db\Adapter\Driver, '
. 'Oci8 instance, or Oci PDO instance'
);
}
/**
* @return null|Pdo|Oci8
*/
public function getDriver()
{
return $this->resource;
}
/**
* {@inheritDoc}
*/
public function getName()
{
return 'Oracle';
}
/**
* {@inheritDoc}
*/
public function quoteIdentifierChain($identifierChain)
{
if ($this->quoteIdentifiers === false) {
return implode('.', (array) $identifierChain);
}
return '"' . implode('"."', (array) str_replace('"', '\\"', $identifierChain)) . '"';
}
/**
* {@inheritDoc}
*/
public function quoteValue($value)
{
if ($this->resource instanceof DriverInterface) {
$this->resource = $this->resource->getConnection()->getResource();
}
if ($this->resource) {
if ($this->resource instanceof PDO) {
return $this->resource->quote($value);
}
if (get_resource_type($this->resource) == 'oci8 connection'
|| get_resource_type($this->resource) == 'oci8 persistent connection'
) {
return "'" . addcslashes(str_replace("'", "''", $value), "\x00\n\r\"\x1a") . "'";
}
}
trigger_error(
'Attempting to quote a value in ' . __CLASS__ . ' without extension/driver support '
. 'can introduce security vulnerabilities in a production environment.'
);
return "'" . addcslashes(str_replace("'", "''", $value), "\x00\n\r\"\x1a") . "'";
}
/**
* {@inheritDoc}
*/
public function quoteTrustedValue($value)
{
return "'" . addcslashes(str_replace('\'', '\'\'', $value), "\x00\n\r\"\x1a") . "'";
}
}
zend-db-release-2.8.1/src/Adapter/Platform/PlatformInterface.php 0000664 0000000 0000000 00000003734 12703724304 0024545 0 ustar 00root root 0000000 0000000 setDriver($driver);
}
}
/**
* @param \Zend\Db\Adapter\Driver\Pgsql\Pgsql|\Zend\Db\Adapter\Driver\Pdo\Pdo|resource|\PDO $driver
* @throws \Zend\Db\Adapter\Exception\InvalidArgumentException
* @return $this
*/
public function setDriver($driver)
{
if ($driver instanceof Pgsql\Pgsql
|| ($driver instanceof Pdo\Pdo && $driver->getDatabasePlatformName() == 'Postgresql')
|| (is_resource($driver) && (in_array(get_resource_type($driver), ['pgsql link', 'pgsql link persistent'])))
|| ($driver instanceof \PDO && $driver->getAttribute(\PDO::ATTR_DRIVER_NAME) == 'pgsql')
) {
$this->resource = $driver;
return $this;
}
throw new Exception\InvalidArgumentException('$driver must be a Pgsql or Postgresql PDO Zend\Db\Adapter\Driver, pgsql link resource or Postgresql PDO instance');
}
/**
* {@inheritDoc}
*/
public function getName()
{
return 'PostgreSQL';
}
/**
* {@inheritDoc}
*/
public function quoteIdentifierChain($identifierChain)
{
return '"' . implode('"."', (array) str_replace('"', '""', $identifierChain)) . '"';
}
/**
* {@inheritDoc}
*/
public function quoteValue($value)
{
if ($this->resource instanceof DriverInterface) {
$this->resource = $this->resource->getConnection()->getResource();
}
if (is_resource($this->resource)) {
return '\'' . pg_escape_string($this->resource, $value) . '\'';
}
if ($this->resource instanceof \PDO) {
return $this->resource->quote($value);
}
return 'E' . parent::quoteValue($value);
}
/**
* {@inheritDoc}
*/
public function quoteTrustedValue($value)
{
if ($this->resource instanceof DriverInterface) {
$this->resource = $this->resource->getConnection()->getResource();
}
if (is_resource($this->resource)) {
return '\'' . pg_escape_string($this->resource, $value) . '\'';
}
if ($this->resource instanceof \PDO) {
return $this->resource->quote($value);
}
return 'E' . parent::quoteTrustedValue($value);
}
}
zend-db-release-2.8.1/src/Adapter/Platform/Sql92.php 0000664 0000000 0000000 00000001522 12703724304 0022043 0 ustar 00root root 0000000 0000000 setDriver($driver);
}
}
/**
* @param \Zend\Db\Adapter\Driver\Sqlsrv\Sqlsrv|\Zend\Db\Adapter\Driver\Pdo\Pdo|resource|\PDO $driver
* @throws \Zend\Db\Adapter\Exception\InvalidArgumentException
*
* @return self
*/
public function setDriver($driver)
{
// handle Zend\Db drivers
if (($driver instanceof Pdo\Pdo && in_array($driver->getDatabasePlatformName(), ['SqlServer', 'Dblib']))
|| (($driver instanceof \PDO && in_array($driver->getAttribute(\PDO::ATTR_DRIVER_NAME), ['sqlsrv', 'dblib'])))
) {
$this->resource = $driver;
return $this;
}
throw new Exception\InvalidArgumentException('$driver must be a Sqlsrv PDO Zend\Db\Adapter\Driver or Sqlsrv PDO instance');
}
/**
* {@inheritDoc}
*/
public function getName()
{
return 'SQLServer';
}
/**
* {@inheritDoc}
*/
public function getQuoteIdentifierSymbol()
{
return $this->quoteIdentifier;
}
/**
* {@inheritDoc}
*/
public function quoteIdentifierChain($identifierChain)
{
return '[' . implode('].[', (array) $identifierChain) . ']';
}
/**
* {@inheritDoc}
*/
public function quoteValue($value)
{
if ($this->resource instanceof DriverInterface) {
$this->resource = $this->resource->getConnection()->getResource();
}
if ($this->resource instanceof \PDO) {
return $this->resource->quote($value);
}
trigger_error(
'Attempting to quote a value in ' . __CLASS__ . ' without extension/driver support '
. 'can introduce security vulnerabilities in a production environment.'
);
return '\'' . str_replace('\'', '\'\'', addcslashes($value, "\000\032")) . '\'';
}
/**
* {@inheritDoc}
*/
public function quoteTrustedValue($value)
{
if ($this->resource instanceof DriverInterface) {
$this->resource = $this->resource->getConnection()->getResource();
}
if ($this->resource instanceof \PDO) {
return $this->resource->quote($value);
}
return '\'' . str_replace('\'', '\'\'', $value) . '\'';
}
}
zend-db-release-2.8.1/src/Adapter/Platform/Sqlite.php 0000664 0000000 0000000 00000004662 12703724304 0022402 0 ustar 00root root 0000000 0000000 setDriver($driver);
}
}
/**
* @param \Zend\Db\Adapter\Driver\Pdo\Pdo|\PDO $driver
* @throws \Zend\Db\Adapter\Exception\InvalidArgumentException
*
* @return self
*/
public function setDriver($driver)
{
if (($driver instanceof \PDO && $driver->getAttribute(\PDO::ATTR_DRIVER_NAME) == 'sqlite')
|| ($driver instanceof Pdo\Pdo && $driver->getDatabasePlatformName() == 'Sqlite')
) {
$this->resource = $driver;
return $this;
}
throw new Exception\InvalidArgumentException('$driver must be a Sqlite PDO Zend\Db\Adapter\Driver, Sqlite PDO instance');
}
/**
* {@inheritDoc}
*/
public function getName()
{
return 'SQLite';
}
/**
* {@inheritDoc}
*/
public function quoteValue($value)
{
$resource = $this->resource;
if ($resource instanceof DriverInterface) {
$resource = $resource->getConnection()->getResource();
}
if ($resource instanceof \PDO) {
return $resource->quote($value);
}
return parent::quoteValue($value);
}
/**
* {@inheritDoc}
*/
public function quoteTrustedValue($value)
{
$resource = $this->resource;
if ($resource instanceof DriverInterface) {
$resource = $resource->getConnection()->getResource();
}
if ($resource instanceof \PDO) {
return $resource->quote($value);
}
return parent::quoteTrustedValue($value);
}
}
zend-db-release-2.8.1/src/Adapter/Profiler/ 0000775 0000000 0000000 00000000000 12703724304 0020416 5 ustar 00root root 0000000 0000000 zend-db-release-2.8.1/src/Adapter/Profiler/Profiler.php 0000664 0000000 0000000 00000004412 12703724304 0022712 0 ustar 00root root 0000000 0000000 '',
'parameters' => null,
'start' => microtime(true),
'end' => null,
'elapse' => null
];
if ($target instanceof StatementContainerInterface) {
$profileInformation['sql'] = $target->getSql();
$profileInformation['parameters'] = clone $target->getParameterContainer();
} elseif (is_string($target)) {
$profileInformation['sql'] = $target;
} else {
throw new Exception\InvalidArgumentException(__FUNCTION__ . ' takes either a StatementContainer or a string');
}
$this->profiles[$this->currentIndex] = $profileInformation;
return $this;
}
/**
* @return Profiler
*/
public function profilerFinish()
{
if (!isset($this->profiles[$this->currentIndex])) {
throw new Exception\RuntimeException('A profile must be started before ' . __FUNCTION__ . ' can be called.');
}
$current = &$this->profiles[$this->currentIndex];
$current['end'] = microtime(true);
$current['elapse'] = $current['end'] - $current['start'];
$this->currentIndex++;
return $this;
}
/**
* @return array|null
*/
public function getLastProfile()
{
return end($this->profiles);
}
/**
* @return array
*/
public function getProfiles()
{
return $this->profiles;
}
}
zend-db-release-2.8.1/src/Adapter/Profiler/ProfilerAwareInterface.php 0000664 0000000 0000000 00000000771 12703724304 0025517 0 ustar 00root root 0000000 0000000 setSql($sql);
}
$this->parameterContainer = ($parameterContainer) ?: new ParameterContainer;
}
/**
* @param $sql
* @return StatementContainer
*/
public function setSql($sql)
{
$this->sql = $sql;
return $this;
}
/**
* @return string
*/
public function getSql()
{
return $this->sql;
}
/**
* @param ParameterContainer $parameterContainer
* @return StatementContainer
*/
public function setParameterContainer(ParameterContainer $parameterContainer)
{
$this->parameterContainer = $parameterContainer;
return $this;
}
/**
* @return null|ParameterContainer
*/
public function getParameterContainer()
{
return $this->parameterContainer;
}
}
zend-db-release-2.8.1/src/Adapter/StatementContainerInterface.php 0000664 0000000 0000000 00000001623 12703724304 0024777 0 ustar 00root root 0000000 0000000 $this->getDependencyConfig(),
];
}
/**
* Retrieve zend-db default dependency configuration.
*
* @return array
*/
public function getDependencyConfig()
{
return [
'abstract_factories' => [
Adapter\AdapterAbstractServiceFactory::class,
],
'factories' => [
Adapter\AdapterInterface::class => Adapter\AdapterServiceFactory::class,
],
];
}
}
zend-db-release-2.8.1/src/Exception/ 0000775 0000000 0000000 00000000000 12703724304 0017212 5 ustar 00root root 0000000 0000000 zend-db-release-2.8.1/src/Exception/ErrorException.php 0000664 0000000 0000000 00000000636 12703724304 0022700 0 ustar 00root root 0000000 0000000 source = Source\Factory::createSourceFromAdapter($adapter);
}
/**
* {@inheritdoc}
*/
public function getTables($schema = null, $includeViews = false)
{
return $this->source->getTables($schema, $includeViews);
}
/**
* {@inheritdoc}
*/
public function getViews($schema = null)
{
return $this->source->getViews($schema);
}
/**
* {@inheritdoc}
*/
public function getTriggers($schema = null)
{
return $this->source->getTriggers($schema);
}
/**
* {@inheritdoc}
*/
public function getConstraints($table, $schema = null)
{
return $this->source->getConstraints($table, $schema);
}
/**
* {@inheritdoc}
*/
public function getColumns($table, $schema = null)
{
return $this->source->getColumns($table, $schema);
}
/**
* {@inheritdoc}
*/
public function getConstraintKeys($constraint, $table, $schema = null)
{
return $this->source->getConstraintKeys($constraint, $table, $schema);
}
/**
* {@inheritdoc}
*/
public function getConstraint($constraintName, $table, $schema = null)
{
return $this->source->getConstraint($constraintName, $table, $schema);
}
/**
* {@inheritdoc}
*/
public function getSchemas()
{
return $this->source->getSchemas();
}
/**
* {@inheritdoc}
*/
public function getTableNames($schema = null, $includeViews = false)
{
return $this->source->getTableNames($schema, $includeViews);
}
/**
* {@inheritdoc}
*/
public function getTable($tableName, $schema = null)
{
return $this->source->getTable($tableName, $schema);
}
/**
* {@inheritdoc}
*/
public function getViewNames($schema = null)
{
return $this->source->getViewNames($schema);
}
/**
* {@inheritdoc}
*/
public function getView($viewName, $schema = null)
{
return $this->source->getView($viewName, $schema);
}
/**
* {@inheritdoc}
*/
public function getTriggerNames($schema = null)
{
return $this->source->getTriggerNames($schema);
}
/**
* {@inheritdoc}
*/
public function getTrigger($triggerName, $schema = null)
{
return $this->source->getTrigger($triggerName, $schema);
}
/**
* {@inheritdoc}
*/
public function getColumnNames($table, $schema = null)
{
return $this->source->getColumnNames($table, $schema);
}
/**
* {@inheritdoc}
*/
public function getColumn($columnName, $table, $schema = null)
{
return $this->source->getColumn($columnName, $table, $schema);
}
}
zend-db-release-2.8.1/src/Metadata/MetadataInterface.php 0000664 0000000 0000000 00000006662 12703724304 0023060 0 ustar 00root root 0000000 0000000 setName($name);
}
}
/**
* Set columns
*
* @param array $columns
*/
public function setColumns(array $columns)
{
$this->columns = $columns;
}
/**
* Get columns
*
* @return array
*/
public function getColumns()
{
return $this->columns;
}
/**
* Set constraints
*
* @param array $constraints
*/
public function setConstraints($constraints)
{
$this->constraints = $constraints;
}
/**
* Get constraints
*
* @return array
*/
public function getConstraints()
{
return $this->constraints;
}
/**
* Set name
*
* @param string $name
*/
public function setName($name)
{
$this->name = $name;
}
/**
* Get name
*
* @return string
*/
public function getName()
{
return $this->name;
}
}
zend-db-release-2.8.1/src/Metadata/Object/ColumnObject.php 0000664 0000000 0000000 00000016221 12703724304 0023301 0 ustar 00root root 0000000 0000000 setName($name);
$this->setTableName($tableName);
$this->setSchemaName($schemaName);
}
/**
* Set name
*
* @param string $name
*/
public function setName($name)
{
$this->name = $name;
}
/**
* Get name
*
* @return string
*/
public function getName()
{
return $this->name;
}
/**
* Get table name
*
* @return string
*/
public function getTableName()
{
return $this->tableName;
}
/**
* Set table name
*
* @param string $tableName
* @return ColumnObject
*/
public function setTableName($tableName)
{
$this->tableName = $tableName;
return $this;
}
/**
* Set schema name
*
* @param string $schemaName
*/
public function setSchemaName($schemaName)
{
$this->schemaName = $schemaName;
}
/**
* Get schema name
*
* @return string
*/
public function getSchemaName()
{
return $this->schemaName;
}
/**
* @return int $ordinalPosition
*/
public function getOrdinalPosition()
{
return $this->ordinalPosition;
}
/**
* @param int $ordinalPosition to set
* @return ColumnObject
*/
public function setOrdinalPosition($ordinalPosition)
{
$this->ordinalPosition = $ordinalPosition;
return $this;
}
/**
* @return null|string the $columnDefault
*/
public function getColumnDefault()
{
return $this->columnDefault;
}
/**
* @param mixed $columnDefault to set
* @return ColumnObject
*/
public function setColumnDefault($columnDefault)
{
$this->columnDefault = $columnDefault;
return $this;
}
/**
* @return bool $isNullable
*/
public function getIsNullable()
{
return $this->isNullable;
}
/**
* @param bool $isNullable to set
* @return ColumnObject
*/
public function setIsNullable($isNullable)
{
$this->isNullable = $isNullable;
return $this;
}
/**
* @return bool $isNullable
*/
public function isNullable()
{
return $this->isNullable;
}
/**
* @return null|string the $dataType
*/
public function getDataType()
{
return $this->dataType;
}
/**
* @param string $dataType the $dataType to set
* @return ColumnObject
*/
public function setDataType($dataType)
{
$this->dataType = $dataType;
return $this;
}
/**
* @return int|null the $characterMaximumLength
*/
public function getCharacterMaximumLength()
{
return $this->characterMaximumLength;
}
/**
* @param int $characterMaximumLength the $characterMaximumLength to set
* @return ColumnObject
*/
public function setCharacterMaximumLength($characterMaximumLength)
{
$this->characterMaximumLength = $characterMaximumLength;
return $this;
}
/**
* @return int|null the $characterOctetLength
*/
public function getCharacterOctetLength()
{
return $this->characterOctetLength;
}
/**
* @param int $characterOctetLength the $characterOctetLength to set
* @return ColumnObject
*/
public function setCharacterOctetLength($characterOctetLength)
{
$this->characterOctetLength = $characterOctetLength;
return $this;
}
/**
* @return int the $numericPrecision
*/
public function getNumericPrecision()
{
return $this->numericPrecision;
}
/**
* @param int $numericPrecision the $numericPrevision to set
* @return ColumnObject
*/
public function setNumericPrecision($numericPrecision)
{
$this->numericPrecision = $numericPrecision;
return $this;
}
/**
* @return int the $numericScale
*/
public function getNumericScale()
{
return $this->numericScale;
}
/**
* @param int $numericScale the $numericScale to set
* @return ColumnObject
*/
public function setNumericScale($numericScale)
{
$this->numericScale = $numericScale;
return $this;
}
/**
* @return bool
*/
public function getNumericUnsigned()
{
return $this->numericUnsigned;
}
/**
* @param bool $numericUnsigned
* @return ColumnObject
*/
public function setNumericUnsigned($numericUnsigned)
{
$this->numericUnsigned = $numericUnsigned;
return $this;
}
/**
* @return bool
*/
public function isNumericUnsigned()
{
return $this->numericUnsigned;
}
/**
* @return array the $errata
*/
public function getErratas()
{
return $this->errata;
}
/**
* @param array $erratas
* @return ColumnObject
*/
public function setErratas(array $erratas)
{
foreach ($erratas as $name => $value) {
$this->setErrata($name, $value);
}
return $this;
}
/**
* @param string $errataName
* @return mixed
*/
public function getErrata($errataName)
{
if (array_key_exists($errataName, $this->errata)) {
return $this->errata[$errataName];
}
return;
}
/**
* @param string $errataName
* @param mixed $errataValue
* @return ColumnObject
*/
public function setErrata($errataName, $errataValue)
{
$this->errata[$errataName] = $errataValue;
return $this;
}
}
zend-db-release-2.8.1/src/Metadata/Object/ConstraintKeyObject.php 0000664 0000000 0000000 00000011673 12703724304 0024647 0 ustar 00root root 0000000 0000000 setColumnName($column);
}
/**
* Get column name
*
* @return string
*/
public function getColumnName()
{
return $this->columnName;
}
/**
* Set column name
*
* @param string $columnName
* @return ConstraintKeyObject
*/
public function setColumnName($columnName)
{
$this->columnName = $columnName;
return $this;
}
/**
* Get ordinal position
*
* @return int
*/
public function getOrdinalPosition()
{
return $this->ordinalPosition;
}
/**
* Set ordinal position
*
* @param int $ordinalPosition
* @return ConstraintKeyObject
*/
public function setOrdinalPosition($ordinalPosition)
{
$this->ordinalPosition = $ordinalPosition;
return $this;
}
/**
* Get position in unique constraint
*
* @return bool
*/
public function getPositionInUniqueConstraint()
{
return $this->positionInUniqueConstraint;
}
/**
* Set position in unique constraint
*
* @param bool $positionInUniqueConstraint
* @return ConstraintKeyObject
*/
public function setPositionInUniqueConstraint($positionInUniqueConstraint)
{
$this->positionInUniqueConstraint = $positionInUniqueConstraint;
return $this;
}
/**
* Get referencred table schema
*
* @return string
*/
public function getReferencedTableSchema()
{
return $this->referencedTableSchema;
}
/**
* Set referenced table schema
*
* @param string $referencedTableSchema
* @return ConstraintKeyObject
*/
public function setReferencedTableSchema($referencedTableSchema)
{
$this->referencedTableSchema = $referencedTableSchema;
return $this;
}
/**
* Get referenced table name
*
* @return string
*/
public function getReferencedTableName()
{
return $this->referencedTableName;
}
/**
* Set Referenced table name
*
* @param string $referencedTableName
* @return ConstraintKeyObject
*/
public function setReferencedTableName($referencedTableName)
{
$this->referencedTableName = $referencedTableName;
return $this;
}
/**
* Get referenced column name
*
* @return string
*/
public function getReferencedColumnName()
{
return $this->referencedColumnName;
}
/**
* Set referenced column name
*
* @param string $referencedColumnName
* @return ConstraintKeyObject
*/
public function setReferencedColumnName($referencedColumnName)
{
$this->referencedColumnName = $referencedColumnName;
return $this;
}
/**
* set foreign key update rule
*
* @param string $foreignKeyUpdateRule
*/
public function setForeignKeyUpdateRule($foreignKeyUpdateRule)
{
$this->foreignKeyUpdateRule = $foreignKeyUpdateRule;
}
/**
* Get foreign key update rule
*
* @return string
*/
public function getForeignKeyUpdateRule()
{
return $this->foreignKeyUpdateRule;
}
/**
* Set foreign key delete rule
*
* @param string $foreignKeyDeleteRule
*/
public function setForeignKeyDeleteRule($foreignKeyDeleteRule)
{
$this->foreignKeyDeleteRule = $foreignKeyDeleteRule;
}
/**
* get foreign key delete rule
*
* @return string
*/
public function getForeignKeyDeleteRule()
{
return $this->foreignKeyDeleteRule;
}
}
zend-db-release-2.8.1/src/Metadata/Object/ConstraintObject.php 0000664 0000000 0000000 00000015570 12703724304 0024176 0 ustar 00root root 0000000 0000000 setName($name);
$this->setTableName($tableName);
$this->setSchemaName($schemaName);
}
/**
* Set name
*
* @param string $name
*/
public function setName($name)
{
$this->name = $name;
}
/**
* Get name
*
* @return string
*/
public function getName()
{
return $this->name;
}
/**
* Set schema name
*
* @param string $schemaName
*/
public function setSchemaName($schemaName)
{
$this->schemaName = $schemaName;
}
/**
* Get schema name
*
* @return string
*/
public function getSchemaName()
{
return $this->schemaName;
}
/**
* Get table name
*
* @return string
*/
public function getTableName()
{
return $this->tableName;
}
/**
* Set table name
*
* @param string $tableName
* @return ConstraintObject
*/
public function setTableName($tableName)
{
$this->tableName = $tableName;
return $this;
}
/**
* Set type
*
* @param string $type
*/
public function setType($type)
{
$this->type = $type;
}
/**
* Get type
*
* @return string
*/
public function getType()
{
return $this->type;
}
public function hasColumns()
{
return (!empty($this->columns));
}
/**
* Get Columns.
*
* @return string[]
*/
public function getColumns()
{
return $this->columns;
}
/**
* Set Columns.
*
* @param string[] $columns
* @return ConstraintObject
*/
public function setColumns(array $columns)
{
$this->columns = $columns;
return $this;
}
/**
* Get Referenced Table Schema.
*
* @return string
*/
public function getReferencedTableSchema()
{
return $this->referencedTableSchema;
}
/**
* Set Referenced Table Schema.
*
* @param string $referencedTableSchema
* @return ConstraintObject
*/
public function setReferencedTableSchema($referencedTableSchema)
{
$this->referencedTableSchema = $referencedTableSchema;
return $this;
}
/**
* Get Referenced Table Name.
*
* @return string
*/
public function getReferencedTableName()
{
return $this->referencedTableName;
}
/**
* Set Referenced Table Name.
*
* @param string $referencedTableName
* @return ConstraintObject
*/
public function setReferencedTableName($referencedTableName)
{
$this->referencedTableName = $referencedTableName;
return $this;
}
/**
* Get Referenced Columns.
*
* @return string[]
*/
public function getReferencedColumns()
{
return $this->referencedColumns;
}
/**
* Set Referenced Columns.
*
* @param string[] $referencedColumns
* @return ConstraintObject
*/
public function setReferencedColumns(array $referencedColumns)
{
$this->referencedColumns = $referencedColumns;
return $this;
}
/**
* Get Match Option.
*
* @return string
*/
public function getMatchOption()
{
return $this->matchOption;
}
/**
* Set Match Option.
*
* @param string $matchOption
* @return ConstraintObject
*/
public function setMatchOption($matchOption)
{
$this->matchOption = $matchOption;
return $this;
}
/**
* Get Update Rule.
*
* @return string
*/
public function getUpdateRule()
{
return $this->updateRule;
}
/**
* Set Update Rule.
*
* @param string $updateRule
* @return ConstraintObject
*/
public function setUpdateRule($updateRule)
{
$this->updateRule = $updateRule;
return $this;
}
/**
* Get Delete Rule.
*
* @return string
*/
public function getDeleteRule()
{
return $this->deleteRule;
}
/**
* Set Delete Rule.
*
* @param string $deleteRule
* @return ConstraintObject
*/
public function setDeleteRule($deleteRule)
{
$this->deleteRule = $deleteRule;
return $this;
}
/**
* Get Check Clause.
*
* @return string
*/
public function getCheckClause()
{
return $this->checkClause;
}
/**
* Set Check Clause.
*
* @param string $checkClause
* @return ConstraintObject
*/
public function setCheckClause($checkClause)
{
$this->checkClause = $checkClause;
return $this;
}
/**
* Is primary key
*
* @return bool
*/
public function isPrimaryKey()
{
return ('PRIMARY KEY' == $this->type);
}
/**
* Is unique key
*
* @return bool
*/
public function isUnique()
{
return ('UNIQUE' == $this->type);
}
/**
* Is foreign key
*
* @return bool
*/
public function isForeignKey()
{
return ('FOREIGN KEY' == $this->type);
}
/**
* Is foreign key
*
* @return bool
*/
public function isCheck()
{
return ('CHECK' == $this->type);
}
}
zend-db-release-2.8.1/src/Metadata/Object/TableObject.php 0000664 0000000 0000000 00000000614 12703724304 0023072 0 ustar 00root root 0000000 0000000 name;
}
/**
* Set Name.
*
* @param string $name
* @return TriggerObject
*/
public function setName($name)
{
$this->name = $name;
return $this;
}
/**
* Get Event Manipulation.
*
* @return string
*/
public function getEventManipulation()
{
return $this->eventManipulation;
}
/**
* Set Event Manipulation.
*
* @param string $eventManipulation
* @return TriggerObject
*/
public function setEventManipulation($eventManipulation)
{
$this->eventManipulation = $eventManipulation;
return $this;
}
/**
* Get Event Object Catalog.
*
* @return string
*/
public function getEventObjectCatalog()
{
return $this->eventObjectCatalog;
}
/**
* Set Event Object Catalog.
*
* @param string $eventObjectCatalog
* @return TriggerObject
*/
public function setEventObjectCatalog($eventObjectCatalog)
{
$this->eventObjectCatalog = $eventObjectCatalog;
return $this;
}
/**
* Get Event Object Schema.
*
* @return string
*/
public function getEventObjectSchema()
{
return $this->eventObjectSchema;
}
/**
* Set Event Object Schema.
*
* @param string $eventObjectSchema
* @return TriggerObject
*/
public function setEventObjectSchema($eventObjectSchema)
{
$this->eventObjectSchema = $eventObjectSchema;
return $this;
}
/**
* Get Event Object Table.
*
* @return string
*/
public function getEventObjectTable()
{
return $this->eventObjectTable;
}
/**
* Set Event Object Table.
*
* @param string $eventObjectTable
* @return TriggerObject
*/
public function setEventObjectTable($eventObjectTable)
{
$this->eventObjectTable = $eventObjectTable;
return $this;
}
/**
* Get Action Order.
*
* @return string
*/
public function getActionOrder()
{
return $this->actionOrder;
}
/**
* Set Action Order.
*
* @param string $actionOrder
* @return TriggerObject
*/
public function setActionOrder($actionOrder)
{
$this->actionOrder = $actionOrder;
return $this;
}
/**
* Get Action Condition.
*
* @return string
*/
public function getActionCondition()
{
return $this->actionCondition;
}
/**
* Set Action Condition.
*
* @param string $actionCondition
* @return TriggerObject
*/
public function setActionCondition($actionCondition)
{
$this->actionCondition = $actionCondition;
return $this;
}
/**
* Get Action Statement.
*
* @return string
*/
public function getActionStatement()
{
return $this->actionStatement;
}
/**
* Set Action Statement.
*
* @param string $actionStatement
* @return TriggerObject
*/
public function setActionStatement($actionStatement)
{
$this->actionStatement = $actionStatement;
return $this;
}
/**
* Get Action Orientation.
*
* @return string
*/
public function getActionOrientation()
{
return $this->actionOrientation;
}
/**
* Set Action Orientation.
*
* @param string $actionOrientation
* @return TriggerObject
*/
public function setActionOrientation($actionOrientation)
{
$this->actionOrientation = $actionOrientation;
return $this;
}
/**
* Get Action Timing.
*
* @return string
*/
public function getActionTiming()
{
return $this->actionTiming;
}
/**
* Set Action Timing.
*
* @param string $actionTiming
* @return TriggerObject
*/
public function setActionTiming($actionTiming)
{
$this->actionTiming = $actionTiming;
return $this;
}
/**
* Get Action Reference Old Table.
*
* @return string
*/
public function getActionReferenceOldTable()
{
return $this->actionReferenceOldTable;
}
/**
* Set Action Reference Old Table.
*
* @param string $actionReferenceOldTable
* @return TriggerObject
*/
public function setActionReferenceOldTable($actionReferenceOldTable)
{
$this->actionReferenceOldTable = $actionReferenceOldTable;
return $this;
}
/**
* Get Action Reference New Table.
*
* @return string
*/
public function getActionReferenceNewTable()
{
return $this->actionReferenceNewTable;
}
/**
* Set Action Reference New Table.
*
* @param string $actionReferenceNewTable
* @return TriggerObject
*/
public function setActionReferenceNewTable($actionReferenceNewTable)
{
$this->actionReferenceNewTable = $actionReferenceNewTable;
return $this;
}
/**
* Get Action Reference Old Row.
*
* @return string
*/
public function getActionReferenceOldRow()
{
return $this->actionReferenceOldRow;
}
/**
* Set Action Reference Old Row.
*
* @param string $actionReferenceOldRow
* @return TriggerObject
*/
public function setActionReferenceOldRow($actionReferenceOldRow)
{
$this->actionReferenceOldRow = $actionReferenceOldRow;
return $this;
}
/**
* Get Action Reference New Row.
*
* @return string
*/
public function getActionReferenceNewRow()
{
return $this->actionReferenceNewRow;
}
/**
* Set Action Reference New Row.
*
* @param string $actionReferenceNewRow
* @return TriggerObject
*/
public function setActionReferenceNewRow($actionReferenceNewRow)
{
$this->actionReferenceNewRow = $actionReferenceNewRow;
return $this;
}
/**
* Get Created.
*
* @return \DateTime
*/
public function getCreated()
{
return $this->created;
}
/**
* Set Created.
*
* @param \DateTime $created
* @return TriggerObject
*/
public function setCreated($created)
{
$this->created = $created;
return $this;
}
}
zend-db-release-2.8.1/src/Metadata/Object/ViewObject.php 0000664 0000000 0000000 00000003126 12703724304 0022756 0 ustar 00root root 0000000 0000000 viewDefinition;
}
/**
* @param string $viewDefinition to set
* @return ViewObject
*/
public function setViewDefinition($viewDefinition)
{
$this->viewDefinition = $viewDefinition;
return $this;
}
/**
* @return string $checkOption
*/
public function getCheckOption()
{
return $this->checkOption;
}
/**
* @param string $checkOption to set
* @return ViewObject
*/
public function setCheckOption($checkOption)
{
$this->checkOption = $checkOption;
return $this;
}
/**
* @return bool $isUpdatable
*/
public function getIsUpdatable()
{
return $this->isUpdatable;
}
/**
* @param bool $isUpdatable to set
* @return ViewObject
*/
public function setIsUpdatable($isUpdatable)
{
$this->isUpdatable = $isUpdatable;
return $this;
}
public function isUpdatable()
{
return $this->isUpdatable;
}
}
zend-db-release-2.8.1/src/Metadata/Source/ 0000775 0000000 0000000 00000000000 12703724304 0020234 5 ustar 00root root 0000000 0000000 zend-db-release-2.8.1/src/Metadata/Source/AbstractSource.php 0000664 0000000 0000000 00000036332 12703724304 0023700 0 ustar 00root root 0000000 0000000 adapter = $adapter;
$this->defaultSchema = ($adapter->getCurrentSchema()) ?: self::DEFAULT_SCHEMA;
}
/**
* Get schemas
*
*/
public function getSchemas()
{
$this->loadSchemaData();
return $this->data['schemas'];
}
/**
* {@inheritdoc}
*/
public function getTableNames($schema = null, $includeViews = false)
{
if ($schema === null) {
$schema = $this->defaultSchema;
}
$this->loadTableNameData($schema);
if ($includeViews) {
return array_keys($this->data['table_names'][$schema]);
}
$tableNames = [];
foreach ($this->data['table_names'][$schema] as $tableName => $data) {
if ('BASE TABLE' == $data['table_type']) {
$tableNames[] = $tableName;
}
}
return $tableNames;
}
/**
* {@inheritdoc}
*/
public function getTables($schema = null, $includeViews = false)
{
if ($schema === null) {
$schema = $this->defaultSchema;
}
$tables = [];
foreach ($this->getTableNames($schema, $includeViews) as $tableName) {
$tables[] = $this->getTable($tableName, $schema);
}
return $tables;
}
/**
* {@inheritdoc}
*/
public function getTable($tableName, $schema = null)
{
if ($schema === null) {
$schema = $this->defaultSchema;
}
$this->loadTableNameData($schema);
if (!isset($this->data['table_names'][$schema][$tableName])) {
throw new \Exception('Table "' . $tableName . '" does not exist');
}
$data = $this->data['table_names'][$schema][$tableName];
switch ($data['table_type']) {
case 'BASE TABLE':
$table = new Object\TableObject($tableName);
break;
case 'VIEW':
$table = new Object\ViewObject($tableName);
$table->setViewDefinition($data['view_definition']);
$table->setCheckOption($data['check_option']);
$table->setIsUpdatable($data['is_updatable']);
break;
default:
throw new \Exception('Table "' . $tableName . '" is of an unsupported type "' . $data['table_type'] . '"');
}
$table->setColumns($this->getColumns($tableName, $schema));
$table->setConstraints($this->getConstraints($tableName, $schema));
return $table;
}
/**
* {@inheritdoc}
*/
public function getViewNames($schema = null)
{
if ($schema === null) {
$schema = $this->defaultSchema;
}
$this->loadTableNameData($schema);
$viewNames = [];
foreach ($this->data['table_names'][$schema] as $tableName => $data) {
if ('VIEW' == $data['table_type']) {
$viewNames[] = $tableName;
}
}
return $viewNames;
}
/**
* {@inheritdoc}
*/
public function getViews($schema = null)
{
if ($schema === null) {
$schema = $this->defaultSchema;
}
$views = [];
foreach ($this->getViewNames($schema) as $tableName) {
$views[] = $this->getTable($tableName, $schema);
}
return $views;
}
/**
* {@inheritdoc}
*/
public function getView($viewName, $schema = null)
{
if ($schema === null) {
$schema = $this->defaultSchema;
}
$this->loadTableNameData($schema);
$tableNames = $this->data['table_names'][$schema];
if (isset($tableNames[$viewName]) && 'VIEW' == $tableNames[$viewName]['table_type']) {
return $this->getTable($viewName, $schema);
}
throw new \Exception('View "' . $viewName . '" does not exist');
}
/**
* {@inheritdoc}
*/
public function getColumnNames($table, $schema = null)
{
if ($schema === null) {
$schema = $this->defaultSchema;
}
$this->loadColumnData($table, $schema);
if (!isset($this->data['columns'][$schema][$table])) {
throw new \Exception('"' . $table . '" does not exist');
}
return array_keys($this->data['columns'][$schema][$table]);
}
/**
* {@inheritdoc}
*/
public function getColumns($table, $schema = null)
{
if ($schema === null) {
$schema = $this->defaultSchema;
}
$this->loadColumnData($table, $schema);
$columns = [];
foreach ($this->getColumnNames($table, $schema) as $columnName) {
$columns[] = $this->getColumn($columnName, $table, $schema);
}
return $columns;
}
/**
* {@inheritdoc}
*/
public function getColumn($columnName, $table, $schema = null)
{
if ($schema === null) {
$schema = $this->defaultSchema;
}
$this->loadColumnData($table, $schema);
if (!isset($this->data['columns'][$schema][$table][$columnName])) {
throw new \Exception('A column by that name was not found.');
}
$info = $this->data['columns'][$schema][$table][$columnName];
$column = new Object\ColumnObject($columnName, $table, $schema);
$props = [
'ordinal_position', 'column_default', 'is_nullable',
'data_type', 'character_maximum_length', 'character_octet_length',
'numeric_precision', 'numeric_scale', 'numeric_unsigned',
'erratas'
];
foreach ($props as $prop) {
if (isset($info[$prop])) {
$column->{'set' . str_replace('_', '', $prop)}($info[$prop]);
}
}
$column->setOrdinalPosition($info['ordinal_position']);
$column->setColumnDefault($info['column_default']);
$column->setIsNullable($info['is_nullable']);
$column->setDataType($info['data_type']);
$column->setCharacterMaximumLength($info['character_maximum_length']);
$column->setCharacterOctetLength($info['character_octet_length']);
$column->setNumericPrecision($info['numeric_precision']);
$column->setNumericScale($info['numeric_scale']);
$column->setNumericUnsigned($info['numeric_unsigned']);
$column->setErratas($info['erratas']);
return $column;
}
/**
* {@inheritdoc}
*/
public function getConstraints($table, $schema = null)
{
if ($schema === null) {
$schema = $this->defaultSchema;
}
$this->loadConstraintData($table, $schema);
$constraints = [];
foreach (array_keys($this->data['constraints'][$schema][$table]) as $constraintName) {
$constraints[] = $this->getConstraint($constraintName, $table, $schema);
}
return $constraints;
}
/**
* {@inheritdoc}
*/
public function getConstraint($constraintName, $table, $schema = null)
{
if ($schema === null) {
$schema = $this->defaultSchema;
}
$this->loadConstraintData($table, $schema);
if (!isset($this->data['constraints'][$schema][$table][$constraintName])) {
throw new \Exception('Cannot find a constraint by that name in this table');
}
$info = $this->data['constraints'][$schema][$table][$constraintName];
$constraint = new Object\ConstraintObject($constraintName, $table, $schema);
foreach ([
'constraint_type' => 'setType',
'match_option' => 'setMatchOption',
'update_rule' => 'setUpdateRule',
'delete_rule' => 'setDeleteRule',
'columns' => 'setColumns',
'referenced_table_schema' => 'setReferencedTableSchema',
'referenced_table_name' => 'setReferencedTableName',
'referenced_columns' => 'setReferencedColumns',
'check_clause' => 'setCheckClause',
] as $key => $setMethod) {
if (isset($info[$key])) {
$constraint->{$setMethod}($info[$key]);
}
}
return $constraint;
}
/**
* {@inheritdoc}
*/
public function getConstraintKeys($constraint, $table, $schema = null)
{
if ($schema === null) {
$schema = $this->defaultSchema;
}
$this->loadConstraintReferences($table, $schema);
// organize references first
$references = [];
foreach ($this->data['constraint_references'][$schema] as $refKeyInfo) {
if ($refKeyInfo['constraint_name'] == $constraint) {
$references[$refKeyInfo['constraint_name']] = $refKeyInfo;
}
}
$this->loadConstraintDataKeys($schema);
$keys = [];
foreach ($this->data['constraint_keys'][$schema] as $constraintKeyInfo) {
if ($constraintKeyInfo['table_name'] == $table && $constraintKeyInfo['constraint_name'] === $constraint) {
$keys[] = $key = new Object\ConstraintKeyObject($constraintKeyInfo['column_name']);
$key->setOrdinalPosition($constraintKeyInfo['ordinal_position']);
if (isset($references[$constraint])) {
//$key->setReferencedTableSchema($constraintKeyInfo['referenced_table_schema']);
$key->setForeignKeyUpdateRule($references[$constraint]['update_rule']);
$key->setForeignKeyDeleteRule($references[$constraint]['delete_rule']);
//$key->setReferencedTableSchema($references[$constraint]['referenced_table_schema']);
$key->setReferencedTableName($references[$constraint]['referenced_table_name']);
$key->setReferencedColumnName($references[$constraint]['referenced_column_name']);
}
}
}
return $keys;
}
/**
* {@inheritdoc}
*/
public function getTriggerNames($schema = null)
{
if ($schema === null) {
$schema = $this->defaultSchema;
}
$this->loadTriggerData($schema);
return array_keys($this->data['triggers'][$schema]);
}
/**
* {@inheritdoc}
*/
public function getTriggers($schema = null)
{
if ($schema === null) {
$schema = $this->defaultSchema;
}
$triggers = [];
foreach ($this->getTriggerNames($schema) as $triggerName) {
$triggers[] = $this->getTrigger($triggerName, $schema);
}
return $triggers;
}
/**
* {@inheritdoc}
*/
public function getTrigger($triggerName, $schema = null)
{
if ($schema === null) {
$schema = $this->defaultSchema;
}
$this->loadTriggerData($schema);
if (!isset($this->data['triggers'][$schema][$triggerName])) {
throw new \Exception('Trigger "' . $triggerName . '" does not exist');
}
$info = $this->data['triggers'][$schema][$triggerName];
$trigger = new Object\TriggerObject();
$trigger->setName($triggerName);
$trigger->setEventManipulation($info['event_manipulation']);
$trigger->setEventObjectCatalog($info['event_object_catalog']);
$trigger->setEventObjectSchema($info['event_object_schema']);
$trigger->setEventObjectTable($info['event_object_table']);
$trigger->setActionOrder($info['action_order']);
$trigger->setActionCondition($info['action_condition']);
$trigger->setActionStatement($info['action_statement']);
$trigger->setActionOrientation($info['action_orientation']);
$trigger->setActionTiming($info['action_timing']);
$trigger->setActionReferenceOldTable($info['action_reference_old_table']);
$trigger->setActionReferenceNewTable($info['action_reference_new_table']);
$trigger->setActionReferenceOldRow($info['action_reference_old_row']);
$trigger->setActionReferenceNewRow($info['action_reference_new_row']);
$trigger->setCreated($info['created']);
return $trigger;
}
/**
* Prepare data hierarchy
*
* @param string $type
* @param string $key ...
*/
protected function prepareDataHierarchy($type)
{
$data = &$this->data;
foreach (func_get_args() as $key) {
if (!isset($data[$key])) {
$data[$key] = [];
}
$data = &$data[$key];
}
}
/**
* Load schema data
*/
protected function loadSchemaData()
{
}
/**
* Load table name data
*
* @param string $schema
*/
protected function loadTableNameData($schema)
{
if (isset($this->data['table_names'][$schema])) {
return;
}
$this->prepareDataHierarchy('table_names', $schema);
}
/**
* Load column data
*
* @param string $table
* @param string $schema
*/
protected function loadColumnData($table, $schema)
{
if (isset($this->data['columns'][$schema][$table])) {
return;
}
$this->prepareDataHierarchy('columns', $schema, $table);
}
/**
* Load constraint data
*
* @param string $table
* @param string $schema
*/
protected function loadConstraintData($table, $schema)
{
if (isset($this->data['constraints'][$schema])) {
return;
}
$this->prepareDataHierarchy('constraints', $schema);
}
/**
* Load constraint data keys
*
* @param string $schema
*/
protected function loadConstraintDataKeys($schema)
{
if (isset($this->data['constraint_keys'][$schema])) {
return;
}
$this->prepareDataHierarchy('constraint_keys', $schema);
}
/**
* Load constraint references
*
* @param string $table
* @param string $schema
*/
protected function loadConstraintReferences($table, $schema)
{
if (isset($this->data['constraint_references'][$schema])) {
return;
}
$this->prepareDataHierarchy('constraint_references', $schema);
}
/**
* Load trigger data
*
* @param string $schema
*/
protected function loadTriggerData($schema)
{
if (isset($this->data['triggers'][$schema])) {
return;
}
$this->prepareDataHierarchy('triggers', $schema);
}
}
zend-db-release-2.8.1/src/Metadata/Source/Factory.php 0000664 0000000 0000000 00000002635 12703724304 0022362 0 ustar 00root root 0000000 0000000 getPlatform()->getName();
switch ($platformName) {
case 'MySQL':
return new MysqlMetadata($adapter);
case 'SQLServer':
return new SqlServerMetadata($adapter);
case 'SQLite':
return new SqliteMetadata($adapter);
case 'PostgreSQL':
return new PostgresqlMetadata($adapter);
case 'Oracle':
return new OracleMetadata($adapter);
default:
throw new InvalidArgumentException("Unknown adapter platform '{$platformName}'");
}
}
}
zend-db-release-2.8.1/src/Metadata/Source/MysqlMetadata.php 0000664 0000000 0000000 00000046157 12703724304 0023530 0 ustar 00root root 0000000 0000000 data['schemas'])) {
return;
}
$this->prepareDataHierarchy('schemas');
$p = $this->adapter->getPlatform();
$sql = 'SELECT ' . $p->quoteIdentifier('SCHEMA_NAME')
. ' FROM ' . $p->quoteIdentifierChain(['INFORMATION_SCHEMA', 'SCHEMATA'])
. ' WHERE ' . $p->quoteIdentifier('SCHEMA_NAME')
. ' != \'INFORMATION_SCHEMA\'';
$results = $this->adapter->query($sql, Adapter::QUERY_MODE_EXECUTE);
$schemas = [];
foreach ($results->toArray() as $row) {
$schemas[] = $row['SCHEMA_NAME'];
}
$this->data['schemas'] = $schemas;
}
protected function loadTableNameData($schema)
{
if (isset($this->data['table_names'][$schema])) {
return;
}
$this->prepareDataHierarchy('table_names', $schema);
$p = $this->adapter->getPlatform();
$isColumns = [
['T', 'TABLE_NAME'],
['T', 'TABLE_TYPE'],
['V', 'VIEW_DEFINITION'],
['V', 'CHECK_OPTION'],
['V', 'IS_UPDATABLE'],
];
array_walk($isColumns, function (&$c) use ($p) { $c = $p->quoteIdentifierChain($c); });
$sql = 'SELECT ' . implode(', ', $isColumns)
. ' FROM ' . $p->quoteIdentifierChain(['INFORMATION_SCHEMA', 'TABLES']) . 'T'
. ' LEFT JOIN ' . $p->quoteIdentifierChain(['INFORMATION_SCHEMA', 'VIEWS']) . ' V'
. ' ON ' . $p->quoteIdentifierChain(['T', 'TABLE_SCHEMA'])
. ' = ' . $p->quoteIdentifierChain(['V', 'TABLE_SCHEMA'])
. ' AND ' . $p->quoteIdentifierChain(['T', 'TABLE_NAME'])
. ' = ' . $p->quoteIdentifierChain(['V', 'TABLE_NAME'])
. ' WHERE ' . $p->quoteIdentifierChain(['T', 'TABLE_TYPE'])
. ' IN (\'BASE TABLE\', \'VIEW\')';
if ($schema != self::DEFAULT_SCHEMA) {
$sql .= ' AND ' . $p->quoteIdentifierChain(['T', 'TABLE_SCHEMA'])
. ' = ' . $p->quoteTrustedValue($schema);
} else {
$sql .= ' AND ' . $p->quoteIdentifierChain(['T', 'TABLE_SCHEMA'])
. ' != \'INFORMATION_SCHEMA\'';
}
$results = $this->adapter->query($sql, Adapter::QUERY_MODE_EXECUTE);
$tables = [];
foreach ($results->toArray() as $row) {
$tables[$row['TABLE_NAME']] = [
'table_type' => $row['TABLE_TYPE'],
'view_definition' => $row['VIEW_DEFINITION'],
'check_option' => $row['CHECK_OPTION'],
'is_updatable' => ('YES' == $row['IS_UPDATABLE']),
];
}
$this->data['table_names'][$schema] = $tables;
}
protected function loadColumnData($table, $schema)
{
if (isset($this->data['columns'][$schema][$table])) {
return;
}
$this->prepareDataHierarchy('columns', $schema, $table);
$p = $this->adapter->getPlatform();
$isColumns = [
['C', 'ORDINAL_POSITION'],
['C', 'COLUMN_DEFAULT'],
['C', 'IS_NULLABLE'],
['C', 'DATA_TYPE'],
['C', 'CHARACTER_MAXIMUM_LENGTH'],
['C', 'CHARACTER_OCTET_LENGTH'],
['C', 'NUMERIC_PRECISION'],
['C', 'NUMERIC_SCALE'],
['C', 'COLUMN_NAME'],
['C', 'COLUMN_TYPE'],
];
array_walk($isColumns, function (&$c) use ($p) { $c = $p->quoteIdentifierChain($c); });
$sql = 'SELECT ' . implode(', ', $isColumns)
. ' FROM ' . $p->quoteIdentifierChain(['INFORMATION_SCHEMA', 'TABLES']) . 'T'
. ' INNER JOIN ' . $p->quoteIdentifierChain(['INFORMATION_SCHEMA', 'COLUMNS']) . 'C'
. ' ON ' . $p->quoteIdentifierChain(['T', 'TABLE_SCHEMA'])
. ' = ' . $p->quoteIdentifierChain(['C', 'TABLE_SCHEMA'])
. ' AND ' . $p->quoteIdentifierChain(['T', 'TABLE_NAME'])
. ' = ' . $p->quoteIdentifierChain(['C', 'TABLE_NAME'])
. ' WHERE ' . $p->quoteIdentifierChain(['T', 'TABLE_TYPE'])
. ' IN (\'BASE TABLE\', \'VIEW\')'
. ' AND ' . $p->quoteIdentifierChain(['T', 'TABLE_NAME'])
. ' = ' . $p->quoteTrustedValue($table);
if ($schema != self::DEFAULT_SCHEMA) {
$sql .= ' AND ' . $p->quoteIdentifierChain(['T', 'TABLE_SCHEMA'])
. ' = ' . $p->quoteTrustedValue($schema);
} else {
$sql .= ' AND ' . $p->quoteIdentifierChain(['T', 'TABLE_SCHEMA'])
. ' != \'INFORMATION_SCHEMA\'';
}
$results = $this->adapter->query($sql, Adapter::QUERY_MODE_EXECUTE);
$columns = [];
foreach ($results->toArray() as $row) {
$erratas = [];
$matches = [];
if (preg_match('/^(?:enum|set)\((.+)\)$/i', $row['COLUMN_TYPE'], $matches)) {
$permittedValues = $matches[1];
if (preg_match_all("/\\s*'((?:[^']++|'')*+)'\\s*(?:,|\$)/", $permittedValues, $matches, PREG_PATTERN_ORDER)) {
$permittedValues = str_replace("''", "'", $matches[1]);
} else {
$permittedValues = [$permittedValues];
}
$erratas['permitted_values'] = $permittedValues;
}
$columns[$row['COLUMN_NAME']] = [
'ordinal_position' => $row['ORDINAL_POSITION'],
'column_default' => $row['COLUMN_DEFAULT'],
'is_nullable' => ('YES' == $row['IS_NULLABLE']),
'data_type' => $row['DATA_TYPE'],
'character_maximum_length' => $row['CHARACTER_MAXIMUM_LENGTH'],
'character_octet_length' => $row['CHARACTER_OCTET_LENGTH'],
'numeric_precision' => $row['NUMERIC_PRECISION'],
'numeric_scale' => $row['NUMERIC_SCALE'],
'numeric_unsigned' => (false !== strpos($row['COLUMN_TYPE'], 'unsigned')),
'erratas' => $erratas,
];
}
$this->data['columns'][$schema][$table] = $columns;
}
protected function loadConstraintData($table, $schema)
{
if (isset($this->data['constraints'][$schema][$table])) {
return;
}
$this->prepareDataHierarchy('constraints', $schema, $table);
$isColumns = [
['T', 'TABLE_NAME'],
['TC', 'CONSTRAINT_NAME'],
['TC', 'CONSTRAINT_TYPE'],
['KCU', 'COLUMN_NAME'],
['RC', 'MATCH_OPTION'],
['RC', 'UPDATE_RULE'],
['RC', 'DELETE_RULE'],
['KCU', 'REFERENCED_TABLE_SCHEMA'],
['KCU', 'REFERENCED_TABLE_NAME'],
['KCU', 'REFERENCED_COLUMN_NAME'],
];
$p = $this->adapter->getPlatform();
array_walk($isColumns, function (&$c) use ($p) {
$c = $p->quoteIdentifierChain($c);
});
$sql = 'SELECT ' . implode(', ', $isColumns)
. ' FROM ' . $p->quoteIdentifierChain(['INFORMATION_SCHEMA', 'TABLES']) . ' T'
. ' INNER JOIN ' . $p->quoteIdentifierChain(['INFORMATION_SCHEMA', 'TABLE_CONSTRAINTS']) . ' TC'
. ' ON ' . $p->quoteIdentifierChain(['T', 'TABLE_SCHEMA'])
. ' = ' . $p->quoteIdentifierChain(['TC', 'TABLE_SCHEMA'])
. ' AND ' . $p->quoteIdentifierChain(['T', 'TABLE_NAME'])
. ' = ' . $p->quoteIdentifierChain(['TC', 'TABLE_NAME'])
. ' LEFT JOIN ' . $p->quoteIdentifierChain(['INFORMATION_SCHEMA', 'KEY_COLUMN_USAGE']) . ' KCU'
. ' ON ' . $p->quoteIdentifierChain(['TC', 'TABLE_SCHEMA'])
. ' = ' . $p->quoteIdentifierChain(['KCU', 'TABLE_SCHEMA'])
. ' AND ' . $p->quoteIdentifierChain(['TC', 'TABLE_NAME'])
. ' = ' . $p->quoteIdentifierChain(['KCU', 'TABLE_NAME'])
. ' AND ' . $p->quoteIdentifierChain(['TC', 'CONSTRAINT_NAME'])
. ' = ' . $p->quoteIdentifierChain(['KCU', 'CONSTRAINT_NAME'])
. ' LEFT JOIN ' . $p->quoteIdentifierChain(['INFORMATION_SCHEMA', 'REFERENTIAL_CONSTRAINTS']) . ' RC'
. ' ON ' . $p->quoteIdentifierChain(['TC', 'CONSTRAINT_SCHEMA'])
. ' = ' . $p->quoteIdentifierChain(['RC', 'CONSTRAINT_SCHEMA'])
. ' AND ' . $p->quoteIdentifierChain(['TC', 'CONSTRAINT_NAME'])
. ' = ' . $p->quoteIdentifierChain(['RC', 'CONSTRAINT_NAME'])
. ' WHERE ' . $p->quoteIdentifierChain(['T', 'TABLE_NAME'])
. ' = ' . $p->quoteTrustedValue($table)
. ' AND ' . $p->quoteIdentifierChain(['T', 'TABLE_TYPE'])
. ' IN (\'BASE TABLE\', \'VIEW\')';
if ($schema != self::DEFAULT_SCHEMA) {
$sql .= ' AND ' . $p->quoteIdentifierChain(['T', 'TABLE_SCHEMA'])
. ' = ' . $p->quoteTrustedValue($schema);
} else {
$sql .= ' AND ' . $p->quoteIdentifierChain(['T', 'TABLE_SCHEMA'])
. ' != \'INFORMATION_SCHEMA\'';
}
$sql .= ' ORDER BY CASE ' . $p->quoteIdentifierChain(['TC', 'CONSTRAINT_TYPE'])
. " WHEN 'PRIMARY KEY' THEN 1"
. " WHEN 'UNIQUE' THEN 2"
. " WHEN 'FOREIGN KEY' THEN 3"
. " ELSE 4 END"
. ', ' . $p->quoteIdentifierChain(['TC', 'CONSTRAINT_NAME'])
. ', ' . $p->quoteIdentifierChain(['KCU', 'ORDINAL_POSITION']);
$results = $this->adapter->query($sql, Adapter::QUERY_MODE_EXECUTE);
$realName = null;
$constraints = [];
foreach ($results->toArray() as $row) {
if ($row['CONSTRAINT_NAME'] !== $realName) {
$realName = $row['CONSTRAINT_NAME'];
$isFK = ('FOREIGN KEY' == $row['CONSTRAINT_TYPE']);
if ($isFK) {
$name = $realName;
} else {
$name = '_zf_' . $row['TABLE_NAME'] . '_' . $realName;
}
$constraints[$name] = [
'constraint_name' => $name,
'constraint_type' => $row['CONSTRAINT_TYPE'],
'table_name' => $row['TABLE_NAME'],
'columns' => [],
];
if ($isFK) {
$constraints[$name]['referenced_table_schema'] = $row['REFERENCED_TABLE_SCHEMA'];
$constraints[$name]['referenced_table_name'] = $row['REFERENCED_TABLE_NAME'];
$constraints[$name]['referenced_columns'] = [];
$constraints[$name]['match_option'] = $row['MATCH_OPTION'];
$constraints[$name]['update_rule'] = $row['UPDATE_RULE'];
$constraints[$name]['delete_rule'] = $row['DELETE_RULE'];
}
}
$constraints[$name]['columns'][] = $row['COLUMN_NAME'];
if ($isFK) {
$constraints[$name]['referenced_columns'][] = $row['REFERENCED_COLUMN_NAME'];
}
}
$this->data['constraints'][$schema][$table] = $constraints;
}
protected function loadConstraintDataNames($schema)
{
if (isset($this->data['constraint_names'][$schema])) {
return;
}
$this->prepareDataHierarchy('constraint_names', $schema);
$p = $this->adapter->getPlatform();
$isColumns = [
['TC', 'TABLE_NAME'],
['TC', 'CONSTRAINT_NAME'],
['TC', 'CONSTRAINT_TYPE'],
];
array_walk($isColumns, function (&$c) use ($p) {
$c = $p->quoteIdentifierChain($c);
});
$sql = 'SELECT ' . implode(', ', $isColumns)
. ' FROM ' . $p->quoteIdentifierChain(['INFORMATION_SCHEMA', 'TABLES']) . 'T'
. ' INNER JOIN ' . $p->quoteIdentifierChain(['INFORMATION_SCHEMA', 'TABLE_CONSTRAINTS']) . 'TC'
. ' ON ' . $p->quoteIdentifierChain(['T', 'TABLE_SCHEMA'])
. ' = ' . $p->quoteIdentifierChain(['TC', 'TABLE_SCHEMA'])
. ' AND ' . $p->quoteIdentifierChain(['T', 'TABLE_NAME'])
. ' = ' . $p->quoteIdentifierChain(['TC', 'TABLE_NAME'])
. ' WHERE ' . $p->quoteIdentifierChain(['T', 'TABLE_TYPE'])
. ' IN (\'BASE TABLE\', \'VIEW\')';
if ($schema != self::DEFAULT_SCHEMA) {
$sql .= ' AND ' . $p->quoteIdentifierChain(['T', 'TABLE_SCHEMA'])
. ' = ' . $p->quoteTrustedValue($schema);
} else {
$sql .= ' AND ' . $p->quoteIdentifierChain(['T', 'TABLE_SCHEMA'])
. ' != \'INFORMATION_SCHEMA\'';
}
$results = $this->adapter->query($sql, Adapter::QUERY_MODE_EXECUTE);
$data = [];
foreach ($results->toArray() as $row) {
$data[] = array_change_key_case($row, CASE_LOWER);
}
$this->data['constraint_names'][$schema] = $data;
}
protected function loadConstraintDataKeys($schema)
{
if (isset($this->data['constraint_keys'][$schema])) {
return;
}
$this->prepareDataHierarchy('constraint_keys', $schema);
$p = $this->adapter->getPlatform();
$isColumns = [
['T', 'TABLE_NAME'],
['KCU', 'CONSTRAINT_NAME'],
['KCU', 'COLUMN_NAME'],
['KCU', 'ORDINAL_POSITION'],
];
array_walk($isColumns, function (&$c) use ($p) {
$c = $p->quoteIdentifierChain($c);
});
$sql = 'SELECT ' . implode(', ', $isColumns)
. ' FROM ' . $p->quoteIdentifierChain(['INFORMATION_SCHEMA', 'TABLES']) . 'T'
. ' INNER JOIN ' . $p->quoteIdentifierChain(['INFORMATION_SCHEMA', 'KEY_COLUMN_USAGE']) . 'KCU'
. ' ON ' . $p->quoteIdentifierChain(['T', 'TABLE_SCHEMA'])
. ' = ' . $p->quoteIdentifierChain(['KCU', 'TABLE_SCHEMA'])
. ' AND ' . $p->quoteIdentifierChain(['T', 'TABLE_NAME'])
. ' = ' . $p->quoteIdentifierChain(['KCU', 'TABLE_NAME'])
. ' WHERE ' . $p->quoteIdentifierChain(['T', 'TABLE_TYPE'])
. ' IN (\'BASE TABLE\', \'VIEW\')';
if ($schema != self::DEFAULT_SCHEMA) {
$sql .= ' AND ' . $p->quoteIdentifierChain(['T', 'TABLE_SCHEMA'])
. ' = ' . $p->quoteTrustedValue($schema);
} else {
$sql .= ' AND ' . $p->quoteIdentifierChain(['T', 'TABLE_SCHEMA'])
. ' != \'INFORMATION_SCHEMA\'';
}
$results = $this->adapter->query($sql, Adapter::QUERY_MODE_EXECUTE);
$data = [];
foreach ($results->toArray() as $row) {
$data[] = array_change_key_case($row, CASE_LOWER);
}
$this->data['constraint_keys'][$schema] = $data;
}
protected function loadConstraintReferences($table, $schema)
{
parent::loadConstraintReferences($table, $schema);
$p = $this->adapter->getPlatform();
$isColumns = [
['RC', 'TABLE_NAME'],
['RC', 'CONSTRAINT_NAME'],
['RC', 'UPDATE_RULE'],
['RC', 'DELETE_RULE'],
['KCU', 'REFERENCED_TABLE_SCHEMA'],
['KCU', 'REFERENCED_TABLE_NAME'],
['KCU', 'REFERENCED_COLUMN_NAME'],
];
array_walk($isColumns, function (&$c) use ($p) {
$c = $p->quoteIdentifierChain($c);
});
$sql = 'SELECT ' . implode(', ', $isColumns)
. 'FROM ' . $p->quoteIdentifierChain(['INFORMATION_SCHEMA', 'TABLES']) . 'T'
. ' INNER JOIN ' . $p->quoteIdentifierChain(['INFORMATION_SCHEMA', 'REFERENTIAL_CONSTRAINTS']) . 'RC'
. ' ON ' . $p->quoteIdentifierChain(['T', 'TABLE_SCHEMA'])
. ' = ' . $p->quoteIdentifierChain(['RC', 'CONSTRAINT_SCHEMA'])
. ' AND ' . $p->quoteIdentifierChain(['T', 'TABLE_NAME'])
. ' = ' . $p->quoteIdentifierChain(['RC', 'TABLE_NAME'])
. ' INNER JOIN ' . $p->quoteIdentifierChain(['INFORMATION_SCHEMA', 'KEY_COLUMN_USAGE']) . 'KCU'
. ' ON ' . $p->quoteIdentifierChain(['RC', 'CONSTRAINT_SCHEMA'])
. ' = ' . $p->quoteIdentifierChain(['KCU', 'TABLE_SCHEMA'])
. ' AND ' . $p->quoteIdentifierChain(['RC', 'TABLE_NAME'])
. ' = ' . $p->quoteIdentifierChain(['KCU', 'TABLE_NAME'])
. ' AND ' . $p->quoteIdentifierChain(['RC', 'CONSTRAINT_NAME'])
. ' = ' . $p->quoteIdentifierChain(['KCU', 'CONSTRAINT_NAME'])
. 'WHERE ' . $p->quoteIdentifierChain(['T', 'TABLE_TYPE'])
. ' IN (\'BASE TABLE\', \'VIEW\')';
if ($schema != self::DEFAULT_SCHEMA) {
$sql .= ' AND ' . $p->quoteIdentifierChain(['T', 'TABLE_SCHEMA'])
. ' = ' . $p->quoteTrustedValue($schema);
} else {
$sql .= ' AND ' . $p->quoteIdentifierChain(['T', 'TABLE_SCHEMA'])
. ' != \'INFORMATION_SCHEMA\'';
}
$results = $this->adapter->query($sql, Adapter::QUERY_MODE_EXECUTE);
$data = [];
foreach ($results->toArray() as $row) {
$data[] = array_change_key_case($row, CASE_LOWER);
}
$this->data['constraint_references'][$schema] = $data;
}
protected function loadTriggerData($schema)
{
if (isset($this->data['triggers'][$schema])) {
return;
}
$this->prepareDataHierarchy('triggers', $schema);
$p = $this->adapter->getPlatform();
$isColumns = [
// 'TRIGGER_CATALOG',
// 'TRIGGER_SCHEMA',
'TRIGGER_NAME',
'EVENT_MANIPULATION',
'EVENT_OBJECT_CATALOG',
'EVENT_OBJECT_SCHEMA',
'EVENT_OBJECT_TABLE',
'ACTION_ORDER',
'ACTION_CONDITION',
'ACTION_STATEMENT',
'ACTION_ORIENTATION',
'ACTION_TIMING',
'ACTION_REFERENCE_OLD_TABLE',
'ACTION_REFERENCE_NEW_TABLE',
'ACTION_REFERENCE_OLD_ROW',
'ACTION_REFERENCE_NEW_ROW',
'CREATED',
];
array_walk($isColumns, function (&$c) use ($p) {
$c = $p->quoteIdentifier($c);
});
$sql = 'SELECT ' . implode(', ', $isColumns)
. ' FROM ' . $p->quoteIdentifierChain(['INFORMATION_SCHEMA', 'TRIGGERS'])
. ' WHERE ';
if ($schema != self::DEFAULT_SCHEMA) {
$sql .= $p->quoteIdentifier('TRIGGER_SCHEMA')
. ' = ' . $p->quoteTrustedValue($schema);
} else {
$sql .= $p->quoteIdentifier('TRIGGER_SCHEMA')
. ' != \'INFORMATION_SCHEMA\'';
}
$results = $this->adapter->query($sql, Adapter::QUERY_MODE_EXECUTE);
$data = [];
foreach ($results->toArray() as $row) {
$row = array_change_key_case($row, CASE_LOWER);
if (null !== $row['created']) {
$row['created'] = new \DateTime($row['created']);
}
$data[$row['trigger_name']] = $row;
}
$this->data['triggers'][$schema] = $data;
}
}
zend-db-release-2.8.1/src/Metadata/Source/OracleMetadata.php 0000664 0000000 0000000 00000017225 12703724304 0023622 0 ustar 00root root 0000000 0000000 'CHECK',
'P' => 'PRIMARY KEY',
'R' => 'FOREIGN_KEY'
];
/**
* {@inheritdoc}
* @see \Zend\Db\Metadata\Source\AbstractSource::loadColumnData()
*/
protected function loadColumnData($table, $schema)
{
if (isset($this->data['columns'][$schema][$table])) {
return;
}
$isColumns = [
'COLUMN_ID',
'COLUMN_NAME',
'DATA_DEFAULT',
'NULLABLE',
'DATA_TYPE',
'DATA_LENGTH',
'DATA_PRECISION',
'DATA_SCALE'
];
$this->prepareDataHierarchy('columns', $schema, $table);
$parameters = [
':ownername' => $schema,
':tablename' => $table
];
$sql = 'SELECT ' . implode(', ', $isColumns)
. ' FROM all_tab_columns'
. ' WHERE owner = :ownername AND table_name = :tablename';
$result = $this->adapter->query($sql)->execute($parameters);
$columns = [];
foreach ($result as $row) {
$columns[$row['COLUMN_NAME']] = [
'ordinal_position' => $row['COLUMN_ID'],
'column_default' => $row['DATA_DEFAULT'],
'is_nullable' => ('Y' == $row['NULLABLE']),
'data_type' => $row['DATA_TYPE'],
'character_maximum_length' => $row['DATA_LENGTH'],
'character_octet_length' => null,
'numeric_precision' => $row['DATA_PRECISION'],
'numeric_scale' => $row['DATA_SCALE'],
'numeric_unsigned' => false,
'erratas' => [],
];
}
$this->data['columns'][$schema][$table] = $columns;
return $this;
}
/**
* Constraint type
*
* @param string $type
* @return string
*/
protected function getConstraintType($type)
{
if (isset($this->constraintTypeMap[$type])) {
return $this->constraintTypeMap[$type];
}
return $type;
}
/**
* {@inheritdoc}
* @see \Zend\Db\Metadata\Source\AbstractSource::loadConstraintData()
*/
protected function loadConstraintData($table, $schema)
{
if (isset($this->data['constraints'][$schema][$table])) {
return;
}
$this->prepareDataHierarchy('constraints', $schema, $table);
$sql = '
SELECT
ac.owner,
ac.constraint_name,
ac.constraint_type,
ac.search_condition check_clause,
ac.table_name,
ac.delete_rule,
cc1.column_name,
cc2.table_name as ref_table,
cc2.column_name as ref_column,
cc2.owner as ref_owner
FROM all_constraints ac
INNER JOIN all_cons_columns cc1
ON cc1.constraint_name = ac.constraint_name
LEFT JOIN all_cons_columns cc2
ON cc2.constraint_name = ac.r_constraint_name
AND cc2.position = cc1.position
WHERE
ac.owner = :ownername AND ac.table_name = :tablename
ORDER BY ac.constraint_name
';
$parameters = [
':ownername' => $schema,
':tablename' => $table
];
$results = $this->adapter->query($sql)->execute($parameters);
$isFK = false;
$name = null;
$constraints = [];
foreach ($results as $row) {
if ($row['CONSTRAINT_NAME'] !== $name) {
$name = $row['CONSTRAINT_NAME'];
$constraints[$name] = [
'constraint_name' => $name,
'constraint_type' => $this->getConstraintType($row['CONSTRAINT_TYPE']),
'table_name' => $row['TABLE_NAME'],
];
if ('C' == $row['CONSTRAINT_TYPE']) {
$constraints[$name]['CHECK_CLAUSE'] = $row['CHECK_CLAUSE'];
continue;
}
$constraints[$name]['columns'] = [];
$isFK = ('R' == $row['CONSTRAINT_TYPE']);
if ($isFK) {
$constraints[$name]['referenced_table_schema'] = $row['REF_OWNER'];
$constraints[$name]['referenced_table_name'] = $row['REF_TABLE'];
$constraints[$name]['referenced_columns'] = [];
$constraints[$name]['match_option'] = 'NONE';
$constraints[$name]['update_rule'] = null;
$constraints[$name]['delete_rule'] = $row['DELETE_RULE'];
}
}
$constraints[$name]['columns'][] = $row['COLUMN_NAME'];
if ($isFK) {
$constraints[$name]['referenced_columns'][] = $row['REF_COLUMN'];
}
}
return $this;
}
/**
* {@inheritdoc}
* @see \Zend\Db\Metadata\Source\AbstractSource::loadSchemaData()
*/
protected function loadSchemaData()
{
if (isset($this->data['schemas'])) {
return;
}
$this->prepareDataHierarchy('schemas');
$sql = 'SELECT USERNAME FROM ALL_USERS';
$results = $this->adapter->query($sql, Adapter::QUERY_MODE_EXECUTE);
$schemas = [];
foreach ($results->toArray() as $row) {
$schemas[] = $row['USERNAME'];
}
$this->data['schemas'] = $schemas;
}
/**
* {@inheritdoc}
* @see \Zend\Db\Metadata\Source\AbstractSource::loadTableNameData()
*/
protected function loadTableNameData($schema)
{
if (isset($this->data['table_names'][$schema])) {
return $this;
}
$this->prepareDataHierarchy('table_names', $schema);
$tables = [];
// Tables
$bind = [':OWNER' => strtoupper($schema)];
$result = $this->adapter->query('SELECT TABLE_NAME FROM ALL_TABLES WHERE OWNER=:OWNER')->execute($bind);
foreach ($result as $row) {
$tables[$row['TABLE_NAME']] = [
'table_type' => 'BASE TABLE',
'view_definition' => null,
'check_option' => null,
'is_updatable' => false,
];
}
// Views
$result = $this->adapter->query('SELECT VIEW_NAME, TEXT FROM ALL_VIEWS WHERE OWNER=:OWNER', $bind);
foreach ($result as $row) {
$tables[$row['VIEW_NAME']] = [
'table_type' => 'VIEW',
'view_definition' => null,
'check_option' => 'NONE',
'is_updatable' => false,
];
}
$this->data['table_names'][$schema] = $tables;
return $this;
}
/**
* FIXME: load trigger data
*
* {@inheritdoc}
*
* @see \Zend\Db\Metadata\Source\AbstractSource::loadTriggerData()
*/
protected function loadTriggerData($schema)
{
if (isset($this->data['triggers'][$schema])) {
return;
}
$this->prepareDataHierarchy('triggers', $schema);
}
}
zend-db-release-2.8.1/src/Metadata/Source/PostgresqlMetadata.php 0000664 0000000 0000000 00000033521 12703724304 0024555 0 ustar 00root root 0000000 0000000 data['schemas'])) {
return;
}
$this->prepareDataHierarchy('schemas');
$p = $this->adapter->getPlatform();
$sql = 'SELECT ' . $p->quoteIdentifier('schema_name')
. ' FROM ' . $p->quoteIdentifierChain(['information_schema', 'schemata'])
. ' WHERE ' . $p->quoteIdentifier('schema_name')
. ' != \'information_schema\''
. ' AND ' . $p->quoteIdentifier('schema_name') . " NOT LIKE 'pg_%'";
$results = $this->adapter->query($sql, Adapter::QUERY_MODE_EXECUTE);
$schemas = [];
foreach ($results->toArray() as $row) {
$schemas[] = $row['schema_name'];
}
$this->data['schemas'] = $schemas;
}
protected function loadTableNameData($schema)
{
if (isset($this->data['table_names'][$schema])) {
return;
}
$this->prepareDataHierarchy('table_names', $schema);
$p = $this->adapter->getPlatform();
$isColumns = [
['t', 'table_name'],
['t', 'table_type'],
['v', 'view_definition'],
['v', 'check_option'],
['v', 'is_updatable'],
];
array_walk($isColumns, function (&$c) use ($p) { $c = $p->quoteIdentifierChain($c); });
$sql = 'SELECT ' . implode(', ', $isColumns)
. ' FROM ' . $p->quoteIdentifierChain(['information_schema', 'tables']) . ' t'
. ' LEFT JOIN ' . $p->quoteIdentifierChain(['information_schema', 'views']) . ' v'
. ' ON ' . $p->quoteIdentifierChain(['t', 'table_schema'])
. ' = ' . $p->quoteIdentifierChain(['v', 'table_schema'])
. ' AND ' . $p->quoteIdentifierChain(['t', 'table_name'])
. ' = ' . $p->quoteIdentifierChain(['v', 'table_name'])
. ' WHERE ' . $p->quoteIdentifierChain(['t', 'table_type'])
. ' IN (\'BASE TABLE\', \'VIEW\')';
if ($schema != self::DEFAULT_SCHEMA) {
$sql .= ' AND ' . $p->quoteIdentifierChain(['t', 'table_schema'])
. ' = ' . $p->quoteTrustedValue($schema);
} else {
$sql .= ' AND ' . $p->quoteIdentifierChain(['t', 'table_schema'])
. ' != \'information_schema\'';
}
$results = $this->adapter->query($sql, Adapter::QUERY_MODE_EXECUTE);
$tables = [];
foreach ($results->toArray() as $row) {
$tables[$row['table_name']] = [
'table_type' => $row['table_type'],
'view_definition' => $row['view_definition'],
'check_option' => $row['check_option'],
'is_updatable' => ('YES' == $row['is_updatable']),
];
}
$this->data['table_names'][$schema] = $tables;
}
protected function loadColumnData($table, $schema)
{
if (isset($this->data['columns'][$schema][$table])) {
return;
}
$this->prepareDataHierarchy('columns', $schema, $table);
$platform = $this->adapter->getPlatform();
$isColumns = [
'table_name',
'column_name',
'ordinal_position',
'column_default',
'is_nullable',
'data_type',
'character_maximum_length',
'character_octet_length',
'numeric_precision',
'numeric_scale',
];
array_walk($isColumns, function (&$c) use ($platform) { $c = $platform->quoteIdentifier($c); });
$sql = 'SELECT ' . implode(', ', $isColumns)
. ' FROM ' . $platform->quoteIdentifier('information_schema')
. $platform->getIdentifierSeparator() . $platform->quoteIdentifier('columns')
. ' WHERE ' . $platform->quoteIdentifier('table_schema')
. ' != \'information\''
. ' AND ' . $platform->quoteIdentifier('table_name')
. ' = ' . $platform->quoteTrustedValue($table);
if ($schema != '__DEFAULT_SCHEMA__') {
$sql .= ' AND ' . $platform->quoteIdentifier('table_schema')
. ' = ' . $platform->quoteTrustedValue($schema);
}
$results = $this->adapter->query($sql, Adapter::QUERY_MODE_EXECUTE);
$columns = [];
foreach ($results->toArray() as $row) {
$columns[$row['column_name']] = [
'ordinal_position' => $row['ordinal_position'],
'column_default' => $row['column_default'],
'is_nullable' => ('YES' == $row['is_nullable']),
'data_type' => $row['data_type'],
'character_maximum_length' => $row['character_maximum_length'],
'character_octet_length' => $row['character_octet_length'],
'numeric_precision' => $row['numeric_precision'],
'numeric_scale' => $row['numeric_scale'],
'numeric_unsigned' => null,
'erratas' => [],
];
}
$this->data['columns'][$schema][$table] = $columns;
}
protected function loadConstraintData($table, $schema)
{
if (isset($this->data['constraints'][$schema][$table])) {
return;
}
$this->prepareDataHierarchy('constraints', $schema, $table);
$isColumns = [
['t', 'table_name'],
['tc', 'constraint_name'],
['tc', 'constraint_type'],
['kcu', 'column_name'],
['cc', 'check_clause'],
['rc', 'match_option'],
['rc', 'update_rule'],
['rc', 'delete_rule'],
['referenced_table_schema' => 'kcu2', 'table_schema'],
['referenced_table_name' => 'kcu2', 'table_name'],
['referenced_column_name' => 'kcu2', 'column_name'],
];
$p = $this->adapter->getPlatform();
array_walk($isColumns, function (&$c) use ($p) {
$alias = key($c);
$c = $p->quoteIdentifierChain($c);
if (is_string($alias)) {
$c .= ' ' . $p->quoteIdentifier($alias);
}
});
$sql = 'SELECT ' . implode(', ', $isColumns)
. ' FROM ' . $p->quoteIdentifierChain(['information_schema', 'tables']) . ' t'
. ' INNER JOIN ' . $p->quoteIdentifierChain(['information_schema', 'table_constraints']) . ' tc'
. ' ON ' . $p->quoteIdentifierChain(['t', 'table_schema'])
. ' = ' . $p->quoteIdentifierChain(['tc', 'table_schema'])
. ' AND ' . $p->quoteIdentifierChain(['t', 'table_name'])
. ' = ' . $p->quoteIdentifierChain(['tc', 'table_name'])
. ' LEFT JOIN ' . $p->quoteIdentifierChain(['information_schema', 'key_column_usage']) . ' kcu'
. ' ON ' . $p->quoteIdentifierChain(['tc', 'table_schema'])
. ' = ' . $p->quoteIdentifierChain(['kcu', 'table_schema'])
. ' AND ' . $p->quoteIdentifierChain(['tc', 'table_name'])
. ' = ' . $p->quoteIdentifierChain(['kcu', 'table_name'])
. ' AND ' . $p->quoteIdentifierChain(['tc', 'constraint_name'])
. ' = ' . $p->quoteIdentifierChain(['kcu', 'constraint_name'])
. ' LEFT JOIN ' . $p->quoteIdentifierChain(['information_schema', 'check_constraints']) . ' cc'
. ' ON ' . $p->quoteIdentifierChain(['tc', 'constraint_schema'])
. ' = ' . $p->quoteIdentifierChain(['cc', 'constraint_schema'])
. ' AND ' . $p->quoteIdentifierChain(['tc', 'constraint_name'])
. ' = ' . $p->quoteIdentifierChain(['cc', 'constraint_name'])
. ' LEFT JOIN ' . $p->quoteIdentifierChain(['information_schema', 'referential_constraints']) . ' rc'
. ' ON ' . $p->quoteIdentifierChain(['tc', 'constraint_schema'])
. ' = ' . $p->quoteIdentifierChain(['rc', 'constraint_schema'])
. ' AND ' . $p->quoteIdentifierChain(['tc', 'constraint_name'])
. ' = ' . $p->quoteIdentifierChain(['rc', 'constraint_name'])
. ' LEFT JOIN ' . $p->quoteIdentifierChain(['information_schema', 'key_column_usage']) . ' kcu2'
. ' ON ' . $p->quoteIdentifierChain(['rc', 'unique_constraint_schema'])
. ' = ' . $p->quoteIdentifierChain(['kcu2', 'constraint_schema'])
. ' AND ' . $p->quoteIdentifierChain(['rc', 'unique_constraint_name'])
. ' = ' . $p->quoteIdentifierChain(['kcu2', 'constraint_name'])
. ' AND ' . $p->quoteIdentifierChain(['kcu', 'position_in_unique_constraint'])
. ' = ' . $p->quoteIdentifierChain(['kcu2', 'ordinal_position'])
. ' WHERE ' . $p->quoteIdentifierChain(['t', 'table_name'])
. ' = ' . $p->quoteTrustedValue($table)
. ' AND ' . $p->quoteIdentifierChain(['t', 'table_type'])
. ' IN (\'BASE TABLE\', \'VIEW\')';
if ($schema != self::DEFAULT_SCHEMA) {
$sql .= ' AND ' . $p->quoteIdentifierChain(['t', 'table_schema'])
. ' = ' . $p->quoteTrustedValue($schema);
} else {
$sql .= ' AND ' . $p->quoteIdentifierChain(['t', 'table_schema'])
. ' != \'information_schema\'';
}
$sql .= ' ORDER BY CASE ' . $p->quoteIdentifierChain(['tc', 'constraint_type'])
. " WHEN 'PRIMARY KEY' THEN 1"
. " WHEN 'UNIQUE' THEN 2"
. " WHEN 'FOREIGN KEY' THEN 3"
. " WHEN 'CHECK' THEN 4"
. " ELSE 5 END"
. ', ' . $p->quoteIdentifierChain(['tc', 'constraint_name'])
. ', ' . $p->quoteIdentifierChain(['kcu', 'ordinal_position']);
$results = $this->adapter->query($sql, Adapter::QUERY_MODE_EXECUTE);
$name = null;
$constraints = [];
foreach ($results->toArray() as $row) {
if ($row['constraint_name'] !== $name) {
$name = $row['constraint_name'];
$constraints[$name] = [
'constraint_name' => $name,
'constraint_type' => $row['constraint_type'],
'table_name' => $row['table_name'],
];
if ('CHECK' == $row['constraint_type']) {
$constraints[$name]['check_clause'] = $row['check_clause'];
continue;
}
$constraints[$name]['columns'] = [];
$isFK = ('FOREIGN KEY' == $row['constraint_type']);
if ($isFK) {
$constraints[$name]['referenced_table_schema'] = $row['referenced_table_schema'];
$constraints[$name]['referenced_table_name'] = $row['referenced_table_name'];
$constraints[$name]['referenced_columns'] = [];
$constraints[$name]['match_option'] = $row['match_option'];
$constraints[$name]['update_rule'] = $row['update_rule'];
$constraints[$name]['delete_rule'] = $row['delete_rule'];
}
}
$constraints[$name]['columns'][] = $row['column_name'];
if ($isFK) {
$constraints[$name]['referenced_columns'][] = $row['referenced_column_name'];
}
}
$this->data['constraints'][$schema][$table] = $constraints;
}
protected function loadTriggerData($schema)
{
if (isset($this->data['triggers'][$schema])) {
return;
}
$this->prepareDataHierarchy('triggers', $schema);
$p = $this->adapter->getPlatform();
$isColumns = [
'trigger_name',
'event_manipulation',
'event_object_catalog',
'event_object_schema',
'event_object_table',
'action_order',
'action_condition',
'action_statement',
'action_orientation',
['action_timing' => 'condition_timing'],
['action_reference_old_table' => 'condition_reference_old_table'],
['action_reference_new_table' => 'condition_reference_new_table'],
'created',
];
array_walk($isColumns, function (&$c) use ($p) {
if (is_array($c)) {
$alias = key($c);
$c = $p->quoteIdentifierChain($c);
if (is_string($alias)) {
$c .= ' ' . $p->quoteIdentifier($alias);
}
} else {
$c = $p->quoteIdentifier($c);
}
});
$sql = 'SELECT ' . implode(', ', $isColumns)
. ' FROM ' . $p->quoteIdentifierChain(['information_schema', 'triggers'])
. ' WHERE ';
if ($schema != self::DEFAULT_SCHEMA) {
$sql .= $p->quoteIdentifier('trigger_schema')
. ' = ' . $p->quoteTrustedValue($schema);
} else {
$sql .= $p->quoteIdentifier('trigger_schema')
. ' != \'information_schema\'';
}
$results = $this->adapter->query($sql, Adapter::QUERY_MODE_EXECUTE);
$data = [];
foreach ($results->toArray() as $row) {
$row = array_change_key_case($row, CASE_LOWER);
$row['action_reference_old_row'] = 'OLD';
$row['action_reference_new_row'] = 'NEW';
if (null !== $row['created']) {
$row['created'] = new \DateTime($row['created']);
}
$data[$row['trigger_name']] = $row;
}
$this->data['triggers'][$schema] = $data;
}
}
zend-db-release-2.8.1/src/Metadata/Source/SqlServerMetadata.php 0000664 0000000 0000000 00000033525 12703724304 0024344 0 ustar 00root root 0000000 0000000 data['schemas'])) {
return;
}
$this->prepareDataHierarchy('schemas');
$p = $this->adapter->getPlatform();
$sql = 'SELECT ' . $p->quoteIdentifier('SCHEMA_NAME')
. ' FROM ' . $p->quoteIdentifierChain(['INFORMATION_SCHEMA', 'SCHEMATA'])
. ' WHERE ' . $p->quoteIdentifier('SCHEMA_NAME')
. ' != \'INFORMATION_SCHEMA\'';
$results = $this->adapter->query($sql, Adapter::QUERY_MODE_EXECUTE);
$schemas = [];
foreach ($results->toArray() as $row) {
$schemas[] = $row['SCHEMA_NAME'];
}
$this->data['schemas'] = $schemas;
}
protected function loadTableNameData($schema)
{
if (isset($this->data['table_names'][$schema])) {
return;
}
$this->prepareDataHierarchy('table_names', $schema);
$p = $this->adapter->getPlatform();
$isColumns = [
['T', 'TABLE_NAME'],
['T', 'TABLE_TYPE'],
['V', 'VIEW_DEFINITION'],
['V', 'CHECK_OPTION'],
['V', 'IS_UPDATABLE'],
];
array_walk($isColumns, function (&$c) use ($p) { $c = $p->quoteIdentifierChain($c); });
$sql = 'SELECT ' . implode(', ', $isColumns)
. ' FROM ' . $p->quoteIdentifierChain(['INFORMATION_SCHEMA', 'TABLES']) . ' t'
. ' LEFT JOIN ' . $p->quoteIdentifierChain(['INFORMATION_SCHEMA', 'VIEWS']) . ' v'
. ' ON ' . $p->quoteIdentifierChain(['T', 'TABLE_SCHEMA'])
. ' = ' . $p->quoteIdentifierChain(['V', 'TABLE_SCHEMA'])
. ' AND ' . $p->quoteIdentifierChain(['T', 'TABLE_NAME'])
. ' = ' . $p->quoteIdentifierChain(['V', 'TABLE_NAME'])
. ' WHERE ' . $p->quoteIdentifierChain(['T', 'TABLE_TYPE'])
. ' IN (\'BASE TABLE\', \'VIEW\')';
if ($schema != self::DEFAULT_SCHEMA) {
$sql .= ' AND ' . $p->quoteIdentifierChain(['T', 'TABLE_SCHEMA'])
. ' = ' . $p->quoteTrustedValue($schema);
} else {
$sql .= ' AND ' . $p->quoteIdentifierChain(['T', 'TABLE_SCHEMA'])
. ' != \'INFORMATION_SCHEMA\'';
}
$results = $this->adapter->query($sql, Adapter::QUERY_MODE_EXECUTE);
$tables = [];
foreach ($results->toArray() as $row) {
$tables[$row['TABLE_NAME']] = [
'table_type' => $row['TABLE_TYPE'],
'view_definition' => $row['VIEW_DEFINITION'],
'check_option' => $row['CHECK_OPTION'],
'is_updatable' => ('YES' == $row['IS_UPDATABLE']),
];
}
$this->data['table_names'][$schema] = $tables;
}
protected function loadColumnData($table, $schema)
{
if (isset($this->data['columns'][$schema][$table])) {
return;
}
$this->prepareDataHierarchy('columns', $schema, $table);
$p = $this->adapter->getPlatform();
$isColumns = [
['C', 'ORDINAL_POSITION'],
['C', 'COLUMN_DEFAULT'],
['C', 'IS_NULLABLE'],
['C', 'DATA_TYPE'],
['C', 'CHARACTER_MAXIMUM_LENGTH'],
['C', 'CHARACTER_OCTET_LENGTH'],
['C', 'NUMERIC_PRECISION'],
['C', 'NUMERIC_SCALE'],
['C', 'COLUMN_NAME'],
];
array_walk($isColumns, function (&$c) use ($p) { $c = $p->quoteIdentifierChain($c); });
$sql = 'SELECT ' . implode(', ', $isColumns)
. ' FROM ' . $p->quoteIdentifierChain(['INFORMATION_SCHEMA', 'TABLES']) . 'T'
. ' INNER JOIN ' . $p->quoteIdentifierChain(['INFORMATION_SCHEMA', 'COLUMNS']) . 'C'
. ' ON ' . $p->quoteIdentifierChain(['T', 'TABLE_SCHEMA'])
. ' = ' . $p->quoteIdentifierChain(['C', 'TABLE_SCHEMA'])
. ' AND ' . $p->quoteIdentifierChain(['T', 'TABLE_NAME'])
. ' = ' . $p->quoteIdentifierChain(['C', 'TABLE_NAME'])
. ' WHERE ' . $p->quoteIdentifierChain(['T', 'TABLE_TYPE'])
. ' IN (\'BASE TABLE\', \'VIEW\')'
. ' AND ' . $p->quoteIdentifierChain(['T', 'TABLE_NAME'])
. ' = ' . $p->quoteTrustedValue($table);
if ($schema != self::DEFAULT_SCHEMA) {
$sql .= ' AND ' . $p->quoteIdentifierChain(['T', 'TABLE_SCHEMA'])
. ' = ' . $p->quoteTrustedValue($schema);
} else {
$sql .= ' AND ' . $p->quoteIdentifierChain(['T', 'TABLE_SCHEMA'])
. ' != \'INFORMATION_SCHEMA\'';
}
$results = $this->adapter->query($sql, Adapter::QUERY_MODE_EXECUTE);
$columns = [];
foreach ($results->toArray() as $row) {
$columns[$row['COLUMN_NAME']] = [
'ordinal_position' => $row['ORDINAL_POSITION'],
'column_default' => $row['COLUMN_DEFAULT'],
'is_nullable' => ('YES' == $row['IS_NULLABLE']),
'data_type' => $row['DATA_TYPE'],
'character_maximum_length' => $row['CHARACTER_MAXIMUM_LENGTH'],
'character_octet_length' => $row['CHARACTER_OCTET_LENGTH'],
'numeric_precision' => $row['NUMERIC_PRECISION'],
'numeric_scale' => $row['NUMERIC_SCALE'],
'numeric_unsigned' => null,
'erratas' => [],
];
}
$this->data['columns'][$schema][$table] = $columns;
}
protected function loadConstraintData($table, $schema)
{
if (isset($this->data['constraints'][$schema][$table])) {
return;
}
$this->prepareDataHierarchy('constraints', $schema, $table);
$isColumns = [
['T', 'TABLE_NAME'],
['TC', 'CONSTRAINT_NAME'],
['TC', 'CONSTRAINT_TYPE'],
['KCU', 'COLUMN_NAME'],
['CC', 'CHECK_CLAUSE'],
['RC', 'MATCH_OPTION'],
['RC', 'UPDATE_RULE'],
['RC', 'DELETE_RULE'],
['REFERENCED_TABLE_SCHEMA' => 'KCU2', 'TABLE_SCHEMA'],
['REFERENCED_TABLE_NAME' => 'KCU2', 'TABLE_NAME'],
['REFERENCED_COLUMN_NAME' => 'KCU2', 'COLUMN_NAME'],
];
$p = $this->adapter->getPlatform();
array_walk($isColumns, function (&$c) use ($p) {
$alias = key($c);
$c = $p->quoteIdentifierChain($c);
if (is_string($alias)) {
$c .= ' ' . $p->quoteIdentifier($alias);
}
});
$sql = 'SELECT ' . implode(', ', $isColumns)
. ' FROM ' . $p->quoteIdentifierChain(['INFORMATION_SCHEMA', 'TABLES']) . ' T'
. ' INNER JOIN ' . $p->quoteIdentifierChain(['INFORMATION_SCHEMA', 'TABLE_CONSTRAINTS']) . ' TC'
. ' ON ' . $p->quoteIdentifierChain(['T', 'TABLE_SCHEMA'])
. ' = ' . $p->quoteIdentifierChain(['TC', 'TABLE_SCHEMA'])
. ' AND ' . $p->quoteIdentifierChain(['T', 'TABLE_NAME'])
. ' = ' . $p->quoteIdentifierChain(['TC', 'TABLE_NAME'])
. ' LEFT JOIN ' . $p->quoteIdentifierChain(['INFORMATION_SCHEMA', 'KEY_COLUMN_USAGE']) . ' KCU'
. ' ON ' . $p->quoteIdentifierChain(['TC', 'TABLE_SCHEMA'])
. ' = ' . $p->quoteIdentifierChain(['KCU', 'TABLE_SCHEMA'])
. ' AND ' . $p->quoteIdentifierChain(['TC', 'TABLE_NAME'])
. ' = ' . $p->quoteIdentifierChain(['KCU', 'TABLE_NAME'])
. ' AND ' . $p->quoteIdentifierChain(['TC', 'CONSTRAINT_NAME'])
. ' = ' . $p->quoteIdentifierChain(['KCU', 'CONSTRAINT_NAME'])
. ' LEFT JOIN ' . $p->quoteIdentifierChain(['INFORMATION_SCHEMA', 'CHECK_CONSTRAINTS']) . ' CC'
. ' ON ' . $p->quoteIdentifierChain(['TC', 'CONSTRAINT_SCHEMA'])
. ' = ' . $p->quoteIdentifierChain(['CC', 'CONSTRAINT_SCHEMA'])
. ' AND ' . $p->quoteIdentifierChain(['TC', 'CONSTRAINT_NAME'])
. ' = ' . $p->quoteIdentifierChain(['CC', 'CONSTRAINT_NAME'])
. ' LEFT JOIN ' . $p->quoteIdentifierChain(['INFORMATION_SCHEMA', 'REFERENTIAL_CONSTRAINTS']) . ' RC'
. ' ON ' . $p->quoteIdentifierChain(['TC', 'CONSTRAINT_SCHEMA'])
. ' = ' . $p->quoteIdentifierChain(['RC', 'CONSTRAINT_SCHEMA'])
. ' AND ' . $p->quoteIdentifierChain(['TC', 'CONSTRAINT_NAME'])
. ' = ' . $p->quoteIdentifierChain(['RC', 'CONSTRAINT_NAME'])
. ' LEFT JOIN ' . $p->quoteIdentifierChain(['INFORMATION_SCHEMA', 'KEY_COLUMN_USAGE']) . ' KCU2'
. ' ON ' . $p->quoteIdentifierChain(['RC', 'UNIQUE_CONSTRAINT_SCHEMA'])
. ' = ' . $p->quoteIdentifierChain(['KCU2', 'CONSTRAINT_SCHEMA'])
. ' AND ' . $p->quoteIdentifierChain(['RC', 'UNIQUE_CONSTRAINT_NAME'])
. ' = ' . $p->quoteIdentifierChain(['KCU2', 'CONSTRAINT_NAME'])
. ' AND ' . $p->quoteIdentifierChain(['KCU', 'ORDINAL_POSITION'])
. ' = ' . $p->quoteIdentifierChain(['KCU2', 'ORDINAL_POSITION'])
. ' WHERE ' . $p->quoteIdentifierChain(['T', 'TABLE_NAME'])
. ' = ' . $p->quoteTrustedValue($table)
. ' AND ' . $p->quoteIdentifierChain(['T', 'TABLE_TYPE'])
. ' IN (\'BASE TABLE\', \'VIEW\')';
if ($schema != self::DEFAULT_SCHEMA) {
$sql .= ' AND ' . $p->quoteIdentifierChain(['T', 'TABLE_SCHEMA'])
. ' = ' . $p->quoteTrustedValue($schema);
} else {
$sql .= ' AND ' . $p->quoteIdentifierChain(['T', 'TABLE_SCHEMA'])
. ' != \'INFORMATION_SCHEMA\'';
}
$sql .= ' ORDER BY CASE ' . $p->quoteIdentifierChain(['TC', 'CONSTRAINT_TYPE'])
. " WHEN 'PRIMARY KEY' THEN 1"
. " WHEN 'UNIQUE' THEN 2"
. " WHEN 'FOREIGN KEY' THEN 3"
. " WHEN 'CHECK' THEN 4"
. " ELSE 5 END"
. ', ' . $p->quoteIdentifierChain(['TC', 'CONSTRAINT_NAME'])
. ', ' . $p->quoteIdentifierChain(['KCU', 'ORDINAL_POSITION']);
$results = $this->adapter->query($sql, Adapter::QUERY_MODE_EXECUTE);
$name = null;
$constraints = [];
$isFK = false;
foreach ($results->toArray() as $row) {
if ($row['CONSTRAINT_NAME'] !== $name) {
$name = $row['CONSTRAINT_NAME'];
$constraints[$name] = [
'constraint_name' => $name,
'constraint_type' => $row['CONSTRAINT_TYPE'],
'table_name' => $row['TABLE_NAME'],
];
if ('CHECK' == $row['CONSTRAINT_TYPE']) {
$constraints[$name]['check_clause'] = $row['CHECK_CLAUSE'];
continue;
}
$constraints[$name]['columns'] = [];
$isFK = ('FOREIGN KEY' == $row['CONSTRAINT_TYPE']);
if ($isFK) {
$constraints[$name]['referenced_table_schema'] = $row['REFERENCED_TABLE_SCHEMA'];
$constraints[$name]['referenced_table_name'] = $row['REFERENCED_TABLE_NAME'];
$constraints[$name]['referenced_columns'] = [];
$constraints[$name]['match_option'] = $row['MATCH_OPTION'];
$constraints[$name]['update_rule'] = $row['UPDATE_RULE'];
$constraints[$name]['delete_rule'] = $row['DELETE_RULE'];
}
}
$constraints[$name]['columns'][] = $row['COLUMN_NAME'];
if ($isFK) {
$constraints[$name]['referenced_columns'][] = $row['REFERENCED_COLUMN_NAME'];
}
}
$this->data['constraints'][$schema][$table] = $constraints;
}
protected function loadTriggerData($schema)
{
if (isset($this->data['triggers'][$schema])) {
return;
}
$this->prepareDataHierarchy('triggers', $schema);
$p = $this->adapter->getPlatform();
$isColumns = [
'TRIGGER_NAME',
'EVENT_MANIPULATION',
'EVENT_OBJECT_CATALOG',
'EVENT_OBJECT_SCHEMA',
'EVENT_OBJECT_TABLE',
'ACTION_ORDER',
'ACTION_CONDITION',
'ACTION_STATEMENT',
'ACTION_ORIENTATION',
'ACTION_TIMING',
'ACTION_REFERENCE_OLD_TABLE',
'ACTION_REFERENCE_NEW_TABLE',
'ACTION_REFERENCE_OLD_ROW',
'ACTION_REFERENCE_NEW_ROW',
'CREATED',
];
array_walk($isColumns, function (&$c) use ($p) {
$c = $p->quoteIdentifier($c);
});
$sql = 'SELECT ' . implode(', ', $isColumns)
. ' FROM ' . $p->quoteIdentifierChain(['INFORMATION_SCHEMA', 'TRIGGERS'])
. ' WHERE ';
if ($schema != self::DEFAULT_SCHEMA) {
$sql .= $p->quoteIdentifier('TRIGGER_SCHEMA')
. ' = ' . $p->quoteTrustedValue($schema);
} else {
$sql .= $p->quoteIdentifier('TRIGGER_SCHEMA')
. ' != \'INFORMATION_SCHEMA\'';
}
$results = $this->adapter->query($sql, Adapter::QUERY_MODE_EXECUTE);
$data = [];
foreach ($results->toArray() as $row) {
$row = array_change_key_case($row, CASE_LOWER);
if (null !== $row['created']) {
$row['created'] = new \DateTime($row['created']);
}
$data[$row['trigger_name']] = $row;
}
$this->data['triggers'][$schema] = $data;
}
}
zend-db-release-2.8.1/src/Metadata/Source/SqliteMetadata.php 0000664 0000000 0000000 00000031644 12703724304 0023657 0 ustar 00root root 0000000 0000000 data['schemas'])) {
return;
}
$this->prepareDataHierarchy('schemas');
$results = $this->fetchPragma('database_list');
foreach ($results as $row) {
$schemas[] = $row['name'];
}
$this->data['schemas'] = $schemas;
}
protected function loadTableNameData($schema)
{
if (isset($this->data['table_names'][$schema])) {
return;
}
$this->prepareDataHierarchy('table_names', $schema);
// FEATURE: Filename?
$p = $this->adapter->getPlatform();
$sql = 'SELECT "name", "type", "sql" FROM ' . $p->quoteIdentifierChain([$schema, 'sqlite_master'])
. ' WHERE "type" IN (\'table\',\'view\') AND "name" NOT LIKE \'sqlite_%\'';
$results = $this->adapter->query($sql, Adapter::QUERY_MODE_EXECUTE);
$tables = [];
foreach ($results->toArray() as $row) {
if ('table' == $row['type']) {
$table = [
'table_type' => 'BASE TABLE',
'view_definition' => null, // VIEW only
'check_option' => null, // VIEW only
'is_updatable' => null, // VIEW only
];
} else {
$table = [
'table_type' => 'VIEW',
'view_definition' => null,
'check_option' => 'NONE',
'is_updatable' => false,
];
// Parse out extra data
if (null !== ($data = $this->parseView($row['sql']))) {
$table = array_merge($table, $data);
}
}
$tables[$row['name']] = $table;
}
$this->data['table_names'][$schema] = $tables;
}
protected function loadColumnData($table, $schema)
{
if (isset($this->data['columns'][$schema][$table])) {
return;
}
$this->prepareDataHierarchy('columns', $schema, $table);
$this->prepareDataHierarchy('sqlite_columns', $schema, $table);
$results = $this->fetchPragma('table_info', $table, $schema);
$columns = [];
foreach ($results as $row) {
$columns[$row['name']] = [
// cid appears to be zero-based, ordinal position needs to be one-based
'ordinal_position' => $row['cid'] + 1,
'column_default' => $row['dflt_value'],
'is_nullable' => !((bool) $row['notnull']),
'data_type' => $row['type'],
'character_maximum_length' => null,
'character_octet_length' => null,
'numeric_precision' => null,
'numeric_scale' => null,
'numeric_unsigned' => null,
'erratas' => [],
];
// TODO: populate character_ and numeric_values with correct info
}
$this->data['columns'][$schema][$table] = $columns;
$this->data['sqlite_columns'][$schema][$table] = $results;
}
protected function loadConstraintData($table, $schema)
{
if (isset($this->data['constraints'][$schema][$table])) {
return;
}
$this->prepareDataHierarchy('constraints', $schema, $table);
$this->loadColumnData($table, $schema);
$primaryKey = [];
foreach ($this->data['sqlite_columns'][$schema][$table] as $col) {
if ((bool) $col['pk']) {
$primaryKey[] = $col['name'];
}
}
if (empty($primaryKey)) {
$primaryKey = null;
}
$constraints = [];
$indexes = $this->fetchPragma('index_list', $table, $schema);
foreach ($indexes as $index) {
if (!((bool) $index['unique'])) {
continue;
}
$constraint = [
'constraint_name' => $index['name'],
'constraint_type' => 'UNIQUE',
'table_name' => $table,
'columns' => [],
];
$info = $this->fetchPragma('index_info', $index['name'], $schema);
foreach ($info as $column) {
$constraint['columns'][] = $column['name'];
}
if ($primaryKey === $constraint['columns']) {
$constraint['constraint_type'] = 'PRIMARY KEY';
$primaryKey = null;
}
$constraints[$constraint['constraint_name']] = $constraint;
}
if (null !== $primaryKey) {
$constraintName = '_zf_' . $table . '_PRIMARY';
$constraints[$constraintName] = [
'constraint_name' => $constraintName,
'constraint_type' => 'PRIMARY KEY',
'table_name' => $table,
'columns' => $primaryKey,
];
}
$foreignKeys = $this->fetchPragma('foreign_key_list', $table, $schema);
$id = $name = null;
foreach ($foreignKeys as $fk) {
if ($id !== $fk['id']) {
$id = $fk['id'];
$name = '_zf_' . $table . '_FOREIGN_KEY_' . ($id + 1);
$constraints[$name] = [
'constraint_name' => $name,
'constraint_type' => 'FOREIGN KEY',
'table_name' => $table,
'columns' => [],
'referenced_table_schema' => $schema,
'referenced_table_name' => $fk['table'],
'referenced_columns' => [],
// TODO: Verify match, on_update, and on_delete values conform to SQL Standard
'match_option' => strtoupper($fk['match']),
'update_rule' => strtoupper($fk['on_update']),
'delete_rule' => strtoupper($fk['on_delete']),
];
}
$constraints[$name]['columns'][] = $fk['from'];
$constraints[$name]['referenced_columns'][] = $fk['to'];
}
$this->data['constraints'][$schema][$table] = $constraints;
}
protected function loadTriggerData($schema)
{
if (isset($this->data['triggers'][$schema])) {
return;
}
$this->prepareDataHierarchy('triggers', $schema);
$p = $this->adapter->getPlatform();
$sql = 'SELECT "name", "tbl_name", "sql" FROM '
. $p->quoteIdentifierChain([$schema, 'sqlite_master'])
. ' WHERE "type" = \'trigger\'';
$results = $this->adapter->query($sql, Adapter::QUERY_MODE_EXECUTE);
$triggers = [];
foreach ($results->toArray() as $row) {
$trigger = [
'trigger_name' => $row['name'],
'event_manipulation' => null, // in $row['sql']
'event_object_catalog' => null,
'event_object_schema' => $schema,
'event_object_table' => $row['tbl_name'],
'action_order' => 0,
'action_condition' => null, // in $row['sql']
'action_statement' => null, // in $row['sql']
'action_orientation' => 'ROW',
'action_timing' => null, // in $row['sql']
'action_reference_old_table' => null,
'action_reference_new_table' => null,
'action_reference_old_row' => 'OLD',
'action_reference_new_row' => 'NEW',
'created' => null,
];
// Parse out extra data
if (null !== ($data = $this->parseTrigger($row['sql']))) {
$trigger = array_merge($trigger, $data);
}
$triggers[$trigger['trigger_name']] = $trigger;
}
$this->data['triggers'][$schema] = $triggers;
}
protected function fetchPragma($name, $value = null, $schema = null)
{
$p = $this->adapter->getPlatform();
$sql = 'PRAGMA ';
if (null !== $schema) {
$sql .= $p->quoteIdentifier($schema) . '.';
}
$sql .= $name;
if (null !== $value) {
$sql .= '(' . $p->quoteTrustedValue($value) . ')';
}
$results = $this->adapter->query($sql, Adapter::QUERY_MODE_EXECUTE);
if ($results instanceof ResultSetInterface) {
return $results->toArray();
}
return [];
}
protected function parseView($sql)
{
static $re = null;
if (null === $re) {
$identifierChain = $this->getIdentifierChainRegularExpression();
$re = $this->buildRegularExpression([
'CREATE',
['TEMP|TEMPORARY'],
'VIEW',
['IF', 'NOT', 'EXISTS'],
$identifierChain,
'AS',
'(?