Ecto 스키마와 데이터베이스 마이그레이션
Ecto 스키마를 정의해 Elixir 구조체를 데이터베이스 테이블에 매핑하고 마이그레이션으로 스키마 변경을 관리합니다.
Ecto 스키마와 데이터베이스 마이그레이션은(는) CoddyKit의 무료 Elixir & Phoenix: Scalable Backend Development 강의입니다. 이것은 4개 중 1번째 강의입니다. 아래에서 전체 강의를 무료로 읽을 수 있으며, 내장 코드 에디터와 24/7 AI 튜터와 함께 브라우저에서 직접 실습할 수 있습니다. 이 강의는 Elixir & Phoenix: Scalable Backend Development 학습 경로의 일부이며, 진행 상황이 웹과 CoddyKit 앱에 동기화됩니다. Elixir & Phoenix: Scalable Backend Development 강의에는 총 4개의 강의가 포함되어 있습니다.
이 강의의 일부는 아직 번역되지 않았으며 영어로 표시됩니다.
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.
자주 묻는 질문
“Ecto 스키마와 데이터베이스 마이그레이션” 강의는 무료인가요?
네 — “Ecto 스키마와 데이터베이스 마이그레이션” 전체 내용을 이 웹사이트에서 무료로 읽을 수 있습니다. 인터랙티브하게 실습하려면(내장 코드 에디터와 24/7 AI 튜터), CoddyKit PRO로 업그레이드하면 Elixir & Phoenix: Scalable Backend Development 강의 전체를 잠금 해제할 수 있습니다. Elixir & Phoenix: Scalable Backend Development 강의에는 총 4개의 강의가 포함되어 있습니다.
“Ecto 스키마와 데이터베이스 마이그레이션”에서 뭘 배우나요?
Ecto 스키마를 정의해 Elixir 구조체를 데이터베이스 테이블에 매핑하고 마이그레이션으로 스키마 변경을 관리합니다. 브라우저에서 직접 실행하는 실습 코드로 Elixir & Phoenix: Scalable Backend Development을(를) 배우며, 24/7 AI 튜터가 강의를 진행하면서 질문에 답변해줍니다.
Elixir & Phoenix: Scalable Backend Development을(를) 시작하는 데 경험이 필요한가요?
사전 경험은 필요하지 않습니다. CoddyKit의 Elixir & Phoenix: Scalable Backend Development은(는) 초급자부터 고급 학습자까지를 위해 구성되어 있으므로, 여기서 시작하거나 처음부터 시작할 수 있으며 자신의 속도대로 진행할 수 있습니다. 이것은 4개 중 1번째 강의입니다.
“Ecto 스키마와 데이터베이스 마이그레이션” 강의는 얼마나 걸리나요?
대부분의 CoddyKit 강의는 약 5~10분이 소요됩니다. 각 강의는 간결하고 인터랙티브하여 꾸준한 진행이 가능하며, 웹과 앱에서 중단한 부분부터 바로 시작할 수 있습니다.
이 Elixir & Phoenix: Scalable Backend Development 강의에서 코드를 작성하고 실행할 수 있나요?
네. 모든 Elixir & Phoenix: Scalable Backend Development 강의에는 내장 코드 에디터가 포함되어 있으므로, 브라우저에서 바로 실제 코드를 작성하고 실행한 후 즉시 AI 피드백을 받을 수 있습니다 — 로컬 설정이 필요 없습니다.
이 강의의 모든 강의
- Ecto 스키마와 데이터베이스 마이그레이션
- Repo, 변경 집합 및 쿼리
- 연관 관계와 내장 스키마
- 트랜잭션과 Ecto.Multi