1defmodule Ecto.Repo do 2 @moduledoc """ 3 Defines a repository. 4 5 A repository maps to an underlying data store, controlled by the 6 adapter. For example, Ecto ships with a Postgres adapter that 7 stores data into a PostgreSQL database. 8 9 When used, the repository expects the `:otp_app` as option. 10 The `:otp_app` should point to an OTP application that has 11 the repository configuration. For example, the repository: 12 13 defmodule Repo do 14 use Ecto.Repo, otp_app: :my_app 15 end 16 17 Could be configured with: 18 19 config :my_app, Repo, 20 adapter: Ecto.Adapters.Postgres, 21 database: "ecto_simple", 22 username: "postgres", 23 password: "postgres", 24 hostname: "localhost" 25 26 Most of the configuration that goes into the `config` is specific 27 to the adapter, so check `Ecto.Adapters.Postgres` documentation 28 for more information. However, some configuration is shared across 29 all adapters, they are: 30 31 * `:adapter` - a compile-time option that specifies the adapter itself. 32 As a compile-time option, it may also be given as an option to `use Ecto.Repo`. 33 34 * `:name`- The name of the Repo supervisor process 35 36 * `:priv` - the directory where to keep repository data, like 37 migrations, schema and more. Defaults to "priv/YOUR_REPO". 38 It must always point to a subdirectory inside the priv directory. 39 40 * `:url` - an URL that specifies storage information. Read below 41 for more information 42 43 * `:loggers` - a list of `{mod, fun, args}` tuples that are 44 invoked by adapters for logging queries and other events. 45 The given module and function will be called with a log 46 entry (see `Ecto.LogEntry`) and the given arguments. The 47 invoked function must return the `Ecto.LogEntry` as result. 48 The default value is: `[{Ecto.LogEntry, :log, []}]`, which 49 will call `Ecto.LogEntry.log/1` that will use Elixir's `Logger` 50 in `:debug` mode. You may pass any desired mod-fun-args 51 triplet or `[{Ecto.LogEntry, :log, [:info]}]` if you want to 52 keep the current behaviour but use another log level. 53 This option is processed at compile-time and may also be given 54 as an option to `use Ecto.Repo`. 55 56 ## URLs 57 58 Repositories by default support URLs. For example, the configuration 59 above could be rewritten to: 60 61 config :my_app, Repo, 62 url: "ecto://postgres:postgres@localhost/ecto_simple" 63 64 The schema can be of any value. The path represents the database name 65 while options are simply merged in. 66 67 URL can include query parameters to override shared and adapter-specific 68 options `ssl`, `timeout`, `pool_timeout`, `pool_size`: 69 70 config :my_app, Repo, 71 url: "ecto://postgres:postgres@localhost/ecto_simple?ssl=true&pool_size=10" 72 73 In case the URL needs to be dynamically configured, for example by 74 reading a system environment variable, such can be done via the 75 `c:init/2` repository callback: 76 77 def init(_type, config) do 78 {:ok, Keyword.put(config, :url, System.get_env("DATABASE_URL"))} 79 end 80 81 ## Shared options 82 83 Almost all of the repository operations below accept the following 84 options: 85 86 * `:timeout` - The time in milliseconds to wait for the query call to 87 finish, `:infinity` will wait indefinitely (default: 15000); 88 * `:pool_timeout` - The time in milliseconds to wait for calls to the pool 89 to finish, `:infinity` will wait indefinitely (default: 5000); 90 * `:log` - When false, does not log the query 91 92 Such cases will be explicitly documented as well as any extra option. 93 """ 94 95 @type t :: module 96 97 @doc false 98 defmacro __using__(opts) do 99 quote bind_quoted: [opts: opts] do 100 @behaviour Ecto.Repo 101 102 {otp_app, adapter, config} = Ecto.Repo.Supervisor.compile_config(__MODULE__, opts) 103 @otp_app otp_app 104 @adapter adapter 105 @config config 106 @before_compile adapter 107 108 loggers = 109 Enum.reduce(opts[:loggers] || config[:loggers] || [Ecto.LogEntry], quote(do: entry), fn 110 mod, acc when is_atom(mod) -> 111 quote do: unquote(mod).log(unquote(acc)) 112 {Ecto.LogEntry, :log, [level]}, _acc when not level in [:error, :info, :warn, :debug] -> 113 raise ArgumentError, "the log level #{inspect level} is not supported in Ecto.LogEntry" 114 {mod, fun, args}, acc -> 115 quote do: unquote(mod).unquote(fun)(unquote(acc), unquote_splicing(args)) 116 end) 117 118 def __adapter__ do 119 @adapter 120 end 121 122 def __log__(entry) do 123 unquote(loggers) 124 end 125 126 def config do 127 {:ok, config} = Ecto.Repo.Supervisor.runtime_config(:dry_run, __MODULE__, @otp_app, []) 128 config 129 end 130 131 def child_spec(opts) do 132 %{ 133 id: __MODULE__, 134 start: {__MODULE__, :start_link, [opts]}, 135 type: :supervisor 136 } 137 end 138 139 def start_link(opts \\ []) do 140 Ecto.Repo.Supervisor.start_link(__MODULE__, @otp_app, @adapter, opts) 141 end 142 143 def stop(pid, timeout \\ 5000) do 144 Supervisor.stop(pid, :normal, timeout) 145 end 146 147 if function_exported?(@adapter, :transaction, 3) do 148 def transaction(fun_or_multi, opts \\ []) do 149 Ecto.Repo.Queryable.transaction(@adapter, __MODULE__, fun_or_multi, opts) 150 end 151 152 def in_transaction? do 153 @adapter.in_transaction?(__MODULE__) 154 end 155 156 @spec rollback(term) :: no_return 157 def rollback(value) do 158 @adapter.rollback(__MODULE__, value) 159 end 160 end 161 162 def all(queryable, opts \\ []) do 163 Ecto.Repo.Queryable.all(__MODULE__, @adapter, queryable, opts) 164 end 165 166 def stream(queryable, opts \\ []) do 167 Ecto.Repo.Queryable.stream(__MODULE__, @adapter, queryable, opts) 168 end 169 170 def get(queryable, id, opts \\ []) do 171 Ecto.Repo.Queryable.get(__MODULE__, @adapter, queryable, id, opts) 172 end 173 174 def get!(queryable, id, opts \\ []) do 175 Ecto.Repo.Queryable.get!(__MODULE__, @adapter, queryable, id, opts) 176 end 177 178 def get_by(queryable, clauses, opts \\ []) do 179 Ecto.Repo.Queryable.get_by(__MODULE__, @adapter, queryable, clauses, opts) 180 end 181 182 def get_by!(queryable, clauses, opts \\ []) do 183 Ecto.Repo.Queryable.get_by!(__MODULE__, @adapter, queryable, clauses, opts) 184 end 185 186 def one(queryable, opts \\ []) do 187 Ecto.Repo.Queryable.one(__MODULE__, @adapter, queryable, opts) 188 end 189 190 def one!(queryable, opts \\ []) do 191 Ecto.Repo.Queryable.one!(__MODULE__, @adapter, queryable, opts) 192 end 193 194 def aggregate(queryable, aggregate, field, opts \\ []) 195 when aggregate in [:count, :avg, :max, :min, :sum] and is_atom(field) do 196 Ecto.Repo.Queryable.aggregate(__MODULE__, @adapter, queryable, aggregate, field, opts) 197 end 198 199 def insert_all(schema_or_source, entries, opts \\ []) do 200 Ecto.Repo.Schema.insert_all(__MODULE__, @adapter, schema_or_source, entries, opts) 201 end 202 203 def update_all(queryable, updates, opts \\ []) do 204 Ecto.Repo.Queryable.update_all(__MODULE__, @adapter, queryable, updates, opts) 205 end 206 207 def delete_all(queryable, opts \\ []) do 208 Ecto.Repo.Queryable.delete_all(__MODULE__, @adapter, queryable, opts) 209 end 210 211 def insert(struct, opts \\ []) do 212 Ecto.Repo.Schema.insert(__MODULE__, @adapter, struct, opts) 213 end 214 215 def update(struct, opts \\ []) do 216 Ecto.Repo.Schema.update(__MODULE__, @adapter, struct, opts) 217 end 218 219 def insert_or_update(changeset, opts \\ []) do 220 Ecto.Repo.Schema.insert_or_update(__MODULE__, @adapter, changeset, opts) 221 end 222 223 def delete(struct, opts \\ []) do 224 Ecto.Repo.Schema.delete(__MODULE__, @adapter, struct, opts) 225 end 226 227 def insert!(struct, opts \\ []) do 228 Ecto.Repo.Schema.insert!(__MODULE__, @adapter, struct, opts) 229 end 230 231 def update!(struct, opts \\ []) do 232 Ecto.Repo.Schema.update!(__MODULE__, @adapter, struct, opts) 233 end 234 235 def insert_or_update!(changeset, opts \\ []) do 236 Ecto.Repo.Schema.insert_or_update!(__MODULE__, @adapter, changeset, opts) 237 end 238 239 def delete!(struct, opts \\ []) do 240 Ecto.Repo.Schema.delete!(__MODULE__, @adapter, struct, opts) 241 end 242 243 def preload(struct_or_structs_or_nil, preloads, opts \\ []) do 244 Ecto.Repo.Preloader.preload(struct_or_structs_or_nil, __MODULE__, preloads, opts) 245 end 246 247 def load(schema_or_types, data) do 248 Ecto.Repo.Schema.load(@adapter, schema_or_types, data) 249 end 250 251 defoverridable child_spec: 1 252 end 253 end 254 255 @optional_callbacks init: 2 256 257 @doc """ 258 Returns the adapter tied to the repository. 259 """ 260 @callback __adapter__ :: Ecto.Adapter.t 261 262 @doc """ 263 A callback invoked by adapters that logs the given action. 264 265 See `Ecto.LogEntry` for more information and `Ecto.Repo` module 266 documentation on setting up your own loggers. 267 """ 268 @callback __log__(entry :: Ecto.LogEntry.t) :: Ecto.LogEntry.t 269 270 @doc """ 271 Returns the adapter configuration stored in the `:otp_app` environment. 272 273 If the `c:init/2` callback is implemented in the repository, 274 it will be invoked with the first argument set to `:dry_run`. 275 """ 276 @callback config() :: Keyword.t 277 278 @doc """ 279 Starts any connection pooling or supervision and return `{:ok, pid}` 280 or just `:ok` if nothing needs to be done. 281 282 Returns `{:error, {:already_started, pid}}` if the repo is already 283 started or `{:error, term}` in case anything else goes wrong. 284 285 ## Options 286 287 See the configuration in the moduledoc for options shared between adapters, 288 for adapter-specific configuration see the adapter's documentation. 289 """ 290 @callback start_link(opts :: Keyword.t) :: {:ok, pid} | 291 {:error, {:already_started, pid}} | 292 {:error, term} 293 294 @doc """ 295 A callback executed when the repo starts or when configuration is read. 296 297 The first argument is the context the callback is being invoked. If it 298 is called because the Repo supervisor is starting, it will be `:supervisor`. 299 It will be `:dry_run` if it is called for reading configuration without 300 actually starting a process. 301 302 The second argument is the repository configuration as stored in the 303 application environment. It must return `{:ok, keyword}` with the updated 304 list of configuration or `:ignore` (only in the `:supervisor` case). 305 """ 306 @callback init(:supervisor | :dry_run, config :: Keyword.t) :: {:ok, Keyword.t} | :ignore 307 308 @doc """ 309 Shuts down the repository represented by the given pid. 310 """ 311 @callback stop(pid, timeout) :: :ok 312 313 @doc """ 314 Fetches a single struct from the data store where the primary key matches the 315 given id. 316 317 Returns `nil` if no result was found. If the struct in the queryable 318 has no or more than one primary key, it will raise an argument error. 319 320 ## Options 321 322 See the "Shared options" section at the module documentation. 323 324 ## Example 325 326 MyRepo.get(Post, 42) 327 328 """ 329 @callback get(queryable :: Ecto.Queryable.t, id :: term, opts :: Keyword.t) :: Ecto.Schema.t | nil | no_return 330 331 @doc """ 332 Similar to `c:get/3` but raises `Ecto.NoResultsError` if no record was found. 333 334 ## Options 335 336 See the "Shared options" section at the module documentation. 337 338 ## Example 339 340 MyRepo.get!(Post, 42) 341 342 """ 343 @callback get!(queryable :: Ecto.Queryable.t, id :: term, opts :: Keyword.t) :: Ecto.Schema.t | nil | no_return 344 345 @doc """ 346 Fetches a single result from the query. 347 348 Returns `nil` if no result was found. 349 350 ## Options 351 352 See the "Shared options" section at the module documentation. 353 354 ## Example 355 356 MyRepo.get_by(Post, title: "My post") 357 358 """ 359 @callback get_by(queryable :: Ecto.Queryable.t, clauses :: Keyword.t | map, opts :: Keyword.t) :: Ecto.Schema.t | nil | no_return 360 361 @doc """ 362 Similar to `get_by/3` but raises `Ecto.NoResultsError` if no record was found. 363 364 ## Options 365 366 See the "Shared options" section at the module documentation. 367 368 ## Example 369 370 MyRepo.get_by!(Post, title: "My post") 371 372 """ 373 @callback get_by!(queryable :: Ecto.Queryable.t, clauses :: Keyword.t | map, opts :: Keyword.t) :: Ecto.Schema.t | nil | no_return 374 375 @doc """ 376 Calculate the given `aggregate` over the given `field`. 377 378 If the query has a limit, offset or distinct set, it will be 379 automatically wrapped in a subquery in order to return the 380 proper result. 381 382 Any preload or select in the query will be ignored in favor of 383 the column being aggregated. 384 385 The aggregation will fail if any `group_by` field is set. 386 387 ## Options 388 389 See the "Shared options" section at the module documentation. 390 391 ## Examples 392 393 # Returns the number of visits per blog post 394 Repo.aggregate(Post, :count, :visits) 395 396 # Returns the average number of visits for the top 10 397 query = from Post, limit: 10 398 Repo.aggregate(query, :avg, :visits) 399 """ 400 @callback aggregate(queryable :: Ecto.Queryable.t, aggregate :: :avg | :count | :max | :min | :sum, 401 field :: atom, opts :: Keyword.t) :: term | nil 402 403 @doc """ 404 Fetches a single result from the query. 405 406 Returns `nil` if no result was found. Raises if more than one entry. 407 408 ## Options 409 410 See the "Shared options" section at the module documentation. 411 """ 412 @callback one(queryable :: Ecto.Queryable.t, opts :: Keyword.t) :: Ecto.Schema.t | nil | no_return 413 414 @doc """ 415 Similar to `c:one/2` but raises `Ecto.NoResultsError` if no record was found. 416 417 Raises if more than one entry. 418 419 ## Options 420 421 See the "Shared options" section at the module documentation. 422 """ 423 @callback one!(queryable :: Ecto.Queryable.t, opts :: Keyword.t) :: Ecto.Schema.t | no_return 424 425 @doc """ 426 Preloads all associations on the given struct or structs. 427 428 This is similar to `Ecto.Query.preload/3` except it allows 429 you to preload structs after they have been fetched from the 430 database. 431 432 In case the association was already loaded, preload won't attempt 433 to reload it. 434 435 ## Options 436 437 Besides the "Shared options" section at the module documentation, 438 it accepts: 439 440 * `:force` - By default, Ecto won't preload associations that 441 are already loaded. By setting this option to true, any existing 442 association will be discarded and reloaded. 443 * `:in_parallel` - If the preloads must be done in parallel. It can 444 only be performed when we have more than one preload and the 445 repository is not in a transaction. Defaults to `true`. 446 * `:prefix` - the prefix to fetch preloads from. By default, queries 447 will use the same prefix as the one in the given collection. This 448 option allows the prefix to be changed. 449 450 ## Examples 451 452 # Use a single atom to preload an association 453 posts = Repo.preload posts, :comments 454 455 # Use a list of atoms to preload multiple associations 456 posts = Repo.preload posts, [:comments, :authors] 457 458 # Use a keyword list to preload nested associations as well 459 posts = Repo.preload posts, [comments: [:replies, :likes], authors: []] 460 461 # Use a keyword list to customize how associations are queried 462 posts = Repo.preload posts, [comments: from(c in Comment, order_by: c.published_at)] 463 464 # Use a two-element tuple for a custom query and nested association definition 465 query = from c in Comment, order_by: c.published_at 466 posts = Repo.preload posts, [comments: {query, [:replies, :likes]}] 467 468 Note: The query given to preload may also preload its own associations. 469 """ 470 @callback preload(structs_or_struct_or_nil, preloads :: term, opts :: Keyword.t) :: 471 structs_or_struct_or_nil when structs_or_struct_or_nil: [Ecto.Schema.t] | Ecto.Schema.t | nil 472 473 @doc """ 474 Fetches all entries from the data store matching the given query. 475 476 May raise `Ecto.QueryError` if query validation fails. 477 478 ## Options 479 480 * `:prefix` - The prefix to run the query on (such as the schema path 481 in Postgres or the database in MySQL). This overrides the prefix set 482 in the query. 483 484 See the "Shared options" section at the module documentation. 485 486 ## Example 487 488 # Fetch all post titles 489 query = from p in Post, 490 select: p.title 491 MyRepo.all(query) 492 """ 493 @callback all(queryable :: Ecto.Query.t, opts :: Keyword.t) :: [Ecto.Schema.t] | no_return 494 495 @doc """ 496 Returns a lazy enumerable that emits all entries from the data store 497 matching the given query. SQL adapters, such as Postgres and MySQL, can only 498 enumerate a stream inside a transaction. 499 500 May raise `Ecto.QueryError` if query validation fails. 501 502 ## Options 503 504 * `:prefix` - The prefix to run the query on (such as the schema path 505 in Postgres or the database in MySQL). This overrides the prefix set 506 in the query 507 508 * `:max_rows` - The number of rows to load from the database as we stream. 509 It is supported at least by Postgres and MySQL and defaults to 500. 510 511 See the "Shared options" section at the module documentation. 512 513 ## Example 514 515 # Fetch all post titles 516 query = from p in Post, 517 select: p.title 518 stream = MyRepo.stream(query) 519 MyRepo.transaction(fn() -> 520 Enum.to_list(stream) 521 end) 522 """ 523 @callback stream(queryable :: Ecto.Query.t, opts :: Keyword.t) :: Enum.t 524 525 @doc """ 526 Inserts all entries into the repository. 527 528 It expects a schema (`MyApp.User`) or a source (`"users"`) or 529 both (`{"users", MyApp.User}`) as the first argument. The second 530 argument is a list of entries to be inserted, either as keyword 531 lists or as maps. 532 533 It returns a tuple containing the number of entries 534 and any returned result as second element. If the database 535 does not support RETURNING in INSERT statements or no 536 return result was selected, the second element will be `nil`. 537 538 When a schema is given, the values given will be properly dumped 539 before being sent to the database. If the schema contains an 540 autogenerated ID field, it will be handled either at the adapter 541 or the storage layer. However any other autogenerated value, like 542 timestamps, won't be autogenerated when using `c:insert_all/3`. 543 This is by design as this function aims to be a more direct way 544 to insert data into the database without the conveniences of 545 `c:insert/2`. This is also consistent with `c:update_all/3` that 546 does not handle timestamps as well. 547 548 It is also not possible to use `insert_all` to insert across multiple 549 tables, therefore associations are not supported. 550 551 If a source is given, without a schema, the given fields are passed 552 as is to the adapter. 553 554 ## Options 555 556 * `:returning` - selects which fields to return. When `true`, 557 returns all fields in the given struct. May be a list of 558 fields, where a struct is still returned but only with the 559 given fields. Or `false`, where nothing is returned (the default). 560 This option is not supported by all databases. 561 * `:prefix` - The prefix to run the query on (such as the schema path 562 in Postgres or the database in MySQL). 563 * `:on_conflict` - It may be one of `:raise` (the default), `:nothing`, 564 `:replace_all`, a keyword list of update instructions or an `Ecto.Query` 565 query for updates. See the "Upserts" section for more information. 566 * `:conflict_target` - Which columns to verify for conflicts. If 567 none is specified, the conflict target is left up to the database 568 and is usually made of primary keys and/or unique/exclusion constraints. 569 May also be `{:constraint, constraint_name_as_atom}` in databases 570 that support the "ON CONSTRAINT" expression. 571 572 See the "Shared options" section at the module documentation for 573 remaining options. 574 575 ## Examples 576 577 MyRepo.insert_all(Post, [[title: "My first post"], [title: "My second post"]]) 578 MyRepo.insert_all(Post, [%{title: "My first post"}, %{title: "My second post"}]) 579 580 ## Upserts 581 582 `c:insert_all/3` provides upserts (update or inserts) via the `:on_conflict` 583 option. The `:on_conflict` option supports the following values: 584 585 * `:raise` - raises if there is a conflicting primary key or unique index 586 * `:nothing` - ignores the error in case of conflicts 587 * `:replace_all` - replace all values on the existing row with the values 588 in the excluded row (the corresponding record given in the function 589 parameters) 590 * a keyword list of update instructions - such as the one given to 591 `c:update_all/3`, for example: `[set: [title: "new title"]]` 592 * an `Ecto.Query` that will act as an `UPDATE` statement, such as the 593 one given to `c:update_all/3` 594 595 Upserts map to "ON CONFLICT" on databases like Postgres and "ON DUPLICATE KEY" 596 on databases such as MySQL. 597 598 ## Return values 599 600 By default, both Postgres and MySQL return the amount of entries 601 inserted on `c:insert_all/3`. However, when the `:on_conflict` option 602 is specified, Postgres will only return a row if it was affected 603 while MySQL returns at least the number of entries attempted. 604 605 For example, if `:on_conflict` is set to `:nothing`, Postgres will 606 return 0 if no new entry was added while MySQL will still return 607 the amount of entries attempted to be inserted, even if no entry 608 was added. Even worse, if `:on_conflict` is query, MySQL will return 609 the number of attempted entries plus the number of entries modified 610 by the UPDATE query. 611 """ 612 @callback insert_all(schema_or_source :: binary | {binary, Ecto.Schema.t} | Ecto.Schema.t, 613 entries :: [map | Keyword.t], opts :: Keyword.t) :: {integer, nil | [term]} | no_return 614 615 @doc """ 616 Updates all entries matching the given query with the given values. 617 618 It returns a tuple containing the number of entries 619 and any returned result as second element. If the database 620 does not support RETURNING in UPDATE statements or no 621 return result was selected, the second element will be `nil`. 622 623 Keep in mind this `update_all` will not update autogenerated 624 fields like the `updated_at` columns. 625 626 See `Ecto.Query.update/3` for update operations that can be 627 performed on fields. 628 629 ## Options 630 631 * `:returning` - selects which fields to return. When `true`, 632 returns all fields in the given struct. May be a list of 633 fields, where a struct is still returned but only with the 634 given fields. Or `false`, where nothing is returned (the default). 635 This option is not supported by all databases. 636 * `:prefix` - The prefix to run the query on (such as the schema path 637 in Postgres or the database in MySQL). This overrides the prefix set 638 in the query. 639 640 See the "Shared options" section at the module documentation for 641 remaining options. 642 643 ## Examples 644 645 MyRepo.update_all(Post, set: [title: "New title"]) 646 647 MyRepo.update_all(Post, inc: [visits: 1]) 648 649 from(p in Post, where: p.id < 10) 650 |> MyRepo.update_all(set: [title: "New title"]) 651 652 from(p in Post, where: p.id < 10, update: [set: [title: "New title"]]) 653 |> MyRepo.update_all([]) 654 655 from(p in Post, where: p.id < 10, update: [set: [title: ^new_title]]) 656 |> MyRepo.update_all([]) 657 658 from(p in Post, where: p.id < 10, update: [set: [title: fragment("upper(?)", ^new_title)]]) 659 |> MyRepo.update_all([]) 660 661 """ 662 @callback update_all(queryable :: Ecto.Queryable.t, updates :: Keyword.t, opts :: Keyword.t) :: 663 {integer, nil | [term]} | no_return 664 665 @doc """ 666 Deletes all entries matching the given query. 667 668 It returns a tuple containing the number of entries 669 and any returned result as second element. If the database 670 does not support RETURNING in DELETE statements or no 671 return result was selected, the second element will be `nil`. 672 673 ## Options 674 675 * `:returning` - selects which fields to return. When `true`, 676 returns all fields in the given struct. May be a list of 677 fields, where a struct is still returned but only with the 678 given fields. Or `false`, where nothing is returned (the default). 679 This option is not supported by all databases. 680 * `:prefix` - The prefix to run the query on (such as the schema path 681 in Postgres or the database in MySQL). This overrides the prefix set 682 in the query. 683 684 See the "Shared options" section at the module documentation for 685 remaining options. 686 687 ## Examples 688 689 MyRepo.delete_all(Post) 690 691 from(p in Post, where: p.id < 10) |> MyRepo.delete_all 692 """ 693 @callback delete_all(queryable :: Ecto.Queryable.t, opts :: Keyword.t) :: 694 {integer, nil | [term]} | no_return 695 696 @doc """ 697 Inserts a struct defined via `Ecto.Schema` or a changeset. 698 699 In case a struct is given, the struct is converted into a changeset 700 with all non-nil fields as part of the changeset. 701 702 In case a changeset is given, the changes in the changeset are 703 merged with the struct fields, and all of them are sent to the 704 database. 705 706 It returns `{:ok, struct}` if the struct has been successfully 707 inserted or `{:error, changeset}` if there was a validation 708 or a known constraint error. 709 710 ## Options 711 712 * `:returning` - selects which fields to return. When `true`, returns 713 all fields in the given struct. May be a list of fields, where a 714 struct is still returned but only with the given fields. In any case, 715 it will include fields with `read_after_writes` set to true. 716 This option is not supported by all databases. 717 * `:prefix` - The prefix to run the query on (such as the schema path 718 in Postgres or the database in MySQL). This overrides the prefix set 719 in the struct. 720 * `:on_conflict` - It may be one of `:raise` (the default), `:nothing`, 721 `:replace_all`, a keyword list of update instructions or an `Ecto.Query` 722 query for updates. See the "Upserts" section for more information. 723 * `:conflict_target` - Which columns to verify for conflicts. If 724 none is specified, the conflict target is left up to the database 725 and is usually made of primary keys and/or unique/exclusion constraints. 726 May also be `{:constraint, constraint_name_as_atom}` in databases 727 that support the "ON CONSTRAINT" expression. 728 729 See the "Shared options" section at the module documentation. 730 731 ## Examples 732 733 A typical example is calling `MyRepo.insert/1` with a struct 734 and acting on the return value: 735 736 case MyRepo.insert %Post{title: "Ecto is great"} do 737 {:ok, struct} -> # Inserted with success 738 {:error, changeset} -> # Something went wrong 739 end 740 741 ## Upserts 742 743 `c:insert/2` provides upserts (update or inserts) via the `:on_conflict` 744 option. The `:on_conflict` option supports the following values: 745 746 * `:raise` - raises if there is a conflicting primary key or unique index 747 * `:nothing` - ignores the error in case of conflicts 748 * `:replace_all` - replace all values on the existing row with the values 749 in the excluded row (the record given in the function parameters) 750 * a keyword list of update instructions - such as the one given to 751 `c:update_all/3`, for example: `[set: [title: "new title"]]` 752 * an `Ecto.Query` that will act as an `UPDATE` statement, such as the 753 one given to `c:update_all/3` 754 755 Upserts map to "ON CONFLICT" on databases like Postgres and "ON DUPLICATE KEY" 756 on databases such as MySQL. 757 758 As an example, imagine `:title` is marked as a unique column in 759 the database: 760 761 {:ok, inserted} = MyRepo.insert(%Post{title: "this is unique"}) 762 763 Now we can insert with the same title but do nothing on conflicts: 764 765 {:ok, ignored} = MyRepo.insert(%Post{title: "this is unique"}, on_conflict: :nothing) 766 assert ignored.id == nil 767 768 Because we used `on_conflict: :nothing`, instead of getting an error, 769 we got `{:ok, struct}`. However the returned struct does not reflect 770 the data in the database. One possible mechanism to detect if an 771 insert or nothing happened in case of `on_conflict: :nothing` is by 772 checking the `id` field. `id` will be nil if the field is autogenerated 773 by the database and no insert happened. 774 775 For actual upserts, where an insert or update may happen, the situation 776 is slightly more complex, as the database does not actually inform us 777 if an insert or update happened. Let's insert a post with the same title 778 but use a query to update the body column in case of conflicts: 779 780 # In Postgres (it requires the conflict target for updates): 781 on_conflict = [set: [body: "updated"]] 782 {:ok, updated} = MyRepo.insert(%Post{title: "this is unique"}, 783 on_conflict: on_conflict, conflict_target: :title) 784 785 # In MySQL (conflict target is not supported): 786 on_conflict = [set: [title: "updated"]] 787 {:ok, updated} = MyRepo.insert(%Post{id: inserted.id, title: "updated"}, 788 on_conflict: on_conflict) 789 790 In the examples above, even though it returned `:ok`, we do not know 791 if we inserted new data or if we updated only the `:on_conflict` fields. 792 In case an update happened, the data in the struct most likely does 793 not match the data in the database. For example, autogenerated fields 794 such as `inserted_at` will point to now rather than the time the 795 struct was actually inserted. 796 797 If you need to guarantee the data in the returned struct mirrors the 798 database, you have three options: 799 800 * Use `on_conflict: :replace_all`, although that will replace all 801 fields in the database with current ones: 802 803 MyRepo.insert(%Post{title: "this is unique"}, 804 on_conflict: :replace_all, conflict_target: :title) 805 806 * Specify `read_after_writes: true` in your schema for choosing 807 fields that are read from the database after every operation. 808 Or pass `returning: true` to `insert` to read all fields back: 809 810 MyRepo.insert(%Post{title: "this is unique"}, returning: true, 811 on_conflict: on_conflict, conflict_target: :title) 812 813 * Alternatively, read the data again from the database in a separate 814 query. This option requires the primary key to be generated by the 815 database: 816 817 {:ok, updated} = MyRepo.insert(%Post{title: "this is unique"}, on_conflict: on_conflict) 818 Repo.get(Post, updated.id) 819 820 Because of the inability to know if the struct is up to date or not, 821 using associations with the `:on_conflict` option is not recommended. 822 For instance, Ecto may even trigger constraint violations when associations 823 are used with `on_conflict: :nothing`, as no ID will be available in 824 the case the record already exists, and it is not possible for Ecto to 825 detect such cases reliably. 826 """ 827 @callback insert(struct_or_changeset :: Ecto.Schema.t | Ecto.Changeset.t, opts :: Keyword.t) :: 828 {:ok, Ecto.Schema.t} | {:error, Ecto.Changeset.t} 829 830 @doc """ 831 Updates a changeset using its primary key. 832 833 A changeset is required as it is the only mechanism for 834 tracking dirty changes. Only the fields present in the `changes` part 835 of the changeset are sent to the database. Any other, in-memory 836 changes done to the schema are ignored. 837 838 If the struct has no primary key, `Ecto.NoPrimaryKeyFieldError` 839 will be raised. 840 841 It returns `{:ok, struct}` if the struct has been successfully 842 updated or `{:error, changeset}` if there was a validation 843 or a known constraint error. 844 845 ## Options 846 847 Besides the "Shared options" section at the module documentation, 848 it accepts: 849 850 * `:force` - By default, if there are no changes in the changeset, 851 `c:update/2` is a no-op. By setting this option to true, update 852 callbacks will always be executed, even if there are no changes 853 (including timestamps). 854 * `:prefix` - The prefix to run the query on (such as the schema path 855 in Postgres or the database in MySQL). This overrides the prefix set 856 in the struct. 857 858 ## Example 859 860 post = MyRepo.get!(Post, 42) 861 post = Ecto.Changeset.change post, title: "New title" 862 case MyRepo.update post do 863 {:ok, struct} -> # Updated with success 864 {:error, changeset} -> # Something went wrong 865 end 866 """ 867 @callback update(changeset :: Ecto.Changeset.t, opts :: Keyword.t) :: 868 {:ok, Ecto.Schema.t} | {:error, Ecto.Changeset.t} 869 870 @doc """ 871 Inserts or updates a changeset depending on whether the struct is persisted 872 or not. 873 874 The distinction whether to insert or update will be made on the 875 `Ecto.Schema.Metadata` field `:state`. The `:state` is automatically set by 876 Ecto when loading or building a schema. 877 878 Please note that for this to work, you will have to load existing structs from 879 the database. So even if the struct exists, this won't work: 880 881 struct = %Post{id: "existing_id", ...} 882 MyRepo.insert_or_update changeset 883 # => {:error, changeset} # id already exists 884 885 ## Options 886 887 * `:prefix` - The prefix to run the query on (such as the schema path 888 in Postgres or the database in MySQL). This overrides the prefix set 889 in the struct. 890 891 See the "Shared options" section at the module documentation. 892 893 ## Example 894 895 result = 896 case MyRepo.get(Post, id) do 897 nil -> %Post{id: id} # Post not found, we build one 898 post -> post # Post exists, let's use it 899 end 900 |> Post.changeset(changes) 901 |> MyRepo.insert_or_update 902 903 case result do 904 {:ok, struct} -> # Inserted or updated with success 905 {:error, changeset} -> # Something went wrong 906 end 907 """ 908 @callback insert_or_update(changeset :: Ecto.Changeset.t, opts :: Keyword.t) :: 909 {:ok, Ecto.Schema.t} | {:error, Ecto.Changeset.t} 910 911 @doc """ 912 Deletes a struct using its primary key. 913 914 If the struct has no primary key, `Ecto.NoPrimaryKeyFieldError` 915 will be raised. 916 917 It returns `{:ok, struct}` if the struct has been successfully 918 deleted or `{:error, changeset}` if there was a validation 919 or a known constraint error. 920 921 ## Options 922 923 * `:prefix` - The prefix to run the query on (such as the schema path 924 in Postgres or the database in MySQL). This overrides the prefix set 925 in the struct. 926 927 See the "Shared options" section at the module documentation. 928 929 ## Example 930 931 post = MyRepo.get!(Post, 42) 932 case MyRepo.delete post do 933 {:ok, struct} -> # Deleted with success 934 {:error, changeset} -> # Something went wrong 935 end 936 937 """ 938 @callback delete(struct_or_changeset :: Ecto.Schema.t | Ecto.Changeset.t, opts :: Keyword.t) :: 939 {:ok, Ecto.Schema.t} | {:error, Ecto.Changeset.t} 940 941 @doc """ 942 Same as `c:insert/2` but returns the struct or raises if the changeset is invalid. 943 """ 944 @callback insert!(struct_or_changeset :: Ecto.Schema.t | Ecto.Changeset.t, opts :: Keyword.t) :: 945 Ecto.Schema.t | no_return 946 947 @doc """ 948 Same as `c:update/2` but returns the struct or raises if the changeset is invalid. 949 """ 950 @callback update!(changeset :: Ecto.Changeset.t, opts :: Keyword.t) :: 951 Ecto.Schema.t | no_return 952 953 @doc """ 954 Same as `c:insert_or_update/2` but returns the struct or raises if the changeset 955 is invalid. 956 """ 957 @callback insert_or_update!(changeset :: Ecto.Changeset.t, opts :: Keyword.t) :: 958 Ecto.Schema.t | no_return 959 960 @doc """ 961 Same as `c:delete/2` but returns the struct or raises if the changeset is invalid. 962 """ 963 @callback delete!(struct_or_changeset :: Ecto.Schema.t | Ecto.Changeset.t, opts :: Keyword.t) :: 964 Ecto.Schema.t | no_return 965 966 @doc """ 967 Runs the given function or `Ecto.Multi` inside a transaction. 968 969 ## Use with function 970 971 If an unhandled error occurs the transaction will be rolled back 972 and the error will bubble up from the transaction function. 973 If no error occurred the transaction will be committed when the 974 function returns. A transaction can be explicitly rolled back 975 by calling `c:rollback/1`, this will immediately leave the function 976 and return the value given to `rollback` as `{:error, value}`. 977 978 A successful transaction returns the value returned by the function 979 wrapped in a tuple as `{:ok, value}`. 980 981 If `c:transaction/2` is called inside another transaction, the function 982 is simply executed, without wrapping the new transaction call in any 983 way. If there is an error in the inner transaction and the error is 984 rescued, or the inner transaction is rolled back, the whole outer 985 transaction is marked as tainted, guaranteeing nothing will be committed. 986 987 ## Use with Ecto.Multi 988 989 Besides functions transaction can be used with an Ecto.Multi struct. 990 Transaction will be started, all operations applied and in case of 991 success committed returning `{:ok, changes}`. In case of any errors 992 the transaction will be rolled back and 993 `{:error, failed_operation, failed_value, changes_so_far}` will be 994 returned. 995 996 You can read more about using transactions with `Ecto.Multi` as well as 997 see some examples in the `Ecto.Multi` documentation. 998 999 ## Options 1000 1001 See the "Shared options" section at the module documentation. 1002 1003 ## Examples 1004 1005 import Ecto.Changeset, only: [change: 2] 1006 1007 MyRepo.transaction(fn -> 1008 MyRepo.update!(change(alice, balance: alice.balance - 10)) 1009 MyRepo.update!(change(bob, balance: bob.balance + 10)) 1010 end) 1011 1012 # Roll back a transaction explicitly 1013 MyRepo.transaction(fn -> 1014 p = MyRepo.insert!(%Post{}) 1015 if not Editor.post_allowed?(p) do 1016 MyRepo.rollback(:posting_not_allowed) 1017 end 1018 end) 1019 1020 # With Ecto.Multi 1021 Ecto.Multi.new 1022 |> Ecto.Multi.insert(:post, %Post{}) 1023 |> MyRepo.transaction 1024 1025 """ 1026 @callback transaction(fun_or_multi :: fun | Ecto.Multi.t, opts :: Keyword.t) :: 1027 {:ok, any} | {:error, any} | {:error, Ecto.Multi.name, any, %{Ecto.Multi.name => any}} 1028 @optional_callbacks [transaction: 2] 1029 1030 @doc """ 1031 Returns true if the current process is inside a transaction. 1032 1033 ## Examples 1034 1035 MyRepo.in_transaction? 1036 #=> false 1037 1038 MyRepo.transaction(fn -> 1039 MyRepo.in_transaction? #=> true 1040 end) 1041 1042 """ 1043 @callback in_transaction?() :: boolean 1044 @optional_callbacks [in_transaction?: 0] 1045 1046 @doc """ 1047 Rolls back the current transaction. 1048 1049 The transaction will return the value given as `{:error, value}`. 1050 """ 1051 @callback rollback(value :: any) :: no_return 1052 @optional_callbacks [rollback: 1] 1053 1054 @doc """ 1055 Loads `data` into a struct or a map. 1056 1057 The first argument can be a schema, or a map (of types) and determines the return value: 1058 a struct or a map, respectively. 1059 1060 The second argument `data` specifies fields and values that are to be loaded. 1061 It can be a map, a keyword list, or a `{fields, values}` tuple. 1062 Fields can be atoms or strings. 1063 1064 Fields that are not present in the schema (or `types` map) are ignored. 1065 If any of the values has invalid type, an error is raised. 1066 1067 ## Examples 1068 1069 iex> MyRepo.load(User, %{name: "Alice", age: 25}) 1070 %User{name: "Alice", age: 25} 1071 1072 iex> MyRepo.load(User, [name: "Alice", age: 25]) 1073 %User{name: "Alice", age: 25} 1074 1075 `data` can also take form of `{fields, values}`: 1076 1077 iex> MyRepo.load(User, {[:name, :age], ["Alice", 25]}) 1078 %User{name: "Alice", age: 25, ...} 1079 1080 The first argument can also be a `types` map: 1081 1082 iex> types = %{name: :string, age: :integer} 1083 iex> MyRepo.load(types, %{name: "Alice", age: 25}) 1084 %{name: "Alice", age: 25} 1085 1086 This function is especially useful when parsing raw query results: 1087 1088 iex> result = Ecto.Adapters.SQL.query!(MyRepo, "SELECT * FROM users", []) 1089 iex> Enum.map(result.rows, &MyRepo.load(User, {result.columns, &1})) 1090 [%User{...}, ...] 1091 1092 """ 1093 @callback load(Ecto.Schema.t | map(), map() | Keyword.t | {list, list}) :: Ecto.Schema.t | map() 1094end 1095