# Updating external datasets from another form's submissions data from within a PostgreSQL database

**URL:** <https://forum.getodk.org/t/updating-external-datasets-from-another-forms-submissions-data-from-within-a-postgresql-database/37596>\
**Category:** Showcase\
**Created:** [May 5, 2022, 11:33am UTC](https://forum.getodk.org/t/updating-external-datasets-from-another-forms-submissions-data-from-within-a-postgresql-database/37596 "2022-05-05T11:33:08Z")\
**Posts on this page:** 5\
**Page:** 1

<div class="post-metadata">

**Author:** ![mathieubossaert](https://getodk.b-cdn.net/user_avatar/forum.getodk.org/mathieubossaert/32/6131_2.png) [@mathieubossaert](https://forum.getodk.org/u/mathieubossaert)\
**Post date:** [May 5, 2022, 11:33am UTC](https://forum.getodk.org/t/updating-external-datasets-from-another-forms-submissions-data-from-within-a-postgresql-database/37596/1 "2022-05-05T11:33:08Z")

</div>

### Background

As @Florian_May's [showcase](https://forum.getodk.org/t/turtle-monitoring-in-western-australia/37565), the background of this is about turtle monitoring, but in France, and not about a marine species. In fact [Caretta caretta](https://inpn.mnhn.fr/espece/cd_nom/77330/tab/fiche) is back on the french Mediterranean beaches since 2018 but does not yet required a heavy monitoring with ODK and authorities try to keep breeding places confident.

The turtle we study here is a small one, living in fresh water, called [_Emys Orbicularis_](https://inpn.mnhn.fr/espece/cd_nom/77381/tab/fiche). It is fun that I spend 2 years working on it 20 years ago just before I met computer sciences and became a GIS admin.

To monitor local populations, we put traps on the field the first day and days 2, 3 and 4 we catch turtles in the traps.  
Once captured, if the individual is already marked we take some measurements, if not we mark it first.

Last few week @Vivian_Inereli developed a dedicated form she'll maybe expose here...

What came up in the discussion with "turtle collectors" is the fact that traps are moved every week and located on a map.  
The user simply note the trap number on the paper when he catch a turtle.

We purposed to manage traps deployment with an ODK form.  
Once that form OK we wanted to adapt [this test](https://forum.getodk.org/t/updating-external-media-files-for-select-questions-from-another-form-using-centrals-api/37295/4) and make it automated as possible.

### Implementation

So let's go.  
We developed 2 forms :

- _ **CMR\_Cistude\_pose\_pieges** _ wich is used to place the traps
- and _ **CMR\_Cistude\_captures** _ wich is used to really monitor trapped individuals

[CMR\_Cistude\_captures.zip](https://forum.getodk.org/uploads/short-url/kTyoRl9jC5aJf1h92DOJcceqxQp.zip) (96,7 Ko)  
[CMR\_Cistude\_pose\_pieges.xlsx](https://forum.getodk.org/uploads/short-url/hKUuRgRXhPKcOlMhmh478Qgec58.xlsx) (13,1 Ko)

All SQL queries below are ran in our "Organization" database. Nothing happens on Central's database.

We use a cron task (each day at 10 PM) to run queries below.

We use [central2pg](https://github.com/mathieubossaert/central2pg/tree/master) functions, located in the _data\_from\_central_ schema to get fresh data about traps :

```sql
SELECT data_from_central.data_from_central_to_pg(
    'my_login','my_password','my.central.fdqn',5,
    'CMR_Cistude_pose_pieges', -- form ID
    'data_from_central', -- schema where to create tables and store data
    'point,point_auto' -- columns to ignore in json transformation to database attributes (geojson fields of GeoWidgets)
);

```

We created a view called _cmr\_cistude\_pose\_pieges\_session\_courante_ that returns only traps from the last (max) date.  
We COPY the result TO a geojson file, somewhere _postgres_ linux user can write.  
At the moment we run that query even if there is no new trap.

```sql
COPY (
    WITH places AS (
        SELECT id_piege, label, value, geometry
    FROM data_from_central.cmr_cistude_pose_pieges_session_courante
    )
SELECT
  json_build_object(
    'type', 'FeatureCollection',
    'features', json_agg(ST_AsGeoJSON(t.*)::json)
  )
FROM places AS t
      ) to '/home/postgres/medias_odk/pieges.geojson';

```

We implement an informative version number for the form, containing the year concatenate to the number of the day in the year (_DOY_) coded on 3 chars and completed with '0' its the left.

> concat(extract(YEAR FROM date\_max),lpad(extract(DOY FROM date\_max)::text,3,'0'))

We compare the current form version to the hypothetical newer one. If the "hypothetical" one is greater than the current one, we create a new draft.  
To do so and following steps, we added new functions to central2pg set of functions.

```sql
SELECT data_from_central.create_draft('my_login','my_password','my.central.fdqn',5,'CMR_Cistude_captures')
FROM data_from_central.cmr_cistude_pose_pieges_session_courante
WHERE concat(extract(YEAR FROM date_max),lpad(extract(doy FROM date_max)::text,3,'0')) > data_from_central.get_form_version('my_login','my_password','my.central.fdqn',5,'CMR_Cistude_captures')
LIMIT 1;

```

Once the draft is created, we push the fresh geojson as a form attachment to the draft.  
~~_-\> to be done : such a function need to be written for csv or this one need to be adapted._~~

```sql
SELECT data_from_central.push_media_to_central('my_login','my_password','my.central.fdqn',5,'CMR_Cistude_captures', '/home/postgres/medias_odk', 'pieges.geojson')
FROM data_from_central.cmr_cistude_pose_pieges_session_courante
WHERE concat(extract(YEAR FROM date_max),lpad(extract(doy FROM date_max)::text,3,'0'))::integer > data_from_central.get_form_version('my_login','my_password','my.central.fdqn',5,'CMR_Cistude_captures')::integer
LIMIT 1;

```

And then publish the new version 😉

```sql
SELECT data_from_central.publish_form_version('my_login','my_password','my.central.fdqn',5,
    'CMR_Cistude_captures', concat(extract(YEAR FROM date_max),lpad(extract(doy FROM date_max)::text,3,'0'))::integer )
FROM data_from_central.cmr_cistude_pose_pieges_session_courante
WHERE concat(extract(YEAR FROM date_max),lpad(extract(doy FROM date_max)::text,3,'0')) > data_from_central.get_form_version('my_login','my_password','my.central.fdqn',5,'CMR_Cistude_captures')
LIMIT 1;

```

---

<div class="post-metadata">

**Author:** ![alios82](https://getodk.b-cdn.net/letter_avatar_proxy/v4/letter/a/f1d935/32.png) [@alios82](https://forum.getodk.org/u/alios82)\
**Post date:** [May 5, 2022, 10:17pm UTC](https://forum.getodk.org/t/updating-external-datasets-from-another-forms-submissions-data-from-within-a-postgresql-database/37596/2 "2022-05-05T22:17:37Z")

</div>

Amazing. Thank you so much for sharing.

> -\> to be done : such a function need to be written for csv or this one need to be adapted.

Any tips on CSV adaptation? Often csv data is updated in my case Rural dairy farm case studies e.g. license plates, cell phone #s

---

<div class="post-metadata">

**Author:** ![mathieubossaert](https://getodk.b-cdn.net/user_avatar/forum.getodk.org/mathieubossaert/32/6131_2.png) [@mathieubossaert](https://forum.getodk.org/u/mathieubossaert)\
**Post date:** [May 6, 2022, 7:02am UTC](https://forum.getodk.org/t/updating-external-datasets-from-another-forms-submissions-data-from-within-a-postgresql-database/37596/3 "2022-05-06T07:02:56Z")

</div>

I will first simply copy/adapt the push\_json\_media\_to\_central() function for csv files. I will try it by the end of the day and update the repo to add push\_csv\_media\_to\_central() function.  
In a second time will probably add a generic function to upload csv or geojson or xml attachments that checks the file extension to adapt the Content-type Header.

---

<div class="post-metadata">

**Author:** ![mathieubossaert](https://getodk.b-cdn.net/user_avatar/forum.getodk.org/mathieubossaert/32/6131_2.png) [@mathieubossaert](https://forum.getodk.org/u/mathieubossaert)\
**Post date:** [May 6, 2022, 1:26pm UTC](https://forum.getodk.org/t/updating-external-datasets-from-another-forms-submissions-data-from-within-a-postgresql-database/37596/4 "2022-05-06T13:26:53Z")

</div>

@alios82 We finally now use a generic function to push any geojson, csv or xml media as attachment to draft form : _push\_media\_to\_central()_. I made the modification in the showcase exemple.  
And [here](https://github.com/mathieubossaert/central2pg/blob/master/push_media_to_central.sql) you can find the new function's definition.

---

<div class="post-metadata">

**Author:** ![alios82](https://getodk.b-cdn.net/letter_avatar_proxy/v4/letter/a/f1d935/32.png) [@alios82](https://forum.getodk.org/u/alios82)\
**Post date:** [May 6, 2022, 10:16pm UTC](https://forum.getodk.org/t/updating-external-datasets-from-another-forms-submissions-data-from-within-a-postgresql-database/37596/5 "2022-05-06T22:16:30Z")

</div>

Hurray! Much appreciated.
