├── .credo.exs ├── .dialyzer_ignore.exs ├── .formatter.exs ├── .github ├── CODEOWNERS ├── actions │ └── elixir-setup │ │ └── action.yml ├── dependabot.yml └── workflows │ ├── elixir-build-and-test.yml │ ├── elixir-dialyzer.yml │ ├── elixir-quality-checks.yml │ └── nightly-integration-test.yml ├── .gitignore ├── .pre-commit-config.yaml ├── CHANGELOG.md ├── LICENSE.txt ├── README.md ├── config ├── config.exs ├── dev.exs ├── prod.exs └── test.exs ├── docker-compose.yml ├── lib ├── ecto_resource.ex ├── helpers.ex ├── mix │ └── tasks │ │ └── ecto_resource │ │ └── resources.ex ├── option_parser.ex ├── resource_functions.ex └── test_repo.ex ├── mix.exs ├── mix.lock ├── priv └── test_repo │ └── migrations │ └── 20200410023114_create_people.exs └── test ├── ecto_resource ├── defaults_test.exs ├── except_filter_test.exs ├── only_filter_test.exs ├── option_parser_test.exs ├── read_test.exs ├── read_write_test.exs ├── resource_functions_test.exs └── without_suffix_test.exs ├── helpers_test.exs ├── support ├── repo_case.ex └── test_schema │ └── person.ex └── test_helper.exs /.credo.exs: -------------------------------------------------------------------------------- 1 | # This file contains the configuration for Credo and you are probably reading 2 | # this after creating it with `mix credo.gen.config`. 3 | # 4 | # If you find anything wrong or unclear in this file, please report an 5 | # issue on GitHub: https://github.com/rrrene/credo/issues 6 | # 7 | %{ 8 | # 9 | # You can have as many configs as you like in the `configs:` field. 10 | configs: [ 11 | %{ 12 | # 13 | # Run any config using `mix credo -C `. If no config name is given 14 | # "default" is used. 15 | # 16 | name: "default", 17 | # 18 | # These are the files included in the analysis: 19 | files: %{ 20 | # 21 | # You can give explicit globs or simply directories. 22 | # In the latter case `**/*.{ex,exs}` will be used. 23 | # 24 | included: [ 25 | "lib/", 26 | "src/", 27 | "web/", 28 | "apps/*/lib/", 29 | "apps/*/src/", 30 | "apps/*/test/", 31 | "apps/*/web/" 32 | ], 33 | excluded: [~r"/_build/", ~r"/deps/", ~r"/node_modules/"] 34 | }, 35 | # 36 | # Load and configure plugins here: 37 | # 38 | plugins: [], 39 | # 40 | # If you create your own checks, you must specify the source files for 41 | # them here, so they can be loaded by Credo before running the analysis. 42 | # 43 | requires: [], 44 | # 45 | # If you want to enforce a style guide and need a more traditional linting 46 | # experience, you can change `strict` to `true` below: 47 | # 48 | strict: false, 49 | # 50 | # To modify the timeout for parsing files, change this value: 51 | # 52 | parse_timeout: 5000, 53 | # 54 | # If you want to use uncolored output by default, you can change `color` 55 | # to `false` below: 56 | # 57 | color: true, 58 | # 59 | # You can customize the parameters of any check by adding a second element 60 | # to the tuple. 61 | # 62 | # To disable a check put `false` as second element: 63 | # 64 | # {Credo.Check.Design.DuplicatedCode, false} 65 | # 66 | checks: %{ 67 | enabled: [ 68 | # 69 | ## Consistency Checks 70 | # 71 | {Credo.Check.Consistency.ExceptionNames, []}, 72 | {Credo.Check.Consistency.LineEndings, []}, 73 | {Credo.Check.Consistency.ParameterPatternMatching, []}, 74 | {Credo.Check.Consistency.SpaceAroundOperators, []}, 75 | {Credo.Check.Consistency.SpaceInParentheses, []}, 76 | {Credo.Check.Consistency.TabsOrSpaces, []}, 77 | 78 | # 79 | ## Design Checks 80 | # 81 | # You can customize the priority of any check 82 | # Priority values are: `low, normal, high, higher` 83 | # 84 | {Credo.Check.Design.AliasUsage, 85 | [priority: :low, if_nested_deeper_than: 2, if_called_more_often_than: 1]}, 86 | # You can also customize the exit_status of each check. 87 | # If you don't want TODO comments to cause `mix credo` to fail, just 88 | # set this value to 0 (zero). 89 | # 90 | {Credo.Check.Design.SkipTestWithoutComment, []}, 91 | {Credo.Check.Design.TagTODO, [exit_status: 2]}, 92 | {Credo.Check.Design.TagFIXME, []}, 93 | 94 | # 95 | ## Readability Checks 96 | # 97 | {Credo.Check.Readability.AliasOrder, []}, 98 | {Credo.Check.Readability.FunctionNames, []}, 99 | {Credo.Check.Readability.ImplTrue, []}, 100 | {Credo.Check.Readability.LargeNumbers, []}, 101 | {Credo.Check.Readability.MaxLineLength, [priority: :low, max_length: 120]}, 102 | {Credo.Check.Readability.ModuleAttributeNames, []}, 103 | {Credo.Check.Readability.ModuleNames, []}, 104 | {Credo.Check.Readability.NestedFunctionCalls, []}, 105 | {Credo.Check.Readability.ParenthesesInCondition, []}, 106 | {Credo.Check.Readability.ParenthesesOnZeroArityDefs, []}, 107 | {Credo.Check.Readability.PipeIntoAnonymousFunctions, []}, 108 | {Credo.Check.Readability.PredicateFunctionNames, []}, 109 | {Credo.Check.Readability.PreferImplicitTry, []}, 110 | {Credo.Check.Readability.RedundantBlankLines, []}, 111 | {Credo.Check.Readability.Semicolons, []}, 112 | {Credo.Check.Readability.SeparateAliasRequire, []}, 113 | {Credo.Check.Readability.SingleFunctionToBlockPipe, []}, 114 | {Credo.Check.Readability.SinglePipe, [allow_0_arity_functions: true]}, 115 | {Credo.Check.Readability.SpaceAfterCommas, []}, 116 | {Credo.Check.Readability.StrictModuleLayout, []}, 117 | {Credo.Check.Readability.StringSigils, []}, 118 | {Credo.Check.Readability.TrailingBlankLine, []}, 119 | {Credo.Check.Readability.TrailingWhiteSpace, []}, 120 | {Credo.Check.Readability.UnnecessaryAliasExpansion, []}, 121 | {Credo.Check.Readability.VariableNames, []}, 122 | {Credo.Check.Readability.WithCustomTaggedTuple, []}, 123 | {Credo.Check.Readability.WithSingleClause, []}, 124 | 125 | # 126 | ## Refactoring Opportunities 127 | # 128 | 129 | {Credo.Check.Refactor.AppendSingleItem, []}, 130 | {Credo.Check.Refactor.Apply, []}, 131 | {Credo.Check.Refactor.CondStatements, []}, 132 | {Credo.Check.Refactor.CyclomaticComplexity, []}, 133 | {Credo.Check.Refactor.DoubleBooleanNegation, []}, 134 | {Credo.Check.Refactor.FilterCount, []}, 135 | {Credo.Check.Refactor.FilterFilter, []}, 136 | {Credo.Check.Refactor.FilterReject, []}, 137 | {Credo.Check.Refactor.FunctionArity, []}, 138 | {Credo.Check.Refactor.IoPuts, []}, 139 | {Credo.Check.Refactor.LongQuoteBlocks, []}, 140 | {Credo.Check.Refactor.MapJoin, []}, 141 | {Credo.Check.Refactor.MapMap, []}, 142 | {Credo.Check.Refactor.MatchInCondition, []}, 143 | {Credo.Check.Refactor.NegatedConditionsInUnless, []}, 144 | {Credo.Check.Refactor.NegatedConditionsWithElse, []}, 145 | {Credo.Check.Refactor.Nesting, []}, 146 | {Credo.Check.Refactor.PipeChainStart, []}, 147 | {Credo.Check.Refactor.RedundantWithClauseResult, []}, 148 | {Credo.Check.Refactor.RejectFilter, []}, 149 | {Credo.Check.Refactor.RejectReject, []}, 150 | {Credo.Check.Refactor.UnlessWithElse, []}, 151 | {Credo.Check.Refactor.WithClauses, []}, 152 | 153 | # 154 | ## Warnings 155 | # 156 | {Credo.Check.Warning.ApplicationConfigInModuleAttribute, []}, 157 | {Credo.Check.Warning.BoolOperationOnSameValues, []}, 158 | {Credo.Check.Warning.Dbg, []}, 159 | {Credo.Check.Warning.ExpensiveEmptyEnumCheck, []}, 160 | {Credo.Check.Warning.IExPry, []}, 161 | {Credo.Check.Warning.IoInspect, []}, 162 | {Credo.Check.Warning.MapGetUnsafePass, []}, 163 | {Credo.Check.Warning.MissedMetadataKeyInLoggerConfig, []}, 164 | {Credo.Check.Warning.MixEnv, []}, 165 | {Credo.Check.Warning.OperationOnSameValues, []}, 166 | {Credo.Check.Warning.OperationWithConstantResult, []}, 167 | {Credo.Check.Warning.RaiseInsideRescue, []}, 168 | {Credo.Check.Warning.SpecWithStruct, []}, 169 | {Credo.Check.Warning.UnsafeExec, []}, 170 | {Credo.Check.Warning.UnusedEnumOperation, []}, 171 | {Credo.Check.Warning.UnusedFileOperation, []}, 172 | {Credo.Check.Warning.UnusedKeywordOperation, []}, 173 | {Credo.Check.Warning.UnusedListOperation, []}, 174 | {Credo.Check.Warning.UnusedPathOperation, []}, 175 | {Credo.Check.Warning.UnusedRegexOperation, []}, 176 | {Credo.Check.Warning.UnusedStringOperation, []}, 177 | {Credo.Check.Warning.UnusedTupleOperation, []}, 178 | {Credo.Check.Warning.WrongTestFileExtension, []} 179 | ], 180 | disabled: [ 181 | # 182 | # Checks scheduled for next check update (opt-in for now, just replace `false` with `[]`) 183 | 184 | # 185 | # Controversial and experimental checks (opt-in, just move the check to `:enabled` 186 | # and be sure to use `mix credo --strict` to see low priority checks) 187 | # 188 | {Credo.Check.Consistency.MultiAliasImportRequireUse, []}, 189 | {Credo.Check.Consistency.UnusedVariableNames, []}, 190 | {Credo.Check.Design.DuplicatedCode, []}, 191 | {Credo.Check.Readability.AliasAs, []}, 192 | {Credo.Check.Readability.BlockPipe, []}, 193 | {Credo.Check.Readability.ModuleDoc, []}, 194 | {Credo.Check.Readability.MultiAlias, []}, 195 | {Credo.Check.Readability.Specs, []}, 196 | {Credo.Check.Refactor.ABCSize, []}, 197 | {Credo.Check.Refactor.ModuleDependencies, []}, 198 | {Credo.Check.Refactor.NegatedIsNil, []}, 199 | {Credo.Check.Refactor.VariableRebinding, []}, 200 | {Credo.Check.Warning.LazyLogging, []}, 201 | {Credo.Check.Warning.LeakyEnvironment, []}, 202 | {Credo.Check.Warning.UnsafeToAtom, []}, 203 | # {Credo.Check.Refactor.MapInto, []}, 204 | 205 | # 206 | # Custom checks can be created using `mix credo.gen.check`. 207 | # 208 | ] 209 | } 210 | } 211 | ] 212 | } 213 | -------------------------------------------------------------------------------- /.dialyzer_ignore.exs: -------------------------------------------------------------------------------- 1 | [] 2 | -------------------------------------------------------------------------------- /.formatter.exs: -------------------------------------------------------------------------------- 1 | # Used by "mix format" 2 | [ 3 | inputs: ["{mix,.formatter}.exs", "{config,lib,test}/**/*.{ex,exs}"], 4 | locals_without_parens: [resource: 2] 5 | ] 6 | -------------------------------------------------------------------------------- /.github/CODEOWNERS: -------------------------------------------------------------------------------- 1 | * @joseph-lozano 2 | -------------------------------------------------------------------------------- /.github/actions/elixir-setup/action.yml: -------------------------------------------------------------------------------- 1 | name: Setup Elixir Project 2 | description: Checks out the code, configures Elixir, fetches dependencies, and manages build caching. 3 | inputs: 4 | elixir-version: 5 | required: true 6 | type: string 7 | description: Elixir version to set up 8 | otp-version: 9 | required: true 10 | type: string 11 | description: OTP version to set up 12 | ################################################################# 13 | # Everything below this line is optional. 14 | # 15 | # It's designed to make compiling a reasonably standard Elixir 16 | # codebase "just work," though there may be speed gains to be had 17 | # by tweaking these flags. 18 | ################################################################# 19 | build-deps: 20 | required: false 21 | type: boolean 22 | default: true 23 | description: True if we should compile dependencies 24 | build-app: 25 | required: false 26 | type: boolean 27 | default: true 28 | description: True if we should compile the application itself 29 | build-flags: 30 | required: false 31 | type: string 32 | default: "--all-warnings" 33 | description: Flags to pass to mix compile 34 | install-rebar: 35 | required: false 36 | type: boolean 37 | default: true 38 | description: By default, we will install Rebar (mix local.rebar --force). 39 | install-hex: 40 | required: false 41 | type: boolean 42 | default: true 43 | description: By default, we will install Hex (mix local.hex --force). 44 | cache-key: 45 | required: false 46 | type: string 47 | default: "v1" 48 | description: If you need to reset the cache for some reason, you can change this key. 49 | outputs: 50 | otp-version: 51 | description: "Exact OTP version selected by the BEAM setup step" 52 | value: ${{ steps.beam.outputs.otp-version }} 53 | elixir-version: 54 | description: "Exact Elixir version selected by the BEAM setup step" 55 | value: ${{ steps.beam.outputs.elixir-version }} 56 | runs: 57 | using: "composite" 58 | steps: 59 | - name: Setup elixir 60 | uses: erlef/setup-beam@v1 61 | id: beam 62 | with: 63 | elixir-version: ${{ inputs.elixir-version }} 64 | otp-version: ${{ inputs.otp-version }} 65 | version-type: "strict" 66 | 67 | - name: Get deps cache 68 | uses: actions/cache@v3 69 | with: 70 | path: deps/ 71 | key: deps-${{ inputs.cache-key }}-${{ runner.os }}-${{ hashFiles('**/mix.lock') }} 72 | restore-keys: | 73 | deps-${{ inputs.cache-key }}-${{ runner.os }}- 74 | - name: Get build cache 75 | uses: actions/cache@v3 76 | id: build-cache 77 | with: 78 | path: _build/${{env.MIX_ENV}}/ 79 | key: build-${{ inputs.cache-key }}-${{ runner.os }}-${{ inputs.otp-version }}-${{ inputs.elixir-version }}-${{ env.MIX_ENV }}-${{ hashFiles('**/mix.lock') }} 80 | restore-keys: | 81 | build-${{ inputs.cache-key }}-${{ runner.os }}-${{ inputs.otp-version }}-${{ inputs.elixir-version }}-${{ env.MIX_ENV }}- 82 | - name: Get Hex cache 83 | uses: actions/cache@v3 84 | id: hex-cache 85 | with: 86 | path: ~/.hex 87 | key: build-${{ runner.os }}-${{ inputs.otp-version }}-${{ inputs.elixir-version }}-${{ hashFiles('**/mix.lock') }} 88 | restore-keys: | 89 | build-${{ runner.os }}-${{ inputs.otp-version }}-${{ inputs.elixir-version }}- 90 | # In my experience, I have issues with incremental builds maybe 1 in 100 91 | # times that are fixed by doing a full recompile. 92 | # In order to not waste dev time on such trivial issues (while also reaping 93 | # the time savings of incremental builds for *most* day-to-day development), 94 | # I force a full recompile only on builds that we retry. 95 | - name: Clean to rule out incremental build as a source of flakiness 96 | if: github.run_attempt != '1' 97 | run: | 98 | mix deps.clean --all 99 | mix clean 100 | shell: sh 101 | 102 | - name: Install Rebar 103 | run: mix local.rebar --force 104 | shell: sh 105 | if: inputs.install-rebar == 'true' 106 | 107 | - name: Install Hex 108 | run: mix local.hex --force 109 | shell: sh 110 | if: inputs.install-hex == 'true' 111 | 112 | - name: Install Dependencies 113 | run: mix deps.get 114 | shell: sh 115 | 116 | # Normally we'd use `mix deps.compile` here, however that incurs a large 117 | # performance penalty when the dependencies are already fully compiled: 118 | # https://elixirforum.com/t/github-action-cache-elixir-always-recompiles-dependencies-elixir-1-13-3/45994/12 119 | # 120 | # Accoring to Jose Valim at the above link `mix loadpaths` will check and 121 | # compile missing dependencies 122 | - name: Compile Dependencies 123 | run: mix loadpaths 124 | shell: sh 125 | if: inputs.build-deps == 'true' 126 | 127 | - name: Compile Application 128 | run: mix compile ${{ inputs.build-flags }} 129 | shell: sh 130 | if: inputs.build-app == 'true' 131 | -------------------------------------------------------------------------------- /.github/dependabot.yml: -------------------------------------------------------------------------------- 1 | version: 2 2 | updates: 3 | - package-ecosystem: mix 4 | directory: "/" 5 | schedule: 6 | interval: weekly 7 | time: "12:00" 8 | open-pull-requests-limit: 5 9 | -------------------------------------------------------------------------------- /.github/workflows/elixir-build-and-test.yml: -------------------------------------------------------------------------------- 1 | name: Build and Test 2 | 3 | on: 4 | push: 5 | branches: 6 | - main 7 | pull_request: 8 | branches: 9 | - "*" 10 | 11 | jobs: 12 | build: 13 | strategy: 14 | matrix: 15 | include: 16 | # Elixir 1.13 17 | - elixir-version: "1.13.0" 18 | otp-version: "24.3.1" 19 | 20 | # Elixir 1.14 21 | - elixir-version: "1.14.0" 22 | otp-version: "24.3.1" 23 | - elixir-version: "1.14.0" 24 | otp-version: "25.3.1" 25 | 26 | # Elixir 1.15 27 | - elixir-version: "1.15.0" 28 | otp-version: "25.3.1" 29 | - elixir-version: "1.15.0" 30 | otp-version: "26.0.1" 31 | 32 | name: Build and test 33 | runs-on: ubuntu-latest 34 | env: 35 | MIX_ENV: test 36 | 37 | # Remove if you don't need a database 38 | services: 39 | db: 40 | image: "postgres:15.3-alpine" 41 | env: 42 | POSTGRES_USER: postgres 43 | POSTGRES_PASSWORD: postgres 44 | POSTGRES_DB: ecto_resource_test 45 | ports: ["5432:5432"] 46 | options: >- 47 | --health-cmd pg_isready 48 | --health-interval 10s 49 | --health-timeout 5s 50 | --health-retries 5 51 | steps: 52 | - name: Checkout repository 53 | uses: actions/checkout@v3 54 | 55 | - name: Setup Elixir Project 56 | uses: ./.github/actions/elixir-setup 57 | with: 58 | elixir-version: ${{ matrix.elixir-version }} 59 | otp-version: ${{ matrix.otp-version }} 60 | build-flags: --all-warnings --warnings-as-errors 61 | build-app: true 62 | 63 | - name: Run Migrations 64 | run: mix ecto.migrate 65 | # Run tests & migrations even if compilation failed (probably due to warnings) 66 | # so that we give devs as much feedback as possible & save some time. 67 | if: always() 68 | 69 | - name: Run Tests 70 | run: mix test --warnings-as-errors 71 | if: always() 72 | -------------------------------------------------------------------------------- /.github/workflows/elixir-dialyzer.yml: -------------------------------------------------------------------------------- 1 | name: Elixir Type Linting 2 | 3 | on: 4 | push: 5 | branches: 6 | - main 7 | pull_request: 8 | branches: 9 | - "*" 10 | 11 | jobs: 12 | build: 13 | name: Run Dialyzer 14 | runs-on: ubuntu-latest 15 | env: 16 | MIX_ENV: dev 17 | 18 | steps: 19 | - name: Checkout repository 20 | uses: actions/checkout@v3 21 | 22 | - name: Setup Elixir Project 23 | uses: ./.github/actions/elixir-setup 24 | id: beam 25 | with: 26 | elixir-version: 1.15.2 27 | otp-version: 26.0.2 28 | build-app: false 29 | 30 | # Don't cache PLTs based on mix.lock hash, as Dialyzer can incrementally update even old ones 31 | # Cache key based on Elixir & Erlang version (also useful when running in matrix) 32 | - name: Restore PLT cache 33 | uses: actions/cache@v3 34 | id: plt_cache 35 | with: 36 | key: plt-${{ runner.os }}-${{ steps.beam.outputs.otp-version }}-${{ steps.beam.outputs.elixir-version }}-${{ hashFiles('**/mix.lock') }}-${{ hashFiles('**/*.ex') }} 37 | restore-keys: | 38 | plt-${{ runner.os }}-${{ steps.beam.outputs.otp-version }}-${{ steps.beam.outputs.elixir-version }}-${{ hashFiles('**/mix.lock') }}-${{ hashFiles('**/*.ex') }} 39 | plt-${{ runner.os }}-${{ steps.beam.outputs.otp-version }}-${{ steps.beam.outputs.elixir-version }}-${{ hashFiles('**/mix.lock') }}- 40 | plt-${{ runner.os }}-${{ steps.beam.outputs.otp-version }}-${{ steps.beam.outputs.elixir-version }}- 41 | plt-${{ runner.os }}-${{ steps.beam.outputs.otp-version }}- 42 | path: priv/plts 43 | 44 | # Create PLTs if no cache was found. 45 | # Always rebuild PLT when a job is retried 46 | # (If they were cached at all, they'll be updated when we run mix dialyzer with no flags.) 47 | - name: Create PLTs 48 | if: steps.plt_cache.outputs.cache-hit != 'true' || github.run_attempt != '1' 49 | run: mix dialyzer --plt 50 | 51 | - name: Run Dialyzer 52 | run: mix dialyzer --format github 53 | -------------------------------------------------------------------------------- /.github/workflows/elixir-quality-checks.yml: -------------------------------------------------------------------------------- 1 | name: Elixir Quality Checks 2 | 3 | on: 4 | push: 5 | branches: 6 | - main 7 | pull_request: 8 | branches: 9 | - "*" 10 | 11 | jobs: 12 | quality_checks: 13 | name: Formatting, Credo, and Unused Deps 14 | runs-on: ubuntu-latest 15 | 16 | steps: 17 | - name: Checkout repository 18 | uses: actions/checkout@v3 19 | 20 | - name: Setup Elixir Project 21 | uses: ./.github/actions/elixir-setup 22 | with: 23 | elixir-version: 1.15.2 24 | otp-version: 26.0.2 25 | build-app: false 26 | 27 | - name: Check for unused deps 28 | run: mix deps.unlock --check-unused 29 | - name: Check code formatting 30 | run: mix format --check-formatted 31 | # Check formatting even if there were unused deps so that 32 | # we give devs as much feedback as possible & save some time. 33 | if: always() 34 | - name: Run Credo 35 | run: mix credo suggest --strict 36 | # Run Credo even if formatting or the unused deps check failed 37 | if: always() 38 | - name: Check for compile-time dependencies 39 | run: mix xref graph --label compile-connected --fail-above 0 40 | if: always() 41 | -------------------------------------------------------------------------------- /.github/workflows/nightly-integration-test.yml: -------------------------------------------------------------------------------- 1 | name: Nightly Integration Tests 2 | 3 | on: 4 | schedule: 5 | - cron: "0 7 * * *" 6 | 7 | jobs: 8 | integration_test: 9 | name: Integration Tests 10 | runs-on: ubuntu-latest 11 | env: 12 | MIX_ENV: test 13 | 14 | # Remove if you don't need a database 15 | services: 16 | db: 17 | image: postgis/postgis:13-3.1 18 | env: 19 | POSTGRES_USER: postgres 20 | POSTGRES_PASSWORD: postgres 21 | POSTGRES_DB: ecto_resource_test 22 | ports: ["5432:5432"] 23 | options: >- 24 | --health-cmd pg_isready 25 | --health-interval 10s 26 | --health-timeout 5s 27 | --health-retries 5 28 | steps: 29 | - name: Checkout repository 30 | uses: actions/checkout@v3 31 | 32 | - name: Setup Elixir Project 33 | uses: ./.github/actions/elixir-setup 34 | with: 35 | elixir-version: 1.15.2 36 | otp-version: 26.0.2 37 | 38 | - name: Run Migrations 39 | run: mix ecto.migrate 40 | if: always() 41 | 42 | - name: Run Tests 43 | run: mix test 44 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # The directory Mix will write compiled artifacts to. 2 | /_build/ 3 | 4 | # If you run "mix test --cover", coverage assets end up here. 5 | /cover/ 6 | 7 | # The directory Mix downloads your dependencies sources to. 8 | /deps/ 9 | 10 | # Where third-party dependencies like ExDoc output generated docs. 11 | /doc/ 12 | 13 | # Ignore .fetch files in case you like to edit your project deps locally. 14 | /.fetch 15 | 16 | # If the VM crashes, it generates a dump, let's ignore it too. 17 | erl_crash.dump 18 | 19 | # Also ignore archive artifacts (built via "mix archive.build"). 20 | *.ez 21 | 22 | # Ignore package tarball (built via "mix hex.build"). 23 | ecto_resource-*.tar 24 | 25 | .elixir_ls 26 | tmp/ 27 | 28 | priv/plts 29 | -------------------------------------------------------------------------------- /.pre-commit-config.yaml: -------------------------------------------------------------------------------- 1 | # See https://pre-commit.com for more information 2 | # See https://pre-commit.com/hooks.html for more hooks 3 | repos: 4 | - repo: https://github.com/pre-commit/pre-commit-hooks 5 | rev: v3.2.0 6 | hooks: 7 | - id: trailing-whitespace 8 | - id: check-yaml 9 | - id: check-added-large-files 10 | 11 | - repo: local 12 | hooks: 13 | - id: format 14 | name: Elixir/Format 15 | language: system 16 | entry: mix format 17 | files: \.(ex|exs) 18 | pass_filenames: false 19 | 20 | - id: credo 21 | name: Elixir/Credo 22 | language: system 23 | entry: mix credo --strict 24 | files: \.(ex|exs) 25 | pass_filenames: false 26 | 27 | - id: test 28 | name: Elixir/Test 29 | language: system 30 | entry: mix test 31 | files: \.(ex|exs) 32 | pass_filenames: false 33 | 34 | - id: compile 35 | name: Elixir/Compile 36 | language: system 37 | entry: mix compile --force --warnings-as-errors 38 | files: \.(ex|exs) 39 | pass_filenames: false -------------------------------------------------------------------------------- /CHANGELOG.md: -------------------------------------------------------------------------------- 1 | # Changelog 2 | 3 | All notable changes to this project will be documented in this file. 4 | 5 | The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/), 6 | and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). 7 | 8 | ## [1.4.0] 9 | 10 | ### Added 11 | 12 | - Add `where` option to `all` function 13 | 14 | ### Changed 15 | 16 | ### Removed 17 | 18 | ### Fixed 19 | 20 | ### Security 21 | 22 | ## [1.3.3] 23 | 24 | ### Fixed 25 | 26 | - Incorrect functions generated when providing both `suffix: false` and other options to the `resource` macro 27 | 28 | ## [1.3.2] 29 | 30 | ### Fixed 31 | 32 | - Incorrect function name generation when providing both `suffix: false` and other options to the `resource` macro 33 | 34 | ## [1.3.1] 35 | 36 | ### Added 37 | 38 | ### Changed 39 | 40 | - Allow keyword lists where currently only maps are supported 41 | 42 | ### Removed 43 | 44 | ### Fixed 45 | 46 | - Fixed some bad tests to have better assertions 47 | 48 | ### Security 49 | 50 | ## [1.3.0] 51 | 52 | ### Added 53 | 54 | - `changeset` convenience function added 55 | 56 | ### Changed 57 | 58 | ### Removed 59 | 60 | ### Fixed 61 | 62 | ### Security 63 | 64 | ## [1.2.0] - 2019-09-17 65 | 66 | ### Added 67 | 68 | - Now generates `get_by`, and `get_by!` functions 69 | - `suffix: false` option 70 | -------------------------------------------------------------------------------- /LICENSE.txt: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright [yyyy] [name of copyright owner] 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | EctoResource 2 | ============ 3 | 4 | * [About](#about) 5 | * [Features](#features) 6 | * [Installation](#installation) 7 | * [Usage](#usage) 8 | * [Basic usage](#basic-usage---generate-all-ectoresource-functions) 9 | * [Explicit usage](#explicit-usage---generate-only-given-functions) 10 | * [Exclusive usage](#exclusive-usage---generate-all-but-the-given-functions) 11 | * [Alias :read](#alias-read---generate-data-access-functions) 12 | * [Alias :read_write](#alias-read_write---generate-data-access-and-manipulation-functions-excluding-delete) 13 | * [Resource functions](#resource-functions) 14 | * [Caveats](#caveats) 15 | * [Contribution](#contribution) 16 | * [Bug reports](#bug_reports) 17 | * [Pull requests](#pull_requests) 18 | * [License](#license) 19 | * [Authors](#authors) 20 | 21 | Eliminate boilerplate involved in defining basic CRUD functions in a Phoenix context or Elixir module. 22 | 23 | Rationale 24 | ----- 25 | When using [Context modules](https://hexdocs.pm/phoenix/contexts.html) in a [Phoenix](https://phoenixframework.org/) application, there's a general need to define the standard CRUD functions for a given `Ecto.Schema`. Phoenix context generators will even do this automatically. Soon you will notice that there's quite a lot of code involved in CRUD access within your contexts. 26 | 27 | This can become problematic for a few reasons: 28 | 29 | * Boilerplate functions for CRUD access, for every `Ecto.Schema` referenced in that context, introduce more noise than signal. This can obscure the more interesting details of the context. 30 | * These functions may tend to accumulate drift from the standard API by inviting edits for new use-cases, reducing the usefulness of naming conventions. 31 | * The burden of locally testing wrapper functions, yields low value for the writing and maintainence investment. 32 | 33 | In short, at best this code is redundant and at worst is a deviant entanglement of modified conventions. All of which amounts to a more-painful development experience. `EctoResource` was created to ease this pain. 34 | 35 | Features 36 | -------- 37 | 38 | ### Generate CRUD functions for a given `Ecto.Repo` and `Ecto.Schema` 39 | 40 | `EctoResource` can be used to generate CRUD functions for a given `Ecto.Repo` and `Ecto.Schema`. By default it will create every function needed to create, read, update, and delete the resouce. It includes the `!` version of each function (where relevant) that will raise an error instead of return a value. 41 | 42 | ### Allow customization of generated resources 43 | 44 | You can optionally include or exclude specific functions to generate exactly the functions your context requires. There's also two handy aliases for generating read functions and read/write functions. 45 | 46 | ### Automatic pluralization 47 | 48 | For methods that return a list of records, it seems natural to use a plural name. For example, take a function named `MyContext.all_schema`. While this works, it makes the grammar a bit awkward and distracts from the intent of the function. `EctoResource` uses `Inflex` when generating functions to create readable english function names automatically. For example, given the schema `Person`, a function named `all_people/1` is generated. 49 | 50 | ### Generate documentation for each generated function 51 | 52 | Every function generated includes documentation so your application's documentation will include the generated functions with examples. 53 | 54 | ### Reflection metadata 55 | 56 | A function is generated for each resource defined by `EctoResource` to list all the functions generated for each `Ecto.Repo` and `Ecto.Schema`. A mix task is included to provide easy access to this information. 57 | 58 | ### Supports any module 59 | 60 | While `EctoResource` was designed for [Phoenix Contexts](https://hexdocs.pm/phoenix/contexts.html) in mind, It can be used in any Elixir module. 61 | 62 | Installation 63 | ------------ 64 | 65 | This package is available in [Hex](https://hex.pm/), the package can be installed by adding ecto_resource to your list of dependencies in mix.exs: 66 | 67 | ```elixir 68 | def deps do 69 | [ 70 | {:ecto_resource, "~> 1.1.0"} 71 | ] 72 | end 73 | ``` 74 | 75 | Usage 76 | ----- 77 | 78 | ### Basic usage - generate all `EctoResource` functions 79 | 80 | ```elixir 81 | defmodule MyApp.MyContext do 82 | alias MyApp.Repo 83 | alias MyApp.Schema 84 | use EctoResource 85 | 86 | using_repo(Repo) do 87 | resource(Schema) 88 | end 89 | end 90 | ``` 91 | 92 | This generates all the functions `EctoResource` has to offer: 93 | 94 | * `MyContext.all_schemas/1` 95 | * `MyContext.change_schema/1` 96 | * `MyContext.create_schema/1` 97 | * `MyContext.create_schema!/1` 98 | * `MyContext.delete_schema/1` 99 | * `MyContext.delete_schema!/1` 100 | * `MyContext.get_schema/2` 101 | * `MyContext.get_schema!/2` 102 | * `MyContext.get_schema_by/2` 103 | * `MyContext.get_schema_by!/2` 104 | * `MyContext.update_schema/2` 105 | * `MyContext.update_schema!/2` 106 | 107 | ### Explicit usage - generate only given functions 108 | 109 | ```elixir 110 | defmodule MyApp.MyContext do 111 | alias MyApp.Repo 112 | alias MyApp.Schema 113 | use EctoResource 114 | 115 | using_repo(Repo) do 116 | resource(Schema, only: [:create, :delete!]) 117 | end 118 | end 119 | ``` 120 | 121 | This generates only the given functions: 122 | 123 | * `MyContext.create_schema/1` 124 | * `MyContext.delete_schema!/1` 125 | 126 | ### Exclusive usage - generate all but the given functions 127 | 128 | ```elixir 129 | defmodule MyApp.MyContext do 130 | alias MyApp.Repo 131 | alias MyApp.Schema 132 | use EctoResource 133 | 134 | using_repo(Repo) do 135 | resource(Schema, except: [:create, :delete!]) 136 | end 137 | end 138 | ``` 139 | 140 | This generates all the functions excluding the given functions: 141 | 142 | * `MyContext.all_schemas/1` 143 | * `MyContext.change_schema/1` 144 | * `MyContext.create_schema!/1` 145 | * `MyContext.delete_schema/1` 146 | * `MyContext.get_schema/2` 147 | * `MyContext.get_schema_by/2` 148 | * `MyContext.get_schema_by!/2` 149 | * `MyContext.get_schema!/2` 150 | * `MyContext.update_schema/2` 151 | * `MyContext.update_schema!/2` 152 | 153 | ### Alias `:read` - generate data access functions 154 | 155 | ```elixir 156 | defmodule MyApp.MyContext do 157 | alias MyApp.Repo 158 | alias MyApp.Schema 159 | use EctoResource 160 | 161 | using_repo(Repo) do 162 | resource(Schema, :read) 163 | end 164 | end 165 | ``` 166 | 167 | This generates all the functions necessary for reading data: 168 | 169 | * `MyContext.all_schemas/1` 170 | * `MyContext.get_schema/2` 171 | * `MyContext.get_schema!/2` 172 | 173 | ### Alias `:read_write` - generate data access and manipulation functions, excluding delete 174 | 175 | ```elixir 176 | defmodule MyApp.MyContext do 177 | alias MyApp.Repo 178 | alias MyApp.Schema 179 | use EctoResource 180 | 181 | using_repo(Repo) do 182 | resource(Schema, :read_write) 183 | end 184 | end 185 | ``` 186 | 187 | This generates all the functions except `delete_schema/1` and `delete_schema!/1`: 188 | 189 | * `MyContext.all_schemas/1` 190 | * `MyContext.change_schema/1` 191 | * `MyContext.create_schema/1` 192 | * `MyContext.create_schema!/1` 193 | * `MyContext.get_schema/2` 194 | * `MyContext.get_schema!/2` 195 | * `MyContext.update_schema/2` 196 | * `MyContext.update_schema!/2` 197 | 198 | ### Resource functions 199 | 200 | The general idea of the generated resource functions is to abstract away the `Ecto.Repo` and `Ecto.Schema` parts of data access with `Ecto` and provide an API to the context that feels natural and clear to the caller. 201 | 202 | The following examples will all assume a repo named `Repo` and a schema named `Person`. 203 | 204 | #### all_people 205 | 206 | Fetches a list of all %Person{} entries from the data store. _Note: `EctoResource` will pluralize this function name using `Inflex`_ 207 | 208 | ```elixir 209 | iex> all_people() 210 | [%Person{id: 1}] 211 | 212 | iex> all_people(preloads: [:address]) 213 | [%Person{id: 1, address: %Address{}}] 214 | 215 | iex> all_people(order_by: [desc: :id]) 216 | [%Person{id: 2}, %Person{id: 1}] 217 | 218 | iex> all_people(preloads: [:address], order_by: [desc: :id])) 219 | [ 220 | %Person{ 221 | id: 2, 222 | address: %Address{} 223 | }, 224 | %Person{ 225 | id: 1, 226 | address: %Address{} 227 | } 228 | ] 229 | 230 | iex> all_people(where: [id: 2]) 231 | [%Person{id: 2, address: %Address{}}] 232 | ``` 233 | 234 | #### change_person 235 | 236 | Creates a `%Person{}` changeset. 237 | 238 | ```elixir 239 | iex> change_person(%{name: "Example Person"}) 240 | #Ecto.Changeset< 241 | action: nil, 242 | changes: %{name: "Example Person"}, 243 | errors: [], 244 | data: #Person<>, 245 | valid?: true 246 | > 247 | ``` 248 | 249 | #### create_person 250 | 251 | Inserts a `%Person{}` with the given attributes in the data store, returning an `:ok`/`:error` tuple. 252 | 253 | ```elixir 254 | iex> create_person(%{name: "Example Person"}) 255 | {:ok, %Person{id: 123, name: "Example Person"}} 256 | 257 | iex> create_person(%{invalid: "invalid"}) 258 | {:error, %Ecto.Changeset} 259 | ``` 260 | 261 | #### create_person! 262 | 263 | Inserts a `%Person{}` with the given attributes in the data store, returning a `%Person{}` or raises `Ecto.InvalidChangesetError`. 264 | 265 | ```elixir 266 | iex> create_person!(%{name: "Example Person"}) 267 | %Person{id: 123, name: "Example Person"} 268 | 269 | iex> create_person!(%{invalid: "invalid"}) 270 | ** (Ecto.InvalidChangesetError) 271 | ``` 272 | 273 | #### delete_person 274 | 275 | Deletes a given `%Person{}` from the data store, returning an `:ok`/`:error` tuple. 276 | 277 | ```elixir 278 | iex> delete_person(%Person{id: 1}) 279 | {:ok, %Person{id: 1}} 280 | 281 | iex> delete_person(%Person{id: 999}) 282 | {:error, %Ecto.Changeset} 283 | ``` 284 | 285 | #### delete_person! 286 | 287 | Deletes a given `%Person{}` from the data store, returning the deleted `%Person{}`, or raises `Ecto.StaleEntryError`. 288 | 289 | ```elixir 290 | iex> delete_person!(%Person{id: 1}) 291 | %Person{id: 1} 292 | 293 | iex> delete_person!(%Person{id: 999}) 294 | ** (Ecto.StaleEntryError) 295 | ``` 296 | 297 | #### get_person 298 | 299 | Fetches a single `%Person{}` from the data store where the primary key matches the given id, returns a `%Person{}` or `nil`. 300 | 301 | ```elixir 302 | iex> get_person(1) 303 | %Person{id: 1} 304 | 305 | iex> get_person(999) 306 | nil 307 | 308 | iex> get_person(1, preloads: [:address]) 309 | %Person{ 310 | id: 1, 311 | address: %Address{} 312 | } 313 | ``` 314 | 315 | #### get_person! 316 | 317 | Fetches a single `%Person{}` from the data store where the primary key matches the given id, returns a `%Person{}` or raises `Ecto.NoResultsError`. 318 | 319 | ```elixir 320 | iex> get_person!(1) 321 | %Person{id: 1} 322 | 323 | iex> get_person!(999) 324 | ** (Ecto.NoResultsError) 325 | 326 | iex> get_person!(1, preloads: [:address]) 327 | %Person{ 328 | id: 1, 329 | address: %Address{} 330 | } 331 | ``` 332 | 333 | #### get_person_by 334 | 335 | Fetches a single `%Person{}` from the data store where the attributes match the 336 | given values. 337 | 338 | ```elixir 339 | iex> get_person_by(%{name: "Chuck Norris"}) 340 | %Person{name: "Chuck Norris"} 341 | 342 | iex> get_person_by(%{name: "Doesn't Exist"}) 343 | nil 344 | ``` 345 | 346 | #### get_person_by! 347 | 348 | Fetches a single `%Person{}` from the data store where the attributes match the 349 | given values. Raises an `Ecto.NoResultsError` if the record does not exist 350 | 351 | ```elixir 352 | iex> get_person_by!(%{name: "Chuck Norris"}) 353 | %Person{name: "Chuck Norris"} 354 | 355 | iex> get_person_by!(%{name: "Doesn't Exist"}) 356 | ** (Ecto.NoResultsError) 357 | ``` 358 | 359 | #### update_person 360 | 361 | Updates a given %Person{} with the given attributes, returns an `:ok`/`:error` tuple. 362 | 363 | ```elixir 364 | iex> update_person(%Person{id: 1}, %{name: "New Person"}) 365 | {:ok, %Person{id: 1, name: "New Person"}} 366 | 367 | iex> update_person(%Person{id: 1}, %{invalid: "invalid"}) 368 | {:error, %Ecto.Changeset} 369 | ``` 370 | 371 | #### update_person! 372 | 373 | Updates a given %Person{} with the given attributes, returns a %Person{} or raises `Ecto.InvalidChangesetError`. 374 | 375 | ```elixir 376 | iex> update_person!(%Person{id: 1}, %{name: "New Person"}) 377 | %Person{id: 1, name: "New Person"} 378 | 379 | iex> update_person!(%Person{id: 1}, %{invalid: "invalid"}) 380 | ** (Ecto.InvalidChangesetError) 381 | ``` 382 | 383 | Caveats 384 | ------- 385 | This is not meant to be used as a wrapper for all the Repo functions within a context. Not all callbacks defined in Ecto.Repo are generated. `EctoResource` should be used to help reduce boilerplate code and tests for general CRUD operations. 386 | 387 | It may be the case that `EctoResource` needs to evolve and provide slightly more functionality/flexibility in the future. However, the general focus is reducing boilerplate code. 388 | 389 | Contribution 390 | ------------ 391 | 392 | ### Bug reports 393 | 394 | If you discover any bugs, feel free to create an issue on [GitHub](https://github.com/daytonn/ecto_resource/issues). Please add as much information as possible to help in fixing the potential bug. You are also encouraged to help even more by forking and sending us a pull request. 395 | 396 | [Issues on GitHub](https://github.com/daytonn/ecto_resource/issues) 397 | 398 | ### Pull requests 399 | 400 | * Fork it (https://github.com/daytonn/ecto_resource/fork) 401 | * Add upstream remote (`git remote add upstream git@github.com:daytonn/ecto_resource.git`) 402 | * Make sure you're up-to-date with upstream main (`git pull upstream main`) 403 | * Create your feature branch (`git checkout -b feature/fooBar`) 404 | * Commit your changes (`git commit -am 'Add some fooBar'`) 405 | * Push to the branch (`git push origin feature/fooBar`) 406 | * Create a new Pull Request 407 | 408 | ### Nice to have features/improvements (:point_up::wink:) 409 | 410 | * Ability to override pluralization 411 | * Find functions (maybe?) 412 | 413 | 414 | License 415 | ------- 416 | [Apache 2.0](https://raw.githubusercontent.com/daytonn/ecto_resource/main/LICENSE.txt) 417 | -------------------------------------------------------------------------------- /config/config.exs: -------------------------------------------------------------------------------- 1 | import Config 2 | 3 | import_config "#{Mix.env()}.exs" 4 | -------------------------------------------------------------------------------- /config/dev.exs: -------------------------------------------------------------------------------- 1 | import Config 2 | -------------------------------------------------------------------------------- /config/prod.exs: -------------------------------------------------------------------------------- 1 | import Config 2 | -------------------------------------------------------------------------------- /config/test.exs: -------------------------------------------------------------------------------- 1 | import Config 2 | 3 | config :ecto_resource, ecto_repos: [EctoResource.TestRepo] 4 | 5 | config :ecto_resource, EctoResource.TestRepo, 6 | username: "postgres", 7 | password: "postgres", 8 | database: "ecto_resource_test", 9 | hostname: "localhost", 10 | pool: Ecto.Adapters.SQL.Sandbox 11 | 12 | config :logger, level: :info 13 | -------------------------------------------------------------------------------- /docker-compose.yml: -------------------------------------------------------------------------------- 1 | version: '3.1' 2 | services: 3 | db: 4 | image: postgres 5 | restart: always 6 | volumes: 7 | - ./tmp/db:/var/lib/postgresql/data 8 | ports: 9 | - "5432:5432" 10 | environment: 11 | - POSTGRES_USER=postgres 12 | - POSTGRES_PASSWORD=postgres 13 | -------------------------------------------------------------------------------- /lib/ecto_resource.ex: -------------------------------------------------------------------------------- 1 | defmodule EctoResource do 2 | @moduledoc """ 3 | EctoResource 4 | ============ 5 | Eliminate boilerplate involved in defining basic CRUD functions in a Phoenix context or Elixir module. 6 | 7 | When using [Context modules](https://hexdocs.pm/phoenix/contexts.html) in a [Phoenix](https://phoenixframework.org/) application, 8 | there's a general need to define the standard CRUD functions for a given `Ecto.Schema`. Phoenix context generators will even do this automatically. 9 | Soon you will notice that there's quite a lot of code involved in CRUD access within your contexts. 10 | 11 | This can become problematic for a few reasons: 12 | 13 | * Boilerplate functions for CRUD access, for every `Ecto.Schema` referenced in that context, introduce more noise than signal. This can obscure the more interesting details of the context. 14 | * These functions may tend to accumulate drift from the standard API by inviting edits for new use-cases, reducing the usefulness of naming conventions. 15 | * The burden of locally testing wrapper functions, yields low value for the writing and maintainence investment. 16 | 17 | In short, at best this code is redundant and at worst is a deviant entanglement of modified conventions. All of which amounts to a more-painful development experience. `EctoResource` was created to ease this pain. 18 | 19 | Usage 20 | ----- 21 | 22 | ### Basic usage - generate all `EctoResource` functions 23 | 24 | ```elixir 25 | defmodule MyApp.MyContext do 26 | alias MyApp.Repo 27 | alias MyApp.Schema 28 | use EctoResource 29 | 30 | using_repo(Repo) do 31 | resource(Schema) 32 | end 33 | end 34 | ``` 35 | 36 | This generates all the functions `EctoResource` has to offer: 37 | 38 | * `MyContext.all_schemas/1` 39 | * `MyContext.change_schema/1` 40 | * `MyContext.create_schema/1` 41 | * `MyContext.create_schema!/1` 42 | * `MyContext.delete_schema/1` 43 | * `MyContext.delete_schema!/1` 44 | * `MyContext.get_schema/2` 45 | * `MyContext.get_schema!/2` 46 | * `MyContext.get_schema_by/2` 47 | * `MyContext.get_schema_by!/2` 48 | * `MyContext.update_schema/2` 49 | * `MyContext.update_schema!/2` 50 | 51 | ### Explicit usage - generate only given functions 52 | 53 | ```elixir 54 | defmodule MyApp.MyContext do 55 | alias MyApp.Repo 56 | alias MyApp.Schema 57 | use EctoResource 58 | 59 | using_repo(Repo) do 60 | resource(Schema, only: [:create, :delete!]) 61 | end 62 | end 63 | ``` 64 | 65 | This generates only the given functions: 66 | 67 | * `MyContext.create_schema/1` 68 | * `MyContext.delete_schema!/1` 69 | 70 | ### Exclusive usage - generate all but the given functions 71 | 72 | ```elixir 73 | defmodule MyApp.MyContext do 74 | alias MyApp.Repo 75 | alias MyApp.Schema 76 | use EctoResource 77 | 78 | using_repo(Repo) do 79 | resource(Schema, except: [:create, :delete!]) 80 | end 81 | end 82 | ``` 83 | 84 | This generates all the functions excluding the given functions: 85 | 86 | * `MyContext.all_schemas/1` 87 | * `MyContext.change_schema/1` 88 | * `MyContext.create_schema!/1` 89 | * `MyContext.delete_schema/1` 90 | * `MyContext.get_schema/2` 91 | * `MyContext.get_schema_by/2` 92 | * `MyContext.get_schema_by!/2` 93 | * `MyContext.get_schema!/2` 94 | * `MyContext.update_schema/2` 95 | * `MyContext.update_schema!/2` 96 | 97 | ### Alias `:read` - generate data access functions 98 | 99 | ```elixir 100 | defmodule MyApp.MyContext do 101 | alias MyApp.Repo 102 | alias MyApp.Schema 103 | use EctoResource 104 | 105 | using_repo(Repo) do 106 | resource(Schema, :read) 107 | end 108 | end 109 | ``` 110 | 111 | This generates all the functions necessary for reading data: 112 | 113 | * `MyContext.all_schemas/1` 114 | * `MyContext.get_schema/2` 115 | * `MyContext.get_schema!/2` 116 | 117 | ### Alias `:read_write` - generate data access and manipulation functions, excluding delete 118 | 119 | ```elixir 120 | defmodule MyApp.MyContext do 121 | alias MyApp.Repo 122 | alias MyApp.Schema 123 | use EctoResource 124 | 125 | using_repo(Repo) do 126 | resource(Schema, :read_write) 127 | end 128 | end 129 | ``` 130 | 131 | This generates all the functions except `delete_schema/1` and `delete_schema!/1`: 132 | 133 | * `MyContext.all_schemas/1` 134 | * `MyContext.change_schema/1` 135 | * `MyContext.create_schema/1` 136 | * `MyContext.create_schema!/1` 137 | * `MyContext.get_schema/2` 138 | * `MyContext.get_schema!/2` 139 | * `MyContext.update_schema/2` 140 | * `MyContext.update_schema!/2` 141 | 142 | ### Resource functions 143 | 144 | The general idea of the generated resource functions is to abstract away the `Ecto.Repo` and `Ecto.Schema` parts of data access with `Ecto` and provide an API to the context that feels natural and clear to the caller. 145 | 146 | The following examples will all assume a repo named `Repo` and a schema named `Person`. 147 | 148 | #### all_people 149 | 150 | Fetches a list of all %Person{} entries from the data store. _Note: `EctoResource` will pluralize this function name using `Inflex`_ 151 | 152 | ```elixir 153 | iex> all_people() 154 | [%Person{id: 1}] 155 | 156 | iex> all_people(preloads: [:address]) 157 | [%Person{id: 1, address: %Address{}}] 158 | 159 | iex> all_people(order_by: [desc: :id]) 160 | [%Person{id: 2}, %Person{id: 1}] 161 | 162 | iex> all_people(preloads: [:address], order_by: [desc: :id])) 163 | [ 164 | %Person{ 165 | id: 2, 166 | address: %Address{} 167 | }, 168 | %Person{ 169 | id: 1, 170 | address: %Address{} 171 | } 172 | ] 173 | 174 | iex> all_people(where: [id: 2]) 175 | [%Person{id: 2, address: %Address{}}] 176 | ``` 177 | 178 | #### change_person 179 | 180 | Creates a `%Person{}` changeset. 181 | 182 | ```elixir 183 | iex> change_person(%{name: "Example Person"}) 184 | #Ecto.Changeset< 185 | action: nil, 186 | changes: %{name: "Example Person"}, 187 | errors: [], 188 | data: #Person<>, 189 | valid?: true 190 | > 191 | ``` 192 | 193 | #### create_person 194 | 195 | Inserts a `%Person{}` with the given attributes in the data store, returning an `:ok`/`:error` tuple. 196 | 197 | ```elixir 198 | iex> create_person(%{name: "Example Person"}) 199 | {:ok, %Person{id: 123, name: "Example Person"}} 200 | 201 | iex> create_person(%{invalid: "invalid"}) 202 | {:error, %Ecto.Changeset} 203 | ``` 204 | 205 | #### create_person! 206 | 207 | Inserts a `%Person{}` with the given attributes in the data store, returning a `%Person{}` or raises `Ecto.InvalidChangesetError`. 208 | 209 | ```elixir 210 | iex> create_person!(%{name: "Example Person"}) 211 | %Person{id: 123, name: "Example Person"} 212 | 213 | iex> create_person!(%{invalid: "invalid"}) 214 | ** (Ecto.InvalidChangesetError) 215 | ``` 216 | 217 | #### delete_person 218 | 219 | Deletes a given `%Person{}` from the data store, returning an `:ok`/`:error` tuple. 220 | 221 | ```elixir 222 | iex> delete_person(%Person{id: 1}) 223 | {:ok, %Person{id: 1}} 224 | 225 | iex> delete_person(%Person{id: 999}) 226 | {:error, %Ecto.Changeset} 227 | ``` 228 | 229 | #### delete_person! 230 | 231 | Deletes a given `%Person{}` from the data store, returning the deleted `%Person{}`, or raises `Ecto.StaleEntryError`. 232 | 233 | ```elixir 234 | iex> delete_person!(%Person{id: 1}) 235 | %Person{id: 1} 236 | 237 | iex> delete_person!(%Person{id: 999}) 238 | ** (Ecto.StaleEntryError) 239 | ``` 240 | 241 | #### get_person 242 | 243 | Fetches a single `%Person{}` from the data store where the primary key matches the given id, returns a `%Person{}` or `nil`. 244 | 245 | ```elixir 246 | iex> get_person(1) 247 | %Person{id: 1} 248 | 249 | iex> get_person(999) 250 | nil 251 | 252 | iex> get_person(1, preloads: [:address]) 253 | %Person{ 254 | id: 1, 255 | address: %Address{} 256 | } 257 | ``` 258 | 259 | #### get_person! 260 | 261 | Fetches a single `%Person{}` from the data store where the primary key matches the given id, returns a `%Person{}` or raises `Ecto.NoResultsError`. 262 | 263 | ```elixir 264 | iex> get_person!(1) 265 | %Person{id: 1} 266 | 267 | iex> get_person!(999) 268 | ** (Ecto.NoResultsError) 269 | 270 | iex> get_person!(1, preloads: [:address]) 271 | %Person{ 272 | id: 1, 273 | address: %Address{} 274 | } 275 | ``` 276 | 277 | #### get_person_by 278 | 279 | Fetches a single `%Person{}` from the data store where the attributes match the 280 | given values. 281 | 282 | ```elixir 283 | iex> get_person_by(%{name: "Chuck Norris"}) 284 | %Person{name: "Chuck Norris"} 285 | 286 | iex> get_person_by(%{name: "Doesn't Exist"}) 287 | nil 288 | ``` 289 | 290 | #### get_person_by! 291 | 292 | Fetches a single `%Person{}` from the data store where the attributes match the 293 | given values. Raises an `Ecto.NoResultsError` if the record does not exist 294 | 295 | ```elixir 296 | iex> get_person_by!(%{name: "Chuck Norris"}) 297 | %Person{name: "Chuck Norris"} 298 | 299 | iex> get_person_by!(%{name: "Doesn't Exist"}) 300 | ** (Ecto.NoResultsError) 301 | ``` 302 | 303 | #### update_person 304 | 305 | Updates a given %Person{} with the given attributes, returns an `:ok`/`:error` tuple. 306 | 307 | ```elixir 308 | iex> update_person(%Person{id: 1}, %{name: "New Person"}) 309 | {:ok, %Person{id: 1, name: "New Person"}} 310 | 311 | iex> update_person(%Person{id: 1}, %{invalid: "invalid"}) 312 | {:error, %Ecto.Changeset} 313 | ``` 314 | 315 | #### update_person! 316 | 317 | Updates a given %Person{} with the given attributes, returns a %Person{} or raises `Ecto.InvalidChangesetError`. 318 | 319 | ```elixir 320 | iex> update_person!(%Person{id: 1}, %{name: "New Person"}) 321 | %Person{id: 1, name: "New Person"} 322 | 323 | iex> update_person!(%Person{id: 1}, %{invalid: "invalid"}) 324 | ** (Ecto.InvalidChangesetError) 325 | ``` 326 | 327 | Caveats 328 | ------- 329 | This is not meant to be used as a wrapper for all the Repo functions within a context. Not all callbacks defined in Ecto.Repo are generated. `EctoResource` should be used to help reduce boilerplate code and tests for general CRUD operations. 330 | 331 | It may be the case that `EctoResource` needs to evolve and provide slightly more functionality/flexibility in the future. However, the general focus is reducing boilerplate code. 332 | """ 333 | 334 | alias __MODULE__ 335 | alias EctoResource.Helpers 336 | alias EctoResource.OptionParser 337 | alias EctoResource.ResourceFunctions 338 | 339 | @doc """ 340 | Macro to import `EctoResource.using_repo/2` 341 | 342 | ## Examples 343 | use EctoResource 344 | """ 345 | defmacro __using__(_) do 346 | quote do 347 | import EctoResource, only: [using_repo: 2] 348 | end 349 | end 350 | 351 | @doc """ 352 | Macro to define schema access within a given `Ecto.Repo` 353 | 354 | ## Examples 355 | using_repo(Repo) do 356 | resource(Schema) 357 | end 358 | """ 359 | defmacro using_repo(repo, do: block) do 360 | quote do 361 | Module.register_attribute(__MODULE__, :repo, []) 362 | Module.put_attribute(__MODULE__, :repo, unquote(repo)) 363 | Module.register_attribute(__MODULE__, :resources, accumulate: true) 364 | import EctoResource, only: [resource: 2, resource: 1] 365 | unquote(block) 366 | def __resource__(:resources), do: @resources 367 | Module.delete_attribute(__MODULE__, :resources) 368 | Module.delete_attribute(__MODULE__, :repo) 369 | end 370 | end 371 | 372 | @doc """ 373 | Macro to define CRUD methods for the given `Ecto.Repo` in the using module. 374 | 375 | ## Examples 376 | using(Repo) do 377 | resource(Schema) 378 | end 379 | 380 | using(Repo) do 381 | resource(Schema, suffix: false) 382 | end 383 | 384 | using(Repo) do 385 | resource(Schema, only: [:get]) 386 | end 387 | 388 | using(Repo) do 389 | resource(Schema, except: [:delete]) 390 | end 391 | 392 | using(Repo) do 393 | resource(Schema, :read) 394 | end 395 | 396 | using(Repo) do 397 | resource(Schema, :write) 398 | end 399 | 400 | using(Repo) do 401 | resource(Schema, :delete) 402 | end 403 | """ 404 | # credo:disable-for-next-line 405 | defmacro resource(schema, options \\ []) do 406 | # credo:disable-for-next-line 407 | quote bind_quoted: [schema: schema, options: options] do 408 | suffix = OptionParser.create_suffix(schema, options) 409 | schema_name = Helpers.schema_name(schema) 410 | resources = OptionParser.parse(suffix, options) 411 | descriptions = Helpers.resource_descriptions(resources) 412 | 413 | Module.put_attribute(__MODULE__, :resources, {@repo, schema, descriptions}) 414 | 415 | Enum.each(resources, fn {action, %{name: name}} -> 416 | case action do 417 | :all -> 418 | @doc """ 419 | Fetches all #{schema_name} entries from the data store. 420 | 421 | ## Examples 422 | #{name}() 423 | [%#{schema_name}{id: 123}] 424 | 425 | #{name}(preloads: [:relation]) 426 | [%#{schema_name}{id: 123, relation: %Relation{}}] 427 | 428 | #{name}(order_by: [desc: :id]) 429 | [%#{schema_name}{id: 2}, %#{schema_name}{id: 1}] 430 | 431 | #{name}(preloads: [:relation], order_by: [desc: :id]) 432 | [ 433 | %#{schema_name}{ 434 | id: 2, 435 | relation: %Relation{} 436 | }, 437 | %#{schema_name}{ 438 | id: 1, 439 | relation: %Relation{} 440 | } 441 | ] 442 | """ 443 | @spec unquote(name)(keyword(list())) :: list(Ecto.Schema.t()) 444 | def unquote(name)(options \\ []) do 445 | ResourceFunctions.all(@repo, unquote(schema), options) 446 | end 447 | 448 | :change -> 449 | @doc """ 450 | Creates a #{schema_name} changeset from an existing schema struct. 451 | 452 | #{name}(%#{schema_name}{}, %{}) 453 | 454 | #Ecto.Changeset< 455 | action: nil, 456 | changes: %{}, 457 | errors: [], 458 | data: ##{schema_name}<>, 459 | valid?: true 460 | > 461 | 462 | #{name}(%#{schema_name}{}, []) 463 | 464 | #Ecto.Changeset< 465 | action: nil, 466 | changes: %{}, 467 | errors: [], 468 | data: ##{schema_name}<>, 469 | valid?: true 470 | > 471 | 472 | """ 473 | @spec unquote(name)(Ecto.Schema.t(), map() | Keyword.t()) :: Ecto.Changeset.t() 474 | def unquote(name)(changeable, changes) do 475 | ResourceFunctions.change(unquote(schema), changeable, changes) 476 | end 477 | 478 | :changeset -> 479 | @doc """ 480 | Creates a blank changeset. 481 | 482 | changeset() 483 | 484 | #Ecto.Changeset< 485 | action: nil, 486 | changes: %{}, 487 | errors: [], 488 | data: ##{schema_name}<>, 489 | valid?: true 490 | > 491 | """ 492 | @spec unquote(name)() :: Ecto.Changeset.t() 493 | def unquote(name)() do 494 | ResourceFunctions.changeset(unquote(schema)) 495 | end 496 | 497 | :create -> 498 | @doc """ 499 | Inserts a #{schema_name} with the given attributes in the data store. 500 | 501 | ## Examples 502 | #{name}(%{}) 503 | {:ok, %#{schema_name}{}} 504 | 505 | #{name}([]) 506 | {:ok, %#{schema_name}{}} 507 | 508 | #{name}(%{invalid: "invalid"}) 509 | {:error, %Ecto.Changeset{}} 510 | """ 511 | @spec unquote(name)(map() | Keyword.t()) :: 512 | {:ok, Ecto.Schema.t()} | {:error, Ecto.Changeset.t()} 513 | def unquote(name)(attributes) do 514 | ResourceFunctions.create(@repo, unquote(schema), attributes) 515 | end 516 | 517 | :create! -> 518 | @doc """ 519 | Same as create_#{suffix}/1 but returns the struct or raises if the changeset is invalid. 520 | 521 | ## Examples 522 | #{name}(%{}) 523 | %#{schema_name}{} 524 | 525 | #{name}([]) 526 | %#{schema_name}{} 527 | 528 | #{name}(%{invalid: "invalid"}) 529 | ** (Ecto.InvalidChangesetError) 530 | """ 531 | @spec unquote(name)(map() | Keyword.t()) :: 532 | Ecto.Schema.t() | Ecto.InvalidChangesetError 533 | def unquote(name)(attributes) do 534 | ResourceFunctions.create!(@repo, unquote(schema), attributes) 535 | end 536 | 537 | :delete -> 538 | @doc """ 539 | Deletes a given %#{schema_name}{} from the data store. 540 | 541 | ## Examples 542 | #{name}(%#{schema_name}{id: 123}) 543 | {:ok, %#{schema_name}{id: 123}} 544 | 545 | #{name}(%#{schema_name}{id: 456}) 546 | {:error, %Ecto.Changeset{}} 547 | 548 | """ 549 | @spec unquote(name)(Ecto.Schema.t()) :: 550 | {:ok, Ecto.Schema.t()} | {:error, Ecto.Changeset.t()} 551 | def unquote(name)(struct) do 552 | ResourceFunctions.delete(@repo, struct) 553 | end 554 | 555 | :delete! -> 556 | @doc """ 557 | Same as delete_#{suffix}/1 but returns the struct or raises if the changeset is invalid. 558 | 559 | ## Examples 560 | #{name}(%#{schema_name}{id: 123}) 561 | %#{schema_name}{id: 123} 562 | 563 | #{name}(%#{schema_name}{id: 456}) 564 | ** (Ecto.StaleEntryError) 565 | """ 566 | def unquote(name)(struct) do 567 | ResourceFunctions.delete!(@repo, struct) 568 | end 569 | 570 | :get -> 571 | @doc """ 572 | Fetches a single #{schema_name} from the data store where the primary key matches the given id. 573 | 574 | ## Examples 575 | #{name}(123) 576 | %#{schema_name}{id: 123} 577 | 578 | #{name}(456) 579 | nil 580 | 581 | #{name}(123, preloads: [:relation]) 582 | %#{schema_name}{ 583 | id: 1, 584 | relation: %Relation{} 585 | } 586 | """ 587 | @spec unquote(name)(String.t() | integer(), keyword(list())) :: Ecto.Schema.t() | nil 588 | def unquote(name)(id, options \\ []) do 589 | ResourceFunctions.get(@repo, unquote(schema), id, options) 590 | end 591 | 592 | :get! -> 593 | @doc """ 594 | Same as get_#{suffix}/2 but raises Ecto.NoResultsError if no record was found. 595 | 596 | ## Examples 597 | #{name}(123) 598 | %#{schema_name}{id: 123} 599 | 600 | #{name}(456) 601 | ** (Ecto.NoResultsError) 602 | 603 | #{name}(123, preloads: [:relation]) 604 | %#{schema_name}{ 605 | id: 1, 606 | relation: %Relation{} 607 | } 608 | """ 609 | def unquote(name)(id, options \\ []) do 610 | ResourceFunctions.get!(@repo, unquote(schema), id, options) 611 | end 612 | 613 | :get_by -> 614 | @doc """ 615 | Fetches a single result from the query. 616 | 617 | Returns nil if no result was found. Raises if more than one entry. 618 | 619 | ## Examples 620 | #{name}(name: "Some Name") 621 | %#{schema_name}{name: "Some Name"} 622 | 623 | #{name}(%{name: "Some Name"}) 624 | %#{schema_name}{name: "Some Name"} 625 | 626 | #{name}(name: "Missing") 627 | nil 628 | """ 629 | def unquote(name)(attributes, options \\ []) do 630 | ResourceFunctions.get_by(@repo, unquote(schema), attributes, options) 631 | end 632 | 633 | :get_by! -> 634 | @doc """ 635 | Similar to get_by/2 but raises Ecto.NoResultsError if no record was found. 636 | 637 | Raises if more than one entry. 638 | 639 | ## Examples 640 | #{name}(name: "Some Name") 641 | %#{schema_name}{name: "Some Name"} 642 | 643 | #{name}(%{name: "Some Name"}) 644 | %#{schema_name}{name: "Some Name"} 645 | 646 | #{name}(name: "Missing") 647 | ** (Ecto.NoResultsError) 648 | """ 649 | def unquote(name)(attributes, options \\ []) do 650 | ResourceFunctions.get_by!(@repo, unquote(schema), attributes, options) 651 | end 652 | 653 | :update -> 654 | @doc """ 655 | Updates a %#{schema_name}{} with the given attributes. 656 | 657 | ## Examples 658 | #{name}(%#{schema_name}{id: 123}, %{attribute: "updated attribute"}) 659 | {:ok, %#{schema_name}{id: 123, attribute: "updated attribute"}} 660 | 661 | #{name}(%#{schema_name}{id: 123}, attribute: "updated attribute") 662 | {:ok, %#{schema_name}{id: 123, attribute: "updated attribute"}} 663 | 664 | #{name}(%#{schema_name}{id: 123}, %{}, force: true) 665 | {:ok, %#{schema_name}{id: 123, attribute: "updated attribute"}} 666 | 667 | #{name}(%#{schema_name}{id: 123}, %{}, prefix: "my_prefix") 668 | {:ok, %#{schema_name}{id: 123, attribute: "updated attribute"}} 669 | 670 | #{name}(%#{schema_name}{id: 123}, %{invalid: "invalid"}) 671 | {:error, %Ecto.Changeset{}} 672 | """ 673 | @spec unquote(name)(Ecto.Schema.t(), map() | Keyword.t()) :: 674 | {:ok, Ecto.Schema.t()} | {:error, Ecto.Changeset.t()} 675 | def unquote(name)(struct, attributes) do 676 | ResourceFunctions.update(@repo, unquote(schema), struct, attributes) 677 | end 678 | 679 | @doc """ 680 | Same as update_#{suffix}/2 returns a %#{schema_name}{} or raises if the changeset is invalid. 681 | 682 | ## Examples 683 | #{name}(%#{schema_name}{id: 123}, %{attribute: "updated attribute"}) 684 | %#{schema_name}{id: 123, attribute: "updated attribute"} 685 | 686 | #{name}(%#{schema_name}{id: 123}, %{}, force: true) 687 | %#{schema_name}{id: 123, attribute: "updated attribute"} 688 | 689 | #{name}(%#{schema_name}{id: 123}, %{}, prefix: "my_prefix") 690 | %#{schema_name}{id: 123, attribute: "updated attribute"} 691 | 692 | #{name}(%#{schema_name}{id: 123}, %{invalid: "invalid"}) 693 | ** (Ecto.InvalidChangesetError) 694 | """ 695 | 696 | :update! -> 697 | @spec unquote(name)(Ecto.Schema.t(), map() | Keyword.t()) :: 698 | Ecto.Schema.t() | Ecto.InvalidChangesetError 699 | def unquote(name)(struct, attributes) do 700 | ResourceFunctions.update!(@repo, unquote(schema), struct, attributes) 701 | end 702 | 703 | _ -> 704 | nil 705 | end 706 | end) 707 | end 708 | end 709 | end 710 | -------------------------------------------------------------------------------- /lib/helpers.ex: -------------------------------------------------------------------------------- 1 | defmodule EctoResource.Helpers do 2 | @moduledoc false 3 | 4 | @spec underscore_module_name(module) :: String.t() 5 | def underscore_module_name(module) do 6 | module 7 | |> Macro.underscore() 8 | |> String.split("/") 9 | |> List.last() 10 | end 11 | 12 | @spec resource_descriptions(term()) :: list(String.t()) 13 | def resource_descriptions(resources) do 14 | resources 15 | |> Map.values() 16 | |> Enum.map(& &1.description) 17 | end 18 | 19 | @spec schema_name(module()) :: String.t() 20 | def schema_name(schema) do 21 | schema 22 | |> Macro.to_string() 23 | |> String.split(".") 24 | |> List.last() 25 | end 26 | end 27 | -------------------------------------------------------------------------------- /lib/mix/tasks/ecto_resource/resources.ex: -------------------------------------------------------------------------------- 1 | defmodule Mix.Tasks.EctoResource.Resources do 2 | @moduledoc """ 3 | Task to list the resources defined by `EctoResource` within a context module. 4 | 5 | ## Examples 6 | 7 | $ mix ecto_resource.resources MyApp.MyContext 8 | 9 | Within the context Account, the following resource functions have been generated: 10 | 11 | User using the repo Repo: 12 | - Accounts.all_users/1 13 | - Accounts.change_user/1 14 | - Accounts.create_user/1 15 | - Accounts.create_user!/1 16 | - Accounts.delete_user/1 17 | - Accounts.delete_user!/1 18 | - Accounts.get_user/2 19 | - Accounts.get_user!/2 20 | - Accounts.update_user/2 21 | - Accounts.update_user!/2 22 | """ 23 | 24 | use Mix.Task 25 | require Logger 26 | 27 | @doc """ 28 | Run the task to list the resources. 29 | 30 | ## Examples 31 | iex> 32 | """ 33 | @spec run(list()) :: any() 34 | def run([]) do 35 | Logger.error(""" 36 | 37 | This task must be called with a context that uses `EctoResource` 38 | 39 | $ mix ecto_resource.resources MyApp.MyContext 40 | """) 41 | end 42 | 43 | def run(contexts) do 44 | Mix.Task.run("compile", []) 45 | Enum.each(contexts, &print_context/1) 46 | end 47 | 48 | @spec print_context(module()) :: any() 49 | defp print_context(context) do 50 | context 51 | |> resources() 52 | |> Enum.each(fn {repo, resource, functions} -> 53 | Logger.info(""" 54 | 55 | Within the context #{context}, the following resource functions have been generated: 56 | 57 | #{resource} using the repo #{repo}: 58 | #{format_functions(context, functions)} 59 | 60 | """) 61 | end) 62 | end 63 | 64 | @spec format_functions(atom(), any()) :: binary() 65 | defp format_functions(context, functions) do 66 | Enum.map_join(functions, "\n", fn f -> "- #{context}.#{f}" end) 67 | end 68 | 69 | @spec resources(module()) :: any() 70 | defp resources(context) do 71 | context_module = Module.concat([context]) 72 | 73 | context_module.__resource__(:resources) 74 | end 75 | end 76 | -------------------------------------------------------------------------------- /lib/option_parser.ex: -------------------------------------------------------------------------------- 1 | defmodule EctoResource.OptionParser do 2 | @moduledoc false 3 | 4 | alias EctoResource.Helpers 5 | 6 | @functions [ 7 | {"all", 1}, 8 | {"change", 1}, 9 | {"changeset", 0}, 10 | {"create!", 1}, 11 | {"create", 1}, 12 | {"delete!", 1}, 13 | {"delete", 1}, 14 | {"get!", 2}, 15 | {"get", 2}, 16 | {"get_by!", 2}, 17 | {"get_by", 2}, 18 | {"update!", 2}, 19 | {"update", 2} 20 | ] 21 | 22 | @spec parse(String.t(), list() | atom()) :: map() 23 | 24 | def parse(suffix, []) do 25 | Enum.reduce(@functions, %{}, fn {function, arity}, acc -> 26 | Map.put(acc, String.to_atom(function), %{ 27 | name: function_name(function, suffix), 28 | description: function_description(function, arity, suffix) 29 | }) 30 | end) 31 | end 32 | 33 | def parse(suffix, :read), do: parse(suffix, only: [:all, :get, :get!, :get_by, :get_by!]) 34 | 35 | def parse(suffix, :read_write) do 36 | parse(suffix, 37 | only: [ 38 | :all, 39 | :get, 40 | :get!, 41 | :get_by, 42 | :get_by!, 43 | :change, 44 | :changeset, 45 | :create, 46 | :create!, 47 | :update, 48 | :update! 49 | ] 50 | ) 51 | end 52 | 53 | def parse(suffix, options) do 54 | @functions 55 | |> filter_functions(options) 56 | |> Enum.reduce(%{}, fn {function, arity}, acc -> 57 | Map.put(acc, String.to_atom(function), %{ 58 | name: function_name(function, suffix), 59 | description: function_description(function, arity, suffix) 60 | }) 61 | end) 62 | end 63 | 64 | @spec create_suffix(module, list()) :: String.t() 65 | def create_suffix(schema, options) when is_list(options) do 66 | case Keyword.get(options, :suffix) do 67 | false -> "" 68 | manual when is_binary(manual) -> manual 69 | _ -> Helpers.underscore_module_name(schema) 70 | end 71 | end 72 | 73 | def create_suffix(schema, _), do: Helpers.underscore_module_name(schema) 74 | 75 | defp function_name(function, ""), do: String.to_atom(function) 76 | defp function_name("all", suffix), do: String.to_atom("all_" <> Inflex.pluralize(suffix)) 77 | 78 | defp function_name("get_by", suffix) do 79 | String.to_atom("get_#{suffix}_by") 80 | end 81 | 82 | defp function_name("get_by!", suffix) do 83 | String.to_atom("get_#{suffix}_by!") 84 | end 85 | 86 | defp function_name("changeset", suffix) do 87 | String.to_atom("#{suffix}_changeset") 88 | end 89 | 90 | defp function_name(function, suffix) do 91 | str = 92 | case function =~ ~r/!/ do 93 | true -> String.replace_suffix(function, "!", "") <> "_" <> suffix <> "!" 94 | false -> function <> "_" <> suffix 95 | end 96 | 97 | String.to_atom(str) 98 | end 99 | 100 | defp function_description(function, arity, "") do 101 | function <> "/" <> Integer.to_string(arity) 102 | end 103 | 104 | defp function_description("all", arity, suffix) do 105 | "all_" <> Inflex.pluralize(suffix) <> "/" <> Integer.to_string(arity) 106 | end 107 | 108 | defp function_description("get_by", arity, suffix) do 109 | arity = Integer.to_string(arity) 110 | "get_" <> suffix <> "_by" <> "/" <> arity 111 | end 112 | 113 | defp function_description("get_by!", arity, suffix) do 114 | arity = Integer.to_string(arity) 115 | "get_" <> suffix <> "_by!" <> "/" <> arity 116 | end 117 | 118 | defp function_description("changeset", arity, suffix) do 119 | arity = Integer.to_string(arity) 120 | suffix <> "_changeset" <> "/" <> arity 121 | end 122 | 123 | defp function_description(function, arity, suffix) do 124 | arity = Integer.to_string(arity) 125 | 126 | case function =~ ~r/!/ do 127 | true -> String.replace_suffix(function, "!", "") <> "_" <> suffix <> "!" <> "/" <> arity 128 | false -> function <> "_" <> suffix <> "/" <> arity 129 | end 130 | end 131 | 132 | defp filter_functions(functions, options) when is_list(options) do 133 | filter_functions(functions, Enum.into(options, %{})) 134 | end 135 | 136 | defp filter_functions(functions, %{except: excluded_functions}) do 137 | Enum.reject(functions, fn {function, _} -> 138 | function = String.to_atom(function) 139 | Enum.member?(excluded_functions, function) 140 | end) 141 | end 142 | 143 | defp filter_functions(functions, %{only: included_functions}) do 144 | Enum.filter(functions, fn {function, _} -> 145 | function = String.to_atom(function) 146 | Enum.member?(included_functions, function) 147 | end) 148 | end 149 | 150 | defp filter_functions(functions, _), do: functions 151 | end 152 | -------------------------------------------------------------------------------- /lib/resource_functions.ex: -------------------------------------------------------------------------------- 1 | defmodule EctoResource.ResourceFunctions do 2 | @moduledoc false 3 | import Ecto.Query 4 | 5 | @spec change(module, Ecto.Schema.t(), map() | Keyword.t()) :: Ecto.Changeset.t() 6 | 7 | def change(schema, changeable, changes) when is_map(changes) do 8 | schema.changeset(changeable, changes) 9 | end 10 | 11 | def change(schema, changeable, changes) when is_list(changes) do 12 | change(schema, changeable, Enum.into(changes, %{})) 13 | end 14 | 15 | @spec changeset(module()) :: Ecto.Changeset.t() 16 | def changeset(schema) do 17 | schema 18 | |> struct() 19 | |> schema.changeset(%{}) 20 | end 21 | 22 | @spec create(Ecto.Repo.t(), module, map() | Keyword.t()) :: 23 | {:ok, Ecto.Schema.t()} | {:error, Ecto.Changeset.t()} 24 | 25 | def create(repo, schema, attributes) when is_map(attributes) do 26 | schema 27 | |> struct() 28 | |> schema.changeset(attributes) 29 | |> repo.insert([]) 30 | end 31 | 32 | def create(repo, schema, attributes) when is_list(attributes) do 33 | create(repo, schema, Enum.into(attributes, %{})) 34 | end 35 | 36 | @spec create!(Ecto.Repo.t(), module, map() | Keyword.t()) :: Ecto.Schema.t() 37 | 38 | def create!(repo, schema, attributes) when is_map(attributes) do 39 | schema 40 | |> struct() 41 | |> schema.changeset(attributes) 42 | |> repo.insert!([]) 43 | end 44 | 45 | def create!(repo, schema, attributes) when is_list(attributes) do 46 | create!(repo, schema, Enum.into(attributes, %{})) 47 | end 48 | 49 | @spec delete(Ecto.Repo.t(), Ecto.Schema.t()) :: 50 | {:ok, Ecto.Schema.t()} | {:error, Ecto.Changeset.t()} 51 | 52 | def delete(repo, deletable) do 53 | repo.delete(deletable, []) 54 | end 55 | 56 | @spec delete!(Ecto.Repo.t(), Ecto.Schema.t()) :: Ecto.Schema.t() 57 | 58 | def delete!(repo, deletable) do 59 | repo.delete!(deletable, []) 60 | end 61 | 62 | @spec get(Ecto.Repo.t(), module, term(), term()) :: Ecto.Schema.t() | nil 63 | 64 | def get(repo, schema, id, options \\ []) do 65 | preloads = Keyword.get(options, :preloads, []) 66 | 67 | schema 68 | |> preload(^preloads) 69 | |> repo.get(id, []) 70 | end 71 | 72 | @spec get!(Ecto.Repo.t(), module, term(), term()) :: Ecto.Schema.t() 73 | 74 | def get!(repo, schema, id, options \\ []) do 75 | preloads = Keyword.get(options, :preloads, []) 76 | 77 | schema 78 | |> preload(^preloads) 79 | |> repo.get!(id, []) 80 | end 81 | 82 | @spec get_by(Ecto.Repo.t(), Ecto.Queryable.t(), Keyword.t() | map(), Keyword.t()) :: 83 | Ecto.Schema.t() | nil 84 | 85 | def get_by(repo, schema, attributes, options \\ []) do 86 | preloads = Keyword.get(options, :preloads, []) 87 | 88 | schema 89 | |> preload(^preloads) 90 | |> repo.get_by(attributes, options) 91 | end 92 | 93 | @spec get_by!(Ecto.Repo.t(), Ecto.Queryable.t(), Keyword.t() | map(), Keyword.t()) :: 94 | Ecto.Schema.t() 95 | 96 | def get_by!(repo, schema, attributes, options \\ []) do 97 | preloads = Keyword.get(options, :preloads, []) 98 | 99 | schema 100 | |> preload(^preloads) 101 | |> repo.get_by!(attributes, options) 102 | end 103 | 104 | @spec all(Ecto.Repo.t(), module, term()) :: list(Ecto.Schema.t()) 105 | 106 | def all(repo, schema, options \\ []) do 107 | options 108 | |> Keyword.take([:preloads, :order_by, :where, :limit, :offset]) 109 | |> Enum.reduce(schema, fn 110 | {:preloads, preloads}, query -> preload(query, ^preloads) 111 | {:order_by, order_by}, query -> order_by(query, ^order_by) 112 | {:where, where}, query -> where(query, ^where) 113 | {:limit, limit}, query -> limit(query, ^limit) 114 | {:offset, offset}, query -> offset(query, ^offset) 115 | _, query -> query 116 | end) 117 | |> repo.all([]) 118 | end 119 | 120 | @spec update(Ecto.Repo.t(), module, Ecto.Schema.t(), map() | Keyword.t()) :: 121 | {:ok, Ecto.Schema.t()} | {:error, Ecto.Changeset.t()} 122 | 123 | def update(repo, schema, updateable, attributes) when is_map(attributes) do 124 | updateable 125 | |> schema.changeset(attributes) 126 | |> repo.update([]) 127 | end 128 | 129 | def update(repo, schema, updateable, attributes) when is_list(attributes) do 130 | update(repo, schema, updateable, Enum.into(attributes, %{})) 131 | end 132 | 133 | @spec update!(Ecto.Repo.t(), module, Ecto.Schema.t(), map() | Keyword.t()) :: Ecto.Schema.t() 134 | 135 | def update!(repo, schema, updateable, attributes) when is_map(attributes) do 136 | updateable 137 | |> schema.changeset(attributes) 138 | |> repo.update!([]) 139 | end 140 | 141 | def update!(repo, schema, updateable, attributes) when is_list(attributes) do 142 | update!(repo, schema, updateable, Enum.into(attributes, %{})) 143 | end 144 | end 145 | -------------------------------------------------------------------------------- /lib/test_repo.ex: -------------------------------------------------------------------------------- 1 | defmodule EctoResource.TestRepo do 2 | @moduledoc false 3 | use Ecto.Repo, 4 | otp_app: :ecto_resource, 5 | adapter: Ecto.Adapters.Postgres 6 | end 7 | -------------------------------------------------------------------------------- /mix.exs: -------------------------------------------------------------------------------- 1 | defmodule EctoResource.MixProject do 2 | use Mix.Project 3 | 4 | def project do 5 | [ 6 | aliases: aliases(), 7 | app: :ecto_resource, 8 | deps: deps(), 9 | description: description(), 10 | dialyzer: [ 11 | ignore_warnings: ".dialyzer_ignore.exs", 12 | plt_file: {:no_warn, "priv/plts/dialyzer.plt"}, 13 | flags: [:error_handling, :unknown], 14 | # Error out when an ignore rule is no longer useful so we can remove it 15 | list_unused_filters: true, 16 | plt_add_apps: [:mix] 17 | ], 18 | docs: [ 19 | main: "readme", 20 | extras: ["README.md"], 21 | api_reference: false 22 | ], 23 | elixir: "~> 1.8", 24 | elixirc_paths: elixirc_paths(Mix.env()), 25 | package: package(), 26 | start_permanent: Mix.env() == :prod, 27 | version: "1.4.0" 28 | ] 29 | end 30 | 31 | # Specifies which paths to compile per environment. 32 | defp elixirc_paths(:test), do: ["lib", "test/support"] 33 | defp elixirc_paths(_), do: ["lib"] 34 | 35 | defp aliases do 36 | [ 37 | credo: "credo --strict", 38 | check: ["credo", "dialyzer", "cmd MIX_ENV=test mix test"], 39 | test: ["ecto.create --quiet", "ecto.migrate", "test"] 40 | ] 41 | end 42 | 43 | defp description do 44 | """ 45 | A simple module to clear up the boilerplate of CRUD resources in Phoenix context files. 46 | """ 47 | end 48 | 49 | defp package do 50 | [ 51 | files: ["lib", "mix.exs", "README*", "LICENSE*"], 52 | licenses: ["Apache-2.0"], 53 | links: %{"GitHub" => "https://github.com/testdouble/ecto_resource"}, 54 | source_url: "https://github.com/testdouble/ecto_resource" 55 | ] 56 | end 57 | 58 | # Run "mix help compile.app" to learn about applications. 59 | def application do 60 | [extra_applications: [:logger]] 61 | end 62 | 63 | # Run "mix help deps" to learn about dependencies. 64 | defp deps do 65 | [ 66 | {:credo, "~> 1.7", only: [:dev, :test], runtime: false}, 67 | {:dialyxir, "~> 1.4", only: [:dev, :test], runtime: false}, 68 | {:ecto_sql, "~> 3.12"}, 69 | {:ex_doc, "~> 0.34", only: :dev, runtime: false}, 70 | {:inflex, "~> 2.1"}, 71 | {:mox, "~> 1.0", only: :test}, 72 | {:postgrex, ">= 0.19.3", only: [:test]} 73 | ] 74 | end 75 | end 76 | -------------------------------------------------------------------------------- /mix.lock: -------------------------------------------------------------------------------- 1 | %{ 2 | "bunt": {:hex, :bunt, "1.0.0", "081c2c665f086849e6d57900292b3a161727ab40431219529f13c4ddcf3e7a44", [:mix], [], "hexpm", "dc5f86aa08a5f6fa6b8096f0735c4e76d54ae5c9fa2c143e5a1fc7c1cd9bb6b5"}, 3 | "credo": {:hex, :credo, "1.7.10", "6e64fe59be8da5e30a1b96273b247b5cf1cc9e336b5fd66302a64b25749ad44d", [:mix], [{:bunt, "~> 0.2.1 or ~> 1.0", [hex: :bunt, repo: "hexpm", optional: false]}, {:file_system, "~> 0.2 or ~> 1.0", [hex: :file_system, repo: "hexpm", optional: false]}, {:jason, "~> 1.0", [hex: :jason, repo: "hexpm", optional: false]}], "hexpm", "71fbc9a6b8be21d993deca85bf151df023a3097b01e09a2809d460348561d8cd"}, 4 | "db_connection": {:hex, :db_connection, "2.7.0", "b99faa9291bb09892c7da373bb82cba59aefa9b36300f6145c5f201c7adf48ec", [:mix], [{:telemetry, "~> 0.4 or ~> 1.0", [hex: :telemetry, repo: "hexpm", optional: false]}], "hexpm", "dcf08f31b2701f857dfc787fbad78223d61a32204f217f15e881dd93e4bdd3ff"}, 5 | "decimal": {:hex, :decimal, "2.2.0", "df3d06bb9517e302b1bd265c1e7f16cda51547ad9d99892049340841f3e15836", [:mix], [], "hexpm", "af8daf87384b51b7e611fb1a1f2c4d4876b65ef968fa8bd3adf44cff401c7f21"}, 6 | "dialyxir": {:hex, :dialyxir, "1.4.5", "ca1571ac18e0f88d4ab245f0b60fa31ff1b12cbae2b11bd25d207f865e8ae78a", [:mix], [{:erlex, ">= 0.2.7", [hex: :erlex, repo: "hexpm", optional: false]}], "hexpm", "b0fb08bb8107c750db5c0b324fa2df5ceaa0f9307690ee3c1f6ba5b9eb5d35c3"}, 7 | "earmark_parser": {:hex, :earmark_parser, "1.4.41", "ab34711c9dc6212dda44fcd20ecb87ac3f3fce6f0ca2f28d4a00e4154f8cd599", [:mix], [], "hexpm", "a81a04c7e34b6617c2792e291b5a2e57ab316365c2644ddc553bb9ed863ebefa"}, 8 | "ecto": {:hex, :ecto, "3.12.4", "267c94d9f2969e6acc4dd5e3e3af5b05cdae89a4d549925f3008b2b7eb0b93c3", [:mix], [{:decimal, "~> 2.0", [hex: :decimal, repo: "hexpm", optional: false]}, {:jason, "~> 1.0", [hex: :jason, repo: "hexpm", optional: true]}, {:telemetry, "~> 0.4 or ~> 1.0", [hex: :telemetry, repo: "hexpm", optional: false]}], "hexpm", "ef04e4101688a67d061e1b10d7bc1fbf00d1d13c17eef08b71d070ff9188f747"}, 9 | "ecto_sql": {:hex, :ecto_sql, "3.12.1", "c0d0d60e85d9ff4631f12bafa454bc392ce8b9ec83531a412c12a0d415a3a4d0", [:mix], [{:db_connection, "~> 2.4.1 or ~> 2.5", [hex: :db_connection, repo: "hexpm", optional: false]}, {:ecto, "~> 3.12", [hex: :ecto, repo: "hexpm", optional: false]}, {:myxql, "~> 0.7", [hex: :myxql, repo: "hexpm", optional: true]}, {:postgrex, "~> 0.19 or ~> 1.0", [hex: :postgrex, repo: "hexpm", optional: true]}, {:tds, "~> 2.1.1 or ~> 2.2", [hex: :tds, repo: "hexpm", optional: true]}, {:telemetry, "~> 0.4.0 or ~> 1.0", [hex: :telemetry, repo: "hexpm", optional: false]}], "hexpm", "aff5b958a899762c5f09028c847569f7dfb9cc9d63bdb8133bff8a5546de6bf5"}, 10 | "erlex": {:hex, :erlex, "0.2.7", "810e8725f96ab74d17aac676e748627a07bc87eb950d2b83acd29dc047a30595", [:mix], [], "hexpm", "3ed95f79d1a844c3f6bf0cea61e0d5612a42ce56da9c03f01df538685365efb0"}, 11 | "ex_doc": {:hex, :ex_doc, "0.34.2", "13eedf3844ccdce25cfd837b99bea9ad92c4e511233199440488d217c92571e8", [:mix], [{:earmark_parser, "~> 1.4.39", [hex: :earmark_parser, repo: "hexpm", optional: false]}, {:makeup_c, ">= 0.1.0", [hex: :makeup_c, repo: "hexpm", optional: true]}, {:makeup_elixir, "~> 0.14 or ~> 1.0", [hex: :makeup_elixir, repo: "hexpm", optional: false]}, {:makeup_erlang, "~> 0.1 or ~> 1.0", [hex: :makeup_erlang, repo: "hexpm", optional: false]}, {:makeup_html, ">= 0.1.0", [hex: :makeup_html, repo: "hexpm", optional: true]}], "hexpm", "5ce5f16b41208a50106afed3de6a2ed34f4acfd65715b82a0b84b49d995f95c1"}, 12 | "file_system": {:hex, :file_system, "1.0.1", "79e8ceaddb0416f8b8cd02a0127bdbababe7bf4a23d2a395b983c1f8b3f73edd", [:mix], [], "hexpm", "4414d1f38863ddf9120720cd976fce5bdde8e91d8283353f0e31850fa89feb9e"}, 13 | "inflex": {:hex, :inflex, "2.1.0", "a365cf0821a9dacb65067abd95008ca1b0bb7dcdd85ae59965deef2aa062924c", [:mix], [], "hexpm", "14c17d05db4ee9b6d319b0bff1bdf22aa389a25398d1952c7a0b5f3d93162dd8"}, 14 | "jason": {:hex, :jason, "1.4.4", "b9226785a9aa77b6857ca22832cffa5d5011a667207eb2a0ad56adb5db443b8a", [:mix], [{:decimal, "~> 1.0 or ~> 2.0", [hex: :decimal, repo: "hexpm", optional: true]}], "hexpm", "c5eb0cab91f094599f94d55bc63409236a8ec69a21a67814529e8d5f6cc90b3b"}, 15 | "makeup": {:hex, :makeup, "1.2.1", "e90ac1c65589ef354378def3ba19d401e739ee7ee06fb47f94c687016e3713d1", [:mix], [{:nimble_parsec, "~> 1.4", [hex: :nimble_parsec, repo: "hexpm", optional: false]}], "hexpm", "d36484867b0bae0fea568d10131197a4c2e47056a6fbe84922bf6ba71c8d17ce"}, 16 | "makeup_elixir": {:hex, :makeup_elixir, "1.0.0", "74bb8348c9b3a51d5c589bf5aebb0466a84b33274150e3b6ece1da45584afc82", [:mix], [{:makeup, "~> 1.0", [hex: :makeup, repo: "hexpm", optional: false]}, {:nimble_parsec, "~> 1.2.3 or ~> 1.3", [hex: :nimble_parsec, repo: "hexpm", optional: false]}], "hexpm", "49159b7d7d999e836bedaf09dcf35ca18b312230cf901b725a64f3f42e407983"}, 17 | "makeup_erlang": {:hex, :makeup_erlang, "1.0.1", "c7f58c120b2b5aa5fd80d540a89fdf866ed42f1f3994e4fe189abebeab610839", [:mix], [{:makeup, "~> 1.0", [hex: :makeup, repo: "hexpm", optional: false]}], "hexpm", "8a89a1eeccc2d798d6ea15496a6e4870b75e014d1af514b1b71fa33134f57814"}, 18 | "mox": {:hex, :mox, "1.2.0", "a2cd96b4b80a3883e3100a221e8adc1b98e4c3a332a8fc434c39526babafd5b3", [:mix], [{:nimble_ownership, "~> 1.0", [hex: :nimble_ownership, repo: "hexpm", optional: false]}], "hexpm", "c7b92b3cc69ee24a7eeeaf944cd7be22013c52fcb580c1f33f50845ec821089a"}, 19 | "nimble_ownership": {:hex, :nimble_ownership, "1.0.0", "3f87744d42c21b2042a0aa1d48c83c77e6dd9dd357e425a038dd4b49ba8b79a1", [:mix], [], "hexpm", "7c16cc74f4e952464220a73055b557a273e8b1b7ace8489ec9d86e9ad56cb2cc"}, 20 | "nimble_parsec": {:hex, :nimble_parsec, "1.4.0", "51f9b613ea62cfa97b25ccc2c1b4216e81df970acd8e16e8d1bdc58fef21370d", [:mix], [], "hexpm", "9c565862810fb383e9838c1dd2d7d2c437b3d13b267414ba6af33e50d2d1cf28"}, 21 | "postgrex": {:hex, :postgrex, "0.19.3", "a0bda6e3bc75ec07fca5b0a89bffd242ca209a4822a9533e7d3e84ee80707e19", [:mix], [{:db_connection, "~> 2.1", [hex: :db_connection, repo: "hexpm", optional: false]}, {:decimal, "~> 1.5 or ~> 2.0", [hex: :decimal, repo: "hexpm", optional: false]}, {:jason, "~> 1.0", [hex: :jason, repo: "hexpm", optional: true]}, {:table, "~> 0.1.0", [hex: :table, repo: "hexpm", optional: true]}], "hexpm", "d31c28053655b78f47f948c85bb1cf86a9c1f8ead346ba1aa0d0df017fa05b61"}, 22 | "telemetry": {:hex, :telemetry, "1.3.0", "fedebbae410d715cf8e7062c96a1ef32ec22e764197f70cda73d82778d61e7a2", [:rebar3], [], "hexpm", "7015fc8919dbe63764f4b4b87a95b7c0996bd539e0d499be6ec9d7f3875b79e6"}, 23 | } 24 | -------------------------------------------------------------------------------- /priv/test_repo/migrations/20200410023114_create_people.exs: -------------------------------------------------------------------------------- 1 | defmodule EctoResource.TestRepo.Migrations.CreatePeople do 2 | use Ecto.Migration 3 | 4 | def change do 5 | create table(:people) do 6 | add(:first_name, :string, null: false) 7 | add(:last_name, :string, null: false) 8 | add(:age, :integer, null: false) 9 | end 10 | end 11 | end 12 | -------------------------------------------------------------------------------- /test/ecto_resource/defaults_test.exs: -------------------------------------------------------------------------------- 1 | defmodule EctoResource.DefaultsTestContext.People do 2 | @moduledoc false 3 | 4 | alias EctoResource.TestRepo 5 | alias EctoResource.TestSchema.Person 6 | 7 | use EctoResource 8 | 9 | using_repo TestRepo do 10 | resource(Person) 11 | end 12 | end 13 | 14 | defmodule EctoResource.DefaultsTest do 15 | use EctoResource.RepoCase 16 | 17 | alias EctoResource.TestSchema.Person 18 | alias EctoResource.DefaultsTestContext.People 19 | 20 | @person_attributes %{ 21 | first_name: "Test", 22 | last_name: "Person", 23 | age: 42 24 | } 25 | 26 | @updated_person_attributes %{ 27 | first_name: "Updated Test", 28 | last_name: "Updated Person", 29 | age: 33 30 | } 31 | 32 | describe "all" do 33 | test "it returns all the records" do 34 | person = struct(Person, @person_attributes) 35 | Repo.insert(person) 36 | result = People.all_people() 37 | [first_person] = result 38 | 39 | assert length(result) == 1 40 | assert first_person.first_name == person.first_name 41 | end 42 | 43 | test "it filters based on 'where' option " do 44 | person = struct(Person, @person_attributes) 45 | Repo.insert(person) 46 | result = People.all_people(where: [age: 40]) 47 | assert [] == result 48 | result = People.all_people(where: [age: 42]) 49 | assert length(result) == 1 50 | end 51 | end 52 | 53 | describe "change" do 54 | test "it returns a changeset with changes" do 55 | person = %Person{ 56 | first_name: "Initial", 57 | last_name: "Value", 58 | age: 0 59 | } 60 | 61 | %{changes: changes} = People.change_person(person, @person_attributes) 62 | 63 | assert changes == @person_attributes 64 | end 65 | 66 | test "it accpets keyword lists" do 67 | person = %Person{ 68 | first_name: "Initial", 69 | last_name: "Value", 70 | age: 0 71 | } 72 | 73 | person_attributes_list = Map.to_list(@person_attributes) 74 | 75 | %{changes: changes} = People.change_person(person, person_attributes_list) 76 | 77 | assert changes == @person_attributes 78 | end 79 | end 80 | 81 | describe "changeset" do 82 | test "it returns an empty changeset" do 83 | expected_changeset = Person.changeset(%Person{}, %{}) 84 | assert People.person_changeset() == expected_changeset 85 | end 86 | end 87 | 88 | describe "create" do 89 | test "with valid attributbes, it creates a new record" do 90 | {:ok, person} = People.create_person(@person_attributes) 91 | 92 | assert Repo.all(Person) == [person] 93 | end 94 | 95 | test "with invalid attributes, it returns an error tuple with a changeset" do 96 | assert {:error, %Ecto.Changeset{}} = People.create_person(%{}) 97 | end 98 | 99 | test "accepts keyword lists" do 100 | person_attributes_list = Map.to_list(@person_attributes) 101 | {:ok, person} = People.create_person(person_attributes_list) 102 | 103 | assert Repo.all(Person) == [person] 104 | end 105 | end 106 | 107 | describe "create!" do 108 | test "with valid attributes, it creates a new record" do 109 | person = People.create_person!(@person_attributes) 110 | 111 | assert Repo.all(Person) == [person] 112 | end 113 | 114 | test "with invalid attributes, it raises an error" do 115 | assert_raise Ecto.InvalidChangesetError, fn -> 116 | People.create_person!(%{}) 117 | end 118 | end 119 | 120 | test "it accepts keyword lists" do 121 | person_attributes_list = Map.to_list(@person_attributes) 122 | person = People.create_person!(person_attributes_list) 123 | 124 | assert Repo.all(Person) == [person] 125 | end 126 | end 127 | 128 | describe "delete" do 129 | test "with an existing record, it deletes a given record" do 130 | {:ok, person} = 131 | %Person{} 132 | |> Person.changeset(@person_attributes) 133 | |> Repo.insert() 134 | 135 | assert Repo.all(Person) == [person] 136 | 137 | People.delete_person(person) 138 | 139 | assert Repo.all(Person) == [] 140 | end 141 | 142 | test "with a non-existent record, it raises an error" do 143 | {:ok, person} = 144 | %Person{} 145 | |> Person.changeset(@person_attributes) 146 | |> Repo.insert() 147 | 148 | Repo.delete(person) 149 | 150 | assert_raise Ecto.StaleEntryError, fn -> 151 | People.delete_person(person) 152 | end 153 | end 154 | end 155 | 156 | describe "delete!" do 157 | test "with an existing record it deletes the given record" do 158 | {:ok, person} = 159 | %Person{} 160 | |> Person.changeset(@person_attributes) 161 | |> Repo.insert() 162 | 163 | assert Repo.all(Person) == [person] 164 | 165 | People.delete_person!(person) 166 | 167 | assert Repo.all(Person) == [] 168 | end 169 | 170 | test "with a non-existent record, it raises an error" do 171 | {:ok, person} = 172 | %Person{} 173 | |> Person.changeset(@person_attributes) 174 | |> Repo.insert() 175 | 176 | Repo.delete(person) 177 | 178 | assert_raise Ecto.StaleEntryError, fn -> 179 | People.delete_person!(person) 180 | end 181 | end 182 | end 183 | 184 | describe "get" do 185 | test "with an existing record, it returns the schema" do 186 | {:ok, person} = 187 | Person 188 | |> struct(@person_attributes) 189 | |> Repo.insert() 190 | 191 | assert person == People.get_person(person.id) 192 | end 193 | 194 | test "with a non-existent record, it returns nil" do 195 | assert nil == People.get_person(999) 196 | end 197 | end 198 | 199 | describe "get!" do 200 | test "with an existing record, it returns the schema" do 201 | {:ok, person} = 202 | Person 203 | |> struct(@person_attributes) 204 | |> Repo.insert() 205 | 206 | assert person == People.get_person!(person.id) 207 | end 208 | 209 | test "with a non-existent record, it raises an error" do 210 | assert_raise Ecto.NoResultsError, fn -> 211 | People.get_person!(999) 212 | end 213 | end 214 | end 215 | 216 | describe "get_by" do 217 | test "with an existing record, it returns a single schema matching the criteria" do 218 | {:ok, person} = 219 | Person 220 | |> struct(@person_attributes) 221 | |> Repo.insert() 222 | 223 | assert People.get_person_by(age: @person_attributes.age) == person 224 | end 225 | 226 | test "with a non-existent record, it returns nil" do 227 | assert People.get_person_by(age: @person_attributes.age) == nil 228 | end 229 | 230 | test "it accepts maps" do 231 | {:ok, person} = 232 | Person 233 | |> struct(@person_attributes) 234 | |> Repo.insert() 235 | 236 | assert People.get_person_by(%{age: @person_attributes.age}) == person 237 | end 238 | end 239 | 240 | describe "get_by!" do 241 | test "with an existing record, it returns a single schema, matching the criteria" do 242 | {:ok, person} = 243 | Person 244 | |> struct(@person_attributes) 245 | |> Repo.insert() 246 | 247 | assert People.get_person_by!(age: @person_attributes.age) == person 248 | end 249 | 250 | test "it accepts maps" do 251 | {:ok, person} = 252 | Person 253 | |> struct(@person_attributes) 254 | |> Repo.insert() 255 | 256 | assert People.get_person_by!(%{age: @person_attributes.age}) == person 257 | end 258 | end 259 | 260 | describe "update" do 261 | test "with valid attributes, it updates the values" do 262 | {:ok, person} = 263 | Person 264 | |> struct(@person_attributes) 265 | |> Repo.insert() 266 | 267 | {:ok, updated_person} = People.update_person(person, @updated_person_attributes) 268 | 269 | assert person.id == updated_person.id 270 | assert person.first_name != updated_person.first_name 271 | assert person.last_name != updated_person.last_name 272 | assert person.age != updated_person.age 273 | end 274 | 275 | test "with invalid attributes, it returns an error changeset tuple" do 276 | {:ok, person} = 277 | Person 278 | |> struct(@person_attributes) 279 | |> Repo.insert() 280 | 281 | assert {:error, changeset} = 282 | People.update_person(person, %{first_name: nil, last_name: nil, age: nil}) 283 | 284 | refute changeset.valid? 285 | end 286 | 287 | test "accepts keyword lists" do 288 | {:ok, person} = 289 | Person 290 | |> struct(@person_attributes) 291 | |> Repo.insert() 292 | 293 | {:ok, updated_person} = 294 | People.update_person(person, Map.to_list(@updated_person_attributes)) 295 | 296 | assert person.id == updated_person.id 297 | assert person.first_name != updated_person.first_name 298 | assert person.last_name != updated_person.last_name 299 | assert person.age != updated_person.age 300 | end 301 | end 302 | 303 | describe "update!" do 304 | test "with valid attributes, it updates the values" do 305 | {:ok, person} = 306 | Person 307 | |> struct(@person_attributes) 308 | |> Repo.insert() 309 | 310 | updated_person = People.update_person!(person, @updated_person_attributes) 311 | 312 | assert person.id == updated_person.id 313 | assert person.first_name != updated_person.first_name 314 | assert person.last_name != updated_person.last_name 315 | assert person.age != updated_person.age 316 | end 317 | 318 | test "with invalid attributes, it returns an error changeset tuple" do 319 | {:ok, person} = 320 | Person 321 | |> struct(@person_attributes) 322 | |> Repo.insert() 323 | 324 | assert_raise Ecto.InvalidChangesetError, fn -> 325 | People.update_person!(person, %{first_name: nil, last_name: nil, age: nil}) 326 | end 327 | end 328 | 329 | test "accepts keyword lists" do 330 | {:ok, person} = 331 | Person 332 | |> struct(@person_attributes) 333 | |> Repo.insert() 334 | 335 | updated_person = People.update_person!(person, Map.to_list(@updated_person_attributes)) 336 | 337 | assert person.id == updated_person.id 338 | assert person.first_name != updated_person.first_name 339 | assert person.last_name != updated_person.last_name 340 | assert person.age != updated_person.age 341 | end 342 | end 343 | end 344 | -------------------------------------------------------------------------------- /test/ecto_resource/except_filter_test.exs: -------------------------------------------------------------------------------- 1 | defmodule EctoResource.ExceptFilterTestContext.People do 2 | @moduledoc false 3 | 4 | alias EctoResource.TestRepo 5 | alias EctoResource.TestSchema.Person 6 | 7 | use EctoResource 8 | 9 | using_repo TestRepo do 10 | resource(Person, except: [:change, :changeset]) 11 | end 12 | end 13 | 14 | defmodule EctoResource.ExceptFilterTest do 15 | use EctoResource.RepoCase 16 | 17 | alias EctoResource.TestSchema.Person 18 | alias EctoResource.ExceptFilterTestContext.People 19 | 20 | @person_attributes %{ 21 | first_name: "Test", 22 | last_name: "Person", 23 | age: 42 24 | } 25 | 26 | @updated_person_attributes %{ 27 | first_name: "Updated Test", 28 | last_name: "Updated Person", 29 | age: 33 30 | } 31 | 32 | describe "all" do 33 | test "it returns all the records" do 34 | person = struct(Person, @person_attributes) 35 | 36 | Repo.insert(person) 37 | [first_person] = results = People.all_people() 38 | 39 | assert length(results) == 1 40 | assert person.first_name == first_person.first_name 41 | end 42 | end 43 | 44 | describe "change" do 45 | test "doesn't create a change function" do 46 | person = %Person{ 47 | first_name: "Initial", 48 | last_name: "Value", 49 | age: 0 50 | } 51 | 52 | assert_raise UndefinedFunctionError, fn -> 53 | apply(People, :change_person, [person, @person_attributes]) 54 | end 55 | end 56 | end 57 | 58 | describe "changeset" do 59 | test "it doesn't create a changeset function" do 60 | assert_raise UndefinedFunctionError, fn -> 61 | apply(People, :person_changeset, []) 62 | end 63 | end 64 | end 65 | 66 | describe "create" do 67 | test "with valid attributbes, it creates a new record" do 68 | {:ok, person} = People.create_person(@person_attributes) 69 | 70 | assert Repo.all(Person) == [person] 71 | end 72 | 73 | test "with invalid attributes, it returns an error tuple with a changeset" do 74 | assert {:error, %Ecto.Changeset{}} = People.create_person(%{}) 75 | end 76 | end 77 | 78 | describe "create!" do 79 | test "whith valid attributes, it creates a new record" do 80 | person = People.create_person!(@person_attributes) 81 | 82 | assert Repo.all(Person) == [person] 83 | end 84 | 85 | test "with invalid attributes, it raises an error" do 86 | assert_raise Ecto.InvalidChangesetError, fn -> 87 | People.create_person!(%{}) 88 | end 89 | end 90 | end 91 | 92 | describe "delete" do 93 | test "with an existing record, it deletes a given record" do 94 | {:ok, person} = 95 | %Person{} 96 | |> Person.changeset(@person_attributes) 97 | |> Repo.insert() 98 | 99 | assert Repo.all(Person) == [person] 100 | 101 | People.delete_person(person) 102 | 103 | assert Repo.all(Person) == [] 104 | end 105 | 106 | test "with a non-existent record, it raises an error" do 107 | {:ok, person} = 108 | %Person{} 109 | |> Person.changeset(@person_attributes) 110 | |> Repo.insert() 111 | 112 | Repo.delete(person) 113 | 114 | assert_raise Ecto.StaleEntryError, fn -> 115 | People.delete_person(person) 116 | end 117 | end 118 | end 119 | 120 | describe "delete!" do 121 | test "with an existing record it deletes the given record" do 122 | {:ok, person} = 123 | %Person{} 124 | |> Person.changeset(@person_attributes) 125 | |> Repo.insert() 126 | 127 | assert Repo.all(Person) == [person] 128 | 129 | People.delete_person!(person) 130 | 131 | assert Repo.all(Person) == [] 132 | end 133 | 134 | test "with a non-existent record, it raises an error" do 135 | {:ok, person} = 136 | %Person{} 137 | |> Person.changeset(@person_attributes) 138 | |> Repo.insert() 139 | 140 | Repo.delete(person) 141 | 142 | assert_raise Ecto.StaleEntryError, fn -> 143 | People.delete_person!(person) 144 | end 145 | end 146 | end 147 | 148 | describe "get" do 149 | test "with an existing record, it returns the schema" do 150 | {:ok, person} = 151 | Person 152 | |> struct(@person_attributes) 153 | |> Repo.insert() 154 | 155 | assert person == People.get_person(person.id) 156 | end 157 | 158 | test "with a non-existent record, it returns nil" do 159 | assert nil == People.get_person(999) 160 | end 161 | end 162 | 163 | describe "get!" do 164 | test "with an existing record, it returns the schema" do 165 | {:ok, person} = 166 | Person 167 | |> struct(@person_attributes) 168 | |> Repo.insert() 169 | 170 | assert person == People.get_person!(person.id) 171 | end 172 | 173 | test "with a non-existent record, it raises an error" do 174 | assert_raise Ecto.NoResultsError, fn -> 175 | People.get_person!(999) 176 | end 177 | end 178 | end 179 | 180 | describe "get_by" do 181 | test "with an existing record, it returns a single schema matching the criteria" do 182 | {:ok, person} = 183 | Person 184 | |> struct(@person_attributes) 185 | |> Repo.insert() 186 | 187 | assert People.get_person_by(age: @person_attributes.age) == person 188 | end 189 | 190 | test "with a non-existent record, it returns nil" do 191 | assert People.get_person_by(age: @person_attributes.age) == nil 192 | end 193 | end 194 | 195 | describe "get_by!" do 196 | test "with an existing record, it returns a single schema, matching the criteria" do 197 | {:ok, person} = 198 | Person 199 | |> struct(@person_attributes) 200 | |> Repo.insert() 201 | 202 | assert People.get_person_by!(age: @person_attributes.age) == person 203 | end 204 | end 205 | 206 | describe "update" do 207 | test "with valid attributes, it updates the values" do 208 | {:ok, person} = 209 | Person 210 | |> struct(@person_attributes) 211 | |> Repo.insert() 212 | 213 | {:ok, updated_person} = People.update_person(person, @updated_person_attributes) 214 | 215 | assert person.id == updated_person.id 216 | assert person.first_name != updated_person.first_name 217 | assert person.last_name != updated_person.last_name 218 | assert person.age != updated_person.age 219 | end 220 | 221 | test "with invalid attributes, it returns an error changeset tuple" do 222 | {:ok, person} = 223 | Person 224 | |> struct(@person_attributes) 225 | |> Repo.insert() 226 | 227 | assert {:error, changeset} = 228 | People.update_person(person, %{first_name: nil, last_name: nil, age: nil}) 229 | 230 | refute changeset.valid? 231 | end 232 | end 233 | 234 | describe "update!" do 235 | test "with valid attributes, it updates the values" do 236 | {:ok, person} = 237 | Person 238 | |> struct(@person_attributes) 239 | |> Repo.insert() 240 | 241 | updated_person = People.update_person!(person, @updated_person_attributes) 242 | 243 | assert person.id == updated_person.id 244 | assert person.first_name != updated_person.first_name 245 | assert person.last_name != updated_person.last_name 246 | assert person.age != updated_person.age 247 | end 248 | 249 | test "with invalid attributes, it returns an error changeset tuple" do 250 | {:ok, person} = 251 | Person 252 | |> struct(@person_attributes) 253 | |> Repo.insert() 254 | 255 | assert_raise Ecto.InvalidChangesetError, fn -> 256 | People.update_person!(person, %{first_name: nil, last_name: nil, age: nil}) 257 | end 258 | end 259 | end 260 | end 261 | -------------------------------------------------------------------------------- /test/ecto_resource/only_filter_test.exs: -------------------------------------------------------------------------------- 1 | defmodule EctoResource.OnlyFilterTestContext.People do 2 | @moduledoc false 3 | 4 | alias EctoResource.TestRepo 5 | alias EctoResource.TestSchema.Person 6 | 7 | use EctoResource 8 | 9 | using_repo TestRepo do 10 | resource(Person, only: [:all, :change]) 11 | end 12 | end 13 | 14 | defmodule EctoResource.OnlyFilterTest do 15 | use EctoResource.RepoCase 16 | 17 | alias EctoResource.TestSchema.Person 18 | alias EctoResource.OnlyFilterTestContext.People 19 | 20 | @person_attributes %{ 21 | first_name: "Test", 22 | last_name: "Person", 23 | age: 42 24 | } 25 | 26 | @updated_person_attributes %{ 27 | first_name: "Updated Test", 28 | last_name: "Updated Person", 29 | age: 33 30 | } 31 | 32 | describe "all" do 33 | test "it returns all the records" do 34 | person = struct(Person, @person_attributes) 35 | 36 | Repo.insert(person) 37 | [first_person] = results = People.all_people() 38 | 39 | assert length(results) == 1 40 | assert person.first_name == first_person.first_name 41 | end 42 | end 43 | 44 | describe "change" do 45 | test "it returns a changeset with changes" do 46 | person = %Person{ 47 | first_name: "Initial", 48 | last_name: "Value", 49 | age: 0 50 | } 51 | 52 | %{changes: changes} = People.change_person(person, @person_attributes) 53 | 54 | assert changes == @person_attributes 55 | end 56 | end 57 | 58 | describe "changeset" do 59 | test "it doesn't create a changeset function" do 60 | assert_raise UndefinedFunctionError, fn -> 61 | apply(People, :person_changeset, []) 62 | end 63 | end 64 | end 65 | 66 | describe "create" do 67 | test "it doesn't create a create function" do 68 | assert_raise UndefinedFunctionError, fn -> 69 | apply(People, :create_person, [@person_attributes]) 70 | end 71 | end 72 | end 73 | 74 | describe "create!" do 75 | test "it doesn't create a create! function" do 76 | assert_raise UndefinedFunctionError, fn -> 77 | apply(People, :create_person!, [@person_attributes]) 78 | end 79 | end 80 | end 81 | 82 | describe "delete" do 83 | test "doesn't create a delete function" do 84 | {:ok, person} = 85 | %Person{} 86 | |> Person.changeset(@person_attributes) 87 | |> Repo.insert() 88 | 89 | assert_raise UndefinedFunctionError, fn -> 90 | apply(People, :delete_person, [person]) 91 | end 92 | end 93 | end 94 | 95 | describe "delete!" do 96 | test "doesn't create a delete! function" do 97 | {:ok, person} = 98 | %Person{} 99 | |> Person.changeset(@person_attributes) 100 | |> Repo.insert() 101 | 102 | assert_raise UndefinedFunctionError, fn -> 103 | apply(People, :delete_person!, [person]) 104 | end 105 | end 106 | end 107 | 108 | describe "get" do 109 | test "it doesn't create a get function" do 110 | {:ok, person} = 111 | Person 112 | |> struct(@person_attributes) 113 | |> Repo.insert() 114 | 115 | assert_raise UndefinedFunctionError, fn -> 116 | apply(People, :get_person, [person.id]) 117 | end 118 | end 119 | end 120 | 121 | describe "get!" do 122 | test "it doesn't create a get! function" do 123 | {:ok, person} = 124 | Person 125 | |> struct(@person_attributes) 126 | |> Repo.insert() 127 | 128 | assert_raise UndefinedFunctionError, fn -> 129 | apply(People, :get_person!, [person.id]) 130 | end 131 | end 132 | end 133 | 134 | describe "get_by" do 135 | test "doesn't create a get_by function" do 136 | assert_raise UndefinedFunctionError, fn -> 137 | apply(People, :get_person_by, age: @person_attributes.age) 138 | end 139 | end 140 | end 141 | 142 | describe "get_by!" do 143 | test "doesn't create a get_by! function" do 144 | assert_raise UndefinedFunctionError, fn -> 145 | apply(People, :get_person_by!, age: @person_attributes.age) 146 | end 147 | end 148 | end 149 | 150 | describe "update" do 151 | test "doesn't create an update function" do 152 | {:ok, person} = 153 | Person 154 | |> struct(@person_attributes) 155 | |> Repo.insert() 156 | 157 | assert_raise UndefinedFunctionError, fn -> 158 | apply(People, :update_person, [person, @updated_person_attributes]) 159 | end 160 | end 161 | end 162 | 163 | describe "update!" do 164 | test "doesn't create an update! function" do 165 | {:ok, person} = 166 | Person 167 | |> struct(@person_attributes) 168 | |> Repo.insert() 169 | 170 | assert_raise UndefinedFunctionError, fn -> 171 | apply(People, :update_person!, [person, @updated_person_attributes]) 172 | end 173 | end 174 | end 175 | end 176 | -------------------------------------------------------------------------------- /test/ecto_resource/option_parser_test.exs: -------------------------------------------------------------------------------- 1 | defmodule EctoResource.OptionParserTest do 2 | use ExUnit.Case 3 | 4 | alias EctoResource.OptionParser 5 | 6 | describe "parse/1" do 7 | test "when given the an empty list" do 8 | assert OptionParser.parse("suffix", []) == %{ 9 | all: %{ 10 | name: :all_suffixes, 11 | description: "all_suffixes/1" 12 | }, 13 | change: %{ 14 | name: :change_suffix, 15 | description: "change_suffix/1" 16 | }, 17 | changeset: %{ 18 | name: :suffix_changeset, 19 | description: "suffix_changeset/0" 20 | }, 21 | create: %{ 22 | name: :create_suffix, 23 | description: "create_suffix/1" 24 | }, 25 | create!: %{ 26 | name: :create_suffix!, 27 | description: "create_suffix!/1" 28 | }, 29 | delete: %{ 30 | name: :delete_suffix, 31 | description: "delete_suffix/1" 32 | }, 33 | delete!: %{ 34 | name: :delete_suffix!, 35 | description: "delete_suffix!/1" 36 | }, 37 | get: %{ 38 | name: :get_suffix, 39 | description: "get_suffix/2" 40 | }, 41 | get!: %{ 42 | name: :get_suffix!, 43 | description: "get_suffix!/2" 44 | }, 45 | get_by: %{ 46 | name: :get_suffix_by, 47 | description: "get_suffix_by/2" 48 | }, 49 | get_by!: %{ 50 | name: :get_suffix_by!, 51 | description: "get_suffix_by!/2" 52 | }, 53 | update: %{ 54 | name: :update_suffix, 55 | description: "update_suffix/2" 56 | }, 57 | update!: %{ 58 | name: :update_suffix!, 59 | description: "update_suffix!/2" 60 | } 61 | } 62 | end 63 | 64 | test "when given the only atom and list of operations" do 65 | assert OptionParser.parse("suffix", only: [:create, :update]) == %{ 66 | create: %{ 67 | name: :create_suffix, 68 | description: "create_suffix/1" 69 | }, 70 | update: %{ 71 | name: :update_suffix, 72 | description: "update_suffix/2" 73 | } 74 | } 75 | end 76 | 77 | test "when given the except atom and list of operations" do 78 | assert OptionParser.parse("suffix", except: [:create, :delete!]) == %{ 79 | all: %{ 80 | name: :all_suffixes, 81 | description: "all_suffixes/1" 82 | }, 83 | create!: %{ 84 | name: :create_suffix!, 85 | description: "create_suffix!/1" 86 | }, 87 | change: %{ 88 | name: :change_suffix, 89 | description: "change_suffix/1" 90 | }, 91 | changeset: %{ 92 | name: :suffix_changeset, 93 | description: "suffix_changeset/0" 94 | }, 95 | delete: %{ 96 | name: :delete_suffix, 97 | description: "delete_suffix/1" 98 | }, 99 | get: %{ 100 | name: :get_suffix, 101 | description: "get_suffix/2" 102 | }, 103 | get!: %{ 104 | name: :get_suffix!, 105 | description: "get_suffix!/2" 106 | }, 107 | get_by: %{ 108 | name: :get_suffix_by, 109 | description: "get_suffix_by/2" 110 | }, 111 | get_by!: %{ 112 | name: :get_suffix_by!, 113 | description: "get_suffix_by!/2" 114 | }, 115 | update: %{ 116 | name: :update_suffix, 117 | description: "update_suffix/2" 118 | }, 119 | update!: %{ 120 | name: :update_suffix!, 121 | description: "update_suffix!/2" 122 | } 123 | } 124 | end 125 | 126 | test "when given :read" do 127 | assert OptionParser.parse("suffix", :read) == %{ 128 | all: %{ 129 | name: :all_suffixes, 130 | description: "all_suffixes/1" 131 | }, 132 | get: %{ 133 | name: :get_suffix, 134 | description: "get_suffix/2" 135 | }, 136 | get!: %{ 137 | name: :get_suffix!, 138 | description: "get_suffix!/2" 139 | }, 140 | get_by: %{ 141 | name: :get_suffix_by, 142 | description: "get_suffix_by/2" 143 | }, 144 | get_by!: %{ 145 | name: :get_suffix_by!, 146 | description: "get_suffix_by!/2" 147 | } 148 | } 149 | end 150 | 151 | test "when given :read_write" do 152 | assert OptionParser.parse("suffix", :read_write) == %{ 153 | all: %{ 154 | name: :all_suffixes, 155 | description: "all_suffixes/1" 156 | }, 157 | get: %{ 158 | name: :get_suffix, 159 | description: "get_suffix/2" 160 | }, 161 | get!: %{ 162 | name: :get_suffix!, 163 | description: "get_suffix!/2" 164 | }, 165 | get_by: %{ 166 | name: :get_suffix_by, 167 | description: "get_suffix_by/2" 168 | }, 169 | get_by!: %{ 170 | name: :get_suffix_by!, 171 | description: "get_suffix_by!/2" 172 | }, 173 | change: %{ 174 | name: :change_suffix, 175 | description: "change_suffix/1" 176 | }, 177 | changeset: %{ 178 | name: :suffix_changeset, 179 | description: "suffix_changeset/0" 180 | }, 181 | create: %{ 182 | name: :create_suffix, 183 | description: "create_suffix/1" 184 | }, 185 | create!: %{ 186 | name: :create_suffix!, 187 | description: "create_suffix!/1" 188 | }, 189 | update: %{ 190 | name: :update_suffix, 191 | description: "update_suffix/2" 192 | }, 193 | update!: %{ 194 | name: :update_suffix!, 195 | description: "update_suffix!/2" 196 | } 197 | } 198 | end 199 | 200 | test "when given the except atom and a list of bang functions" do 201 | assert OptionParser.parse("suffix", except: [:create!, :delete!, :get!, :update!]) == %{ 202 | all: %{ 203 | name: :all_suffixes, 204 | description: "all_suffixes/1" 205 | }, 206 | change: %{ 207 | name: :change_suffix, 208 | description: "change_suffix/1" 209 | }, 210 | changeset: %{ 211 | name: :suffix_changeset, 212 | description: "suffix_changeset/0" 213 | }, 214 | create: %{ 215 | name: :create_suffix, 216 | description: "create_suffix/1" 217 | }, 218 | delete: %{ 219 | name: :delete_suffix, 220 | description: "delete_suffix/1" 221 | }, 222 | get: %{ 223 | name: :get_suffix, 224 | description: "get_suffix/2" 225 | }, 226 | get_by: %{ 227 | name: :get_suffix_by, 228 | description: "get_suffix_by/2" 229 | }, 230 | get_by!: %{ 231 | name: :get_suffix_by!, 232 | description: "get_suffix_by!/2" 233 | }, 234 | update: %{ 235 | name: :update_suffix, 236 | description: "update_suffix/2" 237 | } 238 | } 239 | end 240 | 241 | test "when given the only atom and a list of bang functions" do 242 | assert OptionParser.parse("suffix", only: [:create!, :delete!, :get!, :update!]) == %{ 243 | create!: %{ 244 | name: :create_suffix!, 245 | description: "create_suffix!/1" 246 | }, 247 | delete!: %{ 248 | name: :delete_suffix!, 249 | description: "delete_suffix!/1" 250 | }, 251 | get!: %{ 252 | name: :get_suffix!, 253 | description: "get_suffix!/2" 254 | }, 255 | update!: %{ 256 | name: :update_suffix!, 257 | description: "update_suffix!/2" 258 | } 259 | } 260 | end 261 | 262 | test "when given suffix option and other options" do 263 | assert OptionParser.parse("", suffix: false, except: [:create!, :create]) == %{ 264 | all: %{name: :all, description: "all/1"}, 265 | change: %{name: :change, description: "change/1"}, 266 | changeset: %{name: :changeset, description: "changeset/0"}, 267 | delete: %{name: :delete, description: "delete/1"}, 268 | get: %{name: :get, description: "get/2"}, 269 | get_by: %{name: :get_by, description: "get_by/2"}, 270 | get_by!: %{name: :get_by!, description: "get_by!/2"}, 271 | update: %{name: :update, description: "update/2"}, 272 | delete!: %{name: :delete!, description: "delete!/1"}, 273 | get!: %{name: :get!, description: "get!/2"}, 274 | update!: %{name: :update!, description: "update!/2"} 275 | } 276 | end 277 | end 278 | 279 | describe "create_suffix/2" do 280 | defmodule TestSchema do 281 | end 282 | 283 | test "with no options, it returns the schema name lowercased, prefixed with an underscore" do 284 | assert OptionParser.create_suffix(TestSchema, []) == "test_schema" 285 | end 286 | 287 | test "with suffix false option, it returns an empty string" do 288 | assert OptionParser.create_suffix(TestSchema, suffix: false) == "" 289 | end 290 | 291 | test "with suffix false option and other options" do 292 | assert OptionParser.create_suffix(TestSchema, suffix: false, except: [:create!, :create]) == 293 | "" 294 | end 295 | 296 | test "when suffix is set to a string, it returns that string directly" do 297 | assert OptionParser.create_suffix(TestSchema, suffix: "some_thing") == "some_thing" 298 | end 299 | end 300 | end 301 | -------------------------------------------------------------------------------- /test/ecto_resource/read_test.exs: -------------------------------------------------------------------------------- 1 | defmodule EctoResource.ReadTestContext.People do 2 | @moduledoc false 3 | 4 | alias EctoResource.TestRepo 5 | alias EctoResource.TestSchema.Person 6 | 7 | use EctoResource 8 | 9 | using_repo TestRepo do 10 | resource(Person, :read) 11 | end 12 | end 13 | 14 | defmodule EctoResource.ReadTest do 15 | use EctoResource.RepoCase 16 | 17 | alias EctoResource.TestSchema.Person 18 | alias EctoResource.ReadTestContext.People 19 | 20 | @person_attributes %{ 21 | first_name: "Test", 22 | last_name: "Person", 23 | age: 42 24 | } 25 | 26 | @updated_person_attributes %{ 27 | first_name: "Updated Test", 28 | last_name: "Updated Person", 29 | age: 33 30 | } 31 | 32 | describe "all" do 33 | test "it returns all the records" do 34 | person = struct(Person, @person_attributes) 35 | 36 | Repo.insert(person) 37 | [first_person] = results = People.all_people() 38 | 39 | assert length(results) == 1 40 | assert person.first_name == first_person.first_name 41 | end 42 | end 43 | 44 | describe "change" do 45 | test "it doesn't create a change function" do 46 | person = %Person{ 47 | first_name: "Initial", 48 | last_name: "Value", 49 | age: 0 50 | } 51 | 52 | assert_raise UndefinedFunctionError, fn -> 53 | apply(People, :change_person, [person, @person_attributes]) 54 | end 55 | end 56 | end 57 | 58 | describe "changeset" do 59 | test "it doesn't create a changeset function" do 60 | assert_raise UndefinedFunctionError, fn -> 61 | apply(People, :person_changeset, []) 62 | end 63 | end 64 | end 65 | 66 | describe "create" do 67 | test "it doesn't create a create function" do 68 | assert_raise UndefinedFunctionError, fn -> 69 | apply(People, :create_person, [@person_attributes]) 70 | end 71 | end 72 | end 73 | 74 | describe "create!" do 75 | test "it doesn't create a create! function" do 76 | assert_raise UndefinedFunctionError, fn -> 77 | apply(People, :create_person!, [@person_attributes]) 78 | end 79 | end 80 | end 81 | 82 | describe "delete" do 83 | test "it doesn't create a delete function" do 84 | {:ok, person} = 85 | %Person{} 86 | |> Person.changeset(@person_attributes) 87 | |> Repo.insert() 88 | 89 | assert_raise UndefinedFunctionError, fn -> 90 | apply(People, :delete_person, [person]) 91 | end 92 | end 93 | end 94 | 95 | describe "delete!" do 96 | test "it doesn't create a delete! function" do 97 | {:ok, person} = 98 | %Person{} 99 | |> Person.changeset(@person_attributes) 100 | |> Repo.insert() 101 | 102 | assert_raise UndefinedFunctionError, fn -> 103 | apply(People, :delete_person!, [person]) 104 | end 105 | end 106 | end 107 | 108 | describe "get" do 109 | test "with an existing record, it returns the schema" do 110 | {:ok, person} = 111 | Person 112 | |> struct(@person_attributes) 113 | |> Repo.insert() 114 | 115 | assert person == People.get_person(person.id) 116 | end 117 | 118 | test "with a non-existent record, it returns nil" do 119 | assert nil == People.get_person(999) 120 | end 121 | end 122 | 123 | describe "get!" do 124 | test "with an existing record, it returns the schema" do 125 | {:ok, person} = 126 | Person 127 | |> struct(@person_attributes) 128 | |> Repo.insert() 129 | 130 | assert person == People.get_person!(person.id) 131 | end 132 | 133 | test "with a non-existent record, it raises an error" do 134 | assert_raise Ecto.NoResultsError, fn -> 135 | People.get_person!(999) 136 | end 137 | end 138 | end 139 | 140 | describe "get_by" do 141 | test "with an existing record, it returns a single schema matching the criteria" do 142 | {:ok, person} = 143 | Person 144 | |> struct(@person_attributes) 145 | |> Repo.insert() 146 | 147 | assert People.get_person_by(age: @person_attributes.age) == person 148 | end 149 | 150 | test "with a non-existent record, it returns nil" do 151 | assert People.get_person_by(age: @person_attributes.age) == nil 152 | end 153 | end 154 | 155 | describe "get_by!" do 156 | test "with an existing record, it returns a single schema, matching the criteria" do 157 | {:ok, person} = 158 | Person 159 | |> struct(@person_attributes) 160 | |> Repo.insert() 161 | 162 | assert People.get_person_by!(age: @person_attributes.age) == person 163 | end 164 | end 165 | 166 | describe "update" do 167 | test "it doesn't create an update function" do 168 | {:ok, person} = 169 | Person 170 | |> struct(@person_attributes) 171 | |> Repo.insert() 172 | 173 | assert_raise UndefinedFunctionError, fn -> 174 | apply(People, :update_person, [person, @updated_person_attributes]) 175 | end 176 | end 177 | end 178 | 179 | describe "update!" do 180 | test "it doesn't create an update function" do 181 | {:ok, person} = 182 | Person 183 | |> struct(@person_attributes) 184 | |> Repo.insert() 185 | 186 | assert_raise UndefinedFunctionError, fn -> 187 | apply(People, :update_person!, [person, @updated_person_attributes]) 188 | end 189 | end 190 | end 191 | end 192 | -------------------------------------------------------------------------------- /test/ecto_resource/read_write_test.exs: -------------------------------------------------------------------------------- 1 | defmodule EctoResource.ReadWriteContext.People do 2 | @moduledoc false 3 | 4 | alias EctoResource.TestRepo 5 | alias EctoResource.TestSchema.Person 6 | 7 | use EctoResource 8 | 9 | using_repo TestRepo do 10 | resource(Person, :read_write) 11 | end 12 | end 13 | 14 | defmodule EctoResource.ReadWrite do 15 | use EctoResource.RepoCase 16 | 17 | alias EctoResource.TestSchema.Person 18 | alias EctoResource.ReadWriteContext.People 19 | 20 | @person_attributes %{ 21 | first_name: "Test", 22 | last_name: "Person", 23 | age: 42 24 | } 25 | 26 | @updated_person_attributes %{ 27 | first_name: "Updated Test", 28 | last_name: "Updated Person", 29 | age: 33 30 | } 31 | 32 | describe "all" do 33 | test "it returns all the records" do 34 | person = struct(Person, @person_attributes) 35 | 36 | Repo.insert(person) 37 | [first_person] = results = People.all_people() 38 | 39 | assert length(results) == 1 40 | assert person.first_name == first_person.first_name 41 | end 42 | end 43 | 44 | describe "change" do 45 | test "it returns a changeset with changes" do 46 | person = %Person{ 47 | first_name: "Initial", 48 | last_name: "Value", 49 | age: 0 50 | } 51 | 52 | %{changes: changes} = People.change_person(person, @person_attributes) 53 | 54 | assert changes == @person_attributes 55 | end 56 | end 57 | 58 | describe "changeset" do 59 | test "it returns an empty changeset" do 60 | expected_changeset = Person.changeset(%Person{}, %{}) 61 | assert People.person_changeset() == expected_changeset 62 | end 63 | end 64 | 65 | describe "create" do 66 | test "with valid attributbes, it creates a new record" do 67 | {:ok, person} = People.create_person(@person_attributes) 68 | 69 | assert Repo.all(Person) == [person] 70 | end 71 | 72 | test "with invalid attributes, it returns an error tuple with a changeset" do 73 | assert {:error, %Ecto.Changeset{}} = People.create_person(%{}) 74 | end 75 | end 76 | 77 | describe "create!" do 78 | test "whith valid attributes, it creates a new record" do 79 | person = People.create_person!(@person_attributes) 80 | 81 | assert Repo.all(Person) == [person] 82 | end 83 | 84 | test "with invalid attributes, it raises an error" do 85 | assert_raise Ecto.InvalidChangesetError, fn -> 86 | People.create_person!(%{}) 87 | end 88 | end 89 | end 90 | 91 | describe "delete" do 92 | test "it doesn't create a delete method" do 93 | {:ok, person} = 94 | %Person{} 95 | |> Person.changeset(@person_attributes) 96 | |> Repo.insert() 97 | 98 | assert_raise UndefinedFunctionError, fn -> 99 | apply(People, :delete_person, [person]) 100 | end 101 | end 102 | end 103 | 104 | describe "delete!" do 105 | test "doesn't create a delete! method" do 106 | {:ok, person} = 107 | %Person{} 108 | |> Person.changeset(@person_attributes) 109 | |> Repo.insert() 110 | 111 | assert_raise UndefinedFunctionError, fn -> 112 | apply(People, :delete_person!, [person]) 113 | end 114 | end 115 | end 116 | 117 | describe "get" do 118 | test "with an existing record, it returns the schema" do 119 | {:ok, person} = 120 | Person 121 | |> struct(@person_attributes) 122 | |> Repo.insert() 123 | 124 | assert person == People.get_person(person.id) 125 | end 126 | 127 | test "with a non-existent record, it returns nil" do 128 | assert nil == People.get_person(999) 129 | end 130 | end 131 | 132 | describe "get!" do 133 | test "with an existing record, it returns the schema" do 134 | {:ok, person} = 135 | Person 136 | |> struct(@person_attributes) 137 | |> Repo.insert() 138 | 139 | assert person == People.get_person!(person.id) 140 | end 141 | 142 | test "with a non-existent record, it raises an error" do 143 | assert_raise Ecto.NoResultsError, fn -> 144 | People.get_person!(999) 145 | end 146 | end 147 | end 148 | 149 | describe "get_by" do 150 | test "with an existing record, it returns a single schema matching the criteria" do 151 | {:ok, person} = 152 | Person 153 | |> struct(@person_attributes) 154 | |> Repo.insert() 155 | 156 | assert People.get_person_by(age: @person_attributes.age) == person 157 | end 158 | 159 | test "with a non-existent record, it returns nil" do 160 | assert People.get_person_by(age: @person_attributes.age) == nil 161 | end 162 | end 163 | 164 | describe "get_by!" do 165 | test "with an existing record, it returns a single schema, matching the criteria" do 166 | {:ok, person} = 167 | Person 168 | |> struct(@person_attributes) 169 | |> Repo.insert() 170 | 171 | assert People.get_person_by!(age: @person_attributes.age) == person 172 | end 173 | end 174 | 175 | describe "update" do 176 | test "with valid attributes, it updates the values" do 177 | {:ok, person} = 178 | Person 179 | |> struct(@person_attributes) 180 | |> Repo.insert() 181 | 182 | {:ok, updated_person} = People.update_person(person, @updated_person_attributes) 183 | 184 | assert person.id == updated_person.id 185 | assert person.first_name != updated_person.first_name 186 | assert person.last_name != updated_person.last_name 187 | assert person.age != updated_person.age 188 | end 189 | 190 | test "with invalid attributes, it returns an error changeset tuple" do 191 | {:ok, person} = 192 | Person 193 | |> struct(@person_attributes) 194 | |> Repo.insert() 195 | 196 | assert {:error, changeset} = 197 | People.update_person(person, %{first_name: nil, last_name: nil, age: nil}) 198 | 199 | refute changeset.valid? 200 | end 201 | end 202 | 203 | describe "update!" do 204 | test "with valid attributes, it updates the values" do 205 | {:ok, person} = 206 | Person 207 | |> struct(@person_attributes) 208 | |> Repo.insert() 209 | 210 | updated_person = People.update_person!(person, @updated_person_attributes) 211 | 212 | assert person.id == updated_person.id 213 | assert person.first_name != updated_person.first_name 214 | assert person.last_name != updated_person.last_name 215 | assert person.age != updated_person.age 216 | end 217 | 218 | test "with invalid attributes, it returns an error changeset tuple" do 219 | {:ok, person} = 220 | Person 221 | |> struct(@person_attributes) 222 | |> Repo.insert() 223 | 224 | assert_raise Ecto.InvalidChangesetError, fn -> 225 | People.update_person!(person, %{first_name: nil, last_name: nil, age: nil}) 226 | end 227 | end 228 | end 229 | end 230 | -------------------------------------------------------------------------------- /test/ecto_resource/resource_functions_test.exs: -------------------------------------------------------------------------------- 1 | defmodule EctoResource.ResourceFunctionsTestContext.People do 2 | use EctoResource 3 | 4 | alias EctoResource.TestRepo 5 | alias EctoResource.TestSchema.Person 6 | 7 | using_repo TestRepo do 8 | resource(Person) 9 | end 10 | end 11 | 12 | defmodule EctoResource.ResourceFunctionsTest do 13 | use EctoResource.RepoCase 14 | 15 | alias EctoResource.TestSchema.Person 16 | alias EctoResource.ResourceFunctionsTestContext.People 17 | 18 | defp create_person(opts) do 19 | opts = Keyword.merge([first_name: "Test", last_name: "Person", age: 42], opts) 20 | 21 | Person |> struct(opts) |> Repo.insert!() 22 | end 23 | 24 | describe "all/2" do 25 | setup do 26 | michael = create_person(first_name: "Michael", age: 50) 27 | dwight = create_person(first_name: "Dwight", age: 33) 28 | 29 | %{michael: michael, dwight: dwight} 30 | end 31 | 32 | test "returns all records", %{ 33 | michael: michael, 34 | dwight: dwight 35 | } do 36 | people = People.all_people() 37 | 38 | assert michael in people 39 | assert dwight in people 40 | end 41 | 42 | test "returns all records with a where clause", %{ 43 | michael: michael, 44 | dwight: dwight 45 | } do 46 | assert People.all_people(where: [age: 50]) == [michael] 47 | assert People.all_people(where: [age: 33]) == [dwight] 48 | end 49 | 50 | test "returns all records up to limit", %{ 51 | michael: michael, 52 | dwight: dwight 53 | } do 54 | assert People.all_people(limit: 1) == [michael] 55 | assert People.all_people(limit: 2) == [michael, dwight] 56 | end 57 | 58 | test "returns records in order of order_by", %{ 59 | michael: michael, 60 | dwight: dwight 61 | } do 62 | assert People.all_people(order_by: :age) == [dwight, michael] 63 | assert People.all_people(order_by: [desc: :age]) == [michael, dwight] 64 | end 65 | 66 | test "returns records with offset", %{ 67 | dwight: dwight 68 | } do 69 | assert People.all_people(offset: 1) == [dwight] 70 | assert People.all_people(offset: 2) == [] 71 | end 72 | end 73 | end 74 | -------------------------------------------------------------------------------- /test/ecto_resource/without_suffix_test.exs: -------------------------------------------------------------------------------- 1 | defmodule EctoResource.WithoutSuffixTestContext.People do 2 | @moduledoc false 3 | 4 | alias EctoResource.TestRepo 5 | alias EctoResource.TestSchema.Person 6 | 7 | use EctoResource 8 | 9 | using_repo TestRepo do 10 | resource(Person, suffix: false) 11 | end 12 | end 13 | 14 | defmodule EctoResource.WithoutSuffixTest do 15 | use EctoResource.RepoCase 16 | 17 | alias EctoResource.TestSchema.Person 18 | alias EctoResource.WithoutSuffixTestContext.People 19 | 20 | @person_attributes %{ 21 | first_name: "Test", 22 | last_name: "Person", 23 | age: 42 24 | } 25 | 26 | @updated_person_attributes %{ 27 | first_name: "Updated Test", 28 | last_name: "Updated Person", 29 | age: 33 30 | } 31 | 32 | describe "all" do 33 | test "it returns all the records" do 34 | person = struct(Person, @person_attributes) 35 | 36 | Repo.insert(person) 37 | [first_person] = results = People.all() 38 | 39 | assert length(results) == 1 40 | assert person.first_name == first_person.first_name 41 | end 42 | end 43 | 44 | describe "change" do 45 | test "it returns a changeset with changes" do 46 | person = %Person{ 47 | first_name: "Initial", 48 | last_name: "Value", 49 | age: 0 50 | } 51 | 52 | %{changes: changes} = People.change(person, @person_attributes) 53 | 54 | assert changes == @person_attributes 55 | end 56 | end 57 | 58 | describe "changeset" do 59 | test "it returns an empty changeset" do 60 | expected_changeset = Person.changeset(%Person{}, %{}) 61 | assert People.changeset() == expected_changeset 62 | end 63 | end 64 | 65 | describe "create" do 66 | test "with valid attributbes, it creates a new record" do 67 | {:ok, person} = People.create(@person_attributes) 68 | 69 | assert Repo.all(Person) == [person] 70 | end 71 | 72 | test "with invalid attributes, it returns an error tuple with a changeset" do 73 | assert {:error, %Ecto.Changeset{}} = People.create(%{}) 74 | end 75 | end 76 | 77 | describe "create!" do 78 | test "whith valid attributes, it creates a new record" do 79 | person = People.create!(@person_attributes) 80 | 81 | assert Repo.all(Person) == [person] 82 | end 83 | 84 | test "with invalid attributes, it raises an error" do 85 | assert_raise Ecto.InvalidChangesetError, fn -> 86 | People.create!(%{}) 87 | end 88 | end 89 | end 90 | 91 | describe "delete" do 92 | test "with an existing record, it deletes a given record" do 93 | {:ok, person} = 94 | %Person{} 95 | |> Person.changeset(@person_attributes) 96 | |> Repo.insert() 97 | 98 | assert Repo.all(Person) == [person] 99 | 100 | People.delete(person) 101 | 102 | assert Repo.all(Person) == [] 103 | end 104 | 105 | test "with a non-existent record, it raises an error" do 106 | {:ok, person} = 107 | %Person{} 108 | |> Person.changeset(@person_attributes) 109 | |> Repo.insert() 110 | 111 | Repo.delete(person) 112 | 113 | assert_raise Ecto.StaleEntryError, fn -> 114 | People.delete(person) 115 | end 116 | end 117 | end 118 | 119 | describe "delete!" do 120 | test "with an existing record it deletes the given record" do 121 | {:ok, person} = 122 | %Person{} 123 | |> Person.changeset(@person_attributes) 124 | |> Repo.insert() 125 | 126 | assert Repo.all(Person) == [person] 127 | 128 | People.delete!(person) 129 | 130 | assert Repo.all(Person) == [] 131 | end 132 | 133 | test "with a non-existent record, it raises an error" do 134 | {:ok, person} = 135 | %Person{} 136 | |> Person.changeset(@person_attributes) 137 | |> Repo.insert() 138 | 139 | Repo.delete(person) 140 | 141 | assert_raise Ecto.StaleEntryError, fn -> 142 | People.delete!(person) 143 | end 144 | end 145 | end 146 | 147 | describe "get" do 148 | test "with an existing record, it returns the schema" do 149 | {:ok, person} = 150 | Person 151 | |> struct(@person_attributes) 152 | |> Repo.insert() 153 | 154 | assert person == People.get(person.id) 155 | end 156 | 157 | test "with a non-existent record, it returns nil" do 158 | assert nil == People.get(999) 159 | end 160 | end 161 | 162 | describe "get!" do 163 | test "with an existing record, it returns the schema" do 164 | {:ok, person} = 165 | Person 166 | |> struct(@person_attributes) 167 | |> Repo.insert() 168 | 169 | assert person == People.get!(person.id) 170 | end 171 | 172 | test "with a non-existent record, it raises an error" do 173 | assert_raise Ecto.NoResultsError, fn -> 174 | People.get!(999) 175 | end 176 | end 177 | end 178 | 179 | describe "get_by" do 180 | test "with an existing record, it returns a single schema matching the criteria" do 181 | {:ok, person} = 182 | Person 183 | |> struct(@person_attributes) 184 | |> Repo.insert() 185 | 186 | assert People.get_by(age: @person_attributes.age) == person 187 | end 188 | 189 | test "with a non-existent record, it returns nil" do 190 | assert People.get_by(age: @person_attributes.age) == nil 191 | end 192 | end 193 | 194 | describe "get_by!" do 195 | test "with an existing record, it returns a single schema, matching the criteria" do 196 | {:ok, person} = 197 | Person 198 | |> struct(@person_attributes) 199 | |> Repo.insert() 200 | 201 | assert People.get_by!(age: @person_attributes.age) == person 202 | end 203 | end 204 | 205 | describe "update" do 206 | test "with valid attributes, it updates the values" do 207 | {:ok, person} = 208 | Person 209 | |> struct(@person_attributes) 210 | |> Repo.insert() 211 | 212 | {:ok, updated_person} = People.update(person, @updated_person_attributes) 213 | 214 | assert person.id == updated_person.id 215 | assert person.first_name != updated_person.first_name 216 | assert person.last_name != updated_person.last_name 217 | assert person.age != updated_person.age 218 | end 219 | 220 | test "with invalid attributes, it returns an error changeset tuple" do 221 | {:ok, person} = 222 | Person 223 | |> struct(@person_attributes) 224 | |> Repo.insert() 225 | 226 | assert {:error, changeset} = 227 | People.update(person, %{first_name: nil, last_name: nil, age: nil}) 228 | 229 | refute changeset.valid? 230 | end 231 | end 232 | 233 | describe "update!" do 234 | test "with valid attributes, it updates the values" do 235 | {:ok, person} = 236 | Person 237 | |> struct(@person_attributes) 238 | |> Repo.insert() 239 | 240 | updated_person = People.update!(person, @updated_person_attributes) 241 | 242 | assert person.id == updated_person.id 243 | assert person.first_name != updated_person.first_name 244 | assert person.last_name != updated_person.last_name 245 | assert person.age != updated_person.age 246 | end 247 | 248 | test "with invalid attributes, it returns an error changeset tuple" do 249 | {:ok, person} = 250 | Person 251 | |> struct(@person_attributes) 252 | |> Repo.insert() 253 | 254 | assert_raise Ecto.InvalidChangesetError, fn -> 255 | People.update!(person, %{first_name: nil, last_name: nil, age: nil}) 256 | end 257 | end 258 | end 259 | end 260 | -------------------------------------------------------------------------------- /test/helpers_test.exs: -------------------------------------------------------------------------------- 1 | defmodule EctoResource.HelpersTest do 2 | use ExUnit.Case 3 | 4 | alias EctoResource.Helpers 5 | 6 | describe "schema_name/1" do 7 | test "returns the string schema name" do 8 | defmodule MyApp.MySchema do 9 | end 10 | 11 | assert Helpers.schema_name(MyApp.MySchema) == "MySchema" 12 | end 13 | end 14 | end 15 | -------------------------------------------------------------------------------- /test/support/repo_case.ex: -------------------------------------------------------------------------------- 1 | defmodule EctoResource.RepoCase do 2 | use ExUnit.CaseTemplate 3 | 4 | using do 5 | quote do 6 | alias EctoResource.TestRepo, as: Repo 7 | import Ecto 8 | import Ecto.Query 9 | import EctoResource.RepoCase 10 | end 11 | end 12 | 13 | setup tags do 14 | :ok = Ecto.Adapters.SQL.Sandbox.checkout(EctoResource.TestRepo) 15 | 16 | unless tags[:async] do 17 | Ecto.Adapters.SQL.Sandbox.mode(EctoResource.TestRepo, {:shared, self()}) 18 | end 19 | 20 | :ok 21 | end 22 | end 23 | -------------------------------------------------------------------------------- /test/support/test_schema/person.ex: -------------------------------------------------------------------------------- 1 | defmodule EctoResource.TestSchema.Person do 2 | use Ecto.Schema 3 | import Ecto.Changeset 4 | 5 | schema "people" do 6 | field(:first_name, :string) 7 | field(:last_name, :string) 8 | field(:age, :integer) 9 | end 10 | 11 | @doc false 12 | def changeset(person, attrs) do 13 | person 14 | |> cast(attrs, [:first_name, :last_name, :age]) 15 | |> validate_required([:first_name, :last_name, :age]) 16 | end 17 | end 18 | -------------------------------------------------------------------------------- /test/test_helper.exs: -------------------------------------------------------------------------------- 1 | Supervisor.start_link([{EctoResource.TestRepo, []}], 2 | strategy: :one_for_one, 3 | name: EctoResource.Supervisor 4 | ) 5 | 6 | ExUnit.start() 7 | Ecto.Adapters.SQL.Sandbox.mode(EctoResource.TestRepo, :manual) 8 | --------------------------------------------------------------------------------