Skip to content
Snippets Groups Projects
Commit 2cf43a51 authored by Emmanuel Bruno's avatar Emmanuel Bruno
Browse files

cleans up.

parent a82ec52f
No related branches found
No related tags found
No related merge requests found
%% Cell type:markdown id:9ea52343-cc9d-4b99-9da9-6fdab656e9f1 tags:
# SGBDR avec PostgreSQL dans un notebook
Ce notebook est une première ébacuhe pour tester ce qu'il est possible de faire pour apprendre les bases de données relationnelles en utilisant des notebooks Jupyter.
%% Cell type:markdown id:106e64f2-2480-406a-9a8b-69759603c37a tags:
## Modélisation
### MEA
Un MEA peut etre réalisé simplement avec [MoCoDo](https://rawgit.com/laowantong/mocodo/master/doc/fr_refman.html).
Cet outils permet entre autres de générer à partir d'une description textuelle, le schéma, le passage vers le modèle relationnel (relations, diagramme des tables et script de création).
%% Cell type:code id:cf6ab1d7-a631-4e6e-8423-76d0fe89346e tags:
``` python
%reload_ext mocodo_magic
```
%% Cell type:code id:03b3dec1-10c1-4018-88e0-9c0c750d8b60 tags:
``` python
%%mocodo --title=client_commande --mld --relations=postgresql
PRODUIT: code, prix_unitaire
INCLURE, 1N COMMANDE, 0N PRODUIT: Quantité
COMMANDE: numero, date
CLIENT: email, nom, prenom
PASSER, 0N CLIENT, 11 COMMANDE
```
%% Output
%% Cell type:markdown id:685c0300-3bf6-4633-840d-6b068f2619ac tags:
Le script SQL est dans le fichier [mocodo_notebook/sandbox_postgresql.sql](mocodo_notebook/sandbox_postgresql.sql).
%% Cell type:markdown id:c4723176-0684-4eec-ba60-d91597046d74 tags:
### UML
Il est possible de construire simplement des diagrammes (dont UML) en utilisant [PlantUML](https://plantuml.com).
%% Cell type:code id:d9f7e6ac-7e6e-4870-8bdd-3f9620d6899d tags:
``` python
import iplantuml
```
%% Cell type:code id:82f26e33-c402-4a03-9d17-3878868b4a12 tags:
``` python
%%plantuml --jar
@startuml
class Commande {
- numero : Integer
- date : Date
}
class Produit {
- code : Integer
- prixUnitaire : Integer
}
class LigneDeCommande {
- quantité : Integer
}
class Client {
- email : String
- nom : String
- prenom : String
}
Commande "*" -> "1..*" Produit : comporte
(Commande, Produit) .. LigneDeCommande
Client "1" -- "*" Commande : passe
@enduml
```
%% Output
<IPython.core.display.SVG object>
%% Cell type:markdown id:8faa6c8f-3be8-4fa4-9675-c3f2f354adfb tags:
## Initialisation connection SGBD
L'intégration de SQL est faite avec [ipython-sql](https://github.com/catherinedevlin/ipython-sql).
Pour commencer, il faut changer l'extension SQL pour jupyter.
%% Cell type:code id:ca072ea3-2f43-4542-a7ba-2d4921ca152f tags:
``` python
%reload_ext sql
```
%% Cell type:markdown id:5427ddce-56ea-461b-ac29-e4864b97ce8b tags:
Le lancement du serveur PostgreSQL et création d'une base de données est automatique avant le lancement dans le répertoire 'work/pgdata/DEMO_DB'.
Le lancement du serveur PostgreSQL et création d'une base de données est automatique avant le lancement. La base de données est stockée physiqment dans le répertoire 'work/pgdata/DEMO_DB'.
L'ouverture d'une connexion à la base de données peut se faire une seule fois ou à chaque requête (il est possible d'avoir plusieurs connections différentes).
%% Cell type:code id:cfbca6ff-1393-43da-aa4c-16869fa6f8e0 tags:
``` python
%sql postgresql://localhost/jovyandb
```
%% Cell type:markdown id:497856bb-827f-4b5c-9479-7a76b1fb4919 tags:
## Utilisation de SQL
L'utilisation SQL peut se faire dans une cellule en le préfixant de %%sql
%% Cell type:code id:2c918a0c-5a0f-4db0-b76a-6ae37d13589a tags:
``` python
%%sql
DROP TABLE IF EXISTS LIGNE_DE_COMMANDE;
DROP TABLE IF EXISTS COMMANDE;
DROP TABLE IF EXISTS CLIENT;
DROP TABLE IF EXISTS PRODUIT;
CREATE TABLE CLIENT (
id_client int GENERATED ALWAYS AS IDENTITY,
email varchar(255) NOT NULL UNIQUE,
nom varchar(100) NOT NULL,
prenom varchar(100) NOT NULL,
PRIMARY KEY(id_client)
);
CREATE TABLE PRODUIT (
code_produit int GENERATED ALWAYS AS IDENTITY,
description varchar(10),
prix_unitaire int,
PRIMARY KEY(code_produit)
);
CREATE TABLE COMMANDE (
numero_commande int GENERATED ALWAYS AS IDENTITY,
date date DEFAULT CURRENT_DATE,
id_client int,
PRIMARY KEY(numero_commande),
CONSTRAINT fk_client
FOREIGN KEY(id_client)
REFERENCES CLIENT(id_client)
);
CREATE TABLE LIGNE_DE_COMMANDE (
numero_commande int,
code_produit int,
quantite int,
PRIMARY KEY(numero_commande, code_produit)
);
```
%% Output
* postgresql://localhost/jovyandb
Done.
Done.
Done.
Done.
Done.
Done.
Done.
Done.
[]
%% Cell type:code id:e3b35f69-a5eb-4888-b518-84f3a0841fba tags:
``` python
%%sql
INSERT INTO CLIENT (email, nom, prenom) VALUES ('a.b@x.fr','a','b');
INSERT INTO CLIENT (email, nom, prenom) VALUES ('c.d@x.fr','c','d');
INSERT INTO CLIENT (email, nom, prenom) VALUES ('e.f@x.fr','e','f');
```
%% Output
* postgresql://localhost/jovyandb
1 rows affected.
1 rows affected.
1 rows affected.
[]
%% Cell type:code id:9232e8ad-c21e-4bf1-b92d-30be7ec5d94a tags:
``` python
%%sql
SELECT * FROM CLIENT
```
%% Output
* postgresql://localhost/jovyandb
3 rows affected.
[(1, 'a.b@x.fr', 'a', 'b'),
(2, 'c.d@x.fr', 'c', 'd'),
(3, 'e.f@x.fr', 'e', 'f')]
%% Cell type:markdown id:e9130678-99f7-42c0-a474-aabfbfc8f355 tags:
Les résultats des requêtes peuvent être affecté dans des variables python et traitée sous forme de dataframes avec la librairie Panda.
%% Cell type:code id:c0e8873f-6c46-455d-829d-d042770d9e08 tags:
``` python
clients = %sql SELECT * FROM CLIENT
clients.DataFrame().info()
```
%% Output
* postgresql://localhost/jovyandb
3 rows affected.
<class 'pandas.core.frame.DataFrame'>
RangeIndex: 3 entries, 0 to 2
Data columns (total 4 columns):
# Column Non-Null Count Dtype
--- ------ -------------- -----
0 id_client 3 non-null int64
1 email 3 non-null object
2 nom 3 non-null object
3 prenom 3 non-null object
dtypes: int64(1), object(3)
memory usage: 224.0+ bytes
%% Cell type:code id:cc525ac0-15e4-4ef8-a16b-cad00ce948e3 tags:
``` python
%%sql
INSERT INTO PRODUIT (description, prix_unitaire) VALUES ('pomme',2);
INSERT INTO PRODUIT (description, prix_unitaire) VALUES ('peche',4);
INSERT INTO PRODUIT (description, prix_unitaire) VALUES ('poire',3);
```
%% Output
* postgresql://localhost/jovyandb
1 rows affected.
1 rows affected.
1 rows affected.
[]
%% Cell type:code id:2ba87c2d-65bf-45f9-a71c-1130c11c7e2b tags:
``` python
%%sql
SELECT * FROM PRODUIT
```
%% Output
* postgresql://localhost/jovyandb
3 rows affected.
[(1, 'pomme', 2), (2, 'peche', 4), (3, 'poire', 3)]
%% Cell type:code id:e68b5145-ea69-4574-ac1c-6f1c67de5567 tags:
``` python
insert_command_result=%sql INSERT INTO COMMANDE (id_client) VALUES (1) RETURNING numero_commande;
numero_commande=insert_command_result[0][0]
```
%% Output
* postgresql://localhost/jovyandb
1 rows affected.
%% Cell type:markdown id:2b458632-71cf-4872-ba51-b226bedfe637 tags:
Il est aussi possible d'utiliser des variables python comme paramètres des requêtes.
%% Cell type:code id:ea570c9b-8b52-4099-b5ac-fd14e880def0 tags:
``` python
%%sql
INSERT INTO LIGNE_DE_COMMANDE VALUES ({numero_commande}, 1,5);
INSERT INTO LIGNE_DE_COMMANDE VALUES ({numero_commande}, 2,2);
INSERT INTO LIGNE_DE_COMMANDE VALUES ({numero_commande}, 3,1);
SELECT * FROM LIGNE_DE_COMMANDE;
```
%% Output
* postgresql://localhost/jovyandb
1 rows affected.
1 rows affected.
1 rows affected.
3 rows affected.
[(1, 1, 5), (1, 2, 2), (1, 3, 1)]
%% Cell type:markdown id:a5f348ed-9b42-430d-afde-ae138eb03712 tags:
Et donc de les afficher très simple y compris sous forme graphique.
%% Cell type:code id:96f25786-c320-49ff-8345-88edd2f827ec tags:
``` python
result = %sql select * from PRODUIT;
produits_dataframe = result.DataFrame()
produits_dataframe.set_index('description')[["prix_unitaire"]].plot.bar(rot=0)
```
%% Output
* postgresql://localhost/jovyandb
3 rows affected.
<AxesSubplot:xlabel='description'>
%% Cell type:code id:2fbee874-3fca-4b43-a83a-c7bfff8e16c6 tags:
``` python
```
......
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Please register or to comment