repo.ex (74306B)
1 defmodule 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` and `:adapter` as 10 option. 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, 15 otp_app: :my_app, 16 adapter: Ecto.Adapters.Postgres 17 end 18 19 Could be configured with: 20 21 config :my_app, Repo, 22 database: "ecto_simple", 23 username: "postgres", 24 password: "postgres", 25 hostname: "localhost" 26 27 Most of the configuration that goes into the `config` is specific 28 to the adapter. For this particular example, you can check 29 [`Ecto.Adapters.Postgres`](https://hexdocs.pm/ecto_sql/Ecto.Adapters.Postgres.html) 30 for more information. In spite of this, the following configuration values 31 are shared across all adapters: 32 33 * `:name`- The name of the Repo supervisor process 34 35 * `:priv` - the directory where to keep repository data, like 36 migrations, schema and more. Defaults to "priv/YOUR_REPO". 37 It must always point to a subdirectory inside the priv directory 38 39 * `:url` - an URL that specifies storage information. Read below 40 for more information 41 42 * `:log` - the log level used when logging the query with Elixir's 43 Logger. If false, disables logging for that repository. 44 Defaults to `:debug` 45 46 * `:pool_size` - the size of the pool used by the connection module. 47 Defaults to `10` 48 49 * `:telemetry_prefix` - we recommend adapters to publish events 50 using the `Telemetry` library. By default, the telemetry prefix 51 is based on the module name, so if your module is called 52 `MyApp.Repo`, the prefix will be `[:my_app, :repo]`. See the 53 "Telemetry Events" section to see which events we recommend 54 adapters to publish. Note that if you have multiple databases, you 55 should keep the `:telemetry_prefix` consistent for each repo and 56 use the `:repo` property in the event metadata for distinguishing 57 between repos. 58 59 * `:stacktrace`- when true, publishes the stacktrace in telemetry events 60 and allows more advanced logging. 61 62 ## URLs 63 64 Repositories by default support URLs. For example, the configuration 65 above could be rewritten to: 66 67 config :my_app, Repo, 68 url: "ecto://postgres:postgres@localhost/ecto_simple" 69 70 The schema can be of any value. The path represents the database name 71 while options are simply merged in. 72 73 URL can include query parameters to override shared and adapter-specific 74 options, like `ssl`, `timeout` and `pool_size`. The following example 75 shows how to pass these configuration values: 76 77 config :my_app, Repo, 78 url: "ecto://postgres:postgres@localhost/ecto_simple?ssl=true&pool_size=10" 79 80 In case the URL needs to be dynamically configured, for example by 81 reading a system environment variable, such can be done via the 82 `c:init/2` repository callback: 83 84 def init(_type, config) do 85 {:ok, Keyword.put(config, :url, System.get_env("DATABASE_URL"))} 86 end 87 88 ## Shared options 89 90 Almost all of the repository functions outlined in this module accept the following 91 options: 92 93 * `:timeout` - The time in milliseconds (as an integer) to wait for the query call to 94 finish. `:infinity` will wait indefinitely (default: `15_000`) 95 * `:log` - When false, does not log the query 96 * `:telemetry_event` - The telemetry event name to dispatch the event under. 97 See the next section for more information 98 * `:telemetry_options` - Extra options to attach to telemetry event name. 99 See the next section for more information 100 101 ## Telemetry events 102 103 There are two types of telemetry events. The ones emitted by Ecto and the 104 ones that are adapter specific. 105 106 ### Ecto telemetry events 107 108 The following events are emitted by all Ecto repositories: 109 110 * `[:ecto, :repo, :init]` - it is invoked whenever a repository starts. 111 The measurement is a single `system_time` entry in native unit. The 112 metadata is the `:repo` and all initialization options under `:opts`. 113 114 ### Adapter-specific events 115 116 We recommend adapters to publish certain `Telemetry` events listed below. 117 Those events will use the `:telemetry_prefix` outlined above which defaults 118 to `[:my_app, :repo]`. 119 120 For instance, to receive all query events published by a repository called 121 `MyApp.Repo`, one would define a module: 122 123 defmodule MyApp.Telemetry do 124 def handle_event([:my_app, :repo, :query], measurements, metadata, config) do 125 IO.inspect binding() 126 end 127 end 128 129 Then, in the `Application.start/2` callback, attach the handler to this event using 130 a unique handler id: 131 132 :ok = :telemetry.attach("my-app-handler-id", [:my_app, :repo, :query], &MyApp.Telemetry.handle_event/4, %{}) 133 134 For details, see [the telemetry documentation](https://hexdocs.pm/telemetry/). 135 136 Below we list all events developers should expect from Ecto. All examples 137 below consider a repository named `MyApp.Repo`: 138 139 #### `[:my_app, :repo, :query]` 140 141 This event should be invoked on every query sent to the adapter, including 142 queries that are related to the transaction management. 143 144 The `:measurements` map will include the following, all given in the 145 `:native` time unit: 146 147 * `:idle_time` - the time the connection spent waiting before being checked out for the query 148 * `:queue_time` - the time spent waiting to check out a database connection 149 * `:query_time` - the time spent executing the query 150 * `:decode_time` - the time spent decoding the data received from the database 151 * `:total_time` - the sum of (`queue_time`, `query_time`, and `decode_time`)️ 152 153 All measurements are given in the `:native` time unit. You can read more 154 about it in the docs for `System.convert_time_unit/3`. 155 156 A telemetry `:metadata` map including the following fields. Each database 157 adapter may emit different information here. For Ecto.SQL databases, it 158 will look like this: 159 160 * `:type` - the type of the Ecto query. For example, for Ecto.SQL 161 databases, it would be `:ecto_sql_query` 162 * `:repo` - the Ecto repository 163 * `:result` - the query result 164 * `:params` - the query parameters 165 * `:query` - the query sent to the database as a string 166 * `:source` - the source the query was made on (may be `nil`) 167 * `:stacktrace` - the stacktrace information, if enabled, or `nil` 168 * `:options` - extra options given to the repo operation under 169 `:telemetry_options` 170 171 ## Read-only repositories 172 173 You can mark a repository as read-only by passing the `:read_only` 174 flag on `use`: 175 176 use Ecto.Repo, otp_app: ..., adapter: ..., read_only: true 177 178 By passing the `:read_only` option, none of the functions that perform 179 write operations, such as `c:insert/2`, `c:insert_all/3`, `c:update_all/3`, 180 and friends will be defined. 181 """ 182 183 @type t :: module 184 185 @doc """ 186 Returns all running Ecto repositories. 187 188 The list is returned in no particular order. The list 189 contains either atoms, for named Ecto repositories, or 190 PIDs. 191 """ 192 @spec all_running() :: [atom() | pid()] 193 defdelegate all_running(), to: Ecto.Repo.Registry 194 195 @doc false 196 defmacro __using__(opts) do 197 quote bind_quoted: [opts: opts] do 198 @behaviour Ecto.Repo 199 200 {otp_app, adapter, behaviours} = 201 Ecto.Repo.Supervisor.compile_config(__MODULE__, opts) 202 203 @otp_app otp_app 204 @adapter adapter 205 @default_dynamic_repo opts[:default_dynamic_repo] || __MODULE__ 206 @read_only opts[:read_only] || false 207 @before_compile adapter 208 @aggregates [:count, :avg, :max, :min, :sum] 209 210 def config do 211 {:ok, config} = Ecto.Repo.Supervisor.runtime_config(:runtime, __MODULE__, @otp_app, []) 212 config 213 end 214 215 def __adapter__ do 216 @adapter 217 end 218 219 def child_spec(opts) do 220 %{ 221 id: __MODULE__, 222 start: {__MODULE__, :start_link, [opts]}, 223 type: :supervisor 224 } 225 end 226 227 def start_link(opts \\ []) do 228 Ecto.Repo.Supervisor.start_link(__MODULE__, @otp_app, @adapter, opts) 229 end 230 231 def stop(timeout \\ 5000) do 232 Supervisor.stop(get_dynamic_repo(), :normal, timeout) 233 end 234 235 def load(schema_or_types, data) do 236 Ecto.Repo.Schema.load(@adapter, schema_or_types, data) 237 end 238 239 def checkout(fun, opts \\ []) when is_function(fun) do 240 %{adapter: adapter} = meta = Ecto.Repo.Registry.lookup(get_dynamic_repo()) 241 adapter.checkout(meta, opts, fun) 242 end 243 244 def checked_out? do 245 %{adapter: adapter} = meta = Ecto.Repo.Registry.lookup(get_dynamic_repo()) 246 adapter.checked_out?(meta) 247 end 248 249 @compile {:inline, get_dynamic_repo: 0, prepare_opts: 2} 250 251 def get_dynamic_repo() do 252 Process.get({__MODULE__, :dynamic_repo}, @default_dynamic_repo) 253 end 254 255 def put_dynamic_repo(dynamic) when is_atom(dynamic) or is_pid(dynamic) do 256 Process.put({__MODULE__, :dynamic_repo}, dynamic) || @default_dynamic_repo 257 end 258 259 def default_options(_operation), do: [] 260 defoverridable default_options: 1 261 262 defp prepare_opts(operation_name, opts) do 263 operation_name 264 |> default_options() 265 |> Keyword.merge(opts) 266 end 267 268 ## Transactions 269 270 if Ecto.Adapter.Transaction in behaviours do 271 def transaction(fun_or_multi, opts \\ []) do 272 repo = get_dynamic_repo() 273 Ecto.Repo.Transaction.transaction(__MODULE__, repo, fun_or_multi, Ecto.Repo.Supervisor.tuplet(repo, prepare_opts(:transaction, opts))) 274 end 275 276 def in_transaction? do 277 Ecto.Repo.Transaction.in_transaction?(get_dynamic_repo()) 278 end 279 280 @spec rollback(term) :: no_return 281 def rollback(value) do 282 Ecto.Repo.Transaction.rollback(get_dynamic_repo(), value) 283 end 284 end 285 286 ## Schemas 287 288 if Ecto.Adapter.Schema in behaviours and not @read_only do 289 def insert(struct, opts \\ []) do 290 repo = get_dynamic_repo() 291 Ecto.Repo.Schema.insert(__MODULE__, repo, struct, Ecto.Repo.Supervisor.tuplet(repo, prepare_opts(:insert, opts))) 292 end 293 294 def update(struct, opts \\ []) do 295 repo = get_dynamic_repo() 296 Ecto.Repo.Schema.update(__MODULE__, get_dynamic_repo(), struct, Ecto.Repo.Supervisor.tuplet(repo, prepare_opts(:update, opts))) 297 end 298 299 def insert_or_update(changeset, opts \\ []) do 300 repo = get_dynamic_repo() 301 Ecto.Repo.Schema.insert_or_update(__MODULE__, get_dynamic_repo(), changeset, Ecto.Repo.Supervisor.tuplet(repo, prepare_opts(:insert_or_update, opts))) 302 end 303 304 def delete(struct, opts \\ []) do 305 repo = get_dynamic_repo() 306 Ecto.Repo.Schema.delete(__MODULE__, get_dynamic_repo(), struct, Ecto.Repo.Supervisor.tuplet(repo, prepare_opts(:delete, opts))) 307 end 308 309 def insert!(struct, opts \\ []) do 310 repo = get_dynamic_repo() 311 Ecto.Repo.Schema.insert!(__MODULE__, get_dynamic_repo(), struct, Ecto.Repo.Supervisor.tuplet(repo, prepare_opts(:insert, opts))) 312 end 313 314 def update!(struct, opts \\ []) do 315 repo = get_dynamic_repo() 316 Ecto.Repo.Schema.update!(__MODULE__, get_dynamic_repo(), struct, Ecto.Repo.Supervisor.tuplet(repo, prepare_opts(:update, opts))) 317 end 318 319 def insert_or_update!(changeset, opts \\ []) do 320 repo = get_dynamic_repo() 321 Ecto.Repo.Schema.insert_or_update!(__MODULE__, get_dynamic_repo(), changeset, Ecto.Repo.Supervisor.tuplet(repo, prepare_opts(:insert_or_update, opts))) 322 end 323 324 def delete!(struct, opts \\ []) do 325 repo = get_dynamic_repo() 326 Ecto.Repo.Schema.delete!(__MODULE__, get_dynamic_repo(), struct, Ecto.Repo.Supervisor.tuplet(repo, prepare_opts(:delete, opts))) 327 end 328 329 def insert_all(schema_or_source, entries, opts \\ []) do 330 repo = get_dynamic_repo() 331 Ecto.Repo.Schema.insert_all(__MODULE__, get_dynamic_repo(), schema_or_source, entries, Ecto.Repo.Supervisor.tuplet(repo, prepare_opts(:insert_all, opts))) 332 end 333 end 334 335 ## Queryable 336 337 if Ecto.Adapter.Queryable in behaviours do 338 if not @read_only do 339 def update_all(queryable, updates, opts \\ []) do 340 repo = get_dynamic_repo() 341 Ecto.Repo.Queryable.update_all(get_dynamic_repo(), queryable, updates, Ecto.Repo.Supervisor.tuplet(repo, prepare_opts(:update_all, opts))) 342 end 343 344 def delete_all(queryable, opts \\ []) do 345 repo = get_dynamic_repo() 346 Ecto.Repo.Queryable.delete_all(get_dynamic_repo(), queryable, Ecto.Repo.Supervisor.tuplet(repo, prepare_opts(:delete_all, opts))) 347 end 348 end 349 350 def all(queryable, opts \\ []) do 351 repo = get_dynamic_repo() 352 Ecto.Repo.Queryable.all(get_dynamic_repo(), queryable, Ecto.Repo.Supervisor.tuplet(repo, prepare_opts(:all, opts))) 353 end 354 355 def stream(queryable, opts \\ []) do 356 repo = get_dynamic_repo() 357 Ecto.Repo.Queryable.stream(get_dynamic_repo(), queryable, Ecto.Repo.Supervisor.tuplet(repo, prepare_opts(:stream, opts))) 358 end 359 360 def get(queryable, id, opts \\ []) do 361 repo = get_dynamic_repo() 362 Ecto.Repo.Queryable.get(get_dynamic_repo(), queryable, id, Ecto.Repo.Supervisor.tuplet(repo, prepare_opts(:all, opts))) 363 end 364 365 def get!(queryable, id, opts \\ []) do 366 repo = get_dynamic_repo() 367 Ecto.Repo.Queryable.get!(get_dynamic_repo(), queryable, id, Ecto.Repo.Supervisor.tuplet(repo, prepare_opts(:all, opts))) 368 end 369 370 def get_by(queryable, clauses, opts \\ []) do 371 repo = get_dynamic_repo() 372 Ecto.Repo.Queryable.get_by(get_dynamic_repo(), queryable, clauses, Ecto.Repo.Supervisor.tuplet(repo, prepare_opts(:all, opts))) 373 end 374 375 def get_by!(queryable, clauses, opts \\ []) do 376 repo = get_dynamic_repo() 377 Ecto.Repo.Queryable.get_by!(get_dynamic_repo(), queryable, clauses, Ecto.Repo.Supervisor.tuplet(repo, prepare_opts(:all, opts))) 378 end 379 380 def reload(queryable, opts \\ []) do 381 repo = get_dynamic_repo() 382 Ecto.Repo.Queryable.reload(get_dynamic_repo(), queryable, Ecto.Repo.Supervisor.tuplet(repo, prepare_opts(:reload, opts))) 383 end 384 385 def reload!(queryable, opts \\ []) do 386 repo = get_dynamic_repo() 387 Ecto.Repo.Queryable.reload!(get_dynamic_repo(), queryable, Ecto.Repo.Supervisor.tuplet(repo, prepare_opts(:reload, opts))) 388 end 389 390 def one(queryable, opts \\ []) do 391 repo = get_dynamic_repo() 392 Ecto.Repo.Queryable.one(get_dynamic_repo(), queryable, Ecto.Repo.Supervisor.tuplet(repo, prepare_opts(:all, opts))) 393 end 394 395 def one!(queryable, opts \\ []) do 396 repo = get_dynamic_repo() 397 Ecto.Repo.Queryable.one!(get_dynamic_repo(), queryable, Ecto.Repo.Supervisor.tuplet(repo, prepare_opts(:all, opts))) 398 end 399 400 def aggregate(queryable, aggregate, opts \\ []) 401 402 def aggregate(queryable, aggregate, opts) 403 when aggregate in [:count] and is_list(opts) do 404 repo = get_dynamic_repo() 405 Ecto.Repo.Queryable.aggregate(get_dynamic_repo(), queryable, aggregate, Ecto.Repo.Supervisor.tuplet(repo, prepare_opts(:all, opts))) 406 end 407 408 def aggregate(queryable, aggregate, field) 409 when aggregate in @aggregates and is_atom(field) do 410 repo = get_dynamic_repo() 411 Ecto.Repo.Queryable.aggregate(get_dynamic_repo(), queryable, aggregate, field, Ecto.Repo.Supervisor.tuplet(repo, prepare_opts(:all, []))) 412 end 413 414 def aggregate(queryable, aggregate, field, opts) 415 when aggregate in @aggregates and is_atom(field) and is_list(opts) do 416 repo = get_dynamic_repo() 417 Ecto.Repo.Queryable.aggregate(get_dynamic_repo(), queryable, aggregate, field, Ecto.Repo.Supervisor.tuplet(repo, prepare_opts(:all, opts))) 418 end 419 420 def exists?(queryable, opts \\ []) do 421 repo = get_dynamic_repo() 422 Ecto.Repo.Queryable.exists?(get_dynamic_repo(), queryable, Ecto.Repo.Supervisor.tuplet(repo, prepare_opts(:all, opts))) 423 end 424 425 def preload(struct_or_structs_or_nil, preloads, opts \\ []) do 426 repo = get_dynamic_repo() 427 Ecto.Repo.Preloader.preload(struct_or_structs_or_nil, get_dynamic_repo(), preloads, Ecto.Repo.Supervisor.tuplet(repo, prepare_opts(:preload, opts))) 428 end 429 430 def prepare_query(operation, query, opts), do: {query, opts} 431 defoverridable prepare_query: 3 432 end 433 end 434 end 435 436 ## User callbacks 437 438 @optional_callbacks init: 2 439 440 @doc """ 441 A callback executed when the repo starts or when configuration is read. 442 443 The first argument is the context the callback is being invoked. If it 444 is called because the Repo supervisor is starting, it will be `:supervisor`. 445 It will be `:runtime` if it is called for reading configuration without 446 actually starting a process. 447 448 The second argument is the repository configuration as stored in the 449 application environment. It must return `{:ok, keyword}` with the updated 450 list of configuration or `:ignore` (only in the `:supervisor` case). 451 """ 452 @doc group: "User callbacks" 453 @callback init(context :: :supervisor | :runtime, config :: Keyword.t()) :: 454 {:ok, Keyword.t()} | :ignore 455 456 ## Ecto.Adapter 457 458 @doc """ 459 Returns the adapter tied to the repository. 460 """ 461 @doc group: "Runtime API" 462 @callback __adapter__ :: Ecto.Adapter.t() 463 464 @doc """ 465 Returns the adapter configuration stored in the `:otp_app` environment. 466 467 If the `c:init/2` callback is implemented in the repository, 468 it will be invoked with the first argument set to `:runtime`. 469 """ 470 @doc group: "Runtime API" 471 @callback config() :: Keyword.t() 472 473 @doc """ 474 Starts any connection pooling or supervision and return `{:ok, pid}` 475 or just `:ok` if nothing needs to be done. 476 477 Returns `{:error, {:already_started, pid}}` if the repo is already 478 started or `{:error, term}` in case anything else goes wrong. 479 480 ## Options 481 482 See the configuration in the moduledoc for options shared between adapters, 483 for adapter-specific configuration see the adapter's documentation. 484 """ 485 @doc group: "Runtime API" 486 @callback start_link(opts :: Keyword.t()) :: 487 {:ok, pid} 488 | {:error, {:already_started, pid}} 489 | {:error, term} 490 491 @doc """ 492 Shuts down the repository. 493 """ 494 @doc group: "Runtime API" 495 @callback stop(timeout) :: :ok 496 497 @doc """ 498 Checks out a connection for the duration of the function. 499 500 It returns the result of the function. This is useful when 501 you need to perform multiple operations against the repository 502 in a row and you want to avoid checking out the connection 503 multiple times. 504 505 `checkout/2` and `transaction/2` can be combined and nested 506 multiple times. If `checkout/2` is called inside the function 507 of another `checkout/2` call, the function is simply executed, 508 without checking out a new connection. 509 510 ## Options 511 512 See the ["Shared options"](#module-shared-options) section at the module 513 documentation for more options. 514 """ 515 @doc group: "Transaction API" 516 @callback checkout((() -> result), opts :: Keyword.t()) :: result when result: var 517 518 @doc """ 519 Returns true if a connection has been checked out. 520 521 This is true if inside a `c:Ecto.Repo.checkout/2` or 522 `c:Ecto.Repo.transaction/2`. 523 524 ## Examples 525 526 MyRepo.checked_out? 527 #=> false 528 529 MyRepo.transaction(fn -> 530 MyRepo.checked_out? #=> true 531 end) 532 533 MyRepo.checkout(fn -> 534 MyRepo.checked_out? #=> true 535 end) 536 537 """ 538 @doc group: "Transaction API" 539 @callback checked_out?() :: boolean 540 541 @doc """ 542 Loads `data` into a schema or a map. 543 544 The first argument can be a a schema module or a map (of types). 545 The first argument determines the return value: a struct or a map, 546 respectively. 547 548 The second argument `data` specifies fields and values that are to be loaded. 549 It can be a map, a keyword list, or a `{fields, values}` tuple. 550 Fields can be atoms or strings. 551 552 Fields that are not present in the schema (or `types` map) are ignored. 553 If any of the values has invalid type, an error is raised. 554 555 To load data from non-database sources, use `Ecto.embedded_load/3`. 556 557 ## Examples 558 559 iex> MyRepo.load(User, %{name: "Alice", age: 25}) 560 %User{name: "Alice", age: 25} 561 562 iex> MyRepo.load(User, [name: "Alice", age: 25]) 563 %User{name: "Alice", age: 25} 564 565 `data` can also take form of `{fields, values}`: 566 567 iex> MyRepo.load(User, {[:name, :age], ["Alice", 25]}) 568 %User{name: "Alice", age: 25, ...} 569 570 The first argument can also be a `types` map: 571 572 iex> types = %{name: :string, age: :integer} 573 iex> MyRepo.load(types, %{name: "Alice", age: 25}) 574 %{name: "Alice", age: 25} 575 576 This function is especially useful when parsing raw query results: 577 578 iex> result = Ecto.Adapters.SQL.query!(MyRepo, "SELECT * FROM users", []) 579 iex> Enum.map(result.rows, &MyRepo.load(User, {result.columns, &1})) 580 [%User{...}, ...] 581 582 """ 583 @doc group: "Schema API" 584 @callback load( 585 schema_or_map :: module | map(), 586 data :: map() | Keyword.t() | {list, list} 587 ) :: Ecto.Schema.t() | map() 588 589 @doc """ 590 Returns the atom name or pid of the current repository. 591 592 See `c:put_dynamic_repo/1` for more information. 593 """ 594 @doc group: "Runtime API" 595 @callback get_dynamic_repo() :: atom() | pid() 596 597 @doc """ 598 Sets the dynamic repository to be used in further interactions. 599 600 Sometimes you may want a single Ecto repository to talk to 601 many different database instances. By default, when you call 602 `MyApp.Repo.start_link/1`, it will start a repository with 603 name `MyApp.Repo`. But if you want to start multiple repositories, 604 you can give each of them a different name: 605 606 MyApp.Repo.start_link(name: :tenant_foo, hostname: "foo.example.com") 607 MyApp.Repo.start_link(name: :tenant_bar, hostname: "bar.example.com") 608 609 You can also start repositories without names by explicitly 610 setting the name to nil: 611 612 MyApp.Repo.start_link(name: nil, hostname: "temp.example.com") 613 614 However, once the repository is started, you can't directly interact with 615 it, since all operations in `MyApp.Repo` are sent by default to the repository 616 named `MyApp.Repo`. You can change the default repo at compile time with: 617 618 use Ecto.Repo, default_dynamic_repo: :name_of_repo 619 620 Or you can change it anytime at runtime by calling `put_dynamic_repo/1`: 621 622 MyApp.Repo.put_dynamic_repo(:tenant_foo) 623 624 From this moment on, all future queries done by the current process will 625 run on `:tenant_foo`. 626 """ 627 @doc group: "Runtime API" 628 @callback put_dynamic_repo(name_or_pid :: atom() | pid()) :: atom() | pid() 629 630 ## Ecto.Adapter.Queryable 631 632 @optional_callbacks get: 3, get!: 3, get_by: 3, get_by!: 3, reload: 2, reload!: 2, aggregate: 3, 633 aggregate: 4, exists?: 2, one: 2, one!: 2, preload: 3, all: 2, stream: 2, 634 update_all: 3, delete_all: 2 635 636 @doc """ 637 Fetches a single struct from the data store where the primary key matches the 638 given id. 639 640 Returns `nil` if no result was found. If the struct in the queryable 641 has no or more than one primary key, it will raise an argument error. 642 643 ## Options 644 645 * `:prefix` - The prefix to run the query on (such as the schema path 646 in Postgres or the database in MySQL). This will be applied to all `from` 647 and `join`s in the query that did not have a prefix previously given 648 either via the `:prefix` option on `join`/`from` or via `@schema_prefix` 649 in the schema. For more information see the "Query Prefix" section of the 650 `Ecto.Query` documentation. 651 652 See the ["Shared options"](#module-shared-options) section at the module 653 documentation for more options. 654 655 ## Example 656 657 MyRepo.get(Post, 42) 658 659 MyRepo.get(Post, 42, prefix: "public") 660 661 """ 662 @doc group: "Query API" 663 @callback get(queryable :: Ecto.Queryable.t(), id :: term, opts :: Keyword.t()) :: 664 Ecto.Schema.t() | term | nil 665 666 @doc """ 667 Similar to `c:get/3` but raises `Ecto.NoResultsError` if no record was found. 668 669 ## Options 670 671 * `:prefix` - The prefix to run the query on (such as the schema path 672 in Postgres or the database in MySQL). This will be applied to all `from` 673 and `join`s in the query that did not have a prefix previously given 674 either via the `:prefix` option on `join`/`from` or via `@schema_prefix` 675 in the schema. For more information see the "Query Prefix" section of the 676 `Ecto.Query` documentation. 677 678 See the ["Shared options"](#module-shared-options) section at the module 679 documentation for more options. 680 681 ## Example 682 683 MyRepo.get!(Post, 42) 684 685 MyRepo.get!(Post, 42, prefix: "public") 686 687 """ 688 @doc group: "Query API" 689 @callback get!(queryable :: Ecto.Queryable.t(), id :: term, opts :: Keyword.t()) :: 690 Ecto.Schema.t() | term 691 692 @doc """ 693 Fetches a single result from the query. 694 695 Returns `nil` if no result was found. Raises if more than one entry. 696 697 ## Options 698 699 * `:prefix` - The prefix to run the query on (such as the schema path 700 in Postgres or the database in MySQL). This will be applied to all `from` 701 and `join`s in the query that did not have a prefix previously given 702 either via the `:prefix` option on `join`/`from` or via `@schema_prefix` 703 in the schema. For more information see the "Query Prefix" section of the 704 `Ecto.Query` documentation. 705 706 See the ["Shared options"](#module-shared-options) section at the module 707 documentation for more options. 708 709 ## Example 710 711 MyRepo.get_by(Post, title: "My post") 712 713 MyRepo.get_by(Post, [title: "My post"], prefix: "public") 714 715 """ 716 @doc group: "Query API" 717 @callback get_by( 718 queryable :: Ecto.Queryable.t(), 719 clauses :: Keyword.t() | map, 720 opts :: Keyword.t() 721 ) :: Ecto.Schema.t() | term | nil 722 723 @doc """ 724 Similar to `c:get_by/3` but raises `Ecto.NoResultsError` if no record was found. 725 726 Raises if more than one entry. 727 728 ## Options 729 730 * `:prefix` - The prefix to run the query on (such as the schema path 731 in Postgres or the database in MySQL). This will be applied to all `from` 732 and `join`s in the query that did not have a prefix previously given 733 either via the `:prefix` option on `join`/`from` or via `@schema_prefix` 734 in the schema. For more information see the "Query Prefix" section of the 735 `Ecto.Query` documentation. 736 737 See the ["Shared options"](#module-shared-options) section at the module 738 documentation for more options. 739 740 ## Example 741 742 MyRepo.get_by!(Post, title: "My post") 743 744 MyRepo.get_by!(Post, [title: "My post"], prefix: "public") 745 746 """ 747 @doc group: "Query API" 748 @callback get_by!( 749 queryable :: Ecto.Queryable.t(), 750 clauses :: Keyword.t() | map, 751 opts :: Keyword.t() 752 ) :: Ecto.Schema.t() | term 753 754 @doc """ 755 Reloads a given schema or schema list from the database. 756 757 When using with lists, it is expected that all of the structs in the list belong 758 to the same schema. Ordering is guaranteed to be kept. Results not found in 759 the database will be returned as `nil`. 760 761 ## Example 762 763 MyRepo.reload(post) 764 %Post{} 765 766 MyRepo.reload([post1, post2]) 767 [%Post{}, %Post{}] 768 769 MyRepo.reload([deleted_post, post1]) 770 [nil, %Post{}] 771 """ 772 @doc group: "Schema API" 773 @callback reload( 774 struct_or_structs :: Ecto.Schema.t() | [Ecto.Schema.t()], 775 opts :: Keyword.t() 776 ) :: Ecto.Schema.t() | [Ecto.Schema.t() | nil] | nil 777 778 @doc """ 779 Similar to `c:reload/2`, but raises when something is not found. 780 781 When using with lists, ordering is guaranteed to be kept. 782 783 ## Example 784 785 MyRepo.reload!(post) 786 %Post{} 787 788 MyRepo.reload!([post1, post2]) 789 [%Post{}, %Post{}] 790 """ 791 @doc group: "Schema API" 792 @callback reload!(struct_or_structs, opts :: Keyword.t()) :: struct_or_structs 793 when struct_or_structs: Ecto.Schema.t() | [Ecto.Schema.t()] 794 795 @doc """ 796 Calculate the given `aggregate`. 797 798 If the query has a limit, offset, distinct or combination set, it will be 799 automatically wrapped in a subquery in order to return the 800 proper result. 801 802 Any preload or select in the query will be ignored in favor of 803 the column being aggregated. 804 805 The aggregation will fail if any `group_by` field is set. 806 807 ## Options 808 809 * `:prefix` - The prefix to run the query on (such as the schema path 810 in Postgres or the database in MySQL). This will be applied to all `from` 811 and `join`s in the query that did not have a prefix previously given 812 either via the `:prefix` option on `join`/`from` or via `@schema_prefix` 813 in the schema. For more information see the "Query Prefix" section of the 814 `Ecto.Query` documentation. 815 816 See the ["Shared options"](#module-shared-options) section at the module 817 documentation for more options. 818 819 ## Examples 820 821 # Returns the number of blog posts 822 Repo.aggregate(Post, :count) 823 824 # Returns the number of blog posts in the "private" schema path 825 # (in Postgres) or database (in MySQL) 826 Repo.aggregate(Post, :count, prefix: "private") 827 828 """ 829 @doc group: "Query API" 830 @callback aggregate( 831 queryable :: Ecto.Queryable.t(), 832 aggregate :: :count, 833 opts :: Keyword.t() 834 ) :: term | nil 835 836 @doc """ 837 Calculate the given `aggregate` over the given `field`. 838 839 See `c:aggregate/3` for general considerations and options. 840 841 ## Examples 842 843 # Returns the number of visits per blog post 844 Repo.aggregate(Post, :count, :visits) 845 846 # Returns the number of visits per blog post in the "private" schema path 847 # (in Postgres) or database (in MySQL) 848 Repo.aggregate(Post, :count, :visits, prefix: "private") 849 850 # Returns the average number of visits for the top 10 851 query = from Post, limit: 10 852 Repo.aggregate(query, :avg, :visits) 853 """ 854 @doc group: "Query API" 855 @callback aggregate( 856 queryable :: Ecto.Queryable.t(), 857 aggregate :: :avg | :count | :max | :min | :sum, 858 field :: atom, 859 opts :: Keyword.t() 860 ) :: term | nil 861 862 @doc """ 863 Checks if there exists an entry that matches the given query. 864 865 Returns a boolean. 866 867 ## Options 868 869 * `:prefix` - The prefix to run the query on (such as the schema path 870 in Postgres or the database in MySQL). This will be applied to all `from` 871 and `join`s in the query that did not have a prefix previously given 872 either via the `:prefix` option on `join`/`from` or via `@schema_prefix` 873 in the schema. For more information see the "Query Prefix" section of the 874 `Ecto.Query` documentation. 875 876 See the ["Shared options"](#module-shared-options) section at the module 877 documentation for more options. 878 879 ## Examples 880 881 # checks if any posts exist 882 Repo.exists?(Post) 883 884 # checks if any posts exist in the "private" schema path (in Postgres) or 885 # database (in MySQL) 886 Repo.exists?(Post, schema: "private") 887 888 # checks if any post with a like count greater than 10 exists 889 query = from p in Post, where: p.like_count > 10 890 Repo.exists?(query) 891 """ 892 @doc group: "Query API" 893 @callback exists?(queryable :: Ecto.Queryable.t(), opts :: Keyword.t()) :: boolean() 894 895 @doc """ 896 Fetches a single result from the query. 897 898 Returns `nil` if no result was found. Raises if more than one entry. 899 900 ## Options 901 902 * `:prefix` - The prefix to run the query on (such as the schema path 903 in Postgres or the database in MySQL). This will be applied to all `from` 904 and `join`s in the query that did not have a prefix previously given 905 either via the `:prefix` option on `join`/`from` or via `@schema_prefix` 906 in the schema. For more information see the "Query Prefix" section of the 907 `Ecto.Query` documentation. 908 909 See the ["Shared options"](#module-shared-options) section at the module 910 documentation for more options. 911 912 ## Examples 913 914 Repo.one(from p in Post, join: c in assoc(p, :comments), where: p.id == ^post_id) 915 916 query = from p in Post, join: c in assoc(p, :comments), where: p.id == ^post_id 917 Repo.one(query, prefix: "private") 918 """ 919 @doc group: "Query API" 920 @callback one(queryable :: Ecto.Queryable.t(), opts :: Keyword.t()) :: 921 Ecto.Schema.t() | term | nil 922 923 @doc """ 924 Similar to `c:one/2` but raises `Ecto.NoResultsError` if no record was found. 925 926 Raises if more than one entry. 927 928 ## Options 929 930 * `:prefix` - The prefix to run the query on (such as the schema path 931 in Postgres or the database in MySQL). This will be applied to all `from` 932 and `join`s in the query that did not have a prefix previously given 933 either via the `:prefix` option on `join`/`from` or via `@schema_prefix` 934 in the schema. For more information see the "Query Prefix" section of the 935 `Ecto.Query` documentation. 936 937 See the ["Shared options"](#module-shared-options) section at the module 938 documentation for more options. 939 """ 940 @doc group: "Query API" 941 @callback one!(queryable :: Ecto.Queryable.t(), opts :: Keyword.t()) :: 942 Ecto.Schema.t() | term 943 944 @doc """ 945 Preloads all associations on the given struct or structs. 946 947 This is similar to `Ecto.Query.preload/3` except it allows 948 you to preload structs after they have been fetched from the 949 database. 950 951 In case the association was already loaded, preload won't attempt 952 to reload it. 953 954 ## Options 955 956 * `:force` - By default, Ecto won't preload associations that 957 are already loaded. By setting this option to true, any existing 958 association will be discarded and reloaded. 959 * `:in_parallel` - If the preloads must be done in parallel. It can 960 only be performed when we have more than one preload and the 961 repository is not in a transaction. Defaults to `true`. 962 * `:prefix` - the prefix to fetch preloads from. By default, queries 963 will use the same prefix as the first struct in the given collection. 964 This option allows the prefix to be changed. 965 966 See the ["Shared options"](#module-shared-options) section at the module 967 documentation for more options. 968 969 ## Examples 970 971 # Use a single atom to preload an association 972 posts = Repo.preload posts, :comments 973 974 # Use a list of atoms to preload multiple associations 975 posts = Repo.preload posts, [:comments, :authors] 976 977 # Use a keyword list to preload nested associations as well 978 posts = Repo.preload posts, [comments: [:replies, :likes], authors: []] 979 980 # You can mix atoms and keywords, but the atoms must come first 981 posts = Repo.preload posts, [:authors, comments: [:likes, replies: [:reactions]]] 982 983 # Use a keyword list to customize how associations are queried 984 posts = Repo.preload posts, [comments: from(c in Comment, order_by: c.published_at)] 985 986 # Use a two-element tuple for a custom query and nested association definition 987 query = from c in Comment, order_by: c.published_at 988 posts = Repo.preload posts, [comments: {query, [:replies, :likes]}] 989 990 The query given to preload may also preload its own associations. 991 """ 992 @doc group: "Schema API" 993 @callback preload(structs_or_struct_or_nil, preloads :: term, opts :: Keyword.t()) :: 994 structs_or_struct_or_nil 995 when structs_or_struct_or_nil: [Ecto.Schema.t()] | Ecto.Schema.t() | nil 996 997 @doc """ 998 A user customizable callback invoked for query-based operations. 999 1000 This callback can be used to further modify the query and options 1001 before it is transformed and sent to the database. 1002 1003 This callback is invoked for all query APIs, including the `stream` 1004 functions. It is also invoked for `insert_all` if a source query is 1005 given. It is not invoked for any of the other schema functions. 1006 1007 ## Examples 1008 1009 Let's say you want to filter out records that were "soft-deleted" 1010 (have `deleted_at` column set) from all operations unless an admin 1011 is running the query; you can define the callback like this: 1012 1013 @impl true 1014 def prepare_query(_operation, query, opts) do 1015 if opts[:admin] do 1016 {query, opts} 1017 else 1018 query = from(x in query, where: is_nil(x.deleted_at)) 1019 {query, opts} 1020 end 1021 end 1022 1023 And then execute the query: 1024 1025 Repo.all(query) # only non-deleted records are returned 1026 Repo.all(query, admin: true) # all records are returned 1027 1028 The callback will be invoked for all queries, including queries 1029 made from associations and preloads. It is not invoked for each 1030 individual join inside a query. 1031 """ 1032 @doc group: "User callbacks" 1033 @callback prepare_query(operation, query :: Ecto.Query.t(), opts :: Keyword.t()) :: 1034 {Ecto.Query.t(), Keyword.t()} 1035 when operation: :all | :update_all | :delete_all | :stream | :insert_all 1036 1037 @doc """ 1038 A user customizable callback invoked to retrieve default options 1039 for operations. 1040 1041 This can be used to provide default values per operation that 1042 have higher precedence than the values given on configuration 1043 or when starting the repository. It can also be used to set 1044 query specific options, such as `:prefix`. 1045 1046 This callback is invoked as the entry point for all repository 1047 operations. For example, if you are executing a query with preloads, 1048 this callback will be invoked once at the beginning, but the 1049 options returned here will be passed to all following operations. 1050 """ 1051 @doc group: "User callbacks" 1052 @callback default_options(operation) :: Keyword.t() 1053 when operation: :all | :insert_all | :update_all | :delete_all | :stream | 1054 :transaction | :insert | :update | :delete | :insert_or_update 1055 1056 @doc """ 1057 Fetches all entries from the data store matching the given query. 1058 1059 May raise `Ecto.QueryError` if query validation fails. 1060 1061 ## Options 1062 1063 * `:prefix` - The prefix to run the query on (such as the schema path 1064 in Postgres or the database in MySQL). This will be applied to all `from` 1065 and `join`s in the query that did not have a prefix previously given 1066 either via the `:prefix` option on `join`/`from` or via `@schema_prefix` 1067 in the schema. For more information see the "Query Prefix" section of the 1068 `Ecto.Query` documentation. 1069 1070 See the ["Shared options"](#module-shared-options) section at the module 1071 documentation for more options. 1072 1073 ## Example 1074 1075 # Fetch all post titles 1076 query = from p in Post, 1077 select: p.title 1078 MyRepo.all(query) 1079 """ 1080 @doc group: "Query API" 1081 @callback all(queryable :: Ecto.Queryable.t(), opts :: Keyword.t()) :: [Ecto.Schema.t() | term] 1082 1083 @doc """ 1084 Returns a lazy enumerable that emits all entries from the data store 1085 matching the given query. 1086 1087 SQL adapters, such as Postgres and MySQL, can only enumerate a stream 1088 inside a transaction. 1089 1090 May raise `Ecto.QueryError` if query validation fails. 1091 1092 ## Options 1093 1094 * `:prefix` - The prefix to run the query on (such as the schema path 1095 in Postgres or the database in MySQL). This will be applied to all `from` 1096 and `join`s in the query that did not have a prefix previously given 1097 either via the `:prefix` option on `join`/`from` or via `@schema_prefix` 1098 in the schema. For more information see the "Query Prefix" section of the 1099 `Ecto.Query` documentation. 1100 1101 * `:max_rows` - The number of rows to load from the database as we stream. 1102 It is supported at least by Postgres and MySQL and defaults to 500. 1103 1104 See the ["Shared options"](#module-shared-options) section at the module 1105 documentation for more options. 1106 1107 ## Example 1108 1109 # Fetch all post titles 1110 query = from p in Post, 1111 select: p.title 1112 stream = MyRepo.stream(query) 1113 MyRepo.transaction(fn -> 1114 Enum.to_list(stream) 1115 end) 1116 """ 1117 @doc group: "Query API" 1118 @callback stream(queryable :: Ecto.Queryable.t(), opts :: Keyword.t()) :: Enum.t() 1119 1120 @doc """ 1121 Updates all entries matching the given query with the given values. 1122 1123 It returns a tuple containing the number of entries and any returned 1124 result as second element. The second element is `nil` by default 1125 unless a `select` is supplied in the update query. Note, however, 1126 not all databases support returning data from UPDATEs. 1127 1128 Keep in mind this `update_all` will not update autogenerated 1129 fields like the `updated_at` columns. 1130 1131 See `Ecto.Query.update/3` for update operations that can be 1132 performed on fields. 1133 1134 ## Options 1135 1136 * `:prefix` - The prefix to run the query on (such as the schema path 1137 in Postgres or the database in MySQL). This overrides the prefix set 1138 in the query and any `@schema_prefix` set in the schema. 1139 1140 See the ["Shared options"](#module-shared-options) section at the module 1141 documentation for remaining options. 1142 1143 ## Examples 1144 1145 MyRepo.update_all(Post, set: [title: "New title"]) 1146 1147 MyRepo.update_all(Post, inc: [visits: 1]) 1148 1149 from(p in Post, where: p.id < 10, select: p.visits) 1150 |> MyRepo.update_all(set: [title: "New title"]) 1151 1152 from(p in Post, where: p.id < 10, update: [set: [title: "New title"]]) 1153 |> MyRepo.update_all([]) 1154 1155 from(p in Post, where: p.id < 10, update: [set: [title: ^new_title]]) 1156 |> MyRepo.update_all([]) 1157 1158 from(p in Post, where: p.id < 10, update: [set: [title: fragment("upper(?)", ^new_title)]]) 1159 |> MyRepo.update_all([]) 1160 1161 from(p in Post, where: p.id < 10, update: [set: [visits: p.visits * 1000]]) 1162 |> MyRepo.update_all([]) 1163 1164 """ 1165 @doc group: "Query API" 1166 @callback update_all( 1167 queryable :: Ecto.Queryable.t(), 1168 updates :: Keyword.t(), 1169 opts :: Keyword.t() 1170 ) :: {non_neg_integer, nil | [term]} 1171 1172 @doc """ 1173 Deletes all entries matching the given query. 1174 1175 It returns a tuple containing the number of entries and any returned 1176 result as second element. The second element is `nil` by default 1177 unless a `select` is supplied in the delete query. Note, however, 1178 not all databases support returning data from DELETEs. 1179 1180 ## Options 1181 1182 * `:prefix` - The prefix to run the query on (such as the schema path 1183 in Postgres or the database in MySQL). This overrides the prefix set 1184 in the query and any `@schema_prefix` set in the schema. 1185 1186 See the ["Shared options"](#module-shared-options) section at the module 1187 documentation for remaining options. 1188 1189 ## Examples 1190 1191 MyRepo.delete_all(Post) 1192 1193 from(p in Post, where: p.id < 10) |> MyRepo.delete_all 1194 """ 1195 @doc group: "Query API" 1196 @callback delete_all(queryable :: Ecto.Queryable.t(), opts :: Keyword.t()) :: 1197 {non_neg_integer, nil | [term]} 1198 1199 ## Ecto.Adapter.Schema 1200 1201 @optional_callbacks insert_all: 3, insert: 2, insert!: 2, update: 2, update!: 2, 1202 delete: 2, delete!: 2, insert_or_update: 2, insert_or_update!: 2, 1203 prepare_query: 3 1204 1205 @doc """ 1206 Inserts all entries into the repository. 1207 1208 It expects a schema module (`MyApp.User`) or a source (`"users"`) or 1209 both (`{"users", MyApp.User}`) as the first argument. The second 1210 argument is a list of entries to be inserted, either as keyword 1211 lists or as maps. The keys of the entries are the field names as 1212 atoms and the value should be the respective value for the field 1213 type or, optionally, an `Ecto.Query` that returns a single entry 1214 with a single value. 1215 1216 It returns a tuple containing the number of entries 1217 and any returned result as second element. If the database 1218 does not support RETURNING in INSERT statements or no 1219 return result was selected, the second element will be `nil`. 1220 1221 When a schema module is given, the entries given will be properly dumped 1222 before being sent to the database. If the schema primary key has type 1223 `:id` or `:binary_id`, it will be handled either at the adapter 1224 or the storage layer. However any other primary key type or autogenerated 1225 value, like `Ecto.UUID` and timestamps, won't be autogenerated when 1226 using `c:insert_all/3`. You must set those fields explicitly. This is by 1227 design as this function aims to be a more direct way to insert data into 1228 the database without the conveniences of `c:insert/2`. This is also 1229 consistent with `c:update_all/3` that does not handle auto generated 1230 values as well. 1231 1232 It is also not possible to use `insert_all` to insert across multiple 1233 tables, therefore associations are not supported. 1234 1235 If a source is given, without a schema module, the given fields are passed 1236 as is to the adapter. 1237 1238 ## Options 1239 1240 * `:returning` - selects which fields to return. When `true`, 1241 returns all fields in the given schema. May be a list of 1242 fields, where a struct is still returned but only with the 1243 given fields. Or `false`, where nothing is returned (the default). 1244 This option is not supported by all databases. 1245 1246 * `:prefix` - The prefix to run the query on (such as the schema path 1247 in Postgres or the database in MySQL). This overrides the prefix set 1248 in the query and any `@schema_prefix` set in the schema. 1249 1250 * `:on_conflict` - It may be one of `:raise` (the default), `:nothing`, 1251 `:replace_all`, `{:replace_all_except, fields}`, `{:replace, fields}`, 1252 a keyword list of update instructions or an `Ecto.Query` 1253 query for updates. See the "Upserts" section for more information. 1254 1255 * `:conflict_target` - A list of column names to verify for conflicts. 1256 It is expected those columns to have unique indexes on them that may conflict. 1257 If none is specified, the conflict target is left up to the database. 1258 It may also be `{:unsafe_fragment, binary_fragment}` to pass any 1259 expression to the database without any sanitization, this is useful 1260 for partial index or index with expressions, such as 1261 `{:unsafe_fragment, "(coalesce(firstname, ""), coalesce(lastname, "")) WHERE middlename IS NULL"}` for 1262 `ON CONFLICT (coalesce(firstname, ""), coalesce(lastname, "")) WHERE middlename IS NULL` SQL query. 1263 1264 * `:placeholders` - A map with placeholders. This feature is not supported 1265 by all databases. See the "Placeholders" section for more information. 1266 1267 See the ["Shared options"](#module-shared-options) section at the module 1268 documentation for remaining options. 1269 1270 ## Source query 1271 1272 A query can be given instead of a list with entries. This query needs to select 1273 into a map containing only keys that are available as writeable columns in the 1274 schema. 1275 1276 ## Examples 1277 1278 MyRepo.insert_all(Post, [[title: "My first post"], [title: "My second post"]]) 1279 1280 MyRepo.insert_all(Post, [%{title: "My first post"}, %{title: "My second post"}]) 1281 1282 query = from p in Post, 1283 join: c in assoc(p, :comments), 1284 select: %{ 1285 author_id: p.author_id, 1286 posts: count(p.id, :distinct), 1287 interactions: sum(p.likes) + count(c.id) 1288 }, 1289 group_by: p.author_id 1290 MyRepo.insert_all(AuthorStats, query) 1291 1292 ## Upserts 1293 1294 `c:insert_all/3` provides upserts (update or inserts) via the `:on_conflict` 1295 option. The `:on_conflict` option supports the following values: 1296 1297 * `:raise` - raises if there is a conflicting primary key or unique index 1298 1299 * `:nothing` - ignores the error in case of conflicts 1300 1301 * `:replace_all` - replace **all** values on the existing row with the values 1302 in the schema/changeset, including fields not explicitly set in the changeset, 1303 such as IDs and autogenerated timestamps (`inserted_at` and `updated_at`). 1304 Do not use this option if you have auto-incrementing primary keys, as they 1305 will also be replaced. You most likely want to use `{:replace_all_except, [:id]}` 1306 or `{:replace, fields}` explicitly instead. This option requires a schema 1307 1308 * `{:replace_all_except, fields}` - same as above except the given fields 1309 are not replaced. This option requires a schema 1310 1311 * `{:replace, fields}` - replace only specific columns. This option requires 1312 `:conflict_target` 1313 1314 * a keyword list of update instructions - such as the one given to 1315 `c:update_all/3`, for example: `[set: [title: "new title"]]` 1316 1317 * an `Ecto.Query` that will act as an `UPDATE` statement, such as the 1318 one given to `c:update_all/3` 1319 1320 Upserts map to "ON CONFLICT" on databases like Postgres and "ON DUPLICATE KEY" 1321 on databases such as MySQL. 1322 1323 ## Return values 1324 1325 By default, both Postgres and MySQL will return the number of entries 1326 inserted on `c:insert_all/3`. However, when the `:on_conflict` option 1327 is specified, Postgres and MySQL will return different results. 1328 1329 Postgres will only count a row if it was affected and will 1330 return 0 if no new entry was added. 1331 1332 MySQL will return, at a minimum, the number of entries attempted. For example, 1333 if `:on_conflict` is set to `:nothing`, MySQL will return 1334 the number of entries attempted to be inserted, even when no entry 1335 was added. 1336 1337 Also note that if `:on_conflict` is a query, MySQL will return 1338 the number of attempted entries plus the number of entries modified 1339 by the UPDATE query. 1340 1341 ## Placeholders 1342 1343 Passing in a map for the `:placeholders` allows you to send less 1344 data over the wire when you have many entries with the same value 1345 for a field. To use a placeholder, replace its value in each of your 1346 entries with `{:placeholder, key}`, where `key` is the key you 1347 are using in the `:placeholders` option map. For example: 1348 1349 placeholders = %{blob: large_blob_of_text(...)} 1350 1351 entries = [ 1352 %{title: "v1", body: {:placeholder, :blob}}, 1353 %{title: "v2", body: {:placeholder, :blob}} 1354 ] 1355 1356 Repo.insert_all(Post, entries, placeholders: placeholders) 1357 1358 Keep in mind that: 1359 1360 * placeholders cannot be nested in other values. For example, you 1361 cannot put a placeholder inside an array. Instead, the whole 1362 array has to be the placeholder 1363 1364 * a placeholder key can only be used with columns of the same type 1365 1366 * placeholders require a database that supports index parameters, 1367 so they are not currently compatible with MySQL 1368 1369 """ 1370 @doc group: "Schema API" 1371 @callback insert_all( 1372 schema_or_source :: binary | {binary, module} | module, 1373 entries_or_query :: [%{atom => value} | Keyword.t(value)] | Ecto.Query.t, 1374 opts :: Keyword.t() 1375 ) :: {non_neg_integer, nil | [term]} when value: term | Ecto.Query.t() 1376 1377 @doc """ 1378 Inserts a struct defined via `Ecto.Schema` or a changeset. 1379 1380 In case a struct is given, the struct is converted into a changeset 1381 with all non-nil fields as part of the changeset. 1382 1383 In case a changeset is given, the changes in the changeset are 1384 merged with the struct fields, and all of them are sent to the 1385 database. If more than one database operation is required, they're 1386 automatically wrapped in a transaction. 1387 1388 It returns `{:ok, struct}` if the struct has been successfully 1389 inserted or `{:error, changeset}` if there was a validation 1390 or a known constraint error. 1391 1392 ## Options 1393 1394 * `:returning` - selects which fields to return. It accepts a list 1395 of fields to be returned from the database. When `true`, returns 1396 all fields. When `false`, no extra fields are returned. It will 1397 always include all fields in `read_after_writes` as well as any 1398 autogenerated id. Not all databases support this option and it 1399 may not be available during upserts. See the "Upserts" section 1400 for more information. 1401 1402 * `:prefix` - The prefix to run the query on (such as the schema path 1403 in Postgres or the database in MySQL). This overrides the prefix set 1404 in the query and any `@schema_prefix` set any schemas. Also, the 1405 `@schema_prefix` for the parent record will override all default 1406 `@schema_prefix`s set in any child schemas for associations. 1407 1408 * `:on_conflict` - It may be one of `:raise` (the default), `:nothing`, 1409 `:replace_all`, `{:replace_all_except, fields}`, `{:replace, fields}`, 1410 a keyword list of update instructions or an `Ecto.Query` query for updates. 1411 See the "Upserts" section for more information. 1412 1413 * `:conflict_target` - A list of column names to verify for conflicts. 1414 It is expected those columns to have unique indexes on them that may conflict. 1415 If none is specified, the conflict target is left up to the database. 1416 It may also be `{:unsafe_fragment, binary_fragment}` to pass any 1417 expression to the database without any sanitization, this is useful 1418 for partial index or index with expressions, such as 1419 `{:unsafe_fragment, "(coalesce(firstname, ""), coalesce(lastname, "")) WHERE middlename IS NULL"}` for 1420 `ON CONFLICT (coalesce(firstname, ""), coalesce(lastname, "")) WHERE middlename IS NULL` SQL query. 1421 1422 * `:stale_error_field` - The field where stale errors will be added in 1423 the returning changeset. This option can be used to avoid raising 1424 `Ecto.StaleEntryError`. 1425 1426 * `:stale_error_message` - The message to add to the configured 1427 `:stale_error_field` when stale errors happen, defaults to "is stale". 1428 1429 See the ["Shared options"](#module-shared-options) section at the module 1430 documentation for more options. 1431 1432 ## Examples 1433 1434 A typical example is calling `MyRepo.insert/1` with a struct 1435 and acting on the return value: 1436 1437 case MyRepo.insert %Post{title: "Ecto is great"} do 1438 {:ok, struct} -> # Inserted with success 1439 {:error, changeset} -> # Something went wrong 1440 end 1441 1442 ## Upserts 1443 1444 `c:insert/2` provides upserts (update or inserts) via the `:on_conflict` 1445 option. The `:on_conflict` option supports the following values: 1446 1447 * `:raise` - raises if there is a conflicting primary key or unique index 1448 1449 * `:nothing` - ignores the error in case of conflicts 1450 1451 * `:replace_all` - replace **all** values on the existing row with the values 1452 in the schema/changeset, including fields not explicitly set in the changeset, 1453 such as IDs and autogenerated timestamps (`inserted_at` and `updated_at`). 1454 Do not use this option if you have auto-incrementing primary keys, as they 1455 will also be replaced. You most likely want to use `{:replace_all_except, [:id]}` 1456 or `{:replace, fields}` explicitly instead. This option requires a schema 1457 1458 * `{:replace_all_except, fields}` - same as above except the given fields are 1459 not replaced. This option requires a schema 1460 1461 * `{:replace, fields}` - replace only specific columns. This option requires 1462 `:conflict_target` 1463 1464 * a keyword list of update instructions - such as the one given to 1465 `c:update_all/3`, for example: `[set: [title: "new title"]]` 1466 1467 * an `Ecto.Query` that will act as an `UPDATE` statement, such as the 1468 one given to `c:update_all/3`. Similarly to `c:update_all/3`, auto 1469 generated values, such as timestamps are not automatically updated. 1470 If the struct cannot be found, `Ecto.StaleEntryError` will be raised. 1471 1472 Upserts map to "ON CONFLICT" on databases like Postgres and "ON DUPLICATE KEY" 1473 on databases such as MySQL. 1474 1475 As an example, imagine `:title` is marked as a unique column in 1476 the database: 1477 1478 {:ok, inserted} = MyRepo.insert(%Post{title: "this is unique"}) 1479 1480 Now we can insert with the same title but do nothing on conflicts: 1481 1482 {:ok, ignored} = MyRepo.insert(%Post{title: "this is unique"}, on_conflict: :nothing) 1483 1484 Because we used `on_conflict: :nothing`, instead of getting an error, 1485 we got `{:ok, struct}`. However the returned struct does not reflect 1486 the data in the database. If the primary key is auto-generated by the 1487 database, the primary key in the `ignored` record will be nil if there 1488 was no insertion. For example, if you use the default primary key 1489 (which has name `:id` and a type of `:id`), then `ignored.id` above 1490 will be nil if there was no insertion. 1491 1492 If your id is generated by your application (typically the case for 1493 `:binary_id`) or if you pass another value for `:on_conflict`, detecting 1494 if an insert or update happened is slightly more complex, as the database 1495 does not actually inform us what happened. Let's insert a post with the 1496 same title but use a query to update the body column in case of conflicts: 1497 1498 # In Postgres (it requires the conflict target for updates): 1499 on_conflict = [set: [body: "updated"]] 1500 {:ok, updated} = MyRepo.insert(%Post{title: "this is unique"}, 1501 on_conflict: on_conflict, conflict_target: :title) 1502 1503 # In MySQL (conflict target is not supported): 1504 on_conflict = [set: [title: "updated"]] 1505 {:ok, updated} = MyRepo.insert(%Post{id: inserted.id, title: "updated"}, 1506 on_conflict: on_conflict) 1507 1508 In the examples above, even though it returned `:ok`, we do not know 1509 if we inserted new data or if we updated only the `:on_conflict` fields. 1510 In case an update happened, the data in the struct most likely does 1511 not match the data in the database. For example, autogenerated fields 1512 such as `inserted_at` will point to now rather than the time the 1513 struct was actually inserted. 1514 1515 If you need to guarantee the data in the returned struct mirrors the 1516 database, you have three options: 1517 1518 * Use `on_conflict: :replace_all`, although that will replace all 1519 fields in the database with the ones in the struct/changeset, 1520 including autogenerated fields such as `inserted_at` and `updated_at`: 1521 1522 MyRepo.insert(%Post{title: "this is unique"}, 1523 on_conflict: :replace_all, conflict_target: :title) 1524 1525 * Specify `read_after_writes: true` in your schema for choosing 1526 fields that are read from the database after every operation. 1527 Or pass `returning: true` to `insert` to read all fields back: 1528 1529 MyRepo.insert(%Post{title: "this is unique"}, returning: true, 1530 on_conflict: on_conflict, conflict_target: :title) 1531 1532 * Alternatively, read the data again from the database in a separate 1533 query. This option requires the primary key to be generated by the 1534 database: 1535 1536 {:ok, updated} = MyRepo.insert(%Post{title: "this is unique"}, on_conflict: on_conflict) 1537 Repo.get(Post, updated.id) 1538 1539 Because of the inability to know if the struct is up to date or not, 1540 inserting a struct with associations and using the `:on_conflict` option 1541 at the same time is not recommended, as Ecto will be unable to actually 1542 track the proper status of the association. 1543 """ 1544 @doc group: "Schema API" 1545 @callback insert( 1546 struct_or_changeset :: Ecto.Schema.t() | Ecto.Changeset.t(), 1547 opts :: Keyword.t() 1548 ) :: {:ok, Ecto.Schema.t()} | {:error, Ecto.Changeset.t()} 1549 1550 @doc """ 1551 Updates a changeset using its primary key. 1552 1553 A changeset is required as it is the only mechanism for 1554 tracking dirty changes. Only the fields present in the `changes` part 1555 of the changeset are sent to the database. Any other, in-memory 1556 changes done to the schema are ignored. If more than one database 1557 operation is required, they're automatically wrapped in a transaction. 1558 1559 If the struct has no primary key, `Ecto.NoPrimaryKeyFieldError` 1560 will be raised. 1561 1562 If the struct cannot be found, `Ecto.StaleEntryError` will be raised. 1563 1564 It returns `{:ok, struct}` if the struct has been successfully 1565 updated or `{:error, changeset}` if there was a validation 1566 or a known constraint error. 1567 1568 ## Options 1569 1570 * `:returning` - selects which fields to return. It accepts a list 1571 of fields to be returned from the database. When `true`, returns 1572 all fields. When `false`, no extra fields are returned. It will 1573 always include all fields in `read_after_writes`. Not all 1574 databases support this option. 1575 1576 * `:force` - By default, if there are no changes in the changeset, 1577 `c:update/2` is a no-op. By setting this option to true, update 1578 callbacks will always be executed, even if there are no changes 1579 (including timestamps). 1580 1581 * `:prefix` - The prefix to run the query on (such as the schema path 1582 in Postgres or the database in MySQL). This overrides the prefix set 1583 in the query and any `@schema_prefix` set any schemas. Also, the 1584 `@schema_prefix` for the parent record will override all default 1585 `@schema_prefix`s set in any child schemas for associations. 1586 1587 * `:stale_error_field` - The field where stale errors will be added in 1588 the returning changeset. This option can be used to avoid raising 1589 `Ecto.StaleEntryError`. 1590 1591 * `:stale_error_message` - The message to add to the configured 1592 `:stale_error_field` when stale errors happen, defaults to "is stale". 1593 1594 See the ["Shared options"](#module-shared-options) section at the module 1595 documentation for more options. 1596 1597 ## Example 1598 1599 post = MyRepo.get!(Post, 42) 1600 post = Ecto.Changeset.change post, title: "New title" 1601 case MyRepo.update post do 1602 {:ok, struct} -> # Updated with success 1603 {:error, changeset} -> # Something went wrong 1604 end 1605 """ 1606 @doc group: "Schema API" 1607 @callback update(changeset :: Ecto.Changeset.t(), opts :: Keyword.t()) :: 1608 {:ok, Ecto.Schema.t()} | {:error, Ecto.Changeset.t()} 1609 1610 @doc """ 1611 Inserts or updates a changeset depending on whether the struct is persisted 1612 or not. 1613 1614 The distinction whether to insert or update will be made on the 1615 `Ecto.Schema.Metadata` field `:state`. The `:state` is automatically set by 1616 Ecto when loading or building a schema. 1617 1618 Please note that for this to work, you will have to load existing structs from 1619 the database. So even if the struct exists, this won't work: 1620 1621 struct = %Post{id: "existing_id", ...} 1622 MyRepo.insert_or_update changeset 1623 # => {:error, changeset} # id already exists 1624 1625 ## Options 1626 1627 * `:prefix` - The prefix to run the query on (such as the schema path 1628 in Postgres or the database in MySQL). This overrides the prefix set 1629 in the query and any `@schema_prefix` set any schemas. Also, the 1630 `@schema_prefix` for the parent record will override all default 1631 `@schema_prefix`s set in any child schemas for associations. 1632 * `:stale_error_field` - The field where stale errors will be added in 1633 the returning changeset. This option can be used to avoid raising 1634 `Ecto.StaleEntryError`. Only applies to updates. 1635 * `:stale_error_message` - The message to add to the configured 1636 `:stale_error_field` when stale errors happen, defaults to "is stale". 1637 Only applies to updates. 1638 1639 See the ["Shared options"](#module-shared-options) section at the module 1640 documentation for more options. 1641 1642 ## Example 1643 1644 result = 1645 case MyRepo.get(Post, id) do 1646 nil -> %Post{id: id} # Post not found, we build one 1647 post -> post # Post exists, let's use it 1648 end 1649 |> Post.changeset(changes) 1650 |> MyRepo.insert_or_update 1651 1652 case result do 1653 {:ok, struct} -> # Inserted or updated with success 1654 {:error, changeset} -> # Something went wrong 1655 end 1656 """ 1657 @doc group: "Schema API" 1658 @callback insert_or_update(changeset :: Ecto.Changeset.t(), opts :: Keyword.t()) :: 1659 {:ok, Ecto.Schema.t()} | {:error, Ecto.Changeset.t()} 1660 1661 @doc """ 1662 Deletes a struct using its primary key. 1663 1664 If the struct has no primary key, `Ecto.NoPrimaryKeyFieldError` 1665 will be raised. If the struct has been removed prior to the call, 1666 `Ecto.StaleEntryError` will be raised. If more than one database 1667 operation is required, they're automatically wrapped in a transaction. 1668 1669 It returns `{:ok, struct}` if the struct has been successfully 1670 deleted or `{:error, changeset}` if there was a validation 1671 or a known constraint error. By default, constraint errors will 1672 raise the `Ecto.ConstraintError` exception, unless a changeset is 1673 given as the first argument with the relevant constraints declared 1674 in it (see `Ecto.Changeset`). 1675 1676 ## Options 1677 1678 * `:prefix` - The prefix to run the query on (such as the schema path 1679 in Postgres or the database in MySQL). This overrides the prefix set 1680 in the query and any `@schema_prefix` set in the schema. 1681 1682 * `:stale_error_field` - The field where stale errors will be added in 1683 the returning changeset. This option can be used to avoid raising 1684 `Ecto.StaleEntryError`. 1685 1686 * `:stale_error_message` - The message to add to the configured 1687 `:stale_error_field` when stale errors happen, defaults to "is stale". 1688 1689 See the ["Shared options"](#module-shared-options) section at the module 1690 documentation for more options. 1691 1692 ## Example 1693 1694 post = MyRepo.get!(Post, 42) 1695 case MyRepo.delete post do 1696 {:ok, struct} -> # Deleted with success 1697 {:error, changeset} -> # Something went wrong 1698 end 1699 1700 """ 1701 @doc group: "Schema API" 1702 @callback delete( 1703 struct_or_changeset :: Ecto.Schema.t() | Ecto.Changeset.t(), 1704 opts :: Keyword.t() 1705 ) :: {:ok, Ecto.Schema.t()} | {:error, Ecto.Changeset.t()} 1706 1707 @doc """ 1708 Same as `c:insert/2` but returns the struct or raises if the changeset is invalid. 1709 """ 1710 @doc group: "Schema API" 1711 @callback insert!( 1712 struct_or_changeset :: Ecto.Schema.t() | Ecto.Changeset.t(), 1713 opts :: Keyword.t() 1714 ) :: Ecto.Schema.t() 1715 1716 @doc """ 1717 Same as `c:update/2` but returns the struct or raises if the changeset is invalid. 1718 """ 1719 @doc group: "Schema API" 1720 @callback update!(changeset :: Ecto.Changeset.t(), opts :: Keyword.t()) :: 1721 Ecto.Schema.t() 1722 1723 @doc """ 1724 Same as `c:insert_or_update/2` but returns the struct or raises if the changeset 1725 is invalid. 1726 """ 1727 @doc group: "Schema API" 1728 @callback insert_or_update!(changeset :: Ecto.Changeset.t(), opts :: Keyword.t()) :: 1729 Ecto.Schema.t() 1730 1731 @doc """ 1732 Same as `c:delete/2` but returns the struct or raises if the changeset is invalid. 1733 """ 1734 @doc group: "Schema API" 1735 @callback delete!( 1736 struct_or_changeset :: Ecto.Schema.t() | Ecto.Changeset.t(), 1737 opts :: Keyword.t() 1738 ) :: Ecto.Schema.t() 1739 1740 ## Ecto.Adapter.Transaction 1741 1742 @optional_callbacks transaction: 2, in_transaction?: 0, rollback: 1 1743 1744 @doc """ 1745 Runs the given function or `Ecto.Multi` inside a transaction. 1746 1747 ## Use with function 1748 1749 `c:transaction/2` can be called with both a function of arity 1750 zero or one. The arity zero function will just be executed as is: 1751 1752 import Ecto.Changeset, only: [change: 2] 1753 1754 MyRepo.transaction(fn -> 1755 MyRepo.update!(change(alice, balance: alice.balance - 10)) 1756 MyRepo.update!(change(bob, balance: bob.balance + 10)) 1757 end) 1758 1759 While the arity one function will receive the repo of the transaction 1760 as its first argument: 1761 1762 MyRepo.transaction(fn repo -> 1763 repo.insert!(%Post{}) 1764 end) 1765 1766 If an Elixir exception occurs the transaction will be rolled back 1767 and the exception will bubble up from the transaction function. 1768 If no exception occurs, the transaction is committed when the 1769 function returns. A transaction can be explicitly rolled back 1770 by calling `c:rollback/1`, this will immediately leave the function 1771 and return the value given to `rollback` as `{:error, value}`. 1772 1773 A successful transaction returns the value returned by the function 1774 wrapped in a tuple as `{:ok, value}`. 1775 1776 ### Nested transactions 1777 1778 If `c:transaction/2` is called inside another transaction, the function 1779 is simply executed, without wrapping the new transaction call in any 1780 way. If there is an error in the inner transaction and the error is 1781 rescued, or the inner transaction is rolled back, the whole outer 1782 transaction is aborted, guaranteeing nothing will be committed. 1783 1784 Below is an example of how rollbacks work with nested transactions: 1785 1786 {:error, :rollback} = 1787 MyRepo.transaction(fn -> 1788 {:error, :posting_not_allowed} = 1789 MyRepo.transaction(fn -> 1790 # This function call causes the following to happen: 1791 # 1792 # * the transaction is rolled back in the database, 1793 # * code execution is stopped within the current function, 1794 # * and the value, passed to `rollback/1` is returned from 1795 # `MyRepo.transaction/1` as the second element in the error 1796 # tuple. 1797 # 1798 MyRepo.rollback(:posting_not_allowed) 1799 1800 # `rollback/1` stops execution, so code here won't be run 1801 end) 1802 1803 # The transaction here is now aborted and any further 1804 # operation will raise an exception. 1805 end) 1806 1807 See the "Aborted transactions" section for more examples of aborted 1808 transactions and how to handle them. 1809 1810 In practice, managing nested transactions can become complex quickly. 1811 For this reason, Ecto provides `Ecto.Multi` for composing transactions. 1812 1813 ## Use with Ecto.Multi 1814 1815 `c:transaction/2` also accepts the `Ecto.Multi` struct as first argument. 1816 `Ecto.Multi` allows you to compose transactions operations, step by step, 1817 and manage what happens in case of success or failure. 1818 1819 When an `Ecto.Multi` is given to this function, a transaction will be started, 1820 all operations applied and in case of success committed returning `{:ok, changes}`: 1821 1822 # With Ecto.Multi 1823 Ecto.Multi.new() 1824 |> Ecto.Multi.insert(:post, %Post{}) 1825 |> MyRepo.transaction 1826 1827 In case of any errors the transaction will be rolled back and 1828 `{:error, failed_operation, failed_value, changes_so_far}` will be returned. 1829 1830 Explore the `Ecto.Multi` documentation to learn more and find detailed examples. 1831 1832 ## Aborted transactions 1833 1834 When an operation inside a transaction fails, the transaction is aborted in the database. 1835 For instance, if you attempt an insert that violates a unique constraint, the insert fails 1836 and the transaction is aborted. In such cases, any further operation inside the transaction 1837 will raise exceptions. 1838 1839 Take the following transaction as an example: 1840 1841 Repo.transaction(fn repo -> 1842 case repo.insert(changeset) do 1843 {:ok, post} -> 1844 repo.insert(%Status{value: "success"}) 1845 1846 {:error, changeset} -> 1847 repo.insert(%Status{value: "failure"}) 1848 end 1849 end) 1850 1851 If the changeset is valid, but the insert operation fails due to a database constraint, 1852 the subsequent `repo.insert(%Failure{})` operation will raise an exception because the 1853 database has already aborted the transaction and thus making the operation invalid. 1854 In Postgres, the exception would look like this: 1855 1856 ** (Postgrex.Error) ERROR 25P02 (in_failed_sql_transaction) current transaction is aborted, commands ignored until end of transaction block 1857 1858 If the changeset is invalid before it reaches the database due to a validation error, 1859 no statement is sent to the database, an `:error` tuple is returned, and `repo.insert(%Failure{})` 1860 operation will execute as usual. 1861 1862 We have two options to deal with such scenarios: 1863 1864 If don't want to change the semantics of your code, you can also use the savepoints 1865 feature by passing the `:mode` option like this: `repo.insert(changeset, mode: :savepoint)`. 1866 In case of an exception, the transaction will rollback to the savepoint and prevent 1867 the transaction from failing. 1868 1869 Another alternative is to handle this operation outside of the transaction. 1870 For example, you can choose to perform an explicit `repo.rollback` call in the 1871 `{:error, changeset}` clause and then perform the `repo.insert(%Failure{})` outside 1872 of the transaction. You might also consider using `Ecto.Multi`, as they automatically 1873 rollback whenever an operation fails. 1874 1875 ## Working with processes 1876 1877 The transaction is per process. A separate process started inside a 1878 transaction won't be part of the same transaction and will use a separate 1879 connection altogether. 1880 1881 When using the the `Ecto.Adapters.SQL.Sandbox` in tests, while it may be 1882 possible to share the connection between processes, the parent process 1883 will typically hold the connection until the transaction completes. This 1884 may lead to a deadlock if the child process attempts to use the same connection. 1885 See the docs for 1886 [`Ecto.Adapters.SQL.Sandbox`](https://hexdocs.pm/ecto_sql/Ecto.Adapters.SQL.Sandbox.html) 1887 for more information. 1888 1889 ## Options 1890 1891 See the ["Shared options"](#module-shared-options) section at the module 1892 documentation for more options. 1893 """ 1894 @doc group: "Transaction API" 1895 @callback transaction(fun_or_multi :: fun | Ecto.Multi.t(), opts :: Keyword.t()) :: 1896 {:ok, any} 1897 | {:error, any} 1898 | {:error, Ecto.Multi.name(), any, %{Ecto.Multi.name() => any}} 1899 1900 @doc """ 1901 Returns true if the current process is inside a transaction. 1902 1903 If you are using the `Ecto.Adapters.SQL.Sandbox` in tests, note that even 1904 though each test is inside a transaction, `in_transaction?/0` will only 1905 return true inside transactions explicitly created with `transaction/2`. This 1906 is done so the test environment mimics dev and prod. 1907 1908 ## Examples 1909 1910 MyRepo.in_transaction? 1911 #=> false 1912 1913 MyRepo.transaction(fn -> 1914 MyRepo.in_transaction? #=> true 1915 end) 1916 1917 """ 1918 @doc group: "Transaction API" 1919 @callback in_transaction?() :: boolean 1920 1921 @doc """ 1922 Rolls back the current transaction. 1923 1924 The transaction will return the value given as `{:error, value}`. 1925 1926 Note that calling `rollback` causes the code in the transaction to stop executing. 1927 """ 1928 @doc group: "Transaction API" 1929 @callback rollback(value :: any) :: no_return 1930 end