PHP e PostgreSQL,
Dois Elefantes Trabalham muito
mais!
Nome William Felipe Welter
Dez/2015
2
# whoami
➢ Bacharel em Ciência da
Computação;
➢ Gerente da equipe de
desenvolvimento da 4Linux;
➢ Experiência com
desenvolvimento (PHP e C) e
infraestrutura.
Nome
William Felipe Welter
3
Conhecendo a 4Linux
➢ Metodologia IT Experience -
Cenários reais
➢ Cursos práticos, rápidos e baratos de
autores feras: www.4shot.com.br
➢ Projetos complexos de missão crítica,
com infra e desenvolvimento PHP
4
Alguns dos nossos clientes
A 4Linux suporta o ecossistema de
software livre da Caixa. Um dos maiores
cases do mundo.
Clientes que confiam na qualidade dos serviços
da 4Linux.
5
Cursos práticos, rápidos e baratos de
autores feras
6
7
Lançamento 4Linux
8
PHP e PostgreSQL
9
Por que, hoje, o PHP é tão ligado ao MySQL ?
PHP e PostgreSQL
10
PHP e PostgreSQL
➢ Lançados juntos (PHP ~94 / MySQL ~95);
➢ MySQL tinha porte para Windows;
➢ PostgreSQL passou a ter porte para Windows a partir da
versão 8.0 (2005);
➢ Não tinha integridade referencial (MyISAM);
➢ Pouca configuração;
➢ Maioria dos webhosts adotaram.
11
PHP e PostgreSQL
Por que você
usa MySQL? Minha aplicação
é pequena. Por
isso, resolvi
usar o MySQL.
Quando crescer
penso em outro
banco...
12
PHP e PostgreSQL
Qual é o problema de mudar depois?
13
PHP e PostgreSQL
➢Se usar extensões “mysql” , “mysqli”...
14
PHP e PostgreSQL
➢Se usar PDO ...
15
PHP e PostgreSQL
➢Se usar um ORM..
16
PHP e PostgreSQL
Por que não começar com o
PostgreSQL?
17
PHP e PostgreSQL
Eu uso o phpMyAdmin, como faço no
PostgreSQL?
18
PHP e PostgreSQL
19
PHP e PostgreSQL
Cliente desktop:
20
PHP e PostgreSQL
21
PHP e PostgreSQL
22
PHP e PostgreSQL
➢psql:
23
PHP e PostgreSQL
➢Muito fácil;
➢Autocomplete (TAB);
➢History, ctrl+r (libreadline);
➢Meta Comandos;
➢Visão expandida ;
➢Editor externo.
24
PHP e PostgreSQL
➢E, para modelar ?
SQL
PowerArchitect
PgModeler
25
PHP e PostgreSQL
Mas, por que o PostgreSQL?
26
PHP e PostgreSQL
➢Derivou, originalmente, do projeto Ingres;
➢Iniciou-se, em 1974, na universidade de Berkeley;
➢Outros projetos derivados: Sybase, SQL Server,
NonStop SQL;
➢Linguagem SQL introduzida em 1994.
Um pouco de história:
27
PHP e PostgreSQL
➢Licença é BSD-style;
➢Não tem uma empresa dona do projeto;
➢Projeto é livre!
➢Preza por estabilidade em favor de novas
funcionalidades “da moda”;
➢Segue a risca ao padrão ANSI-SQL 2008.
Principais características:
28
PHP e PostgreSQL
➢Maduro;
➢Estável;
➢Segue padrões!
➢Suporte independente de fornecedor!
➢Futuro do projeto não esta mão de uma única
empresa.
Primeiras conclusões:
29
PHP e PostgreSQL
DESEMPENHO
30
PHP e PostgreSQL
Escalabilidade Vertical
31
PHP e PostgreSQL
➢CPU:
➢Segundo documentação 32 e 64 cores;
➢Experiência pessoal > 80 cores;
➢Memória:
➢Experiência pessoal 1TB;
➢Discos:
➢Tablespaces, RAID, LVM.
32
PHP e PostgreSQL
Índices
33
PHP e PostgreSQL
➢Multicolunas;
➢Índices parciais;
➢Índices baseados em expressões;
➢Index e Reindex, sem locks.
34
PHP e PostgreSQL
➢ b-tree (default):
➢ Numérico e textual
➢ Null/not null
➢ Like
➢ Hash:
➢ =
➢ Pequeno
➢ Corrompe fácil
➢ GIN:
➢ Estruturas complexas
➢ Arrays
➢ FTS
➢ GiST:
➢ Buscas além de intervalos e
igualdade
➢ Operadores geométricos
➢ FTS
➢ SP-GiST:
➢ Arvore não balanceada
➢ CAD, data mining, GIS
35
PHP e PostgreSQL
Planejador de consultas
36
PHP e PostgreSQL
➢Baseado em pesos (customizável);
➢Por tablespace;
➢Coletor de estatísticas;
➢Auto analyze;
➢Otimizador de busca genética.
37
PHP e PostgreSQL
➢seqscan;
➢indexscan;
➢bitmapscan;
➢hash aggregate;
➢hash join;
➢merge join;
➢nested loop;
38
PHP e PostgreSQL
Views
39
PHP e PostgreSQL
➢Views materializadas:
➢Consultas complexas e lentas;
➢Reutilizadas;
➢Comporta-se com uma tabela quando utilizado em
consultas;
➢Permite criação de índices;
➢Pode ser atualizada.
40
PHP e PostgreSQL
SEGURANÇA (CONTROLE DE ACESSO)
41
PHP e PostgreSQL
➢Suporte a grupos e herança de privilégios (ROLES);
➢Suporte a múltiplos schemas;
➢Autenticação baseada em hosts (HBA);
➢Suporta o PAM;
➢Bancos são completamente isolados;
➢Granularidade de privilégios.
42
PHP e PostgreSQL
BACKUP
43
PHP e PostgreSQL
➢Dump:
➢A quente, sem locks;
➢Textual ou binário;
➢O dump e restauração pode ser paralelizados;
➢PITR:
➢Backup continuo, a nível transacional;
➢A quente.
44
PHP e PostgreSQL
➢Master-Slave;
➢Hot-standby;
➢Síncrona ou Assíncrona;
➢Replicas em cascata;
➢Física e lógica*;
➢Novas replicas sem lock ou paradas.
Replicação Nativa:
45
PHP e PostgreSQL
➢ Bucardo (Open Source):
➢ Multimaster;
➢ Lógica;
➢ Slony;
➢ Skytools;
➢ RepManager.
Replicação, ferramentas externas:
46
PHP e PostgreSQL
INTEGRAÇÃO COM OUTROS SISTEMAS
47
PHP e PostgreSQL
➢PostgreSQL;
➢MySQL;
➢Oracle;
➢MS SQL;
➢Sybase;
➢...
FDW:
48
PHP e PostgreSQL
GRANDE VARIEDADE DE TIPO DE DADOS
49
PHP e PostgreSQL
➢Json;
➢Xml;
➢Hstore*;
➢Arrays;
➢Geometric.
50
PHP e PostgreSQL
QUESTÕES CONHECIDAS DO MySQL
51
PHP e PostgreSQL
➢Conversão automática de tipos:
mysql> CREATE TABLE notas (
id integer primary key auto_increment,
alu_id integer not null,
description varchar(150),
grade float not null
);
mysql> INSERT INTO notas(alu_id,description,grade)
VALUES
( 'fulano', 'Nota da primeira fase', 4.4);
mysql> SELECT * FROM notas;
+----+--------+-----------------------+-------+
| id | alu_id | description | grade |
+----+--------+-----------------------+-------+
| 1 | 0 | Nota da primeira fase | 4.4 |
+----+--------+-----------------------+-------+
52
PHP e PostgreSQL
mysql> CREATE TABLE answer (
id integer primary key,
alu_id integer not null,
answer varchar(100),
date timestamp not null
)
mysql> INSERT INTO answer ( alu_id,answer, date)
VALUES (1,'Thi is ..','08/07/15');
mysql> SELECT * FROM answer;
+----+--------+-----------+---------------------+
| id | alu_id | answer | date |
+----+--------+-----------+---------------------+
| 0 | 1 | Thi is .. | 2008-07-15 00:00:00 |
+----+--------+-----------+---------------------+
53
PHP e PostgreSQL
➢ < 5.6.7, perda de integridade referencial com alter table.
➢ => 5.6.7, bloqueia alter table em colunas com foreign key.
mysql> CREATE TABLE notas (
id integer primary key auto_increment,
alu_id integer,
description varchar(150),
grade float not null,
constraint alu_id_fk
foreign key (alu_id) references alunos(id)
);
mysql> ALTER TABLE notas CHANGE alu_id alu_id integer not
null;
ERROR 1832 (HY000): Cannot change column 'alu_id': used in a
foreign key constraint 'alu_id_fk'
54
PHP e PostgreSQL
➢Comportamento no PostgreSQL:
fisl=# CREATE TABLE notas (
id serial primary key,
alu_id integer references alunos(id),
description varchar,
grade float not null
);
fisl=# ALTER TABLE notas ALTER COLUMN alu_id SET not null;
ALTER TABLE
fisl=# ALTER TABLE notas ALTER COLUMN alu_id DROP not null;
ALTER TABLE
fisl=# INSERT INTO notas ( description, grade) VALUES
('asdfasdfa',5.5);
INSERT 0 1
fisl=# ALTER TABLE notas ALTER COLUMN alu_id SET not null;
ERROR: column "alu_id" contains null values
55
PHP e PostgreSQL
➢ Sintaxes não implementadas, são aceitas silenciosamente:
mysql> create table notas (
id integer primary key auto_increment,
alu_id integer references alunos(id),
description varchar(150),
grade float not null
);
Query OK, 0 rows affected (0,59 sec)
mysql> desc notas;
+-------------+--------------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+-------------+--------------+------+-----+---------+----------------+
| id | int(11) | NO | PRI | NULL | auto_increment |
| alu_id | int(11) | YES | | NULL | |
| description | varchar(150) | YES | | NULL | |
| grade | float | NO | | NULL | |
+-------------+--------------+------+-----+---------+----------------+
56
PHP e PostgreSQL
➢ GROUP BY, colunas sem agregação = resultado
indeterminado:
Ex3:
mysql> select * from notas;
+----+--------+-------------+-------+
| id | alu_id | description | grade |
+----+--------+-------------+-------+
| 1 | 1 | teste | 2.2 |
| 2 | 1 | teste2 | 2.2 |
| 3 | 1 | fulano | 2.2 |
| 4 | 1 | fulano | 3 |
+----+--------+-------------+-------+
4 rows in set (0,00 sec)
mysql> select * from notas group by alu_id ;
+----+--------+-------------+-------+
| id | alu_id | description | grade |
+----+--------+-------------+-------+
| 1 | 1 | teste | 2.2 |
+----+--------+-------------+-------+
1 row in set (0,00 sec)
57
PHP e PostgreSQL
➢Comportamento no PostgreSQL:
fisl=> select * from notas;
id | alu_id | description | grade
----+--------+-------------+-------
2 | 1 | asdfasdfa | 5.5
3 | | asdfasdfa | 5.5
4 | 1 | fulano | 4.3
5 | 1 | fulano | 8
6 | 2 | ciclano | 9
(5 rows)
fisl=> select * from notas group by alu_id;
ERROR: column "notas.id" must appear in the GROUP BY clause or
be used in an aggregate function
58
PHP e PostgreSQL
fisl=> select alu_id,count(*) as total from notas group by alu_id;
alu_id | total
--------+-------
| 1
1 | 3
2 | 1
59
PHP e PostgreSQL
PostgreSQL no PHP
60
PHP PostgreSQL
pgsql extension
61
PHP e PostgreSQL
➢Similar a extensão mysql (depreciada):
<?php
pg_connect('host=localhost user=fisl dbname=fisl
password=123456');
$rs=pg_query("SELECT * FROM alunos");
$alunos=pg_fetch_all($rs);
print_r($alunos);
pg_close();
62
PHP e PostgreSQL
➢Suporta prepared statements:
<?php
$dbc=pg_connect('host=localhost user=fisl dbname=fisl password=123456');
$sql = 'INSERT INTO alunos(name) VALUES ($1)';
$params = array(
'william'
);
pg_prepare($dbc,'insertalunos', $sql);
pg_execute($dbc,'insertalunos', $params);
pg_close();
63
PHP e PostgreSQL
➢Chamadas assíncronas:
<?php
$dbc=pg_connect('host=localhost user=fisl dbname=fisl password=123456');
if(!pg_connection_busy($dbc)){
pg_send_query($dbc,'SELECT * FROM notas');
$result=pg_get_result($dbc);
}
$data= pg_fetch_all($result);
print_r($data);
pg_close($dbc);
64
PHP e PostgreSQL
PDO
65
PHP e PostgreSQL
➢Métodos idênticos ao MySQL:
<?php
$db = new PDO('pgsql:host=localhost;dbname=fisl','fisl','123456');
$result=$db->query('SELECT * FROM alunos');
$data=$result->fetchAll(PDO::FETCH_ASSOC);
print_r($data);
66
PHP e PostgreSQL
➢PDO::lastInsertId('nomedasequence'):
<?php
$db = new PDO('pgsql:host=localhost;dbname=fisl','fisl','123456');
$stmt=$db->prepare('INSERT INTO alunos(name) VALUES (?)');
$stmt->execute(array('Felipe'));
$id = $db->lastInsertId('alunos_id_seq');
echo $id;
67
PHP e PostgreSQL
➢Nome padrão das sequences: table_column_seq;
➢Como identificar o nome de uma sequence?
68
PHP e PostgreSQL
fisl=> d notas
Table "public.notas"
Column | Type | Modifiers
-------------+-------------------+----------------------------------------------------
id | integer | not null default nextval('notas_id_seq'::regclass)
alu_id | integer |
description | character varying |
grade | double precision | not null
Indexes:
"notas_pkey" PRIMARY KEY, btree (id)
Foreign-key constraints:
"notas_alu_id_fkey" FOREIGN KEY (alu_id) REFERENCES alunos(id)
69
Conclusão
➢Quando sua aplicação crescer:
➢Robusta;
➢Confiável;
➢Desempenho;
➢Escalável;
➢Segura.
70
Perguntas
71
Boa Sorte!!
72
William Felipe Welter
william.welter@4linux.com.br
www.4linux.com.br
www.4shot.com.br
Sigam-nos
@4linux
@4shotcursos

PHP e PostgreSQL - Dois Elefantes trabalham muito mais !

  • 1.
    PHP e PostgreSQL, DoisElefantes Trabalham muito mais! Nome William Felipe Welter Dez/2015
  • 2.
    2 # whoami ➢ Bacharelem Ciência da Computação; ➢ Gerente da equipe de desenvolvimento da 4Linux; ➢ Experiência com desenvolvimento (PHP e C) e infraestrutura. Nome William Felipe Welter
  • 3.
    3 Conhecendo a 4Linux ➢Metodologia IT Experience - Cenários reais ➢ Cursos práticos, rápidos e baratos de autores feras: www.4shot.com.br ➢ Projetos complexos de missão crítica, com infra e desenvolvimento PHP
  • 4.
    4 Alguns dos nossosclientes A 4Linux suporta o ecossistema de software livre da Caixa. Um dos maiores cases do mundo. Clientes que confiam na qualidade dos serviços da 4Linux.
  • 5.
    5 Cursos práticos, rápidose baratos de autores feras
  • 6.
  • 7.
  • 8.
  • 9.
    9 Por que, hoje,o PHP é tão ligado ao MySQL ? PHP e PostgreSQL
  • 10.
    10 PHP e PostgreSQL ➢Lançados juntos (PHP ~94 / MySQL ~95); ➢ MySQL tinha porte para Windows; ➢ PostgreSQL passou a ter porte para Windows a partir da versão 8.0 (2005); ➢ Não tinha integridade referencial (MyISAM); ➢ Pouca configuração; ➢ Maioria dos webhosts adotaram.
  • 11.
    11 PHP e PostgreSQL Porque você usa MySQL? Minha aplicação é pequena. Por isso, resolvi usar o MySQL. Quando crescer penso em outro banco...
  • 12.
    12 PHP e PostgreSQL Qualé o problema de mudar depois?
  • 13.
    13 PHP e PostgreSQL ➢Seusar extensões “mysql” , “mysqli”...
  • 14.
  • 15.
  • 16.
    16 PHP e PostgreSQL Porque não começar com o PostgreSQL?
  • 17.
    17 PHP e PostgreSQL Euuso o phpMyAdmin, como faço no PostgreSQL?
  • 18.
  • 19.
  • 20.
  • 21.
  • 22.
  • 23.
    23 PHP e PostgreSQL ➢Muitofácil; ➢Autocomplete (TAB); ➢History, ctrl+r (libreadline); ➢Meta Comandos; ➢Visão expandida ; ➢Editor externo.
  • 24.
    24 PHP e PostgreSQL ➢E,para modelar ? SQL PowerArchitect PgModeler
  • 25.
    25 PHP e PostgreSQL Mas,por que o PostgreSQL?
  • 26.
    26 PHP e PostgreSQL ➢Derivou,originalmente, do projeto Ingres; ➢Iniciou-se, em 1974, na universidade de Berkeley; ➢Outros projetos derivados: Sybase, SQL Server, NonStop SQL; ➢Linguagem SQL introduzida em 1994. Um pouco de história:
  • 27.
    27 PHP e PostgreSQL ➢Licençaé BSD-style; ➢Não tem uma empresa dona do projeto; ➢Projeto é livre! ➢Preza por estabilidade em favor de novas funcionalidades “da moda”; ➢Segue a risca ao padrão ANSI-SQL 2008. Principais características:
  • 28.
    28 PHP e PostgreSQL ➢Maduro; ➢Estável; ➢Seguepadrões! ➢Suporte independente de fornecedor! ➢Futuro do projeto não esta mão de uma única empresa. Primeiras conclusões:
  • 29.
  • 30.
  • 31.
    31 PHP e PostgreSQL ➢CPU: ➢Segundodocumentação 32 e 64 cores; ➢Experiência pessoal > 80 cores; ➢Memória: ➢Experiência pessoal 1TB; ➢Discos: ➢Tablespaces, RAID, LVM.
  • 32.
  • 33.
    33 PHP e PostgreSQL ➢Multicolunas; ➢Índicesparciais; ➢Índices baseados em expressões; ➢Index e Reindex, sem locks.
  • 34.
    34 PHP e PostgreSQL ➢b-tree (default): ➢ Numérico e textual ➢ Null/not null ➢ Like ➢ Hash: ➢ = ➢ Pequeno ➢ Corrompe fácil ➢ GIN: ➢ Estruturas complexas ➢ Arrays ➢ FTS ➢ GiST: ➢ Buscas além de intervalos e igualdade ➢ Operadores geométricos ➢ FTS ➢ SP-GiST: ➢ Arvore não balanceada ➢ CAD, data mining, GIS
  • 35.
  • 36.
    36 PHP e PostgreSQL ➢Baseadoem pesos (customizável); ➢Por tablespace; ➢Coletor de estatísticas; ➢Auto analyze; ➢Otimizador de busca genética.
  • 37.
    37 PHP e PostgreSQL ➢seqscan; ➢indexscan; ➢bitmapscan; ➢hashaggregate; ➢hash join; ➢merge join; ➢nested loop;
  • 38.
  • 39.
    39 PHP e PostgreSQL ➢Viewsmaterializadas: ➢Consultas complexas e lentas; ➢Reutilizadas; ➢Comporta-se com uma tabela quando utilizado em consultas; ➢Permite criação de índices; ➢Pode ser atualizada.
  • 40.
    40 PHP e PostgreSQL SEGURANÇA(CONTROLE DE ACESSO)
  • 41.
    41 PHP e PostgreSQL ➢Suportea grupos e herança de privilégios (ROLES); ➢Suporte a múltiplos schemas; ➢Autenticação baseada em hosts (HBA); ➢Suporta o PAM; ➢Bancos são completamente isolados; ➢Granularidade de privilégios.
  • 42.
  • 43.
    43 PHP e PostgreSQL ➢Dump: ➢Aquente, sem locks; ➢Textual ou binário; ➢O dump e restauração pode ser paralelizados; ➢PITR: ➢Backup continuo, a nível transacional; ➢A quente.
  • 44.
    44 PHP e PostgreSQL ➢Master-Slave; ➢Hot-standby; ➢Síncronaou Assíncrona; ➢Replicas em cascata; ➢Física e lógica*; ➢Novas replicas sem lock ou paradas. Replicação Nativa:
  • 45.
    45 PHP e PostgreSQL ➢Bucardo (Open Source): ➢ Multimaster; ➢ Lógica; ➢ Slony; ➢ Skytools; ➢ RepManager. Replicação, ferramentas externas:
  • 46.
  • 47.
  • 48.
    48 PHP e PostgreSQL GRANDEVARIEDADE DE TIPO DE DADOS
  • 49.
  • 50.
    50 PHP e PostgreSQL QUESTÕESCONHECIDAS DO MySQL
  • 51.
    51 PHP e PostgreSQL ➢Conversãoautomática de tipos: mysql> CREATE TABLE notas ( id integer primary key auto_increment, alu_id integer not null, description varchar(150), grade float not null ); mysql> INSERT INTO notas(alu_id,description,grade) VALUES ( 'fulano', 'Nota da primeira fase', 4.4); mysql> SELECT * FROM notas; +----+--------+-----------------------+-------+ | id | alu_id | description | grade | +----+--------+-----------------------+-------+ | 1 | 0 | Nota da primeira fase | 4.4 | +----+--------+-----------------------+-------+
  • 52.
    52 PHP e PostgreSQL mysql>CREATE TABLE answer ( id integer primary key, alu_id integer not null, answer varchar(100), date timestamp not null ) mysql> INSERT INTO answer ( alu_id,answer, date) VALUES (1,'Thi is ..','08/07/15'); mysql> SELECT * FROM answer; +----+--------+-----------+---------------------+ | id | alu_id | answer | date | +----+--------+-----------+---------------------+ | 0 | 1 | Thi is .. | 2008-07-15 00:00:00 | +----+--------+-----------+---------------------+
  • 53.
    53 PHP e PostgreSQL ➢< 5.6.7, perda de integridade referencial com alter table. ➢ => 5.6.7, bloqueia alter table em colunas com foreign key. mysql> CREATE TABLE notas ( id integer primary key auto_increment, alu_id integer, description varchar(150), grade float not null, constraint alu_id_fk foreign key (alu_id) references alunos(id) ); mysql> ALTER TABLE notas CHANGE alu_id alu_id integer not null; ERROR 1832 (HY000): Cannot change column 'alu_id': used in a foreign key constraint 'alu_id_fk'
  • 54.
    54 PHP e PostgreSQL ➢Comportamentono PostgreSQL: fisl=# CREATE TABLE notas ( id serial primary key, alu_id integer references alunos(id), description varchar, grade float not null ); fisl=# ALTER TABLE notas ALTER COLUMN alu_id SET not null; ALTER TABLE fisl=# ALTER TABLE notas ALTER COLUMN alu_id DROP not null; ALTER TABLE fisl=# INSERT INTO notas ( description, grade) VALUES ('asdfasdfa',5.5); INSERT 0 1 fisl=# ALTER TABLE notas ALTER COLUMN alu_id SET not null; ERROR: column "alu_id" contains null values
  • 55.
    55 PHP e PostgreSQL ➢Sintaxes não implementadas, são aceitas silenciosamente: mysql> create table notas ( id integer primary key auto_increment, alu_id integer references alunos(id), description varchar(150), grade float not null ); Query OK, 0 rows affected (0,59 sec) mysql> desc notas; +-------------+--------------+------+-----+---------+----------------+ | Field | Type | Null | Key | Default | Extra | +-------------+--------------+------+-----+---------+----------------+ | id | int(11) | NO | PRI | NULL | auto_increment | | alu_id | int(11) | YES | | NULL | | | description | varchar(150) | YES | | NULL | | | grade | float | NO | | NULL | | +-------------+--------------+------+-----+---------+----------------+
  • 56.
    56 PHP e PostgreSQL ➢GROUP BY, colunas sem agregação = resultado indeterminado: Ex3: mysql> select * from notas; +----+--------+-------------+-------+ | id | alu_id | description | grade | +----+--------+-------------+-------+ | 1 | 1 | teste | 2.2 | | 2 | 1 | teste2 | 2.2 | | 3 | 1 | fulano | 2.2 | | 4 | 1 | fulano | 3 | +----+--------+-------------+-------+ 4 rows in set (0,00 sec) mysql> select * from notas group by alu_id ; +----+--------+-------------+-------+ | id | alu_id | description | grade | +----+--------+-------------+-------+ | 1 | 1 | teste | 2.2 | +----+--------+-------------+-------+ 1 row in set (0,00 sec)
  • 57.
    57 PHP e PostgreSQL ➢Comportamentono PostgreSQL: fisl=> select * from notas; id | alu_id | description | grade ----+--------+-------------+------- 2 | 1 | asdfasdfa | 5.5 3 | | asdfasdfa | 5.5 4 | 1 | fulano | 4.3 5 | 1 | fulano | 8 6 | 2 | ciclano | 9 (5 rows) fisl=> select * from notas group by alu_id; ERROR: column "notas.id" must appear in the GROUP BY clause or be used in an aggregate function
  • 58.
    58 PHP e PostgreSQL fisl=>select alu_id,count(*) as total from notas group by alu_id; alu_id | total --------+------- | 1 1 | 3 2 | 1
  • 59.
  • 60.
  • 61.
    61 PHP e PostgreSQL ➢Similara extensão mysql (depreciada): <?php pg_connect('host=localhost user=fisl dbname=fisl password=123456'); $rs=pg_query("SELECT * FROM alunos"); $alunos=pg_fetch_all($rs); print_r($alunos); pg_close();
  • 62.
    62 PHP e PostgreSQL ➢Suportaprepared statements: <?php $dbc=pg_connect('host=localhost user=fisl dbname=fisl password=123456'); $sql = 'INSERT INTO alunos(name) VALUES ($1)'; $params = array( 'william' ); pg_prepare($dbc,'insertalunos', $sql); pg_execute($dbc,'insertalunos', $params); pg_close();
  • 63.
    63 PHP e PostgreSQL ➢Chamadasassíncronas: <?php $dbc=pg_connect('host=localhost user=fisl dbname=fisl password=123456'); if(!pg_connection_busy($dbc)){ pg_send_query($dbc,'SELECT * FROM notas'); $result=pg_get_result($dbc); } $data= pg_fetch_all($result); print_r($data); pg_close($dbc);
  • 64.
  • 65.
    65 PHP e PostgreSQL ➢Métodosidênticos ao MySQL: <?php $db = new PDO('pgsql:host=localhost;dbname=fisl','fisl','123456'); $result=$db->query('SELECT * FROM alunos'); $data=$result->fetchAll(PDO::FETCH_ASSOC); print_r($data);
  • 66.
    66 PHP e PostgreSQL ➢PDO::lastInsertId('nomedasequence'): <?php $db= new PDO('pgsql:host=localhost;dbname=fisl','fisl','123456'); $stmt=$db->prepare('INSERT INTO alunos(name) VALUES (?)'); $stmt->execute(array('Felipe')); $id = $db->lastInsertId('alunos_id_seq'); echo $id;
  • 67.
    67 PHP e PostgreSQL ➢Nomepadrão das sequences: table_column_seq; ➢Como identificar o nome de uma sequence?
  • 68.
    68 PHP e PostgreSQL fisl=>d notas Table "public.notas" Column | Type | Modifiers -------------+-------------------+---------------------------------------------------- id | integer | not null default nextval('notas_id_seq'::regclass) alu_id | integer | description | character varying | grade | double precision | not null Indexes: "notas_pkey" PRIMARY KEY, btree (id) Foreign-key constraints: "notas_alu_id_fkey" FOREIGN KEY (alu_id) REFERENCES alunos(id)
  • 69.
    69 Conclusão ➢Quando sua aplicaçãocrescer: ➢Robusta; ➢Confiável; ➢Desempenho; ➢Escalável; ➢Segura.
  • 70.
  • 71.
  • 72.