Bancos de Dados Relacionais (SQL) na AWS com Amazon RDS

Overview

Bancos de Dados Relacionais (SQL) na AWS com Amazon RDS

Repositório para o Live Coding DIO do dia 24/11/2021

Serviços utilizados

  • Amazon RDS
  • AWS Lambda
  • MySQL Workbench

Criando o banco de dados no Amazon RDS

  • AWS Console -> Amazon RDS -> Create database -> Standard create -> MySQL -> Versão padrão -> Free Tier -> DB instance identifier [dio-live-db] -> Master username [admin] -> Master password [sua_senha_forte] -> DB instance size - padrão -> Storage - configurações padrão -> Connectivity - vpc padrão -> Publicly accessible [yes] -> VPC Security - padrão -> Database authentication [password authentication] -> Create database
  • Selecionar o DB criado -> Connectivity & security -> Copiar endpoint.

No MySQL Workbench

  • MySQL Connections -> New -> Connection name [DioLive] -> Hostname - colar o endpoint copiado no passo anterior -> Username [admin] -> Teste Connection -> Password [sua_senha]

Em caso de problemas na conexão

  • Security -> VPC security groups -> Acessar o SG criado -> Inbound -> Edit -> Add rule -> type [All traffic] -> Source [Anywhere] -> Save

No MySQL Workbench

  • Selecionar a conexão criada -> Password [sua_senha_forte]

Criando queries

  • Criar um database:

    CREATE DATABASE PERMISSIONS_DB;

  • Acessar o db criado

    USE PERMISSIONS_DB;

  • Criar uma tabela de usuários

    CREATE TABLE user (
      id bigint(20) NOT NULL, 
      email varchar(40) NOT NULL,
      username varchar(15) NOT NULL,
      password varchar(100) NOT NULL,
      PRIMARY KEY (id)
    );
    
  • Criar uma tabela de carrinho de compras

    CREATE TABLE role (
      id bigint(20) NOT NULL,
      name varchar(60) NOT NULL, 
      PRIMARY KEY (id)
    );
    
  • Criar uma tabela associativa de itens em um carrinho de compras

    CREATE TABLE ITEMS (
      cart_id INT NOT NULL,
      product_id INT NOT NULL,
      quantity DECIMAL(15,2) NOT NULL,
      FOREIGN KEY (cart_id) REFERENCES CARTS (id),
      FOREIGN KEY (product_id) REFERENCES PRODUCTS (id)
    );
    
  • Descrevendo o esquema de uma tabela

    CREATE TABLE user_roles (
      user_id bigint(20) NOT NULL,
      role_id bigint(20) NOT NULL,
      FOREIGN KEY (user_id) REFERENCES user (id) ON DELETE RESTRICT ON UPDATE CASCADE,
      FOREIGN KEY (role_id) REFERENCES role (id) ON DELETE RESTRICT ON UPDATE CASCADE,
      PRIMARY KEY (user_id, role_id)
    );
    
  • Inserindo dados em tabelas

    INSERT INTO user VALUES (1, '[email protected]', 'Cassiano', 'strongpasswd');
    INSERT INTO user VALUES (2, '[email protected]', 'Joao', 'strongpasswd');
    
    INSERT INTO role VALUES (3, 'ADMIN');
    INSERT INTO role VALUES (4, 'USER');
    
    INSERT INTO user_roles VALUES (1, 3);
    INSERT INTO user_roles VALUES (1, 4);
    INSERT INTO user_roles VALUES (2, 4);
    
  • Selecionando todos os registros de uma tabela

    SELECT * FROM [table_name];
    
  • Selecionando dados da tabela associativa

    SELECT user.id, user.email, user.username, role.id AS role_id, role.name AS role_name
    FROM user 
    JOIN user_roles on (user.id=user_roles.user_id)
    JOIN role on (role.id=user_roles.role_id);
    

Realizando queries no Amazon RDS a partir de uma função no AWS Lambda

Criando a função Lambda

  • Acessar o AWS Lambda console -> Create function -> Author from scratch -> Function name [RDSQuery] -> Runtime - Python3.9 -> Create new role from AWS policy template -> Role name [RDSQueryFromLambdaRole] -> Create function

Configurando permissões de acesso ao RDS

  • Selecionar a função criada -> Configuration -> Permissions -> Selecionar a função criada e abrir no console do AWS IAM
  • Attach policies -> Pesquisar pela policy AWSLambdaVPCAccessExecutionRole -> Attach policy

Desenvolvendo o código da função Lambda

  • Editor de código da função criada -> Inserir o código disponível na pasta src deste projeto

Importando a biblioteca pymysql utilizando Lambda Layers

  • Lambda Dashboard -> Layers -> Create layer -> Name [pymysql_layer] -> Upload a .zip file - o arquivo pyton.zip está disponível na pasta src do projeto -> Compatible architectures x86_64 -> Compatible runtimes - Python 3.9 -> Create
  • Lambda Dashboard -> selecionar a função criada -> Layers -> Add a layer -> Custom layers -> selecionar o layer criado anteriormente -> Add

Testando a função criada

  • Test -> New event -> Template -> Hello World -> Name [test] -> Save changes -> Test
Owner
Cassiano Ricardo de Oliveira Peres
NodeJs, blockchain and cloud developer. Cryptocurrency enthusiastic.
Cassiano Ricardo de Oliveira Peres
An powerfull telegram group management anime themed bot.

ErzaScarlet Erza Scarlet is the female deuteragonist of the anime/manga series Fairy Tail. She is an S-class Mage from the Guild Fairy Tail. Like most

ꜱōʜᴇʀᴜ ᴋāɴ (AKA) ꜱᴏʜᴀɪʟ ᴋʜᴀɴ 2 May 19, 2022
A Twitch bot to provide information from the WebNowPlayingCompanion extension

WebNowPlayingTwitch A Twitch bot made using TwitchIO which displays information obtained from the WebNowPlaying Compaion browser extension. Image is o

NiceAesth 1 Mar 21, 2022
ShotsGram - For sending captures from your monitor to a telegram chat (robot)

ShotsGram pt-BR Envios de capturas do seu monitor para um chat do telegram. Essa

Carlos Alberto 1 Apr 24, 2022
An example of matrix addition, demonstrating the basic method of Python calling C library functions

Example for Python call C functions An example of matrix addition, demonstrating the basic method of Python calling C library functions. How to run Bu

Quantum LIu 2 Dec 21, 2021
Solves bombcrypto newest captcha

Solves Bombcrypto newest captcha A very compact implementation using just cv2 and ctypes, ready to be deployed to your own project. How does it work I

19 May 06, 2022
Automatically download any NFT collection from OpenSea.

OpenSea NFT Stealer The sole purpose of this script is to download any NFT collection from OpenSea. How does it work? Basically, the OpenSea website a

Dan 111 Dec 29, 2022
Connect your Nintendo Switch playing status to Discord!

Disclaimer: Unfortunately, it appears that Nintendo has removed returning self-Presence in their API as of recently, making this project near obsolete

Deltaion Lee 145 Dec 30, 2022
Automated JSON API based communication with Fronius Symo

PyFronius - a very basic Fronius python bridge A package that connects to a Fronius device in the local network and provides data that is provided via

Niels Mündler 10 Dec 30, 2022
A command line interface for accessing google drive

Drive Cli Get the ability to access Google Drive without leaving your terminal. Inspiration Google Drive has become a vital part of our day to day lif

Chirag Shetty 538 Dec 12, 2022
Tinyman Python SDK

tinyman-py-sdk Tinyman Python SDK Design Goal This SDK is designed for automated interaction with the Tinyman AMM. It will be most useful for develope

Tinyman 113 Dec 30, 2022
nuub-bot is a multi-purpose designed and developed in python3

nuub-bot About Nuub-Bot is an open source, fully customizable Discord bot that is constantly growing. You can invite it to your Discord server using t

Baneet Parmar 8 Jun 28, 2022
A GitHub Action that automatically reports your Advent of Code progress in a table in your README

Advent README Stars This action adds and maintains a stars report in your README based on your Advent of Code progress. Example Table 2021 Results Day

Kevin Duff 36 Dec 30, 2022
Demonstrating attacks, mitigations, and monitoring on AWS

About Inspectaroo is a web app which allows users to upload images to view metadata. It is designed to show off many AWS services including EC2, Lambd

Alex McCormack 1 Feb 11, 2022
Leveraged grid-trading bot using CCXT/CCXT Pro library in FTX exchange.

Leveraged-grid-trading-bot The code is designed to perform infinity grid trading strategy in FTX exchange. The basic trader named Gridtrader.py contro

Hao-Liang Wen 25 Oct 07, 2021
Discord raid tool!

GANG Multi Tool Menu: -- YOUTUBE TUTORIAL! Features: Most Advanced Multi Tool! Spammer DM Spammer Friend Spammer Reaction Spam WebhookSpammer Typing

1 Feb 13, 2022
Simple integration between FastAPI and cloud authentication services (AWS Cognito, Auth0, Firebase Authentication).

FastAPI Cloud Auth fastapi-cloudauth standardizes and simplifies the integration between FastAPI and cloud authentication services (AWS Cognito, Auth0

tokusumi 255 Jan 07, 2023
Minimal API for the COVID Booking System of the Offices at the UniPD Math Dep

Simple and easy to use python BOT for the COVID registration booking system of the math department @ unipd (torre archimede). This API creates an interface with the official website, with more useful

Guglielmo Camporese 4 Dec 24, 2021
Very Sempil Bot Auto Filter bot

SAMANTHA_BOT Very Sempil Bot Auto Filter bot ##[ # 𝐂𝐋𝐈𝐂𝐊 𝐁𝐄𝐋𝐎𝐖 𝐈𝐌𝐀𝐆𝐄 𝐓𝐎 𝐃𝐄𝐏𝐋𝐎𝐘 👇 👇 👇 Auto Filter Manuel Filter IMDB Admin Co

DARK WEBLOAD 3 Jun 27, 2022
Simple tool to gather domains from crt.sh using the organization name

Domain Collector: _ _ ___ _ _ _ __| | ___ _ __ ___ __ _(_)_ __ / __\___ | |

Cyber Guy 63 Dec 24, 2022
The system to host your files on the Discord application

Distorage The system to host your files on the Discord application Documentation Documentation Distorage How to use the package You can install it wit

6 Jun 27, 2022