View source
<?php
namespace Drupal\dynamic_entity_reference\Storage;
use Drupal\Core\Database\Connection;
class IntColumnHandlerPostgreSQL implements IntColumnHandlerInterface {
protected $connection;
public function __construct(Connection $connection) {
$this->connection = $connection;
}
public function create($table, array $columns, array $index_columns = []) {
$schema = $this->connection
->schema();
if (!IntColumnHandler::allColumnsExist($schema, $table, $columns)) {
return [];
}
$spec = [
'type' => 'int',
'unsigned' => TRUE,
'not null' => FALSE,
];
$new = [];
foreach ($columns as $column) {
$column_int = $column . '_int';
if (!$schema
->fieldExists($table, $column_int)) {
$this
->createTriggerFunction($table, $column, $column_int);
$this
->createTrigger($table, $column, $column_int);
$index_fields = [
$column_int,
];
$full_spec = [
'fields' => [
$column_int => $spec,
],
];
if (!empty($index_columns)) {
$full_spec['fields'] = array_merge($full_spec['fields'], $index_columns);
$index_fields = array_merge($index_fields, array_keys($index_columns));
}
$schema
->addField($table, $column_int, $spec);
$schema
->addIndex($table, $column_int, $index_fields, $full_spec);
$new[] = $column_int;
}
}
return $new;
}
protected function createTriggerFunction($table, $column, $column_int) {
$function_name = $this
->getFunctionName($table, $column_int);
$query = "CREATE OR REPLACE FUNCTION {$function_name}() RETURNS trigger AS \$\$\n BEGIN\n NEW.{$column_int} = (CASE WHEN NEW.{$column} ~ '^[0-9]+\$' THEN NEW.{$column} ELSE NULL END)::integer";
if (strpos($query, ';') !== FALSE) {
throw new \InvalidArgumentException('; is not supported in SQL strings. Use only one statement at a time.');
}
$this->connection
->query("{$query}; RETURN NEW; END; \$\$ LANGUAGE plpgsql IMMUTABLE RETURNS NULL ON NULL INPUT", [], [
'allow_delimiter_in_query' => TRUE,
'allow_square_brackets' => TRUE,
]);
}
protected function createTrigger($table, $column, $column_int) {
$function_name = $this
->getFunctionName($table, $column_int);
$prefixed_table = $this
->getPrefixedTable($table);
$this->connection
->query("DROP TRIGGER IF EXISTS {$column_int} ON {$prefixed_table}");
$this->connection
->query("\n CREATE TRIGGER {$column_int}\n BEFORE INSERT OR UPDATE\n ON {$prefixed_table}\n FOR EACH ROW\n EXECUTE PROCEDURE {$function_name}();\n ");
}
protected function getFunctionName($table, $column_int) {
return implode('_', [
$this
->getPrefixedTable($table),
$column_int,
]);
}
protected function getPrefixedTable($table) {
return trim($this->connection
->prefixTables('{' . $table . '}'), '"');
}
}