Skip to content

Commit

Permalink
Initial commit
Browse files Browse the repository at this point in the history
  • Loading branch information
lleger committed Jun 12, 2021
0 parents commit ad7f82d
Show file tree
Hide file tree
Showing 21 changed files with 1,949 additions and 0 deletions.
4 changes: 4 additions & 0 deletions .formatter.exs
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
# Used by "mix format"
[
inputs: ["{mix,.formatter}.exs", "{config,lib,test}/**/*.{ex,exs}"]
]
26 changes: 26 additions & 0 deletions .github/workflows/ci.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
name: CI

on: [push, pull_request]

jobs:
test:
runs-on: ubuntu-latest
name: OTP ${{matrix.otp}} / Elixir ${{matrix.elixir}}
env:
MIX_ENV: "test"
strategy:
matrix:
elixir: ["1.12.x", "1.11.x"]
otp: ["24.0.x", "23.3.x"]
steps:
- uses: actions/checkout@v2
- uses: erlef/setup-beam@v1
with:
otp-version: ${{matrix.otp}}
elixir-version: ${{matrix.elixir}}
- name: Install Dependencies
run: mix deps.get
- name: Compile app
run: mix compile --force --warnings-as-errors
- run: mix test
- run: mix format --check-formatted
26 changes: 26 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
# 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 third-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").
trash-*.tar

# Temporary files, for example, from tests.
/tmp/
3 changes: 3 additions & 0 deletions .tool-versions
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
erlang 23.1.1
elixir 1.11.0-otp-23

79 changes: 79 additions & 0 deletions CODE_OF_CONDUCT.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,79 @@
# Contributor Covenant Code of Conduct

## Our Pledge

In the interest of fostering an open and welcoming environment, we as
contributors and maintainers pledge to making participation in our project and
our community a harassment-free experience for everyone, regardless of age, body
size, disability, ethnicity, sex characteristics, gender identity and expression,
level of experience, education, socio-economic status, nationality, personal
appearance, race, religion, or sexual identity and orientation.

## Our Standards

Examples of behavior that contributes to creating a positive environment
include:

* Using welcoming and inclusive language
* Being respectful of differing viewpoints and experiences
* Gracefully accepting constructive criticism
* Focusing on what is best for the community
* Showing empathy towards other community members

Examples of unacceptable behavior by participants include:

* The use of sexualized language or imagery and unwelcome sexual attention or
advances
* Trolling, insulting/derogatory comments, and personal or political attacks
* Public or private harassment
* Publishing others' private information, such as a physical or electronic
address, without explicit permission
* Other conduct which could reasonably be considered inappropriate in a
professional setting

## Our Responsibilities

Project maintainers are responsible for clarifying the standards of acceptable
behavior and are expected to take appropriate and fair corrective action in
response to any instances of unacceptable behavior.

Project maintainers have the right and responsibility to remove, edit, or
reject comments, commits, code, wiki edits, issues, and other contributions
that are not aligned to this Code of Conduct, or to ban temporarily or
permanently any contributor for other behaviors that they deem inappropriate,
threatening, offensive, or harmful.

## Scope

This Code of Conduct applies both within project spaces and in public spaces
when an individual is representing the project or its community. Examples of
representing a project or community include using an official project e-mail
address, posting via an official social media account, or acting as an appointed
representative at an online or offline event. Representation of a project may be
further defined and clarified by project maintainers.

## Enforcement

Instances of abusive, harassing, or otherwise unacceptable behavior may be
reported by contacting the project team at
[[email protected]]. All complaints will be reviewed and
investigated and will result in a response that is deemed necessary and
appropriate to the circumstances. The project team is obligated to maintain
confidentiality with regard to the reporter of an incident. Further details
of specific enforcement policies may be posted separately.

Project maintainers who do not follow or enforce the Code of Conduct in good
faith may face temporary or permanent repercussions as determined by other
members of the project's leadership.

[[email protected]]: mailto:[email protected]

## Attribution

This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 1.4,
available at https://www.contributor-covenant.org/version/1/4/code-of-conduct.html

[homepage]: https://www.contributor-covenant.org

For answers to common questions about this code of conduct, see
https://www.contributor-covenant.org/faq
21 changes: 21 additions & 0 deletions LICENSE
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
MIT License

Copyright (c) 2020 NewAperio, LLC

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
196 changes: 196 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,196 @@
# ♻️ Trash

![](https://github.com/newaperio/trash/workflows/CI/badge.svg)

Simple soft deletes for Ecto

## Installation

Trash is available on [Hex](https://hex.pm/packages/trash).

This package can be installed by adding `trash` to your list of dependencies in
`mix.exs`:

```elixir
def deps do
[
{:trash, "~> 0.1.0"}
]
end
```

## Usage

Check the [documentation](https://hexdocs.pm/trash) for complete details.

Trash helps manage soft-deleting `Ecto.Schema`s by providing convenience
functions to update and query for discarded and kept records.

### Terminology

Trash uses a few terms throughout to indicate the state of a record. Here are
some quick definitions:

- **Soft-deletion**: removing a record by updating an attribute instead of
issuing a SQL `DELETE`
- **Discarded**: a record that has been soft-deleted
- **Kept**: a record that has not been soft-deleted
- **Restore**: reverse a soft-deletion to keep a record

### Getting Started

Trash is opt-in on individual `Ecto.Schema`s. To start marking schemas as
trashable, first add the required trashable fields:

```bash
mix ecto.gen.migration add_trashable_to_posts
```

```elixir
defmodule MyApp.Repo.Migrations.AddTrashableToPosts do
use Ecto.Migration

def change do
alter(table(:posts)) do
add(:discarded_at, :utc_datetime)
end

create(index(:posts, :discarded_at))
end
end
```

Then declare the fields on your schema. You can do this manually or use the
convenience functions in `Trash.Schema`:

```elixir
defmodule MyApp.Posts.Post do
use Ecto.Schema
use Trash.Schema

schema "posts" do
field(:title, :string)
trashable_fields()
end
end
```

Next, import `Trash` by using it in your `MyApp.Repo`.

```elixir
defmodule MyApp.Repo do
use Ecto.Repo,
otp_app: :my_app,
adapter: Ecto.Adapters.Postgres

use Trash.Repo, repo: __MODULE__
end
```

This generates shorthand functions with the repo implicitly passed. However,
it's not required to call `use`. If preferred you can call the functions
directly on `Trash.Repo` by passing the `Ecto.Repo` manually. It's a bit more
convenient with `use`, though.

```elixir
# Shorthand with `use`
MyRepo.all_discarded(Post)

# Long form without
MyRepo.all_discarded(Post, [], MyRepo)
```

### Soft-deleting and Restoring

The functions `discard` and `restore` will soft-delete and restore records,
respectively.

```elixir
alias MyApp.Posts
alias MyApp.Repo

post = Posts.get_last_post!

{:ok, post} = Repo.discard(post) # => %Post{discarded_at: %DateTime{}}
post = Repo.restore(post) # => %Post{discarded_at: nil}
```

These call out to the repo's `update` function. This means a SQL `UPDATE` has
been issued and the returned schema has updated trashable fields.

These functions also have bang versions, which unwrap the return tuple and raise
on error. Note: when passing a struct instead of a changeset, the bang versions
of these will never raise an error.

### Querying

Trash provides `discarded` and `kept` variations of the following `Ecto.Repo`
functions:

- `all`
- `exists?`
- `get`
- `get!`
- `get_by`
- `get_by!`
- `one`
- `one!`

The variations are postfixed with `discarded` and `kept` (with the exception of
`exists?` which is replaced by `discarded?` and `kept?`) and modify the
passed-in queryable to add a `WHERE` condition to only return discarded or kept
records.

Trash also provides helper `where` functions that can be used in conjunction
with `Ecto.Query`.

```elixir
import Ecto.Query
alias MyApp.Posts.Post

from(p in Post) |> Trash.Query.where_discarded() |> Repo.all()
```

There is also a function that merges in the trashable fields into the select
statement to always ensure they are returned. It also hydrates `discarded?` with
a computed `SQL` value.

```elixir
import Ecto.Query
alias MyApp.Posts.Post
alias MyApp.Repo

Post
|> Trash.Query.where_discarded()
|> Repo.all()
|> Trash.Query.select_trashable()
```

## Contributing

Contributions are welcome! To make changes, clone the repo, make sure tests
pass, and then open a PR on GitHub.

```console
git clone https://github.com/newaperio/trash.git
cd trash
mix deps.get
mix test
```

## License

Trash is Copyright © 2020 NewAperio. It is free software, and may be
redistributed under the terms specified in the [LICENSE](/LICENSE) file.

## About NewAperio

Trash is built by NewAperio, LLC.

NewAperio is a web and mobile design and development studio. We offer [expert
Elixir and Phoenix][services] development as part of our portfolio of services.
[Get in touch][contact] to see how our team can help you.

[services]: https://newaperio.com/services#elixir?utm_source=github
[contact]: https://newaperio.com/contact?utm_source=github

17 changes: 17 additions & 0 deletions lib/trash.ex
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
defmodule Trash do
@moduledoc """
Trash helps manage soft-deleting `Ecto.Schema`s by providing convenience
functions to update and query for discarded and kept records.
## Terminology
Trash uses a few terms throughout to indicate the state of a record. Here's
some quick definitions:
- **Soft-deletion**: removing a record by updating an attribute instead of
issuing a SQL `DELETE`
- **Discarded**: a record that has been soft-deleted
- **Kept**: a record that has not been soft-deleted
- **Restore**: reverse a soft-deletion to keep a record
"""
end
Loading

0 comments on commit ad7f82d

Please sign in to comment.