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
This app is providing you to track some online products' prices via GMAIL.

Price Tracking App variables and descriptions of that code is in Turkish language. but we're working on translate them into English. This app is provi

Abdullah Aslan 1 Dec 11, 2021
BSDotPy, A module to get a bombsquad player's account data.

BSDotPy BSDotPy, A module to get a bombsquad player's account data from bombsquad's servers. Badges Provided By: shields.io Acknowledgements Issues Pu

Rudransh Joshi 3 Feb 17, 2022
StudyLion is a Discord bot that tracks members' study and work time while offering members to view their statistics and use productivity tools such as: To-do lists, Pomodoro timers, reminders, and much more.

StudyLion - Discord Productivity Bot StudyLion is a Discord bot that tracks members' study and work time while offering members the ability to view th

45 Dec 26, 2022
🤟The VC Music Source code of @DaisyXBot ❤️ v3 Out now

DAISYXMUSIC V3 🎵 A bot that can play music on telegram group's voice call Available on telegram as @DaisyXbot Whats new 🔥 Thumbnail Support Playlist

TeamDaisyX 207 Dec 05, 2022
pymobiledevice fork with more recent coding standards and many more features

Description Features Installation Usage Sending your own messages Lockdown messages Instruments messages Example Lockdown services com.apple.instrumen

255 Dec 28, 2022
Forked from 0x36 on github who then rewrote the ida_kernelcache python framework

Forked from 0x36 on github who then rewrote the ida_kernelcache python framework. Sadly 0x36 doesn't seem to have push updates to the project and it took me a very long time to figure out why this wa

Turnerhackz1 6 Dec 13, 2022
A Python Script to automate searching of available vaccination centers in the city and hence booking

Cowin Vaccine Availability Notifier Cowin Vaccine Availability Notifier takes your City or PIN code as an input and automatically notifies you via ema

Jayesh Padhiar 7 Sep 05, 2021
Simple Discord bot which logs several events in your server

logging-bot Simple Discord bot which logs several events in your server, including: Message Edits Message Deletes Role Adds Role Removes Member joins

1 Feb 14, 2022
Open Source Discord Account Creator

Alter Token Generator Open Source Discord Account Creator This program abuses the discord api and uses the 2Captcha captcha solving service to make di

24 Dec 13, 2022
A discord program that will send a message to nearly every user in a discord server

Discord Mass DM Scrapes users from a discord server to promote/mass dm Report Bug · Request Feature Features Asynchronous Easy to use Free Auto scrape

dropout 56 Jan 02, 2023
Telegram 隨機色圖,支援每日自動爬取

Telegram 隨機色圖機器人 使用此原始碼的Bot 開放的隨機色圖機器人: @katonei_bot 已實現的功能 爬取每日R18排行榜 不夠色!再來一張 Tag 索引,指定Tag色圖 將爬取到的色圖轉為 WebP 格式儲存,節省空間 需要注意的事件 好久之前的怪東西,代碼質量不保證 請在使用A

cluckbird 15 Oct 18, 2021
Flask-SQLAlchemy API for daisuki-web

💟 Anime Daisuki! API API de animes com cadastro de usuários. O usuário autenticado pode avaliar e favoritar animes, comentar episódios e verificar o

Paulo Thor 1 Nov 04, 2021
NiceHash Python Library and Command Line Rest API

NiceHash Python Library and Command Line Rest API Requirements / Modules pip install requests Required data and where to get it Following data is nee

Ashlin Darius Govindasamy 2 Jan 02, 2022
Tools for Twitter

Tools for Twitter Data This is a start of a collection of tools to use for collecting data via the Twitter API. If you do not have a Twitter Developer

DiscoverText 36 Oct 13, 2022
Wakatime Response In javascript and python

Project Title Wakatime Response In javascript and python Description just for refrence Getting Started Dependencies For Python: requests json For Java

Gjenius20 1 Dec 31, 2021
A fully decentralized protocol for private transactions FAST snipe BUY token on LUANCH after add LIQUIDITY

TORNADO CASH Pancakeswap Sniper BOT 2022-V1 (MAC WINDOWS ANDROID LINUX) ⭐️ A fully decentralized protocol for private and safe transactions ⭐️ AUTO DO

Crypto Trader 2 Jan 06, 2022
The official Pushy SDK for Python apps.

pushy-python The official Pushy SDK for Python apps. Pushy is the most reliable push notification gateway, perfect for real-time, mission-critical app

Pushy 1 Dec 21, 2021
KaydyPurge - Python Purge Script for Discord made by Kaydy Cain#0001

How to Install Open terminal Execute "git clone https://github.com/apolo1337/Kay

apolo 5 Jan 27, 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
Light weight Scripts and Apps for checking availability of Covid Vaccines in India. Notifies when vaccine becomes avialable in your area.

vaccine-checker Light weight Scripts and Apps for checking availability of Covid Vaccines in India. Notifies when vaccine becomes avialable in your ar

Abishek V Ashok 8 Jun 16, 2021