diff --git a/examples/basic_phoenix_ecto/.formatter.exs b/examples/basic_phoenix_ecto/.formatter.exs new file mode 100644 index 0000000..8a6391c --- /dev/null +++ b/examples/basic_phoenix_ecto/.formatter.exs @@ -0,0 +1,5 @@ +[ + import_deps: [:ecto, :phoenix], + inputs: ["*.{ex,exs}", "priv/*/seeds.exs", "{config,lib,test}/**/*.{ex,exs}"], + subdirectories: ["priv/*/migrations"] +] diff --git a/examples/basic_phoenix_ecto/.gitignore b/examples/basic_phoenix_ecto/.gitignore new file mode 100644 index 0000000..bafd4a1 --- /dev/null +++ b/examples/basic_phoenix_ecto/.gitignore @@ -0,0 +1,34 @@ +# The directory Mix will write compiled artifacts to. +/_build/ + +# If you run "mix test --cover", coverage assets end up here. +/cover/ + +# The directory Mix downloads your dependencies sources to. +/deps/ + +# Where 3rd-party dependencies like ExDoc output generated docs. +/doc/ + +# Ignore .fetch files in case you like to edit your project deps locally. +/.fetch + +# If the VM crashes, it generates a dump, let's ignore it too. +erl_crash.dump + +# Also ignore archive artifacts (built via "mix archive.build"). +*.ez + +# Ignore package tarball (built via "mix hex.build"). +demo-*.tar + +# Ignore assets that are produced by build tools. +/priv/static/assets/ + +# Ignore digested assets cache. +/priv/static/cache_manifest.json + +# In case you use Node.js/npm, you want to ignore these. +npm-debug.log +/assets/node_modules/ + diff --git a/examples/basic_phoenix_ecto/Dockerfile b/examples/basic_phoenix_ecto/Dockerfile new file mode 100644 index 0000000..ab77106 --- /dev/null +++ b/examples/basic_phoenix_ecto/Dockerfile @@ -0,0 +1,89 @@ +# Find eligible builder and runner images on Docker Hub. We use Ubuntu/Debian instead of +# Alpine to avoid DNS resolution issues in production. +# +# https://hub.docker.com/r/hexpm/elixir/tags?page=1&name=ubuntu +# https://hub.docker.com/_/ubuntu?tab=tags +# +# +# This file is based on these images: +# +# - https://hub.docker.com/r/hexpm/elixir/tags - for the build image +# - https://hub.docker.com/_/debian?tab=tags&page=1&name=bullseye-20210902-slim - for the release image +# - https://pkgs.org/ - resource for finding needed packages +# - Ex: hexpm/elixir:1.12.0-erlang-24.0.1-debian-bullseye-20210902-slim +# +ARG BUILDER_IMAGE="hexpm/elixir:1.12.0-erlang-24.0.1-debian-bullseye-20210902-slim" +ARG RUNNER_IMAGE="debian:bullseye-20210902-slim" + +FROM ${BUILDER_IMAGE} as builder + +# install build dependencies +RUN apt-get update -y && apt-get install -y build-essential git \ + && apt-get clean && rm -f /var/lib/apt/lists/*_* + +# prepare build dir +WORKDIR /app + +# install hex + rebar +RUN mix local.hex --force && \ + mix local.rebar --force + +# set build ENV +ENV MIX_ENV="prod" + +# install mix dependencies +COPY mix.exs mix.lock ./ +RUN mix deps.get --only $MIX_ENV +RUN mkdir config + +# copy compile-time config files before we compile dependencies +# to ensure any relevant config change will trigger the dependencies +# to be re-compiled. +COPY config/config.exs config/${MIX_ENV}.exs config/ +RUN mix deps.compile + +COPY priv priv + +# note: if your project uses a tool like https://purgecss.com/, +# which customizes asset compilation based on what it finds in +# your Elixir templates, you will need to move the asset compilation +# step down so that `lib` is available. +COPY assets assets + +# compile assets +RUN mix assets.deploy + +# Compile the release +COPY lib lib + +RUN mix compile + +# Changes to config/runtime.exs don't require recompiling the code +COPY config/runtime.exs config/ + +# COPY rel rel +RUN mix release + +# start a new build stage so that the final image will only contain +# the compiled release and other runtime necessities +FROM ${RUNNER_IMAGE} + +RUN apt-get update -y && apt-get install -y libstdc++6 openssl libncurses5 locales \ + && apt-get clean && rm -f /var/lib/apt/lists/*_* + +# Set the locale +RUN sed -i '/en_US.UTF-8/s/^# //g' /etc/locale.gen && locale-gen + +ENV LANG en_US.UTF-8 +ENV LANGUAGE en_US:en +ENV LC_ALL en_US.UTF-8 + +WORKDIR "/app" +RUN chown nobody /app + +# Only copy the final release from the build stage +COPY --from=builder --chown=nobody:root /app/_build/prod/rel/demo ./ + +USER nobody + +CMD /app/bin/demo start diff --git a/examples/basic_phoenix_ecto/README.md b/examples/basic_phoenix_ecto/README.md new file mode 100644 index 0000000..a5fcab7 --- /dev/null +++ b/examples/basic_phoenix_ecto/README.md @@ -0,0 +1,70 @@ +# Phoenix + Ecto OpenTelemetry Example + +This is a example repository that demo how to setup OpenTelemetry for Phoenix application +with [`opentelemetry_phoenix`][0] and [`opentelemetry_ecto`][1]. + +Here, we are using [`opentelemetry_exporter`][2] to export the traces to [ +OpenTelemetry Collector][3]. The collector in turn export the traces to [Zipkin][4] and [ +Jaeger][5] respectively. + +Additionally, we also include the OpenTelemetry Collector and +`opentelemetry_exporter` configuration to +export the traces to external services like [Honeycomb](https://www.honeycomb.io/) and +[Lightstep](https://lightstep.com/). + +## Getting Stated + +By default, we only configure our OpenTelemetry collector to export traces to +the local Zipkin and Jaeger. + +Assuming you already have Docker and Docker Compose installed: + +1. Run `docker-compose up` to start the Phoenix application, PostgreSQL, + OpenTelemetry Collector, Zipkin and Jaeger. +2. Run migration on another terminal with: + ``` + docker exec -it basic_phoenix_ecto_phoenix_1 /bin/bash ./bin/demo eval 'Demo.Release.migrate()' + ``` +3. Browse to http://localhost:4000. Additionally, you can: + +- Visit http://localhost:4000/posts to see how it works for Phoenix HTML +- Visit http://localhost:4000/users to see how it works for Phoenix LiveView + +4. Visit Zipkin at http://localhost:9411 and hit `Run Query` to look the the sample trace. +5. Visit Jaeger UI at http://localhost:16686, select `demo` under Service and click `Find Trace` to + look at the sample trace. +6. Run `docker-compose down` to destroy the created resources. + +## Different ways to export traces + +In general, there are 2 ways you can export your OpenTelemetry traces. + +- Export to OpenTelemetry Collector, which can then be configured to export to + external services. + + ``` + Application --> OpenTelemetry Collector --> Zipkin + |-----> Jaeger + ``` + +- Export directly to external services that accept OTLP protocol. + + ``` + Application --> External Service + ``` + +For exporting to external services, be sure to checkout their +documentation first. For example: + +- [OpenTelemetry | Honeycomb](https://docs.honeycomb.io/getting-data-in/opentelemetry/) +- [OpenTelemetry Collector | Honeycomb](https://docs.honeycomb.io/getting-data-in/opentelemetry/otel-collector/) +- [Send Telemetry Data via OTLP/HTTP | Lightstep Learning Portal](https://docs.lightstep.com/docs/send-otlp-over-http-to-lightstep) +- [Already Using OpenTelemetry Collectors? | Lightstep Learning Portal](https://docs.lightstep.com/docs/already-using-collectors) +- [OpenTelemetry quick start | New Relic Documentation](https://docs.newrelic.com/docs/more-integrations/open-source-telemetry-integrations/opentelemetry/opentelemetry-quick-start) + +[0]: https://hex.pm/packages/opentelemetry_phoenix +[1]: https://hex.pm/packages/opentelemetry_ecto +[2]: https://hex.pm/packages/opentelemetry_exporter +[3]: https://github.com/open-telemetry/opentelemetry-collector/ +[4]: https://zipkin.io/ +[5]: https://www.jaegertracing.io/ diff --git a/examples/basic_phoenix_ecto/assets/css/app.css b/examples/basic_phoenix_ecto/assets/css/app.css new file mode 100644 index 0000000..19c2e51 --- /dev/null +++ b/examples/basic_phoenix_ecto/assets/css/app.css @@ -0,0 +1,120 @@ +/* This file is for your main application CSS */ +@import "./phoenix.css"; + +/* Alerts and form errors used by phx.new */ +.alert { + padding: 15px; + margin-bottom: 20px; + border: 1px solid transparent; + border-radius: 4px; +} +.alert-info { + color: #31708f; + background-color: #d9edf7; + border-color: #bce8f1; +} +.alert-warning { + color: #8a6d3b; + background-color: #fcf8e3; + border-color: #faebcc; +} +.alert-danger { + color: #a94442; + background-color: #f2dede; + border-color: #ebccd1; +} +.alert p { + margin-bottom: 0; +} +.alert:empty { + display: none; +} +.invalid-feedback { + color: #a94442; + display: block; + margin: -1rem 0 2rem; +} + +/* LiveView specific classes for your customization */ +.phx-no-feedback.invalid-feedback, +.phx-no-feedback .invalid-feedback { + display: none; +} + +.phx-click-loading { + opacity: 0.5; + transition: opacity 1s ease-out; +} + +.phx-loading{ + cursor: wait; +} + +.phx-modal { + opacity: 1!important; + position: fixed; + z-index: 1; + left: 0; + top: 0; + width: 100%; + height: 100%; + overflow: auto; + background-color: rgba(0,0,0,0.4); +} + +.phx-modal-content { + background-color: #fefefe; + margin: 15vh auto; + padding: 20px; + border: 1px solid #888; + width: 80%; +} + +.phx-modal-close { + color: #aaa; + float: right; + font-size: 28px; + font-weight: bold; +} + +.phx-modal-close:hover, +.phx-modal-close:focus { + color: black; + text-decoration: none; + cursor: pointer; +} + +.fade-in-scale { + animation: 0.2s ease-in 0s normal forwards 1 fade-in-scale-keys; +} + +.fade-out-scale { + animation: 0.2s ease-out 0s normal forwards 1 fade-out-scale-keys; +} + +.fade-in { + animation: 0.2s ease-out 0s normal forwards 1 fade-in-keys; +} +.fade-out { + animation: 0.2s ease-out 0s normal forwards 1 fade-out-keys; +} + +@keyframes fade-in-scale-keys{ + 0% { scale: 0.95; opacity: 0; } + 100% { scale: 1.0; opacity: 1; } +} + +@keyframes fade-out-scale-keys{ + 0% { scale: 1.0; opacity: 1; } + 100% { scale: 0.95; opacity: 0; } +} + +@keyframes fade-in-keys{ + 0% { opacity: 0; } + 100% { opacity: 1; } +} + +@keyframes fade-out-keys{ + 0% { opacity: 1; } + 100% { opacity: 0; } +} diff --git a/examples/basic_phoenix_ecto/assets/css/phoenix.css b/examples/basic_phoenix_ecto/assets/css/phoenix.css new file mode 100644 index 0000000..0d59050 --- /dev/null +++ b/examples/basic_phoenix_ecto/assets/css/phoenix.css @@ -0,0 +1,101 @@ +/* Includes some default style for the starter application. + * This can be safely deleted to start fresh. + */ + +/* Milligram v1.4.1 https://milligram.github.io + * Copyright (c) 2020 CJ Patoilo Licensed under the MIT license + */ + +*,*:after,*:before{box-sizing:inherit}html{box-sizing:border-box;font-size:62.5%}body{color:#000000;font-family:'Helvetica Neue', 'Helvetica', 'Arial', sans-serif;font-size:1.6em;font-weight:300;letter-spacing:.01em;line-height:1.6}blockquote{border-left:0.3rem solid #d1d1d1;margin-left:0;margin-right:0;padding:1rem 1.5rem}blockquote *:last-child{margin-bottom:0}.button,button,input[type='button'],input[type='reset'],input[type='submit']{background-color:#0069d9;border:0.1rem solid #0069d9;border-radius:.4rem;color:#fff;cursor:pointer;display:inline-block;font-size:1.1rem;font-weight:700;height:3.8rem;letter-spacing:.1rem;line-height:3.8rem;padding:0 3.0rem;text-align:center;text-decoration:none;text-transform:uppercase;white-space:nowrap}.button:focus,.button:hover,button:focus,button:hover,input[type='button']:focus,input[type='button']:hover,input[type='reset']:focus,input[type='reset']:hover,input[type='submit']:focus,input[type='submit']:hover{background-color:#606c76;border-color:#606c76;color:#fff;outline:0}.button[disabled],button[disabled],input[type='button'][disabled],input[type='reset'][disabled],input[type='submit'][disabled]{cursor:default;opacity:.5}.button[disabled]:focus,.button[disabled]:hover,button[disabled]:focus,button[disabled]:hover,input[type='button'][disabled]:focus,input[type='button'][disabled]:hover,input[type='reset'][disabled]:focus,input[type='reset'][disabled]:hover,input[type='submit'][disabled]:focus,input[type='submit'][disabled]:hover{background-color:#0069d9;border-color:#0069d9}.button.button-outline,button.button-outline,input[type='button'].button-outline,input[type='reset'].button-outline,input[type='submit'].button-outline{background-color:transparent;color:#0069d9}.button.button-outline:focus,.button.button-outline:hover,button.button-outline:focus,button.button-outline:hover,input[type='button'].button-outline:focus,input[type='button'].button-outline:hover,input[type='reset'].button-outline:focus,input[type='reset'].button-outline:hover,input[type='submit'].button-outline:focus,input[type='submit'].button-outline:hover{background-color:transparent;border-color:#606c76;color:#606c76}.button.button-outline[disabled]:focus,.button.button-outline[disabled]:hover,button.button-outline[disabled]:focus,button.button-outline[disabled]:hover,input[type='button'].button-outline[disabled]:focus,input[type='button'].button-outline[disabled]:hover,input[type='reset'].button-outline[disabled]:focus,input[type='reset'].button-outline[disabled]:hover,input[type='submit'].button-outline[disabled]:focus,input[type='submit'].button-outline[disabled]:hover{border-color:inherit;color:#0069d9}.button.button-clear,button.button-clear,input[type='button'].button-clear,input[type='reset'].button-clear,input[type='submit'].button-clear{background-color:transparent;border-color:transparent;color:#0069d9}.button.button-clear:focus,.button.button-clear:hover,button.button-clear:focus,button.button-clear:hover,input[type='button'].button-clear:focus,input[type='button'].button-clear:hover,input[type='reset'].button-clear:focus,input[type='reset'].button-clear:hover,input[type='submit'].button-clear:focus,input[type='submit'].button-clear:hover{background-color:transparent;border-color:transparent;color:#606c76}.button.button-clear[disabled]:focus,.button.button-clear[disabled]:hover,button.button-clear[disabled]:focus,button.button-clear[disabled]:hover,input[type='button'].button-clear[disabled]:focus,input[type='button'].button-clear[disabled]:hover,input[type='reset'].button-clear[disabled]:focus,input[type='reset'].button-clear[disabled]:hover,input[type='submit'].button-clear[disabled]:focus,input[type='submit'].button-clear[disabled]:hover{color:#0069d9}code{background:#f4f5f6;border-radius:.4rem;font-size:86%;margin:0 .2rem;padding:.2rem .5rem;white-space:nowrap}pre{background:#f4f5f6;border-left:0.3rem solid #0069d9;overflow-y:hidden}pre>code{border-radius:0;display:block;padding:1rem 1.5rem;white-space:pre}hr{border:0;border-top:0.1rem solid #f4f5f6;margin:3.0rem 0}input[type='color'],input[type='date'],input[type='datetime'],input[type='datetime-local'],input[type='email'],input[type='month'],input[type='number'],input[type='password'],input[type='search'],input[type='tel'],input[type='text'],input[type='url'],input[type='week'],input:not([type]),textarea,select{-webkit-appearance:none;background-color:transparent;border:0.1rem solid #d1d1d1;border-radius:.4rem;box-shadow:none;box-sizing:inherit;height:3.8rem;padding:.6rem 1.0rem .7rem;width:100%}input[type='color']:focus,input[type='date']:focus,input[type='datetime']:focus,input[type='datetime-local']:focus,input[type='email']:focus,input[type='month']:focus,input[type='number']:focus,input[type='password']:focus,input[type='search']:focus,input[type='tel']:focus,input[type='text']:focus,input[type='url']:focus,input[type='week']:focus,input:not([type]):focus,textarea:focus,select:focus{border-color:#0069d9;outline:0}select{background:url('data:image/svg+xml;utf8,') center right no-repeat;padding-right:3.0rem}select:focus{background-image:url('data:image/svg+xml;utf8,')}select[multiple]{background:none;height:auto}textarea{min-height:6.5rem}label,legend{display:block;font-size:1.6rem;font-weight:700;margin-bottom:.5rem}fieldset{border-width:0;padding:0}input[type='checkbox'],input[type='radio']{display:inline}.label-inline{display:inline-block;font-weight:normal;margin-left:.5rem}.container{margin:0 auto;max-width:112.0rem;padding:0 2.0rem;position:relative;width:100%}.row{display:flex;flex-direction:column;padding:0;width:100%}.row.row-no-padding{padding:0}.row.row-no-padding>.column{padding:0}.row.row-wrap{flex-wrap:wrap}.row.row-top{align-items:flex-start}.row.row-bottom{align-items:flex-end}.row.row-center{align-items:center}.row.row-stretch{align-items:stretch}.row.row-baseline{align-items:baseline}.row .column{display:block;flex:1 1 auto;margin-left:0;max-width:100%;width:100%}.row .column.column-offset-10{margin-left:10%}.row .column.column-offset-20{margin-left:20%}.row .column.column-offset-25{margin-left:25%}.row .column.column-offset-33,.row .column.column-offset-34{margin-left:33.3333%}.row .column.column-offset-40{margin-left:40%}.row .column.column-offset-50{margin-left:50%}.row .column.column-offset-60{margin-left:60%}.row .column.column-offset-66,.row .column.column-offset-67{margin-left:66.6666%}.row .column.column-offset-75{margin-left:75%}.row .column.column-offset-80{margin-left:80%}.row .column.column-offset-90{margin-left:90%}.row .column.column-10{flex:0 0 10%;max-width:10%}.row .column.column-20{flex:0 0 20%;max-width:20%}.row .column.column-25{flex:0 0 25%;max-width:25%}.row .column.column-33,.row .column.column-34{flex:0 0 33.3333%;max-width:33.3333%}.row .column.column-40{flex:0 0 40%;max-width:40%}.row .column.column-50{flex:0 0 50%;max-width:50%}.row .column.column-60{flex:0 0 60%;max-width:60%}.row .column.column-66,.row .column.column-67{flex:0 0 66.6666%;max-width:66.6666%}.row .column.column-75{flex:0 0 75%;max-width:75%}.row .column.column-80{flex:0 0 80%;max-width:80%}.row .column.column-90{flex:0 0 90%;max-width:90%}.row .column .column-top{align-self:flex-start}.row .column .column-bottom{align-self:flex-end}.row .column .column-center{align-self:center}@media (min-width: 40rem){.row{flex-direction:row;margin-left:-1.0rem;width:calc(100% + 2.0rem)}.row .column{margin-bottom:inherit;padding:0 1.0rem}}a{color:#0069d9;text-decoration:none}a:focus,a:hover{color:#606c76}dl,ol,ul{list-style:none;margin-top:0;padding-left:0}dl dl,dl ol,dl ul,ol dl,ol ol,ol ul,ul dl,ul ol,ul ul{font-size:90%;margin:1.5rem 0 1.5rem 3.0rem}ol{list-style:decimal inside}ul{list-style:circle inside}.button,button,dd,dt,li{margin-bottom:1.0rem}fieldset,input,select,textarea{margin-bottom:1.5rem}blockquote,dl,figure,form,ol,p,pre,table,ul{margin-bottom:2.5rem}table{border-spacing:0;display:block;overflow-x:auto;text-align:left;width:100%}td,th{border-bottom:0.1rem solid #e1e1e1;padding:1.2rem 1.5rem}td:first-child,th:first-child{padding-left:0}td:last-child,th:last-child{padding-right:0}@media (min-width: 40rem){table{display:table;overflow-x:initial}}b,strong{font-weight:bold}p{margin-top:0}h1,h2,h3,h4,h5,h6{font-weight:300;letter-spacing:-.1rem;margin-bottom:2.0rem;margin-top:0}h1{font-size:4.6rem;line-height:1.2}h2{font-size:3.6rem;line-height:1.25}h3{font-size:2.8rem;line-height:1.3}h4{font-size:2.2rem;letter-spacing:-.08rem;line-height:1.35}h5{font-size:1.8rem;letter-spacing:-.05rem;line-height:1.5}h6{font-size:1.6rem;letter-spacing:0;line-height:1.4}img{max-width:100%}.clearfix:after{clear:both;content:' ';display:table}.float-left{float:left}.float-right{float:right} + +/* General style */ +h1{font-size: 3.6rem; line-height: 1.25} +h2{font-size: 2.8rem; line-height: 1.3} +h3{font-size: 2.2rem; letter-spacing: -.08rem; line-height: 1.35} +h4{font-size: 1.8rem; letter-spacing: -.05rem; line-height: 1.5} +h5{font-size: 1.6rem; letter-spacing: 0; line-height: 1.4} +h6{font-size: 1.4rem; letter-spacing: 0; line-height: 1.2} +pre{padding: 1em;} + +.container{ + margin: 0 auto; + max-width: 80.0rem; + padding: 0 2.0rem; + position: relative; + width: 100% +} +select { + width: auto; +} + +/* Phoenix promo and logo */ +.phx-hero { + text-align: center; + border-bottom: 1px solid #e3e3e3; + background: #eee; + border-radius: 6px; + padding: 3em 3em 1em; + margin-bottom: 3rem; + font-weight: 200; + font-size: 120%; +} +.phx-hero input { + background: #ffffff; +} +.phx-logo { + min-width: 300px; + margin: 1rem; + display: block; +} +.phx-logo img { + width: auto; + display: block; +} + +/* Headers */ +header { + width: 100%; + background: #fdfdfd; + border-bottom: 1px solid #eaeaea; + margin-bottom: 2rem; +} +header section { + align-items: center; + display: flex; + flex-direction: column; + justify-content: space-between; +} +header section :first-child { + order: 2; +} +header section :last-child { + order: 1; +} +header nav ul, +header nav li { + margin: 0; + padding: 0; + display: block; + text-align: right; + white-space: nowrap; +} +header nav ul { + margin: 1rem; + margin-top: 0; +} +header nav a { + display: block; +} + +@media (min-width: 40.0rem) { /* Small devices (landscape phones, 576px and up) */ + header section { + flex-direction: row; + } + header nav ul { + margin: 1rem; + } + .phx-logo { + flex-basis: 527px; + margin: 2rem 1rem; + } +} diff --git a/examples/basic_phoenix_ecto/assets/js/app.js b/examples/basic_phoenix_ecto/assets/js/app.js new file mode 100644 index 0000000..2ca06a5 --- /dev/null +++ b/examples/basic_phoenix_ecto/assets/js/app.js @@ -0,0 +1,45 @@ +// We import the CSS which is extracted to its own file by esbuild. +// Remove this line if you add a your own CSS build pipeline (e.g postcss). +import "../css/app.css" + +// If you want to use Phoenix channels, run `mix help phx.gen.channel` +// to get started and then uncomment the line below. +// import "./user_socket.js" + +// You can include dependencies in two ways. +// +// The simplest option is to put them in assets/vendor and +// import them using relative paths: +// +// import "../vendor/some-package.js" +// +// Alternatively, you can `npm install some-package --prefix assets` and import +// them using a path starting with the package name: +// +// import "some-package" +// + +// Include phoenix_html to handle method=PUT/DELETE in forms and buttons. +import "phoenix_html" +// Establish Phoenix Socket and LiveView configuration. +import {Socket} from "phoenix" +import {LiveSocket} from "phoenix_live_view" +import topbar from "../vendor/topbar" + +let csrfToken = document.querySelector("meta[name='csrf-token']").getAttribute("content") +let liveSocket = new LiveSocket("/live", Socket, {params: {_csrf_token: csrfToken}}) + +// Show progress bar on live navigation and form submits +topbar.config({barColors: {0: "#29d"}, shadowColor: "rgba(0, 0, 0, .3)"}) +window.addEventListener("phx:page-loading-start", info => topbar.show()) +window.addEventListener("phx:page-loading-stop", info => topbar.hide()) + +// connect if there are any LiveViews on the page +liveSocket.connect() + +// expose liveSocket on window for web console debug logs and latency simulation: +// >> liveSocket.enableDebug() +// >> liveSocket.enableLatencySim(1000) // enabled for duration of browser session +// >> liveSocket.disableLatencySim() +window.liveSocket = liveSocket + diff --git a/examples/basic_phoenix_ecto/assets/vendor/topbar.js b/examples/basic_phoenix_ecto/assets/vendor/topbar.js new file mode 100644 index 0000000..1f62209 --- /dev/null +++ b/examples/basic_phoenix_ecto/assets/vendor/topbar.js @@ -0,0 +1,157 @@ +/** + * @license MIT + * topbar 1.0.0, 2021-01-06 + * https://buunguyen.github.io/topbar + * Copyright (c) 2021 Buu Nguyen + */ +(function (window, document) { + "use strict"; + + // https://gist.github.com/paulirish/1579671 + (function () { + var lastTime = 0; + var vendors = ["ms", "moz", "webkit", "o"]; + for (var x = 0; x < vendors.length && !window.requestAnimationFrame; ++x) { + window.requestAnimationFrame = + window[vendors[x] + "RequestAnimationFrame"]; + window.cancelAnimationFrame = + window[vendors[x] + "CancelAnimationFrame"] || + window[vendors[x] + "CancelRequestAnimationFrame"]; + } + if (!window.requestAnimationFrame) + window.requestAnimationFrame = function (callback, element) { + var currTime = new Date().getTime(); + var timeToCall = Math.max(0, 16 - (currTime - lastTime)); + var id = window.setTimeout(function () { + callback(currTime + timeToCall); + }, timeToCall); + lastTime = currTime + timeToCall; + return id; + }; + if (!window.cancelAnimationFrame) + window.cancelAnimationFrame = function (id) { + clearTimeout(id); + }; + })(); + + var canvas, + progressTimerId, + fadeTimerId, + currentProgress, + showing, + addEvent = function (elem, type, handler) { + if (elem.addEventListener) elem.addEventListener(type, handler, false); + else if (elem.attachEvent) elem.attachEvent("on" + type, handler); + else elem["on" + type] = handler; + }, + options = { + autoRun: true, + barThickness: 3, + barColors: { + 0: "rgba(26, 188, 156, .9)", + ".25": "rgba(52, 152, 219, .9)", + ".50": "rgba(241, 196, 15, .9)", + ".75": "rgba(230, 126, 34, .9)", + "1.0": "rgba(211, 84, 0, .9)", + }, + shadowBlur: 10, + shadowColor: "rgba(0, 0, 0, .6)", + className: null, + }, + repaint = function () { + canvas.width = window.innerWidth; + canvas.height = options.barThickness * 5; // need space for shadow + + var ctx = canvas.getContext("2d"); + ctx.shadowBlur = options.shadowBlur; + ctx.shadowColor = options.shadowColor; + + var lineGradient = ctx.createLinearGradient(0, 0, canvas.width, 0); + for (var stop in options.barColors) + lineGradient.addColorStop(stop, options.barColors[stop]); + ctx.lineWidth = options.barThickness; + ctx.beginPath(); + ctx.moveTo(0, options.barThickness / 2); + ctx.lineTo( + Math.ceil(currentProgress * canvas.width), + options.barThickness / 2 + ); + ctx.strokeStyle = lineGradient; + ctx.stroke(); + }, + createCanvas = function () { + canvas = document.createElement("canvas"); + var style = canvas.style; + style.position = "fixed"; + style.top = style.left = style.right = style.margin = style.padding = 0; + style.zIndex = 100001; + style.display = "none"; + if (options.className) canvas.classList.add(options.className); + document.body.appendChild(canvas); + addEvent(window, "resize", repaint); + }, + topbar = { + config: function (opts) { + for (var key in opts) + if (options.hasOwnProperty(key)) options[key] = opts[key]; + }, + show: function () { + if (showing) return; + showing = true; + if (fadeTimerId !== null) window.cancelAnimationFrame(fadeTimerId); + if (!canvas) createCanvas(); + canvas.style.opacity = 1; + canvas.style.display = "block"; + topbar.progress(0); + if (options.autoRun) { + (function loop() { + progressTimerId = window.requestAnimationFrame(loop); + topbar.progress( + "+" + 0.05 * Math.pow(1 - Math.sqrt(currentProgress), 2) + ); + })(); + } + }, + progress: function (to) { + if (typeof to === "undefined") return currentProgress; + if (typeof to === "string") { + to = + (to.indexOf("+") >= 0 || to.indexOf("-") >= 0 + ? currentProgress + : 0) + parseFloat(to); + } + currentProgress = to > 1 ? 1 : to; + repaint(); + return currentProgress; + }, + hide: function () { + if (!showing) return; + showing = false; + if (progressTimerId != null) { + window.cancelAnimationFrame(progressTimerId); + progressTimerId = null; + } + (function loop() { + if (topbar.progress("+.1") >= 1) { + canvas.style.opacity -= 0.05; + if (canvas.style.opacity <= 0.05) { + canvas.style.display = "none"; + fadeTimerId = null; + return; + } + } + fadeTimerId = window.requestAnimationFrame(loop); + })(); + }, + }; + + if (typeof module === "object" && typeof module.exports === "object") { + module.exports = topbar; + } else if (typeof define === "function" && define.amd) { + define(function () { + return topbar; + }); + } else { + this.topbar = topbar; + } +}.call(this, window, document)); diff --git a/examples/basic_phoenix_ecto/config/config.exs b/examples/basic_phoenix_ecto/config/config.exs new file mode 100644 index 0000000..09eadc1 --- /dev/null +++ b/examples/basic_phoenix_ecto/config/config.exs @@ -0,0 +1,58 @@ +# This file is responsible for configuring your application +# and its dependencies with the aid of the Config module. +# +# This configuration file is loaded before any dependency and +# is restricted to this project. + +# General application configuration +import Config + +config :demo, + ecto_repos: [Demo.Repo] + +# Configures the endpoint +config :demo, DemoWeb.Endpoint, + url: [host: "localhost"], + render_errors: [view: DemoWeb.ErrorView, accepts: ~w(html json), layout: false], + pubsub_server: Demo.PubSub, + live_view: [signing_salt: "VAm4n+i4"] + +# Configures the mailer +# +# By default it uses the "Local" adapter which stores the emails +# locally. You can see the emails in your browser, at "/dev/mailbox". +# +# For production it's recommended to configure a different adapter +# at the `config/runtime.exs`. +config :demo, Demo.Mailer, adapter: Swoosh.Adapters.Local + +# Swoosh API client is needed for adapters other than SMTP. +config :swoosh, :api_client, false + +# Configure esbuild (the version is required) +config :esbuild, + version: "0.14.0", + default: [ + args: + ~w(js/app.js --bundle --target=es2017 --outdir=../priv/static/assets --external:/fonts/* --external:/images/*), + cd: Path.expand("../assets", __DIR__), + env: %{"NODE_PATH" => Path.expand("../deps", __DIR__)} + ] + +# Configures Elixir's Logger +config :logger, :console, + format: "$time $metadata[$level] $message\n", + metadata: [:request_id] + +# Use Jason for JSON parsing in Phoenix +config :phoenix, :json_library, Jason + +# Console Exporter for OpenTelemetry Exporter +config :opentelemetry, :processors, + otel_batch_processor: %{ + exporter: {:otel_exporter_stdout, []} + } + +# Import environment specific config. This must remain at the bottom +# of this file so it overrides the configuration defined above. +import_config "#{config_env()}.exs" diff --git a/examples/basic_phoenix_ecto/config/dev.exs b/examples/basic_phoenix_ecto/config/dev.exs new file mode 100644 index 0000000..3888c84 --- /dev/null +++ b/examples/basic_phoenix_ecto/config/dev.exs @@ -0,0 +1,74 @@ +import Config + +# Configure your database +config :demo, Demo.Repo, + username: "postgres", + password: "postgres", + hostname: "localhost", + database: "demo_dev", + show_sensitive_data_on_connection_error: true, + pool_size: 10 + +# For development, we disable any cache and enable +# debugging and code reloading. +# +# The watchers configuration can be used to run external +# watchers to your application. For example, we use it +# with esbuild to bundle .js and .css sources. +config :demo, DemoWeb.Endpoint, + # Binding to loopback ipv4 address prevents access from other machines. + # Change to `ip: {0, 0, 0, 0}` to allow access from other machines. + http: [ip: {127, 0, 0, 1}, port: 4000], + check_origin: false, + code_reloader: true, + debug_errors: true, + secret_key_base: "sCG0+TPbrMjXcTfqNb/y8OtflRYrWlqugOQev4l37ONaqnKUpB/lucwjYVJ7skz2", + watchers: [ + # Start the esbuild watcher by calling Esbuild.install_and_run(:default, args) + esbuild: {Esbuild, :install_and_run, [:default, ~w(--sourcemap=inline --watch)]} + ] + +# ## SSL Support +# +# In order to use HTTPS in development, a self-signed +# certificate can be generated by running the following +# Mix task: +# +# mix phx.gen.cert +# +# Note that this task requires Erlang/OTP 20 or later. +# Run `mix help phx.gen.cert` for more information. +# +# The `http:` config above can be replaced with: +# +# https: [ +# port: 4001, +# cipher_suite: :strong, +# keyfile: "priv/cert/selfsigned_key.pem", +# certfile: "priv/cert/selfsigned.pem" +# ], +# +# If desired, both `http:` and `https:` keys can be +# configured to run both http and https servers on +# different ports. + +# Watch static and templates for browser reloading. +config :demo, DemoWeb.Endpoint, + live_reload: [ + patterns: [ + ~r"priv/static/.*(js|css|png|jpeg|jpg|gif|svg)$", + ~r"priv/gettext/.*(po)$", + ~r"lib/demo_web/(live|views)/.*(ex)$", + ~r"lib/demo_web/templates/.*(eex)$" + ] + ] + +# Do not include metadata nor timestamps in development logs +config :logger, :console, format: "[$level] $message\n" + +# Set a higher stacktrace during development. Avoid configuring such +# in production as building large stacktraces may be expensive. +config :phoenix, :stacktrace_depth, 20 + +# Initialize plugs at runtime for faster development compilation +config :phoenix, :plug_init_mode, :runtime diff --git a/examples/basic_phoenix_ecto/config/prod.exs b/examples/basic_phoenix_ecto/config/prod.exs new file mode 100644 index 0000000..c421b98 --- /dev/null +++ b/examples/basic_phoenix_ecto/config/prod.exs @@ -0,0 +1,49 @@ +import Config + +# For production, don't forget to configure the url host +# to something meaningful, Phoenix uses this information +# when generating URLs. +# +# Note we also include the path to a cache manifest +# containing the digested version of static files. This +# manifest is generated by the `mix phx.digest` task, +# which you should run after static files are built and +# before starting your production server. +config :demo, DemoWeb.Endpoint, cache_static_manifest: "priv/static/cache_manifest.json" + +# Do not print debug messages in production +config :logger, level: :info + +# ## SSL Support +# +# To get SSL working, you will need to add the `https` key +# to the previous section and set your `:url` port to 443: +# +# config :demo, DemoWeb.Endpoint, +# ..., +# url: [host: "example.com", port: 443], +# https: [ +# ..., +# port: 443, +# cipher_suite: :strong, +# keyfile: System.get_env("SOME_APP_SSL_KEY_PATH"), +# certfile: System.get_env("SOME_APP_SSL_CERT_PATH") +# ] +# +# The `cipher_suite` is set to `:strong` to support only the +# latest and more secure SSL ciphers. This means old browsers +# and clients may not be supported. You can set it to +# `:compatible` for wider support. +# +# `:keyfile` and `:certfile` expect an absolute path to the key +# and cert in disk or a relative path inside priv, for example +# "priv/ssl/server.key". For all supported SSL configuration +# options, see https://hexdocs.pm/plug/Plug.SSL.html#configure/1 +# +# We also recommend setting `force_ssl` in your endpoint, ensuring +# no data is ever sent via http, always redirecting to https: +# +# config :demo, DemoWeb.Endpoint, +# force_ssl: [hsts: true] +# +# Check `Plug.SSL` for all available options in `force_ssl`. diff --git a/examples/basic_phoenix_ecto/config/runtime.exs b/examples/basic_phoenix_ecto/config/runtime.exs new file mode 100644 index 0000000..b909374 --- /dev/null +++ b/examples/basic_phoenix_ecto/config/runtime.exs @@ -0,0 +1,124 @@ +import Config + +# config/runtime.exs is executed for all environments, including +# during releases. It is executed after compilation and before the +# system starts, so it is typically used to load production configuration +# and secrets from environment variables or elsewhere. Do not define +# any compile-time configuration in here, as it won't be applied. +# The block below contains prod specific runtime configuration. + +# Start the phoenix server if environment is set and running in a release +if System.get_env("PHX_SERVER") && System.get_env("RELEASE_NAME") do + config :demo, DemoWeb.Endpoint, server: true +end + +if config_env() == :prod do + database_url = + System.get_env("DATABASE_URL") || + raise """ + environment variable DATABASE_URL is missing. + For example: ecto://USER:PASS@HOST/DATABASE + """ + + maybe_ipv6 = if System.get_env("ECTO_IPV6"), do: [:inet6], else: [] + + config :demo, Demo.Repo, + # ssl: true, + url: database_url, + pool_size: String.to_integer(System.get_env("POOL_SIZE") || "10"), + socket_options: maybe_ipv6 + + # The secret key base is used to sign/encrypt cookies and other secrets. + # A default value is used in config/dev.exs and config/test.exs but you + # want to use a different value for prod and you most likely don't want + # to check this value into version control, so we use an environment + # variable instead. + secret_key_base = + System.get_env("SECRET_KEY_BASE") || + raise """ + environment variable SECRET_KEY_BASE is missing. + You can generate one by calling: mix phx.gen.secret + """ + + host = System.get_env("PHX_HOST") || "example.com" + port = String.to_integer(System.get_env("PORT") || "4000") + + config :demo, DemoWeb.Endpoint, + url: [host: host, port: 443], + http: [ + # Enable IPv6 and bind on all interfaces. + # Set it to {0, 0, 0, 0, 0, 0, 0, 1} for local network only access. + # See the documentation on https://hexdocs.pm/plug_cowboy/Plug.Cowboy.html + # for details about using IPv6 vs IPv4 and loopback vs public addresses. + ip: {0, 0, 0, 0, 0, 0, 0, 0}, + port: port + ], + secret_key_base: secret_key_base + + config :opentelemetry, :processors, + otel_batch_processor: %{ + # Using `otel` here since we are starting through docker-compose where + # otel refer to the hostname of the OpenCollector, + # + # If you are running it locally, kindly change it to the correct + # hostname such as `localhost`, `0.0.0.0` and etc. + exporter: {:opentelemetry_exporter, %{endpoints: ["http://otel:4318"]}} + + # Example configuration to directly export to Honeycomb.io + # exporter: { + # :opentelemetry_exporter, %{ + # endpoints: ["https://api.honeycomb.io:443"], + # headers: [ + # {"x-honeycomb-team", System.get_env("HONEYCOMB_TEAM")}, + # {"x-honeycomb-dataset", System.get_env("HONEYCOMB_DATASET") || "demo"} + # ] + # } + # } + + # Example configuration to directly export to Lightstep.com + # + # Since Lightstep has a different OTLP trace endpoint, we are going need + # to configure it in a separate configuration. + # exporter: { + # :opentelemetry_exporter, %{} + # } + } + + # Example configuration for Lightstep.com, for more refers to: + # https://github.com/open-telemetry/opentelemetry-erlang/tree/main/apps/opentelemetry_exporter#application-environment + # config :opentelemetry_exporter + # # You can also configure the compression type for exporting traces. + # oltp_traces_compression: :gzip, + # otlp_traces_endpoint: "https://ingest.lightstep.com:443/traces/otlp/v0.9", + # otlp_headers: [ + # {"lightstep-access-token", System.get_env("LIGHTSTEP_ACCESS_TOKEN")} + # ] + + # ## Using releases + # + # If you are doing OTP releases, you need to instruct Phoenix + # to start each relevant endpoint: + # + # config :demo, DemoWeb.Endpoint, server: true + # + # Then you can assemble a release by calling `mix release`. + # See `mix help release` for more information. + + # ## Configuring the mailer + # + # In production you need to configure the mailer to use a different adapter. + # Also, you may need to configure the Swoosh API client of your choice if you + # are not using SMTP. Here is an example of the configuration: + # + # config :demo, Demo.Mailer, + # adapter: Swoosh.Adapters.Mailgun, + # api_key: System.get_env("MAILGUN_API_KEY"), + # domain: System.get_env("MAILGUN_DOMAIN") + # + # For this example you need include a HTTP client required by Swoosh API client. + # Swoosh supports Hackney and Finch out of the box: + # + # config :swoosh, :api_client, Swoosh.ApiClient.Hackney + # + # See https://hexdocs.pm/swoosh/Swoosh.html#module-installation for details. +end diff --git a/examples/basic_phoenix_ecto/config/test.exs b/examples/basic_phoenix_ecto/config/test.exs new file mode 100644 index 0000000..049035d --- /dev/null +++ b/examples/basic_phoenix_ecto/config/test.exs @@ -0,0 +1,30 @@ +import Config + +# Configure your database +# +# The MIX_TEST_PARTITION environment variable can be used +# to provide built-in test partitioning in CI environment. +# Run `mix help test` for more information. +config :demo, Demo.Repo, + username: "postgres", + password: "postgres", + hostname: "localhost", + database: "demo_test#{System.get_env("MIX_TEST_PARTITION")}", + pool: Ecto.Adapters.SQL.Sandbox, + pool_size: 10 + +# We don't run a server during test. If one is required, +# you can enable the server option below. +config :demo, DemoWeb.Endpoint, + http: [ip: {127, 0, 0, 1}, port: 4002], + secret_key_base: "HA6q/NdvvNoDUSpoLsTkiwvN8RTuGyiWHc9XT50EQsrxT7MEyEv/SPeO/Ty9Zafz", + server: false + +# In test we don't send emails. +config :demo, Demo.Mailer, adapter: Swoosh.Adapters.Test + +# Print only warnings and errors during test +config :logger, level: :warn + +# Initialize plugs at runtime for faster test compilation +config :phoenix, :plug_init_mode, :runtime diff --git a/examples/basic_phoenix_ecto/docker-compose.yaml b/examples/basic_phoenix_ecto/docker-compose.yaml new file mode 100644 index 0000000..3d7ec61 --- /dev/null +++ b/examples/basic_phoenix_ecto/docker-compose.yaml @@ -0,0 +1,39 @@ +version: '3' +services: + postgres: + image: 'postgres:latest' + ports: + - 5432:5432 + + environment: + POSTGRES_USER: postgres + POSTGRES_PASSWORD: postgres + POSTGRES_DB: demo_dev + + phoenix: + env_file: .env + build: . + ports: + - 4000:4000 + + + otel: + image: otel/opentelemetry-collector-contrib-dev:latest + command: ["--config=/etc/otel-collector-config.yaml"] + ports: + - '4318:4318' + volumes: + - ./otel-collector-config.yaml:/etc/otel-collector-config.yaml + + zipkin: + image: openzipkin/zipkin-slim + ports: + - '9411:9411' + + # Jaeger + jaeger-all-in-one: + image: jaegertracing/all-in-one:latest + ports: + - "16686:16686" + - "14268" + - "14250" diff --git a/examples/basic_phoenix_ecto/lib/demo.ex b/examples/basic_phoenix_ecto/lib/demo.ex new file mode 100644 index 0000000..3f1ac75 --- /dev/null +++ b/examples/basic_phoenix_ecto/lib/demo.ex @@ -0,0 +1,9 @@ +defmodule Demo do + @moduledoc """ + Demo keeps the contexts that define your domain + and business logic. + + Contexts are also responsible for managing your data, regardless + if it comes from the database, an external API or others. + """ +end diff --git a/examples/basic_phoenix_ecto/lib/demo/accounts.ex b/examples/basic_phoenix_ecto/lib/demo/accounts.ex new file mode 100644 index 0000000..c7636dd --- /dev/null +++ b/examples/basic_phoenix_ecto/lib/demo/accounts.ex @@ -0,0 +1,104 @@ +defmodule Demo.Accounts do + @moduledoc """ + The Accounts context. + """ + + import Ecto.Query, warn: false + alias Demo.Repo + + alias Demo.Accounts.User + + @doc """ + Returns the list of users. + + ## Examples + + iex> list_users() + [%User{}, ...] + + """ + def list_users do + Repo.all(User) + end + + @doc """ + Gets a single user. + + Raises `Ecto.NoResultsError` if the User does not exist. + + ## Examples + + iex> get_user!(123) + %User{} + + iex> get_user!(456) + ** (Ecto.NoResultsError) + + """ + def get_user!(id), do: Repo.get!(User, id) + + @doc """ + Creates a user. + + ## Examples + + iex> create_user(%{field: value}) + {:ok, %User{}} + + iex> create_user(%{field: bad_value}) + {:error, %Ecto.Changeset{}} + + """ + def create_user(attrs \\ %{}) do + %User{} + |> User.changeset(attrs) + |> Repo.insert() + end + + @doc """ + Updates a user. + + ## Examples + + iex> update_user(user, %{field: new_value}) + {:ok, %User{}} + + iex> update_user(user, %{field: bad_value}) + {:error, %Ecto.Changeset{}} + + """ + def update_user(%User{} = user, attrs) do + user + |> User.changeset(attrs) + |> Repo.update() + end + + @doc """ + Deletes a user. + + ## Examples + + iex> delete_user(user) + {:ok, %User{}} + + iex> delete_user(user) + {:error, %Ecto.Changeset{}} + + """ + def delete_user(%User{} = user) do + Repo.delete(user) + end + + @doc """ + Returns an `%Ecto.Changeset{}` for tracking user changes. + + ## Examples + + iex> change_user(user) + %Ecto.Changeset{data: %User{}} + + """ + def change_user(%User{} = user, attrs \\ %{}) do + User.changeset(user, attrs) + end +end diff --git a/examples/basic_phoenix_ecto/lib/demo/accounts/user.ex b/examples/basic_phoenix_ecto/lib/demo/accounts/user.ex new file mode 100644 index 0000000..52ac202 --- /dev/null +++ b/examples/basic_phoenix_ecto/lib/demo/accounts/user.ex @@ -0,0 +1,17 @@ +defmodule Demo.Accounts.User do + use Ecto.Schema + import Ecto.Changeset + + schema "users" do + field :name, :string + + timestamps() + end + + @doc false + def changeset(user, attrs) do + user + |> cast(attrs, [:name]) + |> validate_required([:name]) + end +end diff --git a/examples/basic_phoenix_ecto/lib/demo/application.ex b/examples/basic_phoenix_ecto/lib/demo/application.ex new file mode 100644 index 0000000..0d04708 --- /dev/null +++ b/examples/basic_phoenix_ecto/lib/demo/application.ex @@ -0,0 +1,39 @@ +defmodule Demo.Application do + # See https://hexdocs.pm/elixir/Application.html + # for more information on OTP Applications + @moduledoc false + + use Application + + @impl true + def start(_type, _args) do + OpentelemetryPhoenix.setup() + OpentelemetryEcto.setup([:demo, :repo]) + + children = [ + # Start the Ecto repository + Demo.Repo, + # Start the Telemetry supervisor + DemoWeb.Telemetry, + # Start the PubSub system + {Phoenix.PubSub, name: Demo.PubSub}, + # Start the Endpoint (http/https) + DemoWeb.Endpoint + # Start a worker by calling: Demo.Worker.start_link(arg) + # {Demo.Worker, arg} + ] + + # See https://hexdocs.pm/elixir/Supervisor.html + # for other strategies and supported options + opts = [strategy: :one_for_one, name: Demo.Supervisor] + Supervisor.start_link(children, opts) + end + + # Tell Phoenix to update the endpoint configuration + # whenever the application is updated. + @impl true + def config_change(changed, _new, removed) do + DemoWeb.Endpoint.config_change(changed, removed) + :ok + end +end diff --git a/examples/basic_phoenix_ecto/lib/demo/blog.ex b/examples/basic_phoenix_ecto/lib/demo/blog.ex new file mode 100644 index 0000000..56fefbf --- /dev/null +++ b/examples/basic_phoenix_ecto/lib/demo/blog.ex @@ -0,0 +1,104 @@ +defmodule Demo.Blog do + @moduledoc """ + The Blog context. + """ + + import Ecto.Query, warn: false + alias Demo.Repo + + alias Demo.Blog.Post + + @doc """ + Returns the list of posts. + + ## Examples + + iex> list_posts() + [%Post{}, ...] + + """ + def list_posts do + Repo.all(Post) + end + + @doc """ + Gets a single post. + + Raises `Ecto.NoResultsError` if the Post does not exist. + + ## Examples + + iex> get_post!(123) + %Post{} + + iex> get_post!(456) + ** (Ecto.NoResultsError) + + """ + def get_post!(id), do: Repo.get!(Post, id) + + @doc """ + Creates a post. + + ## Examples + + iex> create_post(%{field: value}) + {:ok, %Post{}} + + iex> create_post(%{field: bad_value}) + {:error, %Ecto.Changeset{}} + + """ + def create_post(attrs \\ %{}) do + %Post{} + |> Post.changeset(attrs) + |> Repo.insert() + end + + @doc """ + Updates a post. + + ## Examples + + iex> update_post(post, %{field: new_value}) + {:ok, %Post{}} + + iex> update_post(post, %{field: bad_value}) + {:error, %Ecto.Changeset{}} + + """ + def update_post(%Post{} = post, attrs) do + post + |> Post.changeset(attrs) + |> Repo.update() + end + + @doc """ + Deletes a post. + + ## Examples + + iex> delete_post(post) + {:ok, %Post{}} + + iex> delete_post(post) + {:error, %Ecto.Changeset{}} + + """ + def delete_post(%Post{} = post) do + Repo.delete(post) + end + + @doc """ + Returns an `%Ecto.Changeset{}` for tracking post changes. + + ## Examples + + iex> change_post(post) + %Ecto.Changeset{data: %Post{}} + + """ + def change_post(%Post{} = post, attrs \\ %{}) do + Post.changeset(post, attrs) + end +end diff --git a/examples/basic_phoenix_ecto/lib/demo/blog/post.ex b/examples/basic_phoenix_ecto/lib/demo/blog/post.ex new file mode 100644 index 0000000..fd74346 --- /dev/null +++ b/examples/basic_phoenix_ecto/lib/demo/blog/post.ex @@ -0,0 +1,18 @@ +defmodule Demo.Blog.Post do + use Ecto.Schema + import Ecto.Changeset + + schema "posts" do + field :body, :string + field :title, :string + + timestamps() + end + + @doc false + def changeset(post, attrs) do + post + |> cast(attrs, [:title, :body]) + |> validate_required([:title, :body]) + end +end diff --git a/examples/basic_phoenix_ecto/lib/demo/mailer.ex b/examples/basic_phoenix_ecto/lib/demo/mailer.ex new file mode 100644 index 0000000..c23e8ba --- /dev/null +++ b/examples/basic_phoenix_ecto/lib/demo/mailer.ex @@ -0,0 +1,3 @@ +defmodule Demo.Mailer do + use Swoosh.Mailer, otp_app: :demo +end diff --git a/examples/basic_phoenix_ecto/lib/demo/release.ex b/examples/basic_phoenix_ecto/lib/demo/release.ex new file mode 100644 index 0000000..3c3958e --- /dev/null +++ b/examples/basic_phoenix_ecto/lib/demo/release.ex @@ -0,0 +1,24 @@ +defmodule Demo.Release do + @app :demo + + def migrate do + load_app() + + for repo <- repos() do + {:ok, _, _} = Ecto.Migrator.with_repo(repo, &Ecto.Migrator.run(&1, :up, all: true)) + end + end + + def rollback(repo, version) do + load_app() + {:ok, _, _} = Ecto.Migrator.with_repo(repo, &Ecto.Migrator.run(&1, :down, to: version)) + end + + defp repos do + Application.fetch_env!(@app, :ecto_repos) + end + + defp load_app do + Application.load(@app) + end +end diff --git a/examples/basic_phoenix_ecto/lib/demo/repo.ex b/examples/basic_phoenix_ecto/lib/demo/repo.ex new file mode 100644 index 0000000..445da70 --- /dev/null +++ b/examples/basic_phoenix_ecto/lib/demo/repo.ex @@ -0,0 +1,5 @@ +defmodule Demo.Repo do + use Ecto.Repo, + otp_app: :demo, + adapter: Ecto.Adapters.Postgres +end diff --git a/examples/basic_phoenix_ecto/lib/demo_web.ex b/examples/basic_phoenix_ecto/lib/demo_web.ex new file mode 100644 index 0000000..d821f84 --- /dev/null +++ b/examples/basic_phoenix_ecto/lib/demo_web.ex @@ -0,0 +1,111 @@ +defmodule DemoWeb do + @moduledoc """ + The entrypoint for defining your web interface, such + as controllers, views, channels and so on. + + This can be used in your application as: + + use DemoWeb, :controller + use DemoWeb, :view + + The definitions below will be executed for every view, + controller, etc, so keep them short and clean, focused + on imports, uses and aliases. + + Do NOT define functions inside the quoted expressions + below. Instead, define any helper function in modules + and import those modules here. + """ + + def controller do + quote do + use Phoenix.Controller, namespace: DemoWeb + + import Plug.Conn + import DemoWeb.Gettext + alias DemoWeb.Router.Helpers, as: Routes + end + end + + def view do + quote do + use Phoenix.View, + root: "lib/demo_web/templates", + namespace: DemoWeb + + # Import convenience functions from controllers + import Phoenix.Controller, + only: [get_flash: 1, get_flash: 2, view_module: 1, view_template: 1] + + # Include shared imports and aliases for views + unquote(view_helpers()) + end + end + + def live_view do + quote do + use Phoenix.LiveView, + layout: {DemoWeb.LayoutView, "live.html"} + + unquote(view_helpers()) + end + end + + def live_component do + quote do + use Phoenix.LiveComponent + + unquote(view_helpers()) + end + end + + def component do + quote do + use Phoenix.Component + + unquote(view_helpers()) + end + end + + def router do + quote do + use Phoenix.Router + + import Plug.Conn + import Phoenix.Controller + import Phoenix.LiveView.Router + end + end + + def channel do + quote do + use Phoenix.Channel + import DemoWeb.Gettext + end + end + + defp view_helpers do + quote do + # Use all HTML functionality (forms, tags, etc) + use Phoenix.HTML + + # Import LiveView and .heex helpers (live_render, live_patch, <.form>, etc) + import Phoenix.LiveView.Helpers + import DemoWeb.LiveHelpers + + # Import basic rendering functionality (render, render_layout, etc) + import Phoenix.View + + import DemoWeb.ErrorHelpers + import DemoWeb.Gettext + alias DemoWeb.Router.Helpers, as: Routes + end + end + + @doc """ + When used, dispatch to the appropriate controller/view/etc. + """ + defmacro __using__(which) when is_atom(which) do + apply(__MODULE__, which, []) + end +end diff --git a/examples/basic_phoenix_ecto/lib/demo_web/controllers/page_controller.ex b/examples/basic_phoenix_ecto/lib/demo_web/controllers/page_controller.ex new file mode 100644 index 0000000..fe0fb62 --- /dev/null +++ b/examples/basic_phoenix_ecto/lib/demo_web/controllers/page_controller.ex @@ -0,0 +1,7 @@ +defmodule DemoWeb.PageController do + use DemoWeb, :controller + + def index(conn, _params) do + render(conn, "index.html") + end +end diff --git a/examples/basic_phoenix_ecto/lib/demo_web/controllers/post_controller.ex b/examples/basic_phoenix_ecto/lib/demo_web/controllers/post_controller.ex new file mode 100644 index 0000000..a29a0be --- /dev/null +++ b/examples/basic_phoenix_ecto/lib/demo_web/controllers/post_controller.ex @@ -0,0 +1,62 @@ +defmodule DemoWeb.PostController do + use DemoWeb, :controller + + alias Demo.Blog + alias Demo.Blog.Post + + def index(conn, _params) do + posts = Blog.list_posts() + render(conn, "index.html", posts: posts) + end + + def new(conn, _params) do + changeset = Blog.change_post(%Post{}) + render(conn, "new.html", changeset: changeset) + end + + def create(conn, %{"post" => post_params}) do + case Blog.create_post(post_params) do + {:ok, post} -> + conn + |> put_flash(:info, "Post created successfully.") + |> redirect(to: Routes.post_path(conn, :show, post)) + + {:error, %Ecto.Changeset{} = changeset} -> + render(conn, "new.html", changeset: changeset) + end + end + + def show(conn, %{"id" => id}) do + post = Blog.get_post!(id) + render(conn, "show.html", post: post) + end + + def edit(conn, %{"id" => id}) do + post = Blog.get_post!(id) + changeset = Blog.change_post(post) + render(conn, "edit.html", post: post, changeset: changeset) + end + + def update(conn, %{"id" => id, "post" => post_params}) do + post = Blog.get_post!(id) + + case Blog.update_post(post, post_params) do + {:ok, post} -> + conn + |> put_flash(:info, "Post updated successfully.") + |> redirect(to: Routes.post_path(conn, :show, post)) + + {:error, %Ecto.Changeset{} = changeset} -> + render(conn, "edit.html", post: post, changeset: changeset) + end + end + + def delete(conn, %{"id" => id}) do + post = Blog.get_post!(id) + {:ok, _post} = Blog.delete_post(post) + + conn + |> put_flash(:info, "Post deleted successfully.") + |> redirect(to: Routes.post_path(conn, :index)) + end +end diff --git a/examples/basic_phoenix_ecto/lib/demo_web/endpoint.ex b/examples/basic_phoenix_ecto/lib/demo_web/endpoint.ex new file mode 100644 index 0000000..cf32b82 --- /dev/null +++ b/examples/basic_phoenix_ecto/lib/demo_web/endpoint.ex @@ -0,0 +1,50 @@ +defmodule DemoWeb.Endpoint do + use Phoenix.Endpoint, otp_app: :demo + + # The session will be stored in the cookie and signed, + # this means its contents can be read but not tampered with. + # Set :encryption_salt if you would also like to encrypt it. + @session_options [ + store: :cookie, + key: "_demo_key", + signing_salt: "0WtFu0g7" + ] + + socket "/live", Phoenix.LiveView.Socket, websocket: [connect_info: [session: @session_options]] + + # Serve at "/" the static files from "priv/static" directory. + # + # You should set gzip to true if you are running phx.digest + # when deploying your static files in production. + plug Plug.Static, + at: "/", + from: :demo, + gzip: false, + only: ~w(assets fonts images favicon.ico robots.txt) + + # Code reloading can be explicitly enabled under the + # :code_reloader configuration of your endpoint. + if code_reloading? do + socket "/phoenix/live_reload/socket", Phoenix.LiveReloader.Socket + plug Phoenix.LiveReloader + plug Phoenix.CodeReloader + plug Phoenix.Ecto.CheckRepoStatus, otp_app: :demo + end + + plug Phoenix.LiveDashboard.RequestLogger, + param_key: "request_logger", + cookie_key: "request_logger" + + plug Plug.RequestId + plug Plug.Telemetry, event_prefix: [:phoenix, :endpoint] + + plug Plug.Parsers, + parsers: [:urlencoded, :multipart, :json], + pass: ["*/*"], + json_decoder: Phoenix.json_library() + + plug Plug.MethodOverride + plug Plug.Head + plug Plug.Session, @session_options + plug DemoWeb.Router +end diff --git a/examples/basic_phoenix_ecto/lib/demo_web/gettext.ex b/examples/basic_phoenix_ecto/lib/demo_web/gettext.ex new file mode 100644 index 0000000..01f45dc --- /dev/null +++ b/examples/basic_phoenix_ecto/lib/demo_web/gettext.ex @@ -0,0 +1,24 @@ +defmodule DemoWeb.Gettext do + @moduledoc """ + A module providing Internationalization with a gettext-based API. + + By using [Gettext](https://hexdocs.pm/gettext), + your module gains a set of macros for translations, for example: + + import DemoWeb.Gettext + + # Simple translation + gettext("Here is the string to translate") + + # Plural translation + ngettext("Here is the string to translate", + "Here are the strings to translate", + 3) + + # Domain-based translation + dgettext("errors", "Here is the error message to translate") + + See the [Gettext Docs](https://hexdocs.pm/gettext) for detailed usage. + """ + use Gettext, otp_app: :demo +end diff --git a/examples/basic_phoenix_ecto/lib/demo_web/live/live_helpers.ex b/examples/basic_phoenix_ecto/lib/demo_web/live/live_helpers.ex new file mode 100644 index 0000000..39be33f --- /dev/null +++ b/examples/basic_phoenix_ecto/lib/demo_web/live/live_helpers.ex @@ -0,0 +1,60 @@ +defmodule DemoWeb.LiveHelpers do + import Phoenix.LiveView + import Phoenix.LiveView.Helpers + + alias Phoenix.LiveView.JS + + @doc """ + Renders a live component inside a modal. + + The rendered modal receives a `:return_to` option to properly update + the URL when the modal is closed. + + ## Examples + + <.modal return_to={Routes.user_index_path(@socket, :index)}> + <.live_component + module={DemoWeb.UserLive.FormComponent} + id={@user.id || :new} + title={@page_title} + action={@live_action} + return_to={Routes.user_index_path(@socket, :index)} + user: @user + /> + + """ + def modal(assigns) do + assigns = assign_new(assigns, :return_to, fn -> nil end) + + ~H""" + + """ + end + + defp hide_modal(js \\ %JS{}) do + js + |> JS.hide(to: "#modal", transition: "fade-out") + |> JS.hide(to: "#modal-content", transition: "fade-out-scale") + end +end diff --git a/examples/basic_phoenix_ecto/lib/demo_web/live/user_live/form_component.ex b/examples/basic_phoenix_ecto/lib/demo_web/live/user_live/form_component.ex new file mode 100644 index 0000000..79de91e --- /dev/null +++ b/examples/basic_phoenix_ecto/lib/demo_web/live/user_live/form_component.ex @@ -0,0 +1,55 @@ +defmodule DemoWeb.UserLive.FormComponent do + use DemoWeb, :live_component + + alias Demo.Accounts + + @impl true + def update(%{user: user} = assigns, socket) do + changeset = Accounts.change_user(user) + + {:ok, + socket + |> assign(assigns) + |> assign(:changeset, changeset)} + end + + @impl true + def handle_event("validate", %{"user" => user_params}, socket) do + changeset = + socket.assigns.user + |> Accounts.change_user(user_params) + |> Map.put(:action, :validate) + + {:noreply, assign(socket, :changeset, changeset)} + end + + def handle_event("save", %{"user" => user_params}, socket) do + save_user(socket, socket.assigns.action, user_params) + end + + defp save_user(socket, :edit, user_params) do + case Accounts.update_user(socket.assigns.user, user_params) do + {:ok, _user} -> + {:noreply, + socket + |> put_flash(:info, "User updated successfully") + |> push_redirect(to: socket.assigns.return_to)} + + {:error, %Ecto.Changeset{} = changeset} -> + {:noreply, assign(socket, :changeset, changeset)} + end + end + + defp save_user(socket, :new, user_params) do + case Accounts.create_user(user_params) do + {:ok, _user} -> + {:noreply, + socket + |> put_flash(:info, "User created successfully") + |> push_redirect(to: socket.assigns.return_to)} + + {:error, %Ecto.Changeset{} = changeset} -> + {:noreply, assign(socket, changeset: changeset)} + end + end +end diff --git a/examples/basic_phoenix_ecto/lib/demo_web/live/user_live/form_component.html.heex b/examples/basic_phoenix_ecto/lib/demo_web/live/user_live/form_component.html.heex new file mode 100644 index 0000000..049b96a --- /dev/null +++ b/examples/basic_phoenix_ecto/lib/demo_web/live/user_live/form_component.html.heex @@ -0,0 +1,20 @@ +
+

<%= @title %>

+ + <.form + let={f} + for={@changeset} + id="user-form" + phx-target={@myself} + phx-change="validate" + phx-submit="save"> + + <%= label f, :name %> + <%= text_input f, :name %> + <%= error_tag f, :name %> + +
+ <%= submit "Save", phx_disable_with: "Saving..." %> +
+ +
diff --git a/examples/basic_phoenix_ecto/lib/demo_web/live/user_live/index.ex b/examples/basic_phoenix_ecto/lib/demo_web/live/user_live/index.ex new file mode 100644 index 0000000..a639249 --- /dev/null +++ b/examples/basic_phoenix_ecto/lib/demo_web/live/user_live/index.ex @@ -0,0 +1,46 @@ +defmodule DemoWeb.UserLive.Index do + use DemoWeb, :live_view + + alias Demo.Accounts + alias Demo.Accounts.User + + @impl true + def mount(_params, _session, socket) do + {:ok, assign(socket, :users, list_users())} + end + + @impl true + def handle_params(params, _url, socket) do + {:noreply, apply_action(socket, socket.assigns.live_action, params)} + end + + defp apply_action(socket, :edit, %{"id" => id}) do + socket + |> assign(:page_title, "Edit User") + |> assign(:user, Accounts.get_user!(id)) + end + + defp apply_action(socket, :new, _params) do + socket + |> assign(:page_title, "New User") + |> assign(:user, %User{}) + end + + defp apply_action(socket, :index, _params) do + socket + |> assign(:page_title, "Listing Users") + |> assign(:user, nil) + end + + @impl true + def handle_event("delete", %{"id" => id}, socket) do + user = Accounts.get_user!(id) + {:ok, _} = Accounts.delete_user(user) + + {:noreply, assign(socket, :users, list_users())} + end + + defp list_users do + Accounts.list_users() + end +end diff --git a/examples/basic_phoenix_ecto/lib/demo_web/live/user_live/index.html.heex b/examples/basic_phoenix_ecto/lib/demo_web/live/user_live/index.html.heex new file mode 100644 index 0000000..58f1b37 --- /dev/null +++ b/examples/basic_phoenix_ecto/lib/demo_web/live/user_live/index.html.heex @@ -0,0 +1,39 @@ +

Listing Users

+ +<%= if @live_action in [:new, :edit] do %> + <.modal return_to={Routes.user_index_path(@socket, :index)}> + <.live_component + module={DemoWeb.UserLive.FormComponent} + id={@user.id || :new} + title={@page_title} + action={@live_action} + user={@user} + return_to={Routes.user_index_path(@socket, :index)} + /> + +<% end %> + + + + + + + + + + + <%= for user <- @users do %> + + + + + + <% end %> + +
Name
<%= user.name %> + <%= live_redirect "Show", to: Routes.user_show_path(@socket, :show, user) %> + <%= live_patch "Edit", to: Routes.user_index_path(@socket, :edit, user) %> + <%= link "Delete", to: "#", phx_click: "delete", phx_value_id: user.id, data: [confirm: "Are you sure?"] %> +
+ +<%= live_patch "New User", to: Routes.user_index_path(@socket, :new) %> diff --git a/examples/basic_phoenix_ecto/lib/demo_web/live/user_live/show.ex b/examples/basic_phoenix_ecto/lib/demo_web/live/user_live/show.ex new file mode 100644 index 0000000..69be883 --- /dev/null +++ b/examples/basic_phoenix_ecto/lib/demo_web/live/user_live/show.ex @@ -0,0 +1,21 @@ +defmodule DemoWeb.UserLive.Show do + use DemoWeb, :live_view + + alias Demo.Accounts + + @impl true + def mount(_params, _session, socket) do + {:ok, socket} + end + + @impl true + def handle_params(%{"id" => id}, _, socket) do + {:noreply, + socket + |> assign(:page_title, page_title(socket.assigns.live_action)) + |> assign(:user, Accounts.get_user!(id))} + end + + defp page_title(:show), do: "Show User" + defp page_title(:edit), do: "Edit User" +end diff --git a/examples/basic_phoenix_ecto/lib/demo_web/live/user_live/show.html.heex b/examples/basic_phoenix_ecto/lib/demo_web/live/user_live/show.html.heex new file mode 100644 index 0000000..c85dca1 --- /dev/null +++ b/examples/basic_phoenix_ecto/lib/demo_web/live/user_live/show.html.heex @@ -0,0 +1,26 @@ +

Show User

+ +<%= if @live_action in [:edit] do %> + <.modal return_to={Routes.user_show_path(@socket, :show, @user)}> + <.live_component + module={DemoWeb.UserLive.FormComponent} + id={@user.id} + title={@page_title} + action={@live_action} + user={@user} + return_to={Routes.user_show_path(@socket, :show, @user)} + /> + +<% end %> + + + +<%= live_patch "Edit", to: Routes.user_show_path(@socket, :edit, @user), class: "button" %> | +<%= live_redirect "Back", to: Routes.user_index_path(@socket, :index) %> diff --git a/examples/basic_phoenix_ecto/lib/demo_web/router.ex b/examples/basic_phoenix_ecto/lib/demo_web/router.ex new file mode 100644 index 0000000..796ffc2 --- /dev/null +++ b/examples/basic_phoenix_ecto/lib/demo_web/router.ex @@ -0,0 +1,65 @@ +defmodule DemoWeb.Router do + use DemoWeb, :router + + pipeline :browser do + plug :accepts, ["html"] + plug :fetch_session + plug :fetch_live_flash + plug :put_root_layout, {DemoWeb.LayoutView, :root} + plug :protect_from_forgery + plug :put_secure_browser_headers + end + + pipeline :api do + plug :accepts, ["json"] + end + + scope "/", DemoWeb do + pipe_through :browser + + get "/", PageController, :index + resources "/posts", PostController + + + live "/users", UserLive.Index, :index + live "/users/new", UserLive.Index, :new + live "/users/:id/edit", UserLive.Index, :edit + + live "/users/:id", UserLive.Show, :show + live "/users/:id/show/edit", UserLive.Show, :edit + end + + # Other scopes may use custom stacks. + # scope "/api", DemoWeb do + # pipe_through :api + # end + + # Enables LiveDashboard only for development + # + # If you want to use the LiveDashboard in production, you should put + # it behind authentication and allow only admins to access it. + # If your application does not have an admins-only section yet, + # you can use Plug.BasicAuth to set up some basic authentication + # as long as you are also using SSL (which you should anyway). + if Mix.env() in [:dev, :test] do + import Phoenix.LiveDashboard.Router + + scope "/" do + pipe_through :browser + + live_dashboard "/dashboard", metrics: DemoWeb.Telemetry + end + end + + # Enables the Swoosh mailbox preview in development. + # + # Note that preview only shows emails that were sent by the same + # node running the Phoenix server. + if Mix.env() == :dev do + scope "/dev" do + pipe_through :browser + + forward "/mailbox", Plug.Swoosh.MailboxPreview + end + end +end diff --git a/examples/basic_phoenix_ecto/lib/demo_web/telemetry.ex b/examples/basic_phoenix_ecto/lib/demo_web/telemetry.ex new file mode 100644 index 0000000..b11369c --- /dev/null +++ b/examples/basic_phoenix_ecto/lib/demo_web/telemetry.ex @@ -0,0 +1,71 @@ +defmodule DemoWeb.Telemetry do + use Supervisor + import Telemetry.Metrics + + def start_link(arg) do + Supervisor.start_link(__MODULE__, arg, name: __MODULE__) + end + + @impl true + def init(_arg) do + children = [ + # Telemetry poller will execute the given period measurements + # every 10_000ms. Learn more here: https://hexdocs.pm/telemetry_metrics + {:telemetry_poller, measurements: periodic_measurements(), period: 10_000} + # Add reporters as children of your supervision tree. + # {Telemetry.Metrics.ConsoleReporter, metrics: metrics()} + ] + + Supervisor.init(children, strategy: :one_for_one) + end + + def metrics do + [ + # Phoenix Metrics + summary("phoenix.endpoint.stop.duration", + unit: {:native, :millisecond} + ), + summary("phoenix.router_dispatch.stop.duration", + tags: [:route], + unit: {:native, :millisecond} + ), + + # Database Metrics + summary("demo.repo.query.total_time", + unit: {:native, :millisecond}, + description: "The sum of the other measurements" + ), + summary("demo.repo.query.decode_time", + unit: {:native, :millisecond}, + description: "The time spent decoding the data received from the database" + ), + summary("demo.repo.query.query_time", + unit: {:native, :millisecond}, + description: "The time spent executing the query" + ), + summary("demo.repo.query.queue_time", + unit: {:native, :millisecond}, + description: "The time spent waiting for a database connection" + ), + summary("demo.repo.query.idle_time", + unit: {:native, :millisecond}, + description: + "The time the connection spent waiting before being checked out for the query" + ), + + # VM Metrics + summary("vm.memory.total", unit: {:byte, :kilobyte}), + summary("vm.total_run_queue_lengths.total"), + summary("vm.total_run_queue_lengths.cpu"), + summary("vm.total_run_queue_lengths.io") + ] + end + + defp periodic_measurements do + [ + # A module, function and arguments to be invoked periodically. + # This function must call :telemetry.execute/3 and a metric must be added above. + # {DemoWeb, :count_users, []} + ] + end +end diff --git a/examples/basic_phoenix_ecto/lib/demo_web/templates/layout/app.html.heex b/examples/basic_phoenix_ecto/lib/demo_web/templates/layout/app.html.heex new file mode 100644 index 0000000..169aed9 --- /dev/null +++ b/examples/basic_phoenix_ecto/lib/demo_web/templates/layout/app.html.heex @@ -0,0 +1,5 @@ +
+ + + <%= @inner_content %> +
diff --git a/examples/basic_phoenix_ecto/lib/demo_web/templates/layout/live.html.heex b/examples/basic_phoenix_ecto/lib/demo_web/templates/layout/live.html.heex new file mode 100644 index 0000000..a29d604 --- /dev/null +++ b/examples/basic_phoenix_ecto/lib/demo_web/templates/layout/live.html.heex @@ -0,0 +1,11 @@ +
+ + + + + <%= @inner_content %> +
diff --git a/examples/basic_phoenix_ecto/lib/demo_web/templates/layout/root.html.heex b/examples/basic_phoenix_ecto/lib/demo_web/templates/layout/root.html.heex new file mode 100644 index 0000000..a89e1b2 --- /dev/null +++ b/examples/basic_phoenix_ecto/lib/demo_web/templates/layout/root.html.heex @@ -0,0 +1,30 @@ + + + + + + + <%= csrf_meta_tag() %> + <%= live_title_tag assigns[:page_title] || "Demo", suffix: " · Phoenix Framework" %> + + + + +
+
+ + +
+
+ <%= @inner_content %> + + diff --git a/examples/basic_phoenix_ecto/lib/demo_web/templates/page/index.html.heex b/examples/basic_phoenix_ecto/lib/demo_web/templates/page/index.html.heex new file mode 100644 index 0000000..f844bd8 --- /dev/null +++ b/examples/basic_phoenix_ecto/lib/demo_web/templates/page/index.html.heex @@ -0,0 +1,41 @@ +
+

<%= gettext "Welcome to %{name}!", name: "Phoenix" %>

+

Peace of mind from prototype to production

+
+ +
+
+

Resources

+ +
+
+

Help

+ +
+
diff --git a/examples/basic_phoenix_ecto/lib/demo_web/templates/post/edit.html.heex b/examples/basic_phoenix_ecto/lib/demo_web/templates/post/edit.html.heex new file mode 100644 index 0000000..acf4282 --- /dev/null +++ b/examples/basic_phoenix_ecto/lib/demo_web/templates/post/edit.html.heex @@ -0,0 +1,5 @@ +

Edit Post

+ +<%= render "form.html", Map.put(assigns, :action, Routes.post_path(@conn, :update, @post)) %> + +<%= link "Back", to: Routes.post_path(@conn, :index) %> diff --git a/examples/basic_phoenix_ecto/lib/demo_web/templates/post/form.html.heex b/examples/basic_phoenix_ecto/lib/demo_web/templates/post/form.html.heex new file mode 100644 index 0000000..b43cdd2 --- /dev/null +++ b/examples/basic_phoenix_ecto/lib/demo_web/templates/post/form.html.heex @@ -0,0 +1,19 @@ +<.form let={f} for={@changeset} action={@action}> + <%= if @changeset.action do %> +
+

Oops, something went wrong! Please check the errors below.

+
+ <% end %> + + <%= label f, :title %> + <%= text_input f, :title %> + <%= error_tag f, :title %> + + <%= label f, :body %> + <%= textarea f, :body %> + <%= error_tag f, :body %> + +
+ <%= submit "Save" %> +
+ diff --git a/examples/basic_phoenix_ecto/lib/demo_web/templates/post/index.html.heex b/examples/basic_phoenix_ecto/lib/demo_web/templates/post/index.html.heex new file mode 100644 index 0000000..d9dda04 --- /dev/null +++ b/examples/basic_phoenix_ecto/lib/demo_web/templates/post/index.html.heex @@ -0,0 +1,28 @@ +

Listing Posts

+ + + + + + + + + + + +<%= for post <- @posts do %> + + + + + + +<% end %> + +
TitleBody
<%= post.title %><%= post.body %> + <%= link "Show", to: Routes.post_path(@conn, :show, post) %> + <%= link "Edit", to: Routes.post_path(@conn, :edit, post) %> + <%= link "Delete", to: Routes.post_path(@conn, :delete, post), method: :delete, data: [confirm: "Are you sure?"] %> +
+ +<%= link "New Post", to: Routes.post_path(@conn, :new) %> diff --git a/examples/basic_phoenix_ecto/lib/demo_web/templates/post/new.html.heex b/examples/basic_phoenix_ecto/lib/demo_web/templates/post/new.html.heex new file mode 100644 index 0000000..290286d --- /dev/null +++ b/examples/basic_phoenix_ecto/lib/demo_web/templates/post/new.html.heex @@ -0,0 +1,5 @@ +

New Post

+ +<%= render "form.html", Map.put(assigns, :action, Routes.post_path(@conn, :create)) %> + +<%= link "Back", to: Routes.post_path(@conn, :index) %> diff --git a/examples/basic_phoenix_ecto/lib/demo_web/templates/post/show.html.heex b/examples/basic_phoenix_ecto/lib/demo_web/templates/post/show.html.heex new file mode 100644 index 0000000..3bc7bcb --- /dev/null +++ b/examples/basic_phoenix_ecto/lib/demo_web/templates/post/show.html.heex @@ -0,0 +1,18 @@ +

Show Post

+ + + +<%= link "Edit", to: Routes.post_path(@conn, :edit, @post) %> | +<%= link "Back", to: Routes.post_path(@conn, :index) %> diff --git a/examples/basic_phoenix_ecto/lib/demo_web/views/error_helpers.ex b/examples/basic_phoenix_ecto/lib/demo_web/views/error_helpers.ex new file mode 100644 index 0000000..430582e --- /dev/null +++ b/examples/basic_phoenix_ecto/lib/demo_web/views/error_helpers.ex @@ -0,0 +1,47 @@ +defmodule DemoWeb.ErrorHelpers do + @moduledoc """ + Conveniences for translating and building error messages. + """ + + use Phoenix.HTML + + @doc """ + Generates tag for inlined form input errors. + """ + def error_tag(form, field) do + Enum.map(Keyword.get_values(form.errors, field), fn error -> + content_tag(:span, translate_error(error), + class: "invalid-feedback", + phx_feedback_for: input_name(form, field) + ) + end) + end + + @doc """ + Translates an error message using gettext. + """ + def translate_error({msg, opts}) do + # When using gettext, we typically pass the strings we want + # to translate as a static argument: + # + # # Translate "is invalid" in the "errors" domain + # dgettext("errors", "is invalid") + # + # # Translate the number of files with plural rules + # dngettext("errors", "1 file", "%{count} files", count) + # + # Because the error messages we show in our forms and APIs + # are defined inside Ecto, we need to translate them dynamically. + # This requires us to call the Gettext module passing our gettext + # backend as first argument. + # + # Note we use the "errors" domain, which means translations + # should be written to the errors.po file. The :count option is + # set by Ecto and indicates we should also apply plural rules. + if count = opts[:count] do + Gettext.dngettext(DemoWeb.Gettext, "errors", msg, msg, count, opts) + else + Gettext.dgettext(DemoWeb.Gettext, "errors", msg, opts) + end + end +end diff --git a/examples/basic_phoenix_ecto/lib/demo_web/views/error_view.ex b/examples/basic_phoenix_ecto/lib/demo_web/views/error_view.ex new file mode 100644 index 0000000..c0ccfcb --- /dev/null +++ b/examples/basic_phoenix_ecto/lib/demo_web/views/error_view.ex @@ -0,0 +1,16 @@ +defmodule DemoWeb.ErrorView do + use DemoWeb, :view + + # If you want to customize a particular status code + # for a certain format, you may uncomment below. + # def render("500.html", _assigns) do + # "Internal Server Error" + # end + + # By default, Phoenix returns the status message from + # the template name. For example, "404.html" becomes + # "Not Found". + def template_not_found(template, _assigns) do + Phoenix.Controller.status_message_from_template(template) + end +end diff --git a/examples/basic_phoenix_ecto/lib/demo_web/views/layout_view.ex b/examples/basic_phoenix_ecto/lib/demo_web/views/layout_view.ex new file mode 100644 index 0000000..349ef80 --- /dev/null +++ b/examples/basic_phoenix_ecto/lib/demo_web/views/layout_view.ex @@ -0,0 +1,7 @@ +defmodule DemoWeb.LayoutView do + use DemoWeb, :view + + # Phoenix LiveDashboard is available only in development by default, + # so we instruct Elixir to not warn if the dashboard route is missing. + @compile {:no_warn_undefined, {Routes, :live_dashboard_path, 2}} +end diff --git a/examples/basic_phoenix_ecto/lib/demo_web/views/page_view.ex b/examples/basic_phoenix_ecto/lib/demo_web/views/page_view.ex new file mode 100644 index 0000000..1d32e3c --- /dev/null +++ b/examples/basic_phoenix_ecto/lib/demo_web/views/page_view.ex @@ -0,0 +1,3 @@ +defmodule DemoWeb.PageView do + use DemoWeb, :view +end diff --git a/examples/basic_phoenix_ecto/lib/demo_web/views/post_view.ex b/examples/basic_phoenix_ecto/lib/demo_web/views/post_view.ex new file mode 100644 index 0000000..58809e0 --- /dev/null +++ b/examples/basic_phoenix_ecto/lib/demo_web/views/post_view.ex @@ -0,0 +1,3 @@ +defmodule DemoWeb.PostView do + use DemoWeb, :view +end diff --git a/examples/basic_phoenix_ecto/mix.exs b/examples/basic_phoenix_ecto/mix.exs new file mode 100644 index 0000000..ca8bdb7 --- /dev/null +++ b/examples/basic_phoenix_ecto/mix.exs @@ -0,0 +1,74 @@ +defmodule Demo.MixProject do + use Mix.Project + + def project do + [ + app: :demo, + version: "0.1.0", + elixir: "~> 1.12", + elixirc_paths: elixirc_paths(Mix.env()), + compilers: [:gettext] ++ Mix.compilers(), + start_permanent: Mix.env() == :prod, + aliases: aliases(), + deps: deps() + ] + end + + # Configuration for the OTP application. + # + # Type `mix help compile.app` for more information. + def application do + [ + mod: {Demo.Application, []}, + extra_applications: [:logger, :runtime_tools] + ] + end + + # Specifies which paths to compile per environment. + defp elixirc_paths(:test), do: ["lib", "test/support"] + defp elixirc_paths(_), do: ["lib"] + + # Specifies your project dependencies. + # + # Type `mix help deps` for examples and options. + defp deps do + [ + {:phoenix, "~> 1.6.6"}, + {:phoenix_ecto, "~> 4.4"}, + {:ecto_sql, "~> 3.6"}, + {:postgrex, ">= 0.0.0"}, + {:phoenix_html, "~> 3.0"}, + {:phoenix_live_reload, "~> 1.2", only: :dev}, + {:phoenix_live_view, "~> 0.17.5"}, + {:floki, ">= 0.30.0", only: :test}, + {:phoenix_live_dashboard, "~> 0.6"}, + {:esbuild, "~> 0.3", runtime: Mix.env() == :dev}, + {:swoosh, "~> 1.3"}, + {:telemetry_metrics, "~> 0.6"}, + {:telemetry_poller, "~> 1.0"}, + {:gettext, "~> 0.18"}, + {:jason, "~> 1.2"}, + {:plug_cowboy, "~> 2.5"}, + + {:opentelemetry_phoenix, "~> 1.0.0-rc.7"}, + {:opentelemetry_ecto, "~> 1.0.0-rc.5"}, + {:opentelemetry_exporter, "~> 1.0.0"} + ] + end + + # Aliases are shortcuts or tasks specific to the current project. + # For example, to install project dependencies and perform other setup tasks, run: + # + # $ mix setup + # + # See the documentation for `Mix` for more info on aliases. + defp aliases do + [ + setup: ["deps.get", "ecto.setup"], + "ecto.setup": ["ecto.create", "ecto.migrate", "run priv/repo/seeds.exs"], + "ecto.reset": ["ecto.drop", "ecto.setup"], + test: ["ecto.create --quiet", "ecto.migrate --quiet", "test"], + "assets.deploy": ["esbuild default --minify", "phx.digest"] + ] + end +end diff --git a/examples/basic_phoenix_ecto/mix.lock b/examples/basic_phoenix_ecto/mix.lock new file mode 100644 index 0000000..ebc9ff1 --- /dev/null +++ b/examples/basic_phoenix_ecto/mix.lock @@ -0,0 +1,50 @@ +%{ + "acceptor_pool": {:hex, :acceptor_pool, "1.0.0", "43c20d2acae35f0c2bcd64f9d2bde267e459f0f3fd23dab26485bf518c281b21", [:rebar3], [], "hexpm", "0cbcd83fdc8b9ad2eee2067ef8b91a14858a5883cb7cd800e6fcd5803e158788"}, + "castore": {:hex, :castore, "0.1.14", "3f6d7c7c1574c402fef29559d3f1a7389ba3524bc6a090a5e9e6abc3af65dcca", [:mix], [], "hexpm", "b34af542eadb727e6c8b37fdf73e18b2e02eb483a4ea0b52fd500bc23f052b7b"}, + "chatterbox": {:hex, :ts_chatterbox, "0.11.0", "b8f372c706023eb0de5bf2976764edb27c70fe67052c88c1f6a66b3a5626847f", [:rebar3], [{:hpack, "~>0.2.3", [hex: :hpack_erl, repo: "hexpm", optional: false]}], "hexpm", "722fe2bad52913ab7e87d849fc6370375f0c961ffb2f0b5e6d647c9170c382a6"}, + "connection": {:hex, :connection, "1.1.0", "ff2a49c4b75b6fb3e674bfc5536451607270aac754ffd1bdfe175abe4a6d7a68", [:mix], [], "hexpm", "722c1eb0a418fbe91ba7bd59a47e28008a189d47e37e0e7bb85585a016b2869c"}, + "cowboy": {:hex, :cowboy, "2.9.0", "865dd8b6607e14cf03282e10e934023a1bd8be6f6bacf921a7e2a96d800cd452", [:make, :rebar3], [{:cowlib, "2.11.0", [hex: :cowlib, repo: "hexpm", optional: false]}, {:ranch, "1.8.0", [hex: :ranch, repo: "hexpm", optional: false]}], "hexpm", "2c729f934b4e1aa149aff882f57c6372c15399a20d54f65c8d67bef583021bde"}, + "cowboy_telemetry": {:hex, :cowboy_telemetry, "0.4.0", "f239f68b588efa7707abce16a84d0d2acf3a0f50571f8bb7f56a15865aae820c", [:rebar3], [{:cowboy, "~> 2.7", [hex: :cowboy, repo: "hexpm", optional: false]}, {:telemetry, "~> 1.0", [hex: :telemetry, repo: "hexpm", optional: false]}], "hexpm", "7d98bac1ee4565d31b62d59f8823dfd8356a169e7fcbb83831b8a5397404c9de"}, + "cowlib": {:hex, :cowlib, "2.11.0", "0b9ff9c346629256c42ebe1eeb769a83c6cb771a6ee5960bd110ab0b9b872063", [:make, :rebar3], [], "hexpm", "2b3e9da0b21c4565751a6d4901c20d1b4cc25cbb7fd50d91d2ab6dd287bc86a9"}, + "ctx": {:hex, :ctx, "0.6.0", "8ff88b70e6400c4df90142e7f130625b82086077a45364a78d208ed3ed53c7fe", [:rebar3], [], "hexpm", "a14ed2d1b67723dbebbe423b28d7615eb0bdcba6ff28f2d1f1b0a7e1d4aa5fc2"}, + "db_connection": {:hex, :db_connection, "2.4.1", "6411f6e23f1a8b68a82fa3a36366d4881f21f47fc79a9efb8c615e62050219da", [:mix], [{:connection, "~> 1.0", [hex: :connection, repo: "hexpm", optional: false]}, {:telemetry, "~> 0.4 or ~> 1.0", [hex: :telemetry, repo: "hexpm", optional: false]}], "hexpm", "ea36d226ec5999781a9a8ad64e5d8c4454ecedc7a4d643e4832bf08efca01f00"}, + "decimal": {:hex, :decimal, "2.0.0", "a78296e617b0f5dd4c6caf57c714431347912ffb1d0842e998e9792b5642d697", [:mix], [], "hexpm", "34666e9c55dea81013e77d9d87370fe6cb6291d1ef32f46a1600230b1d44f577"}, + "ecto": {:hex, :ecto, "3.7.1", "a20598862351b29f80f285b21ec5297da1181c0442687f9b8329f0445d228892", [:mix], [{:decimal, "~> 1.6 or ~> 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", "d36e5b39fc479e654cffd4dbe1865d9716e4a9b6311faff799b6f90ab81b8638"}, + "ecto_sql": {:hex, :ecto_sql, "3.7.1", "8de624ef50b2a8540252d8c60506379fbbc2707be1606853df371cf53df5d053", [:mix], [{:db_connection, "~> 2.2", [hex: :db_connection, repo: "hexpm", optional: false]}, {:ecto, "~> 3.7.0", [hex: :ecto, repo: "hexpm", optional: false]}, {:myxql, "~> 0.4.0 or ~> 0.5.0", [hex: :myxql, repo: "hexpm", optional: true]}, {:postgrex, "~> 0.15.0 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", "2b42a32e2ce92f64aba5c88617891ab3b0ba34f3f3a503fa20009eae1a401c81"}, + "esbuild": {:hex, :esbuild, "0.4.0", "9f17db148aead4cf1e6e6a584214357287a93407b5fb51a031f122b61385d4c2", [:mix], [{:castore, ">= 0.0.0", [hex: :castore, repo: "hexpm", optional: false]}], "hexpm", "b61e4e6b92ffe45e4ee4755a22de6211a67c67987dc02afb35a425a0add1d447"}, + "file_system": {:hex, :file_system, "0.2.10", "fb082005a9cd1711c05b5248710f8826b02d7d1784e7c3451f9c1231d4fc162d", [:mix], [], "hexpm", "41195edbfb562a593726eda3b3e8b103a309b733ad25f3d642ba49696bf715dc"}, + "floki": {:hex, :floki, "0.32.0", "f915dc15258bc997d49be1f5ef7d3992f8834d6f5695270acad17b41f5bcc8e2", [:mix], [{:html_entities, "~> 0.5.0", [hex: :html_entities, repo: "hexpm", optional: false]}], "hexpm", "1c5a91cae1fd8931c26a4826b5e2372c284813904c8bacb468b5de39c7ececbd"}, + "gettext": {:hex, :gettext, "0.19.0", "6909d61b38bb33339558f128f8af5913d5d5fe304a770217bf352b1620fb7ec4", [:mix], [], "hexpm", "3f7a274f52ebda9bb6655dfeda3d6b0dc4537ae51ce41dcccc7f73ca7379ad5e"}, + "gproc": {:hex, :gproc, "0.8.0", "cea02c578589c61e5341fce149ea36ccef236cc2ecac8691fba408e7ea77ec2f", [:rebar3], [], "hexpm", "580adafa56463b75263ef5a5df4c86af321f68694e7786cb057fd805d1e2a7de"}, + "grpcbox": {:hex, :grpcbox, "0.14.0", "3eb321bcd2275baf8b54cf381feb7b0559a50c02544de28fda039c7f2f9d1a7a", [:rebar3], [{:acceptor_pool, "~>1.0.0", [hex: :acceptor_pool, repo: "hexpm", optional: false]}, {:chatterbox, "~>0.11.0", [hex: :ts_chatterbox, repo: "hexpm", optional: false]}, {:ctx, "~>0.6.0", [hex: :ctx, repo: "hexpm", optional: false]}, {:gproc, "~>0.8.0", [hex: :gproc, repo: "hexpm", optional: false]}], "hexpm", "e24159b7b6d3f9869bbe528845c0125fed2259366ba908fd04a1f45fe81d0660"}, + "hpack": {:hex, :hpack_erl, "0.2.3", "17670f83ff984ae6cd74b1c456edde906d27ff013740ee4d9efaa4f1bf999633", [:rebar3], [], "hexpm", "06f580167c4b8b8a6429040df36cc93bba6d571faeaec1b28816523379cbb23a"}, + "html_entities": {:hex, :html_entities, "0.5.2", "9e47e70598da7de2a9ff6af8758399251db6dbb7eebe2b013f2bbd2515895c3c", [:mix], [], "hexpm", "c53ba390403485615623b9531e97696f076ed415e8d8058b1dbaa28181f4fdcc"}, + "jason": {:hex, :jason, "1.3.0", "fa6b82a934feb176263ad2df0dbd91bf633d4a46ebfdffea0c8ae82953714946", [:mix], [{:decimal, "~> 1.0 or ~> 2.0", [hex: :decimal, repo: "hexpm", optional: true]}], "hexpm", "53fc1f51255390e0ec7e50f9cb41e751c260d065dcba2bf0d08dc51a4002c2ac"}, + "mime": {:hex, :mime, "2.0.2", "0b9e1a4c840eafb68d820b0e2158ef5c49385d17fb36855ac6e7e087d4b1dcc5", [:mix], [], "hexpm", "e6a3f76b4c277739e36c2e21a2c640778ba4c3846189d5ab19f97f126df5f9b7"}, + "opentelemetry": {:hex, :opentelemetry, "1.0.0", "6e98f4a9230681b2e4c88d45783ce1c02d671ffc0b5ac0cba69a34a3f5ada8d8", [:rebar3], [{:opentelemetry_api, "~> 1.0.0", [hex: :opentelemetry_api, repo: "hexpm", optional: false]}], "hexpm", "08d8697740f70594d05067cb62a0a8845ff568b2d47e1f8c78c46708ab58a74f"}, + "opentelemetry_api": {:hex, :opentelemetry_api, "1.0.0", "6e501f750ead189f35aed07eb8023fa6655fca12f913a196102f67db4ed5172c", [:mix, :rebar3], [], "hexpm", "ac51520bde21fdea7f82cea9236ce4e88a21281c22bc23b0f1fa3b28b4352fcf"}, + "opentelemetry_ecto": {:hex, :opentelemetry_ecto, "1.0.0-rc.5", "b674ddc948fc1dd2fdc1e7fb0797c5d610d60ee5969a8424af36f582b8b0086c", [:mix], [{:opentelemetry_api, "~> 1.0", [hex: :opentelemetry_api, repo: "hexpm", optional: false]}, {:telemetry, "~> 0.4 or ~> 1.0.0", [hex: :telemetry, repo: "hexpm", optional: false]}], "hexpm", "211fa6776abfb8be54bdd57206c99541c1955e6fe68eb5ee4611dc697240deed"}, + "opentelemetry_exporter": {:hex, :opentelemetry_exporter, "1.0.0", "12fd928e72dec8108d40214a667e7a90026827d6268db678617c9e40ec3dc931", [:rebar3], [{:grpcbox, ">= 0.0.0", [hex: :grpcbox, repo: "hexpm", optional: false]}, {:opentelemetry, "~> 1.0", [hex: :opentelemetry, repo: "hexpm", optional: false]}, {:opentelemetry_api, "~> 1.0", [hex: :opentelemetry_api, repo: "hexpm", optional: false]}, {:tls_certificate_check, "~> 1.11", [hex: :tls_certificate_check, repo: "hexpm", optional: false]}], "hexpm", "e2d2377abfb823cc99c1b68b4ce31df1ff1ce63e0c7bdbee7a7527e2d825168d"}, + "opentelemetry_phoenix": {:hex, :opentelemetry_phoenix, "1.0.0-rc.7", "b8829206cbb1539cb8e516908570b92cba5d7d5fd57319fa823e71e385515e71", [:mix], [{:opentelemetry_api, "~> 1.0", [hex: :opentelemetry_api, repo: "hexpm", optional: false]}, {:opentelemetry_telemetry, "~> 1.0.0-beta.7", [hex: :opentelemetry_telemetry, repo: "hexpm", optional: false]}, {:plug, ">= 1.11.0", [hex: :plug, repo: "hexpm", optional: false]}, {:telemetry, "~> 0.4 or ~> 1.0.0", [hex: :telemetry, repo: "hexpm", optional: false]}], "hexpm", "233a02e1f485ad106e8bbb8d9cefff64305bf2cff55a68c1d9bda3b54d0460c5"}, + "opentelemetry_telemetry": {:hex, :opentelemetry_telemetry, "1.0.0-beta.7", "ba1df62515aed63f99a80ddf17e7a3873d1f686f23598edebf1633942772856e", [:mix, :rebar3], [{:opentelemetry_api, "~> 1.0", [hex: :opentelemetry_api, repo: "hexpm", optional: false]}, {:telemetry, "~> 1.0", [hex: :telemetry, repo: "hexpm", optional: false]}, {:telemetry_registry, "~> 0.3.0", [hex: :telemetry_registry, repo: "hexpm", optional: false]}], "hexpm", "480f4fa1e992d597f931e7bc9e68478e8d904ad84489d2c5ca6eb6d48bbd7801"}, + "phoenix": {:hex, :phoenix, "1.6.6", "281c8ce8dccc9f60607346b72cdfc597c3dde134dd9df28dff08282f0b751754", [:mix], [{:jason, "~> 1.0", [hex: :jason, repo: "hexpm", optional: true]}, {:phoenix_pubsub, "~> 2.0", [hex: :phoenix_pubsub, repo: "hexpm", optional: false]}, {:phoenix_view, "~> 1.0", [hex: :phoenix_view, repo: "hexpm", optional: false]}, {:plug, "~> 1.10", [hex: :plug, repo: "hexpm", optional: false]}, {:plug_cowboy, "~> 2.2", [hex: :plug_cowboy, repo: "hexpm", optional: true]}, {:plug_crypto, "~> 1.2", [hex: :plug_crypto, repo: "hexpm", optional: false]}, {:telemetry, "~> 0.4 or ~> 1.0", [hex: :telemetry, repo: "hexpm", optional: false]}], "hexpm", "807bd646e64cd9dc83db016199715faba72758e6db1de0707eef0a2da4924364"}, + "phoenix_ecto": {:hex, :phoenix_ecto, "4.4.0", "0672ed4e4808b3fbed494dded89958e22fb882de47a97634c0b13e7b0b5f7720", [:mix], [{:ecto, "~> 3.3", [hex: :ecto, repo: "hexpm", optional: false]}, {:phoenix_html, "~> 2.14.2 or ~> 3.0", [hex: :phoenix_html, repo: "hexpm", optional: true]}, {:plug, "~> 1.9", [hex: :plug, repo: "hexpm", optional: false]}], "hexpm", "09864e558ed31ee00bd48fcc1d4fc58ae9678c9e81649075431e69dbabb43cc1"}, + "phoenix_html": {:hex, :phoenix_html, "3.2.0", "1c1219d4b6cb22ac72f12f73dc5fad6c7563104d083f711c3fcd8551a1f4ae11", [:mix], [{:plug, "~> 1.5", [hex: :plug, repo: "hexpm", optional: true]}], "hexpm", "36ec97ba56d25c0136ef1992c37957e4246b649d620958a1f9fa86165f8bc54f"}, + "phoenix_live_dashboard": {:hex, :phoenix_live_dashboard, "0.6.2", "0769470265eb13af01b5001b29cb935f4710d6adaa1ffc18417a570a337a2f0f", [:mix], [{:ecto, "~> 3.6.2 or ~> 3.7", [hex: :ecto, repo: "hexpm", optional: true]}, {:ecto_mysql_extras, "~> 0.3", [hex: :ecto_mysql_extras, repo: "hexpm", optional: true]}, {:ecto_psql_extras, "~> 0.7", [hex: :ecto_psql_extras, repo: "hexpm", optional: true]}, {:mime, "~> 1.6 or ~> 2.0", [hex: :mime, repo: "hexpm", optional: false]}, {:phoenix_live_view, "~> 0.17.1", [hex: :phoenix_live_view, repo: "hexpm", optional: false]}, {:telemetry_metrics, "~> 0.6.0", [hex: :telemetry_metrics, repo: "hexpm", optional: false]}], "hexpm", "5bc6c6b38a2ca8b5020b442322fcee6afd5e641637a0b1fb059d4bd89bc58e7b"}, + "phoenix_live_reload": {:hex, :phoenix_live_reload, "1.3.3", "3a53772a6118d5679bf50fc1670505a290e32a1d195df9e069d8c53ab040c054", [:mix], [{:file_system, "~> 0.2.1 or ~> 0.3", [hex: :file_system, repo: "hexpm", optional: false]}, {:phoenix, "~> 1.4", [hex: :phoenix, repo: "hexpm", optional: false]}], "hexpm", "766796676e5f558dbae5d1bdb066849673e956005e3730dfd5affd7a6da4abac"}, + "phoenix_live_view": {:hex, :phoenix_live_view, "0.17.5", "63f52a6f9f6983f04e424586ff897c016ecc5e4f8d1e2c22c2887af1c57215d8", [:mix], [{:jason, "~> 1.0", [hex: :jason, repo: "hexpm", optional: true]}, {:phoenix, "~> 1.5.9 or ~> 1.6.0", [hex: :phoenix, repo: "hexpm", optional: false]}, {:phoenix_html, "~> 3.1", [hex: :phoenix_html, repo: "hexpm", optional: false]}, {:telemetry, "~> 0.4.2 or ~> 1.0", [hex: :telemetry, repo: "hexpm", optional: false]}], "hexpm", "c5586e6a3d4df71b8214c769d4f5eb8ece2b4001711a7ca0f97323c36958b0e3"}, + "phoenix_pubsub": {:hex, :phoenix_pubsub, "2.0.0", "a1ae76717bb168cdeb10ec9d92d1480fec99e3080f011402c0a2d68d47395ffb", [:mix], [], "hexpm", "c52d948c4f261577b9c6fa804be91884b381a7f8f18450c5045975435350f771"}, + "phoenix_view": {:hex, :phoenix_view, "1.1.0", "149f053830ec3c19a2a8a67c208885a26e4c2b92cc4a9d54e03b633d68ef9add", [:mix], [{:phoenix_html, "~> 2.14.2 or ~> 3.0", [hex: :phoenix_html, repo: "hexpm", optional: true]}], "hexpm", "dd219f768b3d97a224ed11e8a83f4fd0f3bd490434d3950d7c51a2e597a762f1"}, + "plug": {:hex, :plug, "1.12.1", "645678c800601d8d9f27ad1aebba1fdb9ce5b2623ddb961a074da0b96c35187d", [:mix], [{:mime, "~> 1.0 or ~> 2.0", [hex: :mime, repo: "hexpm", optional: false]}, {:plug_crypto, "~> 1.1.1 or ~> 1.2", [hex: :plug_crypto, repo: "hexpm", optional: false]}, {:telemetry, "~> 0.4.3 or ~> 1.0", [hex: :telemetry, repo: "hexpm", optional: false]}], "hexpm", "d57e799a777bc20494b784966dc5fbda91eb4a09f571f76545b72a634ce0d30b"}, + "plug_cowboy": {:hex, :plug_cowboy, "2.5.2", "62894ccd601cf9597e2c23911ff12798a8a18d237e9739f58a6b04e4988899fe", [:mix], [{:cowboy, "~> 2.7", [hex: :cowboy, repo: "hexpm", optional: false]}, {:cowboy_telemetry, "~> 0.3", [hex: :cowboy_telemetry, repo: "hexpm", optional: false]}, {:plug, "~> 1.7", [hex: :plug, repo: "hexpm", optional: false]}], "hexpm", "ea6e87f774c8608d60c8d34022a7d073bd7680a0a013f049fc62bf35efea1044"}, + "plug_crypto": {:hex, :plug_crypto, "1.2.2", "05654514ac717ff3a1843204b424477d9e60c143406aa94daf2274fdd280794d", [:mix], [], "hexpm", "87631c7ad914a5a445f0a3809f99b079113ae4ed4b867348dd9eec288cecb6db"}, + "postgrex": {:hex, :postgrex, "0.15.13", "7794e697481799aee8982688c261901de493eb64451feee6ea58207d7266d54a", [:mix], [{:connection, "~> 1.0", [hex: :connection, repo: "hexpm", optional: false]}, {: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]}], "hexpm", "3ffb76e1a97cfefe5c6a95632a27ffb67f28871c9741fb585f9d1c3cd2af70f1"}, + "ranch": {:hex, :ranch, "1.8.0", "8c7a100a139fd57f17327b6413e4167ac559fbc04ca7448e9be9057311597a1d", [:make, :rebar3], [], "hexpm", "49fbcfd3682fab1f5d109351b61257676da1a2fdbe295904176d5e521a2ddfe5"}, + "ssl_verify_fun": {:hex, :ssl_verify_fun, "1.1.6", "cf344f5692c82d2cd7554f5ec8fd961548d4fd09e7d22f5b62482e5aeaebd4b0", [:make, :mix, :rebar3], [], "hexpm", "bdb0d2471f453c88ff3908e7686f86f9be327d065cc1ec16fa4540197ea04680"}, + "swoosh": {:hex, :swoosh, "1.5.2", "c246e0038367bf9ac3b66715151930a7215eb7427c242cc5206fc59fa344a7dc", [:mix], [{:cowboy, "~> 1.1 or ~> 2.4", [hex: :cowboy, repo: "hexpm", optional: true]}, {:finch, "~> 0.6", [hex: :finch, repo: "hexpm", optional: true]}, {:gen_smtp, "~> 0.13 or ~> 1.0", [hex: :gen_smtp, repo: "hexpm", optional: true]}, {:hackney, "~> 1.9", [hex: :hackney, repo: "hexpm", optional: true]}, {:jason, "~> 1.0", [hex: :jason, repo: "hexpm", optional: false]}, {:mail, "~> 0.2", [hex: :mail, repo: "hexpm", optional: true]}, {:mime, "~> 1.1 or ~> 2.0", [hex: :mime, repo: "hexpm", optional: false]}, {:plug_cowboy, ">= 1.0.0", [hex: :plug_cowboy, repo: "hexpm", optional: true]}, {:telemetry, "~> 0.4.2 or ~> 1.0", [hex: :telemetry, repo: "hexpm", optional: false]}], "hexpm", "fc34b2c14afaa6e2cd92c829492536887a00ae625e404e40469926949b029605"}, + "telemetry": {:hex, :telemetry, "1.0.0", "0f453a102cdf13d506b7c0ab158324c337c41f1cc7548f0bc0e130bbf0ae9452", [:rebar3], [], "hexpm", "73bc09fa59b4a0284efb4624335583c528e07ec9ae76aca96ea0673850aec57a"}, + "telemetry_metrics": {:hex, :telemetry_metrics, "0.6.1", "315d9163a1d4660aedc3fee73f33f1d355dcc76c5c3ab3d59e76e3edf80eef1f", [:mix], [{:telemetry, "~> 0.4 or ~> 1.0", [hex: :telemetry, repo: "hexpm", optional: false]}], "hexpm", "7be9e0871c41732c233be71e4be11b96e56177bf15dde64a8ac9ce72ac9834c6"}, + "telemetry_poller": {:hex, :telemetry_poller, "1.0.0", "db91bb424e07f2bb6e73926fcafbfcbcb295f0193e0a00e825e589a0a47e8453", [:rebar3], [{:telemetry, "~> 1.0", [hex: :telemetry, repo: "hexpm", optional: false]}], "hexpm", "b3a24eafd66c3f42da30fc3ca7dda1e9d546c12250a2d60d7b81d264fbec4f6e"}, + "telemetry_registry": {:hex, :telemetry_registry, "0.3.0", "6768f151ea53fc0fbca70dbff5b20a8d663ee4e0c0b2ae589590e08658e76f1e", [:mix, :rebar3], [{:telemetry, "~> 1.0", [hex: :telemetry, repo: "hexpm", optional: false]}], "hexpm", "492e2adbc609f3e79ece7f29fec363a97a2c484ac78a83098535d6564781e917"}, + "tls_certificate_check": {:hex, :tls_certificate_check, "1.11.0", "609dcd503f31170f0799dac380eb0e086388cf918fc769aaa60ddd6bbf575218", [:rebar3], [{:ssl_verify_fun, "1.1.6", [hex: :ssl_verify_fun, repo: "hexpm", optional: false]}], "hexpm", "4ab962212ef7c87482619cb298e1fe06e047b57f0bd58cc417b3b299eb8d036e"}, +} diff --git a/examples/basic_phoenix_ecto/otel-collector-config.yaml b/examples/basic_phoenix_ecto/otel-collector-config.yaml new file mode 100644 index 0000000..4d26be1 --- /dev/null +++ b/examples/basic_phoenix_ecto/otel-collector-config.yaml @@ -0,0 +1,40 @@ +receivers: + otlp: + protocols: + grpc: + http: +processors: + batch: + send_batch_size: 1024 + timeout: 5s +exporters: + otlp: + # Uncomment below for using Honeycomb + # endpoint: "api.honeycomb.io:443" + # headers: + # "x-honeycomb-team": "" + # "x-honeycomb-dataset": "" + # Uncomment below for using Lightstep + # endpoint: ingest.lightstep.com:443 + # headers: + # "lightstep-access-token": "" + zipkin: + endpoint: "http://zipkin:9411/api/v2/spans" + jaeger: + endpoint: jaeger-all-in-one:14250 + tls: + insecure: true +extensions: + zpages: {} +service: + extensions: [zpages] + pipelines: + traces: + receivers: [otlp] + processors: [batch] + exporters: [zipkin, jaeger] + # Add 'otlp' if you're exporting to Honeycomb + # or Lightstep + # exporters: [zipkin, jaeger, otlp] + + diff --git a/examples/basic_phoenix_ecto/priv/gettext/en/LC_MESSAGES/errors.po b/examples/basic_phoenix_ecto/priv/gettext/en/LC_MESSAGES/errors.po new file mode 100644 index 0000000..844c4f5 --- /dev/null +++ b/examples/basic_phoenix_ecto/priv/gettext/en/LC_MESSAGES/errors.po @@ -0,0 +1,112 @@ +## `msgid`s in this file come from POT (.pot) files. +## +## Do not add, change, or remove `msgid`s manually here as +## they're tied to the ones in the corresponding POT file +## (with the same domain). +## +## Use `mix gettext.extract --merge` or `mix gettext.merge` +## to merge POT files into PO files. +msgid "" +msgstr "" +"Language: en\n" + +## From Ecto.Changeset.cast/4 +msgid "can't be blank" +msgstr "" + +## From Ecto.Changeset.unique_constraint/3 +msgid "has already been taken" +msgstr "" + +## From Ecto.Changeset.put_change/3 +msgid "is invalid" +msgstr "" + +## From Ecto.Changeset.validate_acceptance/3 +msgid "must be accepted" +msgstr "" + +## From Ecto.Changeset.validate_format/3 +msgid "has invalid format" +msgstr "" + +## From Ecto.Changeset.validate_subset/3 +msgid "has an invalid entry" +msgstr "" + +## From Ecto.Changeset.validate_exclusion/3 +msgid "is reserved" +msgstr "" + +## From Ecto.Changeset.validate_confirmation/3 +msgid "does not match confirmation" +msgstr "" + +## From Ecto.Changeset.no_assoc_constraint/3 +msgid "is still associated with this entry" +msgstr "" + +msgid "are still associated with this entry" +msgstr "" + +## From Ecto.Changeset.validate_length/3 +msgid "should have %{count} item(s)" +msgid_plural "should have %{count} item(s)" +msgstr[0] "" +msgstr[1] "" + +msgid "should be %{count} character(s)" +msgid_plural "should be %{count} character(s)" +msgstr[0] "" +msgstr[1] "" + +msgid "should be %{count} byte(s)" +msgid_plural "should be %{count} byte(s)" +msgstr[0] "" +msgstr[1] "" + +msgid "should have at least %{count} item(s)" +msgid_plural "should have at least %{count} item(s)" +msgstr[0] "" +msgstr[1] "" + +msgid "should be at least %{count} character(s)" +msgid_plural "should be at least %{count} character(s)" +msgstr[0] "" +msgstr[1] "" + +msgid "should be at least %{count} byte(s)" +msgid_plural "should be at least %{count} byte(s)" +msgstr[0] "" +msgstr[1] "" + +msgid "should have at most %{count} item(s)" +msgid_plural "should have at most %{count} item(s)" +msgstr[0] "" +msgstr[1] "" + +msgid "should be at most %{count} character(s)" +msgid_plural "should be at most %{count} character(s)" +msgstr[0] "" +msgstr[1] "" + +msgid "should be at most %{count} byte(s)" +msgid_plural "should be at most %{count} byte(s)" +msgstr[0] "" +msgstr[1] "" + +## From Ecto.Changeset.validate_number/3 +msgid "must be less than %{number}" +msgstr "" + +msgid "must be greater than %{number}" +msgstr "" + +msgid "must be less than or equal to %{number}" +msgstr "" + +msgid "must be greater than or equal to %{number}" +msgstr "" + +msgid "must be equal to %{number}" +msgstr "" diff --git a/examples/basic_phoenix_ecto/priv/gettext/errors.pot b/examples/basic_phoenix_ecto/priv/gettext/errors.pot new file mode 100644 index 0000000..39a220b --- /dev/null +++ b/examples/basic_phoenix_ecto/priv/gettext/errors.pot @@ -0,0 +1,95 @@ +## This is a PO Template file. +## +## `msgid`s here are often extracted from source code. +## Add new translations manually only if they're dynamic +## translations that can't be statically extracted. +## +## Run `mix gettext.extract` to bring this file up to +## date. Leave `msgstr`s empty as changing them here has no +## effect: edit them in PO (`.po`) files instead. + +## From Ecto.Changeset.cast/4 +msgid "can't be blank" +msgstr "" + +## From Ecto.Changeset.unique_constraint/3 +msgid "has already been taken" +msgstr "" + +## From Ecto.Changeset.put_change/3 +msgid "is invalid" +msgstr "" + +## From Ecto.Changeset.validate_acceptance/3 +msgid "must be accepted" +msgstr "" + +## From Ecto.Changeset.validate_format/3 +msgid "has invalid format" +msgstr "" + +## From Ecto.Changeset.validate_subset/3 +msgid "has an invalid entry" +msgstr "" + +## From Ecto.Changeset.validate_exclusion/3 +msgid "is reserved" +msgstr "" + +## From Ecto.Changeset.validate_confirmation/3 +msgid "does not match confirmation" +msgstr "" + +## From Ecto.Changeset.no_assoc_constraint/3 +msgid "is still associated with this entry" +msgstr "" + +msgid "are still associated with this entry" +msgstr "" + +## From Ecto.Changeset.validate_length/3 +msgid "should be %{count} character(s)" +msgid_plural "should be %{count} character(s)" +msgstr[0] "" +msgstr[1] "" + +msgid "should have %{count} item(s)" +msgid_plural "should have %{count} item(s)" +msgstr[0] "" +msgstr[1] "" + +msgid "should be at least %{count} character(s)" +msgid_plural "should be at least %{count} character(s)" +msgstr[0] "" +msgstr[1] "" + +msgid "should have at least %{count} item(s)" +msgid_plural "should have at least %{count} item(s)" +msgstr[0] "" +msgstr[1] "" + +msgid "should be at most %{count} character(s)" +msgid_plural "should be at most %{count} character(s)" +msgstr[0] "" +msgstr[1] "" + +msgid "should have at most %{count} item(s)" +msgid_plural "should have at most %{count} item(s)" +msgstr[0] "" +msgstr[1] "" + +## From Ecto.Changeset.validate_number/3 +msgid "must be less than %{number}" +msgstr "" + +msgid "must be greater than %{number}" +msgstr "" + +msgid "must be less than or equal to %{number}" +msgstr "" + +msgid "must be greater than or equal to %{number}" +msgstr "" + +msgid "must be equal to %{number}" +msgstr "" diff --git a/examples/basic_phoenix_ecto/priv/repo/migrations/.formatter.exs b/examples/basic_phoenix_ecto/priv/repo/migrations/.formatter.exs new file mode 100644 index 0000000..49f9151 --- /dev/null +++ b/examples/basic_phoenix_ecto/priv/repo/migrations/.formatter.exs @@ -0,0 +1,4 @@ +[ + import_deps: [:ecto_sql], + inputs: ["*.exs"] +] diff --git a/examples/basic_phoenix_ecto/priv/repo/migrations/20220116091316_create_posts.exs b/examples/basic_phoenix_ecto/priv/repo/migrations/20220116091316_create_posts.exs new file mode 100644 index 0000000..5d1bc9e --- /dev/null +++ b/examples/basic_phoenix_ecto/priv/repo/migrations/20220116091316_create_posts.exs @@ -0,0 +1,12 @@ +defmodule Demo.Repo.Migrations.CreatePosts do + use Ecto.Migration + + def change do + create table(:posts) do + add :title, :string + add :body, :text + + timestamps() + end + end +end diff --git a/examples/basic_phoenix_ecto/priv/repo/migrations/20220116092821_create_users.exs b/examples/basic_phoenix_ecto/priv/repo/migrations/20220116092821_create_users.exs new file mode 100644 index 0000000..de67452 --- /dev/null +++ b/examples/basic_phoenix_ecto/priv/repo/migrations/20220116092821_create_users.exs @@ -0,0 +1,11 @@ +defmodule Demo.Repo.Migrations.CreateUsers do + use Ecto.Migration + + def change do + create table(:users) do + add :name, :string + + timestamps() + end + end +end diff --git a/examples/basic_phoenix_ecto/priv/repo/seeds.exs b/examples/basic_phoenix_ecto/priv/repo/seeds.exs new file mode 100644 index 0000000..7ad2f1a --- /dev/null +++ b/examples/basic_phoenix_ecto/priv/repo/seeds.exs @@ -0,0 +1,11 @@ +# Script for populating the database. You can run it as: +# +# mix run priv/repo/seeds.exs +# +# Inside the script, you can read and write to any of your +# repositories directly: +# +# Demo.Repo.insert!(%Demo.SomeSchema{}) +# +# We recommend using the bang functions (`insert!`, `update!` +# and so on) as they will fail if something goes wrong. diff --git a/examples/basic_phoenix_ecto/priv/static/favicon.ico b/examples/basic_phoenix_ecto/priv/static/favicon.ico new file mode 100644 index 0000000..73de524 Binary files /dev/null and b/examples/basic_phoenix_ecto/priv/static/favicon.ico differ diff --git a/examples/basic_phoenix_ecto/priv/static/images/phoenix.png b/examples/basic_phoenix_ecto/priv/static/images/phoenix.png new file mode 100644 index 0000000..9c81075 Binary files /dev/null and b/examples/basic_phoenix_ecto/priv/static/images/phoenix.png differ diff --git a/examples/basic_phoenix_ecto/priv/static/robots.txt b/examples/basic_phoenix_ecto/priv/static/robots.txt new file mode 100644 index 0000000..26e06b5 --- /dev/null +++ b/examples/basic_phoenix_ecto/priv/static/robots.txt @@ -0,0 +1,5 @@ +# See https://www.robotstxt.org/robotstxt.html for documentation on how to use the robots.txt file +# +# To ban all spiders from the entire site uncomment the next two lines: +# User-agent: * +# Disallow: / diff --git a/examples/basic_phoenix_ecto/test/demo/accounts_test.exs b/examples/basic_phoenix_ecto/test/demo/accounts_test.exs new file mode 100644 index 0000000..59050f3 --- /dev/null +++ b/examples/basic_phoenix_ecto/test/demo/accounts_test.exs @@ -0,0 +1,59 @@ +defmodule Demo.AccountsTest do + use Demo.DataCase + + alias Demo.Accounts + + describe "users" do + alias Demo.Accounts.User + + import Demo.AccountsFixtures + + @invalid_attrs %{name: nil} + + test "list_users/0 returns all users" do + user = user_fixture() + assert Accounts.list_users() == [user] + end + + test "get_user!/1 returns the user with given id" do + user = user_fixture() + assert Accounts.get_user!(user.id) == user + end + + test "create_user/1 with valid data creates a user" do + valid_attrs = %{name: "some name"} + + assert {:ok, %User{} = user} = Accounts.create_user(valid_attrs) + assert user.name == "some name" + end + + test "create_user/1 with invalid data returns error changeset" do + assert {:error, %Ecto.Changeset{}} = Accounts.create_user(@invalid_attrs) + end + + test "update_user/2 with valid data updates the user" do + user = user_fixture() + update_attrs = %{name: "some updated name"} + + assert {:ok, %User{} = user} = Accounts.update_user(user, update_attrs) + assert user.name == "some updated name" + end + + test "update_user/2 with invalid data returns error changeset" do + user = user_fixture() + assert {:error, %Ecto.Changeset{}} = Accounts.update_user(user, @invalid_attrs) + assert user == Accounts.get_user!(user.id) + end + + test "delete_user/1 deletes the user" do + user = user_fixture() + assert {:ok, %User{}} = Accounts.delete_user(user) + assert_raise Ecto.NoResultsError, fn -> Accounts.get_user!(user.id) end + end + + test "change_user/1 returns a user changeset" do + user = user_fixture() + assert %Ecto.Changeset{} = Accounts.change_user(user) + end + end +end diff --git a/examples/basic_phoenix_ecto/test/demo/blog_test.exs b/examples/basic_phoenix_ecto/test/demo/blog_test.exs new file mode 100644 index 0000000..d556907 --- /dev/null +++ b/examples/basic_phoenix_ecto/test/demo/blog_test.exs @@ -0,0 +1,61 @@ +defmodule Demo.BlogTest do + use Demo.DataCase + + alias Demo.Blog + + describe "posts" do + alias Demo.Blog.Post + + import Demo.BlogFixtures + + @invalid_attrs %{body: nil, title: nil} + + test "list_posts/0 returns all posts" do + post = post_fixture() + assert Blog.list_posts() == [post] + end + + test "get_post!/1 returns the post with given id" do + post = post_fixture() + assert Blog.get_post!(post.id) == post + end + + test "create_post/1 with valid data creates a post" do + valid_attrs = %{body: "some body", title: "some title"} + + assert {:ok, %Post{} = post} = Blog.create_post(valid_attrs) + assert post.body == "some body" + assert post.title == "some title" + end + + test "create_post/1 with invalid data returns error changeset" do + assert {:error, %Ecto.Changeset{}} = Blog.create_post(@invalid_attrs) + end + + test "update_post/2 with valid data updates the post" do + post = post_fixture() + update_attrs = %{body: "some updated body", title: "some updated title"} + + assert {:ok, %Post{} = post} = Blog.update_post(post, update_attrs) + assert post.body == "some updated body" + assert post.title == "some updated title" + end + + test "update_post/2 with invalid data returns error changeset" do + post = post_fixture() + assert {:error, %Ecto.Changeset{}} = Blog.update_post(post, @invalid_attrs) + assert post == Blog.get_post!(post.id) + end + + test "delete_post/1 deletes the post" do + post = post_fixture() + assert {:ok, %Post{}} = Blog.delete_post(post) + assert_raise Ecto.NoResultsError, fn -> Blog.get_post!(post.id) end + end + + test "change_post/1 returns a post changeset" do + post = post_fixture() + assert %Ecto.Changeset{} = Blog.change_post(post) + end + end +end diff --git a/examples/basic_phoenix_ecto/test/demo_web/controllers/page_controller_test.exs b/examples/basic_phoenix_ecto/test/demo_web/controllers/page_controller_test.exs new file mode 100644 index 0000000..f477198 --- /dev/null +++ b/examples/basic_phoenix_ecto/test/demo_web/controllers/page_controller_test.exs @@ -0,0 +1,8 @@ +defmodule DemoWeb.PageControllerTest do + use DemoWeb.ConnCase + + test "GET /", %{conn: conn} do + conn = get(conn, "/") + assert html_response(conn, 200) =~ "Welcome to Phoenix!" + end +end diff --git a/examples/basic_phoenix_ecto/test/demo_web/controllers/post_controller_test.exs b/examples/basic_phoenix_ecto/test/demo_web/controllers/post_controller_test.exs new file mode 100644 index 0000000..41b403a --- /dev/null +++ b/examples/basic_phoenix_ecto/test/demo_web/controllers/post_controller_test.exs @@ -0,0 +1,84 @@ +defmodule DemoWeb.PostControllerTest do + use DemoWeb.ConnCase + + import Demo.BlogFixtures + + @create_attrs %{body: "some body", title: "some title"} + @update_attrs %{body: "some updated body", title: "some updated title"} + @invalid_attrs %{body: nil, title: nil} + + describe "index" do + test "lists all posts", %{conn: conn} do + conn = get(conn, Routes.post_path(conn, :index)) + assert html_response(conn, 200) =~ "Listing Posts" + end + end + + describe "new post" do + test "renders form", %{conn: conn} do + conn = get(conn, Routes.post_path(conn, :new)) + assert html_response(conn, 200) =~ "New Post" + end + end + + describe "create post" do + test "redirects to show when data is valid", %{conn: conn} do + conn = post(conn, Routes.post_path(conn, :create), post: @create_attrs) + + assert %{id: id} = redirected_params(conn) + assert redirected_to(conn) == Routes.post_path(conn, :show, id) + + conn = get(conn, Routes.post_path(conn, :show, id)) + assert html_response(conn, 200) =~ "Show Post" + end + + test "renders errors when data is invalid", %{conn: conn} do + conn = post(conn, Routes.post_path(conn, :create), post: @invalid_attrs) + assert html_response(conn, 200) =~ "New Post" + end + end + + describe "edit post" do + setup [:create_post] + + test "renders form for editing chosen post", %{conn: conn, post: post} do + conn = get(conn, Routes.post_path(conn, :edit, post)) + assert html_response(conn, 200) =~ "Edit Post" + end + end + + describe "update post" do + setup [:create_post] + + test "redirects when data is valid", %{conn: conn, post: post} do + conn = put(conn, Routes.post_path(conn, :update, post), post: @update_attrs) + assert redirected_to(conn) == Routes.post_path(conn, :show, post) + + conn = get(conn, Routes.post_path(conn, :show, post)) + assert html_response(conn, 200) =~ "some updated body" + end + + test "renders errors when data is invalid", %{conn: conn, post: post} do + conn = put(conn, Routes.post_path(conn, :update, post), post: @invalid_attrs) + assert html_response(conn, 200) =~ "Edit Post" + end + end + + describe "delete post" do + setup [:create_post] + + test "deletes chosen post", %{conn: conn, post: post} do + conn = delete(conn, Routes.post_path(conn, :delete, post)) + assert redirected_to(conn) == Routes.post_path(conn, :index) + + assert_error_sent 404, fn -> + get(conn, Routes.post_path(conn, :show, post)) + end + end + end + + defp create_post(_) do + post = post_fixture() + %{post: post} + end +end diff --git a/examples/basic_phoenix_ecto/test/demo_web/live/user_live_test.exs b/examples/basic_phoenix_ecto/test/demo_web/live/user_live_test.exs new file mode 100644 index 0000000..bcc687c --- /dev/null +++ b/examples/basic_phoenix_ecto/test/demo_web/live/user_live_test.exs @@ -0,0 +1,110 @@ +defmodule DemoWeb.UserLiveTest do + use DemoWeb.ConnCase + + import Phoenix.LiveViewTest + import Demo.AccountsFixtures + + @create_attrs %{name: "some name"} + @update_attrs %{name: "some updated name"} + @invalid_attrs %{name: nil} + + defp create_user(_) do + user = user_fixture() + %{user: user} + end + + describe "Index" do + setup [:create_user] + + test "lists all users", %{conn: conn, user: user} do + {:ok, _index_live, html} = live(conn, Routes.user_index_path(conn, :index)) + + assert html =~ "Listing Users" + assert html =~ user.name + end + + test "saves new user", %{conn: conn} do + {:ok, index_live, _html} = live(conn, Routes.user_index_path(conn, :index)) + + assert index_live |> element("a", "New User") |> render_click() =~ + "New User" + + assert_patch(index_live, Routes.user_index_path(conn, :new)) + + assert index_live + |> form("#user-form", user: @invalid_attrs) + |> render_change() =~ "can't be blank" + + {:ok, _, html} = + index_live + |> form("#user-form", user: @create_attrs) + |> render_submit() + |> follow_redirect(conn, Routes.user_index_path(conn, :index)) + + assert html =~ "User created successfully" + assert html =~ "some name" + end + + test "updates user in listing", %{conn: conn, user: user} do + {:ok, index_live, _html} = live(conn, Routes.user_index_path(conn, :index)) + + assert index_live |> element("#user-#{user.id} a", "Edit") |> render_click() =~ + "Edit User" + + assert_patch(index_live, Routes.user_index_path(conn, :edit, user)) + + assert index_live + |> form("#user-form", user: @invalid_attrs) + |> render_change() =~ "can't be blank" + + {:ok, _, html} = + index_live + |> form("#user-form", user: @update_attrs) + |> render_submit() + |> follow_redirect(conn, Routes.user_index_path(conn, :index)) + + assert html =~ "User updated successfully" + assert html =~ "some updated name" + end + + test "deletes user in listing", %{conn: conn, user: user} do + {:ok, index_live, _html} = live(conn, Routes.user_index_path(conn, :index)) + + assert index_live |> element("#user-#{user.id} a", "Delete") |> render_click() + refute has_element?(index_live, "#user-#{user.id}") + end + end + + describe "Show" do + setup [:create_user] + + test "displays user", %{conn: conn, user: user} do + {:ok, _show_live, html} = live(conn, Routes.user_show_path(conn, :show, user)) + + assert html =~ "Show User" + assert html =~ user.name + end + + test "updates user within modal", %{conn: conn, user: user} do + {:ok, show_live, _html} = live(conn, Routes.user_show_path(conn, :show, user)) + + assert show_live |> element("a", "Edit") |> render_click() =~ + "Edit User" + + assert_patch(show_live, Routes.user_show_path(conn, :edit, user)) + + assert show_live + |> form("#user-form", user: @invalid_attrs) + |> render_change() =~ "can't be blank" + + {:ok, _, html} = + show_live + |> form("#user-form", user: @update_attrs) + |> render_submit() + |> follow_redirect(conn, Routes.user_show_path(conn, :show, user)) + + assert html =~ "User updated successfully" + assert html =~ "some updated name" + end + end +end diff --git a/examples/basic_phoenix_ecto/test/demo_web/views/error_view_test.exs b/examples/basic_phoenix_ecto/test/demo_web/views/error_view_test.exs new file mode 100644 index 0000000..827537b --- /dev/null +++ b/examples/basic_phoenix_ecto/test/demo_web/views/error_view_test.exs @@ -0,0 +1,14 @@ +defmodule DemoWeb.ErrorViewTest do + use DemoWeb.ConnCase, async: true + + # Bring render/3 and render_to_string/3 for testing custom views + import Phoenix.View + + test "renders 404.html" do + assert render_to_string(DemoWeb.ErrorView, "404.html", []) == "Not Found" + end + + test "renders 500.html" do + assert render_to_string(DemoWeb.ErrorView, "500.html", []) == "Internal Server Error" + end +end diff --git a/examples/basic_phoenix_ecto/test/demo_web/views/layout_view_test.exs b/examples/basic_phoenix_ecto/test/demo_web/views/layout_view_test.exs new file mode 100644 index 0000000..f5a8b73 --- /dev/null +++ b/examples/basic_phoenix_ecto/test/demo_web/views/layout_view_test.exs @@ -0,0 +1,8 @@ +defmodule DemoWeb.LayoutViewTest do + use DemoWeb.ConnCase, async: true + + # When testing helpers, you may want to import Phoenix.HTML and + # use functions such as safe_to_string() to convert the helper + # result into an HTML string. + # import Phoenix.HTML +end diff --git a/examples/basic_phoenix_ecto/test/demo_web/views/page_view_test.exs b/examples/basic_phoenix_ecto/test/demo_web/views/page_view_test.exs new file mode 100644 index 0000000..6ee178f --- /dev/null +++ b/examples/basic_phoenix_ecto/test/demo_web/views/page_view_test.exs @@ -0,0 +1,3 @@ +defmodule DemoWeb.PageViewTest do + use DemoWeb.ConnCase, async: true +end diff --git a/examples/basic_phoenix_ecto/test/support/channel_case.ex b/examples/basic_phoenix_ecto/test/support/channel_case.ex new file mode 100644 index 0000000..028647d --- /dev/null +++ b/examples/basic_phoenix_ecto/test/support/channel_case.ex @@ -0,0 +1,36 @@ +defmodule DemoWeb.ChannelCase do + @moduledoc """ + This module defines the test case to be used by + channel tests. + + Such tests rely on `Phoenix.ChannelTest` and also + import other functionality to make it easier + to build common data structures and query the data layer. + + Finally, if the test case interacts with the database, + we enable the SQL sandbox, so changes done to the database + are reverted at the end of every test. If you are using + PostgreSQL, you can even run database tests asynchronously + by setting `use DemoWeb.ChannelCase, async: true`, although + this option is not recommended for other databases. + """ + + use ExUnit.CaseTemplate + + using do + quote do + # Import conveniences for testing with channels + import Phoenix.ChannelTest + import DemoWeb.ChannelCase + + # The default endpoint for testing + @endpoint DemoWeb.Endpoint + end + end + + setup tags do + pid = Ecto.Adapters.SQL.Sandbox.start_owner!(Demo.Repo, shared: not tags[:async]) + on_exit(fn -> Ecto.Adapters.SQL.Sandbox.stop_owner(pid) end) + :ok + end +end diff --git a/examples/basic_phoenix_ecto/test/support/conn_case.ex b/examples/basic_phoenix_ecto/test/support/conn_case.ex new file mode 100644 index 0000000..0756712 --- /dev/null +++ b/examples/basic_phoenix_ecto/test/support/conn_case.ex @@ -0,0 +1,39 @@ +defmodule DemoWeb.ConnCase do + @moduledoc """ + This module defines the test case to be used by + tests that require setting up a connection. + + Such tests rely on `Phoenix.ConnTest` and also + import other functionality to make it easier + to build common data structures and query the data layer. + + Finally, if the test case interacts with the database, + we enable the SQL sandbox, so changes done to the database + are reverted at the end of every test. If you are using + PostgreSQL, you can even run database tests asynchronously + by setting `use DemoWeb.ConnCase, async: true`, although + this option is not recommended for other databases. + """ + + use ExUnit.CaseTemplate + + using do + quote do + # Import conveniences for testing with connections + import Plug.Conn + import Phoenix.ConnTest + import DemoWeb.ConnCase + + alias DemoWeb.Router.Helpers, as: Routes + + # The default endpoint for testing + @endpoint DemoWeb.Endpoint + end + end + + setup tags do + pid = Ecto.Adapters.SQL.Sandbox.start_owner!(Demo.Repo, shared: not tags[:async]) + on_exit(fn -> Ecto.Adapters.SQL.Sandbox.stop_owner(pid) end) + {:ok, conn: Phoenix.ConnTest.build_conn()} + end +end diff --git a/examples/basic_phoenix_ecto/test/support/data_case.ex b/examples/basic_phoenix_ecto/test/support/data_case.ex new file mode 100644 index 0000000..66a5f71 --- /dev/null +++ b/examples/basic_phoenix_ecto/test/support/data_case.ex @@ -0,0 +1,51 @@ +defmodule Demo.DataCase do + @moduledoc """ + This module defines the setup for tests requiring + access to the application's data layer. + + You may define functions here to be used as helpers in + your tests. + + Finally, if the test case interacts with the database, + we enable the SQL sandbox, so changes done to the database + are reverted at the end of every test. If you are using + PostgreSQL, you can even run database tests asynchronously + by setting `use Demo.DataCase, async: true`, although + this option is not recommended for other databases. + """ + + use ExUnit.CaseTemplate + + using do + quote do + alias Demo.Repo + + import Ecto + import Ecto.Changeset + import Ecto.Query + import Demo.DataCase + end + end + + setup tags do + pid = Ecto.Adapters.SQL.Sandbox.start_owner!(Demo.Repo, shared: not tags[:async]) + on_exit(fn -> Ecto.Adapters.SQL.Sandbox.stop_owner(pid) end) + :ok + end + + @doc """ + A helper that transforms changeset errors into a map of messages. + + assert {:error, changeset} = Accounts.create_user(%{password: "short"}) + assert "password is too short" in errors_on(changeset).password + assert %{password: ["password is too short"]} = errors_on(changeset) + + """ + def errors_on(changeset) do + Ecto.Changeset.traverse_errors(changeset, fn {message, opts} -> + Regex.replace(~r"%{(\w+)}", message, fn _, key -> + opts |> Keyword.get(String.to_existing_atom(key), key) |> to_string() + end) + end) + end +end diff --git a/examples/basic_phoenix_ecto/test/support/fixtures/accounts_fixtures.ex b/examples/basic_phoenix_ecto/test/support/fixtures/accounts_fixtures.ex new file mode 100644 index 0000000..248041b --- /dev/null +++ b/examples/basic_phoenix_ecto/test/support/fixtures/accounts_fixtures.ex @@ -0,0 +1,20 @@ +defmodule Demo.AccountsFixtures do + @moduledoc """ + This module defines test helpers for creating + entities via the `Demo.Accounts` context. + """ + + @doc """ + Generate a user. + """ + def user_fixture(attrs \\ %{}) do + {:ok, user} = + attrs + |> Enum.into(%{ + name: "some name" + }) + |> Demo.Accounts.create_user() + + user + end +end diff --git a/examples/basic_phoenix_ecto/test/support/fixtures/blog_fixtures.ex b/examples/basic_phoenix_ecto/test/support/fixtures/blog_fixtures.ex new file mode 100644 index 0000000..9b551ca --- /dev/null +++ b/examples/basic_phoenix_ecto/test/support/fixtures/blog_fixtures.ex @@ -0,0 +1,21 @@ +defmodule Demo.BlogFixtures do + @moduledoc """ + This module defines test helpers for creating + entities via the `Demo.Blog` context. + """ + + @doc """ + Generate a post. + """ + def post_fixture(attrs \\ %{}) do + {:ok, post} = + attrs + |> Enum.into(%{ + body: "some body", + title: "some title" + }) + |> Demo.Blog.create_post() + + post + end +end diff --git a/examples/basic_phoenix_ecto/test/test_helper.exs b/examples/basic_phoenix_ecto/test/test_helper.exs new file mode 100644 index 0000000..c53684b --- /dev/null +++ b/examples/basic_phoenix_ecto/test/test_helper.exs @@ -0,0 +1,2 @@ +ExUnit.start() +Ecto.Adapters.SQL.Sandbox.mode(Demo.Repo, :manual)