DEV Community

Weerasak Chongnguluam
Weerasak Chongnguluam

Posted on • Edited on

1

สรุปคอนเซ็ป Ecto เบื้องต้น

Ecto เป็น Elixir library ที่มีหน้าที่คือช่วยเป็นตัวกลางเชื่อมต่อกับ database (DBMS) ช่วยในการ mapping ค่าจาก record ใน database กับข้อมูลของ Elixir

พูดง่ายๆก็คือ Ecto มี module Ecto.Schema จากข้อมูลที่อยู่ในตารางแต่ละแถวของ database เราจะใช้ Ecto เพื่อช่วยแปลงจาก row มาเป็น struct และข้อมูลแต่ละ column แต่ละ type ใน database กลับมาเป็นข้อมูลแต่ละแบบใน Elixir เช่น integer, string เป็นต้น

นอกจากนั้น Ecto ยังมี module Ecto.Query ที่มี macro ที่ออกแบบมาเป็น DSL (Domain Specific Language) สำหรับใช้ query ข้อมูลซึ่งแม้จะเป็น macro ใน Elixir แต่เวลาใช้งานแถบจะเหมือน SQL แต่ปลอดภัยและสะดวกกว่าเราต่อ string เป็น SQL statement เอง

Ecto มี module Ecto.Changeset เพื่อให้เรา เตรียมการเปลี่ยนแปลงของ row โดยสามารถเช็คได้ว่ามี field ที่ต้องมีหรือไม่ เตรียม validator ต่างๆสำหรับ validate field ให้

Ecto ยังมี migration tool เพื่อให้เราจัดการการเปลี่ยนแปลงของ schema ของ table ให้เราอีกด้วย

สรุป Ecto เตรียมเครื่องมือต่างๆให้เราดังนี้

  • มี mix task สำหรับจัดการการเปลี่ยนแปลง (migration) database schema
  • Ecto.Repo เป็น module ที่เราเอาไว้จัดการส่ง statement ต่างๆไปให้ datbase จริงๆ
  • Ecto.Schema เป็น module ที่ช่วยให้เรา mapping ประเภทข้อมูลใน table กับ ใน Elixir ว่าใน 1 row จะกลายมาเป็น struct ที่แต่ละ column จะกลายมาเป็น field ใน struct โดยได้ข้อมูลประเภทไหน
  • Ecto.Changeset เป็น module เพื่อจัดการ การเปลี่ยนแปลงของข้อมูลใน 1 record ว่าถูกต้อง (valid) ตามเงื่อนไขที่เราต้องการหรือไม่
  • Ecto.Query ช่วยในการสร้าง SQL statement โดยอาศัย DSL macro ที่เตรียมไว้ให้ทำให้เราสร้าง SQL ด้วย syntax ของ Elixir ได้ง่าย สะดวก ปลอดภัยมากกว่าประกอบ string SQL เอง

Buy Me A Coffee

Sentry image

Hands-on debugging session: instrument, monitor, and fix

Join Lazar for a hands-on session where you’ll build it, break it, debug it, and fix it. You’ll set up Sentry, track errors, use Session Replay and Tracing, and leverage some good ol’ AI to find and fix issues fast.

RSVP here →

Top comments (1)

Collapse
 
veer66 profile image
Vee Satayamas

ดูครอบคลุมดี 😍

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay