0Pricing
Elixir & Phoenix: Scalable Backend Development · Ders

Ecto Şeması ve Veritabanı Taşımaları

Elixir yapılarını veritabanı tablolarıyla eşlemek için Ecto şemaları tanımlayın ve şema değişikliklerini taşımalarla yönetin.

Ecto Şeması ve Veritabanı Taşımaları, CoddyKit'te ücretsiz bir Elixir & Phoenix: Scalable Backend Development dersidir. Bu, 4 dersinin 1. dersidir. Aşağıdan dersin tamamını ücretsiz okuyabilir, sonra tarayıcıda yerleşik kod editörü ve 7/24 yapay zeka koçu ile uygulamalı olarak pratik yapabilirsin. Bu, Elixir & Phoenix: Scalable Backend Development öğrenme yolunun bir parçasıdır ve ilerlemeniz web ve CoddyKit uygulaması arasında senkronize olur. Elixir & Phoenix: Scalable Backend Development kursu toplamda 4 dersten oluşur.

Bu dersin bazı bölümleri henüz çevrilmemiş olup İngilizce olarak gösterilmektedir.

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
end

Common 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.
  • :float or :decimal: For numbers with decimal points.
  • :boolean: For true/false values.
  • :datetime or :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_table

This 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
end

Running Your Migrations

Once you've defined your migrations, you apply them to your database using another Mix command:

mix ecto.migrate

Ecto 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.

Sıkça Sorulan Sorular

“Ecto Şeması ve Veritabanı Taşımaları” dersi ücretsiz mi?

Evet — “Ecto Şeması ve Veritabanı Taşımaları” dersin tüm metni burada web'de ücretsiz olarak okunabilir. Etkileşimli olarak pratik yapmak (yerleşik kod editörü ve 7/24 yapay zeka koçu) ve Elixir & Phoenix: Scalable Backend Development kursunun geri kalanını açmak için CoddyKit PRO'ya yükselt. Elixir & Phoenix: Scalable Backend Development kursu toplamda 4 dersten oluşur.

“Ecto Şeması ve Veritabanı Taşımaları” dersinde ne öğreneceğim?

Elixir yapılarını veritabanı tablolarıyla eşlemek için Ecto şemaları tanımlayın ve şema değişikliklerini taşımalarla yönetin. Elixir & Phoenix: Scalable Backend Development ile uygulamalı kodu tarayıcıda doğrudan çalıştırarak pratik yaparsın ve 7/24 yapay zeka koçu dersi çalışırken sorularını yanıtlar.

Elixir & Phoenix: Scalable Backend Development öğrenmeye başlamak için deneyim gerekli mi?

Önceden deneyim gerekmez. CoddyKit'te Elixir & Phoenix: Scalable Backend Development, başlangıçtan ileri seviyeye kadar yapılandırıldığı için buradan başlayabilir veya başından başlayıp kendi hızında ilerleme yapabilirsin. Bu, 4 dersinin 1. dersidir.

“Ecto Şeması ve Veritabanı Taşımaları” dersi ne kadar sürer?

Çoğu CoddyKit dersi yaklaşık 5–10 dakika sürer. Her biri kısa ve etkileşimli olduğu için sabit ilerleme yaparsın ve web ile uygulama arasında tam olarak bıraktığın yerden devam edebilirsin.

Bu Elixir & Phoenix: Scalable Backend Development dersinde kod yazıp çalıştırabilir miyim?

Evet. Her Elixir & Phoenix: Scalable Backend Development dersi yerleşik bir kod editörü içerir, bu sayede tarayıcıda gerçek kod yazıp çalıştırabilir ve anlık yapay zeka geri bildirimi alırsın — yerel kurulum gerekli değildir.

Bu kursun tüm dersleri

  1. Ecto Şeması ve Veritabanı Taşımaları
  2. Repo, Değişiklik Kümeleri ve Sorgular
  3. İlişkilendirmeler ve Gömülü Şemalar
  4. İşlemler ve Ecto.Multi
← Elixir & Phoenix: Scalable Backend Development Sayfasına Dön