mirror of
https://github.com/jbranchaud/til
synced 2026-01-03 15:18:01 +00:00
Add Execute Raw SQL In An Ecto Migration as an elixir til
This commit is contained in:
@@ -7,7 +7,7 @@ variety of languages and technologies. These are things that don't really
|
||||
warrant a full blog post. These are mostly things I learn by pairing with
|
||||
smart people at [Hashrocket](http://hashrocket.com/).
|
||||
|
||||
_437 TILs and counting..._
|
||||
_438 TILs and counting..._
|
||||
|
||||
---
|
||||
|
||||
@@ -82,6 +82,7 @@ _437 TILs and counting..._
|
||||
### Elixir
|
||||
|
||||
- [Append To A Keyword List](elixir/append-to-a-keyword-list.md)
|
||||
- [Execute Raw SQL In An Ecto Migration](elixir/execute-raw-sql-in-an-ecto-migration.md)
|
||||
- [Expose Internal Representation](elixir/expose-internal-representation.md)
|
||||
- [List Functions For A Module](elixir/list-functions-for-a-module.md)
|
||||
- [Replace Duplicates In A Keyword List](elixir/replace-duplicates-in-a-keyword-list.md)
|
||||
|
||||
36
elixir/execute-raw-sql-in-an-ecto-migration.md
Normal file
36
elixir/execute-raw-sql-in-an-ecto-migration.md
Normal file
@@ -0,0 +1,36 @@
|
||||
# Execute Raw SQL In An Ecto Migration
|
||||
|
||||
If you are performing a database migration with
|
||||
[Ecto](https://hexdocs.pm/ecto/Ecto.html), perhaps the most straightforward
|
||||
approach is to use Ecto's DSL. However, the DSL may not always be the best
|
||||
choice. Being able to write raw SQL gives you more control. It will also
|
||||
enable you to use database features that may not be directly or easily
|
||||
available through the DSL.
|
||||
|
||||
Raw SQL can be included in a Ecto migration with a combination of Elixir's
|
||||
heredoc syntax and the [`Ecto.Migration#execute/1`
|
||||
function](https://hexdocs.pm/ecto/Ecto.Migration.html#execute/1). You'll
|
||||
also need to provide both an `up` and `down` function to ensure that your
|
||||
migrations are reversible.
|
||||
|
||||
```elixir
|
||||
defmodule MyApp.Repo.Migrations.CreatePostsTable do
|
||||
use Ecto.Migration
|
||||
|
||||
def up do
|
||||
execute """
|
||||
create table posts (
|
||||
id serial primary key,
|
||||
title varchar not null,
|
||||
body varchar not null default '',
|
||||
inserted_at timestamptz not null default now(),
|
||||
updated_at timestamptz not null default now()
|
||||
);
|
||||
"""
|
||||
end
|
||||
|
||||
def down do
|
||||
execute "drop table posts;"
|
||||
end
|
||||
end
|
||||
```
|
||||
Reference in New Issue
Block a user