SlideShare ist ein Scribd-Unternehmen logo
1 von 34
Downloaden Sie, um offline zu lesen
Gabriela D’Ávila

@gabidavila



Outubro/2016
MySQL 5.7

Tirando o Máximo Proveito
Quem?
• Data Engineer

• Desenvolvedora por 8 anos

• Palestrante ocasional

• @gabidavila

• http://gabriela.io
• Alterações em tempo real de DDL no InnoDB

• JSON
• Colunas Geradas (Generated Columns)

• `sys` schema
O Que Esperar?
3
Alterações em tempo real
de DDL
• In Place
(ALGORITHM=INPLACE)

• Renomear índices

• VARCHAR de 1b para 255b*

• Adicionar uma coluna virtual

• Table-copy
(ALGORITHM=COPY)

• VARCHAR de 256b para
65535b*

• Adicionar colunas

• Conversão de tipos
Online DDL
5
* Depende de encoding da tabela e coluna, para latin1
seriam 255 caracteres, para utf8 seriam até 63 caracteres
JSON
• Armazenamento é binário no banco de dados

• É possível converter campos TEXT se JSON_VALID() retorna
TRUE para toda a tabela

• Conversão de TEXT para JSON é uma operação COPY

• É impossível de se armazenar um JSON inválido

• Colunas do tipo JSON não podem ter um valor DEFAULT
• Índices são possíveis devido à Generated Columns
Recursos
7
Tabela `twitter_users`
8
Field Type Null Key Default Extra
id int(11) NO PRI auto_increment
id_str varchar(255) NO UNI
screen_name varchar(255) NO INDEX
response json YES
created_at datetime NO CURRENT_TIMESTAMP
updated_at datetime NO CURRENT_TIMESTAMP
on update
CURRENT_TIMESTAMP
CREATE TABLE `twitter_users` (
`id` INT(11) NOT NULL AUTO_INCREMENT,
`id_str` VARCHAR(255) NOT NULL,
`screen_name` VARCHAR(255) NOT NULL,
`response` JSON NOT NULL,
`created_at` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
`updated_at` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
PRIMARY KEY (`id`),
UNIQUE KEY `un_id_str` (`id_str`),
KEY `id_str` (`id_str`),
KEY `ix_screen_name` (`screen_name`)
)
ENGINE = InnoDB
DEFAULT CHARSET = utf8mb4
@PHPesteNE
9
SELECT response FROM `twitter_users` WHERE `screen_name` = 'PHPesteNE';
{
"id": 3331483283,
"url": "http://t.co/vKElFb77Te",
"lang": "pt",
"name": "PHPeste",
"id_str": "3331483283",
"profile_image_url": "http://pbs.twimg.com/profile_images/621823785025564673/64yvbfWw_normal.jpg",
"profile_banner_url": "https://pbs.twimg.com/profile_banners/3331483283/1470600499",
"location": "Salvador, Brasil",
"verified": false,
"following": true,
"protected": false,
"time_zone": "Brasilia",
"created_at": "Wed Jun 17 16:33:34 +0000 2015",
"utc_offset": -10800,
"description": "PHP Conference Northeast Brazil.",
"geo_enabled": true,
"screen_name": "phpestene",
"listed_count": 15,
"friends_count": 314,
"statuses_count": 186,
"default_profile": true,
"followers_count": 318,
"favourites_count": 166,
"profile_link_color": "0084B4",
"profile_text_color": "333333",
"profile_image_url_https": "https://pbs.twimg.com/profile_images/621823785025564673/64yvbfWw_normal.jpg",
"profile_background_color": "C0DEED",
"profile_sidebar_fill_color": "DDEEF6",
"profile_background_image_url": "http://abs.twimg.com/images/themes/theme1/bg.png",
"profile_sidebar_border_color": "C0DEED",
"profile_use_background_image": true,
"profile_background_image_url_https": "https://abs.twimg.com/images/themes/theme1/bg.png"
}
Exemplos
• Usando json_extract(json_column, “$.path”)
Acessando Valores
11
SELECT
screen_name,
json_extract(response,"$.location")
FROM `twitter_users`
LIMIT 5;
-- Results
-- +---------------+------------------------------+
-- | screen_name | location |
-- +---------------+------------------------------+
-- | wimgtr | "Belgium" |
-- | wilw | "Los Angeles" |
-- | n0x13 | "Amsterdam, The Netherlands" |
-- | stoker | "DFW Texas" |
-- | anthonyjuanes | "Exeter" |
-- +---------------+------------------------------+
-- 5 rows in set (0.00 sec)
• Valores extraídos estarão sempre com aspas e contra-barra
• Usando o atalho json_column->“$.path”
Acessando Valores
12
SELECT
screen_name,
response->"$.location" AS location
FROM `twitter_users`
LIMIT 5;
-- Results
-- +---------------+------------------------------+
-- | screen_name | location |
-- +---------------+------------------------------+
-- | wimgtr | "Belgium" |
-- | wilw | "Los Angeles" |
-- | n0x13 | "Amsterdam, The Netherlands" |
-- | stoker | "DFW Texas" |
-- | anthonyjuanes | "Exeter" |
-- +---------------+------------------------------+
-- 5 rows in set (0.00 sec)
• Valores extraídos estarão sempre com aspas e contra-barra
Acessando e escapando Valores
13
• Usando a função

• json_unquote(json_extract(json_column, “$.path”))

• Usando o atalho:

• json_column->>“$.path”
SELECT
screen_name,
json_extract(response, "$.status.source") AS location,
json_unquote(json_extract(response, "$.status.source")) AS esc_loc,
response->"$.status.source" AS source,
response->>"$.status.source" AS esc_source
FROM `twitter_users`
LIMIT 2;
-- Resultado
--
-- *************************** 1. row ***************************
-- screen_name: wimgtr
-- location: "<a href="https://about.twitter.com/products/tweetdeck" rel="nofollow">TweetDeck</a>"
-- esc_loc: <a href="https://about.twitter.com/products/tweetdeck" rel="nofollow">TweetDeck</a>
-- source: "<a href="https://about.twitter.com/products/tweetdeck" rel="nofollow">TweetDeck</a>"
-- esc_source: <a href="https://about.twitter.com/products/tweetdeck" rel="nofollow">TweetDeck</a>
-- *************************** 2. row ***************************
-- screen_name: wilw
-- location: "<a href="http://twitter.com" rel="nofollow">Twitter Web Client</a>"
-- esc_loc: <a href="http://twitter.com" rel="nofollow">Twitter Web Client</a>
-- source: "<a href="http://twitter.com" rel="nofollow">Twitter Web Client</a>"
-- esc_source: <a href="http://twitter.com" rel="nofollow">Twitter Web Client</a>
-- 2 rows in set (0.00 sec)
Funções suportadas
• JSON_ARRAY()
• JSON_ARRAY_APPEND()
• JSON_ARRAY_INSERT()
• JSON_ARRAY_APPEND()
• JSON_ARRAY_INSERT()
• JSON_CONTAINS()
• JSON_CONTAINS_PATH()
• JSON_DEPTH()
• JSON_EXTRACT() or ->
• JSON_INSERT()
• JSON_KEYS()
• JSON_LENGTH()
• JSON_MERGE()
• JSON_OBJECT()
• JSON_QUOTE()
• JSON_REMOVE()
• JSON_REPLACE()
• JSON_SEARCH()
• JSON_SET()
• JSON_TYPE()
• JSON_UNQUOTE() or ->>
• JSON_VALID()
Manipulação de JSON
16
Colunas Geradas

(Generated Columns)
• Não ocupa espaço em disco

• A criação é INPLACE

• O valor da coluna é gerado em tempo real

• Chamado quando uma trigger de evento BEFORE é chamada
Virtual Columns
18
• Ocupa espaço em disco

• Valor atualizado para cada operação de escrita (INSERT, UPDATE)

• Usa o algoritmo COPY para criação e remoção da coluna
Stored Columns
19
• Ambas podem ser indexadas

• Permitem que expressões como essas sejam usadas:

• Operadores ( +, -, *, /, etc)

• Funções nativas (LEFT(), SUBSTR(), JSON_EXTRACT(), etc)

• Literais (‘novo’, 2, etc)

• Subqueries não são suportadas
Virtual and Stored Columns
20
Exemplos
-- Total rows
SELECT COUNT(*) FROM `twitter_users`;
-- 8906 rows
-- Virtual Columns
ALTER TABLE `twitter_users`
ADD COLUMN `profile_image_url` VARCHAR(255)
GENERATED ALWAYS AS (response->>"$.profile_image_url");
-- [2016-10-04 14:16:24] completed in 46ms
-- Stored Columns
ALTER TABLE `twitter_users`
ADD COLUMN `location` VARCHAR(255)
GENERATED ALWAYS AS (response->>"$.location") STORED
ADD INDEX `ix_location` (`location`);
-- [2016-10-04 14:20:09] 8906 rows affected in 2s 689ms
Tabela `twitter_users`
23
Field Type Null Key Default Extra
id int(11) NO PRI auto_increment
id_str varchar(255) NO UNI
screen_name varchar(255) NO INDEX
response json YES
location varchar(255) YES INDEX STORED GENERATED
profile_image_url varchar(255) YES VIRTUAL GENERATED
created_at datetime NO CURRENT_TIMESTAMP
updated_at datetime NO CURRENT_TIMESTAMP
on update
CURRENT_TIMESTAMP
Busca
24
SELECT screen_name, location, profile_image_url FROM `twitter_users`
WHERE location LIKE "%Brasil%" LIMIT 5;
-- Results
-- +---------------+-----------------------+----------------------------+
-- | screen_name | location | profile_image_url |
-- +---------------+-----------------------+----------------------------+
-- | hussanii | Brasil | http://pbs.twimg.com/(...) |
-- | fplcampos | São Paulo, Brasil | http://pbs.twimg.com/(...) |
-- | ivanrosolen | Sampa - Brasil | http://pbs.twimg.com/(...) |
-- | rogeriopradoj | Brasil, São Paulo, SP | http://pbs.twimg.com/(...) |
-- | rafinhabastos | Brasil | http://pbs.twimg.com/(...) |
-- +---------------+-----------------------+----------------------------+
-- 5 rows in set (0.00 sec)
`sys` schema
• Precisa ser instalado na versão 5.6

• Instalado por padrão no 5.7

• MySQL Workbench vem com um cliente

• Em produção é recomendado apenas estar ativado em casos
críticos
MySQL `sys` schema
26
SELECT * FROM
29
Description Table
*High Cost SQL statements sys.`x$statement_analysis`
*Top 5% slower queries sys.`x$statements_with_runtimes_in_95th_percentile`
Use temporary tables sys.`statements_with_temp_tables`
Unused Indexes sys.`schema_unused_indexes`
Full table scans sys.`schema_tables_with_full_table_scans`
*x$ é um prefixo para views criadas para um formato mais amigável ao usuário
Demais Alterações
• `sql_mode` agora é mais estrito e os seguintes modos vêm
habilitados por padrão:

• ONLY_FULL_GROUP_BY
• NO_ZERO_DATE
• NO_ZERO_IN_DATE
• ERROR_FOR_DIVISION_BY_ZERO
Demais Alterações
32
• Senhas agora podem ter uma data de expiração

• Tabelas agora suportam mais de uma trigger pro mesmo evento

• Alterações em YEAR(2):

• marcado como deprecated na 5.6

• removido na 5.7
33
Demais Alterações
• Twitter: @gabidavila

• Blog: http://gabriela.io

• Freenode: gabidavila

• References: MySQL documentation
Obrigada!
34

Weitere ähnliche Inhalte

Was ist angesagt?

Turbinando o desenvolvimento Android com Kotlin
Turbinando o desenvolvimento Android com KotlinTurbinando o desenvolvimento Android com Kotlin
Turbinando o desenvolvimento Android com KotlinNelson Glauber Leal
 
Minicurso sobre AndroidAnnotations, GreenDAO, EventBus e Crouton
Minicurso sobre AndroidAnnotations, GreenDAO, EventBus e CroutonMinicurso sobre AndroidAnnotations, GreenDAO, EventBus e Crouton
Minicurso sobre AndroidAnnotations, GreenDAO, EventBus e CroutonRicardo Longa
 
Mongo DB
Mongo DBMongo DB
Mongo DBdist_bp
 
Elasticsearch: Motor de busca e além. Lições aprendidas criando Tu Próximo...
Elasticsearch: Motor de busca e além. Lições aprendidas criando Tu Próximo...Elasticsearch: Motor de busca e além. Lições aprendidas criando Tu Próximo...
Elasticsearch: Motor de busca e além. Lições aprendidas criando Tu Próximo...Miguel Gallardo
 
BigData - ElasticSearch + PHP
BigData - ElasticSearch + PHPBigData - ElasticSearch + PHP
BigData - ElasticSearch + PHPFelipe Weckx
 
Mini-Curso de MongoDB
Mini-Curso de MongoDBMini-Curso de MongoDB
Mini-Curso de MongoDBBrunno Gomes
 
PHPubSP Object Calisthenics aplicado ao PHP
PHPubSP Object Calisthenics aplicado ao PHPPHPubSP Object Calisthenics aplicado ao PHP
PHPubSP Object Calisthenics aplicado ao PHPGuilherme Blanco
 
Hands-on Workshop: Como configurar e utilizar uma estrutura MongoDB para Big ...
Hands-on Workshop: Como configurar e utilizar uma estrutura MongoDB para Big ...Hands-on Workshop: Como configurar e utilizar uma estrutura MongoDB para Big ...
Hands-on Workshop: Como configurar e utilizar uma estrutura MongoDB para Big ...Big Data Week São Paulo
 
Desenvolvimento de aplicações PHP com MongoDB
Desenvolvimento de aplicações PHP com MongoDBDesenvolvimento de aplicações PHP com MongoDB
Desenvolvimento de aplicações PHP com MongoDBAri Stopassola Junior
 
Lazy Evaluation em Scala
Lazy Evaluation em ScalaLazy Evaluation em Scala
Lazy Evaluation em Scalapmatiello
 
Modelando aplicação em documento - MongoDB
Modelando aplicação em documento - MongoDBModelando aplicação em documento - MongoDB
Modelando aplicação em documento - MongoDBThiago Avelino
 
MongoDB - Tudo o que você precisa saber
MongoDB - Tudo o que você precisa saberMongoDB - Tudo o que você precisa saber
MongoDB - Tudo o que você precisa saberChristiano Anderson
 
Minicurso Epoca mongoDB
Minicurso Epoca mongoDBMinicurso Epoca mongoDB
Minicurso Epoca mongoDBLelyBarros
 

Was ist angesagt? (20)

Turbinando o desenvolvimento Android com Kotlin
Turbinando o desenvolvimento Android com KotlinTurbinando o desenvolvimento Android com Kotlin
Turbinando o desenvolvimento Android com Kotlin
 
Minicurso sobre AndroidAnnotations, GreenDAO, EventBus e Crouton
Minicurso sobre AndroidAnnotations, GreenDAO, EventBus e CroutonMinicurso sobre AndroidAnnotations, GreenDAO, EventBus e Crouton
Minicurso sobre AndroidAnnotations, GreenDAO, EventBus e Crouton
 
NoSQL e MongoDB - ETEC
NoSQL e MongoDB - ETECNoSQL e MongoDB - ETEC
NoSQL e MongoDB - ETEC
 
Treinamento Elasticsearch - Parte 2
Treinamento Elasticsearch - Parte 2Treinamento Elasticsearch - Parte 2
Treinamento Elasticsearch - Parte 2
 
Mongo DB
Mongo DBMongo DB
Mongo DB
 
Elasticsearch: Motor de busca e além. Lições aprendidas criando Tu Próximo...
Elasticsearch: Motor de busca e além. Lições aprendidas criando Tu Próximo...Elasticsearch: Motor de busca e além. Lições aprendidas criando Tu Próximo...
Elasticsearch: Motor de busca e além. Lições aprendidas criando Tu Próximo...
 
MongoDB - Iniciando e Conhecendo
MongoDB - Iniciando e ConhecendoMongoDB - Iniciando e Conhecendo
MongoDB - Iniciando e Conhecendo
 
BigData - ElasticSearch + PHP
BigData - ElasticSearch + PHPBigData - ElasticSearch + PHP
BigData - ElasticSearch + PHP
 
#5 CRUD no MongoDB
#5   CRUD  no MongoDB#5   CRUD  no MongoDB
#5 CRUD no MongoDB
 
Sql proficiente
Sql proficienteSql proficiente
Sql proficiente
 
Mini-Curso de MongoDB
Mini-Curso de MongoDBMini-Curso de MongoDB
Mini-Curso de MongoDB
 
PHPubSP Object Calisthenics aplicado ao PHP
PHPubSP Object Calisthenics aplicado ao PHPPHPubSP Object Calisthenics aplicado ao PHP
PHPubSP Object Calisthenics aplicado ao PHP
 
Hands-on Workshop: Como configurar e utilizar uma estrutura MongoDB para Big ...
Hands-on Workshop: Como configurar e utilizar uma estrutura MongoDB para Big ...Hands-on Workshop: Como configurar e utilizar uma estrutura MongoDB para Big ...
Hands-on Workshop: Como configurar e utilizar uma estrutura MongoDB para Big ...
 
Desenvolvimento de aplicações PHP com MongoDB
Desenvolvimento de aplicações PHP com MongoDBDesenvolvimento de aplicações PHP com MongoDB
Desenvolvimento de aplicações PHP com MongoDB
 
Lazy Evaluation em Scala
Lazy Evaluation em ScalaLazy Evaluation em Scala
Lazy Evaluation em Scala
 
Modelando aplicação em documento - MongoDB
Modelando aplicação em documento - MongoDBModelando aplicação em documento - MongoDB
Modelando aplicação em documento - MongoDB
 
MongoDB - Tudo o que você precisa saber
MongoDB - Tudo o que você precisa saberMongoDB - Tudo o que você precisa saber
MongoDB - Tudo o que você precisa saber
 
Minicurso Epoca mongoDB
Minicurso Epoca mongoDBMinicurso Epoca mongoDB
Minicurso Epoca mongoDB
 
Mongo + php
Mongo + phpMongo + php
Mongo + php
 
2011 01-18 mongo-db
2011 01-18 mongo-db2011 01-18 mongo-db
2011 01-18 mongo-db
 

Andere mochten auch

Strip your TEXT fields - Exeter Web Feb/2016
Strip your TEXT fields - Exeter Web Feb/2016Strip your TEXT fields - Exeter Web Feb/2016
Strip your TEXT fields - Exeter Web Feb/2016Gabriela Ferrara
 
Sharding using MySQL and PHP
Sharding using MySQL and PHPSharding using MySQL and PHP
Sharding using MySQL and PHPMats Kindahl
 
Exploring MongoDB & Elasticsearch: Better Together
Exploring MongoDB & Elasticsearch: Better TogetherExploring MongoDB & Elasticsearch: Better Together
Exploring MongoDB & Elasticsearch: Better TogetherObjectRocket
 
MySQL Sharding: Tools and Best Practices for Horizontal Scaling
MySQL Sharding: Tools and Best Practices for Horizontal ScalingMySQL Sharding: Tools and Best Practices for Horizontal Scaling
MySQL Sharding: Tools and Best Practices for Horizontal ScalingMats Kindahl
 
Inexpensive Datamasking for MySQL with ProxySQL — Data Anonymization for Deve...
Inexpensive Datamasking for MySQL with ProxySQL — Data Anonymization for Deve...Inexpensive Datamasking for MySQL with ProxySQL — Data Anonymization for Deve...
Inexpensive Datamasking for MySQL with ProxySQL — Data Anonymization for Deve...Ontico
 
Coding like a girl - DjangoCon
Coding like a girl - DjangoConCoding like a girl - DjangoCon
Coding like a girl - DjangoConGabriela Ferrara
 
Ora mysql bothGetting the best of both worlds with Oracle 11g and MySQL Enter...
Ora mysql bothGetting the best of both worlds with Oracle 11g and MySQL Enter...Ora mysql bothGetting the best of both worlds with Oracle 11g and MySQL Enter...
Ora mysql bothGetting the best of both worlds with Oracle 11g and MySQL Enter...Ivan Zoratti
 
MySQL Cluster Whats New
MySQL Cluster Whats NewMySQL Cluster Whats New
MySQL Cluster Whats NewMark Swarbrick
 
The MySQL Server Ecosystem in 2016
The MySQL Server Ecosystem in 2016The MySQL Server Ecosystem in 2016
The MySQL Server Ecosystem in 2016Colin Charles
 
[스마트스터디]MongoDB 의 역습
[스마트스터디]MongoDB 의 역습[스마트스터디]MongoDB 의 역습
[스마트스터디]MongoDB 의 역습smartstudy_official
 
MySQL Enterprise Cloud
MySQL Enterprise Cloud MySQL Enterprise Cloud
MySQL Enterprise Cloud Mark Swarbrick
 
Building Scalable High Availability Systems using MySQL Fabric
Building Scalable High Availability Systems using MySQL FabricBuilding Scalable High Availability Systems using MySQL Fabric
Building Scalable High Availability Systems using MySQL FabricMats Kindahl
 
SunshinePHP 2017 - Making the most out of MySQL
SunshinePHP 2017 - Making the most out of MySQLSunshinePHP 2017 - Making the most out of MySQL
SunshinePHP 2017 - Making the most out of MySQLGabriela Ferrara
 
LAMP: Desenvolvendo além do trivial
LAMP: Desenvolvendo além do trivialLAMP: Desenvolvendo além do trivial
LAMP: Desenvolvendo além do trivialGabriela Ferrara
 
20171104 hk-py con-mysql-documentstore_v1
20171104 hk-py con-mysql-documentstore_v120171104 hk-py con-mysql-documentstore_v1
20171104 hk-py con-mysql-documentstore_v1Ivan Ma
 
Webinar slides: How to automate and manage MongoDB & Percona Server for MongoDB
Webinar slides: How to automate and manage MongoDB & Percona Server for MongoDBWebinar slides: How to automate and manage MongoDB & Percona Server for MongoDB
Webinar slides: How to automate and manage MongoDB & Percona Server for MongoDBSeveralnines
 

Andere mochten auch (20)

Strip your TEXT fields - Exeter Web Feb/2016
Strip your TEXT fields - Exeter Web Feb/2016Strip your TEXT fields - Exeter Web Feb/2016
Strip your TEXT fields - Exeter Web Feb/2016
 
Sharding using MySQL and PHP
Sharding using MySQL and PHPSharding using MySQL and PHP
Sharding using MySQL and PHP
 
Exploring MongoDB & Elasticsearch: Better Together
Exploring MongoDB & Elasticsearch: Better TogetherExploring MongoDB & Elasticsearch: Better Together
Exploring MongoDB & Elasticsearch: Better Together
 
MySQL Sharding: Tools and Best Practices for Horizontal Scaling
MySQL Sharding: Tools and Best Practices for Horizontal ScalingMySQL Sharding: Tools and Best Practices for Horizontal Scaling
MySQL Sharding: Tools and Best Practices for Horizontal Scaling
 
Inexpensive Datamasking for MySQL with ProxySQL — Data Anonymization for Deve...
Inexpensive Datamasking for MySQL with ProxySQL — Data Anonymization for Deve...Inexpensive Datamasking for MySQL with ProxySQL — Data Anonymization for Deve...
Inexpensive Datamasking for MySQL with ProxySQL — Data Anonymization for Deve...
 
Coding like a girl - DjangoCon
Coding like a girl - DjangoConCoding like a girl - DjangoCon
Coding like a girl - DjangoCon
 
Strip your TEXT fields
Strip your TEXT fieldsStrip your TEXT fields
Strip your TEXT fields
 
MEAN Stack
MEAN StackMEAN Stack
MEAN Stack
 
Ora mysql bothGetting the best of both worlds with Oracle 11g and MySQL Enter...
Ora mysql bothGetting the best of both worlds with Oracle 11g and MySQL Enter...Ora mysql bothGetting the best of both worlds with Oracle 11g and MySQL Enter...
Ora mysql bothGetting the best of both worlds with Oracle 11g and MySQL Enter...
 
Laravel 5 and SOLID
Laravel 5 and SOLIDLaravel 5 and SOLID
Laravel 5 and SOLID
 
MySQL Cluster Whats New
MySQL Cluster Whats NewMySQL Cluster Whats New
MySQL Cluster Whats New
 
The MySQL Server Ecosystem in 2016
The MySQL Server Ecosystem in 2016The MySQL Server Ecosystem in 2016
The MySQL Server Ecosystem in 2016
 
[스마트스터디]MongoDB 의 역습
[스마트스터디]MongoDB 의 역습[스마트스터디]MongoDB 의 역습
[스마트스터디]MongoDB 의 역습
 
MySQL Enterprise Cloud
MySQL Enterprise Cloud MySQL Enterprise Cloud
MySQL Enterprise Cloud
 
Building Scalable High Availability Systems using MySQL Fabric
Building Scalable High Availability Systems using MySQL FabricBuilding Scalable High Availability Systems using MySQL Fabric
Building Scalable High Availability Systems using MySQL Fabric
 
SunshinePHP 2017 - Making the most out of MySQL
SunshinePHP 2017 - Making the most out of MySQLSunshinePHP 2017 - Making the most out of MySQL
SunshinePHP 2017 - Making the most out of MySQL
 
Mongodb
MongodbMongodb
Mongodb
 
LAMP: Desenvolvendo além do trivial
LAMP: Desenvolvendo além do trivialLAMP: Desenvolvendo além do trivial
LAMP: Desenvolvendo além do trivial
 
20171104 hk-py con-mysql-documentstore_v1
20171104 hk-py con-mysql-documentstore_v120171104 hk-py con-mysql-documentstore_v1
20171104 hk-py con-mysql-documentstore_v1
 
Webinar slides: How to automate and manage MongoDB & Percona Server for MongoDB
Webinar slides: How to automate and manage MongoDB & Percona Server for MongoDBWebinar slides: How to automate and manage MongoDB & Percona Server for MongoDB
Webinar slides: How to automate and manage MongoDB & Percona Server for MongoDB
 

Ähnlich wie MySQL 5.7 - 
Tirando o Máximo Proveito

Hibernate efetivo (IA-2014 / Disturbing the Mind)
Hibernate efetivo (IA-2014 / Disturbing the Mind)Hibernate efetivo (IA-2014 / Disturbing the Mind)
Hibernate efetivo (IA-2014 / Disturbing the Mind)Rafael Ponte
 
UNIFAL - MySQL 5.6 - Replicação
UNIFAL - MySQL 5.6 - ReplicaçãoUNIFAL - MySQL 5.6 - Replicação
UNIFAL - MySQL 5.6 - ReplicaçãoWagner Bianchi
 
Busca textual com solr e sunspot no rails
Busca textual com solr e sunspot no railsBusca textual com solr e sunspot no rails
Busca textual com solr e sunspot no railsMaurício Linhares
 
Migrations for Java (Javou #4 - JavaCE)
Migrations for Java (Javou #4 - JavaCE)Migrations for Java (Javou #4 - JavaCE)
Migrations for Java (Javou #4 - JavaCE)Rafael Ponte
 
Desenvolvendo aplicacoes mobile_com_html_css_
Desenvolvendo aplicacoes mobile_com_html_css_Desenvolvendo aplicacoes mobile_com_html_css_
Desenvolvendo aplicacoes mobile_com_html_css_Rodrigo Urubatan
 
QCon 2015 - Combinando AngularJS com Java EE
QCon 2015 - Combinando AngularJS com Java EEQCon 2015 - Combinando AngularJS com Java EE
QCon 2015 - Combinando AngularJS com Java EERodrigo Cândido da Silva
 
Tony\'s Top 10 Computer Forensics Artifacts
Tony\'s Top 10 Computer Forensics ArtifactsTony\'s Top 10 Computer Forensics Artifacts
Tony\'s Top 10 Computer Forensics Artifactstonyrodrigues
 
WebSocket com Node.js ( socketstream && coffeescript ) X RoR ( Juggernaut )
WebSocket com Node.js ( socketstream && coffeescript ) X RoR ( Juggernaut )WebSocket com Node.js ( socketstream && coffeescript ) X RoR ( Juggernaut )
WebSocket com Node.js ( socketstream && coffeescript ) X RoR ( Juggernaut )João Moura
 
QADscsssa sql clean extreme squery .pptx
QADscsssa sql clean extreme squery .pptxQADscsssa sql clean extreme squery .pptx
QADscsssa sql clean extreme squery .pptxEduardoGuambe2
 
MIRA - Um framework Javascript para construção de interfaces adaptativas em a...
MIRA - Um framework Javascript para construção de interfaces adaptativas em a...MIRA - Um framework Javascript para construção de interfaces adaptativas em a...
MIRA - Um framework Javascript para construção de interfaces adaptativas em a...Ezequiel Bertti
 
Edição de conteúdo web usando Javascript de ponta a ponta
Edição de conteúdo web usando Javascript de ponta a pontaEdição de conteúdo web usando Javascript de ponta a ponta
Edição de conteúdo web usando Javascript de ponta a pontaJorge Walendowsky
 
JavaOne LATAM 2016 - Combinando AngularJS com Java EE
JavaOne LATAM 2016 - Combinando AngularJS com Java EEJavaOne LATAM 2016 - Combinando AngularJS com Java EE
JavaOne LATAM 2016 - Combinando AngularJS com Java EERodrigo Cândido da Silva
 
De a máxima cobertura nos seus testes de API
De a máxima cobertura nos seus testes de APIDe a máxima cobertura nos seus testes de API
De a máxima cobertura nos seus testes de APIElias Nogueira
 
Arquitetando Soluções de Dados com PostgreSQL
Arquitetando Soluções de Dados com PostgreSQLArquitetando Soluções de Dados com PostgreSQL
Arquitetando Soluções de Dados com PostgreSQLRaul Oliveira
 
Do Rest Ao Restfull - Rio Jug
Do Rest Ao Restfull - Rio JugDo Rest Ao Restfull - Rio Jug
Do Rest Ao Restfull - Rio JugSergio Azevedo
 
Migrations for Java (QCONSP2013)
Migrations for Java (QCONSP2013)Migrations for Java (QCONSP2013)
Migrations for Java (QCONSP2013)Rafael Ponte
 
Funcionalidades de Acesso a Dados no 'Mango'
Funcionalidades de Acesso a Dados no 'Mango'Funcionalidades de Acesso a Dados no 'Mango'
Funcionalidades de Acesso a Dados no 'Mango'C. Augusto Proiete
 

Ähnlich wie MySQL 5.7 - 
Tirando o Máximo Proveito (20)

Hibernate efetivo (IA-2014 / Disturbing the Mind)
Hibernate efetivo (IA-2014 / Disturbing the Mind)Hibernate efetivo (IA-2014 / Disturbing the Mind)
Hibernate efetivo (IA-2014 / Disturbing the Mind)
 
UNIFAL - MySQL 5.6 - Replicação
UNIFAL - MySQL 5.6 - ReplicaçãoUNIFAL - MySQL 5.6 - Replicação
UNIFAL - MySQL 5.6 - Replicação
 
Busca textual com solr e sunspot no rails
Busca textual com solr e sunspot no railsBusca textual com solr e sunspot no rails
Busca textual com solr e sunspot no rails
 
Migrations for Java (Javou #4 - JavaCE)
Migrations for Java (Javou #4 - JavaCE)Migrations for Java (Javou #4 - JavaCE)
Migrations for Java (Javou #4 - JavaCE)
 
GUJavaSC - Combinando AngularJS com Java EE
GUJavaSC - Combinando AngularJS com Java EEGUJavaSC - Combinando AngularJS com Java EE
GUJavaSC - Combinando AngularJS com Java EE
 
Circuito_OpenLDAP
Circuito_OpenLDAPCircuito_OpenLDAP
Circuito_OpenLDAP
 
Desenvolvendo aplicacoes mobile_com_html_css_
Desenvolvendo aplicacoes mobile_com_html_css_Desenvolvendo aplicacoes mobile_com_html_css_
Desenvolvendo aplicacoes mobile_com_html_css_
 
QCon 2015 - Combinando AngularJS com Java EE
QCon 2015 - Combinando AngularJS com Java EEQCon 2015 - Combinando AngularJS com Java EE
QCon 2015 - Combinando AngularJS com Java EE
 
Tony\'s Top 10 Computer Forensics Artifacts
Tony\'s Top 10 Computer Forensics ArtifactsTony\'s Top 10 Computer Forensics Artifacts
Tony\'s Top 10 Computer Forensics Artifacts
 
WebSocket com Node.js ( socketstream && coffeescript ) X RoR ( Juggernaut )
WebSocket com Node.js ( socketstream && coffeescript ) X RoR ( Juggernaut )WebSocket com Node.js ( socketstream && coffeescript ) X RoR ( Juggernaut )
WebSocket com Node.js ( socketstream && coffeescript ) X RoR ( Juggernaut )
 
QADscsssa sql clean extreme squery .pptx
QADscsssa sql clean extreme squery .pptxQADscsssa sql clean extreme squery .pptx
QADscsssa sql clean extreme squery .pptx
 
MIRA - Um framework Javascript para construção de interfaces adaptativas em a...
MIRA - Um framework Javascript para construção de interfaces adaptativas em a...MIRA - Um framework Javascript para construção de interfaces adaptativas em a...
MIRA - Um framework Javascript para construção de interfaces adaptativas em a...
 
Edição de conteúdo web usando Javascript de ponta a ponta
Edição de conteúdo web usando Javascript de ponta a pontaEdição de conteúdo web usando Javascript de ponta a ponta
Edição de conteúdo web usando Javascript de ponta a ponta
 
JavaOne LATAM 2016 - Combinando AngularJS com Java EE
JavaOne LATAM 2016 - Combinando AngularJS com Java EEJavaOne LATAM 2016 - Combinando AngularJS com Java EE
JavaOne LATAM 2016 - Combinando AngularJS com Java EE
 
De a máxima cobertura nos seus testes de API
De a máxima cobertura nos seus testes de APIDe a máxima cobertura nos seus testes de API
De a máxima cobertura nos seus testes de API
 
Arquitetando Soluções de Dados com PostgreSQL
Arquitetando Soluções de Dados com PostgreSQLArquitetando Soluções de Dados com PostgreSQL
Arquitetando Soluções de Dados com PostgreSQL
 
Do Rest Ao Restfull - Rio Jug
Do Rest Ao Restfull - Rio JugDo Rest Ao Restfull - Rio Jug
Do Rest Ao Restfull - Rio Jug
 
Migrations for Java (QCONSP2013)
Migrations for Java (QCONSP2013)Migrations for Java (QCONSP2013)
Migrations for Java (QCONSP2013)
 
Ruby On Rails Regis
Ruby On Rails RegisRuby On Rails Regis
Ruby On Rails Regis
 
Funcionalidades de Acesso a Dados no 'Mango'
Funcionalidades de Acesso a Dados no 'Mango'Funcionalidades de Acesso a Dados no 'Mango'
Funcionalidades de Acesso a Dados no 'Mango'
 

Mehr von Gabriela Ferrara

GRONINGEN PHP - MySQL 8.0 , not only good, great
GRONINGEN PHP - MySQL 8.0 , not only good, greatGRONINGEN PHP - MySQL 8.0 , not only good, great
GRONINGEN PHP - MySQL 8.0 , not only good, greatGabriela Ferrara
 
Serverless and you @ Women Who Code London 2020
Serverless and you  @ Women Who Code London 2020Serverless and you  @ Women Who Code London 2020
Serverless and you @ Women Who Code London 2020Gabriela Ferrara
 
Serverless and you - where do i run my stateless code
Serverless and you  - where do i run my stateless codeServerless and you  - where do i run my stateless code
Serverless and you - where do i run my stateless codeGabriela Ferrara
 
PHPDay 2019 - MySQL 8, not only good, great!
PHPDay 2019 - MySQL 8, not only good, great!PHPDay 2019 - MySQL 8, not only good, great!
PHPDay 2019 - MySQL 8, not only good, great!Gabriela Ferrara
 
PyTexas - Machine learning APIs by Example
PyTexas - Machine learning APIs by ExamplePyTexas - Machine learning APIs by Example
PyTexas - Machine learning APIs by ExampleGabriela Ferrara
 
MySQL 8.0: not only good, it’s GREAT! - PHP UK 2019
MySQL 8.0: not only good, it’s GREAT! - PHP UK 2019MySQL 8.0: not only good, it’s GREAT! - PHP UK 2019
MySQL 8.0: not only good, it’s GREAT! - PHP UK 2019Gabriela Ferrara
 
Laracon EU 2018: OMG MySQL 8.0 is out! are we there yet?
Laracon EU 2018: OMG MySQL 8.0 is out! are we there yet?Laracon EU 2018: OMG MySQL 8.0 is out! are we there yet?
Laracon EU 2018: OMG MySQL 8.0 is out! are we there yet?Gabriela Ferrara
 
DPC18 - Making the most out of MySQL
DPC18 - Making the most out of MySQLDPC18 - Making the most out of MySQL
DPC18 - Making the most out of MySQLGabriela Ferrara
 
DPC18 - OMG MySQL 8.0 is out! are we there yet?
DPC18 - OMG MySQL 8.0 is out! are we there yet?DPC18 - OMG MySQL 8.0 is out! are we there yet?
DPC18 - OMG MySQL 8.0 is out! are we there yet?Gabriela Ferrara
 
php[tek] - Making the most out of MySQL
php[tek] - Making the most out of MySQLphp[tek] - Making the most out of MySQL
php[tek] - Making the most out of MySQLGabriela Ferrara
 
Diving into MySQL 5.7: advanced features
Diving into MySQL 5.7: advanced featuresDiving into MySQL 5.7: advanced features
Diving into MySQL 5.7: advanced featuresGabriela Ferrara
 
MySQL 8.0 Preview: What Is Coming?
MySQL 8.0 Preview: What Is Coming?MySQL 8.0 Preview: What Is Coming?
MySQL 8.0 Preview: What Is Coming?Gabriela Ferrara
 
Database Wizardry for Legacy Applications
Database Wizardry for Legacy ApplicationsDatabase Wizardry for Legacy Applications
Database Wizardry for Legacy ApplicationsGabriela Ferrara
 
Coding like a girl - Youtube presentation
Coding like a girl - Youtube presentationCoding like a girl - Youtube presentation
Coding like a girl - Youtube presentationGabriela Ferrara
 

Mehr von Gabriela Ferrara (15)

GRONINGEN PHP - MySQL 8.0 , not only good, great
GRONINGEN PHP - MySQL 8.0 , not only good, greatGRONINGEN PHP - MySQL 8.0 , not only good, great
GRONINGEN PHP - MySQL 8.0 , not only good, great
 
Serverless and you @ Women Who Code London 2020
Serverless and you  @ Women Who Code London 2020Serverless and you  @ Women Who Code London 2020
Serverless and you @ Women Who Code London 2020
 
Serverless and you - where do i run my stateless code
Serverless and you  - where do i run my stateless codeServerless and you  - where do i run my stateless code
Serverless and you - where do i run my stateless code
 
PHPDay 2019 - MySQL 8, not only good, great!
PHPDay 2019 - MySQL 8, not only good, great!PHPDay 2019 - MySQL 8, not only good, great!
PHPDay 2019 - MySQL 8, not only good, great!
 
PyTexas - Machine learning APIs by Example
PyTexas - Machine learning APIs by ExamplePyTexas - Machine learning APIs by Example
PyTexas - Machine learning APIs by Example
 
MySQL 8.0: not only good, it’s GREAT! - PHP UK 2019
MySQL 8.0: not only good, it’s GREAT! - PHP UK 2019MySQL 8.0: not only good, it’s GREAT! - PHP UK 2019
MySQL 8.0: not only good, it’s GREAT! - PHP UK 2019
 
Laracon EU 2018: OMG MySQL 8.0 is out! are we there yet?
Laracon EU 2018: OMG MySQL 8.0 is out! are we there yet?Laracon EU 2018: OMG MySQL 8.0 is out! are we there yet?
Laracon EU 2018: OMG MySQL 8.0 is out! are we there yet?
 
DPC18 - Making the most out of MySQL
DPC18 - Making the most out of MySQLDPC18 - Making the most out of MySQL
DPC18 - Making the most out of MySQL
 
DPC18 - OMG MySQL 8.0 is out! are we there yet?
DPC18 - OMG MySQL 8.0 is out! are we there yet?DPC18 - OMG MySQL 8.0 is out! are we there yet?
DPC18 - OMG MySQL 8.0 is out! are we there yet?
 
php[tek] - Making the most out of MySQL
php[tek] - Making the most out of MySQLphp[tek] - Making the most out of MySQL
php[tek] - Making the most out of MySQL
 
Diving into MySQL 5.7: advanced features
Diving into MySQL 5.7: advanced featuresDiving into MySQL 5.7: advanced features
Diving into MySQL 5.7: advanced features
 
MySQL 8.0 Preview: What Is Coming?
MySQL 8.0 Preview: What Is Coming?MySQL 8.0 Preview: What Is Coming?
MySQL 8.0 Preview: What Is Coming?
 
Database Wizardry for Legacy Applications
Database Wizardry for Legacy ApplicationsDatabase Wizardry for Legacy Applications
Database Wizardry for Legacy Applications
 
Coding like a girl - Youtube presentation
Coding like a girl - Youtube presentationCoding like a girl - Youtube presentation
Coding like a girl - Youtube presentation
 
Coding like a Girl
Coding like a GirlCoding like a Girl
Coding like a Girl
 

MySQL 5.7 - 
Tirando o Máximo Proveito

  • 2. Quem? • Data Engineer • Desenvolvedora por 8 anos • Palestrante ocasional • @gabidavila • http://gabriela.io
  • 3. • Alterações em tempo real de DDL no InnoDB • JSON • Colunas Geradas (Generated Columns) • `sys` schema O Que Esperar? 3
  • 4. Alterações em tempo real de DDL
  • 5. • In Place (ALGORITHM=INPLACE) • Renomear índices • VARCHAR de 1b para 255b* • Adicionar uma coluna virtual • Table-copy (ALGORITHM=COPY) • VARCHAR de 256b para 65535b* • Adicionar colunas • Conversão de tipos Online DDL 5 * Depende de encoding da tabela e coluna, para latin1 seriam 255 caracteres, para utf8 seriam até 63 caracteres
  • 7. • Armazenamento é binário no banco de dados • É possível converter campos TEXT se JSON_VALID() retorna TRUE para toda a tabela • Conversão de TEXT para JSON é uma operação COPY • É impossível de se armazenar um JSON inválido • Colunas do tipo JSON não podem ter um valor DEFAULT • Índices são possíveis devido à Generated Columns Recursos 7
  • 8. Tabela `twitter_users` 8 Field Type Null Key Default Extra id int(11) NO PRI auto_increment id_str varchar(255) NO UNI screen_name varchar(255) NO INDEX response json YES created_at datetime NO CURRENT_TIMESTAMP updated_at datetime NO CURRENT_TIMESTAMP on update CURRENT_TIMESTAMP CREATE TABLE `twitter_users` ( `id` INT(11) NOT NULL AUTO_INCREMENT, `id_str` VARCHAR(255) NOT NULL, `screen_name` VARCHAR(255) NOT NULL, `response` JSON NOT NULL, `created_at` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP, `updated_at` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, PRIMARY KEY (`id`), UNIQUE KEY `un_id_str` (`id_str`), KEY `id_str` (`id_str`), KEY `ix_screen_name` (`screen_name`) ) ENGINE = InnoDB DEFAULT CHARSET = utf8mb4
  • 9. @PHPesteNE 9 SELECT response FROM `twitter_users` WHERE `screen_name` = 'PHPesteNE'; { "id": 3331483283, "url": "http://t.co/vKElFb77Te", "lang": "pt", "name": "PHPeste", "id_str": "3331483283", "profile_image_url": "http://pbs.twimg.com/profile_images/621823785025564673/64yvbfWw_normal.jpg", "profile_banner_url": "https://pbs.twimg.com/profile_banners/3331483283/1470600499", "location": "Salvador, Brasil", "verified": false, "following": true, "protected": false, "time_zone": "Brasilia", "created_at": "Wed Jun 17 16:33:34 +0000 2015", "utc_offset": -10800, "description": "PHP Conference Northeast Brazil.", "geo_enabled": true, "screen_name": "phpestene", "listed_count": 15, "friends_count": 314, "statuses_count": 186, "default_profile": true, "followers_count": 318, "favourites_count": 166, "profile_link_color": "0084B4", "profile_text_color": "333333", "profile_image_url_https": "https://pbs.twimg.com/profile_images/621823785025564673/64yvbfWw_normal.jpg", "profile_background_color": "C0DEED", "profile_sidebar_fill_color": "DDEEF6", "profile_background_image_url": "http://abs.twimg.com/images/themes/theme1/bg.png", "profile_sidebar_border_color": "C0DEED", "profile_use_background_image": true, "profile_background_image_url_https": "https://abs.twimg.com/images/themes/theme1/bg.png" }
  • 11. • Usando json_extract(json_column, “$.path”) Acessando Valores 11 SELECT screen_name, json_extract(response,"$.location") FROM `twitter_users` LIMIT 5; -- Results -- +---------------+------------------------------+ -- | screen_name | location | -- +---------------+------------------------------+ -- | wimgtr | "Belgium" | -- | wilw | "Los Angeles" | -- | n0x13 | "Amsterdam, The Netherlands" | -- | stoker | "DFW Texas" | -- | anthonyjuanes | "Exeter" | -- +---------------+------------------------------+ -- 5 rows in set (0.00 sec) • Valores extraídos estarão sempre com aspas e contra-barra
  • 12. • Usando o atalho json_column->“$.path” Acessando Valores 12 SELECT screen_name, response->"$.location" AS location FROM `twitter_users` LIMIT 5; -- Results -- +---------------+------------------------------+ -- | screen_name | location | -- +---------------+------------------------------+ -- | wimgtr | "Belgium" | -- | wilw | "Los Angeles" | -- | n0x13 | "Amsterdam, The Netherlands" | -- | stoker | "DFW Texas" | -- | anthonyjuanes | "Exeter" | -- +---------------+------------------------------+ -- 5 rows in set (0.00 sec) • Valores extraídos estarão sempre com aspas e contra-barra
  • 13. Acessando e escapando Valores 13 • Usando a função • json_unquote(json_extract(json_column, “$.path”)) • Usando o atalho: • json_column->>“$.path”
  • 14. SELECT screen_name, json_extract(response, "$.status.source") AS location, json_unquote(json_extract(response, "$.status.source")) AS esc_loc, response->"$.status.source" AS source, response->>"$.status.source" AS esc_source FROM `twitter_users` LIMIT 2; -- Resultado -- -- *************************** 1. row *************************** -- screen_name: wimgtr -- location: "<a href="https://about.twitter.com/products/tweetdeck" rel="nofollow">TweetDeck</a>" -- esc_loc: <a href="https://about.twitter.com/products/tweetdeck" rel="nofollow">TweetDeck</a> -- source: "<a href="https://about.twitter.com/products/tweetdeck" rel="nofollow">TweetDeck</a>" -- esc_source: <a href="https://about.twitter.com/products/tweetdeck" rel="nofollow">TweetDeck</a> -- *************************** 2. row *************************** -- screen_name: wilw -- location: "<a href="http://twitter.com" rel="nofollow">Twitter Web Client</a>" -- esc_loc: <a href="http://twitter.com" rel="nofollow">Twitter Web Client</a> -- source: "<a href="http://twitter.com" rel="nofollow">Twitter Web Client</a>" -- esc_source: <a href="http://twitter.com" rel="nofollow">Twitter Web Client</a> -- 2 rows in set (0.00 sec)
  • 16. • JSON_ARRAY() • JSON_ARRAY_APPEND() • JSON_ARRAY_INSERT() • JSON_ARRAY_APPEND() • JSON_ARRAY_INSERT() • JSON_CONTAINS() • JSON_CONTAINS_PATH() • JSON_DEPTH() • JSON_EXTRACT() or -> • JSON_INSERT() • JSON_KEYS() • JSON_LENGTH() • JSON_MERGE() • JSON_OBJECT() • JSON_QUOTE() • JSON_REMOVE() • JSON_REPLACE() • JSON_SEARCH() • JSON_SET() • JSON_TYPE() • JSON_UNQUOTE() or ->> • JSON_VALID() Manipulação de JSON 16
  • 18. • Não ocupa espaço em disco • A criação é INPLACE • O valor da coluna é gerado em tempo real • Chamado quando uma trigger de evento BEFORE é chamada Virtual Columns 18
  • 19. • Ocupa espaço em disco • Valor atualizado para cada operação de escrita (INSERT, UPDATE) • Usa o algoritmo COPY para criação e remoção da coluna Stored Columns 19
  • 20. • Ambas podem ser indexadas • Permitem que expressões como essas sejam usadas: • Operadores ( +, -, *, /, etc) • Funções nativas (LEFT(), SUBSTR(), JSON_EXTRACT(), etc) • Literais (‘novo’, 2, etc) • Subqueries não são suportadas Virtual and Stored Columns 20
  • 22. -- Total rows SELECT COUNT(*) FROM `twitter_users`; -- 8906 rows -- Virtual Columns ALTER TABLE `twitter_users` ADD COLUMN `profile_image_url` VARCHAR(255) GENERATED ALWAYS AS (response->>"$.profile_image_url"); -- [2016-10-04 14:16:24] completed in 46ms -- Stored Columns ALTER TABLE `twitter_users` ADD COLUMN `location` VARCHAR(255) GENERATED ALWAYS AS (response->>"$.location") STORED ADD INDEX `ix_location` (`location`); -- [2016-10-04 14:20:09] 8906 rows affected in 2s 689ms
  • 23. Tabela `twitter_users` 23 Field Type Null Key Default Extra id int(11) NO PRI auto_increment id_str varchar(255) NO UNI screen_name varchar(255) NO INDEX response json YES location varchar(255) YES INDEX STORED GENERATED profile_image_url varchar(255) YES VIRTUAL GENERATED created_at datetime NO CURRENT_TIMESTAMP updated_at datetime NO CURRENT_TIMESTAMP on update CURRENT_TIMESTAMP
  • 24. Busca 24 SELECT screen_name, location, profile_image_url FROM `twitter_users` WHERE location LIKE "%Brasil%" LIMIT 5; -- Results -- +---------------+-----------------------+----------------------------+ -- | screen_name | location | profile_image_url | -- +---------------+-----------------------+----------------------------+ -- | hussanii | Brasil | http://pbs.twimg.com/(...) | -- | fplcampos | São Paulo, Brasil | http://pbs.twimg.com/(...) | -- | ivanrosolen | Sampa - Brasil | http://pbs.twimg.com/(...) | -- | rogeriopradoj | Brasil, São Paulo, SP | http://pbs.twimg.com/(...) | -- | rafinhabastos | Brasil | http://pbs.twimg.com/(...) | -- +---------------+-----------------------+----------------------------+ -- 5 rows in set (0.00 sec)
  • 26. • Precisa ser instalado na versão 5.6 • Instalado por padrão no 5.7 • MySQL Workbench vem com um cliente • Em produção é recomendado apenas estar ativado em casos críticos MySQL `sys` schema 26
  • 27.
  • 28.
  • 29. SELECT * FROM 29 Description Table *High Cost SQL statements sys.`x$statement_analysis` *Top 5% slower queries sys.`x$statements_with_runtimes_in_95th_percentile` Use temporary tables sys.`statements_with_temp_tables` Unused Indexes sys.`schema_unused_indexes` Full table scans sys.`schema_tables_with_full_table_scans` *x$ é um prefixo para views criadas para um formato mais amigável ao usuário
  • 30.
  • 32. • `sql_mode` agora é mais estrito e os seguintes modos vêm habilitados por padrão: • ONLY_FULL_GROUP_BY • NO_ZERO_DATE • NO_ZERO_IN_DATE • ERROR_FOR_DIVISION_BY_ZERO Demais Alterações 32
  • 33. • Senhas agora podem ter uma data de expiração • Tabelas agora suportam mais de uma trigger pro mesmo evento • Alterações em YEAR(2): • marcado como deprecated na 5.6 • removido na 5.7 33 Demais Alterações
  • 34. • Twitter: @gabidavila • Blog: http://gabriela.io • Freenode: gabidavila • References: MySQL documentation Obrigada! 34