laravelsp - mysql 5.7: introdução ao json data type

Post on 12-Apr-2017

179 Views

Category:

Internet

2 Downloads

Preview:

Click to see full reader

TRANSCRIPT

MySQL 5.7: introdução ao JSON Data Type

Gabriela D’Avila @gabidavila

Fev/2017

Pesquisa sem validade científica*

2

oi!• Data Engineer

• tipo DBA…

• … mas diferente

• @gabidavila

• http://gabriela.io

4

O que é JSON?

• JavaScript Object Notation (desde 1999)

• Formato mais compacto que XML

• É language-independent

• Atributo-valor

6

Tipos de dados aceitos• Strings

• Números

• Booleanos

• Arrays

• Objetos

8

Use UTF8

9

MySQL + JSON

Leitura Recomendada

• JSON_ARRAY() • JSON_ARRAY_APPEND() • JSON_ARRAY_INSERT() • JSON_ARRAY_APPEND() • JSON_ARRAY_INSERT() • JSON_CONTAINS() • JSON_CONTAINS_PATH() • JSON_DEPTH() • JSON_EXTRACT() • JSON_INSERT() • JSON_KEYS()

• JSON_LENGTH() • JSON_MERGE() • JSON_OBJECT() • JSON_QUOTE() • JSON_REMOVE() • JSON_REPLACE() • JSON_SEARCH() • JSON_SET() • JSON_TYPE() • JSON_UNQUOTE() • JSON_VALID()

Funções JSON

JSON Data Type• Validação automática, documentos inválidos causam

erro

• Case sensitive (utf8mb4_bin)

• null, true, false ✅

• Null, NULL, TRUE, False 🚫

• 'a' != 'A'

• Colunas do tipo JSON não podem ter um valor DEFAULT

12

JSON Data Type• Armazenado em formato binário

• Chaves repetidas são substituídas pela última ocorrência

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

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

• Índices são possíveis devido à GENERATED COLUMNS

13

JSON Data Type• 4 tipos de funções

• Criar JSON

• Buscar/extrair JSON

• Modificar JSON

• Retornar atributos JSON

Mais informações14

PHP + MySQL

PHP + MySQL: encode

<?php

json_encode(object $obj); json_encode(string $str); json_encode('[]');

16

PHP + MySQL: decode<?php

json_decode('[]'); /* -> array(0) { } */

json_decode(''); /* -> NULL */

json_decode('{"id": 5}'); /* -> object(stdClass)#1 (1) { ["id"]=> int(5) } */

17

Criar JSON

Para criar array• JSON_ARRAY(val1[, val2, …])

SELECT JSON_ARRAY('laravel', 5.4, "2017-02-14");

+------------------------------------------+ | JSON_ARRAY('laravel', 5.4, "2017-02-14") | +------------------------------------------+ | ["laravel", 5.4, "2017-02-14"] | +------------------------------------------+ 1 row in set (0.00 sec)

19

Para criar objeto• JSON_OBJECT([key, val[, key, val] ...])

SELECT JSON_OBJECT('framework', 'laravel', 'versao', 5.4);

+----------------------------------------------------+ | JSON_OBJECT('framework', 'laravel', 'versao', 5.4) | +----------------------------------------------------+ | {"versao": 5.4, "framework": "laravel"} | +----------------------------------------------------+ 1 row in set (0.00 sec)

20

Buscar/extrair JSON

Tabela `users`

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 NO

22

Extrair name, status.source

SELECT JSON_EXTRACT(response, '$.name') AS name, JSON_EXTRACT(response, '$.status.source') AS source FROM users WHERE screen_name = 'laravelsp';

*************************** 1. row *************************** name: "Laravel SP Meetup" source: "<a href=\"http://twitter.com/download/android\">Twitter for Android</a>" 1 row in set (0.00 sec)

24

JSON_EXTRACT() ou ->

SELECT response->'$.name' AS name, response->'$.status.source' AS source FROM users WHERE screen_name = 'laravelsp';

*************************** 1. row *************************** name: "Laravel SP Meetup" source: "<a href=\"http://twitter.com/download/android\">Twitter for Android</a>" 1 row in set (0.00 sec)

25

Modificar JSON

JSON_UNQUOTE() ≃ stripslashes()

SELECT JSON_UNQUOTE(JSON_EXTRACT(response, '$.name')) AS name, JSON_UNQUOTE(JSON_EXTRACT(response, '$.status.source')) AS source FROM users WHERE screen_name = 'laravelsp';

*************************** 1. row *************************** name: Laravel SP Meetup source: <a href="http://twitter.com/download/android">Twitter for Android</a> 1 row in set (0.00 sec)

27

JSON_UNQUOTE() ou ->>

SELECT response->>'$.name' AS name, response->>'$.status.source' AS source FROM users WHERE screen_name = 'laravelsp';

*************************** 1. row *************************** name: Laravel SP Meetup source: <a href="http://twitter.com/download/android">Twitter for Android</a> 1 row in set (0.00 sec)

28

Recapitulando

-> é igual a ->> ?

• -> é apenas usado para extração, não modifica o valor (JSON_EXTRACT())

• ->> faz a modificação em runtime mas não altera o JSON por si só (JSON_UNQUOTE(JSON_EXTRACT()))

30

Retornar Atributos JSON

JSON_VALID()

SELECT JSON_VALID("NULL"), JSON_VALID("null"), JSON_VALID("[]"), JSON_VALID('{"screen_name":"laravelsp"}'), JSON_VALID("{\"screen_name\":\"laravelsp\" }");

*************************** 1. row *************************** JSON_VALID("NULL"): 0 JSON_VALID("null"): 1 JSON_VALID("[]"): 1 JSON_VALID('{"screen_name":"laravelsp"}'): 1 JSON_VALID("{\"screen_name\":\"laravelsp\" }"): 1 1 row in set (0.00 sec)

32

JSON_TYPE()

SELECT JSON_TYPE(response->'$.id') AS id_type, JSON_TYPE(response->'$.name') AS name_type, JSON_TYPE(response->'$.status') AS status_type, JSON_TYPE(response->'$.verified') AS verified_type FROM users WHERE screen_name = 'laravelsp';

*************************** 1. row *************************** id_type: UNSIGNED INTEGER name_type: STRING status_type: OBJECT verified_type: BOOLEAN 1 row in set (0.00 sec)

33

Índices

Índices

• Possíveis por meio de VIRTUAL COLUMNS ou STORED COLUMNS

35

Dúvidas?

37

Obrigada!

• Fonte: MySQL Docs

• Twitter: @gabidavila

• Blog: http://gabriela.io

• Freenode: gabidavila #phpwomen / #phpmentoring

38

top related