Upgrade to Pro — share decks privately, control downloads, hide ads and more …

LaravelSP - MySQL 5.7: introdução ao JSON Data ...

LaravelSP - MySQL 5.7: introdução ao JSON Data Type

Essa palestra apresenta uma introdução ao tipo de dados JSON no MySQL 5.7, descrevendo suas principais funcionalidades como validação automática, tipos de dados suportados, funções para criação, busca, modificação e retorno de atributos de dados JSON, e a possibilidade de criação de índices.

Avatar for Gabriela D'Ávila Ferrara

Gabriela D'Ávila Ferrara

February 15, 2017
Tweet

More Decks by Gabriela D'Ávila Ferrara

Other Decks in Programming

Transcript

  1. oi! • Data Engineer • tipo DBA… • … mas

    diferente • @gabidavila • http://gabriela.io 4
  2. O que é JSON? • JavaScript Object Notation (desde 1999)

    • Formato mais compacto que XML • É language-independent • Atributo-valor 6
  3. 7

  4. • 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
  5. 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
  6. 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
  7. JSON Data Type • 4 tipos de funções • Criar

    JSON • Buscar/extrair JSON • Modificar JSON • Retornar atributos JSON Mais informações 14
  8. PHP + MySQL: decode <?php json_decode('[]'); /* -> array(0) {

    } */ json_decode(''); /* -> NULL */ json_decode('{"id": 5}'); /* -> object(stdClass)#1 (1) { ["id"]=> int(5) } */ 17
  9. 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
  10. 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
  11. 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
  12. 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
  13. 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
  14. 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
  15. 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
  16. -> é 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
  17. 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
  18. 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
  19. Obrigada! • Fonte: MySQL Docs • Twitter: @gabidavila • Blog:

    http://gabriela.io • Freenode: gabidavila #phpwomen / #phpmentoring 38