Skip to content

Commit

Permalink
Use onupdate for last_updated_at (#1062)
Browse files Browse the repository at this point in the history
## Fixes issue
#1061

## Description of Changes
Instead of manually updating `last_updated_at`, we should let SQL
Alchemy take care of it.

## Tests and linting
 - [x] This branch is up-to-date with the `develop` branch.
 - [x] `pytest` passes on my local development environment.
 - [x] `pre-commit` passes on my local development environment.
  • Loading branch information
michplunkett authored Sep 20, 2023
1 parent 9569f4e commit c2395a9
Show file tree
Hide file tree
Showing 5 changed files with 11 additions and 16 deletions.
4 changes: 2 additions & 2 deletions CONTRIB.md
Original file line number Diff line number Diff line change
Expand Up @@ -143,15 +143,15 @@ From here on out, we'll be using the Flask CLI. First we need to 'stamp' the cur
```shell
$ docker exec -it openoversight-web-1 bash # 'openoversight-web-1' is the name of the app container seen in the step above
$ flask db stamp head
$ flask db migrate -m "[THE NAME OF YOUR MIGRATION]" # NOTE: Slugs are limited to 40 characters and will be truncated after the limit
$ flask db migrate -m "[THE NAME OF YOUR MIGRATION IN ALL LOWER CASE]" # NOTE: Slugs are limited to 40 characters and will be truncated after the limit
```

(Hint: If you get errors when running `flask` commands, e.g. because of differing Python versions, you may need to run the commands in the docker container by prefacing them as so: `docker exec -it openoversight_web_1 flask db stamp head`)

Next make your changes to the database models in `OpenOversight/app/models/database.py`. You'll then generate the migrations:

```shell
$ flask db migrate
$ flask db migrate -m "[THE NAME OF YOUR MIGRATION IN ALL LOWER CASE]"
```

And then you should inspect/edit the migrations. You can then apply the migrations:
Expand Down
4 changes: 1 addition & 3 deletions OpenOversight/app/main/model_view.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
from datetime import datetime
from http import HTTPMethod
from typing import Callable, Union

Expand Down Expand Up @@ -221,8 +220,7 @@ def populate_obj(self, form, obj):
if hasattr(obj, "created_by") and not getattr(obj, "created_by"):
obj.created_by = current_user.id
# if the object keeps track of who updated it last, set to current user
if hasattr(obj, "last_updated_at"):
obj.last_updated_at = datetime.now()
if hasattr(obj, "last_updated_by"):
obj.last_updated_by = current_user.id

db.session.add(obj)
Expand Down
3 changes: 0 additions & 3 deletions OpenOversight/app/main/views.py
Original file line number Diff line number Diff line change
Expand Up @@ -652,7 +652,6 @@ def classify_submission(image_id: int, contains_cops: int):
elif contains_cops == 0:
image.contains_cops = False
image.last_updated_by = current_user.id
image.last_updated_at = datetime.now()
db.session.commit()
flash("Updated image classification")
except: # noqa: E722
Expand Down Expand Up @@ -774,7 +773,6 @@ def edit_department(department_id: int):
department.short_name = form.short_name.data
department.state = form.state.data
department.last_updated_by = current_user.id
department.last_updated_at = datetime.now()
db.session.flush()
if form.jobs.data:
new_ranks = []
Expand Down Expand Up @@ -1492,7 +1490,6 @@ def complete_tagging(image_id: int):
if not image:
abort(HTTPStatus.NOT_FOUND)
image.is_tagged = True
image.last_updated_at = datetime.now()
image.last_updated_by = current_user.id
db.session.commit()
flash("Marked image as completed.")
Expand Down
3 changes: 2 additions & 1 deletion OpenOversight/app/models/database.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import re
import time
import uuid
from datetime import date
from datetime import date, datetime
from typing import List

from authlib.jose import JoseError, JsonWebToken
Expand Down Expand Up @@ -100,6 +100,7 @@ class TrackUpdates:
nullable=False,
server_default=sql_func.now(),
unique=False,
onupdate=datetime.utcnow,
)

@declared_attr
Expand Down
13 changes: 6 additions & 7 deletions OpenOversight/app/models/database_imports.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
from datetime import date, datetime, time
from datetime import date, time
from typing import Any, Dict, Optional, Sequence, Tuple, Union

import dateutil.parser
Expand Down Expand Up @@ -122,7 +122,6 @@ def update_officer_from_dict(data: Dict[str, Any], officer: Officer) -> Officer:
officer.unique_internal_identifier = parse_str(
data.get("unique_internal_identifier"), None
)
officer.last_updated_at = datetime.now()
officer.last_updated_by = User.query.filter_by(is_administrator=True).first().id
db.session.flush()
return officer
Expand Down Expand Up @@ -165,7 +164,6 @@ def update_assignment_from_dict(
assignment.start_date = parse_date(data.get("start_date"))
if "resign_date" in data.keys():
assignment.resign_date = parse_date(data.get("resign_date"))
assignment.last_updated_at = datetime.now()
assignment.last_updated_by = User.query.filter_by(is_administrator=True).first().id
db.session.flush()

Expand Down Expand Up @@ -202,7 +200,6 @@ def update_salary_from_dict(data: Dict[str, Any], salary: Salary) -> Salary:
salary.year = int(data["year"])
if "is_fiscal_year" in data.keys():
salary.is_fiscal_year = parse_bool(data.get("is_fiscal_year"))
salary.last_updated_at = datetime.now()
salary.last_updated_by = User.query.filter_by(is_administrator=True).first().id
db.session.flush()

Expand Down Expand Up @@ -248,7 +245,6 @@ def update_link_from_dict(data: Dict[str, Any], link: Link) -> Link:
link.officers = data.get("officers") or []
if "incidents" in data:
link.incidents = data.get("incidents") or []
link.last_updated_at = datetime.now()
link.last_updated_by = User.query.filter_by(is_administrator=True).first().id
db.session.flush()

Expand Down Expand Up @@ -338,12 +334,15 @@ def update_incident_from_dict(data: Dict[str, Any], incident: Incident) -> Incid
)
)
if "last_updated_by" in data:
incident.last_updated_by = parse_int(data.get("last_updated_by"))
incident.last_updated_by = parse_int(
data.get(
"last_updated_by", User.query.filter_by(is_administrator=True).first()
),
)
if "officers" in data:
incident.officers = data["officers"] or []
if "license_plate_objects" in data:
incident.license_plates = data["license_plate_objects"] or []
incident.last_updated_at = datetime.now()
db.session.flush()
return incident

Expand Down

0 comments on commit c2395a9

Please sign in to comment.