You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 
 
 

460 lines
17 KiB

<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);
include('util/util.php');
include('bd.php');
define("MAX_LOOP_FK", 1000);
define("CONF_EMPRESA_LOG", '/var/log/asterisk/importa_empresa.log');
/*
-- Table: pbx_organizacao
-- DROP TABLE pbx_organizacao;
CREATE TABLE pbx_organizacao
(
id serial NOT NULL PRIMARY KEY,
nome VARCHAR(128) NOT NULL,
status INTEGER NOT NULL DEFAULT 1,
master int not null DEFAULT 0,
updated_at timestamp without time zone,
created_at timestamp without time zone NOT NULL DEFAULT now()
);
CREATE TABLE pbx_organizacao_usuarios
(
id SERIAL not null primary key,
id_usuario INTEGER not null,
id_organizacao INTEGER not null,
updated_at timestamp without time zone,
created_at timestamp without time zone NOT NULL DEFAULT now()
);
ALTER TABLE pbx_organizacao_usuarios ADD CONSTRAINT id_usuario FOREIGN KEY (id_usuario)
REFERENCES pbx_usuarios(id) ON DELETE CASCADE;
ALTER TABLE pbx_organizacao_usuarios ADD CONSTRAINT id_organizacao FOREIGN KEY (id_organizacao)
REFERENCES pbx_organizacao(id) ON DELETE CASCADE;
*/
try {
/*
* Cria a coluna org_id em todas as tabelas.
*/
CriaCampo($dbcon);
/*
* Cria as empresas padrao.
*/
CriaOrgPadrao($dbcon);
importIdTables($dbcon);
corrigeDadosFila($dbcon);
/*
* Apaga todas as fk.
*/
ApagaFK($dbcon);
/*
* Modifica todas as chaves primarias.
*/
ModificaPK($dbcon);
/*
* Modifica os indices.
*/
ModificaIdx($dbcon);
echo "Script finalizado com sucesso!\n";
} catch (Exception $ex) {
echo $ex->getMessage();
}
function CriaCampo($dbcon)
{
$query = "SELECT table_name FROM information_schema.tables a
WHERE table_schema = 'public'
AND table_type = 'BASE TABLE'
AND NOT EXISTS(SELECT '' FROM information_schema.columns WHERE table_name = a.table_name AND column_name = 'org_id');";
$result = pg_query($dbcon, $query);
if (!$result) {
throw new Exception("Não foi possivel carregar a lista de tabelas.");
}
$tables = pg_fetch_all($result);
$except = ['pbx_organizacao', 'pbx_organizacao_usuarios', 'pbx_usuarios', 'pbx_municipios'];
foreach ($tables as $table) {
if (in_array($table["table_name"], $except)) {
continue;
}
$query = "DO $$
BEGIN
IF EXISTS (SELECT 1 FROM information_schema.columns WHERE table_name = '{$table["table_name"]}' AND column_name = 'org_id') THEN
ALTER TABLE {$table["table_name"]} DROP COLUMN IF EXISTS org_id;
END IF;
END $$;";
$query .= sprintf("alter table %s add org_id int not null default 0;", $table["table_name"]);
if (!$result = pg_query($dbcon, $query)) {
throw new Exception("Não foi possivel criar a coluna \"org_id\" na table!" . $table["table_name"] . "\"!\n");
}
$query = "UPDATE {$table["table_name"]} SET org_id = (SELECT id FROM pbx_organizacao WHERE master = 1 LIMIT 1);";
pg_query($dbcon, $query);
if (!$result) {
throw new Exception("Não foi possivel alterar a coluna \"org_id\" na table!" . $table["table_name"] . "\"!\n");
}
}
}
function ApagaFK($dbcon)
{
$query = "SELECT c.conname constraint_name, c.conrelid::pg_catalog.regclass table_name
FROM pg_catalog.pg_constraint c
JOIN pg_catalog.pg_class r ON r.oid = c.confrelid
JOIN pg_catalog.pg_namespace n ON n.oid = r.relnamespace
WHERE n.nspname = 'public' AND c.contype = 'f'
ORDER BY c.conrelid, r.relname, c.conname;";
$breakInfinitLoop = 0;
do {
if (!$result = pg_query($dbcon, $query)) {
throw new Exception("Não foi possivel carregar a lista de fks.");
}
$tables = pg_fetch_all($result);
foreach ($tables as $table) {
// Remove a pk
$query = sprintf("ALTER TABLE \"%s\" DROP CONSTRAINT \"%s\";", $table["table_name"], $table["constraint_name"]);
if (!$result = pg_query($dbcon, $query)) {
throw new Exception(sprintf("Não foi remover a constraint FK \"%s\" da tabela \"%s\"", $table["constraint_name"], $table["table_name"]));
}
}
} while (ExisteFK($dbcon) && ($breakInfinitLoop < MAX_LOOP_FK));
}
function CriaOrgPadrao($dbcon)
{
$query = "SELECT * FROM pbx_organizacao WHERE master = 1;";
$result = pg_query($dbcon, $query);
$res = pg_fetch_assoc($result);
if ($res) {
return;
}
$query = "INSERT INTO pbx_organizacao(nome, master, status, updated_at) VALUES ('Simples IP', 1, 1, NOW()) RETURNING id;";
$result = pg_query($dbcon, $query);
$res = pg_fetch_assoc($result);
if (!$res) {
$sql = "DELETE FROM pbx_organizacao WHERE id = " . $res['id'];
pg_query($dbcon, $sql);
throw new Exception("Não foi possivel cria a organizacao padrao!");
}
$query = "INSERT INTO pbx_organizacao_usuarios(id_usuario, id_organizacao, updated_at) VALUES ((SELECT id FROM pbx_usuarios WHERE apelido = 'admin'), {$res['id']}, NOW());";
$result = pg_query($dbcon, $query);
if (!$result) {
throw new Exception("Não foi possivel cria a organizacao usuario!");
}
}
function ExisteFK($dbcon)
{
$query = "SELECT count(*)
FROM pg_catalog.pg_constraint c
JOIN pg_catalog.pg_class r ON r.oid = c.confrelid
JOIN pg_catalog.pg_namespace n ON n.oid = r.relnamespace
WHERE n.nspname = 'public' AND c.contype = 'f';";
if (!$result = pg_query($dbcon, $query)) {
throw new Exception("Não foi possivel carregar a lista de fks.");
}
$row = pg_fetch_row($result);
return $row[0];
}
function ModificaPK($dbcon)
{
$query = " drop table if exists tmp_pks;
create temporary table tmp_pks as
select tab.table_schema::varchar(32),
tab.table_name::varchar(64),
tco.constraint_name::varchar(512),
kcu.column_name::varchar(64) as key_columns
from information_schema.tables tab
inner join information_schema.table_constraints tco
on tco.table_schema = tab.table_schema
and tco.table_name = tab.table_name
and tco.constraint_type = 'PRIMARY KEY'
inner join information_schema.key_column_usage kcu
on kcu.constraint_name = tco.constraint_name
and kcu.constraint_schema = tco.constraint_schema
and kcu.constraint_name = tco.constraint_name
where tab.table_schema = 'public'
and tab.table_type = 'BASE TABLE'
group by tab.table_schema,
tab.table_name,
tco.constraint_name,
kcu.column_name
order by tab.table_schema,
tab.table_name;
select table_schema, table_name, constraint_name, translate(array_agg(key_columns)::text, '{}', '') as key_columns
from tmp_pks
group by table_schema,
table_name,
constraint_name
having array_agg(key_columns)::text not ilike '%org_id%'
order by 2;";
if (!$result = pg_query($dbcon, $query)) {
throw new Exception("Não foi possivel carregar a lista de pks.");
}
$tables = pg_fetch_all($result);
// foreach ($tables as $table) {
// // Remove a pk
// $query = sprintf("ALTER TABLE \"%s\" DROP CONSTRAINT \"%s\";", $table["table_name"], $table["constraint_name"]);
// if (!$result = pg_query($dbcon, $query)) {
// throw new Exception(sprintf("Não foi remover a constraint \"%s\" da tabela \"%s\"", $table["constraint_name"], $table["table_name"]));
// }
// // Recria a pk
// $query = sprintf("ALTER TABLE \"%s\" ADD CONSTRAINT \"%s\" PRIMARY KEY (%s,org_id);", $table["table_name"], $table["constraint_name"], $table["key_columns"]);
// if (!$result = pg_query($dbcon, $query)) {
// throw new Exception(sprintf("Não foi criar a constraint \"%s\" da tabela \"%s\"", $table["constraint_name"], $table["table_name"]));
// }
// }
foreach ($tables as $table) {
// Verifica se a tabela é pbx_organizacao_usuarios
//Quando uma tabela for pbx_organizacao_usuarios, o org_id será id_organizacao;
if ($table["table_name"] != "pbx_organizacao_usuarios") {
// Remove a pk
$query = sprintf("ALTER TABLE \"%s\" DROP CONSTRAINT \"%s\";", $table["table_name"], $table["constraint_name"]);
if (!$result = pg_query($dbcon, $query)) {
throw new Exception(sprintf("Não foi possível remover a constraint \"%s\" da tabela \"%s\"", $table["constraint_name"], $table["table_name"]));
}
// Recria a pk
$query = sprintf("ALTER TABLE \"%s\" ADD CONSTRAINT \"%s\" PRIMARY KEY (%s, org_id);", $table["table_name"], $table["constraint_name"], $table["key_columns"]);
if (!$result = pg_query($dbcon, $query)) {
throw new Exception(sprintf("Não foi possível criar a constraint \"%s\" da tabela \"%s\"", $table["constraint_name"], $table["table_name"]));
}
}else{
$query = sprintf("ALTER TABLE \"%s\" DROP CONSTRAINT \"%s\";", $table["table_name"], $table["constraint_name"]);
if (!$result = pg_query($dbcon, $query)) {
throw new Exception(sprintf("Não foi possível remover a constraint \"%s\" da tabela \"%s\"", $table["constraint_name"], $table["table_name"]));
}
// Recria a pk
$query = sprintf("ALTER TABLE \"%s\" ADD CONSTRAINT \"%s\" PRIMARY KEY (%s, id_organizacao);", $table["table_name"], $table["constraint_name"], $table["key_columns"]);
if (!$result = pg_query($dbcon, $query)) {
throw new Exception(sprintf("Não foi possível criar a constraint \"%s\" da tabela \"%s\"", $table["constraint_name"], $table["table_name"]));
}
}
}
}
function ModificaIdx($dbcon)
{
$query = "select idx.relname as index_name,
insp.nspname as index_schema,
tbl.relname as table_name,
tnsp.nspname as table_schema,
ind.indexdef, translate( substring(ind.indexdef, position('(' in indexdef)), '()', '') as key_columns,
case when(pgi.indisunique)then 1 else 0 end as uniquie
from pg_index pgi
join pg_class idx on idx.oid = pgi.indexrelid
join pg_namespace insp on insp.oid = idx.relnamespace
join pg_class tbl on tbl.oid = pgi.indrelid
join pg_namespace tnsp on tnsp.oid = tbl.relnamespace
join pg_indexes ind on ind.indexname = idx.relname
where not pgi.indisprimary
and tnsp.nspname = 'public'
and position('org_id' in indexdef) = 0 and position('CREATE UNIQUE' in upper(indexdef)) > 0
order by tbl.relname;";
if (!$result = pg_query($dbcon, $query)) {
throw new Exception("Não foi possivel carregar a lista de idx.");
}
$tables = pg_fetch_all($result);
foreach ($tables as $table) {
// Remove a pk
$query = sprintf("drop index \"%s\";", $table["index_name"]);
if (!pg_query($dbcon, $query)) {
$query = sprintf("alter table %s drop constraint \"%s\";", $table["table_name"], $table["index_name"]);
if (!pg_query($dbcon, $query)) {
throw new Exception(sprintf("Não foi remover o indice \"%s\" da tabela \"%s\"", $table["index_name"], $table["table_name"]));
}
}
// Recria o idx.
$query = sprintf("create %s index \"%s\" on \"%s\" using btree (%s,org_id);", ($table["uniquie"] ? 'unique' : ''), $table["index_name"], $table["table_name"], $table["key_columns"]);
if (!pg_query($dbcon, $query)) {
throw new Exception(sprintf("Não foi criar o indice \"%s\" da tabela \"%s\"", $table["index_name"], $table["table_name"]));
}
}
}
// function importIdTables($dbcon)
// {
// $tables = [
// 'pbx_parametros' => 'id',
// 'pbx_features_featuremap' => 'id',
// 'pbx_features_general' => 'id',
// 'pbx_iax_general' => 'id',
// 'pbx_facilidades' => 'id',
// 'pbx_voicemail_general' => 'id',
// 'pbx_sip_general' => 'id',
// 'pbx_workflow_parametros' => 'wkf_id'
// ];
// $org_id = GetOrganizacao();
// foreach ($tables as $table => $column) {
// if (!$column) {
// $column = 'id';
// }
// $sql = "SELECT MAX($column) AS id FROM {$table};";
// $result = pg_query($dbcon, $sql);
// $resp = pg_fetch_assoc($result);
// if ($resp['id']) {
// ___Gravalog("Não foi possível o ID da tabela {$table};");
// }
// $query = "DO $$
// BEGIN
// IF EXISTS (SELECT 1 FROM information_schema.columns WHERE table_name = '{$table}' AND column_name = '{$column}') THEN
// ALTER TABLE {$table} DROP COLUMN IF EXISTS {$column};
// END IF;
// ALTER TABLE {$table} ADD COLUMN {$column} SERIAL PRIMARY KEY;
// END $$;";
// $result = pg_query($dbcon, $query);
// $id = $resp['id'];
// $query = "CREATE TEMPORARY TABLE t{$table} AS SELECT * FROM {$table} WHERE $column = 1;";
// $query .= "ALTER TABLE t{$table} DROP COLUMN $column;";
// $query .= "INSERT INTO {$table} SELECT * FROM t{$table};";
// $query .= "UPDATE {$table} SET org_id = $org_id WHERE $column = $id";
// $result = pg_query($dbcon, $query);
// pg_query($dbcon, "DROP TABLE IF EXISTS t{$table};");
// }
// }
function importIdTables($dbcon)
{
$tables = [
'pbx_parametros' => 'id',
'pbx_features_featuremap' => 'id',
'pbx_features_general' => 'id',
'pbx_iax_general' => 'id',
'pbx_facilidades' => 'id',
'pbx_voicemail_general' => 'id',
'pbx_sip_general' => 'id',
'pbx_workflow_parametros' => 'wkf_id'
];
// Obter o ID da organização padrão
$org_id = getOrganizationId($dbcon);
foreach ($tables as $table => $column) {
if (!$column) {
$column = 'id';
}
// Verificar se a coluna 'id' já existe e, se sim, removê-la
dropColumnIfExists($dbcon, $table, $column);
// Adicionar a coluna 'id' do tipo SERIAL
addSerialColumn($dbcon, $table, $column);
// Criar tabela temporária e transferir dados
createTempTableAndTransferData($dbcon, $table, $column, $org_id);
}
}
function getOrganizationId($dbcon)
{
$consulta = "SELECT id FROM pbx_organizacao po ORDER BY po.id ASC LIMIT 1;";
$retornoOrg = pg_query($dbcon, $consulta);
if (!$retornoOrg) {
throw new Exception('Não foi encontrado nenhuma organização padrão');
}
$linha = pg_fetch_assoc($retornoOrg);
return $linha['id'];
}
function dropColumnIfExists($dbcon, $table, $column)
{
$query = "DO $$
BEGIN
IF EXISTS (SELECT 1 FROM information_schema.columns WHERE table_name = '{$table}' AND column_name = '{$column}') THEN
ALTER TABLE {$table} DROP COLUMN IF EXISTS {$column};
END IF;
END $$;";
$result = pg_query($dbcon, $query);
if (!$result) {
throw new Exception("Erro ao remover a coluna '{$column}' da tabela '{$table}'");
}
}
function addSerialColumn($dbcon, $table, $column)
{
$query = "ALTER TABLE {$table} ADD COLUMN {$column} SERIAL PRIMARY KEY;";
$result = pg_query($dbcon, $query);
if (!$result) {
throw new Exception("Erro ao adicionar a coluna '{$column}' na tabela '{$table}'");
}
}
function createTempTableAndTransferData($dbcon, $table, $column, $org_id)
{
$query = "CREATE TEMPORARY TABLE t{$table} AS SELECT * FROM {$table} WHERE $column = 1;";
$query .= "ALTER TABLE t{$table} DROP COLUMN $column;";
$query .= "INSERT INTO {$table} SELECT * FROM t{$table};";
$query .= "UPDATE {$table} SET org_id = $org_id WHERE $column = 1;";
$result = pg_query($dbcon, $query);
if (!$result) {
throw new Exception("Erro ao criar tabela temporária e transferir dados para '{$table}'");
}
pg_query($dbcon, "DROP TABLE IF EXISTS t{$table};");
}
function corrigeDadosFila($dbcon)
{
$query = "SELECT id, nome, org_id FROM pbx_queues_grupos;";
$result = pg_query($dbcon, $query);
$dados = pg_fetch_all($result);
foreach ($dados as $f) {
$nome = null;
if (strpos($f['nome'], '@') === false) {
$nome = $f['nome'] . "@" . $f['org_id'];
$sql = sprintf("UPDATE pbx_queues_grupos SET nome = '%s' WHERE id = %s;", $nome, $f['id']);
$result = pg_query($dbcon, $sql);
}
}
}
function ___Gravalog($message)
{
$line = "\n----------------------------------------------\n";
$line .= sprintf("[ %s ] %s \n", date('Y-m-d H:i:s'), $message);
$line = "----------------------------------------------";
file_put_contents(CONF_EMPRESA_LOG, $message);
}