Monday, May 26, 2025

Online Food Store Case Study

STEP 1 - System Requirements Analysis

1.1 Main Use Case: Making an Order

Here you do an examination the different stages involved in the process of how to do an online order

  1. Browsing and Adding to Cart: The customer explores the online store, finds items they like, and adds them to their virtual shopping cart. When the customer is finished adding items, they requests the cart; they may optionally edit the cart.

  2. Order Checkout: The customer clicks "proceed to order" and enters their personal information, shipping address, and payment details. The customer reviews their order summary, including the items, quantity, price, and shipping details. They then click a button like "Confirm Order" or "Place Order" or "Buy Now" to finalize the purchase. This action sends the order request to the online store.

  3. Confirmation Email: The customer receives a confirmation email with a summary of the order details and an order number. The store is acknowledging that the order has been received and is being processed.

  4. Payment Processing: The online store processes the customer's payment, ensuring the funds are securely transferred.

  5. Order Fulfillment: The online store prepares the order for shipment. This includes picking the items, packing them, and generating a shipping label.

  6. Shipping: The order is handed over to the shipping carrier, which delivers it to the customer's address.

  7. Delivery: The customer receives their order!

  8. Order Completion: The online store marks the order as complete in their system.

  9. Potential Return/Refund: The customer may have the option to return or request a refund for their order if they are not satisfied.

1.2 "Making an Order" System Sequence Diagrams
CustomerSystemAdminrequestMenu"Menu"loopaddItemToCart(item)requestCart"Cart"checkoutOrder(cart)"Order"setDeliveryAddresssetPaymentDetailsplaceOrder(order)"Order Confirmation Email"notifyAdmin(orderId, "new order")approveOrder(orderId)notifyCustomer("order is being prepared")updateOrderStatus(orderId, "ready for delivery")notifyCustomer("order is ready for delivery")notifyCustomer("order is delivered")updateInventory(item, quantity)

STEP 2 - OOA: Functional Requirements Analysis

When doing OO analysis, you create the Domain Model and draw classes/abstractions and interactions.

2.1 Online Food Store Key Abstractions
  • Customer: The person placing the order.
  • Menu: The list of available MenuItem.
  • MenuItem: The dishes items the Customer selects from the Menu. MenuItem details: price, description and dietary info
  • Cart: The virtual cart where the customer adds their items.
  • Restaurant: The establishment providing the food.
  • Order: The collection of items the customer wants.
  • OrderItem: a single item within an order, including quantity and any special instructions.
  • Address: The Customer delivery address and the Restaurant location
  • RestaurantAdmin: The person who accepts orders and manages the order states
  • Payment Details: a class that holds the details of the payment method used.
  • Payment System: The system used to process the payment.
  • Delivery Service: The service responsible for delivering the food.
  • Review/Rating: To allow customers to rate their experience.
2.2 Online Food Store Domain Model
Menumenu itemsMenuItemnamepriceCartorder itemsadd(menuItem)OrderItema menu itema quantityOrdercustomerorder itemsshipping addresspayment methodstatusCustomerfirst namelast nameemaildate of birthphone numberAddressPaymentcontains11..*contains11..*has11is used to createis placed by1*has11..*has11has11

STEP 3 - OOD: Sequence Diagram

3.1 The Sequence Diagram of the "Making an Order" Use Case
CustomerMainUIControllerRestaurantCartOrderMailingSystemPaymentServicePaymentGatewayDeliveryServiceAdminUIAdminrequestMenu()requestMenu()requestMenu()"Menu""Menu"loopaddItemToCart(item)addItemToCart(item)addItemToCart(item)add(item)requestCart()requestCart()requestCart()"Cart""Cart"checkoutOrder(cart)checkoutOrder(cart)checkoutOrder(cart)"Order""Order"setDeliveryAddress(address)setDeliveryAddress(address)setDeliveryAddress(address)setDeliveryAddress(address)setPaymentDetails(payment)setPaymentDetails(payment)setPaymentDetails(payment)setPaymentDetails(payment)placeOrder(order)placeOrder(order)placeOrder(order)sendConfirmationEmail(order)"Order Confirmation Email"updateOrderStatus(orderId, "pending")processPayment(payment)processPayment(payment)paymentResult(success/failure)paymentConfirmation(success/failure)updatePaymentStatus(success/failure)notifyAdmin("new order")approveOrder(orderId)approveOrder(orderId)notifyCustomer("order is being prepared")updateOrderStatus(orderId, "accepted")updateOrderStatus(Id, "ready for delivery")updateOrderStatus(orderId, "ready for delivery")updateOrderStatus(orderId, "ready for delivery")notifyCustomer("order is ready for delivery")requestDelivery(order)deliveryConfirmation(success/failure)updateOrderStatus(orderId, "delivered")notifyCustomer("order is delivered")updateInventory(item, quantity)

STEP 4 - OOD: Class Diagram

4.1 The Refined Domain Model Class Diagram

The class diagram of the design activity which represents the Refined Domain Model

Menuitems : List<MenuItem>MenuItemname : Stringprice : DoubleCartitems : List<OrderItem>add(:MenuItem)OrderItemitem : MenuItemquantity : IntegerCustomercustomerID : LongfirstName : StringlastName : Stringemail : Stringphone : StringshippingAddresses : Address[]billingAddress : AddresspaymentMethods : Payment[]OrderorderID : Longitems : List<OrderItem>customer : CustomershippingAddress : AddresspaymentMethod : PaymentpaymentStatus : StringtotalAmount : DoubleorderStatus : StringAddressPaymentcontains11..*11..*is used to create11is placed by10..*1111..*has11

Saturday, April 12, 2025

UML tools for eclipse IDE

Comparing eclipse IDE: UML Designer, Papyrus and Eclipse Modeling Tools

UML Designer, Eclipse Papyrus, and Eclipse Modeling Tools are all part of the Eclipse ecosystem, particularly focused on model-driven development (MDD). While they can overlap in functionality, they serve different purposes or cater to different user needs.


1. UML Designer (by Obeo)

  • Overview: A tool dedicated to UML modeling that provides a user-friendly interface.
  • Features: Lightweight, drag-and-drop interface, customizable viewpoints.
  • Best for: Beginner users who want standard UML diagrams.

2. Papyrus (by Eclipse Foundation)

  • Overview: A powerful modeling tool that supports multiple modeling languages.
  • Features: Support for UML 2.5, SysML and MARTE modeling languages.
  • Best for: Complex modeling, academic and industrial-grade modeling projects.

3. Eclipse Modeling Tools with UML Plugins

  • Overview: A general-purpose Eclipse package with optional UML plugins (like MDT UML2, EMF, GMF, etc.)
  • Features: Supports multiple modeling languages and frameworks: EMF, GMF, Ecore tools, etc.
  • Best for: Developers creating custom modeling tools or DSLs

Comparison Table

Tool Purpose UML Diagram Support Complexity Target Audience
Eclipse UML Designer UML modeling Good UML support Medium Developers needing custom diagram views
Eclipse Papyrus Multi-language (SysML, UML, MARTE...) modeling environment Full UML 2.x support High System engineers, advanced UML users
Eclipse Modeling Tools A package that includes EMF, GMF, and more Varies by plugin High Developers building modeling tools

Note: The UML Designer 9.0.0 standalone IDE is based on eclipse Oxygen (2017) and includes a JRE 8. UML Designer 9.0.0 can only run on older Ubuntu (e.g. 18.04 or 20.04); newer Ubuntu versions will have compatibilty issues with SWT included with UML Designer. The UML Designer 9.0.0 plugin will not work with current eclipse versions running on JDK 17 and higher.
Solution: Try running UML Designer in a Docker container with an older Ubuntu (e.g., 18.04 or 20.04) and the library versions match what UML Designer expects.
You can use an image like this:

FROM ubuntu:20.04
RUN apt update && apt install -y openjdk-8-jdk libgtk-3-0 libcanberra-gtk3-module libfreetype6
COPY UMLDesigner/ /opt/UMLDesigner/
WORKDIR /opt/UMLDesigner/
CMD ["./UMLDesigner"]

Or even easier: use a base image with Eclipse Oxygen preinstalled.

Friday, October 22, 2021

Eclipse IDE tips

1 Importing a Git project

To import a Git project into an eclipse project, open the command line terminal and move to eclipse workspace:

user@host:~$ cd eclipse-workspace/

clone the Git project into a newly created project folder:

user@host:~/eclipse-workspace$ git clone https://github.com/davidflanagan/jstdg7 Flanagan-JavaScript-Book-7Ed

The Flanagan-JavaScript-Book-7Ed folder is going to be the base folder of the eclipse project.
Run eclipse IDE and open the "eclipse-worskspace" folder. To import the project, select the option File -> Import -> General -> Project from Folder or Archive and click on Next button.

This opens a the "Import Projects from File System or Archive" window, click on "Directory" button. This opens a file chooser, navigate to the newly created folder and click on Open to import the project into eclipse IDE.

2 Importing a Maven project

Download a maven project, for example by cloning a git repo or by using the maven archetype plugin
In my case I am going to clone the maven project from git

Open the command line terminal and move to eclipse workspace:

user@host:~$ cd eclipse-workspace/

clone the Maven project into a newly created project folder:

git clone https://github.com/heroku/java-getting-started heroku-getting-started

You have cloned the Git project into the heroku-getting-started folder. That folder is going to be the base folder of the eclipse project.
Run eclipse IDE and open the "eclipse-worskspace" folder. To import the project, select the option File -> Import -> Maven -> Existing Maven Projects and click on Next button.

This opens a window that allows you to chose the project root directory, click on the Browse button.
This open a file selector, select the folder of the Maven project to be imported. This is what you get:

Select the pom of the project you want to import and click finish. In case you are importing a multi module maven project select the parent pom and all the poms of subproject you want to import.

3 Make eclipse IDE build faster

3.1 Turn Off Validations

As soon as you open a project, eclipse starts to build the project. Validation is part of projects building. If your workspace has many projects open, validation may take too long, threfore you may want to turn off validation to make building faster.

You can disable validators either for your project or for your workspace. To disable validators for your workspace, select Window -> Preferences -> Validation. This opens the Validation window. You can tick the second check box in the upper list "Suspend all Validators" or you can choose to disable individual validator by clearing the box next each validator.

3.2 Uncheck Auto Build

The menu item Project -> Build Automatically is checked by default. That means eclipse build all projects (both closed and opened projects) in your workspace whenever you open the workspace or run a clean command. So, if you your workspace holds many projects, it is convenient to uncheck the Build Automatically item.

Doing so, it will disable automatic building for the projects. To build the project you are currently working on, select the Project -> Clean item, uncheck Clean all projects and select Build only the selected project.

Friday, July 19, 2019

Introduction to SQL


The SQL language is a standard for relational databases:

  • since database systems share a standard language, migrating a database application to another relational database is a quick and inexpensive process
  • database application programs can access data stored in multiple relational DBMSs using the same database language

The practical SQL vs the relational algebra

  • the SQL language is a high level declarative language for the relational model: with a query in the SQL language, the user must only indicate how the result is to be and the DBMS decides how to execute the query
  • the relational algebra is a formal language for the relational model: with a query in the relational algebra, the user must specify a sequence of low-level operations. Relational algebra operations are not suitable for most DBMS users

The SQL name stands for Structured Query Language

  • the SQL language is a standard by the American National Standards Institute (ANSI) and the International Standards Organization (ISO)
  • on the wikipedia page about SQL, you can find out the history of the versions of the SQL standard

Wednesday, May 29, 2019

How to style link as buttons

CSS styles

.my-link{
    margin: 20px 0;
    text-align:center;
}
.my-link a {
    font-size:12px;
    padding: 8px 10px;
    background: #4eb0d7;
    color: #FFF;

    -webkit-border-radius: 4px;
    -moz-border-radius: 4px;
    border-radius: 4px;
    border: solid 1px #20538D;

    text-shadow: 0 -1px 0 rgba(0, 0, 0, 0.4);
    -webkit-box-shadow: inset 0 1px 0 rgba(255, 255, 255, 0.4), 0 1px 1px rgba(0, 0, 0, 0.2);
    -moz-box-shadow: inset 0 1px 0 rgba(255, 255, 255, 0.4), 0 1px 1px rgba(0, 0, 0, 0.2);
    box-shadow: inset 0 1px 0 rgba(255, 255, 255, 0.4), 0 1px 1px rgba(0, 0, 0, 0.2);
}
.my-link a:hover, .my-link a:focus {
    background: #377B96;
    border: solid 1px #2A4E77;
    text-decoration: none;
}
.my-link a:active {
    -webkit-box-shadow: inset 0 1px 4px rgba(0, 0, 0, 0.6);
    -moz-box-shadow: inset 0 1px 4px rgba(0, 0, 0, 0.6);
    box-shadow: inset 0 1px 4px rgba(0, 0, 0, 0.6);
    background: #2E5481;
    border: solid 1px #27586C;
}

HTML code

<div class="my-link">
  <a href="#"> CONTINUE TO LINK </a>
</div>

the result

Friday, December 21, 2018

Introduction To Database

Databases and Database Users

Many daily activities involve the use of applications that interact with a database, for example making a bank operation or an hotel reservations, borrowing a book, purchasing tickets or anything else online.

A database application manages information that is to be stored in a database:

  • traditional applications use databases to store textual or numeric data
  • social-media web sites use big data storage systems or NOSQL systems to store text data and non conventional data such as images and video data

Tuesday, October 23, 2018

Floating-point Arithmetic

Floating-point numbers

A mathematical notation offers a way to represent a number with a string of digits of any length and a radix point. If the position of the radix point is not specified, the string indicates a integer and the position of the radix point would be next the least significative digit.

A mathematical notation can represent numbers as the product of two factors: a number of significant digits in a given base and a scale factor, where the scale factor is the base and an exponent. To obtain the value of the number, multiply the significand by the base raised to the exponent, which is equivalent to shifting the radix point by a number of places equal to the value of the exponent.

In scientific notation, numbers are scaled by a power of ten, the radix point appears immediately after the first digit and the scaling factor is a power of ten.

Floating-point representation is similar to scientific notation. A floating-point number consists of:

  • a signed digit string of a fixed length in a given base (or radix), called the significand, coefficient or mantissa.
    • the length of the significand determines the precision to which numbers can be represented
    • the base can be two, ten or sixteen
  • a signed integer exponent (also called scale or characteristic), which modifies the magnitude of the number.

The number exactly represented has the following form:

  significand * baseexponent (significand ∈ Z, base ∈ Z and base ≥ 2, exponent ∈ Z)

Example:

 +3.1415 = +31415 × 10-4

Floating point computation allows to represent very small and very large real numbers with finite precision.
In computing, floating-point arithmetic is used to represent approximated real numbers.

The term floating point indicates the fact that the radix point (decimal point or binary point in computers) can be floated to left or right, that is, it can be placed anywhere in the significant digits of the number.

The IEEE standard for floating numbers in computers and programming languages

Over the years, different floating-point representations have been used in computers. In 1985, IEEE 754, the Standard for Floating-Point Arithmetic, was established by the Institute of Electrical and Electronics Engineers (IEEE). The IEEE 754 standand is for binary floating point numbers representation.

The three IEEE standard number formats widely used in computers hardware and languages are:

  • single precision: the float type in C language. It is a binary format that occupies 32 bits (4 bytes), the significand has a precision of 24 bits, which implies about 7.2 decimal digits.
  • double precision: the double type in C language . It is a binary format that occupies 64 bits (8 bytes), the significand has a precision of 53 bits, which is equal to about 15.9 decimal digits.
  • double extended: also called exdended precision format. It is binary format that occupies 80 bits, the significand has a precision of 64 bits, which corresponds to about 19 decimal digits. If the processor handles 80 bits foating point, the "long double" C type can be used.

Thursday, September 20, 2018

Esercizio: sistema per la gestione delle gite di una agenzia viaggi

Si vuole progettare una base di dati per la gestione delle gite organizzate da un'agenzia di viaggi.

Per ogni gita si vogliono memorizzare:

  • la descrizione;
  • la data di partenza;
  • la durata;
  • il prezzo;
  • il responsabile della gita;
  • l'elenco dei partecipanti;
  • l'itinerario.

Di ogni partecipante si vogliono memorizzare:

  • nome;
  • cognome;
  • data di nascita.

Ogni gita è associata a un itinerario, costituito da una o più tappe.

Di ogni tappa si vogliono memorizzare:

  • la località;
  • la durata del soggiorno.

Analisi del problema

Si deve costruire uno schema relazionale che e' funzionale alle interrogazioni da fare sul database. Si suppone che l'agenzia di viaggio sia una sola e che non si voglia memorizzare informazioni relative alla agenzia di viaggi.

Le principali entità della base di dati sono:

  • Gita
  • Partecipante
  • Tappa
  • Comune
PARTECIPANTE GITA PRENOTA Nome Cognome Codice (1, 1) (1, N) (1, 1) IdGita Data Durata HA TAPPA (1, N) (1, N) IdTappa Durata Localita DataNascita SUPERVISIONA (1, 1) Prezzo Descrizione COMUNE SI TROVA Codice NomeComune (1, N) (1, 1)  

Associazione Gita-Partecipante

Tra Gita e Partecipante esiste una associazione molti-a-molti.
Infatti: una gita comprende molti partecipanti e un partecipante può prendere parte a più gite organizzate dall'agenzia. Nello traduzione verso lo schema relazionale, si ha una tabella di collegamento.

Le associazioni Cliente-Servizio sono di tipo molti a molti (ad esempio Cliente-AbbonamentoPalestra, Cliente-AnalisiMedica, Cliente-CorsoDiBallo, ecc.) perche' si suppone che il cliente si registra la prima volta quando usa quel servizio e, quando vuole usare quel servizio una seconda volta, il cliente risulta gia' registrato nel database. Anche l'associazione studente-scuola e' una associazione molti a molti, perche' uno studente puo' fare un anno presso un liceo e poi passare ad un istituto tecnico; per cui, se si vuole tener traccia dello storico, si deve modellare l'associazione come N:M. Allo stesso modo, se si vuole sapere a quante gite ha partecipato un cliente, si deve usare una associazione N:M.


Entita' Responsabile

Il responsabile e' un partecipante speciale alla gita, l'entita responsabile NON puo' essere visto una entita' specializzazione di partecipante. In modellazione E-R, una specializzazione (ISA) significa che il responsabile è un'entità con caratteristiche proprie, ma qui non ha nessun attributo aggiuntivo. È semplicemente un partecipante che, per una certa gita, svolge il ruolo di responsabile. Quindi basta una FK. Non serve introdurre il concetto di specializzazione.

Associazione Gita-Responsabile

L'associazione gita-responsabile e' di tipo uno ad uno. Ogni gita ha un responsabile. Il responsabile della gita e' un partecipante alla gita, in piu' e' anche il responsabile della gita. Il responsabile della gita cui ha tutti gli attributi di una partecipante e non è necessario duplicarne i dati anagrafici. È sufficiente memorizzare nella tabella Gite una chiave esterna che fa riferimento alla tabella Partecipanti. In questo modo il responsabile mantiene tutte le caratteristiche di un partecipante, evitando ridondanze.

Nota: L'associazione gita-responsabile e' come l'associazione ufficio-capoufficio di tipo uno ad uno, il capoufficio e' un impiegato che lavora in quell'ufficio ed e' anche il capo dell'ufficio. E' un errore aggiungere cognome e nome del responsabile alla gita; non sarebbe in 3FN, perche' nome e cognome non dipendono da idGita ma da idPartecipante.


Entita Gita

Gli attributi di Gita sono: descrizione, durata in giorni, prezzo, data di partenza. L'attributo descrizione vuole indicare, brevemente, la meta delle gita: ad esempio "Le Cinque Terre", "Arezzo-Cortona", "Isola del Giglio". La gita ha un itinerario, cioe' tutte le tappe della gita, ad esempio per le cinque terre le tappe sono: Monterosso al Mare, Vernazza, Corniglia, Manarola e Riomaggiore.

Associazione Gita-Tappe

Ogni gita è costituita da una o più tappe. Ogni tappa appartiene a una sola gita. La relazione tra Gita e Tappa è quindi uno-a-molti. Ogni tappa è inoltre associata a un comune.

Entita Tappa

Gli attributi di tappa sono durata e localita'. Siccome ci sono delle localita' che sono frazioni, non un comune, posso fare riferimento ad un comune. Un comune puo' essere associato a piu' tappe, una tappa si trova in solo un comune.

Schema relazionale

Gite(
    IDGita, 
    Descrizione, 
    Durata, 
    Prezzo, 
    Data, 
    IDResponsabile (FK))
Partecipanti(
    IDPart, 
    Cognome, 
    Nome, 
    DataNascita)
Gite_Partecipanti(
    IDGita (FK), 
    IDPart (FK))
Tappe(
    IDTappa, 
    Durata, 
    Localita, 
    IDComune (FK), 
    IdGita(FK))
Comuni(
    IDComune, 
    NomeComune)

Lo schema rispetta la terza forma normale. Ogni attributo descrive esclusivamente la propria entità, non sono presenti dipendenze parziali né dipendenze transitive e le relazioni sono collegate tramite chiavi esterne.

Oltre alla verifica della normalizzazione, bisogna controllare se lo schema relazionale e' valido. Si controlla che la base di dati soddisfa i requisiti funzionali richiesti dalla applicazione, cioe' si controlla se si possono eseguire le interrogazioni che servono al committente. Ad esempio, per trovare nome e cognome di tutti i partecipanti alla gita "Cinque Terre", si eseguono due join, in cui l'ordine in cui si incrociano le tabelle non conta:

Esempio 1 - Partecipanti alla gita "Cinque Terre"

Algebra relazionale

π Cognome, Nome
(
    σ Descrizione = 'Cinque Terre'
    (
        Gite
        ⋈ Gite_Partecipanti
        ⋈ Partecipanti
    )
)

SQL

SELECT p.Cognome,
       p.Nome
FROM Gite g
JOIN Gite_Partecipanti gp
     ON g.IDGita = gp.IDGita
JOIN Partecipanti p
     ON gp.IDPart = p.IDPart
WHERE g.Descrizione = 'Cinque Terre';

Esempio 2 - Tutte le gite di un partecipante

Algebra relazionale

π Descrizione, DataPartenza
(
    σ IDPart = 15
    (
        Gite
        ⋈ Gite_Partecipanti
    )
)

SQL

SELECT g.Descrizione,
       g.DataPartenza
FROM Gite g
JOIN Gite_Partecipanti gp
     ON g.IDGita = gp.IDGita
WHERE gp.IDPart = 15;

Esempio 3 - Elenco delle tappe di una gita

Algebra relazionale

π Localita, Durata
(
    σ Descrizione = 'Cinque Terre'
    (
        Gite
        ⋈ Tappe
    )
)

SQL

SELECT t.Localita,
       t.Durata
FROM Gite g
JOIN Tappe t
     ON g.IDGita = t.IDGita
WHERE g.Descrizione = 'Cinque Terre';

Esempio 4 - Nome del responsabile della gita

Algebra relazionale

π Nome, Cognome
(
    σ Descrizione = 'Cinque Terre'
    (
        Gite
        ⋈ Partecipanti
    )
)

con la condizione: Gite.IDResponsabile = Partecipanti.IDPart

SQL

SELECT p.Nome,
       p.Cognome
FROM Gite g
JOIN Partecipanti p
     ON g.IDResponsabile = p.IDPart
WHERE g.Descrizione = 'Cinque Terre';

Wednesday, September 19, 2018

Basi di Dati: La Normalizzazione delle Relazioni

Introduzione

Il procedimento di normalizzazione serve per eliminare gli errori di progettazione da uno schema relazionale. La normalizzazione trasforma uno schema relazionale non normalizzato in uno schema normalizzato, senza alterarne il contenuto informativo.

Normalizzare uno schema significa ridurre le ridondanze che possono provocare incongruenze, dette anche anomalie.

Le principali anomalie che si possono presentare sono:

  • anomalie di inserimento;
  • anomalie di aggiornamento;
  • anomalie di cancellazione.

Immaginiamo di inserire manualmente dei dati in una tabella di Excel. Supponiamo che la tabella contenga le informazioni di un prodotto, con i campi: (codiceProdotto, descrizione, prezzo). Se nella stessa tabella vengono aggiunte anche informazioni relative al fornitore, ad esempio: (codice fornitore, nome, indirizzo) la struttura dei dati può andare incontro ad anomalie.

Infatti, se devo inserire un nuovo prodotto, sono costretto a ripetere anche tutte le informazioni del relativo fornitore: questa è un'anomalia di inserimento. Se cambia l'indirizzo di un fornitore, devo modificarlo in tutte le righe dei prodotti associati a quel fornitore: questa è un'anomalia di aggiornamento. Infine, se elimino l'ultimo prodotto associato a un determinato fornitore, rischio di perdere anche tutte le informazioni relative al fornitore stesso: questa è un'anomalia di cancellazione.

Applicando il processo di normalizzazione a uno schema relazionale si ottengono relazioni che soddisfano diversi livelli di qualità, chiamati forme normali.

Uno schema che soddisfa la prima, la seconda e la terza forma normale (1NF, 2NF e 3NF) è generalmente ben progettato e riduce il rischio di ridondanze e anomalie durante l'inserimento, l'aggiornamento e la cancellazione dei dati.

Tuesday, September 11, 2018

Basi di Dati: L'algebra Relazionale

Le basi di dati contengono informazioni che possono essere interrogate, aggiornate e manipolate dalle applicazioni. Per questo motivo sono necessari linguaggi che consentano di selezionare, elaborare e combinare i dati memorizzati nelle tabelle.

L'algebra relazionale è un linguaggio procedurale utilizzato per descrivere interrogazioni sulle basi di dati relazionali. Viene definito procedurale perché, per ottenere un determinato risultato, è necessario specificare la sequenza di operazioni da eseguire.
L'algebra relazionale non è il linguaggio utilizzato direttamente dagli utenti per interrogare un database. Essa rappresenta invece il fondamento teorico su cui si basano molti linguaggi per basi di dati relazionali, tra cui SQL.
Ogni operazione dell'algebra relazionale prende in ingresso una o più relazioni (tabelle) e restituisce sempre una nuova relazione. Questa proprietà, detta chiusura, permette di concatenare più operatori per costruire interrogazioni anche molto complesse.

Gli operatori dell'algebra relazionale possono essere suddivisi in tre gruppi principali:

  • Operatori insiemistici
    • Unione
    • Intersezione
    • Differenza

  • Operatori che selezionano dati da una relazione
    • Selezione (righe)
    • Proiezione (colonne)
  • Operatori che combinano più relazioni
    • Prodotto cartesiano
    • Join

Per poter applicare gli operatori insiemistici, due relazioni devono essere compatibili. Due relazioni R e S sono compatibili quando:

  1. hanno lo stesso numero di attributi (lo stesso grado);
  2. gli attributi corrispondenti appartengono allo stesso dominio.