├── README.md ├── backend ├── mongodb │ └── mongodb_aggregation │ │ └── README.md ├── mysql │ └── simple-crud.md ├── nodejs │ └── npm │ │ └── README.md └── sequelize │ ├── queries │ └── README.md │ └── setup │ └── README.md └── frontend └── README.md /README.md: -------------------------------------------------------------------------------- 1 | # Repositório Cheat Sheet da Trybe 2 | 3 | Repositório de *cheat sheets* para consultas rápidas. 4 | 5 | - **Backend** 6 | - **MongoDB** 7 | - [MongoDB - Aggregration](backend/mongodb/mongodb_aggregation/README.md) 8 | - **Node.js** 9 | - [NPM - Comandos](backend/nodejs/npm/README.md) 10 | - **Sequelize** 11 | - [Sequelize - Setup](backend/sequelize/setup/README.md) 12 | - [Sequelize - Queries](backend/sequelize/queries/README.md) 13 | - **Frontend** 14 | -------------------------------------------------------------------------------- /backend/mongodb/mongodb_aggregation/README.md: -------------------------------------------------------------------------------- 1 | # MongoDB Aggregation Cheat Sheet 2 | 3 | # Sumário 4 | 5 | - [MongoDB Aggregation Cheat Sheet](#mongodb-aggregation-cheat-sheet) 6 | - [Sumário](#sumário) 7 | - [Operadores](#operadores) 8 | - [Operadores Aggregation](#operadores-aggregation) 9 | - [$match](#match) 10 | - [$limit](#limit) 11 | - [$group](#group) 12 | - [$project](#project) 13 | - [$unwind](#unwind) 14 | - [$lookup](#lookup) 15 | - [$lookup (let/pipeline)](#lookup-letpipeline) 16 | - [$addFields](#addfields) 17 | - [Operadores Aritméticos](#operadores-aritméticos) 18 | - [$add](#add) 19 | - [$subtract](#subtract) 20 | - [$ceil](#ceil) 21 | - [$floor](#floor) 22 | - [$abs](#abs) 23 | - [$multiply](#multiply) 24 | - [$divide](#divide) 25 | 26 | --- 27 | 28 | # Operadores 29 | 30 | ## Operadores Aggregation 31 | 32 | ### $match 33 | 34 | **Template** 35 | 36 | ``` 37 | db.collection.aggregate([ 38 | { $match: { } }, 39 | ]); 40 | ``` 41 | 42 | **Exemplo** 43 | 44 | ```javascript 45 | db.workers.aggregate([ 46 | { $match: { workerName: "Tiago" } }, 47 | ]); 48 | ``` 49 | 50 | [Documentação](https://docs.mongodb.com/manual/reference/operator/aggregation/match/) 51 | 52 | [Voltar para Sumário](#sumário) 53 | 54 | --- 55 | 56 | ### $limit 57 | 58 | **Template** 59 | 60 | ``` 61 | db.collection.aggregate([ 62 | { $limit: }, 63 | ]); 64 | ``` 65 | 66 | **Exemplo** 67 | 68 | ```javascript 69 | db.products.aggregate([ 70 | { $match: { laptop: 'Dell' } }, 71 | { $limit: 5 }, 72 | ]); 73 | ``` 74 | 75 | [Documentação](https://docs.mongodb.com/manual/reference/operator/aggregation/limit/) 76 | 77 | [Voltar para Sumário](#sumário) 78 | 79 | --- 80 | 81 | ### $group 82 | 83 | **Template** 84 | 85 | ``` 86 | db.collection.aggregate([ 87 | { 88 | $group: { 89 | _id: , 90 | : { : }, 91 | ... 92 | : { : }, 93 | }, 94 | }, 95 | ]); 96 | ``` 97 | 98 | **Exemplo** 99 | 100 | ```javascript 101 | db.products.aggregate([ 102 | { 103 | $group : { 104 | _id : "$laptopId", 105 | count: { $sum: 1 }, 106 | }, 107 | }, 108 | ]); 109 | ``` 110 | 111 | [Documentação](https://docs.mongodb.com/manual/reference/operator/aggregation/group/) 112 | 113 | [Voltar para Sumário](#sumário) 114 | 115 | --- 116 | 117 | ### $project 118 | 119 | **Template** 120 | 121 | ``` 122 | db.collection.aggregate([ 123 | { 124 | project: { 125 | 126 | }, 127 | }, 128 | ]); 129 | ``` 130 | 131 | **Exemplo** 132 | 133 | ```javascript 134 | db.products.aggregate([ 135 | { 136 | $project: { 137 | _id: 0, // ou false 138 | productName: "$laptop", 139 | quantity: 1, // ou true 140 | profit: { 141 | $subtract: ["$sale_price", "$cost_price"] 142 | }, 143 | }, 144 | }, 145 | ]); 146 | ``` 147 | 148 | [Documentação](https://docs.mongodb.com/manual/reference/operator/aggregation/project) 149 | 150 | [Voltar para Sumário](#sumário) 151 | 152 | --- 153 | 154 | ### $unwind 155 | 156 | **Template** 157 | 158 | ``` 159 | db.collection.aggregate([ 160 | { $unwind: }, 161 | ]); 162 | ``` 163 | 164 | **Exemplo** 165 | 166 | ```javascript 167 | db.streamings.aggregate([ 168 | { $unwind: "$netflix_plans" }, 169 | ]); 170 | ``` 171 | 172 | [Documentação](https://docs.mongodb.com/manual/reference/operator/aggregation/unwind/) 173 | 174 | [Voltar para Sumário](#sumário) 175 | 176 | --- 177 | 178 | ### $lookup 179 | 180 | **Template** 181 | 182 | ``` 183 | db.collection.aggregate([ 184 | { 185 | $lookup: { 186 | from: , 187 | localField: , 188 | foreignField: 190 | }, 191 | }, 192 | ]); 193 | ``` 194 | 195 | **Exemplo** 196 | 197 | ```javascript 198 | db.orders.aggregate([ 199 | { 200 | $lookup: { 201 | from: "inventory", 202 | localField: "item", 203 | foreignField: "sku", 204 | as: "inventory_docs" 205 | }, 206 | }, 207 | ]); 208 | ``` 209 | 210 | [Documentação](https://docs.mongodb.com/manual/reference/operator/aggregation/lookup/) 211 | 212 | [Voltar para Sumário](#sumário) 213 | 214 | --- 215 | 216 | ### $lookup (let/pipeline) 217 | 218 | **Template** 219 | 220 | ``` 221 | db.collection.aggregate([ 222 | { 223 | $lookup: 224 | { 225 | from: , 226 | let: { : , …, : }, 227 | pipeline: [ ], 228 | as: 229 | } 230 | } 231 | ]); 232 | ``` 233 | 234 | **Exemplo** 235 | 236 | ```javascript 237 | db.orders.aggregate([ 238 | { 239 | $lookup: 240 | { 241 | from: "warehouses", 242 | let: { order_item: "$item", order_qty: "$ordered" }, 243 | pipeline: [ 244 | { $match: 245 | { $expr: 246 | { $and: 247 | [ 248 | { $eq: [ "$stock_item", "$$order_item" ] }, 249 | { $gte: [ "$instock", "$$order_qty" ] } 250 | ] 251 | } 252 | } 253 | }, 254 | { $project: { stock_item: 0, _id: 0 } } 255 | ], 256 | as: "stockdata" 257 | } 258 | } 259 | ]) 260 | ``` 261 | 262 | [Documentação](https://docs.mongodb.com/manual/reference/operator/aggregation/lookup/) 263 | 264 | [Voltar para Sumário](#sumário) 265 | 266 | --- 267 | 268 | ### $addFields 269 | 270 | **Template** 271 | 272 | ``` 273 | db.collection.aggregate([ 274 | { 275 | $addFields: { 276 | : , 277 | : , 278 | ... 279 | }, 280 | }, 281 | ]); 282 | ``` 283 | 284 | **Exemplo** 285 | 286 | ```javascript 287 | db.school.aggregate([ 288 | { 289 | $addFields: { 290 | totalHomework: { $sum: "$homework" } , 291 | totalQuiz: { $sum: "$quiz" } 292 | }, 293 | }, 294 | { 295 | $addFields: { 296 | totalScore: { 297 | $add: [ "$totalHomework", "$totalQuiz", "$extraCredit" ] 298 | }, 299 | }, 300 | }, 301 | ]); 302 | ``` 303 | 304 | [Documentação](https://docs.mongodb.com/manual/reference/operator/aggregation/addFields/) 305 | 306 | [Voltar para Sumário](#sumário) 307 | 308 | ## Operadores Aritméticos 309 | 310 | ### $add 311 | 312 | **Template** 313 | 314 | ``` 315 | db.collection.aggregate([ 316 | { 317 | $project: { 318 | : { 319 | $add: [ , , ... ] 320 | }, 321 | }, 322 | }, 323 | ]); 324 | ``` 325 | 326 | **Exemplo** 327 | 328 | ```javascript 329 | db.products.aggregate([ 330 | { 331 | $project: { 332 | item: 1, 333 | total: { 334 | $add: ["$price", "$fee"] 335 | }, 336 | }, 337 | }, 338 | ]); 339 | ``` 340 | 341 | [Documentação](https://docs.mongodb.com/manual/reference/operator/aggregation/add/) 342 | 343 | [Voltar para Sumário](#sumário) 344 | 345 | --- 346 | 347 | ### $subtract 348 | 349 | **Template** 350 | 351 | ``` 352 | db.collection.aggregate([ 353 | { 354 | $project: { 355 | : { 356 | $subtract: [ 357 | , 358 | 359 | ] 360 | }, 361 | }, 362 | }, 363 | ]); 364 | ``` 365 | 366 | **Exemplo** 367 | 368 | ```javascript 369 | db.products.aggregate([ 370 | { 371 | $project: { 372 | item: 1, 373 | total: { 374 | $subtract: [ 375 | { $add: ["$price", "$fee"] }, 376 | "$discount" 377 | ] 378 | }, 379 | }, 380 | }, 381 | ]); 382 | ``` 383 | 384 | [Documentação](https://docs.mongodb.com/manual/reference/operator/aggregation/subtract/) 385 | 386 | [Voltar para Sumário](#sumário) 387 | 388 | --- 389 | 390 | ### $ceil 391 | 392 | **Template** 393 | 394 | ``` 395 | db.collection.aggregate([ 396 | { 397 | $project: { 398 | roundedNumber: { 399 | $ceil: , 400 | }, 401 | }, 402 | }, 403 | ]); 404 | ``` 405 | 406 | **Exemplo** 407 | 408 | ```javascript 409 | db.movies.aggregate([ 410 | { 411 | $project: { 412 | value: 1, 413 | ceilingValue: { 414 | $ceil: "$rating", 415 | }, 416 | }, 417 | }, 418 | ]); 419 | ``` 420 | 421 | [Documentação](https://docs.mongodb.com/manual/reference/operator/aggregation/ceil/) 422 | 423 | [Voltar para Sumário](#sumário) 424 | 425 | --- 426 | 427 | ### $floor 428 | 429 | **Template** 430 | 431 | ``` 432 | db.collection.aggregate([ 433 | { 434 | $project: { 435 | value: 1, 436 | roundedNumber: { 437 | $floor: , 438 | }, 439 | }, 440 | }, 441 | ]); 442 | ``` 443 | 444 | **Exemplo** 445 | 446 | ```javascript 447 | db.movies.aggregate([ 448 | { 449 | $project: { 450 | value: 1, 451 | floorValue: { 452 | $floor: "$value", 453 | }, 454 | }, 455 | }, 456 | ]); 457 | ``` 458 | 459 | [Documentação](https://docs.mongodb.com/manual/reference/operator/aggregation/floor/) 460 | 461 | [Voltar para Sumário](#sumário) 462 | 463 | --- 464 | 465 | ### $abs 466 | 467 | **Template** 468 | 469 | ``` 470 | db.collection.aggregate([ 471 | { 472 | project: { 473 | : { 474 | abs: , 475 | }, 476 | }, 477 | }, 478 | ]); 479 | ``` 480 | 481 | **Exemplo** 482 | 483 | ```javascript 484 | db.operations.aggregate([ 485 | { 486 | project: { 487 | delta: { 488 | abs: { $subtract: ["$start", "$end"] }, 489 | }, 490 | }, 491 | }, 492 | ]); 493 | ``` 494 | [Documentação](https://docs.mongodb.com/manual/reference/operator/aggregation/abs/) 495 | 496 | [Voltar para Sumário](#sumário) 497 | 498 | --- 499 | 500 | ### $multiply 501 | 502 | **Template** 503 | 504 | ``` 505 | db.collection.aggregate([ 506 | { 507 | project: { 508 | : { 509 | $multiply: [ , , ... ] 510 | }, 511 | }, 512 | }, 513 | ]); 514 | ``` 515 | 516 | **Exemplo** 517 | 518 | ```javascript 519 | db.operations.aggregate([ 520 | { 521 | project: { 522 | date: 1, 523 | item: 1, 524 | total: { 525 | $multiply: [ 526 | "$price", 527 | "$quantity" 528 | ] 529 | }, 530 | }, 531 | }, 532 | ]); 533 | ``` 534 | [Documentação](https://docs.mongodb.com/manual/reference/operator/aggregation/multiply/) 535 | 536 | [Voltar para Sumário](#sumário) 537 | 538 | --- 539 | 540 | ### $divide 541 | 542 | **Template** 543 | 544 | ``` 545 | db.collection.aggregate([ 546 | { 547 | project: { 548 | : { 549 | $divide: [ , ] 550 | }, 551 | }, 552 | }, 553 | ]); 554 | ``` 555 | 556 | **Exemplo** 557 | 558 | ```javascript 559 | db.employees.aggregate([ 560 | { 561 | project: { 562 | name: 1, 563 | workdays: { 564 | $divide: ["$hours", 8] 565 | }, 566 | }, 567 | }, 568 | ]); 569 | ``` 570 | [Documentação](https://docs.mongodb.com/manual/reference/operator/aggregation/divide/) 571 | 572 | [Voltar para Sumário](#sumário) 573 | 574 | --- 575 | -------------------------------------------------------------------------------- /backend/mysql/simple-crud.md: -------------------------------------------------------------------------------- 1 | # Mysql Simple CRUD Sheet Cheat 2 | 3 | ## Sumário 4 | - [`SELECT`](#select) 5 | - [`DISTINCT`](#DISTINCT) 6 | - [`LIMIT` e `OFFSET`](#limit-e-offset) 7 | - [`ORDER BY`](#order-by) 8 | - [`COUNT`](#count) 9 | - [`WHERE`](#WHERE) 10 | - [Condições](#Condições) 11 | - [Operadores Matemáticos](#Operadores-Matemáticos) 12 | - [Operadores Lógicos](#Operadores-Lógicos) 13 | - [`IS`](#IS) 14 | - [`NOT`](#NOT) 15 | - [`LIKE`](#LIKE) 16 | - [`BETWEEN`](#BETWEEN) 17 | - [`IN`](#IN) 18 | - [Datas](#Datas) 19 | - [`INSERT`](#INSERT) 20 | - [`UPDATE`](#UPDATE) 21 | - [`DELETE`](#DELETE) 22 | 23 | 24 | ## `SELECT` 25 | 26 | **Template** 27 | 28 | ```sql 29 | SELECT 30 | [DISTINCT] 31 | expressão_de_coluna [, expressão_de_coluna] ... 32 | [FROM ] 33 | [WHERE condição] 34 | [ORDER BY expressão_de_coluna [ASC | DESC]] 35 | [LIMIT contagem_de_linhas [OFFSET linha_puladas]] 36 | ``` 37 | > a sintaxe dos colchetes (`[]`) são declarações opcionais 38 | 39 | > sintaxe `expressão [, expressão] ...;` representa que uma expressão é obrigatória, mas pode-se encadear mais expressões separadas por vírgula 40 | 41 | 42 | --- 43 | 44 | ```sql 45 | SELECT * FROM .; 46 | SELECT , FROM .; 47 | ``` 48 | 49 | **Exemplo** 50 | 51 | 52 | ```sql 53 | SELECT * FROM sakila.actor; 54 | SELECT first_name, last_name FROM sakila.actor; 55 | ``` 56 | 57 | --- 58 | 59 | ### `DISTINCT` 60 | 61 | **Template** 62 | 63 | ```sql 64 | SELECT DISTINCT FROM .; 65 | SELECT DISTINCT , FROM .; 66 | ``` 67 | 68 | **Exemplo** 69 | 70 | ```sql 71 | SELECT DISTINCT first_name FROM sakila.actor; 72 | ``` 73 | 74 | ```sql 75 | SELECT DISTINCT first_name, last_name FROM sakila.actor; 76 | ``` 77 | 78 | ### `LIMIT` e `OFFSET` 79 | 80 | ```sql 81 | SELECT * FROM . LIMIT 10; 82 | SELECT * FROM . OFFSET 10; 83 | SELECT * FROM . LIMIT 10 OFFSET 10; 84 | ``` 85 | 86 | **Exemplo** 87 | 88 | ```sql 89 | SELECT * FROM sakila.actor LIMIT 10; 90 | SELECT * FROM sakila.actor OFFSET 10; 91 | SELECT * FROM sakila.actor LIMIT 10 OFFSET 10; 92 | ``` 93 | 94 | --- 95 | 96 | ### `ORDER BY` 97 | 98 | **Template** 99 | 100 | ```sql 101 | SELECT * FROM . ORDER BY DESC; -- é ASC por padrão 102 | SELECT * FROM . ORDER BY ASC, DESC; 103 | ``` 104 | 105 | **Exemplo** 106 | 107 | ```sql 108 | SELECT * FROM sakila.actor ORDER BY first_name DESC; 109 | SELECT * FROM sakila.actor ORDER BY first_name DESC, last_name ASC; 110 | SELECT * FROM sakila.payment ORDER BY payment_date ASC; 111 | SELECT * FROM sakila.payment ORDER BY amount DESC; 112 | ``` 113 | 114 | --- 115 | ### `COUNT` 116 | 117 | **Template** 118 | 119 | ```sql 120 | SELECT COUNT([DISTINCT] coluna [, coluna] ...) FROM .; 121 | ``` 122 | 123 | **Exemplo** 124 | 125 | ```sql 126 | SELECT COUNT(*) FROM sakila.film; 127 | SELECT COUNT(DISTINCT first_name) FROM sakila.actor; 128 | SELECT COUNT(DISTINCT first_name, last_name) FROM sakila.actor; 129 | ``` 130 | 131 | --- 132 | 133 | ## `WHERE` 134 | 135 | **Template** 136 | 137 | ```sql 138 | SELECT * FROM . WHERE condition; 139 | SELECT * FROM . WHERE true; -- todas as linhas 140 | SELECT * FROM . WHERE false; -- nenhuma linha 141 | ``` 142 | 143 | --- 144 | 145 | ### Condições 146 | 147 | | OPERADOR | DESCRIÇÃO | Exemplo 148 | |:---:|:----------|:--| 149 | | = | IGUAL | `SELECT * from WHERE . = 1;` | 150 | | > | MAIOR QUE | `SELECT * from WHERE . > 1;` | 151 | | < | MENOR QUE | `SELECT * from WHERE . < 10;` | 152 | | >= | MAIOR QUE OU IGUAL | `SELECT * from WHERE . >= 10;` | 153 | | <= | MENOR QUE OU IGUAL | `SELECT * from WHERE . <= 10;` | 154 | | <> | DIFERENTE DE | `SELECT * from WHERE . <> 10;` | 155 | | AND | OPERADOR LÓGICO E | `SELECT * from WHERE . < 10 AND .coluna2 > 7;` | 156 | | OR | OPERADOR LÓGICO OU | `SELECT * from WHERE . < 10 OR .coluna2 > 7 `| 157 | | NOT | NEGAÇÃO | `SELECT * from WHERE NOT .;` | 158 | | IS | COMPARA COM VALORES BOOLEANOS (TRUE, FALSE, NULL) | `SELECT * from WHERE . IS NULL;` | 159 | 160 | --- 161 | 162 | ### Operadores Matemáticos 163 | 164 | **Exemplos** 165 | 166 | ```sql 167 | SELECT * FROM sakila.payment WHERE id = 1; 168 | ``` 169 | 170 | ```sql 171 | SELECT * FROM sakila.payment WHERE amount < 10; 172 | ``` 173 | 174 | ```sql 175 | SELECT * FROM sakila.payment WHERE amount >= 0.99; 176 | ``` 177 | 178 | ```sql 179 | SELECT * FROM sakila.language WHERE name <> 'English'; 180 | ``` 181 | 182 | --- 183 | 184 | ### Operadores Lógicos 185 | 186 | **Exemplos** 187 | 188 | ```sql 189 | SELECT * FROM sakila.payment 190 | WHERE amount = 0.99 AND staff_id = 2; 191 | ``` 192 | 193 | ```sql 194 | SELECT * FROM sakila.payment 195 | WHERE amount = 0.99 OR amount = 2.99; 196 | ``` 197 | 198 | ```sql 199 | SELECT * FROM sakila.payment 200 | WHERE amount = 0.99 OR amount = 2.99 AND staff_id = 2; 201 | ``` 202 | 203 | --- 204 | 205 | ### `IS` 206 | 207 | **Exemplo** 208 | 209 | ```sql 210 | SELECT * FROM sakila.staff WHERE picture IS NULL; 211 | ``` 212 | 213 | --- 214 | 215 | ### `NOT` 216 | 217 | **Exemplos** 218 | 219 | ```sql 220 | SELECT * FROM sakila.staff WHERE NOT address_id = 3; 221 | ``` 222 | 223 | ```sql 224 | SELECT * FROM sakila.staff WHERE picture IS NOT NULL; 225 | ``` 226 | 227 | --- 228 | 229 | ### `LIKE` 230 | |Sinal| Descrição| 231 | | :--: | :-- | 232 | | `%` | O sinal de percentual, que pode representar zero, um ou múltiplos caracteres 233 | | `_`| O underscore (às vezes chamado de underline, no Brasil), que representa um único caractere | 234 | 235 | **Template** 236 | 237 | ```sql 238 | SELECT * FROM . 239 | WHERE coluna LIKE '__string%'; 240 | ``` 241 | 242 | **Exemplos** 243 | 244 | ```sql 245 | SELECT * FROM sakila.film 246 | WHERE title LIKE '%don'; 247 | ``` 248 | 249 | ```sql 250 | SELECT * FROM sakila.film 251 | WHERE title LIKE 'plu%'; 252 | ``` 253 | 254 | ```sql 255 | SELECT * FROM sakila.film 256 | WHERE title LIKE '%plu%'; 257 | ``` 258 | 259 | ```sql 260 | SELECT * FROM sakila.film 261 | WHERE title LIKE 'p%r'; 262 | ``` 263 | 264 | ```sql 265 | SELECT * FROM sakila.film 266 | WHERE title LIKE '_C%'; 267 | ``` 268 | 269 | ```sql 270 | SELECT * FROM sakila.film 271 | WHERE title LIKE '________'; 272 | ``` 273 | 274 | --- 275 | 276 | ### `BETWEEN` 277 | 278 | **Exemplos** 279 | 280 | ```sql 281 | SELECT title, length FROM sakila.film 282 | WHERE length BETWEEN 50 AND 120; 283 | ``` 284 | 285 | ```sql 286 | SELECT rental_id, rental_date FROM sakila.rental 287 | WHERE rental_date 288 | BETWEEN '2005-05-27' AND '2005-07-17'; 289 | ``` 290 | 291 | --- 292 | 293 | ### `IN` 294 | 295 | **Exemplos** 296 | 297 | ```sql 298 | SELECT * FROM sakila.actor 299 | WHERE first_name IN ('PENELOPE','NICK','ED','JENNIFER'); 300 | ``` 301 | 302 | ```sql 303 | SELECT * FROM sakila.actor 304 | WHERE id IN (1, 2, 3, 7, 48, 42); 305 | ``` 306 | 307 | --- 308 | 309 | ## `Datas` 310 | 311 | **Exemplos** 312 | 313 | ```sql 314 | SELECT DATE(payment_date) FROM sakila.payment; -- YYYY-MM-DD 315 | SELECT YEAR(payment_date) FROM sakila.payment; -- Ano 316 | SELECT MONTH(payment_date) FROM sakila.payment; -- Mês 317 | SELECT DAY(payment_date) FROM sakila.payment; -- Dia 318 | SELECT HOUR(payment_date) FROM sakila.payment; -- Hora 319 | SELECT MINUTE(payment_date) FROM sakila.payment; -- Minuto 320 | SELECT SECOND(payment_date) FROM sakila.payment; -- Segundo 321 | ``` 322 | 323 | ```sql 324 | SELECT * FROM sakila.payment 325 | WHERE YEAR(payment_date) = 2006; 326 | ``` 327 | ```sql 328 | SELECT * FROM sakila.payment 329 | WHERE payment_date LIKE '2005-07-31%'; 330 | ``` 331 | ```sql 332 | SELECT * FROM sakila.payment 333 | WHERE payment_date 334 | BETWEEN '2005-05-26 00:00:00' AND '2005-05-27 23:59:59'; 335 | ``` 336 | ```sql 337 | SELECT * FROM sakila.payment 338 | WHERE HOUR(payment_date) BETWEEN 10 AND 20; 339 | ``` 340 | 341 | --- 342 | 343 | ## `INSERT` 344 | 345 | **Template** 346 | 347 | ```sql 348 | INSERT [IGNORE] 349 | [INTO] 350 | [(coluna [, coluna] ...)] 351 | VALUES (lista_de_valores) [, (lista_de_valores)] ... 352 | 353 | lista_de_valores: 354 | valor [, valor] ... 355 | ``` 356 | 357 | **Exemplos** 358 | 359 | ```sql 360 | INSERT INTO sakila.actor (first_name, last_name) 361 | VALUES ('Bell', 'Hooks'); 362 | ``` 363 | ```sql 364 | INSERT INTO sakila.actor (first_name, last_name) 365 | VALUES ('Bell', 'Hooks'), ('Simone', 'Beauvoir'); 366 | ``` 367 | 368 | --- 369 | 370 | ## `UPDATE` 371 | 372 | **Template** 373 | 374 | ```sql 375 | UPDATE [IGNORE] . 376 | SET lista_de_atribuições 377 | [WHERE condição] 378 | [ORDER BY ...] 379 | [LIMIT contagem_de_linhas] 380 | 381 | lista_de_atribuições: 382 | atribuição [, atribuição] ... 383 | 384 | atribuição: 385 | coluna = valor 386 | ``` 387 | 390 | 391 | **Exemplos** 392 | 393 | ```sql 394 | UPDATE sakila.actor 395 | SET last_name = 'Bauman' 396 | WHERE first_name = 'ZERO'; 397 | ``` 398 | 399 | ```sql 400 | UPDATE sakila.staff 401 | SET first_name = 'Jean-Paul', last_name = 'Sartre' 402 | WHERE first_name = 'Mike'; 403 | ``` 404 | 405 | ⚠️ Caso seja necessário fazer um `UPDATE` sem `WHERE`: 406 | 407 | ```sql 408 | SET SQL_SAFE_UPDATES = 0; 409 | ``` 410 | 411 | ```sql 412 | UPDATE sakila.actor 413 | SET first_name = 'Nina', last_name = 'Simone'; 414 | ``` 415 | 416 | ## `DELETE` 417 | 418 | **Template** 419 | 420 | ```sql 421 | DELETE [IGNORE] FROM 422 | [WHERE condição] 423 | [ORDER BY ...] 424 | [LIMIT contagem_de_linhas] 425 | ``` 426 | 427 | **Exemplos** 428 | 429 | ```sql 430 | DELETE FROM sakila.actor 431 | WHERE first_name = 'NICK'; 432 | ``` 433 | 434 | 435 | ⚠️ Caso seja necessário fazer um `DELETE` sem `WHERE`: 436 | 437 | ```sql 438 | SET SQL_SAFE_UPDATES = 0; 439 | ``` 440 | 441 | ```sql 442 | DELETE FROM sakila.staff; 443 | ``` 444 | 445 | -------------------------------------------------------------------------------- /backend/nodejs/npm/README.md: -------------------------------------------------------------------------------- 1 | # NPM Comandos Cheat Sheet 2 | 3 | # Sumário 4 | 5 | - [Criar novo pacote Node.js](#criar-novo-pacote-nodejs) 6 | - [Cria o arquivo `package.json` personalizado](#cria-o-arquivo-packagejson-personalizado) 7 | - [Cria o arquivo `package.json` padrão](#cria-o-arquivo-packagejson-padrão) 8 | - [Instalar pacotes no Node.js](#instalar-pacotes-no-nodejs) 9 | - [Instala **todas** as depedências do arquivo `package.json`](#instala-todas-as-depedências-do-arquivo-packagejson) 10 | - [Instala o **pacote desejado** nas depedências do arquivo `package.json`](#instala-o-pacote-desejado-nas-depedências-do-arquivo-packagejson) 11 | - [Instala o **pacote desejado** nas depedências de **desenvolvimento** do arquivo `package.json`](#instala-o-pacote-desejado-nas-depedências-de-desenvolvimento-do-arquivo-packagejson) 12 | - [Remover pacotes no Node.js](#remover-pacotes-no-nodejs) 13 | - [Remove o **pacote desejado** das depedências do arquivo `package.json`](#remove-o-pacote-desejado-das-depedências-do-arquivo-packagejson) 14 | - [Criar scripts no arquivo `package.json`](#criar-scripts-no-arquivo-packagejson) 15 | - [Cria script para iniciar a **aplicação principal**](#cria-script-para-iniciar-a-aplicação-principal) 16 | - [Cria **script personalizado** para o pacote desejado](#cria-script-personalizado-para-o-pacote-desejado) 17 | - [Executar scripts do arquivo `package.json`](#executar-scripts-do-arquivo-packagejson) 18 | - [Executa a **aplicação principal** do pacote que esta criando](#executa-a-aplicação-principal-do-pacote-que-esta-criando) 19 | - [Executa o **script registrado** no arquivo `package.json`](#executa-o-script-registrado-no-arquivo-packagejson) 20 | 21 | --- 22 | 23 | ## Criar novo pacote Node.js 24 | 25 | --- 26 | 27 | ### Cria o arquivo `package.json` personalizado 28 | ```shell 29 | $ npm init 30 | ``` 31 | 32 | ### Cria o arquivo `package.json` padrão 33 | ```shell 34 | $ npm init -y 35 | ``` 36 | 37 | [Voltar para Sumário](#sumário) 38 | 39 | --- 40 | 41 | ## Instalar pacotes no Node.js 42 | 43 | --- 44 | 45 | ### Instala **todas** as depedências do arquivo `package.json` 46 | ```shell 47 | $ npm install 48 | ``` 49 | 50 | ### Instala o **pacote desejado** nas depedências do arquivo `package.json` 51 | 52 | **Template** 53 | ```shell 54 | $ npm install 55 | ``` 56 | 57 | **Exemplo** 58 | ```shell 59 | $ npm install express 60 | ``` 61 | 62 | ### Instala o **pacote desejado** nas depedências de **desenvolvimento** do arquivo `package.json` 63 | 64 | **Template** 65 | ```shell 66 | $ npm install --save-dev 67 | ``` 68 | OU 69 | ```shell 70 | $ npm install -D 71 | ``` 72 | 73 | **Exemplo** 74 | ```shell 75 | $ npm install jest --save-dev 76 | ``` 77 | OU 78 | ```shell 79 | $ npm install jest -D 80 | ``` 81 | 82 | [Voltar para Sumário](#sumário) 83 | 84 | --- 85 | 86 | ## Remover pacotes no Node.js 87 | 88 | --- 89 | 90 | ### Remove o **pacote desejado** das depedências do arquivo `package.json` 91 | 92 | **Template** 93 | ```shell 94 | $ npm rm 95 | ``` 96 | 97 | **Exemplo** 98 | ```shell 99 | $ npm rm express 100 | ``` 101 | 102 | [Voltar para Sumário](#sumário) 103 | 104 | --- 105 | 106 | ## Criar scripts no arquivo `package.json` 107 | 108 | --- 109 | 110 | ### Cria script para iniciar a **aplicação principal** 111 | **Template** 112 | ```json 113 | { 114 | "scripts": { 115 | "start": "node nome_do_seu_arquivo.js" 116 | } 117 | } 118 | ``` 119 | 120 | **Exemplo** 121 | ```json 122 | { 123 | "scripts": { 124 | "start": "node index.js" 125 | } 126 | } 127 | ``` 128 | 129 | ### Cria **script personalizado** para o pacote desejado 130 | **Template** 131 | ```json 132 | { 133 | "scripts": { 134 | "nome_do_comando_do_script": "o_que_deseja_executar" 135 | } 136 | } 137 | ``` 138 | **Exemplo** 139 | ```json 140 | { 141 | "scripts": { 142 | "lint": "eslint ." 143 | } 144 | } 145 | ``` 146 | 147 | [Voltar para Sumário](#sumário) 148 | 149 | --- 150 | 151 | ## Executar scripts do arquivo `package.json` 152 | 153 | --- 154 | 155 | ### Executa a **aplicação principal** do pacote que esta criando 156 | 157 | ```shell 158 | $ npm start 159 | ``` 160 | 161 | ### Executa o **script registrado** no arquivo `package.json` 162 | 163 | **Template** 164 | ```shell 165 | $ npm run 166 | ``` 167 | 168 | **Exemplo** 169 | ```shell 170 | $ npm run lint 171 | ``` 172 | 173 | [Voltar para Sumário](#sumário) 174 | 175 | --- 176 | -------------------------------------------------------------------------------- /backend/sequelize/queries/README.md: -------------------------------------------------------------------------------- 1 | # Sequelize Queries Cheat Sheet 2 | 3 | # Sumário 4 | 5 | - [Sequelize Queries Cheat Sheet](#sequelize-queries-cheat-sheet) 6 | - [Sumário](#sumário) 7 | - [Operadores](#operadores) 8 | - [Métodos](#métodos) 9 | - [create](#create) 10 | - [update](#update) 11 | - [destroy](#destroy) 12 | - [findAll](#findall) 13 | - [SELECT simples](#select-simples) 14 | - [SELECT específico](#select-específico) 15 | - [Sem alias](#sem-alias) 16 | - [Com alias](#com-alias) 17 | - [SELECT Agregações](#select-agregações) 18 | - [SELECT com WHERE](#select-com-where) 19 | - [GROUP BY](#group-by) 20 | - [LIMIT / OFFSET](#limit--offset) 21 | - [findByPK](#findbypk) 22 | - [findOne](#findone) 23 | - [findOrCreate](#findorcreate) 24 | - [findAndCountAll](#findandcountall) 25 | - [count](#count) 26 | - [max](#max) 27 | - [min](#min) 28 | - [sum](#sum) 29 | 30 | --- 31 | 32 | # Operadores 33 | 34 | ```javascript 35 | const { Op } = require("sequelize"); 36 | await Post.findAll({ 37 | where: { 38 | [Op.and]: [{ a: 5 }, { b: 6 }], // (a = 5) AND (b = 6) 39 | [Op.or]: [{ a: 5 }, { b: 6 }], // (a = 5) OR (b = 6) 40 | someAttribute: { 41 | // Basics 42 | [Op.eq]: 3, // = 3 43 | [Op.ne]: 20, // != 20 44 | [Op.is]: null, // IS NULL 45 | [Op.not]: true, // IS NOT TRUE 46 | [Op.or]: [5, 6], // (someAttribute = 5) OR (someAttribute = 6) 47 | 48 | // Using dialect specific column identifiers (PG in the following example): 49 | [Op.col]: 'user.organization_id', // = "user"."organization_id" 50 | 51 | // Number comparisons 52 | [Op.gt]: 6, // > 6 53 | [Op.gte]: 6, // >= 6 54 | [Op.lt]: 10, // < 10 55 | [Op.lte]: 10, // <= 10 56 | [Op.between]: [6, 10], // BETWEEN 6 AND 10 57 | [Op.notBetween]: [11, 15], // NOT BETWEEN 11 AND 15 58 | 59 | // Other operators 60 | 61 | [Op.all]: sequelize.literal('SELECT 1'), // > ALL (SELECT 1) 62 | 63 | [Op.in]: [1, 2], // IN [1, 2] 64 | [Op.notIn]: [1, 2], // NOT IN [1, 2] 65 | 66 | [Op.like]: '%hat', // LIKE '%hat' 67 | [Op.notLike]: '%hat', // NOT LIKE '%hat' 68 | [Op.startsWith]: 'hat', // LIKE 'hat%' 69 | [Op.endsWith]: 'hat', // LIKE '%hat' 70 | [Op.substring]: 'hat', // LIKE '%hat%' 71 | [Op.iLike]: '%hat', // ILIKE '%hat' (case insensitive) (PG only) 72 | [Op.notILike]: '%hat', // NOT ILIKE '%hat' (PG only) 73 | [Op.regexp]: '^[h|a|t]', // REGEXP/~ '^[h|a|t]' (MySQL/PG only) 74 | [Op.notRegexp]: '^[h|a|t]', // NOT REGEXP/!~ '^[h|a|t]' (MySQL/PG only) 75 | [Op.iRegexp]: '^[h|a|t]', // ~* '^[h|a|t]' (PG only) 76 | [Op.notIRegexp]: '^[h|a|t]', // !~* '^[h|a|t]' (PG only) 77 | 78 | [Op.any]: [2, 3], // ANY ARRAY[2, 3]::INTEGER (PG only) 79 | } 80 | } 81 | }); 82 | ``` 83 | 84 | # Métodos 85 | 86 | ## create 87 | 88 | **Template** 89 | 90 | ```javascript 91 | await Model.create({ 92 | : , 93 | ..., 94 | : , 95 | }); 96 | ``` 97 | 98 | **Exemplo** 99 | 100 | ```javascript 101 | await User.create({ 102 | fullName: "Jane Doe", 103 | email: "jane.doe@gmail.com", 104 | }); 105 | ``` 106 | 107 | **Query MySQL Equivalente** 108 | 109 | ```sql 110 | INSERT INTO Users('fullName', 'email') 111 | VALUES ('Jane Doe', 'jane.doe@gmail.com'); 112 | ``` 113 | 114 | [Documentação](https://sequelize.org/master/manual/model-querying-basics.html#simple-insert-queries) 115 | 116 | [Voltar para Sumário](#sumário) 117 | 118 | --- 119 | 120 | ## update 121 | 122 | **Template** 123 | 124 | ```javascript 125 | await Model.update( 126 | { 127 | : , 128 | ..., 129 | : 130 | }, 131 | { 132 | where: { }, 133 | }, 134 | ); 135 | ``` 136 | 137 | **Exemplo** 138 | 139 | ```javascript 140 | await User.update( 141 | { lastName: "Doe" }, 142 | { 143 | where: { lastName: null }, 144 | }, 145 | ); 146 | ``` 147 | 148 | **Query MySQL Equivalente** 149 | 150 | ```sql 151 | UPDATE user 152 | SET lastName = 'Doe' 153 | WHERE lastName = 'null'; 154 | ``` 155 | 156 | [Documentação](https://sequelize.org/master/manual/model-querying-basics.html#simple-update-queries) 157 | 158 | [Voltar para Sumário](#sumário) 159 | 160 | --- 161 | 162 | ## destroy 163 | 164 | **Template** 165 | 166 | ```javascript 167 | await Model.destroy({ 168 | where: { 169 | : , 170 | }, 171 | }); 172 | ``` 173 | 174 | **Exemplo** 175 | 176 | ```javascript 177 | await User.destroy({ 178 | where: { 179 | firstName: "Jane", 180 | }, 181 | }); 182 | ``` 183 | 184 | **Query MySQL Equivalente** 185 | 186 | ```sql 187 | DELETE FROM User 188 | WHERE firstname = 'Jane'; 189 | ``` 190 | 191 | [Documentação](https://sequelize.org/master/manual/model-querying-basics.html#simple-delete-queries) 192 | 193 | [Voltar para Sumário](#sumário) 194 | 195 | --- 196 | 197 | ## findAll 198 | 199 | ### SELECT simples 200 | 201 | **Template** 202 | 203 | ```javascript 204 | await Model.findAll(); 205 | ``` 206 | 207 | **Exemplo** 208 | 209 | ```javascript 210 | await User.findAll(); 211 | ``` 212 | 213 | **Query MySQL Equivalente** 214 | 215 | ```sql 216 | SELECT * FROM User; 217 | ``` 218 | 219 | [Documentação](https://sequelize.org/master/manual/model-querying-basics.html#simple-select-queries) 220 | 221 | [Voltar para Sumário](#sumário) 222 | 223 | --- 224 | 225 | ### SELECT específico 226 | 227 | #### Sem alias 228 | 229 | **Template** 230 | 231 | ```javascript 232 | await Model.findAll({ 233 | attributes: [ , ], 234 | }); 235 | ``` 236 | 237 | **Exemplo** 238 | 239 | ```javascript 240 | await Products.findAll({ 241 | attributes: [ 'price', 'stock' ], 242 | }); 243 | ``` 244 | 245 | **Query MySQL Equivalente** 246 | 247 | ```sql 248 | SELECT price, stock FROM Products; 249 | ``` 250 | 251 | [Documentação](https://sequelize.org/master/manual/model-querying-basics.html#specifying-attributes-for-select-queries) 252 | 253 | [Voltar para Sumário](#sumário) 254 | 255 | --- 256 | 257 | #### Com alias 258 | 259 | **Template** 260 | 261 | ```javascript 262 | await Model.findAll({ 263 | attributes: [ , [ , ], ..., ] 264 | }); 265 | ``` 266 | 267 | **Exemplo** 268 | 269 | ```javascript 270 | await Products.findAll({ 271 | attributes: ['price', ['product_name', 'name'], 'stock'] 272 | }); 273 | ``` 274 | 275 | **Query MySQL Equivalente** 276 | 277 | ```sql 278 | SELECT price, product_name AS name, stock FROM Products; 279 | ``` 280 | 281 | [Documentação](https://sequelize.org/master/manual/model-querying-basics.html#specifying-attributes-for-select-queries) 282 | 283 | [Voltar para Sumário](#sumário) 284 | 285 | --- 286 | 287 | ### SELECT Agregações 288 | 289 | **Template** 290 | 291 | ```javascript 292 | await Model.findAll({ 293 | attributes: [ 294 | , 295 | [ sequelize.fn(, sequelize.col()), ], 296 | ..., 297 | , 298 | ], 299 | }); 300 | ``` 301 | 302 | **Exemplo** 303 | 304 | ```javascript 305 | await Products.findAll({ 306 | attributes: [ 307 | 'foo', 308 | [sequelize.fn('COUNT', sequelize.col('hats')), 'n_hats'], 309 | 'bar' 310 | ] 311 | }); 312 | ``` 313 | 314 | **Query MySQL Equivalente** 315 | 316 | ```sql 317 | SELECT foo, COUNT(hats) AS n_hats, bar FROM Products; 318 | ``` 319 | 320 | [Documentação](https://sequelize.org/master/manual/model-querying-basics.html#specifying-attributes-for-select-queries) 321 | 322 | [Voltar para Sumário](#sumário) 323 | 324 | --- 325 | 326 | ### SELECT com WHERE 327 | 328 | **Template** 329 | 330 | ```javascript 331 | await Model.findAll({ 332 | where: { 333 | : , 334 | ..., 335 | : , 336 | }, 337 | }); 338 | ``` 339 | 340 | **Exemplo** 341 | 342 | ```javascript 343 | await Post.findAll({ 344 | where: { 345 | authorId: 2, 346 | status: 'active' 347 | } 348 | }); 349 | ``` 350 | 351 | **Query MySQL Equivalente** 352 | 353 | ```sql 354 | SELECT * FROM post WHERE authorId = 2 AND status = 'active'; 355 | ``` 356 | 357 | [Documentação](https://sequelize.org/master/manual/model-querying-basics.html#applying-where-clauses) 358 | 359 | [Voltar para Sumário](#sumário) 360 | 361 | --- 362 | 363 | ### GROUP BY 364 | 365 | **Template** 366 | 367 | ```javascript 368 | await Model.findAll({ group: }); 369 | ``` 370 | 371 | **Exemplo** 372 | 373 | ```javascript 374 | await Project.findAll({ group: 'name' }); 375 | ``` 376 | 377 | **Query MySQL Equivalente** 378 | 379 | ```sql 380 | GROUP BY name; 381 | ``` 382 | 383 | [Documentação](https://sequelize.org/master/manual/model-querying-basics.html#grouping) 384 | 385 | [Voltar para Sumário](#sumário) 386 | 387 | --- 388 | 389 | ### LIMIT / OFFSET 390 | 391 | **Template** 392 | 393 | ```javascript 394 | // limit 395 | await Model.findAll({ limit: }); 396 | ``` 397 | 398 | ```javascript 399 | // offset 400 | await Model.findAll({ offset: }); 401 | ``` 402 | 403 | ```javascript 404 | // limit & offset 405 | await Model.findAll({ offset: , limit: }); 406 | ``` 407 | 408 | **Exemplo** 409 | 410 | ```javascript 411 | // limit 412 | await Project.findAll({ limit: 10 }); 413 | ``` 414 | 415 | ```javascript 416 | // offset 417 | await Project.findAll({ offset: 8 }); 418 | ``` 419 | 420 | ```javascript 421 | // limit & offset 422 | await Project.findAll({ offset: 5, limit: 5 }); 423 | ``` 424 | 425 | **Query MySQL Equivalente** 426 | 427 | ```sql 428 | -- limit 429 | SELECT * FROM Project 430 | LIMIT 10; 431 | ``` 432 | 433 | ```sql 434 | -- offset 435 | SELECT * FROM Project 436 | OFFSET 8; 437 | ``` 438 | 439 | ```sql 440 | -- limit & offset 441 | SELECT * FROM Project 442 | OFFSET 5 443 | LIMIT 10; 444 | ``` 445 | 446 | [Documentação](https://sequelize.org/master/manual/model-querying-basics.html#limits-and-pagination) 447 | 448 | [Voltar para Sumário](#sumário) 449 | 450 | --- 451 | 452 | 453 | ## findByPK 454 | 455 | Busca por um resultado, usando sua chave primária. 456 | 457 | **Template** 458 | 459 | ```javascript 460 | const results = await Model.findByPk(valor); 461 | if (project === null) { 462 | console.log('Not found!'); 463 | } else { 464 | console.log(results instanceof Model); // true 465 | // a pk é 466 | } 467 | ``` 468 | 469 | **Exemplo** 470 | 471 | ```javascript 472 | const project = await Project.findByPk(123); 473 | if (project === null) { 474 | console.log('Not found!'); 475 | } else { 476 | console.log(project instanceof Project); // true 477 | // a pk é 123 478 | } 479 | ``` 480 | 481 | [Documentação](https://sequelize.org/master/manual/model-querying-finders.html#-code-findbypk--code-) 482 | 483 | [Voltar para Sumário](#sumário) 484 | 485 | --- 486 | 487 | ## findOne 488 | 489 | Busca o primeiro resultado filtrado pela busca. 490 | 491 | **Template** 492 | 493 | ```javascript 494 | const results = await Model.findOne({ where: { campo: valor } }); 495 | if (results === null) { 496 | console.log('Not found!'); 497 | } else { 498 | console.log(results instanceof Model); // true 499 | console.log(results.campo); // valor 500 | } 501 | ``` 502 | 503 | **Exemplo** 504 | 505 | ```javascript 506 | const project = await Project.findOne({ where: { title: 'Título' } }); 507 | if (project === null) { 508 | console.log('Not found!'); 509 | } else { 510 | console.log(project instanceof Project); // true 511 | console.log(project.title); // 'Título' 512 | } 513 | ``` 514 | 515 | [Documentação](https://sequelize.org/master/manual/model-querying-finders.html#-code-findone--code-) 516 | 517 | [Voltar para Sumário](#sumário) 518 | 519 | --- 520 | 521 | ## findOrCreate 522 | 523 | Criará uma entrada na tabela, a menos que encontre um resultado que preencha as opções de consulta. 524 | 525 | > Obs.: Em ambos os casos, ele retornará uma instância (a instância encontrada ou a instância criada) e um booleano indicando se essa instância foi criada ou já existia. 526 | 527 | **Template** 528 | 529 | ```javascript 530 | const [file, created] = await Model.findOrCreate({ 531 | where: { filename: nome }, 532 | defaults: { 533 | campo: valor 534 | } 535 | }); 536 | console.log(file.filename); 537 | console.log(file.campo); 538 | console.log(created); 539 | if (created) { 540 | console.log(file.campo); 541 | } 542 | ``` 543 | 544 | **Exemplo** 545 | 546 | ```javascript 547 | const [user, created] = await User.findOrCreate({ 548 | where: { username: 'Eric' }, 549 | defaults: { 550 | job: 'Technical Lead JavaScript' 551 | } 552 | }); 553 | console.log(user.username); // 'Eric' 554 | console.log(user.job); // pode ou não ser 'Technical Lead JavaScript' 555 | console.log(created); // Valor booleano que indica se a instancia foi criada ou nao 556 | if (created) { 557 | console.log(user.job); // 'Technical Lead JavaScript' 558 | } 559 | ``` 560 | 561 | [Documentação](https://sequelize.org/master/manual/model-querying-finders.html#-code-findorcreate--code-) 562 | 563 | [Voltar para Sumário](#sumário) 564 | 565 | --- 566 | 567 | ## findAndCountAll 568 | 569 | Método conveniente que combina findAll e count. 570 | 571 | **Template** 572 | 573 | ```javascript 574 | const { count, rows } = await Model.findAndCountAll({ 575 | where: { 576 | campo: { 577 | [Op.]: 'foo%' 578 | } 579 | } 580 | }); 581 | ``` 582 | 583 | **Exemplo** 584 | 585 | ```javascript 586 | const { Op } = require("sequelize"); 587 | 588 | const { count, rows } = await Project.findAndCountAll({ 589 | where: { 590 | title: { 591 | [Op.like]: 'foo%' 592 | } 593 | }, 594 | offset: 10, 595 | limit: 2 596 | }); 597 | 598 | console.log(count); 599 | console.log(rows); 600 | ``` 601 | 602 | [Documentação](https://sequelize.org/master/manual/model-querying-finders.html#-code-findandcountall--code-) 603 | 604 | [Sessão Operadores](#operadores) 605 | 606 | [Voltar para Sumário](#sumário) 607 | 608 | --- 609 | 610 | ## count 611 | 612 | **Template** 613 | 614 | ```javascript 615 | // simples 616 | await Model.count(); 617 | ``` 618 | 619 | ```javascript 620 | // com filtro 621 | const { Op } = require("sequelize"); 622 | 623 | await Model.count({ 624 | where: { 625 | : { 626 | [Op.]: , 627 | }, 628 | }, 629 | }); 630 | ``` 631 | 632 | **Exemplo** 633 | 634 | ```javascript 635 | // com filtro 636 | const { Op } = require("sequelize"); 637 | 638 | await Project.count({ 639 | where: { 640 | id: { 641 | [Op.gt]: 25 642 | } 643 | } 644 | }); 645 | ``` 646 | 647 | **Query MySQL Equivalente** 648 | 649 | ```sql 650 | SELECT COUNT('id') from project 651 | WHERE 'id' > 25; 652 | ``` 653 | 654 | [Documentação](https://sequelize.org/master/manual/model-querying-basics.html#-code-count--code-) 655 | 656 | [Sessão Operadores](#operadores) 657 | 658 | [Voltar para Sumário](#sumário) 659 | 660 | --- 661 | 662 | ## max 663 | 664 | **Template** 665 | 666 | ```javascript 667 | await Model.max(); 668 | ``` 669 | 670 | **Exemplo** 671 | 672 | ```javascript 673 | await User.max('age'); 674 | ``` 675 | 676 | ```javascript 677 | // com filtragem 678 | const { Op } = require("sequelize"); 679 | 680 | await User.max('age', { 681 | where: { 682 | age: { [Op.lt]: 20 }, 683 | }, 684 | }); 685 | ``` 686 | 687 | **Query MySQL Equivalente** 688 | 689 | ```sql 690 | SELECT MAX(age) FROM User; 691 | ``` 692 | 693 | ```sql 694 | --- com filtagem 695 | SELECT MAX(age) 696 | FROM User 697 | WHERE age < 20; 698 | ``` 699 | 700 | [Documentação](https://sequelize.org/master/manual/model-querying-basics.html#-code-max--code----code-min--code--and--code-sum--code-) 701 | 702 | [Sessão Operadores](#operadores) 703 | 704 | [Voltar para Sumário](#sumário) 705 | 706 | --- 707 | 708 | ## min 709 | 710 | **Template** 711 | 712 | ```javascript 713 | await Model.min(); 714 | ``` 715 | 716 | **Exemplo** 717 | 718 | ```javascript 719 | await User.min('age'); 720 | ``` 721 | 722 | ```javascript 723 | // com filtragem 724 | const { Op } = require("sequelize"); 725 | 726 | await User.min('age', { 727 | where: { 728 | age: { [Op.gt]: 5 }, 729 | }, 730 | }); 731 | ``` 732 | 733 | **Query MySQL Equivalente** 734 | 735 | ```sql 736 | SELECT MIN(age) FROM User; 737 | ``` 738 | 739 | ```sql 740 | --- com filtagem 741 | SELECT MIN(age) 742 | FROM User 743 | WHERE age > 5; 744 | ``` 745 | 746 | [Documentação](https://sequelize.org/master/manual/model-querying-basics.html#-code-max--code----code-min--code--and--code-sum--code-) 747 | 748 | [Sessão Operadores](#operadores) 749 | 750 | [Voltar para Sumário](#sumário) 751 | 752 | --- 753 | 754 | ## sum 755 | 756 | **Template** 757 | 758 | ```javascript 759 | await Model.sum(); 760 | ``` 761 | 762 | **Exemplo** 763 | 764 | ```javascript 765 | await User.sum('age'); 766 | ``` 767 | 768 | ```javascript 769 | // com filtragem 770 | const { Op } = require("sequelize"); 771 | 772 | await User.sum('age', { 773 | where: { 774 | age: { [Op.gt]: 5 }, 775 | }, 776 | }); 777 | ``` 778 | 779 | **Query MySQL Equivalente** 780 | 781 | ```sql 782 | SELECT SUM(age) FROM User; 783 | ``` 784 | 785 | ```sql 786 | --- com filtagem 787 | SELECT SUM(age) 788 | FROM User 789 | WHERE age > 5; 790 | ``` 791 | 792 | [Documentação](https://sequelize.org/master/manual/model-querying-basics.html#-code-max--code----code-min--code--and--code-sum--code-) 793 | 794 | [Sessão Operadores](#operadores) 795 | 796 | [Voltar para Sumário](#sumário) 797 | 798 | --- 799 | -------------------------------------------------------------------------------- /backend/sequelize/setup/README.md: -------------------------------------------------------------------------------- 1 | # Sequelize Setup Cheat Sheet 2 | 3 | # Sumário 4 | 5 | - [Sequelize Setup Cheat Sheet](#sequelize-setup-cheat-sheet) 6 | - [Sumário](#sumário) 7 | - [Guia](#guia) 8 | - [Instalação das dependências](#instalação-das-dependências) 9 | - [Instalação do sequelize](#instalação-do-sequelize) 10 | - [Instalação do pacote de comandos CLI](#instalação-do-pacote-de-comandos-cli) 11 | - [Instalação do `mysql2`](#instalação-do-mysql2) 12 | - [Inicialização de um projeto sequelize](#inicialização-de-um-projeto-sequelize) 13 | - [Criação de um arquivo _model_](#criação-de-um-arquivo-model) 14 | - [Arquivos _migration_](#arquivos-migration) 15 | - [Criação de um arquivo _migration_](#criação-de-um-arquivo-migration) 16 | - [Execução dos arquivos _migration_](#execução-dos-arquivos-migration) 17 | - [Reverter a _migration_](#reverter-a-migration) 18 | - [Reverter até uma _migration_ específica](#reverter-até-uma-migration-específica) 19 | - [Arquivos _seeds_](#arquivos-seeds) 20 | - [Criação de um arquivo _seed_](#criação-de-um-arquivo-seed) 21 | - [Execução dos arquivos _seeds_](#execução-dos-arquivos-seeds) 22 | - [Reversão dos arquivos _seeds_](#reversão-dos-arquivos-seeds) 23 | - [Reverter todos arquivos _seeds_](#reverter-todos-arquivos-seeds) 24 | - [Reverter _seed_ mais recente](#reverter-seed-mais-recente) 25 | - [Reverter _seed_ específica](#reverter-seed-específica) 26 | 27 | --- 28 | 29 | # Guia 30 | 31 | ## Instalação das dependências 32 | 33 | ### Instalação do sequelize 34 | 35 | ```bash 36 | $ npm install sequelize 37 | ``` 38 | 39 | [Voltar para Sumário](#sumário) 40 | 41 | --- 42 | 43 | ### Instalação do pacote de comandos CLI 44 | 45 | ```bash 46 | $ npm install --save-dev sequelize-cli 47 | ``` 48 | 49 | [Voltar para Sumário](#sumário) 50 | 51 | --- 52 | 53 | ### Instalação do `mysql2` 54 | 55 | ```bash 56 | $ npm install mysql2 57 | ``` 58 | 59 | [Voltar para Sumário](#sumário) 60 | 61 | --- 62 | 63 | ## Inicialização de um projeto sequelize 64 | 65 | > O comando criará as pastas models, migrations, seeders e config. 66 | 67 | ```bash 68 | $ npx sequelize-cli init 69 | ``` 70 | 71 | [Voltar para Sumário](#sumário) 72 | 73 | --- 74 | 75 | ## Criação de um arquivo _model_ 76 | 77 | > O comando irá gerar o arquivo model e o arquivo migration correspondente. 78 | 79 | ```bash 80 | $ npx sequelize model:generate --name NomeDoModel --attributes nomeDoAtributo:string 81 | ``` 82 | 83 | [Voltar para Sumário](#sumário) 84 | 85 | --- 86 | 87 | ## Arquivos _migration_ 88 | 89 | ### Criação de um arquivo _migration_ 90 | 91 | ```bash 92 | $ npx sequelize migration:generate --name migrationName 93 | ``` 94 | 95 | [Voltar para Sumário](#sumário) 96 | 97 | --- 98 | 99 | ### Execução dos arquivos _migration_ 100 | 101 | ```bash 102 | $ npx sequelize db:migrate 103 | ``` 104 | 105 | [Voltar para Sumário](#sumário) 106 | 107 | --- 108 | 109 | ### Reverter a _migration_ 110 | 111 | ```bash 112 | $ npx sequelize db:migrate:undo 113 | ``` 114 | 115 | [Voltar para Sumário](#sumário) 116 | 117 | --- 118 | 119 | ### Reverter até uma _migration_ específica 120 | 121 | ```bash 122 | $ npx sequelize-cli db:migrate:undo:all --to XXXXXXXXXXXXXX-create-posts.js 123 | ``` 124 | 125 | [Voltar para Sumário](#sumário) 126 | 127 | --- 128 | 129 | ## Arquivos _seeds_ 130 | 131 | ### Criação de um arquivo _seed_ 132 | 133 | ```bash 134 | $ npx sequelize seed:generate --name seedName 135 | ``` 136 | 137 | [Voltar para Sumário](#sumário) 138 | 139 | --- 140 | 141 | ### Execução dos arquivos _seeds_ 142 | 143 | > O comando executa **todos** os arquivos seeds 144 | 145 | ```bash 146 | $ npx sequelize db:seed:all 147 | ``` 148 | 149 | [Voltar para Sumário](#sumário) 150 | 151 | --- 152 | 153 | ### Reversão dos arquivos _seeds_ 154 | 155 | #### Reverter todos arquivos _seeds_ 156 | 157 | ```bash 158 | $ npx sequelize db:seed:undo:all 159 | ``` 160 | 161 | [Voltar para Sumário](#sumário) 162 | 163 | --- 164 | 165 | #### Reverter _seed_ mais recente 166 | 167 | ```bash 168 | $ npx sequelize-cli db:seed:undo 169 | ``` 170 | 171 | [Voltar para Sumário](#sumário) 172 | 173 | --- 174 | 175 | #### Reverter _seed_ específica 176 | 177 | ```bash 178 | $ npx sequelize-cli db:seed:undo --seed name-of-seed-as-in-data 179 | ``` 180 | 181 | [Voltar para Sumário](#sumário) 182 | 183 | --- 184 | -------------------------------------------------------------------------------- /frontend/README.md: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/tryber/Trybe-CheatSheets/25d9c24deca0045098b8d684c71a09598e772b2b/frontend/README.md --------------------------------------------------------------------------------