Schema Ecto e migrazioni del database
Definisca gli schemi Ecto per mappare le struct Elixir sulle tabelle del database e gestisca le modifiche allo schema con le migrazioni.
Schema Ecto e migrazioni del database è una lezione Elixir & Phoenix: Scalable Backend Development gratuita su CoddyKit. Questa è la lezione 1 di 4. Puoi leggere la lezione completa qui gratuitamente — poi esercitati direttamente nel browser con un editor di codice integrato e un tutor IA disponibile 24/7. Fa parte del percorso di apprendimento Elixir & Phoenix: Scalable Backend Development, e i tuoi progressi si sincronizzano tra il web e l'app CoddyKit. Il corso Elixir & Phoenix: Scalable Backend Development include 4 lezioni in totale.
Parti di questa lezione non sono ancora state tradotte e vengono mostrate in inglese.
What is Ecto?
Welcome to Ecto! It's Elixir's powerful toolkit for interacting with databases. Think of it as your bridge between Elixir data and your database.
Ecto isn't a traditional Object-Relational Mapper (ORM). Instead, it's a data mapper. This means it focuses on mapping data between your Elixir application (using structs) and your database tables, giving you more control and less 'magic'.
Elixir Structs: Data Shapes
Before Ecto maps data to a database, Elixir uses structs to define data shapes. A struct is a special kind of map that ensures a predefined set of keys and default values.
Ecto schemas build upon this idea, extending structs to understand how their fields correspond to database columns.
Try running this simple struct example:
defmodule UserData do
defstruct name: "", age: 0, email: ""
end
# Create struct instances
user1 = %UserData{name: "Alice", age: 30}
user2 = %UserData{email: "bob@example.com"}
IO.puts "User 1: #{inspect user1}"
IO.puts "User 2: #{inspect user2}"
IO.puts "User 1's age: #{user1.age}"Defining an Ecto Schema
An Ecto schema is an Elixir module that describes how an Elixir struct maps to a database table. It defines the fields, their types, and any special options.
Here's how you'd define a basic User schema, mapping to a users table in your database:
defmodule MyApp.User do
use Ecto.Schema
schema "users" do
field :name, :string
field :email, :string
field :age, :integer
timestamps()
end
endCommon Schema Field Types
When defining fields in your schema, you specify their type. Ecto provides many common types that map directly to database types:
:string: For text data (e.g., names, emails).:integer: For whole numbers.:floator:decimal: For numbers with decimal points.:boolean: For true/false values.:datetimeor:naive_datetime: For date and time values.:binary: For raw binary data.
Choosing the right type helps Ecto validate data and create appropriate database columns.
Primary Keys & Timestamps
Ecto schemas automatically include a primary key, usually an id column of type :integer. You don't need to define it explicitly.
The timestamps() macro is super handy! It automatically adds two fields to your schema and database table:
:inserted_at: Stores when the record was created.:updated_at: Stores when the record was last modified.
These fields are crucial for tracking changes and are automatically managed by Ecto.
Introducing Database Migrations
Your Ecto schemas define the *desired* structure of your database. But how do you apply these changes to the actual database?
This is where migrations come in! A migration is an Elixir script that describes changes to your database schema, like creating tables, adding columns, or changing types. They ensure your database schema evolves in a controlled, versioned way.
Generating a Migration File
You create new migration files using the Mix command mix ecto.gen.migration. You provide a descriptive name for the migration:
mix ecto.gen.migration create_users_tableThis command will generate a new Elixir file in your priv/repo/migrations directory. The filename will include a timestamp, ensuring migrations are applied in the correct order.
Anatomy of a Migration
A migration file contains an Elixir module with a change/0 function. Inside this function, you define your database operations. For example, creating a table:
defmodule MyApp.Repo.Migrations.CreateUsersTable do
use Ecto.Migration
def change do
create table(:users) do
add :name, :string, null: false
add :email, :string, null: false
add :age, :integer
timestamps()
end
create unique_index(:users, [:email])
end
endRunning Your Migrations
Once you've defined your migrations, you apply them to your database using another Mix command:
mix ecto.migrateEcto keeps track of which migrations have been run. If you need to undo the last migration, you can use mix ecto.rollback.
Always run migrations in your development environment first to catch any issues!
Schema vs. Migration
Let's check your understanding of Ecto schemas and migrations.
Recap: Schemas & Migrations
You've taken the first step into Ecto!
- We learned that Ecto schemas define how Elixir structs map to database tables, specifying fields and types.
- We explored how migrations are versioned scripts that apply these schema changes to your actual database.
- You now know how to define a basic schema, generate migration files, and apply them using Mix commands.
Next, we'll dive deeper into interacting with your database using Ecto.Repo and ensuring data integrity with Changesets.
Domande Frequenti
La lezione «Schema Ecto e migrazioni del database» è gratuita?
Sì — il testo completo di «Schema Ecto e migrazioni del database» è gratuito qui sul web. Per esercitarvi in modo interattivo (un editor di codice integrato e un tutor IA 24/7) e sbloccare il resto del corso Elixir & Phoenix: Scalable Backend Development, passa a CoddyKit PRO. Il corso Elixir & Phoenix: Scalable Backend Development include 4 lezioni in totale.
Cosa imparerò in «Schema Ecto e migrazioni del database»?
Definisca gli schemi Ecto per mappare le struct Elixir sulle tabelle del database e gestisca le modifiche allo schema con le migrazioni. Eserciti Elixir & Phoenix: Scalable Backend Development con codice pratico che esegui direttamente nel browser, e un tutor IA 24/7 risponde alle tue domande mentre lavori sulla lezione.
Ho bisogno di esperienza per iniziare Elixir & Phoenix: Scalable Backend Development?
Non è richiesta alcuna esperienza precedente. Elixir & Phoenix: Scalable Backend Development su CoddyKit è strutturato per principianti e studenti avanzati, quindi puoi iniziare da qui o dall'inizio e procedere al tuo ritmo. Questa è la lezione 1 di 4.
Quanto tempo richiede la lezione «Schema Ecto e migrazioni del database»?
La maggior parte delle lezioni CoddyKit richiede circa 5–10 minuti. Ogni lezione è breve e interattiva, quindi fai progressi costanti e riprendi esattamente da dove hai lasciato su web e app.
Posso scrivere ed eseguire codice in questa lezione Elixir & Phoenix: Scalable Backend Development?
Sì. Ogni lezione Elixir & Phoenix: Scalable Backend Development include un editor di codice integrato, quindi scrivi ed esegui codice reale direttamente nel tuo browser e ricevi feedback istantaneo dall'IA — nessuna configurazione locale necessaria.
Tutte le lezioni di questo corso
- Schema Ecto e migrazioni del database
- Repo, changeset e query
- Associazioni e schemi incorporati
- Transazioni ed Ecto.Multi