Reindent code and apply to PSR-2 standards

Also make code more readable in some ways. :)
This commit is contained in:
Lucas Mezêncio 2016-08-19 13:06:06 -03:00
parent e8f17c13a7
commit b19daaa67c
9 changed files with 491 additions and 374 deletions

View File

@ -1,72 +1,86 @@
<?php
namespace Cooperl\Database\DB2\Connectors;
use Illuminate\Database\Connectors\Connector;
use Illuminate\Database\Connectors\ConnectorInterface;
use PDO;
/**
* Class IBMConnector
*
* @package Cooperl\Database\DB2\Connectors
*/
class IBMConnector extends Connector implements ConnectorInterface
{
/**
* @param array $config
*
* @return \PDO
*/
public function connect(array $config)
{
$dsn = $this->getDsn($config);
$options = [
PDO::I5_ATTR_DBC_SYS_NAMING => false,
PDO::I5_ATTR_COMMIT => PDO::I5_TXN_NO_COMMIT,
PDO::I5_ATTR_JOB_SORT => false
\PDO::I5_ATTR_DBC_SYS_NAMING => false,
\PDO::I5_ATTR_COMMIT => \PDO::I5_TXN_NO_COMMIT,
\PDO::I5_ATTR_JOB_SORT => false,
];
// Naming mode
switch ($config['naming']) {
case 1:
$options[PDO::I5_ATTR_DBC_SYS_NAMING] = true;
$options[\PDO::I5_ATTR_DBC_SYS_NAMING] = true;
break;
case 0:
default:
$options[PDO::I5_ATTR_DBC_SYS_NAMING] = false;
$options[\PDO::I5_ATTR_DBC_SYS_NAMING] = false;
break;
}
// Isolation mode
switch ($config['commitMode']) {
case 1:
$options[PDO::I5_ATTR_COMMIT] = PDO::I5_TXN_READ_COMMITTED;
$options[\PDO::I5_ATTR_COMMIT] = \PDO::I5_TXN_READ_COMMITTED;
break;
case 2:
$options[PDO::I5_ATTR_COMMIT] = PDO::I5_TXN_READ_UNCOMMITTED;
$options[\PDO::I5_ATTR_COMMIT] = \PDO::I5_TXN_READ_UNCOMMITTED;
break;
case 3:
$options[PDO::I5_ATTR_COMMIT] = PDO::I5_TXN_REPEATABLE_READ;
$options[\PDO::I5_ATTR_COMMIT] = \PDO::I5_TXN_REPEATABLE_READ;
break;
case 4:
$options[PDO::I5_ATTR_COMMIT] = PDO::I5_TXN_SERIALIZABLE;
$options[\PDO::I5_ATTR_COMMIT] = \PDO::I5_TXN_SERIALIZABLE;
break;
case 0:
default:
$options[PDO::I5_ATTR_COMMIT] = PDO::I5_TXN_NO_COMMIT;
break;
}
// Job sort mode
switch ($config['jobSort']) {
case 1:
$options[PDO::I5_ATTR_DBC_SYS_NAMING] = true;
$options[\PDO::I5_ATTR_DBC_SYS_NAMING] = true;
break;
case 0:
default:
$options[PDO::I5_ATTR_DBC_SYS_NAMING] = false;
$options[\PDO::I5_ATTR_DBC_SYS_NAMING] = false;
break;
}
$options = $this->getOptions($config) + $options;
$connection = $this->createConnection($dsn, $config, $options);
if (isset($config['schema']))
{
if (isset($config['schema'])) {
$schema = $config['schema'];
$connection->prepare("set schema $schema")->execute();
@ -75,10 +89,15 @@ class IBMConnector extends Connector implements ConnectorInterface
return $connection;
}
protected function getDsn(array $config) {
extract($config);
$dsn = "ibm:$database";
/**
* @param array $config
*
* @return string
*/
protected function getDsn(array $config)
{
$dsn = "ibm:{$config['database']}";
return $dsn;
}
}

View File

@ -1,99 +1,86 @@
<?php
namespace Cooperl\Database\DB2\Connectors;
use Illuminate\Database\Connectors\Connector;
use Illuminate\Database\Connectors\ConnectorInterface;
/**
* Class ODBCConnector
*
* @package Cooperl\Database\DB2\Connectors
*/
class ODBCConnector extends Connector implements ConnectorInterface
{
/**
* @param array $config
*
* @return \PDO
*/
public function connect(array $config)
{
$dsn = $this->getDsn($config);
$options = $this->getOptions($config);
$connection = $this->createConnection($dsn, $config, $options);
if (isset($config['schema']))
{
if (isset($config['schema'])) {
$schema = $config['schema'];
$connection->prepare("set schema $schema")->execute();
$connection->prepare('set schema '.$schema)->execute();
}
return $connection;
}
protected function getDsn(array $config) {
extract($config);
/**
* @param array $config
*
* @return string
*/
protected function getDsn(array $config)
{
$dsnParts = [
'odbc:DRIVER=%s', 'SYSTEM=%s', 'UserID=%s', 'Password=%s', 'DATABASE=%s', 'SIGNON=%s', 'SSL=%s',
'CommitMode=%s', 'ConnectionType=%s', 'DefaultLibraries=%s', 'Naming=%s', 'UNICODESQL=%s', 'DateFormat=%s',
'DateSeperator=%s', 'Decimal=%s', 'TimeFormat=%s', 'TimeSeparator=%s', 'BLOCKFETCH=%s', 'BlockSizeKB=%s',
'AllowDataCompression=%s', 'CONCURRENCY=%s', 'LAZYCLOSE=%s', 'MaxFieldLength=%s', 'PREFETCH=%s',
'QUERYTIMEOUT=%s', 'DefaultPkgLibrary=%s', 'DefaultPackage=%s', 'ExtendedDynamic=%s', 'QAQQINILibrary=%s',
'SQDIAGCODE=%s', 'LANGUAGEID=%s', 'SORTTABLE=%s', 'SortSequence=%s', 'SORTWEIGHT=%s',
'AllowUnsupportedChar=%s', 'CCSID=%s', 'GRAPHIC=%s', 'ForceTranslation=%s', 'ALLOWPROCCALLS=%s',
'DB2SQLSTATES=%s', 'DEBUG=%s', 'TRUEAUTOCOMMIT=%s', 'CATALOGOPTIONS=%s', 'LibraryView=%s', 'ODBCRemarks=%s',
'SEARCHPATTERN=%s', 'TranslationDLL=%s', 'TranslationOption=%s', 'MAXTRACESIZE=%s', 'MultipleTraceFiles=%s',
'TRACE=%s', 'TRACEFILENAME=%s', 'ExtendedColInfo=%s',
'', // Just to add a semicolon to the end of string
];
$dsn = "odbc:"
$dsnConfig = [
// General settings
. "DRIVER=$driverName;"
. "SYSTEM=$host;"
. "UserID=$username;"
. "Password=$password;"
$config['driverName'], $config['host'], $config['username'], $config['password'],
//Server settings
. "DATABASE=$database;"
. "SIGNON=$signon;"
. "SSL=$ssl;"
. "CommitMode=$commitMode;"
. "ConnectionType=$connectionType;"
. "DefaultLibraries=$defaultLibraries;"
. "Naming=$naming;"
. "UNICODESQL=$unicodeSql;"
$config['database'], $config['signon'], $config['ssl'], $config['commitMode'], $config['connectionType'],
$config['defaultLibraries'], $config['naming'], $config['unicodeSql'],
// Format settings
. "DateFormat=$dateFormat;"
. "DateSeperator=$dateSeperator;"
. "Decimal=$decimal;"
. "TimeFormat=$timeFormat;"
. "TimeSeparator=$timeSeparator;"
$config['dateFormat'], $config['dateSeperator'], $config['decimal'], $config['timeFormat'],
$config['timeSeparator'],
// Performances settings
. "BLOCKFETCH=$blockFetch;"
. "BlockSizeKB=$blockSizeKB;"
. "AllowDataCompression=$allowDataCompression;"
. "CONCURRENCY=$concurrency;"
. "LAZYCLOSE=$lazyClose;"
. "MaxFieldLength=$maxFieldLength;"
. "PREFETCH=$prefetch;"
. "QUERYTIMEOUT=$queryTimeout;"
$config['blockFetch'], $config['blockSizeKB'], $config['allowDataCompression'], $config['concurrency'],
$config['lazyClose'], $config['maxFieldLength'], $config['prefetch'], $config['queryTimeout'],
// Modules settings
. "DefaultPkgLibrary=$defaultPkgLibrary;"
. "DefaultPackage=$defaultPackage;"
. "ExtendedDynamic=$extendedDynamic;"
$config['defaultPkgLibrary'], $config['defaultPackage'], $config['extendedDynamic'],
// Diagnostic settings
. "QAQQINILibrary=$QAQQINILibrary;"
. "SQDIAGCODE=$sqDiagCode;"
$config['QAQQINILibrary'], $config['sqDiagCode'],
// Sort settings
. "LANGUAGEID=$languageId;"
. "SORTTABLE=$sortTable;"
. "SortSequence=$sortSequence;"
. "SORTWEIGHT=$sortWeight;"
$config['languageId'], $config['sortTable'], $config['sortSequence'], $config['sortWeight'],
// Conversion settings
. "AllowUnsupportedChar=$allowUnsupportedChar;"
. "CCSID=$ccsid;"
. "GRAPHIC=$graphic;"
. "ForceTranslation=$forceTranslation;"
$config['allowUnsupportedChar'], $config['ccsid'], $config['graphic'], $config['forceTranslation'],
// Other settings
. "ALLOWPROCCALLS=$allowProcCalls;"
. "DB2SQLSTATES=$DB2SqlStates;"
. "DEBUG=$debug;"
. "TRUEAUTOCOMMIT=$trueAutoCommit;"
. "CATALOGOPTIONS=$catalogOptions;"
. "LibraryView=$libraryView;"
. "ODBCRemarks=$ODBCRemarks;"
. "SEARCHPATTERN=$searchPattern;"
. "TranslationDLL=$translationDLL;"
. "TranslationOption=$translationOption;"
. "MAXTRACESIZE=$maxTraceSize;"
. "MultipleTraceFiles=$multipleTraceFiles;"
. "TRACE=$trace;"
. "TRACEFILENAME=$traceFilename;"
. "ExtendedColInfo=$extendedColInfo;"
;
$config['allowProcCalls'], $config['DB2SqlStates'], $config['debug'], $config['trueAutoCommit'],
$config['catalogOptions'], $config['libraryView'], $config['ODBCRemarks'], $config['searchPattern'],
$config['translationDLL'], $config['translationOption'], $config['maxTraceSize'],
$config['multipleTraceFiles'], $config['trace'], $config['traceFilename'], $config['extendedColInfo'],
];
return $dsn;
return sprintf(implode(';', $dsnParts), ...$dsnConfig);
}
}

View File

@ -1,4 +1,5 @@
<?php
namespace Cooperl\Database\DB2;
use PDO;
@ -10,9 +11,13 @@ use Cooperl\Database\DB2\Query\Processors\DB2Processor;
use Cooperl\Database\DB2\Query\Grammars\DB2Grammar as QueryGrammar;
use Cooperl\Database\DB2\Schema\Grammars\DB2Grammar as SchemaGrammar;
/**
* Class DB2Connection
*
* @package Cooperl\Database\DB2
*/
class DB2Connection extends Connection
{
/**
* The name of the default schema.
*
@ -20,6 +25,13 @@ class DB2Connection extends Connection
*/
protected $defaultSchema;
/**
* The name of the current schema in use.
*
* @var string
*/
protected $currentSchema;
public function __construct(PDO $pdo, $database = '', $tablePrefix = '', array $config = [])
{
parent::__construct($pdo, $database, $tablePrefix, $config);
@ -49,6 +61,8 @@ class DB2Connection extends Connection
/**
* Set the name of the current schema.
*
* @param $schema
*
* @return string
*/
public function setCurrentSchema($schema)
@ -64,27 +78,29 @@ class DB2Connection extends Connection
*/
public function getSchemaBuilder()
{
if (is_null($this->schemaGrammar)) { $this->useDefaultSchemaGrammar(); }
if (is_null($this->schemaGrammar)) {
$this->useDefaultSchemaGrammar();
}
return new Builder($this);
}
/**
* @return Query\Grammars\Grammar
* @return \Illuminate\Database\Grammar
*/
protected function getDefaultQueryGrammar()
{
return $this->withTablePrefix(new QueryGrammar);
return $this->withTablePrefix(new QueryGrammar());
}
/**
* Default grammar for specified Schema
* @return Schema\Grammars\Grammar
*
* @return \Illuminate\Database\Grammar
*/
protected function getDefaultSchemaGrammar()
{
return $this->withTablePrefix(new SchemaGrammar);
return $this->withTablePrefix(new SchemaGrammar());
}
/**
@ -94,7 +110,6 @@ class DB2Connection extends Connection
*/
protected function getDefaultPostProcessor()
{
return new DB2Processor;
return new DB2Processor();
}
}

View File

@ -1,15 +1,19 @@
<?php
namespace Cooperl\Database\DB2;
use Cooperl\Database\DB2\Connectors\ODBCConnector;
use Cooperl\Database\DB2\Connectors\IBMConnector;
use Illuminate\Support\ServiceProvider;
use Illuminate\Foundation\AliasLoader;
use Config;
class DB2ServiceProvider extends ServiceProvider {
/**
* Class DB2ServiceProvider
*
* @package Cooperl\Database\DB2
*/
class DB2ServiceProvider extends ServiceProvider
{
/**
* Indicates if loading of the provider is deferred.
*
@ -33,42 +37,43 @@ class DB2ServiceProvider extends ServiceProvider {
*/
public function register()
{
// get the configs
$conns = is_array(Config::get('laravel-db2::database.connections')) ? Config::get('laravel-db2::database.connections') : [];
$conns = is_array(Config::get('laravel-db2::database.connections'))
? Config::get('laravel-db2::database.connections')
: [];
// Add my database configurations to the default set of configurations
$this->app['config']['database.connections'] = array_merge($conns, $this->app['config']['database.connections']);
$this->app['config']['database.connections'] = array_merge(
$conns,
$this->app['config']['database.connections']
);
//Extend the connections with pdo_odbc and pdo_ibm drivers
foreach(Config::get('database.connections') as $conn => $config)
{
//Only use configurations that feature a "odbc" or "ibm" driver
if(!isset($config['driver']) || !in_array($config['driver'], ['odbc', 'ibm']) )
{
// Extend the connections with pdo_odbc and pdo_ibm drivers
foreach (Config::get('database.connections') as $conn => $config) {
// Only use configurations that feature a "odbc" or "ibm" driver
if (!isset($config['driver']) || !in_array($config['driver'], ['odbc', 'ibm'])) {
continue;
}
//Create a connector
$this->app['db']->extend($conn, function($config)
{
// Create a connector
$this->app['db']->extend($conn, function ($config) {
switch ($config['driver']) {
case 'odbc':
$connector = new ODBCConnector();
break;
case 'ibm':
$connector = new IBMConnector();
break;
default:
$connector = new IBMConnector();
break;
}
$db2Connection = $connector->connect($config);
return new DB2Connection($db2Connection, $config["database"], $config["prefix"], $config);
});
}
}
/**
@ -80,5 +85,4 @@ class DB2ServiceProvider extends ServiceProvider {
{
return [];
}
}

View File

@ -1,21 +1,29 @@
<?php
namespace Cooperl\Database\DB2\Query\Grammars;
use Illuminate\Database\Query\Grammars\Grammar;
use Illuminate\Database\Query\Builder;
/**
* Class DB2Grammar
*
* @package Cooperl\Database\DB2\Query\Grammars
*/
class DB2Grammar extends Grammar
{
/**
* Wrap a single string in keyword identifiers.
*
* @param string $value
*
* @return string
*/
protected function wrapValue($value)
{
if ($value === '*') return $value;
if ($value === '*') {
return $value;
}
return str_replace('"', '""', $value);
}
@ -23,8 +31,9 @@ class DB2Grammar extends Grammar
/**
* Compile the "limit" portions of the query.
*
* @param Illuminate\Database\Query\Builder $query
* @param \Illuminate\Database\Query\Builder $query
* @param int $limit
*
* @return string
*/
protected function compileLimit(Builder $query, $limit)
@ -35,7 +44,8 @@ class DB2Grammar extends Grammar
/**
* Compile a select query into SQL.
*
* @param Illuminate\Database\Query\Builder
* @param \Illuminate\Database\Query\Builder $query
*
* @return string
*/
public function compileSelect(Builder $query)
@ -45,8 +55,7 @@ class DB2Grammar extends Grammar
// If an offset is present on the query, we will need to wrap the query in
// a big "ANSI" offset syntax block. This is very nasty compared to the
// other database systems but is necessary for implementing features.
if ($query->offset > 0)
{
if ($query->offset > 0) {
return $this->compileAnsiOffset($query, $components);
}
@ -56,8 +65,9 @@ class DB2Grammar extends Grammar
/**
* Create a full ANSI offset clause for the query.
*
* @param Illuminate\Database\Query\Builder $query
* @param \Illuminate\Database\Query\Builder $query
* @param array $components
*
* @return string
*/
protected function compileAnsiOffset(Builder $query, $components)
@ -65,8 +75,7 @@ class DB2Grammar extends Grammar
// An ORDER BY clause is required to make this offset query work, so if one does
// not exist we'll just create a dummy clause to trick the database and so it
// does not complain about the queries for not having an "order by" clause.
if ( ! isset($components['orders']))
{
if (!isset($components['orders'])) {
$components['orders'] = 'order by 1';
}
@ -77,7 +86,7 @@ class DB2Grammar extends Grammar
// the "select" that will give back the row numbers on each of the records.
$orderings = $components['orders'];
$columns = (!empty($components['columns']) ? $components['columns'] . ', ': 'select');
$columns = (!empty($components['columns']) ? $components['columns'].', ' : 'select');
$components['columns'] = $this->compileOver($orderings, $columns);
@ -102,6 +111,8 @@ class DB2Grammar extends Grammar
* Compile the over statement for a table expression.
*
* @param string $orderings
* @param $columns
*
* @return string
*/
protected function compileOver($orderings, $columns)
@ -109,12 +120,16 @@ class DB2Grammar extends Grammar
return "{$columns} row_number() over ({$orderings}) as row_num";
}
/**
* @param $query
*
* @return string
*/
protected function compileRowConstraint($query)
{
$start = $query->offset + 1;
if ($query->limit > 0)
{
if ($query->limit > 0) {
$finish = $query->offset + $query->limit;
return "between {$start} and {$finish}";
@ -128,6 +143,7 @@ class DB2Grammar extends Grammar
*
* @param string $sql
* @param string $constraint
*
* @return string
*/
protected function compileTableExpression($sql, $constraint)
@ -138,8 +154,9 @@ class DB2Grammar extends Grammar
/**
* Compile the "offset" portions of the query.
*
* @param Illuminate\Database\Query\Builder $query
* @param \Illuminate\Database\Query\Builder $query
* @param int $offset
*
* @return string
*/
protected function compileOffset(Builder $query, $offset)
@ -156,5 +173,4 @@ class DB2Grammar extends Grammar
{
return 'Y-m-d H:i:s.u';
}
}

View File

@ -1,17 +1,24 @@
<?php
namespace Cooperl\Database\DB2\Query\Processors;
use Illuminate\Database\Query\Builder;
use Illuminate\Database\Query\Processors\Processor;
use Cooperl\Database\DB2\Query\Grammars\DB2Grammar;
class DB2Processor extends Processor {
/**
* Class DB2Processor
*
* @package Cooperl\Database\DB2\Query\Processors
*/
class DB2Processor extends Processor
{
/**
* Process the results of a "select" query.
*
* @param \Illuminate\Database\Query\Builder $query
* @param array $results
*
* @return array
*/
/*public function processSelect(Builder $query, $results)
@ -37,30 +44,29 @@ class DB2Processor extends Processor {
* @param string $sql
* @param array $values
* @param string $sequence
*
* @return int/array
*/
public function processInsertGetId(Builder $query, $sql, $values, $sequence = null)
{
$sequenceStr = $sequence ?: 'id';
if (is_array($sequence))
{
$grammar = new DB2Grammar;
if (is_array($sequence)) {
$grammar = new DB2Grammar();
$sequenceStr = $grammar->columnize($sequence);
}
$sql = 'select ' . $sequenceStr . ' from new table (' . $sql;
$sql = 'select '.$sequenceStr.' from new table ('.$sql;
$sql .= ')';
$results = $query->getConnection()->select($sql, $values);
if (is_array($sequence))
{
if (is_array($sequence)) {
return array_values((array) $results[0]);
}
else
{
} else {
$result = (array) $results[0];
$id = $result[$sequenceStr];
return is_numeric($id) ? (int) $id : $id;
}
}
}

View File

@ -1,8 +1,14 @@
<?php
namespace Cooperl\Database\DB2\Schema;
class Blueprint extends \Illuminate\Database\Schema\Blueprint {
/**
* Class Blueprint
*
* @package Cooperl\Database\DB2\Schema
*/
class Blueprint extends \Illuminate\Database\Schema\Blueprint
{
/**
* Specify a system name for the table.
*
@ -17,6 +23,7 @@ class Blueprint extends \Illuminate\Database\Schema\Blueprint {
* Specify a label for the table.
*
* @param string $label
*
* @return \Illuminate\Support\Fluent
*/
public function label($label)
@ -30,6 +37,7 @@ class Blueprint extends \Illuminate\Database\Schema\Blueprint {
* @param string $type
* @param string|array $columns
* @param string $index
*
* @return \Illuminate\Support\Fluent
*/
protected function indexCommand($type, $columns, $index)
@ -39,14 +47,14 @@ class Blueprint extends \Illuminate\Database\Schema\Blueprint {
switch ($type) {
case 'index':
$indexSystem = false;
if (!is_null($index))
{
if (!is_null($index)) {
$indexSystem = $index;
}
$index = $this->createIndexName($type, $columns);
return $this->addCommand($type, compact('index', 'indexSystem', 'columns'));
break;
$index = $this->createIndexName($type, $columns);
return $this->addCommand($type, compact('index', 'indexSystem', 'columns'));
default:
break;
}
@ -54,8 +62,7 @@ class Blueprint extends \Illuminate\Database\Schema\Blueprint {
// If no name was specified for this index, we will create one using a basic
// convention of the table name, followed by the columns, followed by an
// index type, such as primary or index, which makes the index unique.
if (is_null($index))
{
if (is_null($index)) {
$index = $this->createIndexName($type, $columns);
}
@ -66,6 +73,7 @@ class Blueprint extends \Illuminate\Database\Schema\Blueprint {
* Create a new boolean column on the table.
*
* @param string $column
*
* @return \Illuminate\Support\Fluent
*/
public function boolean($column)
@ -73,10 +81,11 @@ class Blueprint extends \Illuminate\Database\Schema\Blueprint {
$prefix = $this->table;
// Aucune utilité d'avoir le nom du schéma dans le préfixe de la contrainte check pour le type booléen
$schemaTable = explode(".", $this->table);
if (count($schemaTable) > 1)
{
if (count($schemaTable) > 1) {
$prefix = $schemaTable[1];
}
return $this->addColumn('boolean', $column, ['prefix' => $prefix]);
}
@ -86,11 +95,11 @@ class Blueprint extends \Illuminate\Database\Schema\Blueprint {
* @param string $column
* @param int $total
* @param int $places
*
* @return \Illuminate\Support\Fluent
*/
public function numeric($column, $total = 8, $places = 2)
{
return $this->addColumn('numeric', $column, compact('total', 'places'));
}
}

View File

@ -1,29 +1,34 @@
<?php
namespace Cooperl\Database\DB2\Schema;
use Closure;
use Illuminate\Database\Schema\Blueprint;
class Builder extends \Illuminate\Database\Schema\Builder {
/**
* Class Builder
*
* @package Cooperl\Database\DB2\Schema
*/
class Builder extends \Illuminate\Database\Schema\Builder
{
/**
* Determine if the given table exists.
*
* @param string $table
*
* @return bool
*/
public function hasTable($table)
{
$sql = $this->grammar->compileTableExists();
$schemaTable = explode(".", $table);
if (count($schemaTable) > 1)
{
if (count($schemaTable) > 1) {
$schema = $schemaTable[0];
$table = $this->connection->getTablePrefix().$schemaTable[1];
}
else
{
} else {
$schema = $this->connection->getDefaultSchema();
$table = $this->connection->getTablePrefix().$table;
}
@ -35,16 +40,14 @@ class Builder extends \Illuminate\Database\Schema\Builder {
* Get the column listing for a given table.
*
* @param string $table
*
* @return array
*/
public function getColumnListing($table)
{
$sql = $this->grammar->compileColumnExists();
$database = $this->connection->getDatabaseName();
$table = $this->connection->getTablePrefix().$table;
$results = $this->connection->select($sql, [$database, $table]);
return $this->connection->getPostProcessor()->processColumnListing($results);
@ -53,19 +56,17 @@ class Builder extends \Illuminate\Database\Schema\Builder {
/**
* Execute the blueprint to build / modify the table.
*
* @param \Cooperl\Database\DB2\Schema\Blueprint $blueprint
* @return void
* @param Blueprint $blueprint
*/
protected function build(Blueprint $blueprint)
{
$schemaTable = explode(".", $blueprint->getTable());
if (count($schemaTable) > 1)
{
if (count($schemaTable) > 1) {
$this->connection->setCurrentSchema($schemaTable[0]);
}
$blueprint->build($this->connection, $this->grammar);
$this->connection->resetCurrentSchema();
}
@ -74,16 +75,15 @@ class Builder extends \Illuminate\Database\Schema\Builder {
*
* @param string $table
* @param \Closure $callback
*
* @return \Cooperl\Database\DB2\Schema\Blueprint
*/
protected function createBlueprint($table, Closure $callback = null)
{
if (isset($this->resolver))
{
if (isset($this->resolver)) {
return call_user_func($this->resolver, $table, $callback);
}
return new \Cooperl\Database\DB2\Schema\Blueprint($table, $callback);
}
}

View File

@ -1,14 +1,15 @@
<?php
namespace Cooperl\Database\DB2\Schema\Grammars;
use Illuminate\Database\Query\Expression;
use Illuminate\Support\Fluent;
use Illuminate\Database\Connection;
use Illuminate\Database\Schema\Grammars\Grammar;
use Illuminate\Database\Schema\Blueprint;
class DB2Grammar extends Grammar {
class DB2Grammar extends Grammar
{
/**
* The possible column modifiers.
*
@ -28,11 +29,14 @@ class DB2Grammar extends Grammar {
* Wrap a single string in keyword identifiers.
*
* @param string $value
*
* @return string
*/
protected function wrapValue($value)
{
if ($value === '*') return $value;
if ($value === '*') {
return $value;
}
return str_replace('"', '""', $value);
}
@ -50,12 +54,16 @@ class DB2Grammar extends Grammar {
/**
* Compile the query to determine the list of columns.
*
* @param string $table
* @return string
*/
public function compileColumnExists()
{
return "select column_name from information_schema.columns where table_schema = upper(?) and table_name = upper(?)";
return "
select column_name
from information_schema.columns
where table_schema = upper(?)
and table_name = upper(?)
";
}
@ -65,16 +73,15 @@ class DB2Grammar extends Grammar {
* @param \Illuminate\Database\Schema\Blueprint $blueprint
* @param \Illuminate\Support\Fluent $command
* @param \Illuminate\Database\Connection $connection
*
* @return string
*/
public function compileCreate(Blueprint $blueprint, Fluent $command, Connection $connection)
{
$columns = implode(', ', $this->getColumns($blueprint));
$sql = 'create table '.$this->wrapTable($blueprint);
if (isset($blueprint->systemName))
{
if (isset($blueprint->systemName)) {
$sql .= ' for system name '.$blueprint->systemName;
}
@ -89,25 +96,26 @@ class DB2Grammar extends Grammar {
* @param \Illuminate\Database\Schema\Blueprint $blueprint
* @param \Illuminate\Support\Fluent $command
* @param \Illuminate\Database\Connection $connection
*
* @return string
*/
public function compileLabel(Blueprint $blueprint, Fluent $command, Connection $connection)
{
return 'label on table '.$this->wrapTable($blueprint).' is \'' . $command->label . '\'';
return 'label on table '.$this->wrapTable($blueprint).' is \''.$command->label.'\'';
}
/**
* Compile the blueprint's column definitions.
*
* @param \Illuminate\Database\Schema\Blueprint $blueprint
*
* @return array
*/
protected function getColumns(Blueprint $blueprint)
{
$columns = [];
foreach ($blueprint->getColumns() as $column)
{
foreach ($blueprint->getColumns() as $column) {
// Each of the column types have their own compiler functions which are tasked
// with turning the column definition into its SQL format for this platform
// used by the connection. The column's modifiers are compiled and added.
@ -127,14 +135,13 @@ class DB2Grammar extends Grammar {
* @param string $sql
* @param \Illuminate\Database\Schema\Blueprint $blueprint
* @param \Illuminate\Support\Fluent $column
*
* @return string
*/
protected function addPreModifiers($sql, Blueprint $blueprint, Fluent $column)
{
foreach ($this->preModifiers as $preModifier)
{
if (method_exists($this, $method = "modify{$preModifier}"))
{
foreach ($this->preModifiers as $preModifier) {
if (method_exists($this, $method = "modify{$preModifier}")) {
$sql .= $this->{$method}($blueprint, $column);
}
}
@ -147,16 +154,16 @@ class DB2Grammar extends Grammar {
*
* @param \Illuminate\Database\Schema\Blueprint $blueprint
* @param \Illuminate\Support\Fluent $command
*
* @return string
*/
public function compileAdd(Blueprint $blueprint, Fluent $command)
{
$table = $this->wrapTable($blueprint);
$columns = $this->prefixArray('add', $this->getColumns($blueprint));
$statements = [];
foreach ($columns as $column)
{
foreach ($columns as $column) {
$statements[] = 'alter table '.$table.' '.$column;
}
@ -168,18 +175,18 @@ class DB2Grammar extends Grammar {
*
* @param \Illuminate\Database\Schema\Blueprint $blueprint
* @param \Illuminate\Support\Fluent $command
*
* @return string
*/
public function compilePrimary(Blueprint $blueprint, Fluent $command)
{
$table = $this->wrapTable($blueprint);
$columns = $this->columnize($command->columns);
// Aucune utilité d'avoir le nom du schéma dans le nom de la contrainte Primary
$schemaTable = explode(".", $table);
if (count($schemaTable) > 1)
{
if (count($schemaTable) > 1) {
$command->index = str_replace($schemaTable[0]."_", "", $command->index);
}
@ -191,42 +198,38 @@ class DB2Grammar extends Grammar {
*
* @param \Illuminate\Database\Schema\Blueprint $blueprint
* @param \Illuminate\Support\Fluent $command
*
* @return string
*/
public function compileForeign(Blueprint $blueprint, Fluent $command)
{
$table = $this->wrapTable($blueprint);
$on = $this->wrapTable($command->on);
// We need to prepare several of the elements of the foreign key definition
// before we can create the SQL, such as wrapping the tables and convert
// an array of columns to comma-delimited strings for the SQL queries.
$columns = $this->columnize($command->columns);
$onColumns = $this->columnize((array) $command->references);
// Aucune utilité d'avoir le nom du schéma dans le nom de la contrainte Foreign
$schemaTable = explode(".", $table);
if (count($schemaTable) > 1)
{
if (count($schemaTable) > 1) {
$command->index = str_replace($schemaTable[0]."_", "", $command->index);
}
$sql = "alter table {$table} add constraint {$command->index} ";
$sql .= "foreign key ({$columns}) references {$on} ({$onColumns})";
// Once we have the basic foreign key creation statement constructed we can
// build out the syntax for what should happen on an update or delete of
// the affected columns, which will get something like "cascade", etc.
if ( ! is_null($command->onDelete))
{
if (!is_null($command->onDelete)) {
$sql .= " on delete {$command->onDelete}";
}
if ( ! is_null($command->onUpdate))
{
if (!is_null($command->onUpdate)) {
$sql .= " on update {$command->onUpdate}";
}
@ -238,18 +241,18 @@ class DB2Grammar extends Grammar {
*
* @param \Illuminate\Database\Schema\Blueprint $blueprint
* @param \Illuminate\Support\Fluent $command
*
* @return string
*/
public function compileUnique(Blueprint $blueprint, Fluent $command)
{
$table = $this->wrapTable($blueprint);
$columns = $this->columnize($command->columns);
// Aucune utilité d'avoir le nom du schéma dans le nom de la contrainte Unique
$schemaTable = explode(".", $table);
if (count($schemaTable) > 1)
{
if (count($schemaTable) > 1) {
$command->index = str_replace($schemaTable[0]."_", "", $command->index);
}
@ -261,26 +264,27 @@ class DB2Grammar extends Grammar {
*
* @param \Illuminate\Database\Schema\Blueprint $blueprint
* @param \Illuminate\Support\Fluent $command
*
* @return string
*/
public function compileIndex(Blueprint $blueprint, Fluent $command)
{
$table = $this->wrapTable($blueprint);
$columns = $this->columnize($command->columns);
// Aucune utilité d'avoir le nom du schéma dans le nom de la contrainte Index
$schemaTable = explode(".", $table);
if (count($schemaTable) > 1)
{
if (count($schemaTable) > 1) {
$command->index = str_replace($schemaTable[0]."_", "", $command->index);
}
$sql = "create index {$command->index}";
if ($command->indexSystem)
{
if ($command->indexSystem) {
$sql .= " for system name {$command->indexSystem}";
}
$sql .= " on {$table}($columns)";
//return "create index {$command->index} for system name on {$table}($columns)";
@ -292,6 +296,7 @@ class DB2Grammar extends Grammar {
*
* @param \Illuminate\Database\Schema\Blueprint $blueprint
* @param \Illuminate\Support\Fluent $command
*
* @return string
*/
public function compileDrop(Blueprint $blueprint, Fluent $command)
@ -304,6 +309,7 @@ class DB2Grammar extends Grammar {
*
* @param \Illuminate\Database\Schema\Blueprint $blueprint
* @param \Illuminate\Support\Fluent $command
*
* @return string
*/
public function compileDropIfExists(Blueprint $blueprint, Fluent $command)
@ -316,12 +322,12 @@ class DB2Grammar extends Grammar {
*
* @param \Illuminate\Database\Schema\Blueprint $blueprint
* @param \Illuminate\Support\Fluent $command
*
* @return string
*/
public function compileDropColumn(Blueprint $blueprint, Fluent $command)
{
$columns = $this->prefixArray('drop', $this->wrapArray($command->columns));
$table = $this->wrapTable($blueprint);
return 'alter table '.$table.' '.implode(', ', $columns);
@ -332,6 +338,7 @@ class DB2Grammar extends Grammar {
*
* @param \Illuminate\Database\Schema\Blueprint $blueprint
* @param \Illuminate\Support\Fluent $command
*
* @return string
*/
public function compileDropPrimary(Blueprint $blueprint, Fluent $command)
@ -344,6 +351,7 @@ class DB2Grammar extends Grammar {
*
* @param \Illuminate\Database\Schema\Blueprint $blueprint
* @param \Illuminate\Support\Fluent $command
*
* @return string
*/
public function compileDropUnique(Blueprint $blueprint, Fluent $command)
@ -352,8 +360,8 @@ class DB2Grammar extends Grammar {
// Aucune utilité d'avoir le nom du schéma dans le nom de la contrainte Unique
$schemaTable = explode(".", $table);
if (count($schemaTable) > 1)
{
if (count($schemaTable) > 1) {
$command->index = str_replace($schemaTable[0]."_", "", $command->index);
}
@ -365,6 +373,7 @@ class DB2Grammar extends Grammar {
*
* @param \Illuminate\Database\Schema\Blueprint $blueprint
* @param \Illuminate\Support\Fluent $command
*
* @return string
*/
public function compileDropIndex(Blueprint $blueprint, Fluent $command)
@ -373,8 +382,8 @@ class DB2Grammar extends Grammar {
// Aucune utilité d'avoir le nom du schéma dans le nom de la contrainte Index
$schemaTable = explode(".", $table);
if (count($schemaTable) > 1)
{
if (count($schemaTable) > 1) {
$command->index = str_replace($schemaTable[0]."_", "", $command->index);
}
@ -386,6 +395,7 @@ class DB2Grammar extends Grammar {
*
* @param \Illuminate\Database\Schema\Blueprint $blueprint
* @param \Illuminate\Support\Fluent $command
*
* @return string
*/
public function compileDropForeign(Blueprint $blueprint, Fluent $command)
@ -394,8 +404,8 @@ class DB2Grammar extends Grammar {
// Aucune utilité d'avoir le nom du schéma dans le nom de la contrainte Foreign
$schemaTable = explode(".", $table);
if (count($schemaTable) > 1)
{
if (count($schemaTable) > 1) {
$command->index = str_replace($schemaTable[0]."_", "", $command->index);
}
@ -407,6 +417,7 @@ class DB2Grammar extends Grammar {
*
* @param \Illuminate\Database\Schema\Blueprint $blueprint
* @param \Illuminate\Support\Fluent $command
*
* @return string
*/
public function compileRename(Blueprint $blueprint, Fluent $command)
@ -420,6 +431,7 @@ class DB2Grammar extends Grammar {
* Create the column definition for a char type.
*
* @param \Illuminate\Support\Fluent $column
*
* @return string
*/
protected function typeChar(Fluent $column)
@ -431,6 +443,7 @@ class DB2Grammar extends Grammar {
* Create the column definition for a string type.
*
* @param \Illuminate\Support\Fluent $column
*
* @return string
*/
protected function typeString(Fluent $column)
@ -442,11 +455,13 @@ class DB2Grammar extends Grammar {
* Create the column definition for a text type.
*
* @param \Illuminate\Support\Fluent $column
*
* @return string
*/
protected function typeText(Fluent $column)
{
$colLength = ($column->length ? $column->length : 16369);
return "varchar($colLength)";
}
@ -454,11 +469,13 @@ class DB2Grammar extends Grammar {
* Create the column definition for a medium text type.
*
* @param \Illuminate\Support\Fluent $column
*
* @return string
*/
protected function typeMediumText(Fluent $column)
{
$colLength = ($column->length ? $column->length : 16369);
return "varchar($colLength)";
}
@ -466,11 +483,13 @@ class DB2Grammar extends Grammar {
* Create the column definition for a long text type.
*
* @param \Illuminate\Support\Fluent $column
*
* @return string
*/
protected function typeLongText(Fluent $column)
{
$colLength = ($column->length ? $column->length : 16369);
return "varchar($colLength)";
}
@ -478,6 +497,7 @@ class DB2Grammar extends Grammar {
* Create the column definition for a big integer type.
*
* @param \Illuminate\Support\Fluent $column
*
* @return string
*/
protected function typeBigInteger(Fluent $column)
@ -489,6 +509,7 @@ class DB2Grammar extends Grammar {
* Create the column definition for a integer type.
*
* @param \Illuminate\Support\Fluent $column
*
* @return string
*/
protected function typeInteger(Fluent $column)
@ -500,6 +521,7 @@ class DB2Grammar extends Grammar {
* Create the column definition for a small integer type.
*
* @param \Illuminate\Support\Fluent $column
*
* @return string
*/
protected function typeSmallInteger(Fluent $column)
@ -511,6 +533,7 @@ class DB2Grammar extends Grammar {
* Create the column definition for a numeric type.
*
* @param \Illuminate\Support\Fluent $column
*
* @return string
*/
protected function typeNumeric(Fluent $column)
@ -522,6 +545,7 @@ class DB2Grammar extends Grammar {
* Create the column definition for a float type.
*
* @param \Illuminate\Support\Fluent $column
*
* @return string
*/
protected function typeFloat(Fluent $column)
@ -533,24 +557,23 @@ class DB2Grammar extends Grammar {
* Create the column definition for a double type.
*
* @param \Illuminate\Support\Fluent $column
*
* @return string
*/
protected function typeDouble(Fluent $column)
{
if ($column->total && $column->places)
{
if ($column->total && $column->places) {
return "double({$column->total}, {$column->places})";
}
else
{
return 'double';
}
}
/**
* Create the column definition for a decimal type.
*
* @param \Illuminate\Support\Fluent $column
*
* @return string
*/
protected function typeDecimal(Fluent $column)
@ -562,17 +585,28 @@ class DB2Grammar extends Grammar {
* Create the column definition for a boolean type.
*
* @param \Illuminate\Support\Fluent $column
*
* @return string
*/
protected function typeBoolean(Fluent $column)
{
return 'smallint constraint '.$column->type.'_'.$column->prefix.'_'.$column->name.' check('.$column->name.' in(0,1))'.(is_null($column->default) ? ' default 0' : '');
$definition = 'smallint constraint %s_%s_%s check(%s in(0, 1)) %s';
return sprintf(
$definition,
$column->type,
$column->prefix,
$column->name,
$column->name,
is_null($column->default) ? ' default 0' : ''
);
}
/**
* Create the column definition for an enum type.
*
* @param \Illuminate\Support\Fluent $column
*
* @return string
*/
protected function typeEnum(Fluent $column)
@ -584,12 +618,14 @@ class DB2Grammar extends Grammar {
* Create the column definition for a date type.
*
* @param \Illuminate\Support\Fluent $column
*
* @return string
*/
protected function typeDate(Fluent $column)
{
if ( ! $column->nullable)
if (!$column->nullable) {
return 'date default current_date';
}
return 'date';
}
@ -598,6 +634,7 @@ class DB2Grammar extends Grammar {
* Create the column definition for a date-time type.
*
* @param \Illuminate\Support\Fluent $column
*
* @return string
*/
protected function typeDateTime(Fluent $column)
@ -609,12 +646,14 @@ class DB2Grammar extends Grammar {
* Create the column definition for a time type.
*
* @param \Illuminate\Support\Fluent $column
*
* @return string
*/
protected function typeTime(Fluent $column)
{
if ( ! $column->nullable)
if (!$column->nullable) {
return 'time default current_time';
}
return 'time';
}
@ -623,12 +662,14 @@ class DB2Grammar extends Grammar {
* Create the column definition for a timestamp type.
*
* @param \Illuminate\Support\Fluent $column
*
* @return string
*/
protected function typeTimestamp(Fluent $column)
{
if ( ! $column->nullable)
if (!$column->nullable) {
return 'timestamp default current_timestamp';
}
return 'timestamp';
}
@ -637,6 +678,7 @@ class DB2Grammar extends Grammar {
* Create the column definition for a binary type.
*
* @param \Illuminate\Support\Fluent $column
*
* @return string
*/
protected function typeBinary(Fluent $column)
@ -649,6 +691,7 @@ class DB2Grammar extends Grammar {
*
* @param \Illuminate\Database\Schema\Blueprint $blueprint
* @param \Illuminate\Support\Fluent $column
*
* @return string|null
*/
protected function modifyNullable(Blueprint $blueprint, Fluent $column)
@ -661,14 +704,16 @@ class DB2Grammar extends Grammar {
*
* @param \Illuminate\Database\Schema\Blueprint $blueprint
* @param \Illuminate\Support\Fluent $column
*
* @return string|null
*/
protected function modifyDefault(Blueprint $blueprint, Fluent $column)
{
if ( ! is_null($column->default))
{
if (!is_null($column->default)) {
return " default ".$this->getDefaultValue($column->default);
}
return null;
}
/**
@ -676,14 +721,16 @@ class DB2Grammar extends Grammar {
*
* @param \Illuminate\Database\Schema\Blueprint $blueprint
* @param \Illuminate\Support\Fluent $column
*
* @return string|null
*/
protected function modifyIncrement(Blueprint $blueprint, Fluent $column)
{
if (in_array($column->type, $this->serials) && $column->autoIncrement)
{
return ' as identity constraint ' . $blueprint->getTable() . '_' . $column->name . '_primary primary key';
if (in_array($column->type, $this->serials) && $column->autoIncrement) {
return ' as identity constraint '.$blueprint->getTable().'_'.$column->name.'_primary primary key';
}
return null;
}
@ -692,14 +739,16 @@ class DB2Grammar extends Grammar {
*
* @param \Illuminate\Database\Schema\Blueprint $blueprint
* @param \Illuminate\Support\Fluent $column
*
* @return string|null
*/
protected function modifyBefore(Blueprint $blueprint, Fluent $column)
{
if ( ! is_null($column->before))
{
if (!is_null($column->before)) {
return ' before '.$this->wrap($column->before);
}
return null;
}
/**
@ -707,14 +756,16 @@ class DB2Grammar extends Grammar {
*
* @param \Illuminate\Database\Schema\Blueprint $blueprint
* @param \Illuminate\Support\Fluent $column
*
* @return string|null
*/
protected function modifyForColumn(Blueprint $blueprint, Fluent $column)
{
if ( ! is_null($column->forColumn))
{
if (!is_null($column->forColumn)) {
return ' for column '.$this->wrap($column->forColumn);
}
return null;
}
/**
@ -722,14 +773,16 @@ class DB2Grammar extends Grammar {
*
* @param \Illuminate\Database\Schema\Blueprint $blueprint
* @param \Illuminate\Support\Fluent $column
*
* @return string|null
*/
protected function modifyGenerated(Blueprint $blueprint, Fluent $column)
{
if ( ! is_null($column->generated))
{
if (!is_null($column->generated)) {
return ' generated '.($column->generated === true ? 'always' : $this->wrap($column->generated));
}
return null;
}
/**
@ -737,14 +790,16 @@ class DB2Grammar extends Grammar {
*
* @param \Illuminate\Database\Schema\Blueprint $blueprint
* @param \Illuminate\Support\Fluent $column
*
* @return string|null
*/
protected function modifyStartWith(Blueprint $blueprint, Fluent $column)
{
if ( ! is_null($column->startWith))
{
if (!is_null($column->startWith)) {
return ' (start with '.$column->startWith.')';
}
return null;
}
/**
@ -752,29 +807,35 @@ class DB2Grammar extends Grammar {
*
* @param \Illuminate\Database\Schema\Blueprint $blueprint
* @param \Illuminate\Support\Fluent $column
*
* @return string|null
*/
protected function modifyImplicitlyHidden(Blueprint $blueprint, Fluent $column)
{
if ( ! is_null($column->implicitlyHidden))
{
if (!is_null($column->implicitlyHidden)) {
return ' implicitly hidden';
}
return null;
}
/**
* Format a value so that it can be used in "default" clauses.
*
* @param mixed $value
*
* @return string
*/
protected function getDefaultValue($value)
{
if ($value instanceof Expression
if (
$value instanceof Expression
|| is_bool($value)
|| is_numeric($value)) return $value;
|| is_numeric($value)
) {
return $value;
}
return "'".strval($value)."'";
}
}