Compare commits

...

248 Commits

Author SHA1 Message Date
Antonio Carlón
b845717077 Merge pull request #574 from CartoDB/development
Add geocodio geocoder
2020-01-20 13:01:28 +01:00
antoniocarlon
9955b3b8ff Updated NEWS.md 2020-01-20 12:56:40 +01:00
Antonio Carlón
89dff1244f Merge pull request #571 from CartoDB/antoniocarlon/568/Add_geocodio_geocoder
Add Geocodio geocoder
2020-01-20 12:53:15 +01:00
antoniocarlon
b495fcfef3 Add geocodio geocoder to tests 2020-01-20 11:20:36 +01:00
antoniocarlon
a2f0ee01a2 Add geocodio geocoder to tests 2020-01-20 11:16:57 +01:00
antoniocarlon
0c23cc4f4f Modification to trigger the CI 2020-01-20 11:07:00 +01:00
antoniocarlon
861bef0382 Fixed badly generated client scripts 2020-01-15 17:40:36 +01:00
antoniocarlon
9b9f032d30 Fixed geocoding with components 2020-01-15 14:48:31 +01:00
antoniocarlon
620b02c259 Added geocodio config to the README file 2020-01-14 15:04:47 +01:00
antoniocarlon
9558df2095 Client extension sql files 2020-01-14 13:34:02 +01:00
antoniocarlon
b5d3c5fd8e Server extension sql files 2020-01-14 13:33:33 +01:00
antoniocarlon
42c9d21475 Extensions 2020-01-14 13:27:16 +01:00
antoniocarlon
1e0a8fae06 Added geocodio geocoder to the Python library 2020-01-14 13:25:44 +01:00
antoniocarlon
7a08cdf096 Old versions 2020-01-14 13:23:22 +01:00
jvillarf
509e56468b Merge pull request #565 from CartoDB/development
Updating carto-package for Onpremises 4.0.0
2019-11-13 10:00:01 +01:00
jvillarf
d2be601049 Merge pull request #564 from CartoDB/onpremises_4_0_0_update_carto_package
Updating carto-package
2019-11-12 12:55:39 +01:00
Javier Villar
7335bacc00 Removing server extension dependency temporarily 2019-11-12 12:32:33 +01:00
Javier Villar
f0070e6158 Updating carto-package 2019-11-12 11:52:40 +01:00
Raul Marin
4684eac410 Merge branch 'development' into blessed/master 2019-10-10 13:03:31 +02:00
Raúl Marín
48748b479e Merge pull request #559 from CartoDB/client_0270
Release client extension 0.27.0
2019-10-09 13:54:47 +02:00
Raul Marin
346db43968 Release client extension 0.27.0 2019-10-09 12:57:27 +02:00
Raúl Marín
0bca39c6a8 Merge pull request #558 from CartoDB/sec
Set safe path
2019-10-08 12:32:17 +02:00
Raul Marin
a30ba351cf Qualify extension calls 2019-10-08 11:47:00 +02:00
Raul Marin
33b723fa3d Set safe path 2019-10-08 11:19:09 +02:00
Raúl Marín
80ab38a0c9 Merge pull request #557 from CartoDB/dev_pg11
Fix CI
2019-10-08 11:16:15 +02:00
Raul Marin
5ab5e8ddf9 Fix CI 2019-10-07 18:16:33 +02:00
Raúl Marín
ced23bbe93 Merge pull request #555 from CartoDB/pg11_test
Fix CI
2019-10-07 18:12:00 +02:00
Raul Marin
8b0ec7b6f5 Fix CI 2019-10-07 18:09:37 +02:00
Javier Torres
f1bfc70e6e Merge pull request #553 from CartoDB/531-document-batch-geocoding
TomTom as default LDS provider and reference documentation for cdb_bulk_geocode_street_point
2019-03-25 13:31:12 +01:00
Daniel Carrión
9e6da8908c TomTom as default LDS provider instead of Mapbox 2019-03-22 13:27:46 +01:00
Daniel Carrión
6ef7d2cd6e added reference documentation for cdb_bulk_geocode_street_point 2019-03-22 13:06:38 +01:00
Javier Goizueta
304f9fd0d3 Merge pull request #551 from CartoDB/tomtom-bulk-fix
Fix altered public method of TomTomGeocoder
2019-03-13 13:51:02 +01:00
Javier Goizueta
63dfa51092 Merge pull request #551 from CartoDB/tomtom-bulk-fix
Fix altered public method of TomTomGeocoder
2019-03-13 13:40:02 +01:00
Javier Goizueta
f07ff35b58 Release python-lib 0.21.4 2019-03-13 13:39:07 +01:00
Javier Goizueta
1cbbe29e22 Fix altered public method of TomTomGeocoder
In #456 the public method geocode_meta return value was changed
(to a tuple).
2019-03-13 12:47:37 +01:00
cillas
1ae8eaafd0 Merge pull request #470 from CartoDB/developer-center
New docs folder for developer center
2019-03-07 18:32:17 +01:00
csubira
2a05b86e55 Add CR changes and update older links in dev center docs 2019-03-06 18:15:42 +01:00
Javier Goizueta
dc0b3191f6 Merge pull request #549 from CartoDB/development
Release python-0.21.3
2019-03-05 11:59:21 +01:00
Javier Goizueta
6a57a85e72 Release new python lib version 0.21.3 2019-03-05 11:55:40 +01:00
Javier Goizueta
08a50c14bb Merge pull request #548 from CartoDB/tomtom-qps
Pass the response through the exception object
2019-03-05 11:51:25 +01:00
Javier Goizueta
ec2fe14ed3 Pass http response to ServiceException 2019-03-05 11:33:25 +01:00
Javier Goizueta
305b010225 Pass the response through the exception object 2019-03-05 11:12:58 +01:00
Javier Goizueta
885c7c50fb Merge pull request #547 from CartoDB/development
Release python-0.21.2
2019-03-04 18:48:55 +01:00
Javier Goizueta
a38c5b275d Merge pull request #546 from CartoDB/545-tomtom-qps
Detect alternative TomTom rate limit header
2019-03-04 18:26:43 +01:00
Javier Goizueta
45542b2f28 Release new python lib version 2019-03-04 18:25:25 +01:00
Javier Goizueta
f0a9779a8d Detect alternative TomTom rate limit header
Also flexibilizes detection by making it case-insensitive and allowing for text around the message
Fixes 545
2019-03-04 15:43:22 +01:00
csubira
de1ab5218a Remove empty file 2019-03-01 12:08:41 +01:00
csubira
84f17f946f Update with development branch 2019-03-01 12:06:42 +01:00
csubira
a31b429c7a Remove older content 2019-03-01 11:54:33 +01:00
csubira
f1e4ff6f33 Reorder dev center folder 2019-03-01 11:53:49 +01:00
Javier Goizueta
dd1df8695f Merge pull request #544 from CartoDB/development
Release client extension 0.26.2
2019-02-26 10:18:48 +01:00
Javier Goizueta
8507067901 Release 0.26.2 client extension 2019-02-25 16:48:36 +01:00
Javier Goizueta
00f77cca8a Merge pull request #543 from CartoDB/fix-bulk-geocoding-soft-limit
Fix bulk geocoding soft limit
2019-02-25 16:39:29 +01:00
Javier Goizueta
dfaf0d5245 Prevent use of quota for bogus configurations
This is a stop-gap measure for the hypothetical case of a service configuration that yields NULL quota values.
2019-02-25 16:32:01 +01:00
Rafa de la Torre
f63d73b9d7 Fix the bulk geocoding when soft_limit is enabled
Fix the case where there's not enough quota to geocode a table but the
soft_limit is set to true.

The function `cdb_enough_quota` accounts for the `soft_limit` flag, as
well as for the remaining quota and the rows to be geocoded.
2019-02-19 12:27:29 +01:00
Rafa de la Torre
29e636f115 Test for bulk geocoding w/ soft_limit enabled 2019-02-19 12:24:06 +01:00
Iñigo Medina (aka MacGyver)
2ae1547f3c update references to developer center components 2019-01-31 14:45:30 +01:00
Javier Torres
f082c918f0 Merge pull request #542 from CartoDB/development
Client 0.26.1, Server 0.35.1 -> Fix batch geocoder geometry type
2018-12-31 11:04:45 +01:00
Javier Torres
246ec135db Update NEWS.md 2018-12-31 11:02:26 +01:00
Javier Torres
4f5745988f Merge pull request #540 from CartoDB/538-multipolygon_geocoding_batch
538 multipolygon geocoding batch
2018-12-31 11:01:17 +01:00
Javier Torres
f996cb35db Merge pull request #541 from CartoDB/development
Python 0.21.1: Fix batch geocoder precision
2018-12-26 12:18:29 +01:00
Javier Torres
bbfa03749a Merge pull request #539 from CartoDB/s1891-bulk_geocoder_no_street_address
S1891 bulk geocoder no street address
2018-12-26 12:17:48 +01:00
Javier Torres
ab13f3a803 Also have to upgrade the geocoding function type 2018-12-24 17:55:50 +01:00
Javier Torres
ac991a05ab ALTER TYPE syntax fixes 2018-12-24 17:36:09 +01:00
Javier Torres
0dfd1a9caa Update/downgrade scripts 2018-12-24 17:28:56 +01:00
Javier Torres
370272f6c4 Version bumps 2018-12-24 17:22:32 +01:00
Javier Torres
e2c0a63803 Use Point for geocoding results 2018-12-24 17:19:13 +01:00
Javier Torres
84276b4cd3 Do not crash when matchType is empty 2018-12-24 13:04:54 +01:00
cillas
e9856d92f6 Replace mapbox with tomtom in support quota info docs 2018-12-14 10:03:26 +01:00
Mario de Frutos
b608830bce Merge pull request #537 from CartoDB/development
Release 0.35.0 for server extension
2018-11-30 12:34:38 +01:00
Mario de Frutos
a8140e53c3 Update routing mode type doc 2018-11-30 12:30:40 +01:00
Mario de Frutos
c28ca4861a Update NEWS.md 2018-11-30 12:24:47 +01:00
Mario de Frutos
b269c46724 Merge pull request #536 from CartoDB/add_mode_type_tomtom
Mode type options for routing
2018-11-30 12:17:06 +01:00
Mario de Frutos
6b6fbef586 Remove unused import 2018-11-30 11:31:46 +01:00
Mario de Frutos
eb4638a326 CR fixes 2018-11-30 11:24:12 +01:00
Mario de Frutos
a919b87664 Include test for valid request with route type 2018-11-29 16:22:34 +01:00
Mario de Frutos
98a4ed81c5 Add test for route type verification 2018-11-29 16:16:22 +01:00
Mario de Frutos
0ec1e051be Include options parsing functions 2018-11-29 14:28:54 +01:00
Mario de Frutos
850497ef79 Fix some missing arguments in the functions and add drop for the old ones 2018-11-29 13:02:18 +01:00
Mario de Frutos
8d2d0ececd SQL server extension artifact for version 0.35.0 2018-11-29 12:34:56 +01:00
Mario de Frutos
90fd8587e2 Upgrade and downgrade files 2018-11-29 12:12:19 +01:00
Mario de Frutos
64a0616c97 Added options and units parameters to the routing functions 2018-11-29 12:12:05 +01:00
Mario de Frutos
b1bdf2460e Version 0.35.0 initial files 2018-11-29 12:09:48 +01:00
Mario de Frutos
04bbb32849 Added mode type to Tomtom routing functions 2018-11-29 11:51:59 +01:00
Mario de Frutos
3e6c273b48 Merge pull request #535 from CartoDB/development
Release 0.34.2
2018-11-27 18:04:11 +01:00
Mario de Frutos
522591dd63 Update NEWS.md 2018-11-27 17:51:45 +01:00
Mario de Frutos
75d0959aff Merge pull request #532 from CartoDB/fix_metrics
Fix metrics
2018-11-27 17:49:55 +01:00
Mario de Frutos
b2cdb378fb Regenerate 0.34.2 artifact 2018-11-27 17:43:02 +01:00
Mario de Frutos
100319ed0e Migrate old versions 2018-11-27 17:41:14 +01:00
Mario de Frutos
5e161b55d2 Merge branch 'development' into fix_metrics 2018-11-27 17:39:56 +01:00
Mario de Frutos
7f4b87f513 Rename to release 2018-11-27 17:39:05 +01:00
Mario de Frutos
378458c0ae Merge pull request #534 from CartoDB/development
Release 0.34.1 of the server extension
2018-11-22 15:15:13 +01:00
Mario de Frutos
4ae4080bba Updated NEWS.md 2018-11-22 15:10:11 +01:00
Mario de Frutos
2bb67ba17a Merge pull request #533 from CartoDB/fix_isochrones_metrics
Fix isochrones metrics
2018-11-22 15:07:57 +01:00
Mario de Frutos
1027d554a5 Upgrade script from 0.34.0 to 0.34.1 2018-11-19 18:23:28 +01:00
Mario de Frutos
4e1f081952 Generated 0.34.1 artifact with changes 2018-11-19 18:11:23 +01:00
Mario de Frutos
87bb8bea68 Remove duped metrics for isochrones
We are counting the success/empty inside the iteration of the results
returned by the third party service.

For example, if we ask for 3 isochrones to a provider we count:

- 1 for success or empty
- If success we add 1 more success for each isochrone in the result
- N isolines_generated

but it should be

- 1 for success or empty
- N isolines_generated
2018-11-19 17:59:47 +01:00
Mario de Frutos
dc47f6f71b New version 0.34.1 artifacts 2018-11-19 17:51:26 +01:00
Mario de Frutos
2f6d067b4e Parse JSON parameters to avoid problems
If we pass JSON as string, with scape characters and so on, we are
going to have problems parsing that metrics in ES
2018-11-05 17:06:52 +01:00
Mario de Frutos
089d3e3f27 New version 0.34.1 2018-11-05 16:51:17 +01:00
Mario de Frutos
765b2f0901 Merge pull request #529 from CartoDB/development
Release version 0.20.2 for python library
2018-10-31 14:00:31 +01:00
Mario de Frutos
36c42096e4 Updated NEWS.md 2018-10-31 13:58:29 +01:00
Mario de Frutos
909554b453 Merge pull request #528 from CartoDB/fix_qps_tomtom
Fix qps tomtom
2018-10-31 13:55:40 +01:00
Mario de Frutos
33f40bc945 TOMTOM uses 403 instead of 429 for rate limiting
That has a great problem when we're dealing with legit 403 status for
example deactivated user, forbidden access, etc.

I've added a check for the HTTP header `X-Error-Detail-Header` in order
to distinguish between legit 403 and 429 error messages

Possible values for `X-Error-Detail-Header` in a 403 error:

  o Service Requires SSL : http is used instead of https (secure)

  o Invalid Referer : invalid 'Referer' header value is send
  to https://api.tomtom.com and allowed referer values are
  configured on specific API key

  o Account Over Queries Per Second Limit : rate limit exceeded

  o Account Inactive : incorrect API key/API key no longer valid
2018-10-31 12:59:13 +01:00
Mario de Frutos
17c993f6ef Bump version 2018-10-24 12:00:44 +02:00
Mario de Frutos
6640909780 Add provider for QPS manger in tomtom services 2018-10-24 12:00:08 +02:00
Mario de Frutos
0bcdaeabc5 Include note to explain why some isodistances could not be precise 2018-10-24 11:59:06 +02:00
Mario de Frutos
0e859d8955 Merge pull request #527 from CartoDB/change_isodistance_doc
Include note to explain why some isodistances could not be precise
2018-10-24 11:57:53 +02:00
Mario de Frutos
cd8173c7e0 Include note to explain why some isodistances could not be precise 2018-10-23 16:36:05 +02:00
Mario de Frutos
8f362c923e Merge pull request #524 from CartoDB/development
Release python library 0.20.1
2018-10-03 18:54:25 +02:00
Mario de Frutos
56a2ebb210 Fix qps timeout bug 2018-10-03 18:50:20 +02:00
Mario de Frutos
6c1c06f6be Merge pull request #523 from CartoDB/qps_fix_tomtom
Qps fix tomtom
2018-10-03 17:33:07 +02:00
Mario de Frutos
61a27a9f9d Tomtom QPS fix
Tomtom return 403 status code in the following scenarios:

- Forbidden
- Not authorized
- Account inactive
- Account over queries per second limit
- Account over rate limit
- Rate limit exceeded

So when we reach the QPS limit we receive a 403 instead of 429 so we
have to include the provider in the qps service to differentiate between
providers that returns 429 and special cases like tomtom
2018-10-03 16:35:38 +02:00
Javier Torres
ee6f2ab1c2 Merge pull request #521 from CartoDB/Fix_integration_tests
Fixed tests
2018-09-14 15:06:01 +02:00
antoniocarlon
4aa587d32b Fixing DO integration tests 2018-09-14 12:46:43 +02:00
antoniocarlon
4598d5ed7d Added CR suggestion 2018-09-14 10:14:59 +02:00
antoniocarlon
a57500c966 Fixed tests 2018-09-13 16:01:53 +02:00
Antonio Carlón
247e9040dd Merge pull request #520 from CartoDB/development
Release 0.34.0 server and 0.26.0 client
2018-09-13 10:05:34 +02:00
Antonio Carlón
4f983ec32f Merge pull request #519 from CartoDB/518-Use_non-master_keys
Use non-master keys
2018-09-13 10:02:08 +02:00
antoniocarlon
88e6245014 Updated NEWS.md 2018-09-13 10:00:32 +02:00
antoniocarlon
bafa60303c Added data observatory permission 2018-09-11 15:45:06 +02:00
antoniocarlon
ffa67fe6ca Client changes 2018-09-11 14:50:11 +02:00
antoniocarlon
3990d13572 Server changes 2018-09-11 14:35:02 +02:00
antoniocarlon
5989cb1dff Fixed exception safe functions 2018-09-11 12:17:28 +02:00
antoniocarlon
5307078171 Added CR suggestions 2018-09-11 12:13:06 +02:00
antoniocarlon
ad9619bb00 Removed unused declaration 2018-09-11 12:04:19 +02:00
antoniocarlon
2a6e63b618 Fixed tests 2018-09-11 12:02:24 +02:00
antoniocarlon
c5b6c27045 Fixed JSON return value 2018-09-11 11:19:12 +02:00
antoniocarlon
b6d37c6773 Managing public api key permissions 2018-09-11 11:07:59 +02:00
antoniocarlon
e82fb49028 organization default to null 2018-09-11 10:57:32 +02:00
antoniocarlon
4d3e9f2b32 Getting the username from cdb_conf 2018-09-11 10:14:52 +02:00
antoniocarlon
d5864ccada Using ERRCODE 2018-09-10 17:06:37 +02:00
antoniocarlon
0bdba67342 Using ERRCODE 2018-09-10 16:54:25 +02:00
antoniocarlon
08daa6a6a2 Changed error message 2018-09-10 16:45:31 +02:00
antoniocarlon
f4cb9ba812 Fixe 2018-09-10 14:33:54 +02:00
antoniocarlon
a33dd4315c Fixe 2018-09-10 14:31:08 +02:00
antoniocarlon
49bcf31832 Removed appname parameter 2018-09-10 14:26:53 +02:00
antoniocarlon
3d42281d2a Fixed test 2018-09-10 13:50:52 +02:00
antoniocarlon
696c24e432 Fixed test 2018-09-10 13:47:35 +02:00
antoniocarlon
f5ad0290b4 Fixed functions 2018-09-10 13:43:04 +02:00
antoniocarlon
01f145ab69 Fixed client tests 2018-09-10 13:40:15 +02:00
antoniocarlon
b4123625f7 Fixed server tests 2018-09-10 13:15:19 +02:00
antoniocarlon
4b6b4e92e8 CR suggestions (remove appname) 2018-09-10 12:54:37 +02:00
antoniocarlon
5ea1a4ca6b Added permissions to tests 2018-09-06 16:40:05 +02:00
antoniocarlon
ca717ed123 Fixed permission check 2018-09-06 15:40:41 +02:00
antoniocarlon
8a8970efa8 Fixed tests 2018-09-06 15:18:42 +02:00
antoniocarlon
603d691017 Added metrics 2018-09-06 13:47:50 +02:00
antoniocarlon
04a5a25d06 Fixed m04r tests 2018-09-06 12:55:31 +02:00
antoniocarlon
30e480e545 Fixed m04r tests 2018-09-06 12:46:12 +02:00
antoniocarlon
eca4b42a73 Fixed tests 2018-09-06 12:32:48 +02:00
antoniocarlon
7a7ccbbfcf Added appname parameter to the public server functions 2018-09-06 12:04:11 +02:00
antoniocarlon
56c975fef1 Added appname parameter 2018-09-06 10:55:34 +02:00
antoniocarlon
8fb9524213 Added exceptions to bulk geocoding client 2018-09-06 10:42:56 +02:00
antoniocarlon
393da56964 Updated exception safe private functions 2018-09-06 10:06:33 +02:00
antoniocarlon
17dc3ad1c7 Updated exception safe private functions 2018-09-06 10:01:01 +02:00
antoniocarlon
1eff219883 Changes in _cdb_entity_config 2018-09-05 17:57:16 +02:00
antoniocarlon
a09d18a6ee Fixing template 2018-09-05 17:51:08 +02:00
antoniocarlon
d43c9461b1 Fixing template 2018-09-05 17:36:16 +02:00
antoniocarlon
2a2ae481fb Permissions check and client templates 2018-09-05 17:28:15 +02:00
antoniocarlon
652242a8f8 Permissions check and client templates 2018-09-05 17:02:02 +02:00
Mario de Frutos
9a6f52d63b Merge pull request #517 from CartoDB/development
Release 0.33 server and 0.20 for python library
2018-08-27 12:19:07 +02:00
Mario de Frutos
48d82e025a Merge pull request #516 from CartoDB/remove_obs_snapshot_quota
Remove obs snapshot quota
2018-08-27 11:57:44 +02:00
Mario de Frutos
9398ec0524 Updated NEWS.md 2018-08-27 11:56:15 +02:00
Mario de Frutos
073c527a62 Update NEWS.md 2018-08-21 18:42:16 +02:00
Mario de Frutos
a8e96366a5 Bump for the python library version 2018-08-21 18:40:22 +02:00
Mario de Frutos
6cc3cda6e0 Remove obs_snapshot_config from python library 2018-08-21 18:28:55 +02:00
Mario de Frutos
0e95c5ff90 Now the snapshot functions use the obs_genral config 2018-08-21 18:25:12 +02:00
Mario de Frutos
fba933cc88 Remove obs_snapshot_config 2018-08-21 18:18:10 +02:00
Mario de Frutos
44da876b4c Version 0.33.0 initial commit 2018-08-21 18:15:29 +02:00
Alejandro Guirao Rodríguez
288e3a4077 Merge pull request #515 from CartoDB/development
carto-package.json
2018-08-20 10:35:32 +02:00
Juan Ignacio Sánchez Lara
821fc04d49 Merge pull request #514 from CartoDB/naming-fixes
Component change and versioning using more numbers
2018-08-20 10:17:17 +02:00
Alejandro Guirao Rodríguez
a563abb7ab Update carto-package.json 2018-08-17 10:58:56 +02:00
Alejandro Guirao Rodríguez
9c8647ebd4 Changes in component names and versions 2018-08-17 10:57:52 +02:00
Alejandro Guirao Rodríguez
61aaa0804f Changes in component names and versions 2018-08-17 10:56:07 +02:00
Alejandro Guirao Rodríguez
bd391f4bf4 Component change and versioning using more numbers 2018-08-17 10:54:24 +02:00
Juan Ignacio Sánchez Lara
2f4e3d6e05 Merge pull request #513 from CartoDB/development
Disable Mapbox Matrix API
2018-08-14 10:50:43 +02:00
Juan Ignacio Sánchez Lara
a025034d64 Merge pull request #512 from CartoDB/remove_mapbox_matrix_api_usage
Remove mapbox matrix api usage
2018-08-14 10:49:26 +02:00
Juan Ignacio Sánchez Lara
d9f647504a Disable Mapbox Matrix API usage at tests 2018-08-14 09:39:42 +02:00
Juan Ignacio Sánchez Lara
ed2e87f4ca Fix test fixture 2018-08-14 09:27:59 +02:00
Juan Ignacio Sánchez Lara
f6791d6ec8 Merge pull request #511 from CartoDB/dataservices_dependencies_specification
Dataservices dependencies specification
2018-08-13 17:13:32 +02:00
Juan Ignacio Sánchez Lara
c1c671755c Final carto-package.json format 2018-08-13 16:28:47 +02:00
cillas
1f61419467 Fix typo in filename 2018-08-08 17:49:18 +02:00
Juan Ignacio Sánchez Lara
a32e90ea8a carto-package.json proposal 2018-08-02 12:59:45 +02:00
Juan Ignacio Sánchez Lara
a6bff9b8d2 Merge pull request #509 from CartoDB/development
Version `0.19.1` of the Python library
2018-07-25 11:27:43 +02:00
Juan Ignacio Sánchez Lara
075f602a7f WELL_KNOWN_SHAPE and WELL_KNOWN_LENGTH fixture update 2018-07-25 11:22:31 +02:00
Juan Ignacio Sánchez Lara
e69849fb86 Merge pull request #508 from CartoDB/fix_batch_geocoding_error_accounting
Fix batch geocoding error accounting
2018-07-25 11:04:11 +02:00
Juan Ignacio Sánchez Lara
11ec6075c3 Python library version 0.19.1 2018-07-24 11:59:29 +02:00
Juan Ignacio Sánchez Lara
c6720bf689 Better debug message 2018-07-24 11:57:54 +02:00
Juan Ignacio Sánchez Lara
3524ee1e24 Handle postprocessing error 2018-07-24 11:31:05 +02:00
Juan Ignacio Sánchez Lara
80dcde2db0 Log Mapbox unknown status 2018-07-23 22:00:16 +02:00
Juan Ignacio Sánchez Lara
fa3d7db5f8 Fix Google geocoder error handling 2018-07-23 21:54:37 +02:00
Juan Ignacio Sánchez Lara
d060ab3d41 Empty vs missing count detail 2018-07-23 19:11:23 +02:00
Juan Ignacio Sánchez Lara
3a5360c96c Refactor and fix for actual searches type 2018-07-23 19:10:35 +02:00
Juan Ignacio Sánchez Lara
fc75f1afc8 Google batch geocoder error handling 2018-07-23 18:41:47 +02:00
Juan Ignacio Sánchez Lara
4be3aa88fd Constant extraction refactor 2018-07-23 18:30:33 +02:00
Juan Ignacio Sánchez Lara
8162bff204 Serial geocoding error handling 2018-07-23 18:27:02 +02:00
Juan Ignacio Sánchez Lara
1b31c089ce Global error handling for batched geocoding 2018-07-23 18:16:40 +02:00
Juan Ignacio Sánchez Lara
faf9b7237b Adjustments on street level fixtures 2018-07-23 17:36:06 +02:00
Juan Ignacio Sánchez Lara
5d2303e1de Log a failed one if any 2018-07-23 17:23:08 +02:00
Juan Ignacio Sánchez Lara
07f5be9207 TomTom error handling 2018-07-23 17:17:38 +02:00
Juan Ignacio Sánchez Lara
bcb34d1cea Adjustments on street level fixtures 2018-07-23 15:57:32 +02:00
Juan Ignacio Sánchez Lara
c5d9db61e6 Mapbox error handling 2018-07-23 15:48:32 +02:00
Juan Ignacio Sánchez Lara
1ff512839d Fixes empty results count 2018-07-23 13:01:46 +02:00
Juan Ignacio Sánchez Lara
9a1b1e2832 Error count 2018-07-23 12:18:26 +02:00
Juan Ignacio Sánchez Lara
1cebbe7af0 Missing warning mock and fix for debug 2018-07-23 12:16:48 +02:00
Juan Ignacio Sánchez Lara
2862c80025 Proper empty count on bulk geocoding 2018-07-23 11:53:02 +02:00
Juan Ignacio Sánchez Lara
abbaf83e97 run_street_point_geocoder tests 2018-07-23 11:42:51 +02:00
Juan Ignacio Sánchez Lara
cd5e6510a6 In case of general error, failed service use should be incremented by searches length 2018-07-23 09:30:09 +02:00
Juan Ignacio Sánchez Lara
fd097724f1 In case of general error, total service use should be incremented by searches length 2018-07-19 21:17:09 +02:00
Juan Ignacio Sánchez Lara
96fbf3080a Base run_street_point_geocoder test 2018-07-19 21:08:07 +02:00
Juan Ignacio Sánchez Lara
0d490bbb19 Extract EMPTY_RESPONSE 2018-07-19 20:52:59 +02:00
Iñigo Medina (aka MacGyver)
ab7bc424d3 remove references to providers depending on the platform 2018-06-25 12:41:40 +02:00
Iñigo Medina
cb7e9d48f4 Update 02-contribute.md 2018-04-17 14:43:12 +02:00
Iñigo Medina
6cc6ee8162 Update 02-authentication.md 2018-04-13 10:46:53 +02:00
Iñigo Medina
920c5a9fc0 Update 02-authentication.md 2018-04-13 10:45:34 +02:00
Iñigo Medina
c682bec387 Update 05-geocoding-functions.md 2018-04-13 10:44:51 +02:00
Iñigo Medina
ce79038f46 Rename 05-segementation-functions.md to 09-segementation-functions.md 2018-04-13 10:43:04 +02:00
Iñigo Medina
7727fbb1c7 Rename 04-routing-functions.md to 08-routing-functions.md 2018-04-13 10:36:44 +02:00
Iñigo Medina
214b84f606 Rename 03-demographic-functions.md to 07-demographic-functions.md 2018-04-13 10:35:05 +02:00
Iñigo Medina
971695899b Rename 02-isoline-functions.md to 06-isoline-functions.md 2018-04-13 10:34:47 +02:00
Iñigo Medina
1a7d0e5a8f Rename 01-geocoding-functions.md to 05-geocoding-functions.md 2018-04-13 10:33:30 +02:00
Iñigo Medina
e4256c1eb1 Create 04-error-handling.md 2018-04-13 10:33:03 +02:00
Iñigo Medina
6b38d89153 Create 03-versioning.md 2018-04-13 10:32:43 +02:00
Iñigo Medina
341c240907 Create 02-authentication.md 2018-04-13 10:32:07 +02:00
Iñigo Medina
8be34f0132 Create 01-introduction.md 2018-04-13 10:31:37 +02:00
Iñigo Medina
a56e9f63a3 Update 01-geocoding-functions.md 2018-04-13 10:26:29 +02:00
Iñigo Medina
efad90aa62 Delete test 2018-04-13 10:23:05 +02:00
Iñigo Medina
8ceb1e02a5 Add files via upload 2018-04-13 10:22:51 +02:00
Iñigo Medina
8e49d837b0 Create test 2018-04-13 10:22:27 +02:00
Iñigo Medina
eb1e3fc5e5 Update 01-geocoding-functions.md 2018-04-13 10:17:28 +02:00
Iñigo Medina
02071f1cde Update 01-geocoding-functions.md 2018-04-13 10:15:28 +02:00
Iñigo Medina
f368925f8e Delete 06-segmentation-functions.md 2018-04-13 00:50:12 +02:00
Iñigo Medina
f7349e6a92 Delete 05-demographic-functions.md 2018-04-13 00:50:04 +02:00
Iñigo Medina
39af462136 Delete 04-routing-functions.md 2018-04-13 00:49:53 +02:00
Iñigo Medina
073dc3b68b Delete 03-isoline-functions.md 2018-04-13 00:49:44 +02:00
Iñigo Medina
9f9bdd7e64 Delete 02-geocoding-functions.md 2018-04-13 00:49:35 +02:00
Iñigo Medina
292755215c Rename 02-rate-limits.md to 04-rate-limits.md 2018-04-13 00:45:36 +02:00
Iñigo Medina
6d82896eaa Rename 01-quota-information.md to 03-quota-information.md 2018-04-13 00:45:24 +02:00
Iñigo Medina
89ee3ff8fb Create 02-contribute.md 2018-04-13 00:45:12 +02:00
Iñigo Medina
5f2a0bb7dd Create 01-support-options.md 2018-04-13 00:44:22 +02:00
Iñigo Medina
38a2c3d063 Delete 07-quota-information.md 2018-04-13 00:43:30 +02:00
Iñigo Medina
6606d26984 Create 07-quota-information.md 2018-04-13 00:42:17 +02:00
Iñigo Medina
5a3fcec664 Create 06-segmentation-functions.md 2018-04-13 00:41:53 +02:00
Iñigo Medina
af81ba2cf2 Create 05-demographic-functions.md 2018-04-13 00:41:27 +02:00
Iñigo Medina
70232957f8 Create 04-routing-functions.md 2018-04-13 00:40:45 +02:00
Iñigo Medina
8ab24dc611 Create 03-isoline-functions.md 2018-04-13 00:40:07 +02:00
Iñigo Medina
140094cdde Create 02-geocoding-functions.md 2018-04-13 00:39:38 +02:00
csubira
ef68ad4dcb Add new docs folder structure 2018-02-22 17:25:12 +01:00
160 changed files with 69720 additions and 692 deletions

77
NEWS.md
View File

@@ -1,6 +1,81 @@
Jan 20th, 2020
==============
* Version `0.22.0` of the Python library
* Added geocodio geocoder
* Version `0.36.0` of the server extension
* Added geocodio geocoder
* Version `0.28.0` of the client extension
* Added geocodio geocoder
Oct 9th, 2019
==============
* Version `0.27.0` of the client extension
* Changes in search_path
Mar 13rd, 2019
==============
* Version `0.21.4` of the python library
* Fix TomTom bulk geocoder bug (#551)
Mar 5th, 2019
==============
* Version `0.21.3` of the python library
* Fixed TomTom Qps respondes part 2 (#546)
Mar 4th, 2019
==============
* Version `0.21.2` of the python library
* Fixed TomTom Qps responses (#546)
Feb 25th, 2019
==============
* Version `0.26.2` of the client extension
* Fixed bulk geocoding soft limit (#543)
Dec 31st, 2018
==============
* Version `0.35.1` of the server extension and `0.26.1` of the client
* Now the bulk geocoder returns `Point` geometries instead of MultiPolygons (#538)
Nov 30th, 2018
==============
* Version `0.35.0` of the server extension
* Now the `mode_type` is working the providers that support it (#536)
Nov 27th, 2018
==============
* Version `0.34.2` of the server extension
* Fixed bulk geocoding log metrics in order to fix problems in ELK due to the JSON not being standard (#530)
Nov 22th, 2018
==============
* Version `0.34.1` of the server extension
* Fixed isochrones metrics that increase `success_rows` field for every isochrone generated (#533)
Oct 31th, 2018
==============
* Version `0.20.2` of the python library
* Added missing provider property to the QPS decorator in other TomTom services
* Now we only retry with the properly header coming from TomTom
Oct 3rd, 2018
==============
* Version `0.20.1` of the python library
* Fix QPS manager to retry with 403 status codes coming from TomTom
Sep 13th, 2018
==============
* Version `0.34.0` of the server, and `0.26.0` of the client.
* Use dataservices with non-master keys
Aug 27th, 2018
==============
* Version `0.33.0` of the server, and `0.20.0` of the Python library.
* Remove the obs_snapshot quota and now the snapshot functions uses obs_general quota
Jul 19th, 2018
==============
* Version `0.25.0` of the client, `0.32.0` of the server, and `0.19.0` of the Python library.
* Version `0.25.0` of the client, `0.32.0` of the server, and `0.19.1` of the Python library.
* Support for batch street-level geocoding.
May 7th, 2018

View File

@@ -180,6 +180,15 @@ SELECT CDB_Conf_SetConf(
);
```
#### Geocod.io configuration
```sql
SELECT CDB_Conf_SetConf(
'geocodio_conf',
'{"geocoder": {"api_keys": ["your_api_key"], "monthly_quota": 999999}}'
);
```
#### Data Observatory
```sql

12
client/carto-package.json Normal file
View File

@@ -0,0 +1,12 @@
{
"name": "dataservices-api-client-extension",
"current_version": {
"requires": {
"postgresql": "^11.0.0",
"postgis": "^2.5.0.0",
"carto_postgresql_ext": "^0.32.0"
},
"works_with": {
}
}
}

View File

@@ -0,0 +1,83 @@
--DO NOT MODIFY THIS FILE, IT IS GENERATED AUTOMATICALLY FROM SOURCES
-- Complain if script is sourced in psql, rather than via CREATE EXTENSION
\echo Use "ALTER EXTENSION cdb_dataservices_client UPDATE TO '0.28.0'" to load this file. \quit
-- Make sure we have a sane search path to create/update the extension
SET search_path = "$user",cartodb,public,cdb_dataservices_client;
-- HERE goes your code to upgrade/downgrade
CREATE OR REPLACE FUNCTION cdb_dataservices_client._cdb_geocodio_geocode_street_point_exception_safe (searchtext text ,city text DEFAULT NULL ,state_province text DEFAULT NULL ,country text DEFAULT NULL)
RETURNS public.Geometry AS $$
DECLARE
ret public.Geometry;
username text;
orgname text;
_returned_sqlstate TEXT;
_message_text TEXT;
_pg_exception_context TEXT;
apikey_permissions json;
BEGIN
SELECT u, o, p INTO username, orgname, apikey_permissions FROM cdb_dataservices_client._cdb_entity_config() AS (u text, o text, p json);
IF apikey_permissions IS NULL OR NOT apikey_permissions::jsonb ? 'geocoding' THEN
RAISE EXCEPTION 'Geocoding permission denied';
END IF;
-- JSON value stored "" is taken as literal
IF username IS NULL OR username = '' OR username = '""' THEN
RAISE EXCEPTION 'Username is a mandatory argument, check it out';
END IF;
BEGIN
SELECT cdb_dataservices_client._cdb_geocodio_geocode_street_point(username, orgname, searchtext, city, state_province, country) INTO ret; RETURN ret;
EXCEPTION
WHEN OTHERS THEN
GET STACKED DIAGNOSTICS _returned_sqlstate = RETURNED_SQLSTATE,
_message_text = MESSAGE_TEXT,
_pg_exception_context = PG_EXCEPTION_CONTEXT;
RAISE WARNING USING ERRCODE = _returned_sqlstate, MESSAGE = _message_text, DETAIL = _pg_exception_context;
RETURN ret;
END;
END;
$$ LANGUAGE 'plpgsql' SECURITY DEFINER STABLE PARALLEL UNSAFE
SET search_path = pg_temp;
DROP FUNCTION IF EXISTS cdb_dataservices_client._cdb_geocodio_geocode_street_point (username text, orgname text, searchtext text, city text, state_province text, country text);
CREATE OR REPLACE FUNCTION cdb_dataservices_client._cdb_geocodio_geocode_street_point (username text, orgname text, searchtext text, city text DEFAULT NULL, state_province text DEFAULT NULL, country text DEFAULT NULL)
RETURNS Geometry AS $$
CONNECT cdb_dataservices_client._server_conn_str();
SELECT cdb_dataservices_server.cdb_geocodio_geocode_street_point (username, orgname, searchtext, city, state_province, country);
$$ LANGUAGE plproxy VOLATILE PARALLEL UNSAFE;
DROP FUNCTION IF EXISTS cdb_dataservices_client.cdb_geocodio_geocode_street_point (searchtext text ,city text ,state_province text ,country text);
CREATE OR REPLACE FUNCTION cdb_dataservices_client.cdb_geocodio_geocode_street_point (searchtext text ,city text DEFAULT NULL ,state_province text DEFAULT NULL ,country text DEFAULT NULL)
RETURNS public.Geometry AS $$
DECLARE
ret public.Geometry;
username text;
orgname text;
apikey_permissions json;
BEGIN
SELECT u, o, p INTO username, orgname, apikey_permissions FROM cdb_dataservices_client._cdb_entity_config() AS (u text, o text, p json);
IF apikey_permissions IS NULL OR NOT apikey_permissions::jsonb ? 'geocoding' THEN
RAISE EXCEPTION 'Geocoding permission denied' USING ERRCODE = '01007';
END IF;
-- JSON value stored "" is taken as literal
IF username IS NULL OR username = '' OR username = '""' THEN
RAISE EXCEPTION 'Username is a mandatory argument, check it out';
END IF;
SELECT cdb_dataservices_client._cdb_geocodio_geocode_street_point(username, orgname, searchtext, city, state_province, country) INTO ret; RETURN ret;
END;
$$ LANGUAGE 'plpgsql' SECURITY DEFINER STABLE PARALLEL UNSAFE
SET search_path = pg_temp;
GRANT EXECUTE ON FUNCTION cdb_dataservices_client.cdb_geocodio_geocode_street_point(searchtext text, city text, state_province text, country text) TO publicuser;
GRANT EXECUTE ON FUNCTION cdb_dataservices_client._cdb_geocodio_geocode_street_point_exception_safe(searchtext text, city text, state_province text, country text ) TO publicuser;

View File

@@ -0,0 +1,14 @@
--DO NOT MODIFY THIS FILE, IT IS GENERATED AUTOMATICALLY FROM SOURCES
-- Complain if script is sourced in psql, rather than via CREATE EXTENSION
\echo Use "ALTER EXTENSION cdb_dataservices_client UPDATE TO '0.27.0'" to load this file. \quit
-- Make sure we have a sane search path to create/update the extension
SET search_path = "$user",cartodb,public,cdb_dataservices_client;
-- HERE goes your code to upgrade/downgrade
DROP FUNCTION IF EXISTS cdb_dataservices_client._cdb_geocodio_geocode_street_point_exception_safe;
DROP FUNCTION IF EXISTS cdb_dataservices_client._cdb_geocodio_geocode_street_point;
DROP FUNCTION IF EXISTS cdb_dataservices_client.cdb_geocodio_geocode_street_point;

File diff suppressed because it is too large Load Diff

View File

@@ -1,5 +1,5 @@
comment = 'CartoDB dataservices client API extension'
default_version = '0.25.0'
default_version = '0.28.0'
requires = 'plproxy, cartodb'
superuser = true
schema = cdb_dataservices_client

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,99 @@
--DO NOT MODIFY THIS FILE, IT IS GENERATED AUTOMATICALLY FROM SOURCES
-- Complain if script is sourced in psql, rather than via CREATE EXTENSION
\echo Use "ALTER EXTENSION cdb_dataservices_client UPDATE TO '0.26.1'" to load this file. \quit
-- Make sure we have a sane search path to create/update the extension
SET search_path = "$user",cartodb,public,cdb_dataservices_client;
-- HERE goes your code to upgrade/downgrade
ALTER TYPE cdb_dataservices_client.geocoding ALTER ATTRIBUTE the_geom TYPE geometry(Point,4326);
CREATE OR REPLACE FUNCTION cdb_dataservices_client.cdb_bulk_geocode_street_point (query text,
street_column text, city_column text default null, state_column text default null, country_column text default null, batch_size integer DEFAULT NULL)
RETURNS SETOF cdb_dataservices_client.geocoding AS $$
DECLARE
query_row_count integer;
enough_quota boolean;
remaining_quota integer;
max_batch_size integer;
cartodb_id_batch integer;
batches_n integer;
DEFAULT_BATCH_SIZE CONSTANT numeric := 100;
MAX_SAFE_BATCH_SIZE CONSTANT numeric := 5000;
temp_table_name text;
username text;
orgname text;
apikey_permissions json;
BEGIN
SELECT u, o, p INTO username, orgname, apikey_permissions FROM cdb_dataservices_client._cdb_entity_config() AS (u text, o text, p json);
IF apikey_permissions IS NULL OR NOT apikey_permissions::jsonb ? 'geocoding' THEN
RAISE EXCEPTION 'Geocoding permission denied' USING ERRCODE = '01007';
END IF;
-- JSON value stored "" is taken as literal
IF username IS NULL OR username = '' OR username = '""' THEN
RAISE EXCEPTION 'Username is a mandatory argument, check it out';
END IF;
SELECT csqi.monthly_quota - csqi.used_quota AS remaining_quota, csqi.max_batch_size
INTO remaining_quota, max_batch_size
FROM cdb_dataservices_client.cdb_service_quota_info_batch() csqi
WHERE service = 'hires_geocoder';
RAISE DEBUG 'remaining_quota: %; max_batch_size: %', remaining_quota, max_batch_size;
IF batch_size IS NULL THEN
batch_size := max_batch_size;
ELSIF batch_size > max_batch_size THEN
RAISE EXCEPTION 'batch_size must be lower than %', max_batch_size + 1;
END IF;
IF batch_size > MAX_SAFE_BATCH_SIZE THEN
batch_size := MAX_SAFE_BATCH_SIZE;
END IF;
EXECUTE format('SELECT count(1), ceil(count(1)::float/%s) FROM (%s) _x', batch_size, query)
INTO query_row_count, batches_n;
RAISE DEBUG 'cdb_bulk_geocode_street_point --> query_row_count: %; query: %; country: %; state: %; city: %; street: %',
query_row_count, query, country_column, state_column, city_column, street_column;
SELECT cdb_dataservices_client.cdb_enough_quota('hires_geocoder', query_row_count) INTO enough_quota;
IF remaining_quota < query_row_count THEN
RAISE EXCEPTION 'Remaining quota: %. Estimated cost: %', remaining_quota, query_row_count;
END IF;
RAISE DEBUG 'batches_n: %', batches_n;
temp_table_name := 'bulk_geocode_street_' || md5(random()::text);
EXECUTE format('CREATE TEMPORARY TABLE %s ' ||
'(cartodb_id integer, the_geom geometry(Point,4326), metadata jsonb)',
temp_table_name);
select
coalesce(street_column, ''''''), coalesce(city_column, ''''''),
coalesce(state_column, ''''''), coalesce(country_column, '''''')
into street_column, city_column, state_column, country_column;
IF batches_n > 0 THEN
FOR cartodb_id_batch in 0..(batches_n - 1)
LOOP
EXECUTE format(
'WITH geocoding_data as (' ||
' SELECT ' ||
' json_build_object(''id'', cartodb_id, ''address'', %s, ''city'', %s, ''state'', %s, ''country'', %s) as data , ' ||
' floor((row_number() over () - 1)::float/$1) as batch' ||
' FROM (%s) _x' ||
') ' ||
'INSERT INTO %s SELECT (cdb_dataservices_client._cdb_bulk_geocode_street_point(jsonb_agg(data))).* ' ||
'FROM geocoding_data ' ||
'WHERE batch = $2', street_column, city_column, state_column, country_column, query, temp_table_name)
USING batch_size, cartodb_id_batch;
END LOOP;
END IF;
RETURN QUERY EXECUTE 'SELECT * FROM ' || quote_ident(temp_table_name);
END;
$$ LANGUAGE 'plpgsql' SECURITY DEFINER VOLATILE PARALLEL UNSAFE;

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,99 @@
--DO NOT MODIFY THIS FILE, IT IS GENERATED AUTOMATICALLY FROM SOURCES
-- Complain if script is sourced in psql, rather than via CREATE EXTENSION
\echo Use "ALTER EXTENSION cdb_dataservices_client UPDATE TO '0.26.0'" to load this file. \quit
-- Make sure we have a sane search path to create/update the extension
SET search_path = "$user",cartodb,public,cdb_dataservices_client;
-- HERE goes your code to upgrade/downgrade
ALTER TYPE cdb_dataservices_client.geocoding ALTER ATTRIBUTE the_geom TYPE geometry(MultiPolygon,4326);
CREATE OR REPLACE FUNCTION cdb_dataservices_client.cdb_bulk_geocode_street_point (query text,
street_column text, city_column text default null, state_column text default null, country_column text default null, batch_size integer DEFAULT NULL)
RETURNS SETOF cdb_dataservices_client.geocoding AS $$
DECLARE
query_row_count integer;
enough_quota boolean;
remaining_quota integer;
max_batch_size integer;
cartodb_id_batch integer;
batches_n integer;
DEFAULT_BATCH_SIZE CONSTANT numeric := 100;
MAX_SAFE_BATCH_SIZE CONSTANT numeric := 5000;
temp_table_name text;
username text;
orgname text;
apikey_permissions json;
BEGIN
SELECT u, o, p INTO username, orgname, apikey_permissions FROM cdb_dataservices_client._cdb_entity_config() AS (u text, o text, p json);
IF apikey_permissions IS NULL OR NOT apikey_permissions::jsonb ? 'geocoding' THEN
RAISE EXCEPTION 'Geocoding permission denied' USING ERRCODE = '01007';
END IF;
-- JSON value stored "" is taken as literal
IF username IS NULL OR username = '' OR username = '""' THEN
RAISE EXCEPTION 'Username is a mandatory argument, check it out';
END IF;
SELECT csqi.monthly_quota - csqi.used_quota AS remaining_quota, csqi.max_batch_size
INTO remaining_quota, max_batch_size
FROM cdb_dataservices_client.cdb_service_quota_info_batch() csqi
WHERE service = 'hires_geocoder';
RAISE DEBUG 'remaining_quota: %; max_batch_size: %', remaining_quota, max_batch_size;
IF batch_size IS NULL THEN
batch_size := max_batch_size;
ELSIF batch_size > max_batch_size THEN
RAISE EXCEPTION 'batch_size must be lower than %', max_batch_size + 1;
END IF;
IF batch_size > MAX_SAFE_BATCH_SIZE THEN
batch_size := MAX_SAFE_BATCH_SIZE;
END IF;
EXECUTE format('SELECT count(1), ceil(count(1)::float/%s) FROM (%s) _x', batch_size, query)
INTO query_row_count, batches_n;
RAISE DEBUG 'cdb_bulk_geocode_street_point --> query_row_count: %; query: %; country: %; state: %; city: %; street: %',
query_row_count, query, country_column, state_column, city_column, street_column;
SELECT cdb_dataservices_client.cdb_enough_quota('hires_geocoder', query_row_count) INTO enough_quota;
IF remaining_quota < query_row_count THEN
RAISE EXCEPTION 'Remaining quota: %. Estimated cost: %', remaining_quota, query_row_count;
END IF;
RAISE DEBUG 'batches_n: %', batches_n;
temp_table_name := 'bulk_geocode_street_' || md5(random()::text);
EXECUTE format('CREATE TEMPORARY TABLE %s ' ||
'(cartodb_id integer, the_geom geometry(Multipolygon,4326), metadata jsonb)',
temp_table_name);
select
coalesce(street_column, ''''''), coalesce(city_column, ''''''),
coalesce(state_column, ''''''), coalesce(country_column, '''''')
into street_column, city_column, state_column, country_column;
IF batches_n > 0 THEN
FOR cartodb_id_batch in 0..(batches_n - 1)
LOOP
EXECUTE format(
'WITH geocoding_data as (' ||
' SELECT ' ||
' json_build_object(''id'', cartodb_id, ''address'', %s, ''city'', %s, ''state'', %s, ''country'', %s) as data , ' ||
' floor((row_number() over () - 1)::float/$1) as batch' ||
' FROM (%s) _x' ||
') ' ||
'INSERT INTO %s SELECT (cdb_dataservices_client._cdb_bulk_geocode_street_point(jsonb_agg(data))).* ' ||
'FROM geocoding_data ' ||
'WHERE batch = $2', street_column, city_column, state_column, country_column, query, temp_table_name)
USING batch_size, cartodb_id_batch;
END LOOP;
END IF;
RETURN QUERY EXECUTE 'SELECT * FROM ' || quote_ident(temp_table_name);
END;
$$ LANGUAGE 'plpgsql' SECURITY DEFINER VOLATILE PARALLEL UNSAFE;

View File

@@ -0,0 +1,96 @@
--DO NOT MODIFY THIS FILE, IT IS GENERATED AUTOMATICALLY FROM SOURCES
-- Complain if script is sourced in psql, rather than via CREATE EXTENSION
\echo Use "ALTER EXTENSION cdb_dataservices_client UPDATE TO '0.26.2'" to load this file. \quit
-- Make sure we have a sane search path to create/update the extension
SET search_path = "$user",cartodb,public,cdb_dataservices_client;
CREATE OR REPLACE FUNCTION cdb_dataservices_client.cdb_bulk_geocode_street_point (query text,
street_column text, city_column text default null, state_column text default null, country_column text default null, batch_size integer DEFAULT NULL)
RETURNS SETOF cdb_dataservices_client.geocoding AS $$
DECLARE
query_row_count integer;
enough_quota boolean;
remaining_quota integer;
max_batch_size integer;
cartodb_id_batch integer;
batches_n integer;
DEFAULT_BATCH_SIZE CONSTANT numeric := 100;
MAX_SAFE_BATCH_SIZE CONSTANT numeric := 5000;
temp_table_name text;
username text;
orgname text;
apikey_permissions json;
BEGIN
SELECT u, o, p INTO username, orgname, apikey_permissions FROM cdb_dataservices_client._cdb_entity_config() AS (u text, o text, p json);
IF apikey_permissions IS NULL OR NOT apikey_permissions::jsonb ? 'geocoding' THEN
RAISE EXCEPTION 'Geocoding permission denied' USING ERRCODE = '01007';
END IF;
-- JSON value stored "" is taken as literal
IF username IS NULL OR username = '' OR username = '""' THEN
RAISE EXCEPTION 'Username is a mandatory argument, check it out';
END IF;
SELECT csqi.monthly_quota - csqi.used_quota AS remaining_quota, csqi.max_batch_size
INTO remaining_quota, max_batch_size
FROM cdb_dataservices_client.cdb_service_quota_info_batch() csqi
WHERE service = 'hires_geocoder';
RAISE DEBUG 'remaining_quota: %; max_batch_size: %', remaining_quota, max_batch_size;
IF batch_size IS NULL THEN
batch_size := max_batch_size;
ELSIF batch_size > max_batch_size THEN
RAISE EXCEPTION 'batch_size must be lower than %', max_batch_size + 1;
END IF;
IF batch_size > MAX_SAFE_BATCH_SIZE THEN
batch_size := MAX_SAFE_BATCH_SIZE;
END IF;
EXECUTE format('SELECT count(1), ceil(count(1)::float/%s) FROM (%s) _x', batch_size, query)
INTO query_row_count, batches_n;
RAISE DEBUG 'cdb_bulk_geocode_street_point --> query_row_count: %; query: %; country: %; state: %; city: %; street: %',
query_row_count, query, country_column, state_column, city_column, street_column;
SELECT cdb_dataservices_client.cdb_enough_quota('hires_geocoder', query_row_count) INTO enough_quota;
IF enough_quota IS NULL OR NOT enough_quota THEN
RAISE EXCEPTION 'Remaining quota: %. Estimated cost: %', remaining_quota, query_row_count;
END IF;
RAISE DEBUG 'batches_n: %', batches_n;
temp_table_name := 'bulk_geocode_street_' || md5(random()::text);
EXECUTE format('CREATE TEMPORARY TABLE %s ' ||
'(cartodb_id integer, the_geom geometry(Point,4326), metadata jsonb)',
temp_table_name);
select
coalesce(street_column, ''''''), coalesce(city_column, ''''''),
coalesce(state_column, ''''''), coalesce(country_column, '''''')
into street_column, city_column, state_column, country_column;
IF batches_n > 0 THEN
FOR cartodb_id_batch in 0..(batches_n - 1)
LOOP
EXECUTE format(
'WITH geocoding_data as (' ||
' SELECT ' ||
' json_build_object(''id'', cartodb_id, ''address'', %s, ''city'', %s, ''state'', %s, ''country'', %s) as data , ' ||
' floor((row_number() over () - 1)::float/$1) as batch' ||
' FROM (%s) _x' ||
') ' ||
'INSERT INTO %s SELECT (cdb_dataservices_client._cdb_bulk_geocode_street_point(jsonb_agg(data))).* ' ||
'FROM geocoding_data ' ||
'WHERE batch = $2', street_column, city_column, state_column, country_column, query, temp_table_name)
USING batch_size, cartodb_id_batch;
END LOOP;
END IF;
RETURN QUERY EXECUTE 'SELECT * FROM ' || quote_ident(temp_table_name);
END;
$$ LANGUAGE 'plpgsql' SECURITY DEFINER VOLATILE PARALLEL UNSAFE;

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,96 @@
--DO NOT MODIFY THIS FILE, IT IS GENERATED AUTOMATICALLY FROM SOURCES
-- Complain if script is sourced in psql, rather than via CREATE EXTENSION
\echo Use "ALTER EXTENSION cdb_dataservices_client UPDATE TO '0.26.1'" to load this file. \quit
-- Make sure we have a sane search path to create/update the extension
SET search_path = "$user",cartodb,public,cdb_dataservices_client;
CREATE OR REPLACE FUNCTION cdb_dataservices_client.cdb_bulk_geocode_street_point (query text,
street_column text, city_column text default null, state_column text default null, country_column text default null, batch_size integer DEFAULT NULL)
RETURNS SETOF cdb_dataservices_client.geocoding AS $$
DECLARE
query_row_count integer;
enough_quota boolean;
remaining_quota integer;
max_batch_size integer;
cartodb_id_batch integer;
batches_n integer;
DEFAULT_BATCH_SIZE CONSTANT numeric := 100;
MAX_SAFE_BATCH_SIZE CONSTANT numeric := 5000;
temp_table_name text;
username text;
orgname text;
apikey_permissions json;
BEGIN
SELECT u, o, p INTO username, orgname, apikey_permissions FROM cdb_dataservices_client._cdb_entity_config() AS (u text, o text, p json);
IF apikey_permissions IS NULL OR NOT apikey_permissions::jsonb ? 'geocoding' THEN
RAISE EXCEPTION 'Geocoding permission denied' USING ERRCODE = '01007';
END IF;
-- JSON value stored "" is taken as literal
IF username IS NULL OR username = '' OR username = '""' THEN
RAISE EXCEPTION 'Username is a mandatory argument, check it out';
END IF;
SELECT csqi.monthly_quota - csqi.used_quota AS remaining_quota, csqi.max_batch_size
INTO remaining_quota, max_batch_size
FROM cdb_dataservices_client.cdb_service_quota_info_batch() csqi
WHERE service = 'hires_geocoder';
RAISE DEBUG 'remaining_quota: %; max_batch_size: %', remaining_quota, max_batch_size;
IF batch_size IS NULL THEN
batch_size := max_batch_size;
ELSIF batch_size > max_batch_size THEN
RAISE EXCEPTION 'batch_size must be lower than %', max_batch_size + 1;
END IF;
IF batch_size > MAX_SAFE_BATCH_SIZE THEN
batch_size := MAX_SAFE_BATCH_SIZE;
END IF;
EXECUTE format('SELECT count(1), ceil(count(1)::float/%s) FROM (%s) _x', batch_size, query)
INTO query_row_count, batches_n;
RAISE DEBUG 'cdb_bulk_geocode_street_point --> query_row_count: %; query: %; country: %; state: %; city: %; street: %',
query_row_count, query, country_column, state_column, city_column, street_column;
SELECT cdb_dataservices_client.cdb_enough_quota('hires_geocoder', query_row_count) INTO enough_quota;
IF remaining_quota < query_row_count THEN
RAISE EXCEPTION 'Remaining quota: %. Estimated cost: %', remaining_quota, query_row_count;
END IF;
RAISE DEBUG 'batches_n: %', batches_n;
temp_table_name := 'bulk_geocode_street_' || md5(random()::text);
EXECUTE format('CREATE TEMPORARY TABLE %s ' ||
'(cartodb_id integer, the_geom geometry(Point,4326), metadata jsonb)',
temp_table_name);
select
coalesce(street_column, ''''''), coalesce(city_column, ''''''),
coalesce(state_column, ''''''), coalesce(country_column, '''''')
into street_column, city_column, state_column, country_column;
IF batches_n > 0 THEN
FOR cartodb_id_batch in 0..(batches_n - 1)
LOOP
EXECUTE format(
'WITH geocoding_data as (' ||
' SELECT ' ||
' json_build_object(''id'', cartodb_id, ''address'', %s, ''city'', %s, ''state'', %s, ''country'', %s) as data , ' ||
' floor((row_number() over () - 1)::float/$1) as batch' ||
' FROM (%s) _x' ||
') ' ||
'INSERT INTO %s SELECT (cdb_dataservices_client._cdb_bulk_geocode_street_point(jsonb_agg(data))).* ' ||
'FROM geocoding_data ' ||
'WHERE batch = $2', street_column, city_column, state_column, country_column, query, temp_table_name)
USING batch_size, cartodb_id_batch;
END LOOP;
END IF;
RETURN QUERY EXECUTE 'SELECT * FROM ' || quote_ident(temp_table_name);
END;
$$ LANGUAGE 'plpgsql' SECURITY DEFINER VOLATILE PARALLEL UNSAFE;

View File

@@ -0,0 +1,8 @@
--DO NOT MODIFY THIS FILE, IT IS GENERATED AUTOMATICALLY FROM SOURCES
-- Complain if script is sourced in psql, rather than via CREATE EXTENSION
\echo Use "ALTER EXTENSION cdb_dataservices_client UPDATE TO '0.27.0'" to load this file. \quit
-- Make sure we have a sane search path to create/update the extension
SET search_path = "$user",cartodb,public,cdb_dataservices_client;
-- HERE goes your code to upgrade/downgrade

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,8 @@
--DO NOT MODIFY THIS FILE, IT IS GENERATED AUTOMATICALLY FROM SOURCES
-- Complain if script is sourced in psql, rather than via CREATE EXTENSION
\echo Use "ALTER EXTENSION cdb_dataservices_client UPDATE TO '0.26.2'" to load this file. \quit
-- Make sure we have a sane search path to create/update the extension
SET search_path = "$user",cartodb,public,cdb_dataservices_client;
-- HERE goes your code to upgrade/downgrade

File diff suppressed because it is too large Load Diff

View File

@@ -1,69 +1,105 @@
---
- name: cdb_geocode_admin0_polygon
return_type: Geometry
return_type: public.Geometry
requires_permission: true
permission_name: geocoding
permission_error: Geocoding permission denied
params:
- { name: country_name, type: text }
- name: cdb_geocode_admin1_polygon
return_type: Geometry
return_type: public.Geometry
requires_permission: true
permission_name: geocoding
permission_error: Geocoding permission denied
params:
- { name: admin1_name, type: text }
- name: cdb_geocode_admin1_polygon
return_type: Geometry
return_type: public.Geometry
requires_permission: true
permission_name: geocoding
permission_error: Geocoding permission denied
params:
- { name: admin1_name, type: text }
- { name: country_name, type: text }
- name: cdb_geocode_namedplace_point
return_type: Geometry
return_type: public.Geometry
requires_permission: true
permission_name: geocoding
permission_error: Geocoding permission denied
params:
- { name: city_name, type: text}
- name: cdb_geocode_namedplace_point
return_type: Geometry
return_type: public.Geometry
requires_permission: true
permission_name: geocoding
permission_error: Geocoding permission denied
params:
- { name: city_name, type: text}
- { name: country_name, type: text}
- name: cdb_geocode_namedplace_point
return_type: Geometry
return_type: public.Geometry
requires_permission: true
permission_name: geocoding
permission_error: Geocoding permission denied
params:
- { name: city_name, type: text}
- { name: admin1_name, type: text}
- { name: country_name, type: text}
- name: cdb_geocode_postalcode_polygon
return_type: Geometry
return_type: public.Geometry
requires_permission: true
permission_name: geocoding
permission_error: Geocoding permission denied
params:
- { name: postal_code, type: text}
- { name: country_name, type: text}
- name: cdb_geocode_postalcode_polygon
return_type: Geometry
return_type: public.Geometry
requires_permission: true
permission_name: geocoding
permission_error: Geocoding permission denied
params:
- { name: postal_code, type: double precision}
- { name: country_name, type: text}
- name: cdb_geocode_postalcode_point
return_type: Geometry
return_type: public.Geometry
requires_permission: true
permission_name: geocoding
permission_error: Geocoding permission denied
params:
- { name: postal_code, type: text}
- { name: country_name, type: text}
- name: cdb_geocode_postalcode_point
return_type: Geometry
return_type: public.Geometry
requires_permission: true
permission_name: geocoding
permission_error: Geocoding permission denied
params:
- { name: postal_code, type: double precision}
- { name: country_name, type: text}
- name: cdb_geocode_ipaddress_point
return_type: Geometry
return_type: public.Geometry
requires_permission: true
permission_name: geocoding
permission_error: Geocoding permission denied
params:
- { name: ip_address, type: text}
- name: cdb_geocode_street_point
return_type: Geometry
return_type: public.Geometry
requires_permission: true
permission_name: geocoding
permission_error: Geocoding permission denied
params:
- { name: searchtext, type: text}
- { name: city, type: text, default: 'NULL'}
@@ -74,11 +110,17 @@
return_type: SETOF cdb_dataservices_client.geocoding
multi_row: true
multi_field: true
requires_permission: true
permission_name: geocoding
permission_error: Geocoding permission denied
params:
- { name: searches, type: jsonb } # Array of JSON objects with id, address, city, state and country fields
- name: cdb_here_geocode_street_point
return_type: Geometry
return_type: public.Geometry
requires_permission: true
permission_name: geocoding
permission_error: Geocoding permission denied
params:
- { name: searchtext, type: text}
- { name: city, type: text, default: 'NULL'}
@@ -86,7 +128,10 @@
- { name: country, type: text, default: 'NULL'}
- name: cdb_google_geocode_street_point
return_type: Geometry
return_type: public.Geometry
requires_permission: true
permission_name: geocoding
permission_error: Geocoding permission denied
params:
- { name: searchtext, type: text}
- { name: city, type: text, default: 'NULL'}
@@ -94,7 +139,10 @@
- { name: country, type: text, default: 'NULL'}
- name: cdb_mapbox_geocode_street_point
return_type: Geometry
return_type: public.Geometry
requires_permission: true
permission_name: geocoding
permission_error: Geocoding permission denied
params:
- { name: searchtext, type: text}
- { name: city, type: text, default: 'NULL'}
@@ -102,7 +150,21 @@
- { name: country, type: text, default: 'NULL'}
- name: cdb_tomtom_geocode_street_point
return_type: Geometry
return_type: public.Geometry
requires_permission: true
permission_name: geocoding
permission_error: Geocoding permission denied
params:
- { name: searchtext, type: text}
- { name: city, type: text, default: 'NULL'}
- { name: state_province, type: text, default: 'NULL'}
- { name: country, type: text, default: 'NULL'}
- name: cdb_geocodio_geocode_street_point
return_type: public.Geometry
requires_permission: true
permission_name: geocoding
permission_error: Geocoding permission denied
params:
- { name: searchtext, type: text}
- { name: city, type: text, default: 'NULL'}
@@ -110,7 +172,10 @@
- { name: country, type: text, default: 'NULL'}
- name: cdb_mapzen_geocode_street_point
return_type: Geometry
return_type: public.Geometry
requires_permission: true
permission_name: geocoding
permission_error: Geocoding permission denied
params:
- { name: searchtext, type: text}
- { name: city, type: text, default: 'NULL'}
@@ -121,8 +186,11 @@
return_type: SETOF cdb_dataservices_client.isoline
multi_row: true
multi_field: true
requires_permission: true
permission_name: isolines
permission_error: Isolines permission denied
params:
- { name: source, type: "geometry(Geometry, 4326)" }
- { name: source, type: "public.geometry(Geometry, 4326)" }
- { name: mode, type: text }
- { name: range, type: "integer[]" }
- { name: options, type: "text[]", default: 'ARRAY[]::text[]' }
@@ -131,8 +199,11 @@
return_type: SETOF cdb_dataservices_client.isoline
multi_row: true
multi_field: true
requires_permission: true
permission_name: isolines
permission_error: Isolines permission denied
params:
- { name: source, type: "geometry(Geometry, 4326)" }
- { name: source, type: "public.geometry(Geometry, 4326)" }
- { name: mode, type: text }
- { name: range, type: "integer[]" }
- { name: options, type: "text[]", default: 'ARRAY[]::text[]' }
@@ -141,8 +212,11 @@
return_type: SETOF cdb_dataservices_client.isoline
multi_row: true
multi_field: true
requires_permission: true
permission_name: isolines
permission_error: Isolines permission denied
params:
- { name: source, type: "geometry(Geometry, 4326)" }
- { name: source, type: "public.geometry(Geometry, 4326)" }
- { name: mode, type: text }
- { name: range, type: "integer[]" }
- { name: options, type: "text[]", default: 'ARRAY[]::text[]' }
@@ -151,8 +225,11 @@
return_type: SETOF cdb_dataservices_client.isoline
multi_row: true
multi_field: true
requires_permission: true
permission_name: isolines
permission_error: Isolines permission denied
params:
- { name: source, type: "geometry(Geometry, 4326)" }
- { name: source, type: "public.geometry(Geometry, 4326)" }
- { name: mode, type: text }
- { name: range, type: "integer[]" }
- { name: options, type: "text[]", default: 'ARRAY[]::text[]' }
@@ -161,8 +238,11 @@
return_type: SETOF cdb_dataservices_client.isoline
multi_row: true
multi_field: true
requires_permission: true
permission_name: isolines
permission_error: Isolines permission denied
params:
- { name: source, type: "geometry(Geometry, 4326)" }
- { name: source, type: "public.geometry(Geometry, 4326)" }
- { name: mode, type: text }
- { name: range, type: "integer[]" }
- { name: options, type: "text[]", default: 'ARRAY[]::text[]' }
@@ -171,8 +251,11 @@
return_type: SETOF cdb_dataservices_client.isoline
multi_row: true
multi_field: true
requires_permission: true
permission_name: isolines
permission_error: Isolines permission denied
params:
- { name: source, type: "geometry(Geometry, 4326)" }
- { name: source, type: "public.geometry(Geometry, 4326)" }
- { name: mode, type: text }
- { name: range, type: "integer[]" }
- { name: options, type: "text[]", default: 'ARRAY[]::text[]' }
@@ -181,8 +264,11 @@
return_type: SETOF cdb_dataservices_client.isoline
multi_row: true
multi_field: true
requires_permission: true
permission_name: isolines
permission_error: Isolines permission denied
params:
- { name: source, type: "geometry(Geometry, 4326)" }
- { name: source, type: "public.geometry(Geometry, 4326)" }
- { name: mode, type: text }
- { name: range, type: "integer[]" }
- { name: options, type: "text[]", default: 'ARRAY[]::text[]' }
@@ -191,8 +277,11 @@
return_type: SETOF cdb_dataservices_client.isoline
multi_row: true
multi_field: true
requires_permission: true
permission_name: isolines
permission_error: Isolines permission denied
params:
- { name: source, type: "geometry(Geometry, 4326)" }
- { name: source, type: "public.geometry(Geometry, 4326)" }
- { name: mode, type: text }
- { name: range, type: "integer[]" }
- { name: options, type: "text[]", default: 'ARRAY[]::text[]' }
@@ -200,9 +289,12 @@
- name: cdb_route_point_to_point
return_type: cdb_dataservices_client.simple_route
multi_field: true
requires_permission: true
permission_name: routing
permission_error: Routing permission denied
params:
- { name: origin, type: "geometry(Point, 4326)" }
- { name: destination, type: "geometry(Point, 4326)" }
- { name: origin, type: "public.geometry(Point, 4326)" }
- { name: destination, type: "public.geometry(Point, 4326)" }
- { name: mode, type: text }
- { name: options, type: "text[]", default: 'ARRAY[]::text[]' }
- { name: units, type: "text", default: "'kilometers'"}
@@ -210,56 +302,80 @@
- name: cdb_route_with_waypoints
return_type: cdb_dataservices_client.simple_route
multi_field: true
requires_permission: true
permission_name: routing
permission_error: Routing permission denied
params:
- { name: waypoints, type: "geometry(Point, 4326)[]" }
- { name: waypoints, type: "public.geometry(Point, 4326)[]" }
- { name: mode, type: text }
- { name: options, type: "text[]", default: 'ARRAY[]::text[]' }
- { name: units, type: "text", default: "'kilometers'"}
- name: obs_get_demographic_snapshot
return_type: json
requires_permission: true
permission_name: observatory
permission_error: Data Observatory permission denied
params:
- { name: geom, type: "geometry(Geometry, 4326)" }
- { name: geom, type: "public.geometry(Geometry, 4326)" }
- { name: time_span, type: "text", default: "'2009 - 2013'::text" }
- { name: geometry_level, type: text, default: 'NULL' }
- name: obs_get_segment_snapshot
return_type: json
requires_permission: true
permission_name: observatory
permission_error: Data Observatory permission denied
params:
- { name: geom, type: "geometry(Geometry, 4326)" }
- { name: geom, type: "public.geometry(Geometry, 4326)" }
- { name: geometry_level, type: text, default: 'NULL' }
- name: obs_getdemographicsnapshot
return_type: SETOF JSON
multi_row: true
requires_permission: true
permission_name: observatory
permission_error: Data Observatory permission denied
params:
- { name: geom, type: "geometry(Geometry, 4326)" }
- { name: geom, type: "public.geometry(Geometry, 4326)" }
- { name: time_span, type: "text", default: 'NULL' }
- { name: geometry_level, type: text, default: 'NULL' }
- name: obs_getsegmentsnapshot
return_type: SETOF JSON
multi_row: true
requires_permission: true
permission_name: observatory
permission_error: Data Observatory permission denied
params:
- { name: geom, type: "geometry(Geometry, 4326)" }
- { name: geom, type: "public.geometry(Geometry, 4326)" }
- { name: geometry_level, type: text, default: 'NULL' }
- name: obs_getboundary
return_type: Geometry
return_type: public.Geometry
requires_permission: true
permission_name: observatory
permission_error: Data Observatory permission denied
params:
- { name: geom, type: "geometry(Geometry, 4326)" }
- { name: geom, type: "public.geometry(Geometry, 4326)" }
- { name: boundary_id, type: text }
- { name: time_span, type: text, default: 'NULL'}
- name: obs_getboundaryid
return_type: text
requires_permission: true
permission_name: observatory
permission_error: Data Observatory permission denied
params:
- { name: geom, type: "geometry(Geometry, 4326)" }
- { name: geom, type: "public.geometry(Geometry, 4326)" }
- { name: boundary_id, type: text }
- { name: time_span, type: text, default: 'NULL'}
- name: obs_getboundarybyid
return_type: Geometry
return_type: public.Geometry
requires_permission: true
permission_name: observatory
permission_error: Data Observatory permission denied
params:
- { name: geometry_id, type: text }
- { name: boundary_id, type: text }
@@ -269,11 +385,14 @@
return_type: TABLE(the_geom geometry, geom_refs text)
multi_row: true
multi_field: true
requires_permission: true
permission_name: observatory
permission_error: Data Observatory permission denied
table_fields:
- { name: the_geom, type: geometry }
- { name: geom_refs, type: text }
params:
- { name: geom, type: "geometry(Geometry, 4326)" }
- { name: geom, type: "public.geometry(Geometry, 4326)" }
- { name: boundary_id, type: text }
- { name: time_span, type: text, default: 'NULL'}
- { name: overlap_type, type: text, default: 'NULL'}
@@ -282,11 +401,14 @@
return_type: TABLE(the_geom geometry, geom_refs text)
multi_row: true
multi_field: true
requires_permission: true
permission_name: observatory
permission_error: Data Observatory permission denied
table_fields:
- { name: the_geom, type: geometry }
- { name: geom_refs, type: text }
params:
- { name: geom, type: "geometry(Geometry, 4326)" }
- { name: geom, type: "public.geometry(Geometry, 4326)" }
- { name: radius, type: numeric }
- { name: boundary_id, type: text }
- { name: time_span, type: text, default: 'NULL'}
@@ -296,11 +418,14 @@
return_type: TABLE(the_geom geometry, geom_refs text)
multi_row: true
multi_field: true
requires_permission: true
permission_name: observatory
permission_error: Data Observatory permission denied
table_fields:
- { name: the_geom, type: geometry }
- { name: geom_refs, type: text }
params:
- { name: geom, type: "geometry(Geometry, 4326)" }
- { name: geom, type: "public.geometry(Geometry, 4326)" }
- { name: boundary_id, type: text }
- { name: time_span, type: text, default: 'NULL'}
- { name: overlap_type, type: text, default: 'NULL'}
@@ -309,11 +434,14 @@
return_type: TABLE(the_geom geometry, geom_refs text)
multi_row: true
multi_field: true
requires_permission: true
permission_name: observatory
permission_error: Data Observatory permission denied
table_fields:
- { name: the_geom, type: geometry }
- { name: geom_refs, type: text }
params:
- { name: geom, type: "geometry(Geometry, 4326)" }
- { name: geom, type: "public.geometry(Geometry, 4326)" }
- { name: radius, type: numeric }
- { name: boundary_id, type: text }
- { name: time_span, type: text, default: 'NULL'}
@@ -321,8 +449,11 @@
- name: obs_getmeasure
return_type: numeric
requires_permission: true
permission_name: observatory
permission_error: Data Observatory permission denied
params:
- { name: geom, type: Geometry }
- { name: geom, type: public.Geometry }
- { name: measure_id, type: text }
- { name: normalize, type: text, default: 'NULL'}
- { name: boundary_id, type: text, default: 'NULL' }
@@ -330,6 +461,9 @@
- name: obs_getmeasurebyid
return_type: numeric
requires_permission: true
permission_name: observatory
permission_error: Data Observatory permission denied
params:
- { name: geom_ref, type: text }
- { name: measure_id, type: text }
@@ -340,6 +474,9 @@
return_type: TABLE(id int, data json)
multi_row: true
multi_field: true
requires_permission: true
permission_name: observatory
permission_error: Data Observatory permission denied
table_fields:
- { name: id, type: integer }
- { name: data, type: json }
@@ -352,6 +489,9 @@
return_type: TABLE(id text, data json)
multi_row: true
multi_field: true
requires_permission: true
permission_name: observatory
permission_error: Data Observatory permission denied
table_fields:
- { name: id, type: text }
- { name: data, type: json }
@@ -361,8 +501,11 @@
- name: obs_getmeta
return_type: json
requires_permission: true
permission_name: observatory
permission_error: Data Observatory permission denied
params:
- { name: geom_ref, type: "Geometry(Geometry, 4326)" }
- { name: geom_ref, type: "public.Geometry(Geometry, 4326)" }
- { name: params, type: json }
- { name: max_timespan_rank, type: integer, default: 'NULL' }
- { name: max_score_rank, type: integer, default: 'NULL' }
@@ -372,24 +515,33 @@
return_type: TABLE(valid boolean, errors text[])
multi_row: true
multi_field: true
requires_permission: true
permission_name: observatory
permission_error: Data Observatory permission denied
params:
- { name: geom_extent, type: "Geometry(Geometry, 4326)" }
- { name: geom_extent, type: "public.Geometry(Geometry, 4326)" }
- { name: geom_type, type: text }
- { name: params, type: json }
- { name: target_geoms, type: integer, default: 'NULL' }
- name: obs_getcategory
return_type: text
requires_permission: true
permission_name: observatory
permission_error: Data Observatory permission denied
params:
- { name: geom, type: Geometry }
- { name: geom, type: public.Geometry }
- { name: category_id, type: text }
- { name: boundary_id, type: text, default: 'NULL' }
- { name: time_span, type: text, default: 'NULL'}
- name: obs_getuscensusmeasure
return_type: numeric
requires_permission: true
permission_name: observatory
permission_error: Data Observatory permission denied
params:
- { name: geom, type: Geometry }
- { name: geom, type: public.Geometry }
- { name: name, type: text }
- { name: normalize, type: text, default: 'NULL'}
- { name: boundary_id, type: text, default: 'NULL' }
@@ -397,16 +549,22 @@
- name: obs_getuscensuscategory
return_type: text
requires_permission: true
permission_name: observatory
permission_error: Data Observatory permission denied
params:
- { name: geom, type: Geometry }
- { name: geom, type: public.Geometry }
- { name: name, type: text }
- { name: boundary_id, type: text, default: 'NULL' }
- { name: time_span, type: text, default: 'NULL'}
- name: obs_getpopulation
return_type: numeric
requires_permission: true
permission_name: observatory
permission_error: Data Observatory permission denied
params:
- { name: geom, type: Geometry }
- { name: geom, type: public.Geometry }
- { name: normalize, type: text, default: 'NULL'}
- { name: boundary_id, type: text, default: 'NULL' }
- { name: time_span, type: text, default: 'NULL'}
@@ -415,6 +573,9 @@
return_type: TABLE(id text, description text, name text, aggregate text, source text)
multi_row: true
multi_field: true
requires_permission: true
permission_name: observatory
permission_error: Data Observatory permission denied
table_fields:
- { name: id, type: text }
- { name: description, type: text }
@@ -429,17 +590,23 @@
return_type: TABLE(boundary_id text, description text, time_span text, tablename text)
multi_row: true
multi_field: true
requires_permission: true
permission_name: observatory
permission_error: Data Observatory permission denied
table_fields:
- { name: boundary_id, type: text }
- { name: description, type: text }
- { name: time_span, type: text }
- { name: tablename, type: text }
params:
- { name: geom, type: Geometry }
- { name: geom, type: public.Geometry }
- { name: timespan, type: text, default: 'NULL'}
- name: obs_dumpversion
return_type: text
requires_permission: true
permission_name: observatory
permission_error: Data Observatory permission denied
params:
- {}
@@ -447,8 +614,11 @@
return_type: SETOF cdb_dataservices_client.obs_meta_numerator
multi_row: true
multi_field: true
requires_permission: true
permission_name: observatory
permission_error: Data Observatory permission denied
params:
- { name: bounds, type: "geometry(Geometry, 4326)", default: 'NULL' }
- { name: bounds, type: "public.geometry(Geometry, 4326)", default: 'NULL' }
- { name: filter_tags, type: "text[]", default: 'NULL' }
- { name: denom_id, type: text, default: 'NULL' }
- { name: geom_id, type: text, default: 'NULL' }
@@ -458,8 +628,11 @@
return_type: SETOF cdb_dataservices_client.obs_meta_numerator
multi_row: true
multi_field: true
requires_permission: true
permission_name: observatory
permission_error: Data Observatory permission denied
params:
- { name: bounds, type: "geometry(Geometry, 4326)", default: 'NULL' }
- { name: bounds, type: "public.geometry(Geometry, 4326)", default: 'NULL' }
- { name: section_tags, type: "text[]", default: 'ARRAY[]::TEXT[]' }
- { name: subsection_tags, type: "text[]", default: 'ARRAY[]::TEXT[]' }
- { name: other_tags, type: "text[]", default: 'ARRAY[]::TEXT[]' }
@@ -473,8 +646,11 @@
return_type: SETOF cdb_dataservices_client.obs_meta_denominator
multi_row: true
multi_field: true
requires_permission: true
permission_name: observatory
permission_error: Data Observatory permission denied
params:
- { name: bounds, type: "geometry(Geometry, 4326)", default: 'NULL' }
- { name: bounds, type: "public.geometry(Geometry, 4326)", default: 'NULL' }
- { name: filter_tags, type: "text[]", default: 'NULL' }
- { name: numer_id, type: text, default: 'NULL' }
- { name: geom_id, type: text, default: 'NULL' }
@@ -484,8 +660,11 @@
return_type: SETOF cdb_dataservices_client.obs_meta_geometry
multi_row: true
multi_field: true
requires_permission: true
permission_name: observatory
permission_error: Data Observatory permission denied
params:
- { name: bounds, type: "geometry(Geometry, 4326)", default: 'NULL' }
- { name: bounds, type: "public.geometry(Geometry, 4326)", default: 'NULL' }
- { name: filter_tags, type: "text[]", default: 'NULL' }
- { name: numer_id, type: text, default: 'NULL' }
- { name: denom_id, type: text, default: 'NULL' }
@@ -496,8 +675,11 @@
return_type: SETOF cdb_dataservices_client.obs_meta_timespan
multi_row: true
multi_field: true
requires_permission: true
permission_name: observatory
permission_error: Data Observatory permission denied
params:
- { name: bounds, type: "geometry(Geometry, 4326)", default: 'NULL' }
- { name: bounds, type: "public.geometry(Geometry, 4326)", default: 'NULL' }
- { name: filter_tags, type: "text[]", default: 'NULL' }
- { name: numer_id, type: text, default: 'NULL' }
- { name: denom_id, type: text, default: 'NULL' }
@@ -507,6 +689,9 @@
return_type: TABLE(name text, subsection json)
multi_row: true
multi_field: true
requires_permission: true
permission_name: observatory
permission_error: Data Observatory permission denied
params:
- { name: aggregate_type, type: text, default: 'NULL' }

View File

@@ -28,6 +28,18 @@ class SqlTemplateRenderer
@function_signature['return_type']
end
def requires_permission
@function_signature['requires_permission']
end
def permission_name
@function_signature['permission_name']
end
def permission_error
@function_signature['permission_error']
end
def multi_field
@function_signature['multi_field']
end

View File

@@ -9,11 +9,16 @@ RETURNS <%= return_type %> AS $$
DECLARE
<%= return_declaration if not multi_row %>
<%= user_org_declaration %>
<% unless superuser_function? -%>apikey_permissions json;<% end %>
BEGIN
IF session_user = 'publicuser' OR session_user ~ 'cartodb_publicuser_*' THEN
<% unless requires_permission %>IF session_user = 'publicuser' OR session_user ~ 'cartodb_publicuser_*' THEN
RAISE EXCEPTION 'The api_key must be provided';
END IF;
<% unless superuser_function? -%>SELECT u, o INTO username, orgname FROM <%= DATASERVICES_CLIENT_SCHEMA %>._cdb_entity_config() AS (u text, o text);<% end %>
END IF;<% end %>
<% unless superuser_function? -%>SELECT u, o, p INTO username, orgname, apikey_permissions FROM cdb_dataservices_client._cdb_entity_config() AS (u text, o text, p json);
<% if requires_permission %>IF apikey_permissions IS NULL OR NOT apikey_permissions::jsonb ? '<%= permission_name %>' THEN
RAISE EXCEPTION '<%= permission_error %>' USING ERRCODE = '01007';
END IF;<% end %>
<% else %>SELECT u, o INTO username, orgname FROM <%= DATASERVICES_CLIENT_SCHEMA %>._cdb_entity_config() AS (u text, o text, p json);<% end %>
-- JSON value stored "" is taken as literal
IF username IS NULL OR username = '' OR username = '""' THEN
RAISE EXCEPTION 'Username is a mandatory argument, check it out';
@@ -21,4 +26,5 @@ BEGIN
<% return_statement do %><%= DATASERVICES_CLIENT_SCHEMA %>._<%= name %>(<%= params(_with_user_org=true).join(', ') %>)<% end %>
END;
$$ LANGUAGE 'plpgsql' SECURITY DEFINER STABLE PARALLEL UNSAFE;
$$ LANGUAGE 'plpgsql' SECURITY DEFINER STABLE PARALLEL UNSAFE
SET search_path = pg_temp;

View File

@@ -10,11 +10,16 @@ DECLARE
_returned_sqlstate TEXT;
_message_text TEXT;
_pg_exception_context TEXT;
<% unless superuser_function? -%>apikey_permissions json;<% end %>
BEGIN
IF session_user = 'publicuser' OR session_user ~ 'cartodb_publicuser_*' THEN
<% unless requires_permission %>IF session_user = 'publicuser' OR session_user ~ 'cartodb_publicuser_*' THEN
RAISE EXCEPTION 'The api_key must be provided';
END IF;
<% unless superuser_function? -%>SELECT u, o INTO username, orgname FROM <%= DATASERVICES_CLIENT_SCHEMA %>._cdb_entity_config() AS (u text, o text);<% end %>
END IF;<% end %>
<% unless superuser_function? -%>SELECT u, o, p INTO username, orgname, apikey_permissions FROM cdb_dataservices_client._cdb_entity_config() AS (u text, o text, p json);
<% if requires_permission %>IF apikey_permissions IS NULL OR NOT apikey_permissions::jsonb ? '<%= permission_name %>' THEN
RAISE EXCEPTION '<%= permission_error %>';
END IF;<% end %>
<% else %>SELECT u, o INTO username, orgname FROM <%= DATASERVICES_CLIENT_SCHEMA %>._cdb_entity_config() AS (u text, o text, p json);<% end %>
-- JSON value stored "" is taken as literal
IF username IS NULL OR username = '' OR username = '""' THEN
RAISE EXCEPTION 'Username is a mandatory argument, check it out';
@@ -32,4 +37,5 @@ BEGIN
<%= return_statement %>
END;
END;
$$ LANGUAGE 'plpgsql' SECURITY DEFINER STABLE PARALLEL UNSAFE;
$$ LANGUAGE 'plpgsql' SECURITY DEFINER STABLE PARALLEL UNSAFE
SET search_path = pg_temp;

View File

@@ -1,6 +1,7 @@
CREATE TYPE cdb_dataservices_client._entity_config AS (
username text,
organization_name text
organization_name text,
apikey_permissions json
);
--
@@ -13,25 +14,23 @@ CREATE OR REPLACE FUNCTION cdb_dataservices_client._cdb_entity_config()
RETURNS record AS $$
DECLARE
result cdb_dataservices_client._entity_config;
apikey_config json;
is_organization boolean;
username text;
organization_name text;
organization_name text DEFAULT NULL;
BEGIN
SELECT cartodb.cdb_conf_getconf('api_keys_'||session_user) INTO apikey_config;
SELECT cartodb.cdb_conf_getconf('user_config')->'is_organization' INTO is_organization;
IF is_organization IS NULL THEN
RAISE EXCEPTION 'User must have user configuration in the config table';
ELSIF is_organization = TRUE THEN
SELECT nspname
FROM pg_namespace s
LEFT JOIN pg_roles r ON s.nspowner = r.oid
WHERE r.rolname = session_user INTO username;
SELECT cartodb.cdb_conf_getconf('user_config')->>'entity_name' INTO organization_name;
ELSE
SELECT cartodb.cdb_conf_getconf('user_config')->>'entity_name' INTO username;
organization_name = NULL;
END IF;
result.username = username;
result.username = apikey_config->>'username';
result.organization_name = organization_name;
result.apikey_permissions = apikey_config->'permissions';
RETURN result;
END;
$$ LANGUAGE 'plpgsql' SECURITY DEFINER STABLE PARALLEL SAFE;
$$ LANGUAGE 'plpgsql' SECURITY DEFINER STABLE PARALLEL SAFE
SET search_path = pg_temp;

View File

@@ -6,7 +6,7 @@ CREATE TYPE cdb_dataservices_client.isoline AS (
CREATE TYPE cdb_dataservices_client.geocoding AS (
cartodb_id integer,
the_geom geometry(Multipolygon,4326),
the_geom geometry(Point,4326),
metadata jsonb
);

View File

@@ -18,7 +18,7 @@ BEGIN
SELECT session_user INTO user_db_role;
SELECT u, o INTO username, orgname FROM cdb_dataservices_client._cdb_entity_config() AS (u text, o text);
SELECT u, o INTO username, orgname FROM cdb_dataservices_client._cdb_entity_config() AS (u text, o text, p json);
-- JSON value stored "" is taken as literal
IF username IS NULL OR username = '' OR username = '""' THEN
RAISE EXCEPTION 'Username is a mandatory argument';
@@ -41,7 +41,9 @@ BEGIN
RETURN result;
END;
$$ LANGUAGE 'plpgsql' SECURITY DEFINER VOLATILE PARALLEL UNSAFE;
$$ LANGUAGE 'plpgsql' SECURITY DEFINER VOLATILE PARALLEL UNSAFE
SET search_path = pg_temp;
CREATE OR REPLACE FUNCTION cdb_dataservices_client._DST_PopulateTableOBS_GetMeasure(
table_name text,
@@ -62,7 +64,7 @@ BEGIN
SELECT session_user INTO user_db_role;
SELECT u, o INTO username, orgname FROM cdb_dataservices_client._cdb_entity_config() AS (u text, o text);
SELECT u, o INTO username, orgname FROM cdb_dataservices_client._cdb_entity_config() AS (u text, o text, p json);
-- JSON value stored "" is taken as literal
IF username IS NULL OR username = '' OR username = '""' THEN
RAISE EXCEPTION 'Username is a mandatory argument';
@@ -89,7 +91,9 @@ BEGIN
RETURN result;
END;
$$ LANGUAGE 'plpgsql' SECURITY DEFINER VOLATILE PARALLEL UNSAFE;
$$ LANGUAGE 'plpgsql' SECURITY DEFINER VOLATILE PARALLEL UNSAFE
SET search_path = pg_temp;
CREATE OR REPLACE FUNCTION cdb_dataservices_client.__DST_PrepareTableOBS_GetMeasure(
@@ -124,7 +128,7 @@ CREATE OR REPLACE FUNCTION cdb_dataservices_client.__DST_PrepareTableOBS_GetMeas
# Create a new table with the required columns
plpy.execute('CREATE TABLE "{schema}".{table_name} ( '
'cartodb_id int, the_geom geometry, {columns_with_types} '
'cartodb_id int, the_geom public.geometry, {columns_with_types} '
');'
.format(schema=user_schema, table_name=output_table_name, columns_with_types=columns_with_types)
)
@@ -200,7 +204,7 @@ CREATE OR REPLACE FUNCTION cdb_dataservices_client.__DST_PopulateTableOBS_GetMea
'INSERT INTO "{schema}".{analysis_table_name} '
'SELECT ut.cartodb_id, ut.the_geom, {colname_list} '
'FROM "{schema}".{table_name} ut '
'LEFT JOIN _DST_FetchJoinFdwTableData({username}::text, {orgname}::text, {server_schema}::text, {server_table_name}::text, '
'LEFT JOIN cdb_dataservices_client._DST_FetchJoinFdwTableData({username}::text, {orgname}::text, {server_schema}::text, {server_table_name}::text, '
'{function_name}::text, {params}::json) '
'AS result ({columns_with_types}, cartodb_id int) '
'ON result.cartodb_id = ut.cartodb_id;' .format(

View File

@@ -13,7 +13,20 @@ DECLARE
MAX_SAFE_BATCH_SIZE CONSTANT numeric := 5000;
temp_table_name text;
username text;
orgname text;
apikey_permissions json;
BEGIN
SELECT u, o, p INTO username, orgname, apikey_permissions FROM cdb_dataservices_client._cdb_entity_config() AS (u text, o text, p json);
IF apikey_permissions IS NULL OR NOT apikey_permissions::jsonb ? 'geocoding' THEN
RAISE EXCEPTION 'Geocoding permission denied' USING ERRCODE = '01007';
END IF;
-- JSON value stored "" is taken as literal
IF username IS NULL OR username = '' OR username = '""' THEN
RAISE EXCEPTION 'Username is a mandatory argument, check it out';
END IF;
SELECT csqi.monthly_quota - csqi.used_quota AS remaining_quota, csqi.max_batch_size
INTO remaining_quota, max_batch_size
FROM cdb_dataservices_client.cdb_service_quota_info_batch() csqi
@@ -36,7 +49,7 @@ BEGIN
RAISE DEBUG 'cdb_bulk_geocode_street_point --> query_row_count: %; query: %; country: %; state: %; city: %; street: %',
query_row_count, query, country_column, state_column, city_column, street_column;
SELECT cdb_dataservices_client.cdb_enough_quota('hires_geocoder', query_row_count) INTO enough_quota;
IF remaining_quota < query_row_count THEN
IF enough_quota IS NULL OR NOT enough_quota THEN
RAISE EXCEPTION 'Remaining quota: %. Estimated cost: %', remaining_quota, query_row_count;
END IF;
@@ -45,7 +58,7 @@ BEGIN
temp_table_name := 'bulk_geocode_street_' || md5(random()::text);
EXECUTE format('CREATE TEMPORARY TABLE %s ' ||
'(cartodb_id integer, the_geom geometry(Multipolygon,4326), metadata jsonb)',
'(cartodb_id integer, the_geom public.geometry(Point,4326), metadata jsonb)',
temp_table_name);
select
@@ -73,4 +86,5 @@ BEGIN
RETURN QUERY EXECUTE 'SELECT * FROM ' || quote_ident(temp_table_name);
END;
$$ LANGUAGE 'plpgsql' SECURITY DEFINER VOLATILE PARALLEL UNSAFE;
$$ LANGUAGE 'plpgsql' SECURITY DEFINER VOLATILE PARALLEL UNSAFE
SET search_path = pg_temp;

View File

@@ -9,7 +9,26 @@ BEGIN
RETURN NULL;
END;
$$ LANGUAGE 'plpgsql';
-- Exercise the public and the proxied function
-- -- Exercise the public and the proxied function
-- No permissions granted
SELECT cdb_geocode_admin0_polygon('Spain');
ERROR: Geocoding permission denied
-- Grant other permissions but geocoding
SELECT CDB_Conf_SetConf('api_keys_postgres', '{"username": "test_user", "permissions": ["routing", "isolines"]}');
cdb_conf_setconf
------------------
(1 row)
SELECT cdb_geocode_admin0_polygon('Spain');
ERROR: Geocoding permission denied
-- Grant geocoding permissions
SELECT CDB_Conf_SetConf('api_keys_postgres', '{"username": "test_user", "permissions": ["geocoding"]}');
cdb_conf_setconf
------------------
(1 row)
SELECT cdb_geocode_admin0_polygon('Spain');
NOTICE: cdb_dataservices_client._cdb_geocode_admin0_polygon(3): [contrib_regression] REMOTE NOTICE: cdb_dataservices_server.cdb_geocode_admin0_polygon invoked with params (test_user, <NULL>, Spain)
cdb_geocode_admin0_polygon
@@ -17,3 +36,10 @@ NOTICE: cdb_dataservices_client._cdb_geocode_admin0_polygon(3): [contrib_regres
(1 row)
-- Remove permissions
SELECT CDB_Conf_RemoveConf('api_keys_postgres');
cdb_conf_removeconf
---------------------
(1 row)

View File

@@ -16,7 +16,30 @@ BEGIN
RETURN NULL;
END;
$$ LANGUAGE 'plpgsql';
-- Exercise the public and the proxied function
-- -- Exercise the public and the proxied function
-- No permissions granted
SELECT cdb_geocode_admin1_polygon('California');
ERROR: Geocoding permission denied
SELECT cdb_geocode_admin1_polygon('California', 'United States');
ERROR: Geocoding permission denied
-- Grant other permissions but geocoding
SELECT CDB_Conf_SetConf('api_keys_postgres', '{"username": "test_user", "permissions": ["routing", "isolines"]}');
cdb_conf_setconf
------------------
(1 row)
SELECT cdb_geocode_admin1_polygon('California');
ERROR: Geocoding permission denied
SELECT cdb_geocode_admin1_polygon('California', 'United States');
ERROR: Geocoding permission denied
-- Grant geocoding permissions
SELECT CDB_Conf_SetConf('api_keys_postgres', '{"username": "test_user", "permissions": ["geocoding"]}');
cdb_conf_setconf
------------------
(1 row)
SELECT cdb_geocode_admin1_polygon('California');
NOTICE: cdb_dataservices_client._cdb_geocode_admin1_polygon(3): [contrib_regression] REMOTE NOTICE: cdb_dataservices_server.cdb_geocode_admin1_polygon invoked with params (test_user, <NULL>, California)
cdb_geocode_admin1_polygon
@@ -31,3 +54,10 @@ NOTICE: cdb_dataservices_client._cdb_geocode_admin1_polygon(4): [contrib_regres
(1 row)
-- Remove permissions
SELECT CDB_Conf_RemoveConf('api_keys_postgres');
cdb_conf_removeconf
---------------------
(1 row)

View File

@@ -9,13 +9,68 @@ CREATE FUNCTION cdb_dataservices_client.cdb_enough_quota (service TEXT ,input_si
RETURNS BOOLEAN as $$
SELECT FALSE;
$$ LANGUAGE SQL;
ALTER FUNCTION cdb_dataservices_client._cdb_bulk_geocode_street_point(searches jsonb) RENAME TO _cdb_bulk_geocode_street_point_mocked;
CREATE FUNCTION cdb_dataservices_client._cdb_bulk_geocode_street_point(searches jsonb)
RETURNS SETOF cdb_dataservices_client.geocoding AS $$
BEGIN
RAISE NOTICE 'called with this searches: %', searches;
END;
$$ LANGUAGE 'plpgsql' SECURITY DEFINER STABLE PARALLEL UNSAFE SET search_path = pg_temp;
-- No permissions granted
-- Test bulk size not mandatory (it will get the optimal)
SELECT cdb_dataservices_client.cdb_bulk_geocode_street_point('select 1 as cartodb_id', '''Valladolid, Spain''', null, null, null, null);
ERROR: Geocoding permission denied
-- Test quota check by mocking quota 0
SELECT cdb_dataservices_client.cdb_bulk_geocode_street_point('select 1 as cartodb_id', '''Valladolid, Spain''');
ERROR: Geocoding permission denied
-- Grant other permissions but geocoding
SELECT CDB_Conf_SetConf('api_keys_postgres', '{"username": "test_user", "permissions": ["routing", "isolines"]}');
cdb_conf_setconf
------------------
(1 row)
-- Test bulk size not mandatory (it will get the optimal)
SELECT cdb_dataservices_client.cdb_bulk_geocode_street_point('select 1 as cartodb_id', '''Valladolid, Spain''', null, null, null, null);
ERROR: Geocoding permission denied
-- Test quota check by mocking quota 0
SELECT cdb_dataservices_client.cdb_bulk_geocode_street_point('select 1 as cartodb_id', '''Valladolid, Spain''');
ERROR: Geocoding permission denied
-- Grant geocoding permissions
SELECT CDB_Conf_SetConf('api_keys_postgres', '{"username": "test_user", "permissions": ["geocoding"]}');
cdb_conf_setconf
------------------
(1 row)
-- Test bulk size not mandatory (it will get the optimal)
SELECT cdb_dataservices_client.cdb_bulk_geocode_street_point('select 1 as cartodb_id', '''Valladolid, Spain''', null, null, null, null);
ERROR: Remaining quota: 0. Estimated cost: 1
-- Test quota check by mocking quota 0
SELECT cdb_dataservices_client.cdb_bulk_geocode_street_point('select 1 as cartodb_id', '''Valladolid, Spain''');
ERROR: Remaining quota: 0. Estimated cost: 1
-- Check that when cdb_enough_quota returns true (ie. when soft_limit is set to true, even if not enough quota)
-- it is able to proceed with the bulk geocode
CREATE OR REPLACE FUNCTION cdb_dataservices_client.cdb_enough_quota (service TEXT ,input_size NUMERIC)
RETURNS BOOLEAN as $$
SELECT TRUE;
$$ LANGUAGE SQL;
SELECT cdb_dataservices_client.cdb_bulk_geocode_street_point('select 1 as cartodb_id', '''Valladolid, Spain''');
NOTICE: called with this searches: [{"id": 1, "city": "", "state": "", "address": "Valladolid, Spain", "country": ""}]
cdb_bulk_geocode_street_point
-------------------------------
(0 rows)
-- Remove permissions
SELECT CDB_Conf_RemoveConf('api_keys_postgres');
cdb_conf_removeconf
---------------------
(1 row)
DROP FUNCTION cdb_dataservices_client.cdb_service_quota_info_batch;
DROP FUNCTION cdb_dataservices_client.cdb_enough_quota;
DROP FUNCTION cdb_dataservices_client._cdb_bulk_geocode_street_point;
ALTER FUNCTION cdb_dataservices_client.cdb_enough_quota_mocked (service TEXT ,input_size NUMERIC) RENAME TO cdb_enough_quota;
ALTER FUNCTION cdb_dataservices_client.cdb_service_quota_info_batch_mocked() RENAME TO cdb_service_quota_info_batch;
ALTER FUNCTION cdb_dataservices_client._cdb_bulk_geocode_street_point_mocked(searches jsonb) RENAME TO _cdb_bulk_geocode_street_point;

View File

@@ -27,9 +27,39 @@ BEGIN
RETURN ret;
END;
$$ LANGUAGE 'plpgsql';
-- Use regular user role
SET ROLE test_regular_user;
-- Exercise the exception safe and the proxied functions
-- No permissions granted
SET ROLE test_regular_user; -- Use regular user role
SELECT _cdb_geocode_street_point_exception_safe('One street, 1');
ERROR: Geocoding permission denied
SELECT * FROM _cdb_isodistance_exception_safe('POINT(-3.70568 40.42028)'::geometry, 'walk', ARRAY[300]::integer[]);
ERROR: Isolines permission denied
SELECT * FROM _cdb_route_point_to_point_exception_safe('POINT(-3.70237112 40.41706163)'::geometry,'POINT(-3.69909883 40.41236875)'::geometry, 'car', ARRAY['mode_type=shortest']::text[]);
ERROR: Routing permission denied
-- No permissions granted but conf created
SET ROLE postgres;
SELECT CDB_Conf_SetConf('api_keys_postgres', '{"username": "test_user", "permissions": []}');
cdb_conf_setconf
------------------
(1 row)
SET ROLE test_regular_user; -- Use regular user role
SELECT _cdb_geocode_street_point_exception_safe('One street, 1');
ERROR: Geocoding permission denied
SELECT * FROM _cdb_isodistance_exception_safe('POINT(-3.70568 40.42028)'::geometry, 'walk', ARRAY[300]::integer[]);
ERROR: Isolines permission denied
SELECT * FROM _cdb_route_point_to_point_exception_safe('POINT(-3.70237112 40.41706163)'::geometry,'POINT(-3.69909883 40.41236875)'::geometry, 'car', ARRAY['mode_type=shortest']::text[]);
ERROR: Routing permission denied
-- Grant geocoding permissions
SET ROLE postgres;
SELECT CDB_Conf_SetConf('api_keys_postgres', '{"username": "test_user", "permissions": ["geocoding", "routing", "isolines"]}');
cdb_conf_setconf
------------------
(1 row)
SET ROLE test_regular_user; -- Use regular user role
SELECT _cdb_geocode_street_point_exception_safe('One street, 1');
WARNING: cdb_dataservices_client._cdb_geocode_street_point(6): [contrib_regression] REMOTE ERROR: Not enough quota or any other exception whatsoever.
_cdb_geocode_street_point_exception_safe
@@ -50,3 +80,11 @@ WARNING: cdb_dataservices_client._cdb_route_point_to_point(7): [contrib_regress
| |
(1 row)
-- Remove permissions
SET ROLE postgres;
SELECT CDB_Conf_RemoveConf('api_keys_postgres');
cdb_conf_removeconf
---------------------
(1 row)

View File

@@ -23,7 +23,34 @@ BEGIN
RETURN NULL;
END;
$$ LANGUAGE 'plpgsql';
-- Exercise the public and the proxied function
-- -- Exercise the public and the proxied function
-- No permissions granted
SELECT cdb_geocode_namedplace_point('Elx');
ERROR: Geocoding permission denied
SELECT cdb_geocode_namedplace_point('Elx', 'Spain');
ERROR: Geocoding permission denied
SELECT cdb_geocode_namedplace_point('Elx', 'Valencia', 'Spain');
ERROR: Geocoding permission denied
-- Grant other permissions but geocoding
SELECT CDB_Conf_SetConf('api_keys_postgres', '{"username": "test_user", "permissions": ["routing", "isolines"]}');
cdb_conf_setconf
------------------
(1 row)
SELECT cdb_geocode_namedplace_point('Elx');
ERROR: Geocoding permission denied
SELECT cdb_geocode_namedplace_point('Elx', 'Spain');
ERROR: Geocoding permission denied
SELECT cdb_geocode_namedplace_point('Elx', 'Valencia', 'Spain');
ERROR: Geocoding permission denied
-- Grant geocoding permissions
SELECT CDB_Conf_SetConf('api_keys_postgres', '{"username": "test_user", "permissions": ["geocoding"]}');
cdb_conf_setconf
------------------
(1 row)
SELECT cdb_geocode_namedplace_point('Elx');
NOTICE: cdb_dataservices_client._cdb_geocode_namedplace_point(3): [contrib_regression] REMOTE NOTICE: cdb_dataservices_server.cdb_geocode_namedplace_point invoked with params (test_user, <NULL>, Elx)
cdb_geocode_namedplace_point
@@ -45,3 +72,10 @@ NOTICE: cdb_dataservices_client._cdb_geocode_namedplace_point(5): [contrib_regr
(1 row)
-- Remove permissions
SELECT CDB_Conf_RemoveConf('api_keys_postgres');
cdb_conf_removeconf
---------------------
(1 row)

View File

@@ -16,7 +16,30 @@ BEGIN
RETURN NULL;
END;
$$ LANGUAGE 'plpgsql';
-- Exercise the public and the proxied function
-- -- Exercise the public and the proxied function
-- No permissions granted
SELECT cdb_geocode_postalcode_polygon('03204', 'Spain');
ERROR: Geocoding permission denied
SELECT cdb_geocode_postalcode_point('03204', 'Spain');
ERROR: Geocoding permission denied
-- Grant other permissions but geocoding
SELECT CDB_Conf_SetConf('api_keys_postgres', '{"username": "test_user", "permissions": ["routing", "isolines"]}');
cdb_conf_setconf
------------------
(1 row)
SELECT cdb_geocode_postalcode_polygon('03204', 'Spain');
ERROR: Geocoding permission denied
SELECT cdb_geocode_postalcode_point('03204', 'Spain');
ERROR: Geocoding permission denied
-- Grant geocoding permissions
SELECT CDB_Conf_SetConf('api_keys_postgres', '{"username": "test_user", "permissions": ["geocoding"]}');
cdb_conf_setconf
------------------
(1 row)
SELECT cdb_geocode_postalcode_polygon('03204', 'Spain');
NOTICE: cdb_dataservices_client._cdb_geocode_postalcode_polygon(4): [contrib_regression] REMOTE NOTICE: cdb_dataservices_server.cdb_geocode_postalcode_polygon invoked with params (test_user, <NULL>, 03204, Spain)
cdb_geocode_postalcode_polygon
@@ -31,3 +54,10 @@ NOTICE: cdb_dataservices_client._cdb_geocode_postalcode_point(4): [contrib_regr
(1 row)
-- Remove permissions
SELECT CDB_Conf_RemoveConf('api_keys_postgres');
cdb_conf_removeconf
---------------------
(1 row)

View File

@@ -9,7 +9,26 @@ BEGIN
RETURN NULL;
END;
$$ LANGUAGE 'plpgsql';
-- Exercise the public and the proxied function
-- -- Exercise the public and the proxied function
-- No permissions granted
SELECT cdb_geocode_ipaddress_point('8.8.8.8');
ERROR: Geocoding permission denied
-- Grant other permissions but geocoding
SELECT CDB_Conf_SetConf('api_keys_postgres', '{"username": "test_user", "permissions": ["routing", "isolines"]}');
cdb_conf_setconf
------------------
(1 row)
SELECT cdb_geocode_ipaddress_point('8.8.8.8');
ERROR: Geocoding permission denied
-- Grant geocoding permissions
SELECT CDB_Conf_SetConf('api_keys_postgres', '{"username": "test_user", "permissions": ["geocoding"]}');
cdb_conf_setconf
------------------
(1 row)
SELECT cdb_geocode_ipaddress_point('8.8.8.8');
NOTICE: cdb_dataservices_client._cdb_geocode_ipaddress_point(3): [contrib_regression] REMOTE NOTICE: cdb_dataservices_server.cdb_geocode_ipaddress_point invoked with params (test_user, <NULL>, 8.8.8.8)
cdb_geocode_ipaddress_point
@@ -17,3 +36,10 @@ NOTICE: cdb_dataservices_client._cdb_geocode_ipaddress_point(3): [contrib_regre
(1 row)
-- Remove permissions
SELECT CDB_Conf_RemoveConf('api_keys_postgres');
cdb_conf_removeconf
---------------------
(1 row)

View File

@@ -9,7 +9,62 @@ BEGIN
RETURN NULL;
END;
$$ LANGUAGE 'plpgsql';
-- Exercise the public and the proxied function
-- -- Exercise the public and the proxied function
-- No permissions granted
SELECT cdb_geocode_street_point('One street, 1');
ERROR: Geocoding permission denied
SELECT cdb_geocode_street_point('One street', 'city');
ERROR: Geocoding permission denied
SELECT cdb_geocode_street_point('One street', 'city', 'state');
ERROR: Geocoding permission denied
SELECT cdb_geocode_street_point('One street', 'city', 'state', 'country');
ERROR: Geocoding permission denied
SELECT cdb_geocode_street_point('One street', 'city', NULL, 'country');
ERROR: Geocoding permission denied
SELECT cdb_geocode_street_point('One street, 1');
ERROR: Geocoding permission denied
SELECT cdb_geocode_street_point('One street', 'city');
ERROR: Geocoding permission denied
SELECT cdb_geocode_street_point('One street', 'city', 'state');
ERROR: Geocoding permission denied
SELECT cdb_geocode_street_point('One street', 'city', 'state', 'country');
ERROR: Geocoding permission denied
SELECT cdb_geocode_street_point('One street', 'city', NULL, 'country');
ERROR: Geocoding permission denied
-- Grant other permissions but geocoding
SELECT CDB_Conf_SetConf('api_keys_postgres', '{"username": "test_user", "permissions": ["routing", "isolines"]}');
cdb_conf_setconf
------------------
(1 row)
SELECT cdb_geocode_street_point('One street, 1');
ERROR: Geocoding permission denied
SELECT cdb_geocode_street_point('One street', 'city');
ERROR: Geocoding permission denied
SELECT cdb_geocode_street_point('One street', 'city', 'state');
ERROR: Geocoding permission denied
SELECT cdb_geocode_street_point('One street', 'city', 'state', 'country');
ERROR: Geocoding permission denied
SELECT cdb_geocode_street_point('One street', 'city', NULL, 'country');
ERROR: Geocoding permission denied
SELECT cdb_geocode_street_point('One street, 1');
ERROR: Geocoding permission denied
SELECT cdb_geocode_street_point('One street', 'city');
ERROR: Geocoding permission denied
SELECT cdb_geocode_street_point('One street', 'city', 'state');
ERROR: Geocoding permission denied
SELECT cdb_geocode_street_point('One street', 'city', 'state', 'country');
ERROR: Geocoding permission denied
SELECT cdb_geocode_street_point('One street', 'city', NULL, 'country');
ERROR: Geocoding permission denied
-- Grant geocoding permissions
SELECT CDB_Conf_SetConf('api_keys_postgres', '{"username": "test_user", "permissions": ["geocoding"]}');
cdb_conf_setconf
------------------
(1 row)
SELECT cdb_geocode_street_point('One street, 1');
NOTICE: cdb_dataservices_client._cdb_geocode_street_point(6): [contrib_regression] REMOTE NOTICE: cdb_dataservices_server.cdb_geocode_geocoder_street_point invoked with params (test_user, <NULL>, One street, 1, <NULL>, <NULL>, <NULL>)
cdb_geocode_street_point
@@ -80,3 +135,10 @@ NOTICE: cdb_dataservices_client._cdb_geocode_street_point(6): [contrib_regressi
(1 row)
-- Remove permissions
SELECT CDB_Conf_RemoveConf('api_keys_postgres');
cdb_conf_removeconf
---------------------
(1 row)

View File

@@ -22,7 +22,46 @@ BEGIN
RETURN ret;
END;
$$ LANGUAGE 'plpgsql';
-- Exercise the public and the proxied functions
-- -- Exercise the public and the proxied function
-- No permissions granted
SELECT cdb_route_point_to_point('POINT(-87.81406 41.89308)'::geometry,'POINT(-87.79209 41.86138)'::geometry, 'car');
ERROR: Routing permission denied
SELECT cdb_route_point_to_point('POINT(-87.81406 41.89308)'::geometry,'POINT(-87.79209 41.86138)'::geometry, 'car', ARRAY['mode_type=shortest']::text[]);
ERROR: Routing permission denied
SELECT cdb_route_point_to_point('POINT(-87.81406 41.89308)'::geometry,'POINT(-87.79209 41.86138)'::geometry, 'car', ARRAY[]::text[], 'miles');
ERROR: Routing permission denied
SELECT cdb_route_with_waypoints(Array['POINT(-87.81406 41.89308)'::geometry,'POINT(-87.80406 41.87308)'::geometry,'POINT(-87.79209 41.86138)'::geometry], 'car');
ERROR: Routing permission denied
SELECT cdb_route_with_waypoints(Array['POINT(-87.81406 41.89308)'::geometry,'POINT(-87.80406 41.87308)'::geometry,'POINT(-87.79209 41.86138)'::geometry], 'car', ARRAY['mode_type=shortest']::text[]);
ERROR: Routing permission denied
SELECT cdb_route_with_waypoints(Array['POINT(-87.81406 41.89308)'::geometry,'POINT(-87.80406 41.87308)'::geometry,'POINT(-87.79209 41.86138)'::geometry], 'car', ARRAY[]::text[], 'miles');
ERROR: Routing permission denied
-- Grant other permissions but routing
SELECT CDB_Conf_SetConf('api_keys_postgres', '{"username": "test_user", "permissions": ["geocoding", "isolines"]}');
cdb_conf_setconf
------------------
(1 row)
SELECT cdb_route_point_to_point('POINT(-87.81406 41.89308)'::geometry,'POINT(-87.79209 41.86138)'::geometry, 'car');
ERROR: Routing permission denied
SELECT cdb_route_point_to_point('POINT(-87.81406 41.89308)'::geometry,'POINT(-87.79209 41.86138)'::geometry, 'car', ARRAY['mode_type=shortest']::text[]);
ERROR: Routing permission denied
SELECT cdb_route_point_to_point('POINT(-87.81406 41.89308)'::geometry,'POINT(-87.79209 41.86138)'::geometry, 'car', ARRAY[]::text[], 'miles');
ERROR: Routing permission denied
SELECT cdb_route_with_waypoints(Array['POINT(-87.81406 41.89308)'::geometry,'POINT(-87.80406 41.87308)'::geometry,'POINT(-87.79209 41.86138)'::geometry], 'car');
ERROR: Routing permission denied
SELECT cdb_route_with_waypoints(Array['POINT(-87.81406 41.89308)'::geometry,'POINT(-87.80406 41.87308)'::geometry,'POINT(-87.79209 41.86138)'::geometry], 'car', ARRAY['mode_type=shortest']::text[]);
ERROR: Routing permission denied
SELECT cdb_route_with_waypoints(Array['POINT(-87.81406 41.89308)'::geometry,'POINT(-87.80406 41.87308)'::geometry,'POINT(-87.79209 41.86138)'::geometry], 'car', ARRAY[]::text[], 'miles');
ERROR: Routing permission denied
-- Grant routing permissions
SELECT CDB_Conf_SetConf('api_keys_postgres', '{"username": "test_user", "permissions": ["routing"]}');
cdb_conf_setconf
------------------
(1 row)
SELECT cdb_route_point_to_point('POINT(-87.81406 41.89308)'::geometry,'POINT(-87.79209 41.86138)'::geometry, 'car');
NOTICE: cdb_dataservices_client._cdb_route_point_to_point(7): [contrib_regression] REMOTE NOTICE: cdb_dataservices_server.cdb_route_point_to_point invoked with params (test_user, <NULL>, 0101000000D53E1D8F19F455C0185B087250F24440, 0101000000465F419AB1F255C0D8B628B341EE4440, car, {}, kilometers)
cdb_route_point_to_point
@@ -65,3 +104,10 @@ NOTICE: cdb_dataservices_client._cdb_route_with_waypoints(6): [contrib_regressi
(,2.22,500)
(1 row)
-- Remove permissions
SELECT CDB_Conf_RemoveConf('api_keys_postgres');
cdb_conf_removeconf
---------------------
(1 row)

View File

@@ -202,7 +202,114 @@ BEGIN
RETURN QUERY SELECT true AS valid, ARRAY[]::TEXT[] AS errors;
END;
$$ LANGUAGE 'plpgsql';
-- Exercise the public and the proxied function
-- -- Exercise the public and the proxied function
-- No permissions granted
SELECT obs_get_demographic_snapshot(ST_SetSRID(ST_Point(-73.936669 , 40.704512), 4326), '2009 - 2013'::text, '"us.census.tiger".block_group'::text);
ERROR: Data Observatory permission denied
SELECT obs_get_segment_snapshot(ST_SetSRID(ST_Point(-73.936669 , 40.704512), 4326), '"us.census.tiger".block_group'::text);
ERROR: Data Observatory permission denied
SELECT obs_getdemographicsnapshot(ST_SetSRID(ST_Point(-73.936669 , 40.704512), 4326), '2009 - 2013', '"us.census.tiger".block_group'::text);
ERROR: Data Observatory permission denied
SELECT obs_getsegmentsnapshot(ST_SetSRID(ST_Point(-73.936669 , 40.704512), 4326), '"us.census.tiger".block_group'::text);
ERROR: Data Observatory permission denied
SELECT obs_getboundary(ST_SetSRID(ST_Point(-73.936669 , 40.704512), 4326), 'us.census.tiger.census_tract'::text);
ERROR: Data Observatory permission denied
SELECT obs_getboundaryid(ST_SetSRID(ST_Point(-73.936669 , 40.704512), 4326), 'us.census.tiger.census_tract'::text);
ERROR: Data Observatory permission denied
SELECT obs_getboundarybyid('36047'::text, 'us.census.tiger.county'::text);
ERROR: Data Observatory permission denied
SELECT obs_getboundariesbygeometry(ST_MakeEnvelope(-73.9452409744, 40.6988851644, -73.9280319214, 40.7101254524, 4326), 'us.census.tiger.census_tract'::text);
ERROR: Data Observatory permission denied
SELECT obs_getboundariesbypointandradius(ST_SetSRID(ST_Point(-73.936669 , 40.704512), 4326), 500, 'us.census.tiger.census_tract'::text);
ERROR: Data Observatory permission denied
SELECT obs_getpointsbygeometry(ST_MakeEnvelope(-73.9452409744, 40.6988851644, -73.9280319214, 40.7101254524, 4326), 'us.census.tiger.census_tract'::text);
ERROR: Data Observatory permission denied
SELECT obs_getpointsbypointandradius(ST_SetSRID(ST_Point(-73.936669 , 40.704512), 4326), 500::numeric, 'us.census.tiger.census_tract'::text);
ERROR: Data Observatory permission denied
SELECT obs_getmeasure(ST_SetSRID(ST_Point(-73.936669 , 40.704512), 4326), 'us.census.acs.B01001001'::text);
ERROR: Data Observatory permission denied
SELECT obs_getmeasurebyid('36047'::text, 'us.census.acs.B01001001'::text, 'us.census.tiger.county'::text);
ERROR: Data Observatory permission denied
SELECT obs_getcategory(ST_SetSRID(ST_Point(-73.936669 , 40.704512), 4326), 'us.census.spielman_singleton_segments.X10'::text);
ERROR: Data Observatory permission denied
SELECT obs_getuscensusmeasure(ST_SetSRID(ST_Point(-73.936669 , 40.704512), 4326), 'male population'::text);
ERROR: Data Observatory permission denied
SELECT obs_getuscensuscategory(ST_SetSRID(ST_Point(-73.936669 , 40.704512), 4326), 'Spielman-Singleton Segments: 10 Clusters'::text);
ERROR: Data Observatory permission denied
SELECT obs_getpopulation(ST_SetSRID(ST_Point(-73.936669 , 40.704512), 4326));
ERROR: Data Observatory permission denied
SELECT obs_search('total_pop'::text);
ERROR: Data Observatory permission denied
SELECT obs_getavailableboundaries(ST_SetSRID(ST_Point(-73.936669 , 40.704512), 4326));
ERROR: Data Observatory permission denied
SELECT obs_getmeta(ST_SetSRID(ST_Point(-73.9, 40.7), 4326), '[{"numer_id": "us.census.acs.B01003001"}]', 1, 1, 1000);
ERROR: Data Observatory permission denied
SELECT obs_getdata(ARRAY['36047'], obs_getmeta(st_setsrid(st_point(-73.9, 40.7), 4326), '[{"numer_id": "us.census.acs.B01003001", "geom_id": "us.census.tiger.county"}]', 1, 1, 1000));
ERROR: Data Observatory permission denied
SELECT obs_getdata(ARRAY[(ST_SetSRID(ST_Point(-73.9, 40.7), 4326), 1)::geomval], obs_getmeta(st_setsrid(st_point(-73.9, 40.7), 4326), '[{"numer_id": "us.census.acs.B01003001"}]'));
ERROR: Data Observatory permission denied
SELECT obs_metadatavalidation(ST_SetSRID(ST_Point(-73.9, 40.7), 4326), 'ST_Polygon', '[{"numer_id": "us.census.acs.B01003001"}]', 1000);
ERROR: Data Observatory permission denied
-- Grant other permissions but DO
SELECT CDB_Conf_SetConf('api_keys_postgres', '{"username": "test_user", "permissions": ["routing", "isolines"]}');
cdb_conf_setconf
------------------
(1 row)
SELECT obs_get_demographic_snapshot(ST_SetSRID(ST_Point(-73.936669 , 40.704512), 4326), '2009 - 2013'::text, '"us.census.tiger".block_group'::text);
ERROR: Data Observatory permission denied
SELECT obs_get_segment_snapshot(ST_SetSRID(ST_Point(-73.936669 , 40.704512), 4326), '"us.census.tiger".block_group'::text);
ERROR: Data Observatory permission denied
SELECT obs_getdemographicsnapshot(ST_SetSRID(ST_Point(-73.936669 , 40.704512), 4326), '2009 - 2013', '"us.census.tiger".block_group'::text);
ERROR: Data Observatory permission denied
SELECT obs_getsegmentsnapshot(ST_SetSRID(ST_Point(-73.936669 , 40.704512), 4326), '"us.census.tiger".block_group'::text);
ERROR: Data Observatory permission denied
SELECT obs_getboundary(ST_SetSRID(ST_Point(-73.936669 , 40.704512), 4326), 'us.census.tiger.census_tract'::text);
ERROR: Data Observatory permission denied
SELECT obs_getboundaryid(ST_SetSRID(ST_Point(-73.936669 , 40.704512), 4326), 'us.census.tiger.census_tract'::text);
ERROR: Data Observatory permission denied
SELECT obs_getboundarybyid('36047'::text, 'us.census.tiger.county'::text);
ERROR: Data Observatory permission denied
SELECT obs_getboundariesbygeometry(ST_MakeEnvelope(-73.9452409744, 40.6988851644, -73.9280319214, 40.7101254524, 4326), 'us.census.tiger.census_tract'::text);
ERROR: Data Observatory permission denied
SELECT obs_getboundariesbypointandradius(ST_SetSRID(ST_Point(-73.936669 , 40.704512), 4326), 500, 'us.census.tiger.census_tract'::text);
ERROR: Data Observatory permission denied
SELECT obs_getpointsbygeometry(ST_MakeEnvelope(-73.9452409744, 40.6988851644, -73.9280319214, 40.7101254524, 4326), 'us.census.tiger.census_tract'::text);
ERROR: Data Observatory permission denied
SELECT obs_getpointsbypointandradius(ST_SetSRID(ST_Point(-73.936669 , 40.704512), 4326), 500::numeric, 'us.census.tiger.census_tract'::text);
ERROR: Data Observatory permission denied
SELECT obs_getmeasure(ST_SetSRID(ST_Point(-73.936669 , 40.704512), 4326), 'us.census.acs.B01001001'::text);
ERROR: Data Observatory permission denied
SELECT obs_getmeasurebyid('36047'::text, 'us.census.acs.B01001001'::text, 'us.census.tiger.county'::text);
ERROR: Data Observatory permission denied
SELECT obs_getcategory(ST_SetSRID(ST_Point(-73.936669 , 40.704512), 4326), 'us.census.spielman_singleton_segments.X10'::text);
ERROR: Data Observatory permission denied
SELECT obs_getuscensusmeasure(ST_SetSRID(ST_Point(-73.936669 , 40.704512), 4326), 'male population'::text);
ERROR: Data Observatory permission denied
SELECT obs_getuscensuscategory(ST_SetSRID(ST_Point(-73.936669 , 40.704512), 4326), 'Spielman-Singleton Segments: 10 Clusters'::text);
ERROR: Data Observatory permission denied
SELECT obs_getpopulation(ST_SetSRID(ST_Point(-73.936669 , 40.704512), 4326));
ERROR: Data Observatory permission denied
SELECT obs_search('total_pop'::text);
ERROR: Data Observatory permission denied
SELECT obs_getavailableboundaries(ST_SetSRID(ST_Point(-73.936669 , 40.704512), 4326));
ERROR: Data Observatory permission denied
SELECT obs_getmeta(ST_SetSRID(ST_Point(-73.9, 40.7), 4326), '[{"numer_id": "us.census.acs.B01003001"}]', 1, 1, 1000);
ERROR: Data Observatory permission denied
SELECT obs_getdata(ARRAY['36047'], obs_getmeta(st_setsrid(st_point(-73.9, 40.7), 4326), '[{"numer_id": "us.census.acs.B01003001", "geom_id": "us.census.tiger.county"}]', 1, 1, 1000));
ERROR: Data Observatory permission denied
SELECT obs_getdata(ARRAY[(ST_SetSRID(ST_Point(-73.9, 40.7), 4326), 1)::geomval], obs_getmeta(st_setsrid(st_point(-73.9, 40.7), 4326), '[{"numer_id": "us.census.acs.B01003001"}]'));
ERROR: Data Observatory permission denied
SELECT obs_metadatavalidation(ST_SetSRID(ST_Point(-73.9, 40.7), 4326), 'ST_Polygon', '[{"numer_id": "us.census.acs.B01003001"}]', 1000);
ERROR: Data Observatory permission denied
-- Grant DO permissions
SELECT CDB_Conf_SetConf('api_keys_postgres', '{"username": "test_user", "permissions": ["observatory"]}');
cdb_conf_setconf
------------------
(1 row)
SELECT obs_get_demographic_snapshot(ST_SetSRID(ST_Point(-73.936669 , 40.704512), 4326), '2009 - 2013'::text, '"us.census.tiger".block_group'::text);
NOTICE: cdb_dataservices_client._obs_get_demographic_snapshot(5): [contrib_regression] REMOTE NOTICE: cdb_dataservices_server.obs_get_demographic_snapshot invoked with params (test_user, <NULL>, 0101000020E6100000548B8862F27B52C0DDD1FF722D5A4440, 2009 - 2013, "us.census.tiger".block_group)
obs_get_demographic_snapshot
@@ -366,3 +473,9 @@ NOTICE: cdb_dataservices_client._obs_metadatavalidation(6): [contrib_regression
(t,{})
(1 row)
SELECT CDB_Conf_RemoveConf('api_keys_postgres');
cdb_conf_removeconf
---------------------
(1 row)

View File

@@ -27,6 +27,12 @@ BEGIN
RETURN true;
END;
$$ LANGUAGE 'plpgsql';
SELECT CDB_Conf_SetConf('api_keys_postgres', '{"username": "test_user", "permissions": [""]}');
cdb_conf_setconf
------------------
(1 row)
-- Create a sample user table
CREATE TABLE user_table (cartodb_id int, the_geom geometry);
INSERT INTO user_table(cartodb_id, the_geom) VALUES (1, '0101000020E6100000F74FC902E07D52C05FE24CC7654B4440');
@@ -63,3 +69,9 @@ SELECT * FROM my_table_dst;
-- Clean tables
DROP TABLE my_table_dst;
SELECT CDB_Conf_RemoveConf('api_keys_postgres');
cdb_conf_removeconf
---------------------
(1 row)

View File

@@ -3,8 +3,94 @@
SET ROLE test_regular_user;
-- Add to the search path the schema
SET search_path TO public,cartodb,cdb_dataservices_client;
-- Exercise the public function
-- it is public, it shall work
-- Check the regular user has no permissions on private functions
SELECT _cdb_geocode_admin0_polygon('evil_user', 'evil_orgname', 'Hell');
ERROR: permission denied for function _cdb_geocode_admin0_polygon
SELECT _cdb_geocode_admin1_polygon('evil_user', 'evil_orgname', 'Hell');
ERROR: permission denied for function _cdb_geocode_admin1_polygon
SELECT _cdb_geocode_admin1_polygon('evil_user', 'evil_orgname', 'Sheol', 'Hell');
ERROR: permission denied for function _cdb_geocode_admin1_polygon
SELECT _cdb_geocode_namedplace_point('evil_user', 'evil_orgname', 'Sheol');
ERROR: permission denied for function _cdb_geocode_namedplace_point
SELECT _cdb_geocode_namedplace_point('evil_user', 'evil_orgname', 'Sheol', 'Hell');
ERROR: permission denied for function _cdb_geocode_namedplace_point
SELECT _cdb_geocode_namedplace_point('evil_user', 'evil_orgname', 'Sheol', 'Hell', 'Ugly world');
ERROR: permission denied for function _cdb_geocode_namedplace_point
SELECT _cdb_geocode_postalcode_polygon('evil_user', 'evil_orgname', '66666', 'Hell');
ERROR: permission denied for function _cdb_geocode_postalcode_polygon
SELECT _cdb_geocode_postalcode_point('evil_user', 'evil_orgname', '66666', 'Hell');
ERROR: permission denied for function _cdb_geocode_postalcode_point
SELECT _cdb_geocode_ipaddress_point('evil_user', 'evil_orgname', '8.8.8.8');
ERROR: permission denied for function _cdb_geocode_ipaddress_point
SELECT _cdb_geocode_street_point('evil_user', 'evil_orgname', 'one street, 1');
ERROR: permission denied for function _cdb_geocode_street_point
SELECT _cdb_route_point_to_point('evil_user', 'evil_orgname', 'POINT(-87.81406 41.89308)'::geometry,'POINT(-87.79209 41.86138)'::geometry, 'car');
ERROR: permission denied for function _cdb_route_point_to_point
-- -- Exercise the public function
-- -- it is public, it shall work
-- No permissions granted
SELECT cdb_geocode_admin0_polygon('Spain');
ERROR: Geocoding permission denied
SELECT cdb_geocode_admin1_polygon('California');
ERROR: Geocoding permission denied
SELECT cdb_geocode_admin1_polygon('California', 'United States');
ERROR: Geocoding permission denied
SELECT cdb_geocode_namedplace_point('Elx');
ERROR: Geocoding permission denied
SELECT cdb_geocode_namedplace_point('Elx', 'Valencia');
ERROR: Geocoding permission denied
SELECT cdb_geocode_namedplace_point('Elx', 'Valencia', 'Spain');
ERROR: Geocoding permission denied
SELECT cdb_geocode_postalcode_polygon('03204', 'Spain');
ERROR: Geocoding permission denied
SELECT cdb_geocode_postalcode_point('03204', 'Spain');
ERROR: Geocoding permission denied
SELECT cdb_geocode_ipaddress_point('8.8.8.8');
ERROR: Geocoding permission denied
SELECT cdb_geocode_street_point('one street, 1');
ERROR: Geocoding permission denied
SELECT cdb_route_point_to_point('POINT(-87.81406 41.89308)'::geometry,'POINT(-87.79209 41.86138)'::geometry, 'car');
ERROR: Routing permission denied
-- Grant other permissions but geocoding and routing
SET ROLE postgres;
SELECT CDB_Conf_SetConf('api_keys_postgres', '{"username": "test_user", "permissions": ["isolines"]}');
cdb_conf_setconf
------------------
(1 row)
SET ROLE test_regular_user; -- Use regular user role
SELECT cdb_geocode_admin0_polygon('Spain');
ERROR: Geocoding permission denied
SELECT cdb_geocode_admin1_polygon('California');
ERROR: Geocoding permission denied
SELECT cdb_geocode_admin1_polygon('California', 'United States');
ERROR: Geocoding permission denied
SELECT cdb_geocode_namedplace_point('Elx');
ERROR: Geocoding permission denied
SELECT cdb_geocode_namedplace_point('Elx', 'Valencia');
ERROR: Geocoding permission denied
SELECT cdb_geocode_namedplace_point('Elx', 'Valencia', 'Spain');
ERROR: Geocoding permission denied
SELECT cdb_geocode_postalcode_polygon('03204', 'Spain');
ERROR: Geocoding permission denied
SELECT cdb_geocode_postalcode_point('03204', 'Spain');
ERROR: Geocoding permission denied
SELECT cdb_geocode_ipaddress_point('8.8.8.8');
ERROR: Geocoding permission denied
SELECT cdb_geocode_street_point('one street, 1');
ERROR: Geocoding permission denied
SELECT cdb_route_point_to_point('POINT(-87.81406 41.89308)'::geometry,'POINT(-87.79209 41.86138)'::geometry, 'car');
ERROR: Routing permission denied
-- Grant geocoding permissions
SET ROLE postgres;
SELECT CDB_Conf_SetConf('api_keys_postgres', '{"username": "test_user", "permissions": ["geocoding", "routing"]}');
cdb_conf_setconf
------------------
(1 row)
SET ROLE test_regular_user; -- Use regular user role
SELECT cdb_geocode_admin0_polygon('Spain');
NOTICE: cdb_dataservices_client._cdb_geocode_admin0_polygon(3): [contrib_regression] REMOTE NOTICE: cdb_dataservices_server.cdb_geocode_admin0_polygon invoked with params (test_user, <NULL>, Spain)
cdb_geocode_admin0_polygon
@@ -82,26 +168,11 @@ NOTICE: cdb_dataservices_client._cdb_route_point_to_point(7): [contrib_regressi
(,5.33,100)
(1 row)
-- Check the regular user has no permissions on private functions
SELECT _cdb_geocode_admin0_polygon('evil_user', 'evil_orgname', 'Hell');
ERROR: permission denied for function _cdb_geocode_admin0_polygon
SELECT _cdb_geocode_admin1_polygon('evil_user', 'evil_orgname', 'Hell');
ERROR: permission denied for function _cdb_geocode_admin1_polygon
SELECT _cdb_geocode_admin1_polygon('evil_user', 'evil_orgname', 'Sheol', 'Hell');
ERROR: permission denied for function _cdb_geocode_admin1_polygon
SELECT _cdb_geocode_namedplace_point('evil_user', 'evil_orgname', 'Sheol');
ERROR: permission denied for function _cdb_geocode_namedplace_point
SELECT _cdb_geocode_namedplace_point('evil_user', 'evil_orgname', 'Sheol', 'Hell');
ERROR: permission denied for function _cdb_geocode_namedplace_point
SELECT _cdb_geocode_namedplace_point('evil_user', 'evil_orgname', 'Sheol', 'Hell', 'Ugly world');
ERROR: permission denied for function _cdb_geocode_namedplace_point
SELECT _cdb_geocode_postalcode_polygon('evil_user', 'evil_orgname', '66666', 'Hell');
ERROR: permission denied for function _cdb_geocode_postalcode_polygon
SELECT _cdb_geocode_postalcode_point('evil_user', 'evil_orgname', '66666', 'Hell');
ERROR: permission denied for function _cdb_geocode_postalcode_point
SELECT _cdb_geocode_ipaddress_point('evil_user', 'evil_orgname', '8.8.8.8');
ERROR: permission denied for function _cdb_geocode_ipaddress_point
SELECT _cdb_geocode_street_point('evil_user', 'evil_orgname', 'one street, 1');
ERROR: permission denied for function _cdb_geocode_street_point
SELECT _cdb_route_point_to_point('evil_user', 'evil_orgname', 'POINT(-87.81406 41.89308)'::geometry,'POINT(-87.79209 41.86138)'::geometry, 'car');
ERROR: permission denied for function _cdb_route_point_to_point
-- Remove permissions
SET ROLE postgres;
SELECT CDB_Conf_RemoveConf('api_keys_postgres');
cdb_conf_removeconf
---------------------
(1 row)

View File

@@ -11,6 +11,18 @@ BEGIN
END;
$$ LANGUAGE 'plpgsql';
-- -- Exercise the public and the proxied function
-- Exercise the public and the proxied function
-- No permissions granted
SELECT cdb_geocode_admin0_polygon('Spain');
-- Grant other permissions but geocoding
SELECT CDB_Conf_SetConf('api_keys_postgres', '{"username": "test_user", "permissions": ["routing", "isolines"]}');
SELECT cdb_geocode_admin0_polygon('Spain');
-- Grant geocoding permissions
SELECT CDB_Conf_SetConf('api_keys_postgres', '{"username": "test_user", "permissions": ["geocoding"]}');
SELECT cdb_geocode_admin0_polygon('Spain');
-- Remove permissions
SELECT CDB_Conf_RemoveConf('api_keys_postgres');

View File

@@ -19,7 +19,21 @@ BEGIN
END;
$$ LANGUAGE 'plpgsql';
-- -- Exercise the public and the proxied function
-- Exercise the public and the proxied function
-- No permissions granted
SELECT cdb_geocode_admin1_polygon('California');
SELECT cdb_geocode_admin1_polygon('California', 'United States');
-- Grant other permissions but geocoding
SELECT CDB_Conf_SetConf('api_keys_postgres', '{"username": "test_user", "permissions": ["routing", "isolines"]}');
SELECT cdb_geocode_admin1_polygon('California');
SELECT cdb_geocode_admin1_polygon('California', 'United States');
-- Grant geocoding permissions
SELECT CDB_Conf_SetConf('api_keys_postgres', '{"username": "test_user", "permissions": ["geocoding"]}');
SELECT cdb_geocode_admin1_polygon('California');
SELECT cdb_geocode_admin1_polygon('California', 'United States');
-- Remove permissions
SELECT CDB_Conf_RemoveConf('api_keys_postgres');

View File

@@ -12,15 +12,49 @@ RETURNS BOOLEAN as $$
SELECT FALSE;
$$ LANGUAGE SQL;
ALTER FUNCTION cdb_dataservices_client._cdb_bulk_geocode_street_point(searches jsonb) RENAME TO _cdb_bulk_geocode_street_point_mocked;
CREATE FUNCTION cdb_dataservices_client._cdb_bulk_geocode_street_point(searches jsonb)
RETURNS SETOF cdb_dataservices_client.geocoding AS $$
BEGIN
RAISE NOTICE 'called with this searches: %', searches;
END;
$$ LANGUAGE 'plpgsql' SECURITY DEFINER STABLE PARALLEL UNSAFE SET search_path = pg_temp;
-- No permissions granted
-- Test bulk size not mandatory (it will get the optimal)
SELECT cdb_dataservices_client.cdb_bulk_geocode_street_point('select 1 as cartodb_id', '''Valladolid, Spain''', null, null, null, null);
-- Test quota check by mocking quota 0
SELECT cdb_dataservices_client.cdb_bulk_geocode_street_point('select 1 as cartodb_id', '''Valladolid, Spain''');
-- Grant other permissions but geocoding
SELECT CDB_Conf_SetConf('api_keys_postgres', '{"username": "test_user", "permissions": ["routing", "isolines"]}');
-- Test bulk size not mandatory (it will get the optimal)
SELECT cdb_dataservices_client.cdb_bulk_geocode_street_point('select 1 as cartodb_id', '''Valladolid, Spain''', null, null, null, null);
-- Test quota check by mocking quota 0
SELECT cdb_dataservices_client.cdb_bulk_geocode_street_point('select 1 as cartodb_id', '''Valladolid, Spain''');
-- Grant geocoding permissions
SELECT CDB_Conf_SetConf('api_keys_postgres', '{"username": "test_user", "permissions": ["geocoding"]}');
-- Test bulk size not mandatory (it will get the optimal)
SELECT cdb_dataservices_client.cdb_bulk_geocode_street_point('select 1 as cartodb_id', '''Valladolid, Spain''', null, null, null, null);
-- Test quota check by mocking quota 0
SELECT cdb_dataservices_client.cdb_bulk_geocode_street_point('select 1 as cartodb_id', '''Valladolid, Spain''');
-- Check that when cdb_enough_quota returns true (ie. when soft_limit is set to true, even if not enough quota)
-- it is able to proceed with the bulk geocode
CREATE OR REPLACE FUNCTION cdb_dataservices_client.cdb_enough_quota (service TEXT ,input_size NUMERIC)
RETURNS BOOLEAN as $$
SELECT TRUE;
$$ LANGUAGE SQL;
SELECT cdb_dataservices_client.cdb_bulk_geocode_street_point('select 1 as cartodb_id', '''Valladolid, Spain''');
-- Remove permissions
SELECT CDB_Conf_RemoveConf('api_keys_postgres');
DROP FUNCTION cdb_dataservices_client.cdb_service_quota_info_batch;
DROP FUNCTION cdb_dataservices_client.cdb_enough_quota;
DROP FUNCTION cdb_dataservices_client._cdb_bulk_geocode_street_point;
ALTER FUNCTION cdb_dataservices_client.cdb_enough_quota_mocked (service TEXT ,input_size NUMERIC) RENAME TO cdb_enough_quota;
ALTER FUNCTION cdb_dataservices_client.cdb_service_quota_info_batch_mocked() RENAME TO cdb_service_quota_info_batch;
ALTER FUNCTION cdb_dataservices_client._cdb_bulk_geocode_street_point_mocked(searches jsonb) RENAME TO _cdb_bulk_geocode_street_point;

View File

@@ -32,11 +32,30 @@ END;
$$ LANGUAGE 'plpgsql';
-- Use regular user role
SET ROLE test_regular_user;
-- Exercise the exception safe and the proxied functions
-- No permissions granted
SET ROLE test_regular_user; -- Use regular user role
SELECT _cdb_geocode_street_point_exception_safe('One street, 1');
SELECT * FROM _cdb_isodistance_exception_safe('POINT(-3.70568 40.42028)'::geometry, 'walk', ARRAY[300]::integer[]);
SELECT * FROM _cdb_route_point_to_point_exception_safe('POINT(-3.70237112 40.41706163)'::geometry,'POINT(-3.69909883 40.41236875)'::geometry, 'car', ARRAY['mode_type=shortest']::text[]);
-- No permissions granted but conf created
SET ROLE postgres;
SELECT CDB_Conf_SetConf('api_keys_postgres', '{"username": "test_user", "permissions": []}');
SET ROLE test_regular_user; -- Use regular user role
SELECT _cdb_geocode_street_point_exception_safe('One street, 1');
SELECT * FROM _cdb_isodistance_exception_safe('POINT(-3.70568 40.42028)'::geometry, 'walk', ARRAY[300]::integer[]);
SELECT * FROM _cdb_route_point_to_point_exception_safe('POINT(-3.70237112 40.41706163)'::geometry,'POINT(-3.69909883 40.41236875)'::geometry, 'car', ARRAY['mode_type=shortest']::text[]);
-- Grant geocoding permissions
SET ROLE postgres;
SELECT CDB_Conf_SetConf('api_keys_postgres', '{"username": "test_user", "permissions": ["geocoding", "routing", "isolines"]}');
SET ROLE test_regular_user; -- Use regular user role
SELECT _cdb_geocode_street_point_exception_safe('One street, 1');
SELECT * FROM _cdb_isodistance_exception_safe('POINT(-3.70568 40.42028)'::geometry, 'walk', ARRAY[300]::integer[]);
SELECT * FROM _cdb_route_point_to_point_exception_safe('POINT(-3.70237112 40.41706163)'::geometry,'POINT(-3.69909883 40.41236875)'::geometry, 'car', ARRAY['mode_type=shortest']::text[]);
-- Remove permissions
SET ROLE postgres;
SELECT CDB_Conf_RemoveConf('api_keys_postgres');

View File

@@ -27,8 +27,24 @@ BEGIN
END;
$$ LANGUAGE 'plpgsql';
-- Exercise the public and the proxied function
-- -- Exercise the public and the proxied function
-- No permissions granted
SELECT cdb_geocode_namedplace_point('Elx');
SELECT cdb_geocode_namedplace_point('Elx', 'Spain');
SELECT cdb_geocode_namedplace_point('Elx', 'Valencia', 'Spain');
-- Grant other permissions but geocoding
SELECT CDB_Conf_SetConf('api_keys_postgres', '{"username": "test_user", "permissions": ["routing", "isolines"]}');
SELECT cdb_geocode_namedplace_point('Elx');
SELECT cdb_geocode_namedplace_point('Elx', 'Spain');
SELECT cdb_geocode_namedplace_point('Elx', 'Valencia', 'Spain');
-- Grant geocoding permissions
SELECT CDB_Conf_SetConf('api_keys_postgres', '{"username": "test_user", "permissions": ["geocoding"]}');
SELECT cdb_geocode_namedplace_point('Elx');
SELECT cdb_geocode_namedplace_point('Elx', 'Spain');
SELECT cdb_geocode_namedplace_point('Elx', 'Valencia', 'Spain');
-- Remove permissions
SELECT CDB_Conf_RemoveConf('api_keys_postgres');

View File

@@ -19,6 +19,21 @@ BEGIN
END;
$$ LANGUAGE 'plpgsql';
-- Exercise the public and the proxied function
-- -- Exercise the public and the proxied function
-- No permissions granted
SELECT cdb_geocode_postalcode_polygon('03204', 'Spain');
SELECT cdb_geocode_postalcode_point('03204', 'Spain');
-- Grant other permissions but geocoding
SELECT CDB_Conf_SetConf('api_keys_postgres', '{"username": "test_user", "permissions": ["routing", "isolines"]}');
SELECT cdb_geocode_postalcode_polygon('03204', 'Spain');
SELECT cdb_geocode_postalcode_point('03204', 'Spain');
-- Grant geocoding permissions
SELECT CDB_Conf_SetConf('api_keys_postgres', '{"username": "test_user", "permissions": ["geocoding"]}');
SELECT cdb_geocode_postalcode_polygon('03204', 'Spain');
SELECT cdb_geocode_postalcode_point('03204', 'Spain');
-- Remove permissions
SELECT CDB_Conf_RemoveConf('api_keys_postgres');

View File

@@ -12,5 +12,18 @@ END;
$$ LANGUAGE 'plpgsql';
-- Exercise the public and the proxied function
-- -- Exercise the public and the proxied function
-- No permissions granted
SELECT cdb_geocode_ipaddress_point('8.8.8.8');
-- Grant other permissions but geocoding
SELECT CDB_Conf_SetConf('api_keys_postgres', '{"username": "test_user", "permissions": ["routing", "isolines"]}');
SELECT cdb_geocode_ipaddress_point('8.8.8.8');
-- Grant geocoding permissions
SELECT CDB_Conf_SetConf('api_keys_postgres', '{"username": "test_user", "permissions": ["geocoding"]}');
SELECT cdb_geocode_ipaddress_point('8.8.8.8');
-- Remove permissions
SELECT CDB_Conf_RemoveConf('api_keys_postgres');

View File

@@ -12,7 +12,9 @@ END;
$$ LANGUAGE 'plpgsql';
-- Exercise the public and the proxied function
-- -- Exercise the public and the proxied function
-- No permissions granted
SELECT cdb_geocode_street_point('One street, 1');
SELECT cdb_geocode_street_point('One street', 'city');
SELECT cdb_geocode_street_point('One street', 'city', 'state');
@@ -23,3 +25,32 @@ SELECT cdb_geocode_street_point('One street', 'city');
SELECT cdb_geocode_street_point('One street', 'city', 'state');
SELECT cdb_geocode_street_point('One street', 'city', 'state', 'country');
SELECT cdb_geocode_street_point('One street', 'city', NULL, 'country');
-- Grant other permissions but geocoding
SELECT CDB_Conf_SetConf('api_keys_postgres', '{"username": "test_user", "permissions": ["routing", "isolines"]}');
SELECT cdb_geocode_street_point('One street, 1');
SELECT cdb_geocode_street_point('One street', 'city');
SELECT cdb_geocode_street_point('One street', 'city', 'state');
SELECT cdb_geocode_street_point('One street', 'city', 'state', 'country');
SELECT cdb_geocode_street_point('One street', 'city', NULL, 'country');
SELECT cdb_geocode_street_point('One street, 1');
SELECT cdb_geocode_street_point('One street', 'city');
SELECT cdb_geocode_street_point('One street', 'city', 'state');
SELECT cdb_geocode_street_point('One street', 'city', 'state', 'country');
SELECT cdb_geocode_street_point('One street', 'city', NULL, 'country');
-- Grant geocoding permissions
SELECT CDB_Conf_SetConf('api_keys_postgres', '{"username": "test_user", "permissions": ["geocoding"]}');
SELECT cdb_geocode_street_point('One street, 1');
SELECT cdb_geocode_street_point('One street', 'city');
SELECT cdb_geocode_street_point('One street', 'city', 'state');
SELECT cdb_geocode_street_point('One street', 'city', 'state', 'country');
SELECT cdb_geocode_street_point('One street', 'city', NULL, 'country');
SELECT cdb_geocode_street_point('One street, 1');
SELECT cdb_geocode_street_point('One street', 'city');
SELECT cdb_geocode_street_point('One street', 'city', 'state');
SELECT cdb_geocode_street_point('One street', 'city', 'state', 'country');
SELECT cdb_geocode_street_point('One street', 'city', NULL, 'country');
-- Remove permissions
SELECT CDB_Conf_RemoveConf('api_keys_postgres');

View File

@@ -28,12 +28,33 @@ END;
$$ LANGUAGE 'plpgsql';
-- Exercise the public and the proxied functions
-- -- Exercise the public and the proxied function
-- No permissions granted
SELECT cdb_route_point_to_point('POINT(-87.81406 41.89308)'::geometry,'POINT(-87.79209 41.86138)'::geometry, 'car');
SELECT cdb_route_point_to_point('POINT(-87.81406 41.89308)'::geometry,'POINT(-87.79209 41.86138)'::geometry, 'car', ARRAY['mode_type=shortest']::text[]);
SELECT cdb_route_point_to_point('POINT(-87.81406 41.89308)'::geometry,'POINT(-87.79209 41.86138)'::geometry, 'car', ARRAY[]::text[], 'miles');
SELECT cdb_route_with_waypoints(Array['POINT(-87.81406 41.89308)'::geometry,'POINT(-87.80406 41.87308)'::geometry,'POINT(-87.79209 41.86138)'::geometry], 'car');
SELECT cdb_route_with_waypoints(Array['POINT(-87.81406 41.89308)'::geometry,'POINT(-87.80406 41.87308)'::geometry,'POINT(-87.79209 41.86138)'::geometry], 'car', ARRAY['mode_type=shortest']::text[]);
SELECT cdb_route_with_waypoints(Array['POINT(-87.81406 41.89308)'::geometry,'POINT(-87.80406 41.87308)'::geometry,'POINT(-87.79209 41.86138)'::geometry], 'car', ARRAY[]::text[], 'miles');
-- Grant other permissions but routing
SELECT CDB_Conf_SetConf('api_keys_postgres', '{"username": "test_user", "permissions": ["geocoding", "isolines"]}');
SELECT cdb_route_point_to_point('POINT(-87.81406 41.89308)'::geometry,'POINT(-87.79209 41.86138)'::geometry, 'car');
SELECT cdb_route_point_to_point('POINT(-87.81406 41.89308)'::geometry,'POINT(-87.79209 41.86138)'::geometry, 'car', ARRAY['mode_type=shortest']::text[]);
SELECT cdb_route_point_to_point('POINT(-87.81406 41.89308)'::geometry,'POINT(-87.79209 41.86138)'::geometry, 'car', ARRAY[]::text[], 'miles');
SELECT cdb_route_with_waypoints(Array['POINT(-87.81406 41.89308)'::geometry,'POINT(-87.80406 41.87308)'::geometry,'POINT(-87.79209 41.86138)'::geometry], 'car');
SELECT cdb_route_with_waypoints(Array['POINT(-87.81406 41.89308)'::geometry,'POINT(-87.80406 41.87308)'::geometry,'POINT(-87.79209 41.86138)'::geometry], 'car', ARRAY['mode_type=shortest']::text[]);
SELECT cdb_route_with_waypoints(Array['POINT(-87.81406 41.89308)'::geometry,'POINT(-87.80406 41.87308)'::geometry,'POINT(-87.79209 41.86138)'::geometry], 'car', ARRAY[]::text[], 'miles');
-- Grant routing permissions
SELECT CDB_Conf_SetConf('api_keys_postgres', '{"username": "test_user", "permissions": ["routing"]}');
SELECT cdb_route_point_to_point('POINT(-87.81406 41.89308)'::geometry,'POINT(-87.79209 41.86138)'::geometry, 'car');
SELECT cdb_route_point_to_point('POINT(-87.81406 41.89308)'::geometry,'POINT(-87.79209 41.86138)'::geometry, 'car', ARRAY['mode_type=shortest']::text[]);
SELECT cdb_route_point_to_point('POINT(-87.81406 41.89308)'::geometry,'POINT(-87.79209 41.86138)'::geometry, 'car', ARRAY[]::text[], 'miles');
SELECT cdb_route_with_waypoints(Array['POINT(-87.81406 41.89308)'::geometry,'POINT(-87.80406 41.87308)'::geometry,'POINT(-87.79209 41.86138)'::geometry], 'car');
SELECT cdb_route_with_waypoints(Array['POINT(-87.81406 41.89308)'::geometry,'POINT(-87.80406 41.87308)'::geometry,'POINT(-87.79209 41.86138)'::geometry], 'car', ARRAY['mode_type=shortest']::text[]);
SELECT cdb_route_with_waypoints(Array['POINT(-87.81406 41.89308)'::geometry,'POINT(-87.80406 41.87308)'::geometry,'POINT(-87.79209 41.86138)'::geometry], 'car', ARRAY[]::text[], 'miles');
-- Remove permissions
SELECT CDB_Conf_RemoveConf('api_keys_postgres');

View File

@@ -227,7 +227,9 @@ BEGIN
END;
$$ LANGUAGE 'plpgsql';
-- Exercise the public and the proxied function
-- -- Exercise the public and the proxied function
-- No permissions granted
SELECT obs_get_demographic_snapshot(ST_SetSRID(ST_Point(-73.936669 , 40.704512), 4326), '2009 - 2013'::text, '"us.census.tiger".block_group'::text);
SELECT obs_get_segment_snapshot(ST_SetSRID(ST_Point(-73.936669 , 40.704512), 4326), '"us.census.tiger".block_group'::text);
SELECT obs_getdemographicsnapshot(ST_SetSRID(ST_Point(-73.936669 , 40.704512), 4326), '2009 - 2013', '"us.census.tiger".block_group'::text);
@@ -252,3 +254,56 @@ SELECT obs_getdata(ARRAY['36047'], obs_getmeta(st_setsrid(st_point(-73.9, 40.7),
SELECT obs_getdata(ARRAY[(ST_SetSRID(ST_Point(-73.9, 40.7), 4326), 1)::geomval], obs_getmeta(st_setsrid(st_point(-73.9, 40.7), 4326), '[{"numer_id": "us.census.acs.B01003001"}]'));
SELECT obs_metadatavalidation(ST_SetSRID(ST_Point(-73.9, 40.7), 4326), 'ST_Polygon', '[{"numer_id": "us.census.acs.B01003001"}]', 1000);
-- Grant other permissions but DO
SELECT CDB_Conf_SetConf('api_keys_postgres', '{"username": "test_user", "permissions": ["routing", "isolines"]}');
SELECT obs_get_demographic_snapshot(ST_SetSRID(ST_Point(-73.936669 , 40.704512), 4326), '2009 - 2013'::text, '"us.census.tiger".block_group'::text);
SELECT obs_get_segment_snapshot(ST_SetSRID(ST_Point(-73.936669 , 40.704512), 4326), '"us.census.tiger".block_group'::text);
SELECT obs_getdemographicsnapshot(ST_SetSRID(ST_Point(-73.936669 , 40.704512), 4326), '2009 - 2013', '"us.census.tiger".block_group'::text);
SELECT obs_getsegmentsnapshot(ST_SetSRID(ST_Point(-73.936669 , 40.704512), 4326), '"us.census.tiger".block_group'::text);
SELECT obs_getboundary(ST_SetSRID(ST_Point(-73.936669 , 40.704512), 4326), 'us.census.tiger.census_tract'::text);
SELECT obs_getboundaryid(ST_SetSRID(ST_Point(-73.936669 , 40.704512), 4326), 'us.census.tiger.census_tract'::text);
SELECT obs_getboundarybyid('36047'::text, 'us.census.tiger.county'::text);
SELECT obs_getboundariesbygeometry(ST_MakeEnvelope(-73.9452409744, 40.6988851644, -73.9280319214, 40.7101254524, 4326), 'us.census.tiger.census_tract'::text);
SELECT obs_getboundariesbypointandradius(ST_SetSRID(ST_Point(-73.936669 , 40.704512), 4326), 500, 'us.census.tiger.census_tract'::text);
SELECT obs_getpointsbygeometry(ST_MakeEnvelope(-73.9452409744, 40.6988851644, -73.9280319214, 40.7101254524, 4326), 'us.census.tiger.census_tract'::text);
SELECT obs_getpointsbypointandradius(ST_SetSRID(ST_Point(-73.936669 , 40.704512), 4326), 500::numeric, 'us.census.tiger.census_tract'::text);
SELECT obs_getmeasure(ST_SetSRID(ST_Point(-73.936669 , 40.704512), 4326), 'us.census.acs.B01001001'::text);
SELECT obs_getmeasurebyid('36047'::text, 'us.census.acs.B01001001'::text, 'us.census.tiger.county'::text);
SELECT obs_getcategory(ST_SetSRID(ST_Point(-73.936669 , 40.704512), 4326), 'us.census.spielman_singleton_segments.X10'::text);
SELECT obs_getuscensusmeasure(ST_SetSRID(ST_Point(-73.936669 , 40.704512), 4326), 'male population'::text);
SELECT obs_getuscensuscategory(ST_SetSRID(ST_Point(-73.936669 , 40.704512), 4326), 'Spielman-Singleton Segments: 10 Clusters'::text);
SELECT obs_getpopulation(ST_SetSRID(ST_Point(-73.936669 , 40.704512), 4326));
SELECT obs_search('total_pop'::text);
SELECT obs_getavailableboundaries(ST_SetSRID(ST_Point(-73.936669 , 40.704512), 4326));
SELECT obs_getmeta(ST_SetSRID(ST_Point(-73.9, 40.7), 4326), '[{"numer_id": "us.census.acs.B01003001"}]', 1, 1, 1000);
SELECT obs_getdata(ARRAY['36047'], obs_getmeta(st_setsrid(st_point(-73.9, 40.7), 4326), '[{"numer_id": "us.census.acs.B01003001", "geom_id": "us.census.tiger.county"}]', 1, 1, 1000));
SELECT obs_getdata(ARRAY[(ST_SetSRID(ST_Point(-73.9, 40.7), 4326), 1)::geomval], obs_getmeta(st_setsrid(st_point(-73.9, 40.7), 4326), '[{"numer_id": "us.census.acs.B01003001"}]'));
SELECT obs_metadatavalidation(ST_SetSRID(ST_Point(-73.9, 40.7), 4326), 'ST_Polygon', '[{"numer_id": "us.census.acs.B01003001"}]', 1000);
-- Grant DO permissions
SELECT CDB_Conf_SetConf('api_keys_postgres', '{"username": "test_user", "permissions": ["observatory"]}');
SELECT obs_get_demographic_snapshot(ST_SetSRID(ST_Point(-73.936669 , 40.704512), 4326), '2009 - 2013'::text, '"us.census.tiger".block_group'::text);
SELECT obs_get_segment_snapshot(ST_SetSRID(ST_Point(-73.936669 , 40.704512), 4326), '"us.census.tiger".block_group'::text);
SELECT obs_getdemographicsnapshot(ST_SetSRID(ST_Point(-73.936669 , 40.704512), 4326), '2009 - 2013', '"us.census.tiger".block_group'::text);
SELECT obs_getsegmentsnapshot(ST_SetSRID(ST_Point(-73.936669 , 40.704512), 4326), '"us.census.tiger".block_group'::text);
SELECT obs_getboundary(ST_SetSRID(ST_Point(-73.936669 , 40.704512), 4326), 'us.census.tiger.census_tract'::text);
SELECT obs_getboundaryid(ST_SetSRID(ST_Point(-73.936669 , 40.704512), 4326), 'us.census.tiger.census_tract'::text);
SELECT obs_getboundarybyid('36047'::text, 'us.census.tiger.county'::text);
SELECT obs_getboundariesbygeometry(ST_MakeEnvelope(-73.9452409744, 40.6988851644, -73.9280319214, 40.7101254524, 4326), 'us.census.tiger.census_tract'::text);
SELECT obs_getboundariesbypointandradius(ST_SetSRID(ST_Point(-73.936669 , 40.704512), 4326), 500, 'us.census.tiger.census_tract'::text);
SELECT obs_getpointsbygeometry(ST_MakeEnvelope(-73.9452409744, 40.6988851644, -73.9280319214, 40.7101254524, 4326), 'us.census.tiger.census_tract'::text);
SELECT obs_getpointsbypointandradius(ST_SetSRID(ST_Point(-73.936669 , 40.704512), 4326), 500::numeric, 'us.census.tiger.census_tract'::text);
SELECT obs_getmeasure(ST_SetSRID(ST_Point(-73.936669 , 40.704512), 4326), 'us.census.acs.B01001001'::text);
SELECT obs_getmeasurebyid('36047'::text, 'us.census.acs.B01001001'::text, 'us.census.tiger.county'::text);
SELECT obs_getcategory(ST_SetSRID(ST_Point(-73.936669 , 40.704512), 4326), 'us.census.spielman_singleton_segments.X10'::text);
SELECT obs_getuscensusmeasure(ST_SetSRID(ST_Point(-73.936669 , 40.704512), 4326), 'male population'::text);
SELECT obs_getuscensuscategory(ST_SetSRID(ST_Point(-73.936669 , 40.704512), 4326), 'Spielman-Singleton Segments: 10 Clusters'::text);
SELECT obs_getpopulation(ST_SetSRID(ST_Point(-73.936669 , 40.704512), 4326));
SELECT obs_search('total_pop'::text);
SELECT obs_getavailableboundaries(ST_SetSRID(ST_Point(-73.936669 , 40.704512), 4326));
SELECT obs_getmeta(ST_SetSRID(ST_Point(-73.9, 40.7), 4326), '[{"numer_id": "us.census.acs.B01003001"}]', 1, 1, 1000);
SELECT obs_getdata(ARRAY['36047'], obs_getmeta(st_setsrid(st_point(-73.9, 40.7), 4326), '[{"numer_id": "us.census.acs.B01003001", "geom_id": "us.census.tiger.county"}]', 1, 1, 1000));
SELECT obs_getdata(ARRAY[(ST_SetSRID(ST_Point(-73.9, 40.7), 4326), 1)::geomval], obs_getmeta(st_setsrid(st_point(-73.9, 40.7), 4326), '[{"numer_id": "us.census.acs.B01003001"}]'));
SELECT obs_metadatavalidation(ST_SetSRID(ST_Point(-73.9, 40.7), 4326), 'ST_Polygon', '[{"numer_id": "us.census.acs.B01003001"}]', 1000);
SELECT CDB_Conf_RemoveConf('api_keys_postgres');

View File

@@ -34,6 +34,8 @@ BEGIN
END;
$$ LANGUAGE 'plpgsql';
SELECT CDB_Conf_SetConf('api_keys_postgres', '{"username": "test_user", "permissions": [""]}');
-- Create a sample user table
CREATE TABLE user_table (cartodb_id int, the_geom geometry);
INSERT INTO user_table(cartodb_id, the_geom) VALUES (1, '0101000020E6100000F74FC902E07D52C05FE24CC7654B4440');
@@ -53,4 +55,6 @@ SELECT cdb_dataservices_client._DST_PopulateTableOBS_GetMeasure('user_table', 'm
SELECT * FROM my_table_dst;
-- Clean tables
DROP TABLE my_table_dst;
DROP TABLE my_table_dst;
SELECT CDB_Conf_RemoveConf('api_keys_postgres');

View File

@@ -5,20 +5,6 @@ SET ROLE test_regular_user;
-- Add to the search path the schema
SET search_path TO public,cartodb,cdb_dataservices_client;
-- Exercise the public function
-- it is public, it shall work
SELECT cdb_geocode_admin0_polygon('Spain');
SELECT cdb_geocode_admin1_polygon('California');
SELECT cdb_geocode_admin1_polygon('California', 'United States');
SELECT cdb_geocode_namedplace_point('Elx');
SELECT cdb_geocode_namedplace_point('Elx', 'Valencia');
SELECT cdb_geocode_namedplace_point('Elx', 'Valencia', 'Spain');
SELECT cdb_geocode_postalcode_polygon('03204', 'Spain');
SELECT cdb_geocode_postalcode_point('03204', 'Spain');
SELECT cdb_geocode_ipaddress_point('8.8.8.8');
SELECT cdb_geocode_street_point('one street, 1');
SELECT cdb_route_point_to_point('POINT(-87.81406 41.89308)'::geometry,'POINT(-87.79209 41.86138)'::geometry, 'car');
-- Check the regular user has no permissions on private functions
SELECT _cdb_geocode_admin0_polygon('evil_user', 'evil_orgname', 'Hell');
SELECT _cdb_geocode_admin1_polygon('evil_user', 'evil_orgname', 'Hell');
@@ -31,3 +17,54 @@ SELECT _cdb_geocode_postalcode_point('evil_user', 'evil_orgname', '66666', 'Hell
SELECT _cdb_geocode_ipaddress_point('evil_user', 'evil_orgname', '8.8.8.8');
SELECT _cdb_geocode_street_point('evil_user', 'evil_orgname', 'one street, 1');
SELECT _cdb_route_point_to_point('evil_user', 'evil_orgname', 'POINT(-87.81406 41.89308)'::geometry,'POINT(-87.79209 41.86138)'::geometry, 'car');
-- -- Exercise the public function
-- -- it is public, it shall work
-- No permissions granted
SELECT cdb_geocode_admin0_polygon('Spain');
SELECT cdb_geocode_admin1_polygon('California');
SELECT cdb_geocode_admin1_polygon('California', 'United States');
SELECT cdb_geocode_namedplace_point('Elx');
SELECT cdb_geocode_namedplace_point('Elx', 'Valencia');
SELECT cdb_geocode_namedplace_point('Elx', 'Valencia', 'Spain');
SELECT cdb_geocode_postalcode_polygon('03204', 'Spain');
SELECT cdb_geocode_postalcode_point('03204', 'Spain');
SELECT cdb_geocode_ipaddress_point('8.8.8.8');
SELECT cdb_geocode_street_point('one street, 1');
SELECT cdb_route_point_to_point('POINT(-87.81406 41.89308)'::geometry,'POINT(-87.79209 41.86138)'::geometry, 'car');
-- Grant other permissions but geocoding and routing
SET ROLE postgres;
SELECT CDB_Conf_SetConf('api_keys_postgres', '{"username": "test_user", "permissions": ["isolines"]}');
SET ROLE test_regular_user; -- Use regular user role
SELECT cdb_geocode_admin0_polygon('Spain');
SELECT cdb_geocode_admin1_polygon('California');
SELECT cdb_geocode_admin1_polygon('California', 'United States');
SELECT cdb_geocode_namedplace_point('Elx');
SELECT cdb_geocode_namedplace_point('Elx', 'Valencia');
SELECT cdb_geocode_namedplace_point('Elx', 'Valencia', 'Spain');
SELECT cdb_geocode_postalcode_polygon('03204', 'Spain');
SELECT cdb_geocode_postalcode_point('03204', 'Spain');
SELECT cdb_geocode_ipaddress_point('8.8.8.8');
SELECT cdb_geocode_street_point('one street, 1');
SELECT cdb_route_point_to_point('POINT(-87.81406 41.89308)'::geometry,'POINT(-87.79209 41.86138)'::geometry, 'car');
-- Grant geocoding permissions
SET ROLE postgres;
SELECT CDB_Conf_SetConf('api_keys_postgres', '{"username": "test_user", "permissions": ["geocoding", "routing"]}');
SET ROLE test_regular_user; -- Use regular user role
SELECT cdb_geocode_admin0_polygon('Spain');
SELECT cdb_geocode_admin1_polygon('California');
SELECT cdb_geocode_admin1_polygon('California', 'United States');
SELECT cdb_geocode_namedplace_point('Elx');
SELECT cdb_geocode_namedplace_point('Elx', 'Valencia');
SELECT cdb_geocode_namedplace_point('Elx', 'Valencia', 'Spain');
SELECT cdb_geocode_postalcode_polygon('03204', 'Spain');
SELECT cdb_geocode_postalcode_point('03204', 'Spain');
SELECT cdb_geocode_ipaddress_point('8.8.8.8');
SELECT cdb_geocode_street_point('one street, 1');
SELECT cdb_route_point_to_point('POINT(-87.81406 41.89308)'::geometry,'POINT(-87.79209 41.86138)'::geometry, 'car');
-- Remove permissions
SET ROLE postgres;
SELECT CDB_Conf_RemoveConf('api_keys_postgres');

View File

@@ -1,13 +0,0 @@
# Data Services API
The CARTO Data Services API offers a set of location based services that can be used programatically to empower your geospatial applications.
## Documentation
* [Overview](overview.md)
* [Geocoding Functions](geocoding_functions.md)
* [Isoline Functions](isoline_functions.md)
* [Routing Functions](routing_functions.md)
* [Demographic Functions](demographic_functions.md)
* [Segmentation Functions](segmentation_functions.md)
* [Quota Information](quota_information.md)

View File

@@ -1,34 +1,34 @@
# Overview
## Overview
By using CARTO libraries and the SQL API, you can apply location data services to your maps with unique data services functions. These functions are integrated with a number of internal and external services, enabling you to programatically customize subsets of data for your visualizations. These features are useful for geospatial analysis and the results can be saved, and stored, for additional location data service operations.
**Note:** Based on your account plan, some of these data services are subject to different [quota limitations](https://carto.com/docs/carto-engine/dataservices-api/quota-information/#quota-information).
**Note:** Based on your account plan, some of these data services are subject to different [quota limitations]({{site.dataservicesapi_docs}}/support/quota-information/).
_In order to supply the best location data services from within our CARTO Engine, the Data Services API collaborates with [Mapbox](https://www.mapbox.com/) and several other geospatial service providers. [Contact us](mailto:sales@carto.com) if you have any specific questions or requirements about the location data service provider being used with your account._
_In order to supply the best location data services from within our CARTO Engine, the Data Services API collaborates with [TomTom](https://www.tomtom.com/) and several other geospatial service providers. [Contact us](mailto:sales@carto.com) if you have any specific questions or requirements about the location data service provider being used with your account._
## Data Services Integration
### Data Services Integration
By using the SQL API to query the Data Services API functions, you can manage specific operations and the corresponding geometries (a `polygon` or a `point`), according to the input information.
The Data Services API also exposes its services directly through CARTO Builder. For example, you can geocode data (from single rows, complete datasets, or simple inputs) and perform trade areas analysis (computing isodistances or isochrones) programatically, through authenticated SQL requests, or by using the ANALYSIS options.
The Data Services API also exposes its services directly through CARTO Builder. For example, you can geocode data (from single rows, complete datasets, or simple inputs) and perform trade areas analysis (computing isodistances or isochrones) programatically, through authenticated SQL requests, or by using the ANALYSIS options.
The geometries provided by this API are projected in the projection [WGS 84 SRID 4326](http://spatialreference.org/ref/epsg/wgs-84/).
**Note:** The Data Services API [geocoding functions](https://carto.com/docs/carto-engine/dataservices-api/geocoding-functions/#geocoding-functions) return different types of geometries (points or polygons) as result of different geocoding processes. The CARTO Engine does not support multi-geometry layers or datasets, therefore you must confirm that you are using consistent geometry types inside a table, to avoid future conflicts in your map visualization.
**Note:** The Data Services API [geocoding functions]({{site.dataservicesapi_docs}}/reference/#geocoding-functions) return different types of geometries (points or polygons) as result of different geocoding processes. The CARTO Engine does not support multi-geometry layers or datasets, therefore you must verify that you are using consistent geometry types inside a table, to avoid future conflicts in your map visualization.
### Best Practices
#### Best Practices
_Be mindful of the following usage notes when using the Data Services functions with the SQL API:_
It is discouraged to use the SELECT operation with the Data Services API functions in your map layers, as these type of queries consume quota when rendering tiles for your live map views. It may also result in sync performance issues, due to executing multiple requests to the API each time your map is viewed. See details about [Quota Consumption](https://carto.com/docs/carto-engine/dataservices-api/quota-information/#quota-consumption).
It is discouraged to use the SELECT operation with the Data Services API functions in your map layers, as these type of queries consume quota when rendering tiles for your live map views. It may also result in sync performance issues, due to executing multiple requests to the API each time your map is viewed. See details about [Quota Consumption]({{site.dataservicesapi_docs}}/support/quota-information/#quota-consumption).
The Data Services API is **recommended** to be used with INSERT or UPDATE operations, for applying location data to your tables. While SELECT (retrieve) is standard for SQL API requests, be mindful of quota consumption and use INSERT (to insert a new record) or UPDATE (to update an existing record), for best practices.
## Authentication
### Authentication
All requests performed to the CARTO Data Services API must be authenticated with the user API Key. For more information about where to find your API Key, and how to authenticate your SQL API requests, view the [SQL API authentication](/carto-engine/sql-api/authentication/) documentation.
All requests performed to the CARTO Data Services API must be authenticated with the user API Key. For more information about where to find your API Key, and how to authenticate your SQL API requests, view the [Auth API]({{site.authapi_docs}}/) documentation.
## Errors
### Errors
Errors are described in the response of the request. An example is as follows:
@@ -40,10 +40,10 @@ Errors are described in the response of the request. An example is as follows:
}
```
Since the Data Services API is used on top of the CARTO SQL API, you can refer to the [Making calls to the SQL API](https://carto.com/docs/carto-engine/sql-api/making-calls/) documentation for help debugging your SQL errors.
Since the Data Services API is used on top of the CARTO SQL API, you can refer to the [Making calls to the SQL API]({{site.sqlapi_docs}}/guides/making-calls/) documentation for help debugging your SQL errors.
If the requested information is not in the CARTO geocoding database, or if CARTO is unable to recognize your input and match it with a result, the geocoding function returns `null` as a result.
## Limits
### Limits
Usage of the Data Services API is subject to the CARTO SQL API limits, stated in our [Terms of Service](https://carto.com/terms/#excessive).

Binary file not shown.

After

Width:  |  Height:  |  Size: 95 KiB

View File

@@ -0,0 +1,5 @@
## Introduction
The CARTO Data Services API offers a set of location based services that can be used to programatically customize subsets of data for your visualizations.
The contents described in this document are subject to CARTO's [Terms of Service](https://carto.com/legal/)

View File

@@ -0,0 +1,9 @@
## Authentication
Data Services API, like any other [CARTO platform's component]({{site.fundamental_docs}}/components/), requires using an API Key. From your CARTO dashboard, click _[Your API keys](https://carto.com/login)_ from the avatar drop-down menu to view your uniquely generated API Key for managing data with CARTO Engine.
![Your API Keys](../img/avatar.gif)
Learn more about the [basics of authorization]({{site.fundamental_docs}}/authorization/), or dig into the details of [Auth API]({{site.authapi_docs}}/), if you want to know more about this part of CARTO platform.
The examples in this documentation may include a placeholder for the API Key. Ensure that you modify any placeholder parameters with your own credentials.

View File

@@ -0,0 +1,3 @@
## Versioning
Data Services API uses [Semantic Versioning](http://semver.org/). View our Github repository to find tags for each [release](https://github.com/CartoDB/data-services-api/releases).

View File

@@ -0,0 +1,5 @@
## Error handling
Most of the errors fired by the API are handled by the API itself. It triggers a `CartoError` every time an error happens.
A cartoError is an object containing a single `message` field with a string explaining the error.

View File

@@ -1,8 +1,8 @@
# Geocoding Functions
## Geocoding Functions
The [geocoder](https://carto.com/data/geocoder-api/) functions allow you to match your data with geometries on your map. This geocoding service can be used programatically to geocode datasets via the CARTO SQL API. It is fed from _Open Data_ and it serves geometries for countries, provinces, states, cities, postal codes, IP addresses and street addresses. CARTO provides functions for several different categories of geocoding through the Data Services API.
_**This service is subject to quota limitations and extra fees may apply**. View the [Quota Information](https://carto.com/docs/carto-engine/dataservices-api/quota-information/) section for details and recommendations about to quota consumption._
**Warning:** This service is subject to quota limitations and extra fees may apply. View the [Quota Information]({{site.dataservicesapi_docs}}/support/quota-information/) section for details and recommendations about to quota consumption.
The following example displays how to geocode a single country:
@@ -25,169 +25,168 @@ https://{username}.carto.com/api/v2/sql?q=UPDATE {tablename} SET the_geom = ST_C
The following geocoding functions are available, grouped by categories.
## Country Geocoder
### Country Geocoder
This function geocodes your data into country border geometries. It recognizes the names of the different countries either by different synonyms (such as their English name or their endonym), or by ISO (ISO2 or ISO3) codes.
### cdb_geocode_admin0_polygon(_country_name text_)
#### cdb_geocode_admin0_polygon(_country_name text_)
Geocodes the text name of a country into a country_name geometry, displayed as polygon data.
#### Arguments
##### Arguments
Name | Type | Description
--- | --- | ---
`country_name` | `text` | Name of the country
#### Returns
##### Returns
Geometry (polygon, EPSG 4326) or null
#### Example
### Example
##### Update the geometry of a table to geocode it
#### Update the geometry of a table to geocode it
```bash
UPDATE {tablename} SET the_geom = cdb_geocode_admin0_polygon({country_column})
```
##### Insert a geocoded row into a table
#### Insert a geocoded row into a table
```bash
INSERT INTO {tablename} (the_geom) SELECT cdb_geocode_admin0_polygon('France')
```
## Level-1 Administrative Regions Geocoder
### Level-1 Administrative Regions Geocoder
This function geocodes your data into polygon geometries for [Level 1](https://en.wikipedia.org/wiki/Table_of_administrative_divisions_by_country), or [NUTS-1](https://en.wikipedia.org/wiki/NUTS_1_statistical_regions_of_England), administrative divisions (or units) of countries. For example, a "state" in the United States, "départements" in France, or an autonomous community in Spain.
### cdb_geocode_admin1_polygon(_admin1_name text_)
#### cdb_geocode_admin1_polygon(_admin1_name text_)
Geocodes the name of the province/state into a Level-1 administrative region, displayed as a polygon geometry.
#### Arguments
##### Arguments
Name | Type | Description
--- | --- | ---
`admin1_name` | `text` | Name of the province/state
#### Returns
##### Returns
Geometry (polygon, EPSG 4326) or null
#### Example
##### Example
##### Update the geometry of a table to geocode it
###### Update the geometry of a table to geocode it
```bash
UPDATE {tablename} SET the_geom = cdb_geocode_admin1_polygon({province_column})
```
##### Insert a geocoded row into a table
###### Insert a geocoded row into a table
```bash
INSERT INTO {tablename} (the_geom) SELECT cdb_geocode_admin1_polygon('Alicante')
```
### cdb_geocode_admin1_polygon(_admin1_name text, country_name text_)
#### cdb_geocode_admin1_polygon(_admin1_name text, country_name text_)
Geocodes the name of the province/state for a specified country into a Level-1 administrative region, displayed as a polygon geometry.
#### Arguments
##### Arguments
Name | Type | Description
--- | --- | ---
`admin1_name` | `text` | Name of the province/state
`country_name` | `text` | Name of the country in which the province/state is located
#### Returns
##### Returns
Geometry (polygon, EPSG 4326) or null
#### Example
##### Example
##### Update the geometry of a table to geocode it
###### Update the geometry of a table to geocode it
```bash
UPDATE {tablename} SET the_geom = cdb_geocode_admin1_polygon({province_column}, {country_column})
```
##### Insert a geocoded row into a table
###### Insert a geocoded row into a table
```bash
INSERT INTO {tablename} (the_geom) SELECT cdb_geocode_admin1_polygon('Alicante', 'Spain')
```
## City Geocoder
### City Geocoder
This function geocodes your data into point geometries for names of cities. It is recommended to use geocoding functions that require more defined parameters — this returns more accurate results when several cities have the same name. _If there are duplicate results for a city name, the city name with the highest population will be returned._
### cdb_geocode_namedplace_point(_city_name text_)
#### cdb_geocode_namedplace_point(_city_name text_)
Geocodes the text name of a city into a named place geometry, displayed as point data.
#### Arguments
##### Arguments
Name | Type | Description
--- | --- | ---
`city_name` | `text` | Name of the city
#### Returns
##### Returns
Geometry (point, EPSG 4326) or null
#### Example
##### Example
##### Select
###### Select
##### Update the geometry of a table to geocode it
###### Update the geometry of a table to geocode it
```bash
UPDATE {tablename} SET the_geom = cdb_geocode_namedplace_point({city_column})
```
##### Insert a geocoded row into a table
###### Insert a geocoded row into a table
```bash
INSERT INTO {tablename} (the_geom) SELECT cdb_geocode_namedplace_point('Barcelona')
```
### cdb_geocode_namedplace_point(_city_name text, country_name text_)
#### cdb_geocode_namedplace_point(_city_name text, country_name text_)
Geocodes the text name of a city for a specified country into a named place point geometry.
#### Arguments
##### Arguments
Name | Type | Description
--- | --- | ---
`city_name` | `text` | Name of the city
`country_name` | `text` | Name of the country in which the city is located
#### Returns
##### Returns
Geometry (point, EPSG 4326) or null
#### Example
##### Example
##### Update the geometry of a table to geocode it
###### Update the geometry of a table to geocode it
```bash
UPDATE {tablename} SET the_geom = cdb_geocode_namedplace_point({city_column}, 'Spain')
```
##### Insert a geocoded row into a table
###### Insert a geocoded row into a table
```bash
INSERT INTO {tablename} (the_geom) SELECT cdb_geocode_namedplace_point('Barcelona', 'Spain')
```
### cdb_geocode_namedplace_point(_city_name text, admin1_name text, country_name text_)
#### cdb_geocode_namedplace_point(_city_name text, admin1_name text, country_name text_)
Geocodes your data into a named place point geometry, containing the text name of a city, for a specified province/state and country. This is recommended for the most accurate geocoding of city data.
#### Arguments
Geocodes your data into a named place point geometry, containing the text name of a city, for a specified province/state and country. This is recommended for the most accurate geocoding of city data.
##### Arguments
Name | Type | Description
--- | --- | ---
@@ -195,132 +194,132 @@ Name | Type | Description
`admin1_name` | `text` | Name of the province/state in which the city is located
`country_name` | `text` | Name of the country in which the city is located
#### Returns
##### Returns
Geometry (point, EPSG 4326) or null
#### Example
##### Example
##### Update the geometry of a table to geocode it
###### Update the geometry of a table to geocode it
```bash
UPDATE {tablename} SET the_geom = cdb_geocode_namedplace_point({city_column}, {province_column}, 'USA')
```
##### Insert a geocoded row into a table
###### Insert a geocoded row into a table
```bash
INSERT INTO {tablename} (the_geom) SELECT cdb_geocode_namedplace_point('New York', 'New York', 'USA')
```
## Postal Code Geocoder
### Postal Code Geocoder
These functions geocode your data into point, or polygon, geometries for postal codes. The postal code geocoder covers the United States, France, Australia and Canada; a request for a different country will return an empty response.
**Note:** For the USA, US Census Zip Code Tabulation Areas (ZCTA) are used to reference geocodes for USPS postal codes service areas. This is not a CARTO restriction, this is a US Government licensing protection of their zip code data source; which is not publicly available. Additionally, zip codes are considered service areas and are not actually geometric areas. As a solution, the US Census provides ZCTA data, which tabulates GIS postal codes for USPS locations by aggregating census blocks. For details about how ZCTAs are created, see [ZIP Code™ Tabulation Areas (ZCTAs™)](https://www.census.gov/geo/reference/zctas.html). If you are geocoding data and your zip codes fail, ensure you are using ZCTAs for the postal code.
### cdb_geocode_postalcode_polygon(_postal_code text, country_name text_)
#### cdb_geocode_postalcode_polygon(_postal_code text, country_name text_)
Geocodes the postal code for a specified country into a **polygon** geometry.
#### Arguments
##### Arguments
Name | Type | Description
--- | --- | ---
`postal_code` | `text` | Postal code
`country_name` | `text` | Name of the country in which the postal code is located
#### Returns
##### Returns
Geometry (polygon, EPSG 4326) or null
#### Example
##### Example
##### Update the geometry of a table to geocode it
###### Update the geometry of a table to geocode it
```bash
UPDATE {tablename} SET the_geom = cdb_geocode_postalcode_polygon({postal_code_column}, 'USA')
```
##### Insert a geocoded row into a table
###### Insert a geocoded row into a table
```bash
INSERT INTO {tablename} (the_geom) SELECT cdb_geocode_postalcode_polygon('11211', 'USA')
```
### cdb_geocode_postalcode_point(_code text, country_name text_)
#### cdb_geocode_postalcode_point(_code text, country_name text_)
Geocodes the postal code for a specified country into a **point** geometry.
#### Arguments
##### Arguments
Name | Type | Description
--- | --- | ---
`postal_code` | `text` | Postal code
`country_name` | `text` | Name of the country in which the postal code is located
#### Returns
##### Returns
Geometry (point, EPSG 4326) or null
#### Example
##### Example
##### Update the geometry of a table to geocode it
###### Update the geometry of a table to geocode it
```bash
UPDATE {tablename} SET the_geom = cdb_geocode_postalcode_point({postal_code_column}, 'USA')
```
##### Insert a geocoded row into a table
###### Insert a geocoded row into a table
```bash
INSERT INTO {tablename} (the_geom) SELECT cdb_geocode_postalcode_point('11211', 'USA')
```
## IP Addresses Geocoder
### IP Addresses Geocoder
This function geocodes your data into point geometries for IP addresses. This is useful if you are analyzing location based data, based on a set of user's IP addresses.
### cdb_geocode_ipaddress_point(_ip_address text_)
#### cdb_geocode_ipaddress_point(_ip_address text_)
Geocodes a postal code from a specified country into an IP address, displayed as a point geometry.
#### Arguments
##### Arguments
Name | Type | Description
--- | --- | ---
`ip_address` | `text` | IPv4 or IPv6 address
#### Returns
##### Returns
Geometry (point, EPSG 4326) or null
#### Example
##### Example
##### Update the geometry of a table to geocode it
###### Update the geometry of a table to geocode it
```bash
UPDATE {tablename} SET the_geom = cdb_geocode_ipaddress_point('102.23.34.1')
```
##### Insert a geocoded row into a table
###### Insert a geocoded row into a table
```bash
INSERT INTO {tablename} (the_geom) SELECT cdb_geocode_ipaddress_point('102.23.34.1')
```
## Street-Level Geocoder
### Street-Level Geocoder
This function geocodes your data into a point geometry for a street address. CARTO uses several different service providers for street-level geocoding, depending on your platform. If you access CARTO on a Google Cloud Platform, [Google Maps geocoding](https://developers.google.com/maps/documentation/geocoding/intro) is applied. All other platform users are provided with [Mapbox geocoding services](https://www.mapbox.com/). [Contact us](mailto:sales@carto.com) if you have any specific questions or requirements about the location data service provider being used with your account._.
These functions geocode your data into a point geometry for a street address. CARTO platform uses [TomTom geocoding services](https://www.tomtom.com/) by default as the service provider for street-level geocoding. [Contact us](mailto:sales@carto.com) if you have any specific questions or requirements about the location data service provider being used with your account.
**This service is subject to quota limitations, and extra fees may apply**. View the [Quota information](https://carto.com/docs/carto-engine/dataservices-api/quota-information/) for details and recommendations about quota consumption.
**This service is subject to quota limitations, and extra fees may apply**. View the [Quota information]({{site.dataservicesapi_docs}}/support/quota-information/) for details and recommendations about quota consumption.
### cdb_geocode_street_point(_search_text text, [city text], [state text], [country text]_)
#### cdb_geocode_street_point(_search_text text, [city text], [state text], [country text]_)
Geocodes a complete address into a single street geometry, displayed as point data.
#### Arguments
##### Arguments
Name | Type | Description
--- | --- | --- | ---
@@ -329,20 +328,62 @@ Name | Type | Description
`state` | `text` | (Optional) Name of the state.
`country` | `text` | (Optional) Name of the country.
#### Returns
##### Returns
Geometry (point, EPSG 4326) or null
#### Example
##### Example
##### Update the geometry of a table to geocode it
###### Update the geometry of a table to geocode it
```bash
UPDATE {tablename} SET the_geom = cdb_geocode_street_point({street_name_column})
```
##### Insert a geocoded row into a table
###### Insert a geocoded row into a table
```bash
INSERT INTO {tablename} (the_geom) SELECT cdb_geocode_street_point('651 Lombard Street', 'San Francisco', 'California', 'United States')
```
#### cdb_bulk_geocode_street_point (_query text, street_column text, [city_column text], [state_column text], [country_column text], [batch_size integer]_)
Geocodes complete street addresses into point data. Similar to `cdb_geocode_street_point`, but using batch services and therefore allowing for several addresses to be geocoded in a single API call.
##### Arguments
Name | Type | Description
--- | --- | --- | ---
`query` | `text` | SQL query that returns the addresses to be geocoded. It must include a `cartodb_id` column and another column to get the free-form addresses from. Optionally, it may include other columns to fine-tune the geocoding, such as a city column, a state column and a country column.
`street_column` | `text` | Name of the free-form address column, must be present in the SQL query.
`city_column` | `text` | (Optional) Name of the city column, if present in the SQL query.
`state_column` | `text` | (Optional) Name of the state column, if present in the SQL query.
`country_column` | `text` | (Optional) Name of the country column, if present in the SQL query.
`batch_size` | `integer` | (Optional) Geocoding queries are sent in batches. Batch size can be configured, from 1 geocoding query per batch to a maximum value, limited by user quota or other limits. If not specified, it defaults to the maximum size available to the user, which is typically the best option, performance-wise.
##### Returns
Geocoding results are returned in an array. Each array element contains:
Name | Type | Description
--- | --- | --- | ---
`cartodb_id` | `integer` | `cartodb_id` from the original query.
`the_geom` | `Geometry (point, EPSG 4326)` | Point that corresponds to the most accurate match found for this particular address, or `null` if no match was found.
`metadata` | `JSON` | Information about the geocoding result, empty if no match was found.
The `metadata` JSON type includes the following attributes when geocoding was successful:
Name | Type | Description
--- | --- | --- | ---
`precision` | `text` | One of `precise` or `interpolated`.
`relevance` | `number` | Relevance factor, from 0 to 1, higher being more relevant.
`match_type` | `text` | Array with one of `point_of_interest`, `country`, `state`, `county`, `locality`, `district`, `street`, `intersection`, `street_number`, `postal_code`. Empty array if match type is unknown.
##### Example
###### Update the geometries of an entire table by geocoding all the rows based on a street address
```bash
WITH geocoding_results AS (SELECT cartodb_id, the_geom FROM cdb_bulk_geocode_street_point('SELECT cartodb_id, {address_column} from {tablename}', '{address_column}')) UPDATE {tablename} tn SET the_geom = geocoding_results.the_geom FROM geocoding_results WHERE tn.cartodb_id = geocoding_results.cartodb_id
```

View File

@@ -1,8 +1,8 @@
# Isoline Functions
## Isoline Functions
[Isolines](https://carto.com/data/isolines/) are contoured lines that display equally calculated levels over a given surface area. This enables you to view polygon dimensions by forward or reverse measurements. Isoline functions are calculated as the intersection of areas from the origin point, measured by distance (isodistance) or time (isochrone). For example, the distance of a road from a sidewalk. Isoline services through CARTO are available by requesting a single function in the Data Services API.
_**This service is subject to quota limitations and extra fees may apply**. View the [Quota Information](https://carto.com/docs/carto-engine/dataservices-api/quota-information/) section for details and recommendations about to quota consumption._
_**This service is subject to quota limitations and extra fees may apply**. View the [Quota Information]({{site.dataservicesapi_docs}}/support/quota-information/) section for details and recommendations about to quota consumption._
You can use the isoline functions to retrieve, for example, isochrone lines from a certain location, specifying the mode and the ranges that will define each of the isolines. The following query calculates isolines for areas that are 5, 10 and 15 minutes (300, 600 and 900 seconds, respectively) away from the location by following a path defined by car routing and inserts them into a table.
@@ -12,10 +12,12 @@ https://{username}.carto.com/api/v2/sql?q=INSERT INTO {table} (the_geom) SELECT
The following functions provide an isoline generator service, based on time or distance. This service uses the isolines service defined for your account. The default service limits the usage of displayed polygons represented on top of [Mapbox](https://www.mapbox.com/) maps.
## cdb_isodistance(_source geometry, mode text, range integer[], [options text[]]_)
### cdb_isodistance(_source geometry, mode text, range integer[], [options text[]]_)
Displays a contoured line on a map, connecting geometries to a defined area, measured by an equal range of distance (in meters).
Note that not all the providers, for example TomTom, provide us a way to define the isoline limit in distance so we need to make some estimations. Due that estimations the produced isolines could not be 100% precise.
#### Arguments
Name | Type | Description | Accepted values
@@ -26,7 +28,7 @@ Name | Type | Description | Accepted values
`options` | `text[]` | (Optional) Multiple options to add more capabilities to the analysis. See [Optional isolines parameters](#optional-isoline-parameters) for details.
#### Returns
##### Returns
Name | Type | Description
--- | --- | ---
@@ -34,9 +36,9 @@ Name | Type | Description
`data_range` | `integer` | The range that belongs to the generated isoline.
`the_geom` | `geometry(MultiPolygon)` | MultiPolygon geometry of the generated isoline in the 4326 projection.
#### Examples
##### Examples
##### Calculate and insert isodistance polygons from a point into another table
###### Calculate and insert isodistance polygons from a point into another table
```bash
INSERT INTO {table} (the_geom) SELECT the_geom FROM cdb_isodistance('POINT(-3.70568 40.42028)'::geometry, 'walk', ARRAY[300, 600, 900]::integer[])
@@ -48,18 +50,18 @@ or equivalently:
INSERT INTO {table} (the_geom) SELECT (cdb_isodistance('POINT(-3.70568 40.42028)'::geometry, 'walk', ARRAY[300, 600, 900]::integer[])).the_geom
```
##### Calculate and insert the generated isolines from `points_table` table to another table
###### Calculate and insert the generated isolines from `points_table` table to another table
```bash
INSERT INTO {table} (the_geom) SELECT (cdb_isodistance(the_geom, 'walk', string_to_array(distance, ',')::integer[])).the_geom FROM {points_table}
```
## cdb_isochrone(_source geometry, mode text, range integer[], [options text[]]_)
### cdb_isochrone(_source geometry, mode text, range integer[], [options text[]]_)
Displays a contoured line on a map, connecting geometries to a defined area, measured by an equal range of time (in seconds).
#### Arguments
##### Arguments
This function uses the same parameters and information as the `cdb_isodistance` function, with the exception that the range is measured in seconds instead of meters.
@@ -70,9 +72,9 @@ Name | Type | Description | Accepted values
`range` | `integer[]` | Range of the isoline, in seconds. |
`options` | `text[]` | (Optional) Multiple options to add more capabilities to the analysis. See [Optional isolines parameters](#optional-isoline-parameters) for details.
#### Examples
##### Examples
##### Calculate and insert isochrone polygons from a point into another table
###### Calculate and insert isochrone polygons from a point into another table
```bash
INSERT INTO {table} (the_geom) SELECT the_geom FROM cdb_isochrone('POINT(-3.70568 40.42028)'::geometry, 'car', ARRAY[300, 900, 12000]::integer[], ARRAY['mode_traffic=enabled','quality=3']::text[])
@@ -84,13 +86,13 @@ or equivalently:
INSERT INTO {table} (the_geom) SELECT (cdb_isochrone('POINT(-3.70568 40.42028)'::geometry, 'car', ARRAY[300, 900, 12000]::integer[], ARRAY['mode_traffic=enabled','quality=3']::text[])).the_geom
```
##### Calculate and insert the generated isolines from `points_table` table into another table
###### Calculate and insert the generated isolines from `points_table` table into another table
```bash
INSERT INTO {table} (the_geom) SELECT (cdb_isochrone(the_geom, 'walk', string_to_array(time_distance, ',')::integer[])).the_geom FROM {points_table}
```
### Optional isoline parameters
#### Optional isoline parameters
The optional value parameters must be passed using the format: `option=value`.

View File

@@ -1,20 +1,20 @@
# Demographic Functions
### Demographic Functions
The Demographic Snapshot enables you to collect demographic reports around a point location. For example, you can take the coordinates of a coffee shop and find the average population characteristics, such as total population, educational attainment, housing and income information around that location. You can use raw street addresses by combining the Demographic Snapshot with CARTO's geocoding features. If you need help creating coordinates from addresses, see the [Geocoding Functions](https://carto.com/docs/carto-engine/dataservices-api/geocoding-functions/) documentation.
The Demographic Snapshot enables you to collect demographic reports around a point location. For example, you can take the coordinates of a coffee shop and find the average population characteristics, such as total population, educational attainment, housing and income information around that location. You can use raw street addresses by combining the Demographic Snapshot with CARTO's geocoding features. If you need help creating coordinates from addresses, see the [Geocoding Functions]({{site.dataservicesapi_docs}}/reference/#geocoding-functions) documentation.
_**Note:** The Demographic Snapshot functions are only available for the United States._
## OBS_GetDemographicSnapshot( point geometry )
#### OBS_GetDemographicSnapshot( point geometry )
Fields returned include information about income, education, transportation, race, and more. Not all fields will have information for every coordinate queried.
### Arguments
##### Arguments
Name | Description | Example Values
--- | --- | ---
point geometry | A point geometry. You can use the helper function, `CDB_LatLng` to quickly generate one from latitude and longitude | `CDB_LatLng(40.760410,-73.964242)`
### Returns
##### Returns
The Demographic Snapshot contains a broad subset of demographic measures in the Data Observatory. Over 80 measurements are returned by a single API request. For each demographic measure, the API returns the following values.
@@ -37,14 +37,14 @@ obs_getdemographicsnapshot: {
**For details, see the [Glossary of Demographic Measures](#glossary-of-demographic-measures).**
### Examples
##### Examples
```bash
https://{username}.carto.com/api/v2/sql?q=SELECT * FROM
OBS_GetDemographicSnapshot({{point geometry}})
```
##### Get the Geographic Snapshot of a Demographic
####### Get the Geographic Snapshot of a Demographic
__Get the Demographic Snapshot at Camp David__
@@ -60,7 +60,7 @@ https://{username}.carto.com/api/v2/sql?q=SELECT * FROM
OBS_GetDemographicSnapshot(CDB_LatLng(40.80, -73.960))
```
## Glossary of Demographic Measures
#### Glossary of Demographic Measures
This list contains the demographic measures and response names for results from the ```OBS_GetDemographicSnapshot``` function.

View File

@@ -1,12 +1,12 @@
# Routing Functions
## Routing Functions
Routing is the navigation from a defined start location to a defined end location. The calculated results are displayed as turn-by-turn directions on your map, based on the transportation mode that you specified. Routing services through CARTO are available by using the available functions in the Data Services API.
## cdb_route_point_to_point(_origin geometry(Point), destination geometry(Point), mode text, [options text[], units text]_)
### cdb_route_point_to_point(_origin geometry(Point), destination geometry(Point), mode text, [options text[], units text]_)
Returns a route from origin to destination.
#### Arguments
##### Arguments
Name | Type | Description | Accepted values
--- | --- | --- | ---
@@ -17,7 +17,7 @@ Name | Type | Description | Accepted values
`units` | `text` | (Optional) Unit used to represent the length of the route. | `kilometers`, `miles`. By default is `kilometers`. This option is not supported by Mapbox provider
#### Returns
##### Returns
Name | Type | Description
--- | --- | ---
@@ -25,24 +25,24 @@ Name | Type | Description
`length` | `real` | Length in the defined unit in the `units` field. `meters` by default .
`the_geom` | `geometry(LineString)` | LineString geometry of the calculated route in the 4326 projection.
#### Examples
##### Examples
##### Insert the values from the calculated route in your table
###### Insert the values from the calculated route in your table
```bash
INSERT INTO <TABLE> (duration, length, the_geom) SELECT duration, length, shape FROM cdb_route_point_to_point('POINT(-3.70237112 40.41706163)'::geometry,'POINT(-3.69909883 40.41236875)'::geometry, 'car')
```
##### Update the geometry field with the calculated route shape
###### Update the geometry field with the calculated route shape
```bash
UPDATE <TABLE> SET the_geom = (SELECT shape FROM cdb_route_point_to_point('POINT(-3.70237112 40.41706163)'::geometry,'POINT(-3.69909883 40.41236875)'::geometry, 'car', ARRAY['mode_type=shortest']::text[]))
```
## cdb_route_with_waypoints(_waypoints geometry(Point)[], mode text, [options text[], units text]_)
### cdb_route_with_waypoints(_waypoints geometry(Point)[], mode text, [options text[], units text]_)
Returns a route that goes from origin to destination and whose path travels through the defined locations.
#### Arguments
##### Arguments
Name | Type | Description | Accepted values
--- | --- | --- | ---
@@ -52,7 +52,7 @@ Name | Type | Description | Accepted values
`units` | `text` | (Optional) Unit used to represent the length of the route. | `kilometers`, `miles`. By default is `kilometers`. This option is not supported by Mapbox provider
#### Returns
##### Returns
Name | Type | Description
--- | --- | ---
@@ -62,23 +62,23 @@ Name | Type | Description
*Note*: A request to the function _cdb\_route\_with\_waypoints(waypoints geometry(Point)[], mode text, [options text[], units text])_ with only two points in the geometry array are automatically defined as origin and destination. It is equivalent to performing the following request with these two locations as parameters: _cdb\_route\_point\_to\_point(origin geometry(Point), destination geometry(Point), mode text, [options text[], units text])_.
#### Examples
##### Examples
##### Insert the values from the calculated route in your table
###### Insert the values from the calculated route in your table
```bash
INSERT INTO <TABLE> (duration, length, the_geom) SELECT duration, length, shape FROM cdb_route_with_waypoints(Array['POINT(-3.7109 40.4234)'::GEOMETRY, 'POINT(-3.7059 40.4203)'::geometry, 'POINT(-3.7046 40.4180)'::geometry]::geometry[], 'walk')
```
##### Update the geometry field with the calculated route shape
###### Update the geometry field with the calculated route shape
```bash
UPDATE <TABLE> SET the_geom = (SELECT shape FROM cdb_route_with_waypoints(Array['POINT(-3.7109 40.4234)'::GEOMETRY, 'POINT(-3.7059 40.4203)'::geometry, 'POINT(-3.7046 40.4180)'::geometry]::geometry[], 'car', ARRAY['mode_type=shortest']::text[]))
```
### Optional routing parameters
#### Optional routing parameters
The optional value parameters must be passed using the format: `option=value`. Not all are available for all the routing providers
Name | Type | Description | Accepted values
--- | --- | --- | ---
`mode_type` | `text` | Type of route calculation | `shortest` (this option only applies to the car transport mode)
`mode_type` | `text` | Type of route calculation | `shortest` or `fastest` (this option only applies to the car transport mode)

View File

@@ -1,18 +1,18 @@
# Segmentation Functions
## Segmentation Functions
The Segmentation Snapshot functions enable you to determine the pre-calculated population segment for a location. Segmentation is a method that divides a populations into subclassifications based on common traits. For example, you can take the a store location and determine what classification of population exists around that location. If you need help creating coordinates from addresses, see the [Geocoding Functions](https://carto.com/docs/carto-engine/dataservices-api/geocoding-functions/) documentation.
The Segmentation Snapshot functions enable you to determine the pre-calculated population segment for a location. Segmentation is a method that divides a populations into subclassifications based on common traits. For example, you can take the a store location and determine what classification of population exists around that location. If you need help creating coordinates from addresses, see the [Geocoding Functions]({{site.dataservicesapi_docs}}/reference/#geocoding-functions) documentation.
_**Note:** The Segmentation Snapshot functions are only available for the United States. Our first release (May 18, 2016) is derived from Census 2010 variables. Our next release will be based on Census 2014 data. For the latest information, see the [Open Segments](https://github.com/CartoDB/open-segments) project repository._
## OBS_GetSegmentSnapshot( Point Geometry )
### OBS_GetSegmentSnapshot( Point Geometry )
### Arguments
#### Arguments
Name | Description | Example Values
--- | --- | ---
point geometry | A point geometry. You can use the helper function, `CDB_LatLng` to quickly generate one from latitude and longitude | `CDB_LatLng(40.760410,-73.964242)`
### Returns
#### Returns
The segmentation function returns two segment levels for the point you requests, the x10\_segment and x55\_segment. These segmentation levels contain different classifications of population within with each segment. The function also returns the quantile of a number of census variables. For example, if total_poulation is at 90% quantile level then this tract has a higher total population than 90% of the other tracts.
@@ -155,14 +155,14 @@ The possible segments are:
</table>
### Examples
#### Examples
```bash
https://{username}.carto.com/api/v2/sql?q=SELECT * FROM
OBS_GetSegmentSnapshot({{point geometry}})
```
##### Get the Geographic Snapshot of a Segmentation
###### Get the Geographic Snapshot of a Segmentation
__Get the Segmentation Snapshot around the MGM Grand__

View File

@@ -0,0 +1,36 @@
## Support Options
Feeling stuck? There are many ways to find help.
* Ask a question on [GIS StackExchange](https://gis.stackexchange.com/questions/tagged/carto) using the `CARTO` tag.
* [Report an issue](https://github.com/CartoDB/cartodb/issues) in Github.
* Engine Plan customers have additional access to enterprise-level support through CARTO's support representatives.
If you just want to describe an issue or share an idea, just <a class="typeform-share" href="https://cartohq.typeform.com/to/mH6RRl" data-mode="popup" target="_blank"> send your feedback</a>
### Issues on Github
If you think you may have found a bug, or if you have a feature request that you would like to share with the Data Services API team, please [open an issue](https://github.com/CartoDB/cartodb/issues/new).
Before opening an issue, review the [contributing guidelines](https://github.com/CartoDB/cartodb/blob/master/CONTRIBUTING.md).
### Community support on GIS Stack Exchange
GIS Stack Exchange is the most popular community in the geospatial industry. This is a collaboratively-edited question and answer site for geospatial programmers and technicians. It is a fantastic resource for asking technical questions about developing and maintaining your application.
When posting a new question, please consider the following:
* Read the GIS Stack Exchange [help](https://gis.stackexchange.com/help) and [how to ask](https://gis.stackexchange.com/help/how-to-ask) pages for guidelines and tips about posting questions.
* Be very clear about your question in the subject. A clear explanation helps those trying to answer your question, as well as those who may be looking for information in the future.
* Be informative in your post. Details, code snippets, logs, screenshots, etc. help others to understand your problem.
* Use code that demonstrates the problem. It is very hard to debug errors without sample code to reproduce the problem.
### Engine Plan Customers
Engine Plan customers have additional support options beyond general community support. As per your account Terms of Service, you have access to enterprise-level support through CARTO's support representatives available at [enterprise-support@carto.com](mailto:enterprise-support@carto.com)
In order to speed up the resolution of your issue, provide as much information as possible (even if it is a link from community support). This allows our engineers to investigate your problem as soon as possible.
If you are not yet CARTO customer, browse our [plans & pricing](https://carto.com/pricing/) and find the right plan for you.

View File

@@ -0,0 +1,36 @@
## Contribute
CARTO platform is an open-source ecosystem. You can read about the [fundamentals]({{site.fundamental_docs}}/components/) of CARTO architecture and its components.
We are more than happy to receive your contributions to the code and the documentation as well.
## Filling a ticket
If you want to open a new issue in our repository, please follow these instructions:
1. Descriptive title.
2. Write a good description, it always helps.
3. Specify the steps to reproduce the problem.
4. Try to add an example showing the problem.
## Contributing code
Best part of open source, collaborate in Data Services API code!. We like hearing from you, so if you have any bug fixed, or a new feature ready to be merged, those are the steps you should follow:
1. Fork the repository.
2. Create a new branch in your forked repository.
3. Commit your changes. Add new tests if it is necessary.
4. Open a pull request.
5. Any of the maintainers will take a look.
6. If everything works, it will merged and released \o/.
If you want more detailed information, this [GitHub guide](https://guides.github.com/activities/contributing-to-open-source/) is a must.
## Completing documentation
Data Services API documentation is located in ```docs/```. That folder is the content that appears in the [Developer Center](http://carto.com/developers/data-services-api/). Just follow the instructions described in [contributing code](#contributing-code) and after accepting your pull request, we will make it appear online :).
**Tip:** A convenient, easy way of proposing changes in documentation is by using the GitHub editor directly on the web. You can easily create a branch with your changes and make a PR from there.
## Submitting contributions
You will need to sign a Contributor License Agreement (CLA) before making a submission. [Learn more here](https://carto.com/contributions).

View File

@@ -1,8 +1,8 @@
# Quota Information
## Quota Information
**Based on your account plan, some of the Data Services API functions are subject to quota limitations and extra fees may apply.** View our [terms and conditions](https://carto.com/terms/), or [contact us](mailto:sales@carto.com) for details about which functions require service credits to your account.
## Quota Consumption
### Quota Consumption
Quota consumption is calculated based on the number of request made for each function. Be mindful of the following usage recommendations when using the Data Services API functions:
@@ -14,15 +14,15 @@ Quota consumption is calculated based on the number of request made for each fun
* It is advised to store results of these queries into your datasets, and refresh them as needed. This ensure more control of quota credits for your account
## Quota Information Functions
### Quota Information Functions
There are several SQL functions that you can run to obtain quota information about your services.
## cdb_service_quota_info()
### cdb_service_quota_info()
Returns information about per-service quotas (available and used) for the account.
#### Returns
##### Returns
This function returns a set of service quota information records, one per service.
@@ -36,10 +36,10 @@ Name | Type | Description
Service Types:
* `'isolines'` [Isoline/Isochrones (isochrone/isodistance lines) service](https://carto.com/docs/carto-engine/dataservices-api/isoline_functions/)
* `'hires_geocoder'` [Street level geocoding](https://carto.com/docs/carto-engine/dataservices-api/geocoding-functions#street-level-geocoder)
* `'routing'` [Routing functions](https://carto.com/docs/carto-engine/dataservices-api/routing_functions/)
* `'observatory'` Data Observatory services ([demographic](https://carto.com/docs/carto-engine/dataservices-api/demographic_functions/) and [segmentation](https://carto.com/docs/carto-engine/dataservices-api/segmentation_functions/) functions)
* `'isolines'` [Isoline/Isochrones (isochrone/isodistance lines) service]({{site.dataservicesapi_docs}}/reference/#isoline_functions/)
* `'hires_geocoder'` [Street level geocoding]({{site.dataservicesapi_docs}}/reference/#street-level-geocoder)
* `'routing'` [Routing functions]({{site.dataservicesapi_docs}}/reference/#routing_functions/)
* `'observatory'` Data Observatory services ([demographic]({{site.dataservicesapi_docs}}/reference/#demographic_functions/) and [segmentation]({{site.dataservicesapi_docs}}/reference/#segmentation_functions/) functions)
**Notes**
@@ -48,7 +48,7 @@ expenses when the regular quota is exceeded.
A zero value of `monthly_quota` indicates that the service has not been activated for the user.
#### Example
##### Example
```sql
SELECT * FROM cdb_service_quota_info();
@@ -59,9 +59,9 @@ Result:
```sql
service | monthly_quota | used_quota | soft_limit | provider
----------------+---------------+------------+------------+------------------
isolines | 100 | 0 | f | mapbox
hires_geocoder | 100 | 0 | f | mapbox
routing | 50 | 0 | f | mapbox
isolines | 100 | 0 | f | tomtom
hires_geocoder | 100 | 0 | f | tomtom
routing | 50 | 0 | f | tomtom
observatory | 0 | 0 | f | data observatory
(4 rows)
@@ -69,7 +69,7 @@ Result:
In this case, notice that the user has no access to the observatory services. All quotas are *hard-limited* (no soft limits), and no quota has been used in the present period.
## cdb_enough_quota(service text ,input_size numeric)
### cdb_enough_quota(service text ,input_size numeric)
This function is useful to check if enough quota is available for completing a job.
@@ -79,20 +79,20 @@ This is specifically relevant if a number of service calls are to be performed i
Note that some services consume more than one credit per row/call. For example, isolines (with more than one range/track) consume (N rows x M ranges) credits; indicating that the input size should be N x M.
#### Arguments
##### Arguments
Name | Type | Description
------------ | --------- | -----------
`service` | `text` | Service to check; see the list of valid services above.
`input_size` | `numeric` | Number of service calls required, i.e. size of the input to be processed.
#### Returns
##### Returns
The result is a *boolean* value. A *true* value (`'t'`) indicates that the available quota
for the service is enough for the input size requested. A *false* value (`'f'`) indicates
insufficient quota.
#### Example
##### Example
Suppose you want to geocode a whole table. In order to check that you have enough quota, and avoid a "quota exhausted" exception, first find out how many records you need to geocode:

View File

@@ -1,4 +1,4 @@
# Rate limits
## Rate limits
Services can be rate-limited. (currently only gecoding is limited)
@@ -15,72 +15,72 @@ If a service request exceeds the configured rate limits
(i.e. if more than `limit` calls are performe in a fixed interval of
duration `period` seconds) the call will fail with an "Rate limit exceeded" error.
## Server-side interface
### Server-side interface
There's a server-side SQL interface to query or change the configuration.
### cdb_dataservices_server.cdb_service_get_rate_limit(username, orgname, service)
#### cdb_dataservices_server.cdb_service_get_rate_limit(username, orgname, service)
This function returns the rate limit configuration for a given user and service.
#### Returns
##### Returns
The result is a JSON object with the configuration (`period` and `limit` attributes as explained above).
### cdb_dataservices_server.cdb_service_set_user_rate_limit(username, orgname, service, rate_limit)
#### cdb_dataservices_server.cdb_service_set_user_rate_limit(username, orgname, service, rate_limit)
This function sets the rate limit configuration for the user. This overrides any other configuration.
The configuration is provided as a JSON literal. To remove the user-level configuration `NULL` should be passed as the `rate_limit`.
#### Returns
##### Returns
This functions doesn't return any value.
### cdb_dataservices_server.cdb_service_set_org_rate_limit(username, orgname, service, rate_limit)
#### cdb_dataservices_server.cdb_service_set_org_rate_limit(username, orgname, service, rate_limit)
This function sets the rate limit configuration for the organization.
This overrides server level configuration and is overriden by user configuration if present.
The configuration is provided as a JSON literal. To remove the organization-level configuration `NULL` should be passed as the `rate_limit`.
#### Returns
##### Returns
This functions doesn't return any value.
### cdb_dataservices_server.cdb_service_set_server_rate_limit(username, orgname, service, rate_limit)
#### cdb_dataservices_server.cdb_service_set_server_rate_limit(username, orgname, service, rate_limit)
This function sets the default rate limit configuration for all users accesing the dataservices server. This is overriden by organization of user configuration.
The configuration is provided as a JSON literal. To remove the organization-level configuration `NULL` should be passed as the `rate_limit`.
#### Returns
##### Returns
This functions doesn't return any value.
## Client-side interface
### Client-side interface
For convenience there's also a client-side interface (in the client dataservices-api extension), consisting
of public functions to get the current configuration and privileged functions to change it.
### Public functions
#### Public functions
These functions are accesible to non-privileged roles, and should only be executed
using the role corresponding to a CARTO user, since that will determine the
user and organization to which the rate limits configuration applies.
### cdb_dataservices_client.cdb_service_get_rate_limit(service)
#### cdb_dataservices_client.cdb_service_get_rate_limit(service)
This function returns the rate limit configuration in effect for the specified service
and the user corresponding to the role which makes the calls. The effective configuration
may come from any of the configuration levels (server/organization/user); only the
existing configuration with most precedence is returned.
#### Returns
##### Returns
The result is a JSON object with the configuration (`period` and `limit` attributes as explained above).
#### Example:
##### Example:
```
SELECT cdb_dataservices_client.cdb_service_get_rate_limit('geocoder');
@@ -92,21 +92,21 @@ SELECT cdb_dataservices_client.cdb_service_get_rate_limit('geocoder');
```
### Privileged (superuser) functions
#### Privileged (superuser) functions
Thes functions are not accessible by regular user roles, and the user and organization names must be provided as parameters.
### cdb_dataservices_client.cdb_service_set_user_rate_limit(username, orgname, service, rate_limit)
#### cdb_dataservices_client.cdb_service_set_user_rate_limit(username, orgname, service, rate_limit)
This function sets the rate limit configuration for the user. This overrides any other configuration.
The configuration is provided as a JSON literal. To remove the user-level configuration `NULL` should be passed as the `rate_limit`.
#### Returns
##### Returns
This functions doesn't return any value.
#### Example
##### Example
This will configure the geocoder service rate limit for user `myusername`, a non-organization user.
The limit will be set at 1000 requests per day. Since the user doesn't belong to any organization,
@@ -129,18 +129,18 @@ SELECT cdb_dataservices_client.cdb_service_set_user_rate_limit(
(1 row)
```
### cdb_dataservices_client.cdb_service_set_org_rate_limit(username, orgname, service, rate_limit)
#### cdb_dataservices_client.cdb_service_set_org_rate_limit(username, orgname, service, rate_limit)
This function sets the rate limit configuration for the organization.
This overrides server level configuration and is overriden by user configuration if present.
The configuration is provided as a JSON literal. To remove the organization-level configuration `NULL` should be passed as the `rate_limit`.
#### Returns
##### Returns
This functions doesn't return any value.
#### Example
##### Example
This will configure the geocoder service rate limit for the `myorg` organization.
The limit will be set at 100 requests per hour.
@@ -162,17 +162,17 @@ SELECT cdb_dataservices_client.cdb_service_set_org_rate_limit(
(1 row)
```
### cdb_dataservices_client.cdb_service_set_server_rate_limit(username, orgname, service, rate_limit)
#### cdb_dataservices_client.cdb_service_set_server_rate_limit(username, orgname, service, rate_limit)
This function sets the default rate limit configuration for all users accesing the dataservices server. This is overriden by organization of user configuration.
The configuration is provided as a JSON literal. To remove the organization-level configuration `NULL` should be passed as the `rate_limit`.
#### Returns
##### Returns
This functions doesn't return any value.
#### Example
##### Example
This will configure the default geocoder service rate limit for all users
accesing the data-services server.

View File

@@ -0,0 +1,14 @@
{
"name": "dataservices-api-server-extension",
"current_version": {
"requires": {
"postgresql": "^10.0.0",
"postgis": "^2.4.0.0",
"carto_postgresql_ext": "^0.23.0"
},
"works_with": {
"dataservices-api-server-python-lib": "^0.19.1",
"observatory-server-extension": "^1.9.0"
}
}
}

View File

@@ -0,0 +1,197 @@
--DO NOT MODIFY THIS FILE, IT IS GENERATED AUTOMATICALLY FROM SOURCES
-- Complain if script is sourced in psql, rather than via CREATE EXTENSION
\echo Use "ALTER EXTENSION cdb_dataservices_server UPDATE TO '0.36.0'" to load this file. \quit
CREATE OR REPLACE FUNCTION cdb_dataservices_server.cdb_geocode_street_point(username TEXT, orgname TEXT, searchtext TEXT, city TEXT DEFAULT NULL, state_province TEXT DEFAULT NULL, country TEXT DEFAULT NULL)
RETURNS Geometry AS $$
from cartodb_services.metrics import metrics
from cartodb_services.tools import Logger,LoggerConfig
plpy.execute("SELECT cdb_dataservices_server._connect_to_redis('{0}')".format(username))
redis_conn = GD["redis_connection_{0}".format(username)]['redis_metrics_connection']
plpy.execute("SELECT cdb_dataservices_server._get_geocoder_config({0}, {1})".format(plpy.quote_nullable(username), plpy.quote_nullable(orgname)))
user_geocoder_config = GD["user_geocoder_config_{0}".format(username)]
plpy.execute("SELECT cdb_dataservices_server._get_logger_config()")
logger_config = GD["logger_config"]
logger = Logger(logger_config)
params = {'username': username, 'orgname': orgname, 'searchtext': searchtext, 'city': city, 'state_province': state_province, 'country': country}
with metrics('cdb_geocode_street_point', user_geocoder_config, logger, params):
if user_geocoder_config.heremaps_geocoder:
here_plan = plpy.prepare("SELECT cdb_dataservices_server._cdb_here_geocode_street_point($1, $2, $3, $4, $5, $6) as point; ", ["text", "text", "text", "text", "text", "text"])
return plpy.execute(here_plan, [username, orgname, searchtext, city, state_province, country], 1)[0]['point']
elif user_geocoder_config.google_geocoder:
google_plan = plpy.prepare("SELECT cdb_dataservices_server._cdb_google_geocode_street_point($1, $2, $3, $4, $5, $6) as point; ", ["text", "text", "text", "text", "text", "text"])
return plpy.execute(google_plan, [username, orgname, searchtext, city, state_province, country], 1)[0]['point']
elif user_geocoder_config.mapzen_geocoder:
mapzen_plan = plpy.prepare("SELECT cdb_dataservices_server._cdb_mapzen_geocode_street_point($1, $2, $3, $4, $5, $6) as point; ", ["text", "text", "text", "text", "text", "text"])
return plpy.execute(mapzen_plan, [username, orgname, searchtext, city, state_province, country], 1)[0]['point']
elif user_geocoder_config.mapbox_geocoder:
mapbox_plan = plpy.prepare("SELECT cdb_dataservices_server._cdb_mapbox_geocode_street_point($1, $2, $3, $4, $5, $6) as point; ", ["text", "text", "text", "text", "text", "text"])
return plpy.execute(mapbox_plan, [username, orgname, searchtext, city, state_province, country], 1)[0]['point']
elif user_geocoder_config.tomtom_geocoder:
tomtom_plan = plpy.prepare("SELECT cdb_dataservices_server._cdb_tomtom_geocode_street_point($1, $2, $3, $4, $5, $6) as point; ", ["text", "text", "text", "text", "text", "text"])
return plpy.execute(tomtom_plan, [username, orgname, searchtext, city, state_province, country], 1)[0]['point']
elif user_geocoder_config.geocodio_geocoder:
geocodio_plan = plpy.prepare("SELECT cdb_dataservices_server._cdb_geocodio_geocode_street_point($1, $2, $3, $4, $5, $6) as point; ", ["text", "text", "text", "text", "text", "text"])
return plpy.execute(geocodio_plan, [username, orgname, searchtext, city, state_province, country], 1)[0]['point']
else:
raise Exception('Requested geocoder is not available')
$$ LANGUAGE plpythonu STABLE PARALLEL RESTRICTED;
CREATE OR REPLACE FUNCTION cdb_dataservices_server.cdb_geocodio_geocode_street_point(username TEXT, orgname TEXT, searchtext TEXT, city TEXT DEFAULT NULL, state_province TEXT DEFAULT NULL, country TEXT DEFAULT NULL)
RETURNS Geometry AS $$
# The configuration is retrieved but no checks are performed on it
plpy.execute("SELECT cdb_dataservices_server._connect_to_redis('{0}')".format(username))
redis_conn = GD["redis_connection_{0}".format(username)]['redis_metrics_connection']
plpy.execute("SELECT cdb_dataservices_server._get_geocoder_config({0}, {1})".format(plpy.quote_nullable(username), plpy.quote_nullable(orgname)))
user_geocoder_config = GD["user_geocoder_config_{0}".format(username)]
geocodio_plan = plpy.prepare("SELECT cdb_dataservices_server._cdb_geocodio_geocode_street_point($1, $2, $3, $4, $5, $6) as point; ", ["text", "text", "text", "text", "text", "text"])
return plpy.execute(geocodio_plan, [username, orgname, searchtext, city, state_province, country], 1)[0]['point']
$$ LANGUAGE plpythonu STABLE PARALLEL RESTRICTED;
CREATE OR REPLACE FUNCTION cdb_dataservices_server._cdb_geocodio_geocode_street_point(username TEXT, orgname TEXT, searchtext TEXT, city TEXT DEFAULT NULL, state_province TEXT DEFAULT NULL, country TEXT DEFAULT NULL)
RETURNS Geometry AS $$
from iso3166 import countries
from cartodb_services.tools import ServiceManager, QuotaExceededException
from cartodb_services.geocodio import GeocodioGeocoder
from cartodb_services.tools.country import country_to_iso3
from cartodb_services.refactor.service.geocodio_geocoder_config import GeocodioGeocoderConfigBuilder
import cartodb_services
cartodb_services.init(plpy, GD)
service_manager = ServiceManager('geocoder', GeocodioGeocoderConfigBuilder, username, orgname, GD)
try:
service_manager.assert_within_limits()
geocoder = GeocodioGeocoder(service_manager.config.geocodio_api_key, service_manager.logger, service_manager.config.service_params)
country_iso3166 = None
if country:
country_iso3 = country_to_iso3(country)
if country_iso3:
country_iso3166 = countries.get(country_iso3).alpha2.lower()
coordinates = geocoder.geocode(searchtext=searchtext, city=city,
state_province=state_province,
country=country_iso3166)
if coordinates:
service_manager.quota_service.increment_success_service_use()
plan = plpy.prepare("SELECT ST_SetSRID(ST_MakePoint($1, $2), 4326); ", ["double precision", "double precision"])
point = plpy.execute(plan, [coordinates[0], coordinates[1]], 1)[0]
return point['st_setsrid']
else:
service_manager.quota_service.increment_empty_service_use()
return None
except QuotaExceededException as qe:
service_manager.quota_service.increment_failed_service_use()
return None
except BaseException as e:
import sys
service_manager.quota_service.increment_failed_service_use()
service_manager.logger.error('Error trying to geocode street point using Geocodio', sys.exc_info(), data={"username": username, "orgname": orgname})
raise Exception('Error trying to geocode street point using Geocodio')
finally:
service_manager.quota_service.increment_total_service_use()
$$ LANGUAGE plpythonu STABLE PARALLEL RESTRICTED;
CREATE OR REPLACE FUNCTION cdb_dataservices_server._cdb_bulk_geocode_street_point(username TEXT, orgname TEXT, searches jsonb)
RETURNS SETOF cdb_dataservices_server.geocoding AS $$
from cartodb_services.metrics import metrics
from cartodb_services.tools import Logger
import json
plpy.execute("SELECT cdb_dataservices_server._connect_to_redis('{0}')".format(username))
redis_conn = GD["redis_connection_{0}".format(username)]['redis_metrics_connection']
plpy.execute("SELECT cdb_dataservices_server._get_geocoder_config({0}, {1})".format(plpy.quote_nullable(username), plpy.quote_nullable(orgname)))
user_geocoder_config = GD["user_geocoder_config_{0}".format(username)]
plpy.execute("SELECT cdb_dataservices_server._get_logger_config()")
logger_config = GD["logger_config"]
logger = Logger(logger_config)
params = {'username': username, 'orgname': orgname, 'searches': json.loads(searches)}
with metrics('cdb_bulk_geocode_street_point', user_geocoder_config, logger, params):
if user_geocoder_config.google_geocoder:
provider_function = "_cdb_bulk_google_geocode_street_point";
elif user_geocoder_config.heremaps_geocoder:
provider_function = "_cdb_bulk_heremaps_geocode_street_point";
elif user_geocoder_config.tomtom_geocoder:
provider_function = "_cdb_bulk_tomtom_geocode_street_point";
elif user_geocoder_config.mapbox_geocoder:
provider_function = "_cdb_bulk_mapbox_geocode_street_point";
elif user_geocoder_config.geocodio_geocoder:
provider_function = "_cdb_bulk_geocodio_geocode_street_point";
else:
raise Exception('Requested geocoder is not available')
plan = plpy.prepare("SELECT * FROM cdb_dataservices_server.{}($1, $2, $3); ".format(provider_function), ["text", "text", "jsonb"])
return plpy.execute(plan, [username, orgname, searches])
$$ LANGUAGE plpythonu STABLE PARALLEL RESTRICTED;
CREATE OR REPLACE FUNCTION cdb_dataservices_server._cdb_bulk_geocodio_geocode_street_point(username TEXT, orgname TEXT, searches jsonb)
RETURNS SETOF cdb_dataservices_server.geocoding AS $$
from cartodb_services import run_street_point_geocoder
from cartodb_services.tools import ServiceManager
from cartodb_services.refactor.service.geocodio_geocoder_config import GeocodioGeocoderConfigBuilder
from cartodb_services.geocodio import GeocodioBulkGeocoder
from cartodb_services.tools import Logger
import cartodb_services
cartodb_services.init(plpy, GD)
logger_config = GD["logger_config"]
logger = Logger(logger_config)
service_manager = ServiceManager('geocoder', GeocodioGeocoderConfigBuilder, username, orgname, GD)
geocoder = GeocodioBulkGeocoder(service_manager.config.geocodio_api_key, service_manager.logger, service_manager.config.service_params)
return run_street_point_geocoder(plpy, GD, geocoder, service_manager, username, orgname, searches)
$$ LANGUAGE plpythonu STABLE PARALLEL RESTRICTED;
CREATE OR REPLACE FUNCTION cdb_dataservices_server.cdb_geocode_admin0_polygon(username text, orgname text, country_name text)
RETURNS Geometry AS $$
from cartodb_services.metrics import QuotaService
from cartodb_services.metrics import InternalGeocoderConfig
from cartodb_services.metrics import metrics
from cartodb_services.tools import Logger,LoggerConfig
plpy.execute("SELECT cdb_dataservices_server._connect_to_redis('{0}')".format(username))
redis_conn = GD["redis_connection_{0}".format(username)]['redis_metrics_connection']
plpy.execute("SELECT cdb_dataservices_server._get_internal_geocoder_config({0}, {1})".format(plpy.quote_nullable(username), plpy.quote_nullable(orgname)))
user_geocoder_config = GD["user_internal_geocoder_config_{0}".format(username)]
plpy.execute("SELECT cdb_dataservices_server._get_logger_config()")
logger_config = GD["logger_config"]
logger = Logger(logger_config)
quota_service = QuotaService(user_geocoder_config, redis_conn)
params = {'username': username, 'orgname': orgname, 'country_name': country_name}
with metrics('cdb_geocode_admin0_polygon', user_geocoder_config, logger, params):
try:
plan = plpy.prepare("SELECT cdb_dataservices_server._cdb_geocode_admin0_polygon(trim($1)) AS mypolygon", ["text"])
rv = plpy.execute(plan, [country_name], 1)
result = rv[0]["mypolygon"]
if result:
quota_service.increment_success_service_use()
return result
else:
quota_service.increment_empty_service_use()
return None
except BaseException as e:
import sys
quota_service.increment_failed_service_use()
logger.error('Error trying to geocode admin0 polygon', sys.exc_info(), data={"username": username, "orgname": orgname})
raise Exception('Error trying to geocode admin0 polygon')
finally:
quota_service.increment_total_service_use()
$$ LANGUAGE plpythonu STABLE PARALLEL RESTRICTED;

View File

@@ -0,0 +1,79 @@
--DO NOT MODIFY THIS FILE, IT IS GENERATED AUTOMATICALLY FROM SOURCES
-- Complain if script is sourced in psql, rather than via CREATE EXTENSION
\echo Use "ALTER EXTENSION cdb_dataservices_server UPDATE TO '0.35.1'" to load this file. \quit
CREATE OR REPLACE FUNCTION cdb_dataservices_server.cdb_geocode_street_point(username TEXT, orgname TEXT, searchtext TEXT, city TEXT DEFAULT NULL, state_province TEXT DEFAULT NULL, country TEXT DEFAULT NULL)
RETURNS Geometry AS $$
from cartodb_services.metrics import metrics
from cartodb_services.tools import Logger,LoggerConfig
plpy.execute("SELECT cdb_dataservices_server._connect_to_redis('{0}')".format(username))
redis_conn = GD["redis_connection_{0}".format(username)]['redis_metrics_connection']
plpy.execute("SELECT cdb_dataservices_server._get_geocoder_config({0}, {1})".format(plpy.quote_nullable(username), plpy.quote_nullable(orgname)))
user_geocoder_config = GD["user_geocoder_config_{0}".format(username)]
plpy.execute("SELECT cdb_dataservices_server._get_logger_config()")
logger_config = GD["logger_config"]
logger = Logger(logger_config)
params = {'username': username, 'orgname': orgname, 'searchtext': searchtext, 'city': city, 'state_province': state_province, 'country': country}
with metrics('cdb_geocode_street_point', user_geocoder_config, logger, params):
if user_geocoder_config.heremaps_geocoder:
here_plan = plpy.prepare("SELECT cdb_dataservices_server._cdb_here_geocode_street_point($1, $2, $3, $4, $5, $6) as point; ", ["text", "text", "text", "text", "text", "text"])
return plpy.execute(here_plan, [username, orgname, searchtext, city, state_province, country], 1)[0]['point']
elif user_geocoder_config.google_geocoder:
google_plan = plpy.prepare("SELECT cdb_dataservices_server._cdb_google_geocode_street_point($1, $2, $3, $4, $5, $6) as point; ", ["text", "text", "text", "text", "text", "text"])
return plpy.execute(google_plan, [username, orgname, searchtext, city, state_province, country], 1)[0]['point']
elif user_geocoder_config.mapzen_geocoder:
mapzen_plan = plpy.prepare("SELECT cdb_dataservices_server._cdb_mapzen_geocode_street_point($1, $2, $3, $4, $5, $6) as point; ", ["text", "text", "text", "text", "text", "text"])
return plpy.execute(mapzen_plan, [username, orgname, searchtext, city, state_province, country], 1)[0]['point']
elif user_geocoder_config.mapbox_geocoder:
mapbox_plan = plpy.prepare("SELECT cdb_dataservices_server._cdb_mapbox_geocode_street_point($1, $2, $3, $4, $5, $6) as point; ", ["text", "text", "text", "text", "text", "text"])
return plpy.execute(mapbox_plan, [username, orgname, searchtext, city, state_province, country], 1)[0]['point']
elif user_geocoder_config.tomtom_geocoder:
tomtom_plan = plpy.prepare("SELECT cdb_dataservices_server._cdb_tomtom_geocode_street_point($1, $2, $3, $4, $5, $6) as point; ", ["text", "text", "text", "text", "text", "text"])
return plpy.execute(tomtom_plan, [username, orgname, searchtext, city, state_province, country], 1)[0]['point']
else:
raise Exception('Requested geocoder is not available')
$$ LANGUAGE plpythonu STABLE PARALLEL RESTRICTED;
DROP FUNCTION IF EXISTS cdb_dataservices_server.cdb_geocodio_geocode_street_point;
DROP FUNCTION IF EXISTS cdb_dataservices_server._cdb_geocodio_geocode_street_point;
CREATE OR REPLACE FUNCTION cdb_dataservices_server._cdb_bulk_geocode_street_point(username TEXT, orgname TEXT, searches jsonb)
RETURNS SETOF cdb_dataservices_server.geocoding AS $$
from cartodb_services.metrics import metrics
from cartodb_services.tools import Logger
import json
plpy.execute("SELECT cdb_dataservices_server._connect_to_redis('{0}')".format(username))
redis_conn = GD["redis_connection_{0}".format(username)]['redis_metrics_connection']
plpy.execute("SELECT cdb_dataservices_server._get_geocoder_config({0}, {1})".format(plpy.quote_nullable(username), plpy.quote_nullable(orgname)))
user_geocoder_config = GD["user_geocoder_config_{0}".format(username)]
plpy.execute("SELECT cdb_dataservices_server._get_logger_config()")
logger_config = GD["logger_config"]
logger = Logger(logger_config)
params = {'username': username, 'orgname': orgname, 'searches': json.loads(searches)}
with metrics('cdb_bulk_geocode_street_point', user_geocoder_config, logger, params):
if user_geocoder_config.google_geocoder:
provider_function = "_cdb_bulk_google_geocode_street_point";
elif user_geocoder_config.heremaps_geocoder:
provider_function = "_cdb_bulk_heremaps_geocode_street_point";
elif user_geocoder_config.tomtom_geocoder:
provider_function = "_cdb_bulk_tomtom_geocode_street_point";
elif user_geocoder_config.mapbox_geocoder:
provider_function = "_cdb_bulk_mapbox_geocode_street_point";
else:
raise Exception('Requested geocoder is not available')
plan = plpy.prepare("SELECT * FROM cdb_dataservices_server.{}($1, $2, $3); ".format(provider_function), ["text", "text", "jsonb"])
return plpy.execute(plan, [username, orgname, searches])
$$ LANGUAGE plpythonu STABLE PARALLEL RESTRICTED;
DROP FUNCTION IF EXISTS cdb_dataservices_server._cdb_bulk_geocodio_geocode_street_point;

File diff suppressed because it is too large Load Diff

View File

@@ -1,5 +1,5 @@
comment = 'CartoDB dataservices server extension'
default_version = '0.32.0'
default_version = '0.36.0'
requires = 'plpythonu, plproxy, postgis, cdb_geocoder'
superuser = true
schema = cdb_dataservices_server

View File

@@ -0,0 +1,204 @@
--DO NOT MODIFY THIS FILE, IT IS GENERATED AUTOMATICALLY FROM SOURCES
-- Complain if script is sourced in psql, rather than via CREATE EXTENSION
\echo Use "ALTER EXTENSION cdb_dataservices_server UPDATE TO '0.33.0'" to load this file. \quit
-- HERE goes your code to upgrade/downgrade
DROP FUNCTION IF EXISTS cdb_dataservices_server._get_obs_snapshot_config;
CREATE OR REPLACE FUNCTION cdb_dataservices_server._obs_server_conn_str(
username TEXT,
orgname TEXT)
RETURNS text AS $$
plpy.execute("SELECT cdb_dataservices_server._connect_to_redis('{0}')".format(username))
redis_conn = GD["redis_connection_{0}".format(username)]['redis_metrics_connection']
plpy.execute("SELECT cdb_dataservices_server._get_obs_config({0}, {1})".format(plpy.quote_nullable(username), plpy.quote_nullable(orgname)))
user_obs_config = GD["user_obs_config_{0}".format(username)]
return user_obs_config.connection_str
$$ LANGUAGE plpythonu STABLE PARALLEL RESTRICTED;
CREATE OR REPLACE FUNCTION cdb_dataservices_server.obs_get_demographic_snapshot(
username TEXT,
orgname TEXT,
geom geometry(Geometry, 4326),
time_span TEXT DEFAULT NULL,
geometry_level TEXT DEFAULT NULL)
RETURNS json AS $$
from cartodb_services.metrics import metrics
from cartodb_services.metrics import QuotaService
from cartodb_services.tools import Logger,LoggerConfig
import json
plpy.execute("SELECT cdb_dataservices_server._connect_to_redis('{0}')".format(username))
redis_conn = GD["redis_connection_{0}".format(username)]['redis_metrics_connection']
plpy.execute("SELECT cdb_dataservices_server._get_obs_config({0}, {1})".format(plpy.quote_nullable(username), plpy.quote_nullable(orgname)))
user_obs_config = GD["user_obs_config_{0}".format(username)]
plpy.execute("SELECT cdb_dataservices_server._get_logger_config()")
logger_config = GD["logger_config"]
logger = Logger(logger_config)
quota_service = QuotaService(user_obs_config, redis_conn)
if not quota_service.check_user_quota():
raise Exception('You have reached the limit of your quota')
with metrics('obs_getdemographicsnapshot', user_obs_config, logger):
try:
obs_plan = plpy.prepare("SELECT cdb_dataservices_server._OBS_GetDemographicSnapshotJSON($1, $2, $3, $4, $5) as snapshot;", ["text", "text", "geometry(Geometry, 4326)", "text", "text"])
result = plpy.execute(obs_plan, [username, orgname, geom, time_span, geometry_level])
if result:
quota_service.increment_success_service_use()
return result[0]['snapshot']
else:
quota_service.increment_empty_service_use()
return None
except BaseException as e:
import sys
quota_service.increment_failed_service_use()
logger.error('Error trying to obs_get_demographic_snapshot', sys.exc_info(), data={"username": username, "orgname": orgname})
raise Exception('Error trying to obs_get_demographic_snapshot')
finally:
quota_service.increment_total_service_use()
$$ LANGUAGE plpythonu STABLE PARALLEL RESTRICTED;
CREATE OR REPLACE FUNCTION cdb_dataservices_server.OBS_GetDemographicSnapshot(
username TEXT,
orgname TEXT,
geom geometry(Geometry, 4326),
time_span TEXT DEFAULT NULL,
geometry_level TEXT DEFAULT NULL)
RETURNS SETOF JSON AS $$
from cartodb_services.metrics import metrics
from cartodb_services.metrics import QuotaService
from cartodb_services.tools import Logger,LoggerConfig
plpy.execute("SELECT cdb_dataservices_server._connect_to_redis('{0}')".format(username))
redis_conn = GD["redis_connection_{0}".format(username)]['redis_metrics_connection']
plpy.execute("SELECT cdb_dataservices_server._get_obs_config({0}, {1})".format(plpy.quote_nullable(username), plpy.quote_nullable(orgname)))
user_obs_config = GD["user_obs_config_{0}".format(username)]
plpy.execute("SELECT cdb_dataservices_server._get_logger_config()")
logger_config = GD["logger_config"]
logger = Logger(logger_config)
quota_service = QuotaService(user_obs_config, redis_conn)
if not quota_service.check_user_quota():
raise Exception('You have reached the limit of your quota')
with metrics('obs_getdemographicsnapshot', user_obs_config, logger):
try:
obs_plan = plpy.prepare("SELECT cdb_dataservices_server._OBS_GetDemographicSnapshot($1, $2, $3, $4, $5) as snapshot;", ["text", "text", "geometry(Geometry, 4326)", "text", "text"])
result = plpy.execute(obs_plan, [username, orgname, geom, time_span, geometry_level])
if result:
resp = []
for element in result:
value = element['snapshot']
resp.append(value)
quota_service.increment_success_service_use()
return resp
else:
quota_service.increment_empty_service_use()
return []
except BaseException as e:
import sys
quota_service.increment_failed_service_use()
logger.error('Error trying to obs_get_demographic_snapshot', sys.exc_info(), data={"username": username, "orgname": orgname})
raise Exception('Error trying to obs_get_demographic_snapshot')
finally:
quota_service.increment_total_service_use()
$$ LANGUAGE plpythonu STABLE PARALLEL RESTRICTED;
CREATE OR REPLACE FUNCTION cdb_dataservices_server.obs_get_segment_snapshot(
username TEXT,
orgname TEXT,
geom geometry(Geometry, 4326),
geometry_level TEXT DEFAULT NULL)
RETURNS json AS $$
from cartodb_services.metrics import metrics
from cartodb_services.metrics import QuotaService
from cartodb_services.tools import Logger,LoggerConfig
import json
plpy.execute("SELECT cdb_dataservices_server._connect_to_redis('{0}')".format(username))
redis_conn = GD["redis_connection_{0}".format(username)]['redis_metrics_connection']
plpy.execute("SELECT cdb_dataservices_server._get_obs_config({0}, {1})".format(plpy.quote_nullable(username), plpy.quote_nullable(orgname)))
user_obs_config = GD["user_obs_config_{0}".format(username)]
plpy.execute("SELECT cdb_dataservices_server._get_logger_config()")
logger_config = GD["logger_config"]
logger = Logger(logger_config)
quota_service = QuotaService(user_obs_config, redis_conn)
if not quota_service.check_user_quota():
raise Exception('You have reached the limit of your quota')
with metrics('obs_getsegmentsnapshot', user_obs_config, logger):
try:
obs_plan = plpy.prepare("SELECT cdb_dataservices_server._OBS_GetSegmentSnapshotJSON($1, $2, $3, $4) as snapshot;", ["text", "text", "geometry(Geometry, 4326)", "text"])
result = plpy.execute(obs_plan, [username, orgname, geom, geometry_level])
if result:
quota_service.increment_success_service_use()
return result[0]['snapshot']
else:
quota_service.increment_empty_service_use()
return None
except BaseException as e:
import sys
quota_service.increment_failed_service_use()
logger.error('Error trying to obs_get_segment_snapshot', sys.exc_info(), data={"username": username, "orgname": orgname})
raise Exception('Error trying to obs_get_segment_snapshot')
finally:
quota_service.increment_total_service_use()
$$ LANGUAGE plpythonu STABLE PARALLEL RESTRICTED;
CREATE OR REPLACE FUNCTION cdb_dataservices_server._OBS_GetSegmentSnapshot(
username TEXT,
orgname TEXT,
geom geometry(Geometry, 4326),
geometry_level TEXT DEFAULT NULL)
RETURNS SETOF json AS $$
CONNECT cdb_dataservices_server._obs_server_conn_str(username, orgname);
SELECT * FROM cdb_observatory.OBS_GetSegmentSnapshot(geom, geometry_level);
$$ LANGUAGE plproxy VOLATILE PARALLEL UNSAFE;
CREATE OR REPLACE FUNCTION cdb_dataservices_server.OBS_GetSegmentSnapshot(
username TEXT,
orgname TEXT,
geom geometry(Geometry, 4326),
geometry_level TEXT DEFAULT NULL)
RETURNS SETOF JSON AS $$
from cartodb_services.metrics import metrics
from cartodb_services.metrics import QuotaService
from cartodb_services.tools import Logger,LoggerConfig
plpy.execute("SELECT cdb_dataservices_server._connect_to_redis('{0}')".format(username))
redis_conn = GD["redis_connection_{0}".format(username)]['redis_metrics_connection']
plpy.execute("SELECT cdb_dataservices_server._get_obs_config({0}, {1})".format(plpy.quote_nullable(username), plpy.quote_nullable(orgname)))
user_obs_config = GD["user_obs_config_{0}".format(username)]
plpy.execute("SELECT cdb_dataservices_server._get_logger_config()")
logger_config = GD["logger_config"]
logger = Logger(logger_config)
quota_service = QuotaService(user_obs_config, redis_conn)
if not quota_service.check_user_quota():
raise Exception('You have reached the limit of your quota')
with metrics('obs_getsegmentsnapshot', user_obs_config, logger):
try:
obs_plan = plpy.prepare("SELECT * FROM cdb_dataservices_server._OBS_GetSegmentSnapshot($1, $2, $3, $4) as snapshot;", ["text", "text", "geometry(Geometry, 4326)", "text"])
result = plpy.execute(obs_plan, [username, orgname, geom, geometry_level])
if result:
resp = []
for element in result:
value = element['snapshot']
resp.append(value)
quota_service.increment_success_service_use()
return resp
else:
quota_service.increment_empty_service_use()
return []
except BaseException as e:
import sys
quota_service.increment_failed_service_use()
logger.error('Error trying to OBS_GetSegmentSnapshot', sys.exc_info(), data={"username": username, "orgname": orgname})
raise Exception('Error trying to OBS_GetSegmentSnapshot')
finally:
quota_service.increment_total_service_use()
$$ LANGUAGE plpythonu STABLE PARALLEL RESTRICTED;

View File

@@ -0,0 +1,216 @@
--DO NOT MODIFY THIS FILE, IT IS GENERATED AUTOMATICALLY FROM SOURCES
-- Complain if script is sourced in psql, rather than via CREATE EXTENSION
\echo Use "ALTER EXTENSION cdb_dataservices_server UPDATE TO '0.32.0'" to load this file. \quit
-- HERE goes your code to upgrade/downgrade
CREATE OR REPLACE FUNCTION cdb_dataservices_server._get_obs_snapshot_config(username text, orgname text)
RETURNS boolean AS $$
cache_key = "user_obs_snapshot_config_{0}".format(username)
if cache_key in GD:
return False
else:
from cartodb_services.metrics import ObservatorySnapshotConfig
plpy.execute("SELECT cdb_dataservices_server._connect_to_redis('{0}')".format(username))
redis_conn = GD["redis_connection_{0}".format(username)]['redis_metadata_connection']
obs_snapshot_config = ObservatorySnapshotConfig(redis_conn, plpy, username, orgname)
GD[cache_key] = obs_snapshot_config
return True
$$ LANGUAGE plpythonu SECURITY DEFINER STABLE PARALLEL RESTRICTED;
CREATE OR REPLACE FUNCTION cdb_dataservices_server._obs_server_conn_str(
username TEXT,
orgname TEXT)
RETURNS text AS $$
plpy.execute("SELECT cdb_dataservices_server._connect_to_redis('{0}')".format(username))
redis_conn = GD["redis_connection_{0}".format(username)]['redis_metrics_connection']
plpy.execute("SELECT cdb_dataservices_server._get_obs_snapshot_config({0}, {1})".format(plpy.quote_nullable(username), plpy.quote_nullable(orgname)))
user_obs_config = GD["user_obs_snapshot_config_{0}".format(username)]
return user_obs_config.connection_str
$$ LANGUAGE plpythonu STABLE PARALLEL RESTRICTED;
CREATE OR REPLACE FUNCTION cdb_dataservices_server.obs_get_demographic_snapshot(
username TEXT,
orgname TEXT,
geom geometry(Geometry, 4326),
time_span TEXT DEFAULT NULL,
geometry_level TEXT DEFAULT NULL)
RETURNS json AS $$
from cartodb_services.metrics import metrics
from cartodb_services.metrics import QuotaService
from cartodb_services.tools import Logger,LoggerConfig
import json
plpy.execute("SELECT cdb_dataservices_server._connect_to_redis('{0}')".format(username))
redis_conn = GD["redis_connection_{0}".format(username)]['redis_metrics_connection']
plpy.execute("SELECT cdb_dataservices_server._get_obs_snapshot_config({0}, {1})".format(plpy.quote_nullable(username), plpy.quote_nullable(orgname)))
user_obs_config = GD["user_obs_snapshot_config_{0}".format(username)]
plpy.execute("SELECT cdb_dataservices_server._get_logger_config()")
logger_config = GD["logger_config"]
logger = Logger(logger_config)
quota_service = QuotaService(user_obs_config, redis_conn)
if not quota_service.check_user_quota():
raise Exception('You have reached the limit of your quota')
with metrics('obs_getdemographicsnapshot', user_obs_config, logger):
try:
obs_plan = plpy.prepare("SELECT cdb_dataservices_server._OBS_GetDemographicSnapshotJSON($1, $2, $3, $4, $5) as snapshot;", ["text", "text", "geometry(Geometry, 4326)", "text", "text"])
result = plpy.execute(obs_plan, [username, orgname, geom, time_span, geometry_level])
if result:
quota_service.increment_success_service_use()
return result[0]['snapshot']
else:
quota_service.increment_empty_service_use()
return None
except BaseException as e:
import sys
quota_service.increment_failed_service_use()
logger.error('Error trying to obs_get_demographic_snapshot', sys.exc_info(), data={"username": username, "orgname": orgname})
raise Exception('Error trying to obs_get_demographic_snapshot')
finally:
quota_service.increment_total_service_use()
$$ LANGUAGE plpythonu STABLE PARALLEL RESTRICTED;
CREATE OR REPLACE FUNCTION cdb_dataservices_server.OBS_GetDemographicSnapshot(
username TEXT,
orgname TEXT,
geom geometry(Geometry, 4326),
time_span TEXT DEFAULT NULL,
geometry_level TEXT DEFAULT NULL)
RETURNS SETOF JSON AS $$
from cartodb_services.metrics import metrics
from cartodb_services.metrics import QuotaService
from cartodb_services.tools import Logger,LoggerConfig
plpy.execute("SELECT cdb_dataservices_server._connect_to_redis('{0}')".format(username))
redis_conn = GD["redis_connection_{0}".format(username)]['redis_metrics_connection']
plpy.execute("SELECT cdb_dataservices_server._get_obs_snapshot_config({0}, {1})".format(plpy.quote_nullable(username), plpy.quote_nullable(orgname)))
user_obs_config = GD["user_obs_snapshot_config_{0}".format(username)]
plpy.execute("SELECT cdb_dataservices_server._get_logger_config()")
logger_config = GD["logger_config"]
logger = Logger(logger_config)
quota_service = QuotaService(user_obs_config, redis_conn)
if not quota_service.check_user_quota():
raise Exception('You have reached the limit of your quota')
with metrics('obs_getdemographicsnapshot', user_obs_config, logger):
try:
obs_plan = plpy.prepare("SELECT cdb_dataservices_server._OBS_GetDemographicSnapshot($1, $2, $3, $4, $5) as snapshot;", ["text", "text", "geometry(Geometry, 4326)", "text", "text"])
result = plpy.execute(obs_plan, [username, orgname, geom, time_span, geometry_level])
if result:
resp = []
for element in result:
value = element['snapshot']
resp.append(value)
quota_service.increment_success_service_use()
return resp
else:
quota_service.increment_empty_service_use()
return []
except BaseException as e:
import sys
quota_service.increment_failed_service_use()
logger.error('Error trying to obs_get_demographic_snapshot', sys.exc_info(), data={"username": username, "orgname": orgname})
raise Exception('Error trying to obs_get_demographic_snapshot')
finally:
quota_service.increment_total_service_use()
$$ LANGUAGE plpythonu STABLE PARALLEL RESTRICTED;
CREATE OR REPLACE FUNCTION cdb_dataservices_server.obs_get_segment_snapshot(
username TEXT,
orgname TEXT,
geom geometry(Geometry, 4326),
geometry_level TEXT DEFAULT NULL)
RETURNS json AS $$
from cartodb_services.metrics import metrics
from cartodb_services.metrics import QuotaService
from cartodb_services.tools import Logger,LoggerConfig
import json
plpy.execute("SELECT cdb_dataservices_server._connect_to_redis('{0}')".format(username))
redis_conn = GD["redis_connection_{0}".format(username)]['redis_metrics_connection']
plpy.execute("SELECT cdb_dataservices_server._get_obs_snapshot_config({0}, {1})".format(plpy.quote_nullable(username), plpy.quote_nullable(orgname)))
user_obs_config = GD["user_obs_snapshot_config_{0}".format(username)]
plpy.execute("SELECT cdb_dataservices_server._get_logger_config()")
logger_config = GD["logger_config"]
logger = Logger(logger_config)
quota_service = QuotaService(user_obs_config, redis_conn)
if not quota_service.check_user_quota():
raise Exception('You have reached the limit of your quota')
with metrics('obs_getsegmentsnapshot', user_obs_config, logger):
try:
obs_plan = plpy.prepare("SELECT cdb_dataservices_server._OBS_GetSegmentSnapshotJSON($1, $2, $3, $4) as snapshot;", ["text", "text", "geometry(Geometry, 4326)", "text"])
result = plpy.execute(obs_plan, [username, orgname, geom, geometry_level])
if result:
quota_service.increment_success_service_use()
return result[0]['snapshot']
else:
quota_service.increment_empty_service_use()
return None
except BaseException as e:
import sys
quota_service.increment_failed_service_use()
logger.error('Error trying to obs_get_segment_snapshot', sys.exc_info(), data={"username": username, "orgname": orgname})
raise Exception('Error trying to obs_get_segment_snapshot')
finally:
quota_service.increment_total_service_use()
$$ LANGUAGE plpythonu STABLE PARALLEL RESTRICTED;
CREATE OR REPLACE FUNCTION cdb_dataservices_server._OBS_GetSegmentSnapshot(
username TEXT,
orgname TEXT,
geom geometry(Geometry, 4326),
geometry_level TEXT DEFAULT NULL)
RETURNS SETOF json AS $$
CONNECT cdb_dataservices_server._obs_server_conn_str(username, orgname);
SELECT * FROM cdb_observatory.OBS_GetSegmentSnapshot(geom, geometry_level);
$$ LANGUAGE plproxy VOLATILE PARALLEL UNSAFE;
CREATE OR REPLACE FUNCTION cdb_dataservices_server.OBS_GetSegmentSnapshot(
username TEXT,
orgname TEXT,
geom geometry(Geometry, 4326),
geometry_level TEXT DEFAULT NULL)
RETURNS SETOF JSON AS $$
from cartodb_services.metrics import metrics
from cartodb_services.metrics import QuotaService
from cartodb_services.tools import Logger,LoggerConfig
plpy.execute("SELECT cdb_dataservices_server._connect_to_redis('{0}')".format(username))
redis_conn = GD["redis_connection_{0}".format(username)]['redis_metrics_connection']
plpy.execute("SELECT cdb_dataservices_server._get_obs_snapshot_config({0}, {1})".format(plpy.quote_nullable(username), plpy.quote_nullable(orgname)))
user_obs_config = GD["user_obs_snapshot_config_{0}".format(username)]
plpy.execute("SELECT cdb_dataservices_server._get_logger_config()")
logger_config = GD["logger_config"]
logger = Logger(logger_config)
quota_service = QuotaService(user_obs_config, redis_conn)
if not quota_service.check_user_quota():
raise Exception('You have reached the limit of your quota')
with metrics('obs_getsegmentsnapshot', user_obs_config, logger):
try:
obs_plan = plpy.prepare("SELECT * FROM cdb_dataservices_server._OBS_GetSegmentSnapshot($1, $2, $3, $4) as snapshot;", ["text", "text", "geometry(Geometry, 4326)", "text"])
result = plpy.execute(obs_plan, [username, orgname, geom, geometry_level])
if result:
resp = []
for element in result:
value = element['snapshot']
resp.append(value)
quota_service.increment_success_service_use()
return resp
else:
quota_service.increment_empty_service_use()
return []
except BaseException as e:
import sys
quota_service.increment_failed_service_use()
logger.error('Error trying to OBS_GetSegmentSnapshot', sys.exc_info(), data={"username": username, "orgname": orgname})
raise Exception('Error trying to OBS_GetSegmentSnapshot')
finally:
quota_service.increment_total_service_use()
$$ LANGUAGE plpythonu STABLE PARALLEL RESTRICTED;

View File

@@ -0,0 +1,425 @@
--DO NOT MODIFY THIS FILE, IT IS GENERATED AUTOMATICALLY FROM SOURCES
-- Complain if script is sourced in psql, rather than via CREATE EXTENSION
\echo Use "ALTER EXTENSION cdb_dataservices_server UPDATE TO '0.34.0'" to load this file. \quit
-- HERE goes your code to upgrade/downgrade
CREATE OR REPLACE FUNCTION cdb_dataservices_server.cdb_route_point_to_point(
username TEXT,
orgname TEXT,
origin geometry(Point, 4326),
destination geometry(Point, 4326),
mode TEXT,
options text[] DEFAULT ARRAY[]::text[],
units text DEFAULT 'kilometers')
RETURNS cdb_dataservices_server.simple_route AS $$
from cartodb_services.metrics import metrics
from cartodb_services.tools import Logger
plpy.execute("SELECT cdb_dataservices_server._connect_to_redis('{0}')".format(username))
redis_conn = GD["redis_connection_{0}".format(username)]['redis_metrics_connection']
plpy.execute("SELECT cdb_dataservices_server._get_routing_config({0}, {1})".format(plpy.quote_nullable(username), plpy.quote_nullable(orgname)))
user_routing_config = GD["user_routing_config_{0}".format(username)]
plpy.execute("SELECT cdb_dataservices_server._get_logger_config()")
logger_config = GD["logger_config"]
logger = Logger(logger_config)
params = {'username': username, 'orgname': orgname, 'origin': origin, 'destination': destination, 'mode': mode, 'options': options, 'units': units}
with metrics('cdb_route_with_point', user_routing_config, logger, params):
waypoints = [origin, destination]
if user_routing_config.mapzen_provider:
mapzen_plan = plpy.prepare("SELECT * FROM cdb_dataservices_server._cdb_mapzen_route_with_waypoints($1, $2, $3, $4) as route;", ["text", "text", "geometry(Point, 4326)[]", "text"])
result = plpy.execute(mapzen_plan, [username, orgname, waypoints, mode])
return [result[0]['shape'],result[0]['length'], result[0]['duration']]
elif user_routing_config.mapbox_provider:
mapbox_plan = plpy.prepare("SELECT * FROM cdb_dataservices_server._cdb_mapbox_route_with_waypoints($1, $2, $3, $4) as route;", ["text", "text", "geometry(Point, 4326)[]", "text"])
result = plpy.execute(mapbox_plan, [username, orgname, waypoints, mode])
return [result[0]['shape'],result[0]['length'], result[0]['duration']]
elif user_routing_config.tomtom_provider:
tomtom_plan = plpy.prepare("SELECT * FROM cdb_dataservices_server._cdb_tomtom_route_with_waypoints($1, $2, $3, $4) as route;", ["text", "text", "geometry(Point, 4326)[]", "text"])
result = plpy.execute(tomtom_plan, [username, orgname, waypoints, mode])
return [result[0]['shape'],result[0]['length'], result[0]['duration']]
else:
raise Exception('Requested routing method is not available')
$$ LANGUAGE plpythonu STABLE PARALLEL RESTRICTED;
CREATE OR REPLACE FUNCTION cdb_dataservices_server.cdb_route_with_waypoints(
username TEXT,
orgname TEXT,
waypoints geometry(Point, 4326)[],
mode TEXT,
options text[] DEFAULT ARRAY[]::text[],
units text DEFAULT 'kilometers')
RETURNS cdb_dataservices_server.simple_route AS $$
from cartodb_services.metrics import metrics
from cartodb_services.tools import Logger
plpy.execute("SELECT cdb_dataservices_server._connect_to_redis('{0}')".format(username))
redis_conn = GD["redis_connection_{0}".format(username)]['redis_metrics_connection']
plpy.execute("SELECT cdb_dataservices_server._get_routing_config({0}, {1})".format(plpy.quote_nullable(username), plpy.quote_nullable(orgname)))
user_routing_config = GD["user_routing_config_{0}".format(username)]
plpy.execute("SELECT cdb_dataservices_server._get_logger_config()")
logger_config = GD["logger_config"]
logger = Logger(logger_config)
params = {'username': username, 'orgname': orgname, 'waypoints': waypoints, 'mode': mode, 'options': options, 'units': units}
with metrics('cdb_route_with_waypoints', user_routing_config, logger, params):
if user_routing_config.mapzen_provider:
mapzen_plan = plpy.prepare("SELECT * FROM cdb_dataservices_server._cdb_mapzen_route_with_waypoints($1, $2, $3, $4) as route;", ["text", "text", "geometry(Point, 4326)[]", "text"])
result = plpy.execute(mapzen_plan, [username, orgname, waypoints, mode])
return [result[0]['shape'],result[0]['length'], result[0]['duration']]
elif user_routing_config.mapbox_provider:
mapbox_plan = plpy.prepare("SELECT * FROM cdb_dataservices_server._cdb_mapbox_route_with_waypoints($1, $2, $3, $4) as route;", ["text", "text", "geometry(Point, 4326)[]", "text"])
result = plpy.execute(mapbox_plan, [username, orgname, waypoints, mode])
return [result[0]['shape'],result[0]['length'], result[0]['duration']]
elif user_routing_config.tomtom_provider:
tomtom_plan = plpy.prepare("SELECT * FROM cdb_dataservices_server._cdb_tomtom_route_with_waypoints($1, $2, $3, $4) as route;", ["text", "text", "geometry(Point, 4326)[]", "text"])
result = plpy.execute(tomtom_plan, [username, orgname, waypoints, mode])
return [result[0]['shape'],result[0]['length'], result[0]['duration']]
else:
raise Exception('Requested routing method is not available')
$$ LANGUAGE plpythonu STABLE PARALLEL RESTRICTED;
CREATE OR REPLACE FUNCTION cdb_dataservices_server.cdb_geocode_street_point(username TEXT, orgname TEXT, searchtext TEXT, city TEXT DEFAULT NULL, state_province TEXT DEFAULT NULL, country TEXT DEFAULT NULL)
RETURNS Geometry AS $$
from cartodb_services.metrics import metrics
from cartodb_services.tools import Logger,LoggerConfig
plpy.execute("SELECT cdb_dataservices_server._connect_to_redis('{0}')".format(username))
redis_conn = GD["redis_connection_{0}".format(username)]['redis_metrics_connection']
plpy.execute("SELECT cdb_dataservices_server._get_geocoder_config({0}, {1})".format(plpy.quote_nullable(username), plpy.quote_nullable(orgname)))
user_geocoder_config = GD["user_geocoder_config_{0}".format(username)]
plpy.execute("SELECT cdb_dataservices_server._get_logger_config()")
logger_config = GD["logger_config"]
logger = Logger(logger_config)
params = {'username': username, 'orgname': orgname, 'searchtext': searchtext, 'city': city, 'state_province': state_province, 'country': country}
with metrics('cdb_geocode_street_point', user_geocoder_config, logger, params):
if user_geocoder_config.heremaps_geocoder:
here_plan = plpy.prepare("SELECT cdb_dataservices_server._cdb_here_geocode_street_point($1, $2, $3, $4, $5, $6) as point; ", ["text", "text", "text", "text", "text", "text"])
return plpy.execute(here_plan, [username, orgname, searchtext, city, state_province, country], 1)[0]['point']
elif user_geocoder_config.google_geocoder:
google_plan = plpy.prepare("SELECT cdb_dataservices_server._cdb_google_geocode_street_point($1, $2, $3, $4, $5, $6) as point; ", ["text", "text", "text", "text", "text", "text"])
return plpy.execute(google_plan, [username, orgname, searchtext, city, state_province, country], 1)[0]['point']
elif user_geocoder_config.mapzen_geocoder:
mapzen_plan = plpy.prepare("SELECT cdb_dataservices_server._cdb_mapzen_geocode_street_point($1, $2, $3, $4, $5, $6) as point; ", ["text", "text", "text", "text", "text", "text"])
return plpy.execute(mapzen_plan, [username, orgname, searchtext, city, state_province, country], 1)[0]['point']
elif user_geocoder_config.mapbox_geocoder:
mapbox_plan = plpy.prepare("SELECT cdb_dataservices_server._cdb_mapbox_geocode_street_point($1, $2, $3, $4, $5, $6) as point; ", ["text", "text", "text", "text", "text", "text"])
return plpy.execute(mapbox_plan, [username, orgname, searchtext, city, state_province, country], 1)[0]['point']
elif user_geocoder_config.tomtom_geocoder:
tomtom_plan = plpy.prepare("SELECT cdb_dataservices_server._cdb_tomtom_geocode_street_point($1, $2, $3, $4, $5, $6) as point; ", ["text", "text", "text", "text", "text", "text"])
return plpy.execute(tomtom_plan, [username, orgname, searchtext, city, state_province, country], 1)[0]['point']
else:
raise Exception('Requested geocoder is not available')
$$ LANGUAGE plpythonu STABLE PARALLEL RESTRICTED;
CREATE OR REPLACE FUNCTION cdb_dataservices_server._cdb_bulk_geocode_street_point(username TEXT, orgname TEXT, searches jsonb)
RETURNS SETOF cdb_dataservices_server.geocoding AS $$
from cartodb_services.metrics import metrics
from cartodb_services.tools import Logger
plpy.execute("SELECT cdb_dataservices_server._connect_to_redis('{0}')".format(username))
redis_conn = GD["redis_connection_{0}".format(username)]['redis_metrics_connection']
plpy.execute("SELECT cdb_dataservices_server._get_geocoder_config({0}, {1})".format(plpy.quote_nullable(username), plpy.quote_nullable(orgname)))
user_geocoder_config = GD["user_geocoder_config_{0}".format(username)]
plpy.execute("SELECT cdb_dataservices_server._get_logger_config()")
logger_config = GD["logger_config"]
logger = Logger(logger_config)
params = {'username': username, 'orgname': orgname, 'searches': searches}
with metrics('cdb_bulk_geocode_street_point', user_geocoder_config, logger, params):
if user_geocoder_config.google_geocoder:
provider_function = "_cdb_bulk_google_geocode_street_point";
elif user_geocoder_config.heremaps_geocoder:
provider_function = "_cdb_bulk_heremaps_geocode_street_point";
elif user_geocoder_config.tomtom_geocoder:
provider_function = "_cdb_bulk_tomtom_geocode_street_point";
elif user_geocoder_config.mapbox_geocoder:
provider_function = "_cdb_bulk_mapbox_geocode_street_point";
else:
raise Exception('Requested geocoder is not available')
plan = plpy.prepare("SELECT * FROM cdb_dataservices_server.{}($1, $2, $3); ".format(provider_function), ["text", "text", "jsonb"])
return plpy.execute(plan, [username, orgname, searches])
$$ LANGUAGE plpythonu STABLE PARALLEL RESTRICTED;
CREATE OR REPLACE FUNCTION cdb_dataservices_server.cdb_geocode_admin0_polygon(username text, orgname text, country_name text)
RETURNS Geometry AS $$
from cartodb_services.metrics import QuotaService
from cartodb_services.metrics import InternalGeocoderConfig
from cartodb_services.metrics import metrics
from cartodb_services.tools import Logger,LoggerConfig
plpy.execute("SELECT cdb_dataservices_server._connect_to_redis('{0}')".format(username))
redis_conn = GD["redis_connection_{0}".format(username)]['redis_metrics_connection']
plpy.execute("SELECT cdb_dataservices_server._get_internal_geocoder_config({0}, {1})".format(plpy.quote_nullable(username), plpy.quote_nullable(orgname)))
user_geocoder_config = GD["user_internal_geocoder_config_{0}".format(username)]
plpy.execute("SELECT cdb_dataservices_server._get_logger_config()")
logger_config = GD["logger_config"]
logger = Logger(logger_config)
quota_service = QuotaService(user_geocoder_config, redis_conn)
params = {'username': username, 'orgname': orgname, 'country_name': country_name}
with metrics('cdb_geocode_admin0_polygon', user_geocoder_config, logger, params):
try:
plan = plpy.prepare("SELECT cdb_dataservices_server._cdb_geocode_admin0_polygon(trim($1)) AS mypolygon", ["text"])
rv = plpy.execute(plan, [country_name], 1)
result = rv[0]["mypolygon"]
if result:
quota_service.increment_success_service_use()
return result
else:
quota_service.increment_empty_service_use()
return None
except BaseException as e:
import sys
quota_service.increment_failed_service_use()
logger.error('Error trying to geocode admin0 polygon', sys.exc_info(), data={"username": username, "orgname": orgname})
raise Exception('Error trying to geocode admin0 polygon')
finally:
quota_service.increment_total_service_use()
$$ LANGUAGE plpythonu STABLE PARALLEL RESTRICTED;
CREATE OR REPLACE FUNCTION cdb_dataservices_server.cdb_geocode_admin1_polygon(username text, orgname text, admin1_name text)
RETURNS Geometry AS $$
from cartodb_services.metrics import metrics
from cartodb_services.metrics import QuotaService
from cartodb_services.metrics import InternalGeocoderConfig
from cartodb_services.tools import Logger,LoggerConfig
plpy.execute("SELECT cdb_dataservices_server._connect_to_redis('{0}')".format(username))
redis_conn = GD["redis_connection_{0}".format(username)]['redis_metrics_connection']
plpy.execute("SELECT cdb_dataservices_server._get_internal_geocoder_config({0}, {1})".format(plpy.quote_nullable(username), plpy.quote_nullable(orgname)))
user_geocoder_config = GD["user_internal_geocoder_config_{0}".format(username)]
plpy.execute("SELECT cdb_dataservices_server._get_logger_config()")
logger_config = GD["logger_config"]
logger = Logger(logger_config)
quota_service = QuotaService(user_geocoder_config, redis_conn)
params = {'username': username, 'orgname': orgname, 'admin1_name': admin1_name}
with metrics('cdb_geocode_admin1_polygon', user_geocoder_config, logger, params):
try:
plan = plpy.prepare("SELECT cdb_dataservices_server._cdb_geocode_admin1_polygon(trim($1)) AS mypolygon", ["text"])
rv = plpy.execute(plan, [admin1_name], 1)
result = rv[0]["mypolygon"]
if result:
quota_service.increment_success_service_use()
return result
else:
quota_service.increment_empty_service_use()
return None
except BaseException as e:
import sys
quota_service.increment_failed_service_use()
logger.error('Error trying to geocode admin1 polygon', sys.exc_info(), data={"username": username, "orgname": orgname})
raise Exception('Error trying to geocode admin1 polygon')
finally:
quota_service.increment_total_service_use()
$$ LANGUAGE plpythonu STABLE PARALLEL RESTRICTED;
CREATE OR REPLACE FUNCTION cdb_dataservices_server._cdb_internal_geocode_namedplace(username text, orgname text, city_name text, admin1_name text DEFAULT NULL, country_name text DEFAULT NULL)
RETURNS Geometry AS $$
from cartodb_services.metrics import QuotaService
from cartodb_services.metrics import InternalGeocoderConfig, metrics
from cartodb_services.tools import Logger,LoggerConfig
plpy.execute("SELECT cdb_dataservices_server._connect_to_redis('{0}')".format(username))
redis_conn = GD["redis_connection_{0}".format(username)]['redis_metrics_connection']
plpy.execute("SELECT cdb_dataservices_server._get_internal_geocoder_config({0}, {1})".format(plpy.quote_nullable(username), plpy.quote_nullable(orgname)))
user_geocoder_config = GD["user_internal_geocoder_config_{0}".format(username)]
plpy.execute("SELECT cdb_dataservices_server._get_logger_config()")
logger_config = GD["logger_config"]
logger = Logger(logger_config)
quota_service = QuotaService(user_geocoder_config, redis_conn)
params = {'username': username, 'orgname': orgname, 'city_name': city_name, 'admin1_name': admin1_name, 'country_name': country_name}
with metrics('cdb_geocode_namedplace_point', user_geocoder_config, logger, params):
try:
if admin1_name and country_name:
plan = plpy.prepare("SELECT cdb_dataservices_server._cdb_geocode_namedplace_point(trim($1), trim($2), trim($3)) AS mypoint", ["text", "text", "text"])
rv = plpy.execute(plan, [city_name, admin1_name, country_name], 1)
elif country_name:
plan = plpy.prepare("SELECT cdb_dataservices_server._cdb_geocode_namedplace_point(trim($1), trim($2)) AS mypoint", ["text", "text"])
rv = plpy.execute(plan, [city_name, country_name], 1)
else:
plan = plpy.prepare("SELECT cdb_dataservices_server._cdb_geocode_namedplace_point(trim($1)) AS mypoint", ["text"])
rv = plpy.execute(plan, [city_name], 1)
result = rv[0]["mypoint"]
if result:
quota_service.increment_success_service_use()
return result
else:
quota_service.increment_empty_service_use()
return None
except BaseException as e:
import sys
quota_service.increment_failed_service_use()
logger.error('Error trying to geocode namedplace point', sys.exc_info(), data={"username": username, "orgname": orgname})
raise Exception('Error trying to geocode namedplace point')
finally:
quota_service.increment_total_service_use()
$$ LANGUAGE plpythonu STABLE PARALLEL RESTRICTED;
CREATE OR REPLACE FUNCTION cdb_dataservices_server.cdb_geocode_postalcode_point(username text, orgname text, code text)
RETURNS Geometry AS $$
from cartodb_services.metrics import metrics
from cartodb_services.metrics import QuotaService
from cartodb_services.metrics import InternalGeocoderConfig
from cartodb_services.tools import Logger,LoggerConfig
plpy.execute("SELECT cdb_dataservices_server._connect_to_redis('{0}')".format(username))
redis_conn = GD["redis_connection_{0}".format(username)]['redis_metrics_connection']
plpy.execute("SELECT cdb_dataservices_server._get_internal_geocoder_config({0}, {1})".format(plpy.quote_nullable(username), plpy.quote_nullable(orgname)))
user_geocoder_config = GD["user_internal_geocoder_config_{0}".format(username)]
plpy.execute("SELECT cdb_dataservices_server._get_logger_config()")
logger_config = GD["logger_config"]
logger = Logger(logger_config)
quota_service = QuotaService(user_geocoder_config, redis_conn)
params = {'username': username, 'orgname': orgname, 'code': code}
with metrics('cdb_geocode_postalcode_point', user_geocoder_config, logger, params):
try:
plan = plpy.prepare("SELECT cdb_dataservices_server._cdb_geocode_postalcode_point(trim($1)) AS mypoint", ["text"])
rv = plpy.execute(plan, [code], 1)
result = rv[0]["mypoint"]
if result:
quota_service.increment_success_service_use()
return result
else:
quota_service.increment_empty_service_use()
return None
except BaseException as e:
import sys
quota_service.increment_failed_service_use()
logger.error('Error trying to geocode postal code point', sys.exc_info(), data={"username": username, "orgname": orgname})
raise Exception('Error trying to geocode postal code point')
finally:
quota_service.increment_total_service_use()
$$ LANGUAGE plpythonu STABLE PARALLEL RESTRICTED;
CREATE OR REPLACE FUNCTION cdb_dataservices_server.cdb_geocode_ipaddress_point(username text, orgname text, ip text)
RETURNS Geometry AS $$
from cartodb_services.metrics import metrics
from cartodb_services.metrics import QuotaService
from cartodb_services.metrics import InternalGeocoderConfig
from cartodb_services.tools import Logger,LoggerConfig
plpy.execute("SELECT cdb_dataservices_server._connect_to_redis('{0}')".format(username))
redis_conn = GD["redis_connection_{0}".format(username)]['redis_metrics_connection']
plpy.execute("SELECT cdb_dataservices_server._get_internal_geocoder_config({0}, {1})".format(plpy.quote_nullable(username), plpy.quote_nullable(orgname)))
user_geocoder_config = GD["user_internal_geocoder_config_{0}".format(username)]
plpy.execute("SELECT cdb_dataservices_server._get_logger_config()")
logger_config = GD["logger_config"]
logger = Logger(logger_config)
quota_service = QuotaService(user_geocoder_config, redis_conn)
params = {'username': username, 'orgname': orgname, 'ip': ip}
with metrics('cdb_geocode_ipaddress_point', user_geocoder_config, logger):
try:
plan = plpy.prepare("SELECT cdb_dataservices_server._cdb_geocode_ipaddress_point(trim($1)) AS mypoint", ["TEXT"])
rv = plpy.execute(plan, [ip], 1)
result = rv[0]["mypoint"]
if result:
quota_service.increment_success_service_use()
return result
else:
quota_service.increment_empty_service_use()
return None
except BaseException as e:
import sys
quota_service.increment_failed_service_use()
logger.error('Error trying to geocode postal code polygon', sys.exc_info(), data={"username": username, "orgname": orgname})
raise Exception('Error trying to geocode postal code polygon')
finally:
quota_service.increment_total_service_use()
$$ LANGUAGE plpythonu STABLE PARALLEL RESTRICTED;
CREATE OR REPLACE FUNCTION cdb_dataservices_server.cdb_isodistance(username TEXT, orgname TEXT, source geometry(Geometry, 4326), mode TEXT, range integer[], options text[] DEFAULT array[]::text[])
RETURNS SETOF cdb_dataservices_server.isoline AS $$
from cartodb_services.metrics import metrics
from cartodb_services.tools import Logger
plpy.execute("SELECT cdb_dataservices_server._connect_to_redis('{0}')".format(username))
redis_conn = GD["redis_connection_{0}".format(username)]['redis_metrics_connection']
plpy.execute("SELECT cdb_dataservices_server._get_isolines_routing_config({0}, {1})".format(plpy.quote_nullable(username), plpy.quote_nullable(orgname)))
user_isolines_config = GD["user_isolines_routing_config_{0}".format(username)]
plpy.execute("SELECT cdb_dataservices_server._get_logger_config()")
logger_config = GD["logger_config"]
logger = Logger(logger_config)
if user_isolines_config.google_services_user:
raise Exception('This service is not available for google service users.')
params = {'username': username, 'orgname': orgname, 'source': source, 'mode': mode, 'range': range, 'options': options}
with metrics('cdb_isodistance', user_isolines_config, logger, params):
if user_isolines_config.heremaps_provider:
here_plan = plpy.prepare("SELECT * FROM cdb_dataservices_server.cdb_here_isodistance($1, $2, $3, $4, $5, $6) as isoline; ", ["text", "text", "geometry(geometry, 4326)", "text", "integer[]", "text[]"])
return plpy.execute(here_plan, [username, orgname, source, mode, range, options])
elif user_isolines_config.mapzen_provider:
mapzen_plan = plpy.prepare("SELECT * FROM cdb_dataservices_server.cdb_mapzen_isodistance($1, $2, $3, $4, $5, $6) as isoline; ", ["text", "text", "geometry(geometry, 4326)", "text", "integer[]", "text[]"])
return plpy.execute(mapzen_plan, [username, orgname, source, mode, range, options])
elif user_isolines_config.mapbox_provider:
mapbox_plan = plpy.prepare("SELECT * FROM cdb_dataservices_server.cdb_mapbox_isodistance($1, $2, $3, $4, $5, $6) as isoline; ", ["text", "text", "geometry(geometry, 4326)", "text", "integer[]", "text[]"])
return plpy.execute(mapbox_plan, [username, orgname, source, mode, range, options])
elif user_isolines_config.tomtom_provider:
tomtom_plan = plpy.prepare("SELECT * FROM cdb_dataservices_server.cdb_tomtom_isodistance($1, $2, $3, $4, $5, $6) as isoline; ", ["text", "text", "geometry(geometry, 4326)", "text", "integer[]", "text[]"])
return plpy.execute(tomtom_plan, [username, orgname, source, mode, range, options])
else:
raise Exception('Requested isolines provider is not available')
$$ LANGUAGE plpythonu STABLE PARALLEL RESTRICTED;
CREATE OR REPLACE FUNCTION cdb_dataservices_server.cdb_isochrone(username TEXT, orgname TEXT, source geometry(Geometry, 4326), mode TEXT, range integer[], options text[] DEFAULT array[]::text[])
RETURNS SETOF cdb_dataservices_server.isoline AS $$
from cartodb_services.metrics import metrics
from cartodb_services.tools import Logger
plpy.execute("SELECT cdb_dataservices_server._connect_to_redis('{0}')".format(username))
redis_conn = GD["redis_connection_{0}".format(username)]['redis_metrics_connection']
plpy.execute("SELECT cdb_dataservices_server._get_isolines_routing_config({0}, {1})".format(plpy.quote_nullable(username), plpy.quote_nullable(orgname)))
user_isolines_config = GD["user_isolines_routing_config_{0}".format(username)]
plpy.execute("SELECT cdb_dataservices_server._get_logger_config()")
logger_config = GD["logger_config"]
logger = Logger(logger_config)
if user_isolines_config.google_services_user:
raise Exception('This service is not available for google service users.')
params = {'username': username, 'orgname': orgname, 'source': source, 'mode': mode, 'range': range, 'options': options}
with metrics('cdb_isochrone', user_isolines_config, logger, params):
if user_isolines_config.heremaps_provider:
here_plan = plpy.prepare("SELECT * FROM cdb_dataservices_server.cdb_here_isochrone($1, $2, $3, $4, $5, $6) as isoline; ", ["text", "text", "geometry(geometry, 4326)", "text", "integer[]", "text[]"])
return plpy.execute(here_plan, [username, orgname, source, mode, range, options])
elif user_isolines_config.mapzen_provider:
mapzen_plan = plpy.prepare("SELECT * FROM cdb_dataservices_server.cdb_mapzen_isochrone($1, $2, $3, $4, $5, $6) as isoline; ", ["text", "text", "geometry(geometry, 4326)", "text", "integer[]", "text[]"])
return plpy.execute(mapzen_plan, [username, orgname, source, mode, range, options])
elif user_isolines_config.mapbox_provider:
mapbox_plan = plpy.prepare("SELECT * FROM cdb_dataservices_server.cdb_mapbox_isochrone($1, $2, $3, $4, $5, $6) as isoline; ", ["text", "text", "geometry(geometry, 4326)", "text", "integer[]", "text[]"])
return plpy.execute(mapbox_plan, [username, orgname, source, mode, range, options])
elif user_isolines_config.tomtom_provider:
tomtom_plan = plpy.prepare("SELECT * FROM cdb_dataservices_server.cdb_tomtom_isochrone($1, $2, $3, $4, $5, $6) as isoline; ", ["text", "text", "geometry(geometry, 4326)", "text", "integer[]", "text[]"])
return plpy.execute(tomtom_plan, [username, orgname, source, mode, range, options])
else:
raise Exception('Requested isolines provider is not available')
$$ LANGUAGE plpythonu STABLE PARALLEL RESTRICTED;

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,412 @@
--DO NOT MODIFY THIS FILE, IT IS GENERATED AUTOMATICALLY FROM SOURCES
-- Complain if script is sourced in psql, rather than via CREATE EXTENSION
\echo Use "ALTER EXTENSION cdb_dataservices_server UPDATE TO '0.33.0'" to load this file. \quit
-- HERE goes your code to upgrade/downgrade
CREATE OR REPLACE FUNCTION cdb_dataservices_server.cdb_route_point_to_point(
username TEXT,
orgname TEXT,
origin geometry(Point, 4326),
destination geometry(Point, 4326),
mode TEXT,
options text[] DEFAULT ARRAY[]::text[],
units text DEFAULT 'kilometers')
RETURNS cdb_dataservices_server.simple_route AS $$
from cartodb_services.metrics import metrics
from cartodb_services.tools import Logger
plpy.execute("SELECT cdb_dataservices_server._connect_to_redis('{0}')".format(username))
redis_conn = GD["redis_connection_{0}".format(username)]['redis_metrics_connection']
plpy.execute("SELECT cdb_dataservices_server._get_routing_config({0}, {1})".format(plpy.quote_nullable(username), plpy.quote_nullable(orgname)))
user_routing_config = GD["user_routing_config_{0}".format(username)]
plpy.execute("SELECT cdb_dataservices_server._get_logger_config()")
logger_config = GD["logger_config"]
logger = Logger(logger_config)
params = {'origin': origin, 'destination': destination, 'mode': mode, 'options': options, 'units': units}
with metrics('cdb_route_with_point', user_routing_config, logger, params):
waypoints = [origin, destination]
if user_routing_config.mapzen_provider:
mapzen_plan = plpy.prepare("SELECT * FROM cdb_dataservices_server._cdb_mapzen_route_with_waypoints($1, $2, $3, $4) as route;", ["text", "text", "geometry(Point, 4326)[]", "text"])
result = plpy.execute(mapzen_plan, [username, orgname, waypoints, mode])
return [result[0]['shape'],result[0]['length'], result[0]['duration']]
elif user_routing_config.mapbox_provider:
mapbox_plan = plpy.prepare("SELECT * FROM cdb_dataservices_server._cdb_mapbox_route_with_waypoints($1, $2, $3, $4) as route;", ["text", "text", "geometry(Point, 4326)[]", "text"])
result = plpy.execute(mapbox_plan, [username, orgname, waypoints, mode])
return [result[0]['shape'],result[0]['length'], result[0]['duration']]
elif user_routing_config.tomtom_provider:
tomtom_plan = plpy.prepare("SELECT * FROM cdb_dataservices_server._cdb_tomtom_route_with_waypoints($1, $2, $3, $4) as route;", ["text", "text", "geometry(Point, 4326)[]", "text"])
result = plpy.execute(tomtom_plan, [username, orgname, waypoints, mode])
return [result[0]['shape'],result[0]['length'], result[0]['duration']]
else:
raise Exception('Requested routing method is not available')
$$ LANGUAGE plpythonu STABLE PARALLEL RESTRICTED;
CREATE OR REPLACE FUNCTION cdb_dataservices_server.cdb_route_with_waypoints(
username TEXT,
orgname TEXT,
waypoints geometry(Point, 4326)[],
mode TEXT,
options text[] DEFAULT ARRAY[]::text[],
units text DEFAULT 'kilometers')
RETURNS cdb_dataservices_server.simple_route AS $$
from cartodb_services.metrics import metrics
from cartodb_services.tools import Logger
plpy.execute("SELECT cdb_dataservices_server._connect_to_redis('{0}')".format(username))
redis_conn = GD["redis_connection_{0}".format(username)]['redis_metrics_connection']
plpy.execute("SELECT cdb_dataservices_server._get_routing_config({0}, {1})".format(plpy.quote_nullable(username), plpy.quote_nullable(orgname)))
user_routing_config = GD["user_routing_config_{0}".format(username)]
plpy.execute("SELECT cdb_dataservices_server._get_logger_config()")
logger_config = GD["logger_config"]
logger = Logger(logger_config)
params = {'waypoints': waypoints, 'mode': mode, 'options': options, 'units': units}
with metrics('cdb_route_with_waypoints', user_routing_config, logger, params):
if user_routing_config.mapzen_provider:
mapzen_plan = plpy.prepare("SELECT * FROM cdb_dataservices_server._cdb_mapzen_route_with_waypoints($1, $2, $3, $4) as route;", ["text", "text", "geometry(Point, 4326)[]", "text"])
result = plpy.execute(mapzen_plan, [username, orgname, waypoints, mode])
return [result[0]['shape'],result[0]['length'], result[0]['duration']]
elif user_routing_config.mapbox_provider:
mapbox_plan = plpy.prepare("SELECT * FROM cdb_dataservices_server._cdb_mapbox_route_with_waypoints($1, $2, $3, $4) as route;", ["text", "text", "geometry(Point, 4326)[]", "text"])
result = plpy.execute(mapbox_plan, [username, orgname, waypoints, mode])
return [result[0]['shape'],result[0]['length'], result[0]['duration']]
elif user_routing_config.tomtom_provider:
tomtom_plan = plpy.prepare("SELECT * FROM cdb_dataservices_server._cdb_tomtom_route_with_waypoints($1, $2, $3, $4) as route;", ["text", "text", "geometry(Point, 4326)[]", "text"])
result = plpy.execute(tomtom_plan, [username, orgname, waypoints, mode])
return [result[0]['shape'],result[0]['length'], result[0]['duration']]
else:
raise Exception('Requested routing method is not available')
$$ LANGUAGE plpythonu STABLE PARALLEL RESTRICTED;
CREATE OR REPLACE FUNCTION cdb_dataservices_server.cdb_geocode_street_point(username TEXT, orgname TEXT, searchtext TEXT, city TEXT DEFAULT NULL, state_province TEXT DEFAULT NULL, country TEXT DEFAULT NULL)
RETURNS Geometry AS $$
from cartodb_services.metrics import metrics
from cartodb_services.tools import Logger,LoggerConfig
plpy.execute("SELECT cdb_dataservices_server._connect_to_redis('{0}')".format(username))
redis_conn = GD["redis_connection_{0}".format(username)]['redis_metrics_connection']
plpy.execute("SELECT cdb_dataservices_server._get_geocoder_config({0}, {1})".format(plpy.quote_nullable(username), plpy.quote_nullable(orgname)))
user_geocoder_config = GD["user_geocoder_config_{0}".format(username)]
plpy.execute("SELECT cdb_dataservices_server._get_logger_config()")
logger_config = GD["logger_config"]
logger = Logger(logger_config)
params = {'searchtext': searchtext, 'city': city, 'state_province': state_province, 'country': country}
with metrics('cdb_geocode_street_point', user_geocoder_config, logger, params):
if user_geocoder_config.heremaps_geocoder:
here_plan = plpy.prepare("SELECT cdb_dataservices_server._cdb_here_geocode_street_point($1, $2, $3, $4, $5, $6) as point; ", ["text", "text", "text", "text", "text", "text"])
return plpy.execute(here_plan, [username, orgname, searchtext, city, state_province, country], 1)[0]['point']
elif user_geocoder_config.google_geocoder:
google_plan = plpy.prepare("SELECT cdb_dataservices_server._cdb_google_geocode_street_point($1, $2, $3, $4, $5, $6) as point; ", ["text", "text", "text", "text", "text", "text"])
return plpy.execute(google_plan, [username, orgname, searchtext, city, state_province, country], 1)[0]['point']
elif user_geocoder_config.mapzen_geocoder:
mapzen_plan = plpy.prepare("SELECT cdb_dataservices_server._cdb_mapzen_geocode_street_point($1, $2, $3, $4, $5, $6) as point; ", ["text", "text", "text", "text", "text", "text"])
return plpy.execute(mapzen_plan, [username, orgname, searchtext, city, state_province, country], 1)[0]['point']
elif user_geocoder_config.mapbox_geocoder:
mapbox_plan = plpy.prepare("SELECT cdb_dataservices_server._cdb_mapbox_geocode_street_point($1, $2, $3, $4, $5, $6) as point; ", ["text", "text", "text", "text", "text", "text"])
return plpy.execute(mapbox_plan, [username, orgname, searchtext, city, state_province, country], 1)[0]['point']
elif user_geocoder_config.tomtom_geocoder:
tomtom_plan = plpy.prepare("SELECT cdb_dataservices_server._cdb_tomtom_geocode_street_point($1, $2, $3, $4, $5, $6) as point; ", ["text", "text", "text", "text", "text", "text"])
return plpy.execute(tomtom_plan, [username, orgname, searchtext, city, state_province, country], 1)[0]['point']
else:
raise Exception('Requested geocoder is not available')
$$ LANGUAGE plpythonu STABLE PARALLEL RESTRICTED;
CREATE OR REPLACE FUNCTION cdb_dataservices_server._cdb_bulk_geocode_street_point(username TEXT, orgname TEXT, searches jsonb)
RETURNS SETOF cdb_dataservices_server.geocoding AS $$
from cartodb_services.metrics import metrics
from cartodb_services.tools import Logger
plpy.execute("SELECT cdb_dataservices_server._connect_to_redis('{0}')".format(username))
redis_conn = GD["redis_connection_{0}".format(username)]['redis_metrics_connection']
plpy.execute("SELECT cdb_dataservices_server._get_geocoder_config({0}, {1})".format(plpy.quote_nullable(username), plpy.quote_nullable(orgname)))
user_geocoder_config = GD["user_geocoder_config_{0}".format(username)]
plpy.execute("SELECT cdb_dataservices_server._get_logger_config()")
logger_config = GD["logger_config"]
logger = Logger(logger_config)
params = {'searches': searches}
with metrics('cdb_bulk_geocode_street_point', user_geocoder_config, logger, params):
if user_geocoder_config.google_geocoder:
provider_function = "_cdb_bulk_google_geocode_street_point";
elif user_geocoder_config.heremaps_geocoder:
provider_function = "_cdb_bulk_heremaps_geocode_street_point";
elif user_geocoder_config.tomtom_geocoder:
provider_function = "_cdb_bulk_tomtom_geocode_street_point";
elif user_geocoder_config.mapbox_geocoder:
provider_function = "_cdb_bulk_mapbox_geocode_street_point";
else:
raise Exception('Requested geocoder is not available')
plan = plpy.prepare("SELECT * FROM cdb_dataservices_server.{}($1, $2, $3); ".format(provider_function), ["text", "text", "jsonb"])
return plpy.execute(plan, [username, orgname, searches])
$$ LANGUAGE plpythonu STABLE PARALLEL RESTRICTED;
CREATE OR REPLACE FUNCTION cdb_dataservices_server.cdb_geocode_admin0_polygon(username text, orgname text, country_name text)
RETURNS Geometry AS $$
from cartodb_services.metrics import QuotaService
from cartodb_services.metrics import InternalGeocoderConfig
from cartodb_services.metrics import metrics
from cartodb_services.tools import Logger,LoggerConfig
plpy.execute("SELECT cdb_dataservices_server._connect_to_redis('{0}')".format(username))
redis_conn = GD["redis_connection_{0}".format(username)]['redis_metrics_connection']
plpy.execute("SELECT cdb_dataservices_server._get_internal_geocoder_config({0}, {1})".format(plpy.quote_nullable(username), plpy.quote_nullable(orgname)))
user_geocoder_config = GD["user_internal_geocoder_config_{0}".format(username)]
plpy.execute("SELECT cdb_dataservices_server._get_logger_config()")
logger_config = GD["logger_config"]
logger = Logger(logger_config)
quota_service = QuotaService(user_geocoder_config, redis_conn)
with metrics('cdb_geocode_admin0_polygon', user_geocoder_config, logger):
try:
plan = plpy.prepare("SELECT cdb_dataservices_server._cdb_geocode_admin0_polygon(trim($1)) AS mypolygon", ["text"])
rv = plpy.execute(plan, [country_name], 1)
result = rv[0]["mypolygon"]
if result:
quota_service.increment_success_service_use()
return result
else:
quota_service.increment_empty_service_use()
return None
except BaseException as e:
import sys
quota_service.increment_failed_service_use()
logger.error('Error trying to geocode admin0 polygon', sys.exc_info(), data={"username": username, "orgname": orgname})
raise Exception('Error trying to geocode admin0 polygon')
finally:
quota_service.increment_total_service_use()
$$ LANGUAGE plpythonu STABLE PARALLEL RESTRICTED;
CREATE OR REPLACE FUNCTION cdb_dataservices_server.cdb_geocode_admin1_polygon(username text, orgname text, admin1_name text)
RETURNS Geometry AS $$
from cartodb_services.metrics import metrics
from cartodb_services.metrics import QuotaService
from cartodb_services.metrics import InternalGeocoderConfig
from cartodb_services.tools import Logger,LoggerConfig
plpy.execute("SELECT cdb_dataservices_server._connect_to_redis('{0}')".format(username))
redis_conn = GD["redis_connection_{0}".format(username)]['redis_metrics_connection']
plpy.execute("SELECT cdb_dataservices_server._get_internal_geocoder_config({0}, {1})".format(plpy.quote_nullable(username), plpy.quote_nullable(orgname)))
user_geocoder_config = GD["user_internal_geocoder_config_{0}".format(username)]
plpy.execute("SELECT cdb_dataservices_server._get_logger_config()")
logger_config = GD["logger_config"]
logger = Logger(logger_config)
quota_service = QuotaService(user_geocoder_config, redis_conn)
with metrics('cdb_geocode_admin1_polygon', user_geocoder_config, logger):
try:
plan = plpy.prepare("SELECT cdb_dataservices_server._cdb_geocode_admin1_polygon(trim($1)) AS mypolygon", ["text"])
rv = plpy.execute(plan, [admin1_name], 1)
result = rv[0]["mypolygon"]
if result:
quota_service.increment_success_service_use()
return result
else:
quota_service.increment_empty_service_use()
return None
except BaseException as e:
import sys
quota_service.increment_failed_service_use()
logger.error('Error trying to geocode admin1 polygon', sys.exc_info(), data={"username": username, "orgname": orgname})
raise Exception('Error trying to geocode admin1 polygon')
finally:
quota_service.increment_total_service_use()
$$ LANGUAGE plpythonu STABLE PARALLEL RESTRICTED;
CREATE OR REPLACE FUNCTION cdb_dataservices_server._cdb_internal_geocode_namedplace(username text, orgname text, city_name text, admin1_name text DEFAULT NULL, country_name text DEFAULT NULL)
RETURNS Geometry AS $$
from cartodb_services.metrics import QuotaService
from cartodb_services.metrics import InternalGeocoderConfig, metrics
from cartodb_services.tools import Logger,LoggerConfig
plpy.execute("SELECT cdb_dataservices_server._connect_to_redis('{0}')".format(username))
redis_conn = GD["redis_connection_{0}".format(username)]['redis_metrics_connection']
plpy.execute("SELECT cdb_dataservices_server._get_internal_geocoder_config({0}, {1})".format(plpy.quote_nullable(username), plpy.quote_nullable(orgname)))
user_geocoder_config = GD["user_internal_geocoder_config_{0}".format(username)]
plpy.execute("SELECT cdb_dataservices_server._get_logger_config()")
logger_config = GD["logger_config"]
logger = Logger(logger_config)
quota_service = QuotaService(user_geocoder_config, redis_conn)
with metrics('cdb_geocode_namedplace_point', user_geocoder_config, logger):
try:
if admin1_name and country_name:
plan = plpy.prepare("SELECT cdb_dataservices_server._cdb_geocode_namedplace_point(trim($1), trim($2), trim($3)) AS mypoint", ["text", "text", "text"])
rv = plpy.execute(plan, [city_name, admin1_name, country_name], 1)
elif country_name:
plan = plpy.prepare("SELECT cdb_dataservices_server._cdb_geocode_namedplace_point(trim($1), trim($2)) AS mypoint", ["text", "text"])
rv = plpy.execute(plan, [city_name, country_name], 1)
else:
plan = plpy.prepare("SELECT cdb_dataservices_server._cdb_geocode_namedplace_point(trim($1)) AS mypoint", ["text"])
rv = plpy.execute(plan, [city_name], 1)
result = rv[0]["mypoint"]
if result:
quota_service.increment_success_service_use()
return result
else:
quota_service.increment_empty_service_use()
return None
except BaseException as e:
import sys
quota_service.increment_failed_service_use()
logger.error('Error trying to geocode namedplace point', sys.exc_info(), data={"username": username, "orgname": orgname})
raise Exception('Error trying to geocode namedplace point')
finally:
quota_service.increment_total_service_use()
$$ LANGUAGE plpythonu STABLE PARALLEL RESTRICTED;
CREATE OR REPLACE FUNCTION cdb_dataservices_server.cdb_geocode_postalcode_point(username text, orgname text, code text)
RETURNS Geometry AS $$
from cartodb_services.metrics import metrics
from cartodb_services.metrics import QuotaService
from cartodb_services.metrics import InternalGeocoderConfig
from cartodb_services.tools import Logger,LoggerConfig
plpy.execute("SELECT cdb_dataservices_server._connect_to_redis('{0}')".format(username))
redis_conn = GD["redis_connection_{0}".format(username)]['redis_metrics_connection']
plpy.execute("SELECT cdb_dataservices_server._get_internal_geocoder_config({0}, {1})".format(plpy.quote_nullable(username), plpy.quote_nullable(orgname)))
user_geocoder_config = GD["user_internal_geocoder_config_{0}".format(username)]
plpy.execute("SELECT cdb_dataservices_server._get_logger_config()")
logger_config = GD["logger_config"]
logger = Logger(logger_config)
quota_service = QuotaService(user_geocoder_config, redis_conn)
with metrics('cdb_geocode_postalcode_point', user_geocoder_config, logger):
try:
plan = plpy.prepare("SELECT cdb_dataservices_server._cdb_geocode_postalcode_point(trim($1)) AS mypoint", ["text"])
rv = plpy.execute(plan, [code], 1)
result = rv[0]["mypoint"]
if result:
quota_service.increment_success_service_use()
return result
else:
quota_service.increment_empty_service_use()
return None
except BaseException as e:
import sys
quota_service.increment_failed_service_use()
logger.error('Error trying to geocode postal code point', sys.exc_info(), data={"username": username, "orgname": orgname})
raise Exception('Error trying to geocode postal code point')
finally:
quota_service.increment_total_service_use()
$$ LANGUAGE plpythonu STABLE PARALLEL RESTRICTED;
CREATE OR REPLACE FUNCTION cdb_dataservices_server.cdb_geocode_ipaddress_point(username text, orgname text, ip text)
RETURNS Geometry AS $$
from cartodb_services.metrics import metrics
from cartodb_services.metrics import QuotaService
from cartodb_services.metrics import InternalGeocoderConfig
from cartodb_services.tools import Logger,LoggerConfig
plpy.execute("SELECT cdb_dataservices_server._connect_to_redis('{0}')".format(username))
redis_conn = GD["redis_connection_{0}".format(username)]['redis_metrics_connection']
plpy.execute("SELECT cdb_dataservices_server._get_internal_geocoder_config({0}, {1})".format(plpy.quote_nullable(username), plpy.quote_nullable(orgname)))
user_geocoder_config = GD["user_internal_geocoder_config_{0}".format(username)]
plpy.execute("SELECT cdb_dataservices_server._get_logger_config()")
logger_config = GD["logger_config"]
logger = Logger(logger_config)
quota_service = QuotaService(user_geocoder_config, redis_conn)
with metrics('cdb_geocode_ipaddress_point', user_geocoder_config, logger):
try:
plan = plpy.prepare("SELECT cdb_dataservices_server._cdb_geocode_ipaddress_point(trim($1)) AS mypoint", ["TEXT"])
rv = plpy.execute(plan, [ip], 1)
result = rv[0]["mypoint"]
if result:
quota_service.increment_success_service_use()
return result
else:
quota_service.increment_empty_service_use()
return None
except BaseException as e:
import sys
quota_service.increment_failed_service_use()
logger.error('Error trying to geocode postal code polygon', sys.exc_info(), data={"username": username, "orgname": orgname})
raise Exception('Error trying to geocode postal code polygon')
finally:
quota_service.increment_total_service_use()
$$ LANGUAGE plpythonu STABLE PARALLEL RESTRICTED;
CREATE OR REPLACE FUNCTION cdb_dataservices_server.cdb_isodistance(username TEXT, orgname TEXT, source geometry(Geometry, 4326), mode TEXT, range integer[], options text[] DEFAULT array[]::text[])
RETURNS SETOF cdb_dataservices_server.isoline AS $$
from cartodb_services.metrics import metrics
from cartodb_services.tools import Logger
plpy.execute("SELECT cdb_dataservices_server._connect_to_redis('{0}')".format(username))
redis_conn = GD["redis_connection_{0}".format(username)]['redis_metrics_connection']
plpy.execute("SELECT cdb_dataservices_server._get_isolines_routing_config({0}, {1})".format(plpy.quote_nullable(username), plpy.quote_nullable(orgname)))
user_isolines_config = GD["user_isolines_routing_config_{0}".format(username)]
plpy.execute("SELECT cdb_dataservices_server._get_logger_config()")
logger_config = GD["logger_config"]
logger = Logger(logger_config)
if user_isolines_config.google_services_user:
raise Exception('This service is not available for google service users.')
params = {'source': source, 'mode': mode, 'range': range, 'options': options}
with metrics('cdb_isodistance', user_isolines_config, logger, params):
if user_isolines_config.heremaps_provider:
here_plan = plpy.prepare("SELECT * FROM cdb_dataservices_server.cdb_here_isodistance($1, $2, $3, $4, $5, $6) as isoline; ", ["text", "text", "geometry(geometry, 4326)", "text", "integer[]", "text[]"])
return plpy.execute(here_plan, [username, orgname, source, mode, range, options])
elif user_isolines_config.mapzen_provider:
mapzen_plan = plpy.prepare("SELECT * FROM cdb_dataservices_server.cdb_mapzen_isodistance($1, $2, $3, $4, $5, $6) as isoline; ", ["text", "text", "geometry(geometry, 4326)", "text", "integer[]", "text[]"])
return plpy.execute(mapzen_plan, [username, orgname, source, mode, range, options])
elif user_isolines_config.mapbox_provider:
mapbox_plan = plpy.prepare("SELECT * FROM cdb_dataservices_server.cdb_mapbox_isodistance($1, $2, $3, $4, $5, $6) as isoline; ", ["text", "text", "geometry(geometry, 4326)", "text", "integer[]", "text[]"])
return plpy.execute(mapbox_plan, [username, orgname, source, mode, range, options])
elif user_isolines_config.tomtom_provider:
tomtom_plan = plpy.prepare("SELECT * FROM cdb_dataservices_server.cdb_tomtom_isodistance($1, $2, $3, $4, $5, $6) as isoline; ", ["text", "text", "geometry(geometry, 4326)", "text", "integer[]", "text[]"])
return plpy.execute(tomtom_plan, [username, orgname, source, mode, range, options])
else:
raise Exception('Requested isolines provider is not available')
$$ LANGUAGE plpythonu STABLE PARALLEL RESTRICTED;
CREATE OR REPLACE FUNCTION cdb_dataservices_server.cdb_isochrone(username TEXT, orgname TEXT, source geometry(Geometry, 4326), mode TEXT, range integer[], options text[] DEFAULT array[]::text[])
RETURNS SETOF cdb_dataservices_server.isoline AS $$
from cartodb_services.metrics import metrics
from cartodb_services.tools import Logger
plpy.execute("SELECT cdb_dataservices_server._connect_to_redis('{0}')".format(username))
redis_conn = GD["redis_connection_{0}".format(username)]['redis_metrics_connection']
plpy.execute("SELECT cdb_dataservices_server._get_isolines_routing_config({0}, {1})".format(plpy.quote_nullable(username), plpy.quote_nullable(orgname)))
user_isolines_config = GD["user_isolines_routing_config_{0}".format(username)]
plpy.execute("SELECT cdb_dataservices_server._get_logger_config()")
logger_config = GD["logger_config"]
logger = Logger(logger_config)
if user_isolines_config.google_services_user:
raise Exception('This service is not available for google service users.')
params = {'source': source, 'mode': mode, 'range': range, 'options': options}
with metrics('cdb_isochrone', user_isolines_config, logger, params):
if user_isolines_config.heremaps_provider:
here_plan = plpy.prepare("SELECT * FROM cdb_dataservices_server.cdb_here_isochrone($1, $2, $3, $4, $5, $6) as isoline; ", ["text", "text", "geometry(geometry, 4326)", "text", "integer[]", "text[]"])
return plpy.execute(here_plan, [username, orgname, source, mode, range, options])
elif user_isolines_config.mapzen_provider:
mapzen_plan = plpy.prepare("SELECT * FROM cdb_dataservices_server.cdb_mapzen_isochrone($1, $2, $3, $4, $5, $6) as isoline; ", ["text", "text", "geometry(geometry, 4326)", "text", "integer[]", "text[]"])
return plpy.execute(mapzen_plan, [username, orgname, source, mode, range, options])
elif user_isolines_config.mapbox_provider:
mapbox_plan = plpy.prepare("SELECT * FROM cdb_dataservices_server.cdb_mapbox_isochrone($1, $2, $3, $4, $5, $6) as isoline; ", ["text", "text", "geometry(geometry, 4326)", "text", "integer[]", "text[]"])
return plpy.execute(mapbox_plan, [username, orgname, source, mode, range, options])
elif user_isolines_config.tomtom_provider:
tomtom_plan = plpy.prepare("SELECT * FROM cdb_dataservices_server.cdb_tomtom_isochrone($1, $2, $3, $4, $5, $6) as isoline; ", ["text", "text", "geometry(geometry, 4326)", "text", "integer[]", "text[]"])
return plpy.execute(tomtom_plan, [username, orgname, source, mode, range, options])
else:
raise Exception('Requested isolines provider is not available')
$$ LANGUAGE plpythonu STABLE PARALLEL RESTRICTED;

View File

@@ -0,0 +1,182 @@
--DO NOT MODIFY THIS FILE, IT IS GENERATED AUTOMATICALLY FROM SOURCES
-- Complain if script is sourced in psql, rather than via CREATE EXTENSION
\echo Use "ALTER EXTENSION cdb_dataservices_server UPDATE TO '0.34.1'" to load this file. \quit
-- HERE goes your code to upgrade/downgrade
CREATE OR REPLACE FUNCTION cdb_dataservices_server._cdb_mapzen_isochrones(
username TEXT,
orgname TEXT,
source geometry(Geometry, 4326),
mode TEXT,
data_range integer[],
options text[])
RETURNS SETOF cdb_dataservices_server.isoline AS $$
import json
from cartodb_services.mapzen import MatrixClient, MapzenIsochrones
from cartodb_services.metrics import QuotaService
from cartodb_services.tools import Logger,LoggerConfig
from cartodb_services.mapzen.types import coordinates_to_polygon
redis_conn = GD["redis_connection_{0}".format(username)]['redis_metrics_connection']
user_isolines_routing_config = GD["user_isolines_routing_config_{0}".format(username)]
plpy.execute("SELECT cdb_dataservices_server._get_logger_config()")
logger_config = GD["logger_config"]
logger = Logger(logger_config)
# -- Check the quota
quota_service = QuotaService(user_isolines_routing_config, redis_conn)
if not quota_service.check_user_quota():
raise Exception('You have reached the limit of your quota')
try:
mapzen_isochrones = MapzenIsochrones(user_isolines_routing_config.mapzen_matrix_api_key,
logger, user_isolines_routing_config.mapzen_isochrones_service_params)
if source:
lat = plpy.execute("SELECT ST_Y('%s') AS lat" % source)[0]['lat']
lon = plpy.execute("SELECT ST_X('%s') AS lon" % source)[0]['lon']
origin = {'lat': lat, 'lon': lon}
else:
raise Exception('source is NULL')
resp = mapzen_isochrones.isochrone(origin, mode, data_range)
if resp:
result = []
for isochrone in resp:
result_polygon = coordinates_to_polygon(isochrone.coordinates)
if result_polygon:
result.append([source, isochrone.duration, result_polygon])
else:
result.append([source, isochrone.duration, None])
quota_service.increment_success_service_use()
quota_service.increment_isolines_service_use(len(result))
return result
else:
quota_service.increment_empty_service_use()
return []
except BaseException as e:
import sys
quota_service.increment_failed_service_use()
logger.error('Error trying to get mapzen isochrones', sys.exc_info(), data={"username": username, "orgname": orgname})
raise Exception('Error trying to get mapzen isochrones')
finally:
quota_service.increment_total_service_use()
$$ LANGUAGE plpythonu SECURITY DEFINER STABLE PARALLEL RESTRICTED;
CREATE OR REPLACE FUNCTION cdb_dataservices_server._cdb_mapbox_isochrones(
username TEXT,
orgname TEXT,
source geometry(Geometry, 4326),
mode TEXT,
data_range integer[],
options text[])
RETURNS SETOF cdb_dataservices_server.isoline AS $$
from cartodb_services.tools import ServiceManager
from cartodb_services.mapbox import MapboxMatrixClient, MapboxIsolines
from cartodb_services.mapbox.types import TRANSPORT_MODE_TO_MAPBOX
from cartodb_services.tools import Coordinate
from cartodb_services.tools.coordinates import coordinates_to_polygon
from cartodb_services.refactor.service.mapbox_isolines_config import MapboxIsolinesConfigBuilder
import cartodb_services
cartodb_services.init(plpy, GD)
service_manager = ServiceManager('isolines', MapboxIsolinesConfigBuilder, username, orgname, GD)
service_manager.assert_within_limits()
try:
client = MapboxMatrixClient(service_manager.config.mapbox_api_key, service_manager.logger, service_manager.config.service_params)
mapbox_isolines = MapboxIsolines(client, service_manager.logger)
if source:
lat = plpy.execute("SELECT ST_Y('%s') AS lat" % source)[0]['lat']
lon = plpy.execute("SELECT ST_X('%s') AS lon" % source)[0]['lon']
origin = Coordinate(lon,lat)
else:
raise Exception('source is NULL')
profile = TRANSPORT_MODE_TO_MAPBOX.get(mode)
resp = mapbox_isolines.calculate_isochrone(origin, data_range, profile)
if resp:
result = []
for isochrone in resp:
result_polygon = coordinates_to_polygon(isochrone.coordinates)
if result_polygon:
result.append([source, isochrone.duration, result_polygon])
else:
result.append([source, isochrone.duration, None])
service_manager.quota_service.increment_success_service_use()
service_manager.quota_service.increment_isolines_service_use(len(result))
return result
else:
service_manager.quota_service.increment_empty_service_use()
return []
except BaseException as e:
import sys
service_manager.quota_service.increment_failed_service_use()
service_manager.logger.error('Error trying to get Mapbox isochrones', sys.exc_info(), data={"username": username, "orgname": orgname})
raise Exception('Error trying to get Mapbox isochrones')
finally:
service_manager.quota_service.increment_total_service_use()
$$ LANGUAGE plpythonu SECURITY DEFINER STABLE PARALLEL RESTRICTED;
CREATE OR REPLACE FUNCTION cdb_dataservices_server._cdb_tomtom_isochrones(
username TEXT,
orgname TEXT,
source geometry(Geometry, 4326),
mode TEXT,
data_range integer[],
options text[])
RETURNS SETOF cdb_dataservices_server.isoline AS $$
from cartodb_services.tools import ServiceManager
from cartodb_services.tomtom import TomTomIsolines
from cartodb_services.tomtom.types import TRANSPORT_MODE_TO_TOMTOM
from cartodb_services.tools import Coordinate
from cartodb_services.tools.coordinates import coordinates_to_polygon
from cartodb_services.refactor.service.tomtom_isolines_config import TomTomIsolinesConfigBuilder
import cartodb_services
cartodb_services.init(plpy, GD)
service_manager = ServiceManager('isolines', TomTomIsolinesConfigBuilder, username, orgname, GD)
service_manager.assert_within_limits()
try:
tomtom_isolines = TomTomIsolines(service_manager.config.tomtom_api_key, service_manager.logger, service_manager.config.service_params)
if source:
lat = plpy.execute("SELECT ST_Y('%s') AS lat" % source)[0]['lat']
lon = plpy.execute("SELECT ST_X('%s') AS lon" % source)[0]['lon']
origin = Coordinate(lon,lat)
else:
raise Exception('source is NULL')
profile = TRANSPORT_MODE_TO_TOMTOM.get(mode)
resp = tomtom_isolines.calculate_isochrone(origin, data_range, profile)
if resp:
result = []
for isochrone in resp:
result_polygon = coordinates_to_polygon(isochrone.coordinates)
if result_polygon:
result.append([source, isochrone.duration, result_polygon])
else:
result.append([source, isochrone.duration, None])
service_manager.quota_service.increment_success_service_use()
service_manager.quota_service.increment_isolines_service_use(len(result))
return result
else:
service_manager.quota_service.increment_empty_service_use()
return []
except BaseException as e:
import sys
service_manager.quota_service.increment_failed_service_use()
service_manager.logger.error('Error trying to get TomTom isochrones', sys.exc_info(), data={"username": username, "orgname": orgname})
raise Exception('Error trying to get TomTom isochrones')
finally:
service_manager.quota_service.increment_total_service_use()
$$ LANGUAGE plpythonu SECURITY DEFINER STABLE PARALLEL RESTRICTED;

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,188 @@
--DO NOT MODIFY THIS FILE, IT IS GENERATED AUTOMATICALLY FROM SOURCES
-- Complain if script is sourced in psql, rather than via CREATE EXTENSION
\echo Use "ALTER EXTENSION cdb_dataservices_server UPDATE TO '0.34.0'" to load this file. \quit
-- HERE goes your code to upgrade/downgrade
CREATE OR REPLACE FUNCTION cdb_dataservices_server._cdb_mapzen_isochrones(
username TEXT,
orgname TEXT,
source geometry(Geometry, 4326),
mode TEXT,
data_range integer[],
options text[])
RETURNS SETOF cdb_dataservices_server.isoline AS $$
import json
from cartodb_services.mapzen import MatrixClient, MapzenIsochrones
from cartodb_services.metrics import QuotaService
from cartodb_services.tools import Logger,LoggerConfig
from cartodb_services.mapzen.types import coordinates_to_polygon
redis_conn = GD["redis_connection_{0}".format(username)]['redis_metrics_connection']
user_isolines_routing_config = GD["user_isolines_routing_config_{0}".format(username)]
plpy.execute("SELECT cdb_dataservices_server._get_logger_config()")
logger_config = GD["logger_config"]
logger = Logger(logger_config)
# -- Check the quota
quota_service = QuotaService(user_isolines_routing_config, redis_conn)
if not quota_service.check_user_quota():
raise Exception('You have reached the limit of your quota')
try:
mapzen_isochrones = MapzenIsochrones(user_isolines_routing_config.mapzen_matrix_api_key,
logger, user_isolines_routing_config.mapzen_isochrones_service_params)
if source:
lat = plpy.execute("SELECT ST_Y('%s') AS lat" % source)[0]['lat']
lon = plpy.execute("SELECT ST_X('%s') AS lon" % source)[0]['lon']
origin = {'lat': lat, 'lon': lon}
else:
raise Exception('source is NULL')
resp = mapzen_isochrones.isochrone(origin, mode, data_range)
if resp:
result = []
for isochrone in resp:
result_polygon = coordinates_to_polygon(isochrone.coordinates)
if result_polygon:
quota_service.increment_success_service_use()
result.append([source, isochrone.duration, result_polygon])
else:
quota_service.increment_empty_service_use()
result.append([source, isochrone.duration, None])
quota_service.increment_success_service_use()
quota_service.increment_isolines_service_use(len(result))
return result
else:
quota_service.increment_empty_service_use()
return []
except BaseException as e:
import sys
quota_service.increment_failed_service_use()
logger.error('Error trying to get mapzen isochrones', sys.exc_info(), data={"username": username, "orgname": orgname})
raise Exception('Error trying to get mapzen isochrones')
finally:
quota_service.increment_total_service_use()
$$ LANGUAGE plpythonu SECURITY DEFINER STABLE PARALLEL RESTRICTED;
CREATE OR REPLACE FUNCTION cdb_dataservices_server._cdb_mapbox_isochrones(
username TEXT,
orgname TEXT,
source geometry(Geometry, 4326),
mode TEXT,
data_range integer[],
options text[])
RETURNS SETOF cdb_dataservices_server.isoline AS $$
from cartodb_services.tools import ServiceManager
from cartodb_services.mapbox import MapboxMatrixClient, MapboxIsolines
from cartodb_services.mapbox.types import TRANSPORT_MODE_TO_MAPBOX
from cartodb_services.tools import Coordinate
from cartodb_services.tools.coordinates import coordinates_to_polygon
from cartodb_services.refactor.service.mapbox_isolines_config import MapboxIsolinesConfigBuilder
import cartodb_services
cartodb_services.init(plpy, GD)
service_manager = ServiceManager('isolines', MapboxIsolinesConfigBuilder, username, orgname, GD)
service_manager.assert_within_limits()
try:
client = MapboxMatrixClient(service_manager.config.mapbox_api_key, service_manager.logger, service_manager.config.service_params)
mapbox_isolines = MapboxIsolines(client, service_manager.logger)
if source:
lat = plpy.execute("SELECT ST_Y('%s') AS lat" % source)[0]['lat']
lon = plpy.execute("SELECT ST_X('%s') AS lon" % source)[0]['lon']
origin = Coordinate(lon,lat)
else:
raise Exception('source is NULL')
profile = TRANSPORT_MODE_TO_MAPBOX.get(mode)
resp = mapbox_isolines.calculate_isochrone(origin, data_range, profile)
if resp:
result = []
for isochrone in resp:
result_polygon = coordinates_to_polygon(isochrone.coordinates)
if result_polygon:
service_manager.quota_service.increment_success_service_use()
result.append([source, isochrone.duration, result_polygon])
else:
service_manager.quota_service.increment_empty_service_use()
result.append([source, isochrone.duration, None])
service_manager.quota_service.increment_success_service_use()
service_manager.quota_service.increment_isolines_service_use(len(result))
return result
else:
service_manager.quota_service.increment_empty_service_use()
return []
except BaseException as e:
import sys
service_manager.quota_service.increment_failed_service_use()
service_manager.logger.error('Error trying to get Mapbox isochrones', sys.exc_info(), data={"username": username, "orgname": orgname})
raise Exception('Error trying to get Mapbox isochrones')
finally:
service_manager.quota_service.increment_total_service_use()
$$ LANGUAGE plpythonu SECURITY DEFINER STABLE PARALLEL RESTRICTED;
CREATE OR REPLACE FUNCTION cdb_dataservices_server._cdb_tomtom_isochrones(
username TEXT,
orgname TEXT,
source geometry(Geometry, 4326),
mode TEXT,
data_range integer[],
options text[])
RETURNS SETOF cdb_dataservices_server.isoline AS $$
from cartodb_services.tools import ServiceManager
from cartodb_services.tomtom import TomTomIsolines
from cartodb_services.tomtom.types import TRANSPORT_MODE_TO_TOMTOM
from cartodb_services.tools import Coordinate
from cartodb_services.tools.coordinates import coordinates_to_polygon
from cartodb_services.refactor.service.tomtom_isolines_config import TomTomIsolinesConfigBuilder
import cartodb_services
cartodb_services.init(plpy, GD)
service_manager = ServiceManager('isolines', TomTomIsolinesConfigBuilder, username, orgname, GD)
service_manager.assert_within_limits()
try:
tomtom_isolines = TomTomIsolines(service_manager.config.tomtom_api_key, service_manager.logger, service_manager.config.service_params)
if source:
lat = plpy.execute("SELECT ST_Y('%s') AS lat" % source)[0]['lat']
lon = plpy.execute("SELECT ST_X('%s') AS lon" % source)[0]['lon']
origin = Coordinate(lon,lat)
else:
raise Exception('source is NULL')
profile = TRANSPORT_MODE_TO_TOMTOM.get(mode)
resp = tomtom_isolines.calculate_isochrone(origin, data_range, profile)
if resp:
result = []
for isochrone in resp:
result_polygon = coordinates_to_polygon(isochrone.coordinates)
if result_polygon:
service_manager.quota_service.increment_success_service_use()
result.append([source, isochrone.duration, result_polygon])
else:
service_manager.quota_service.increment_empty_service_use()
result.append([source, isochrone.duration, None])
service_manager.quota_service.increment_success_service_use()
service_manager.quota_service.increment_isolines_service_use(len(result))
return result
else:
service_manager.quota_service.increment_empty_service_use()
return []
except BaseException as e:
import sys
service_manager.quota_service.increment_failed_service_use()
service_manager.logger.error('Error trying to get TomTom isochrones', sys.exc_info(), data={"username": username, "orgname": orgname})
raise Exception('Error trying to get TomTom isochrones')
finally:
service_manager.quota_service.increment_total_service_use()
$$ LANGUAGE plpythonu SECURITY DEFINER STABLE PARALLEL RESTRICTED;

View File

@@ -0,0 +1,39 @@
--DO NOT MODIFY THIS FILE, IT IS GENERATED AUTOMATICALLY FROM SOURCES
-- Complain if script is sourced in psql, rather than via CREATE EXTENSION
\echo Use "ALTER EXTENSION cdb_dataservices_server UPDATE TO '0.34.1'" to load this file. \quit
-- HERE goes your code to upgrade/downgrade
CREATE OR REPLACE FUNCTION cdb_dataservices_server._cdb_bulk_geocode_street_point(username TEXT, orgname TEXT, searches jsonb)
RETURNS SETOF cdb_dataservices_server.geocoding AS $$
from cartodb_services.metrics import metrics
from cartodb_services.tools import Logger
import json
plpy.execute("SELECT cdb_dataservices_server._connect_to_redis('{0}')".format(username))
redis_conn = GD["redis_connection_{0}".format(username)]['redis_metrics_connection']
plpy.execute("SELECT cdb_dataservices_server._get_geocoder_config({0}, {1})".format(plpy.quote_nullable(username), plpy.quote_nullable(orgname)))
user_geocoder_config = GD["user_geocoder_config_{0}".format(username)]
plpy.execute("SELECT cdb_dataservices_server._get_logger_config()")
logger_config = GD["logger_config"]
logger = Logger(logger_config)
params = {'username': username, 'orgname': orgname, 'searches': json.loads(searches)}
with metrics('cdb_bulk_geocode_street_point', user_geocoder_config, logger, params):
if user_geocoder_config.google_geocoder:
provider_function = "_cdb_bulk_google_geocode_street_point";
elif user_geocoder_config.heremaps_geocoder:
provider_function = "_cdb_bulk_heremaps_geocode_street_point";
elif user_geocoder_config.tomtom_geocoder:
provider_function = "_cdb_bulk_tomtom_geocode_street_point";
elif user_geocoder_config.mapbox_geocoder:
provider_function = "_cdb_bulk_mapbox_geocode_street_point";
else:
raise Exception('Requested geocoder is not available')
plan = plpy.prepare("SELECT * FROM cdb_dataservices_server.{}($1, $2, $3); ".format(provider_function), ["text", "text", "jsonb"])
return plpy.execute(plan, [username, orgname, searches])
$$ LANGUAGE plpythonu STABLE PARALLEL RESTRICTED;

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,39 @@
--DO NOT MODIFY THIS FILE, IT IS GENERATED AUTOMATICALLY FROM SOURCES
-- Complain if script is sourced in psql, rather than via CREATE EXTENSION
\echo Use "ALTER EXTENSION cdb_dataservices_server UPDATE TO '0.34.0'" to load this file. \quit
-- HERE goes your code to upgrade/downgrade
CREATE OR REPLACE FUNCTION cdb_dataservices_server._cdb_bulk_geocode_street_point(username TEXT, orgname TEXT, searches jsonb)
RETURNS SETOF cdb_dataservices_server.geocoding AS $$
from cartodb_services.metrics import metrics
from cartodb_services.tools import Logger
import json
plpy.execute("SELECT cdb_dataservices_server._connect_to_redis('{0}')".format(username))
redis_conn = GD["redis_connection_{0}".format(username)]['redis_metrics_connection']
plpy.execute("SELECT cdb_dataservices_server._get_geocoder_config({0}, {1})".format(plpy.quote_nullable(username), plpy.quote_nullable(orgname)))
user_geocoder_config = GD["user_geocoder_config_{0}".format(username)]
plpy.execute("SELECT cdb_dataservices_server._get_logger_config()")
logger_config = GD["logger_config"]
logger = Logger(logger_config)
params = {'username': username, 'orgname': orgname, 'searches': searches}
with metrics('cdb_bulk_geocode_street_point', user_geocoder_config, logger, params):
if user_geocoder_config.google_geocoder:
provider_function = "_cdb_bulk_google_geocode_street_point";
elif user_geocoder_config.heremaps_geocoder:
provider_function = "_cdb_bulk_heremaps_geocode_street_point";
elif user_geocoder_config.tomtom_geocoder:
provider_function = "_cdb_bulk_tomtom_geocode_street_point";
elif user_geocoder_config.mapbox_geocoder:
provider_function = "_cdb_bulk_mapbox_geocode_street_point";
else:
raise Exception('Requested geocoder is not available')
plan = plpy.prepare("SELECT * FROM cdb_dataservices_server.{}($1, $2, $3); ".format(provider_function), ["text", "text", "jsonb"])
return plpy.execute(plan, [username, orgname, searches])
$$ LANGUAGE plpythonu STABLE PARALLEL RESTRICTED;

View File

@@ -0,0 +1,221 @@
--DO NOT MODIFY THIS FILE, IT IS GENERATED AUTOMATICALLY FROM SOURCES
-- Complain if script is sourced in psql, rather than via CREATE EXTENSION
\echo Use "ALTER EXTENSION cdb_dataservices_server UPDATE TO '0.35.0'" to load this file. \quit
-- HERE goes your code to upgrade/downgrade
DROP FUNCTION IF EXISTS cdb_dataservices_server._cdb_mapbox_route_with_waypoints(text, text, geometry(Point, 4326)[], text);
DROP FUNCTION IF EXISTS cdb_dataservices_server._cdb_tomtom_route_with_waypoints(text, text, geometry(Point, 4326)[], text);
CREATE OR REPLACE FUNCTION cdb_dataservices_server._cdb_mapbox_route_with_waypoints(
username TEXT,
orgname TEXT,
waypoints geometry(Point, 4326)[],
mode TEXT,
options text[] DEFAULT ARRAY[]::text[],
units text DEFAULT 'kilometers')
RETURNS cdb_dataservices_server.simple_route AS $$
from cartodb_services.tools import ServiceManager
from cartodb_services.mapbox import MapboxRouting
from cartodb_services.mapbox.types import TRANSPORT_MODE_TO_MAPBOX
from cartodb_services.tools import Coordinate
from cartodb_services.tools.polyline import polyline_to_linestring
from cartodb_services.tools.normalize import options_to_dict
from cartodb_services.refactor.service.mapbox_routing_config import MapboxRoutingConfigBuilder
import cartodb_services
cartodb_services.init(plpy, GD)
service_manager = ServiceManager('routing', MapboxRoutingConfigBuilder, username, orgname, GD)
service_manager.assert_within_limits()
try:
client = MapboxRouting(service_manager.config.mapbox_api_key, service_manager.logger, service_manager.config.service_params)
if not waypoints or len(waypoints) < 2:
service_manager.logger.info("Empty origin or destination")
service_manager.quota_service.increment_empty_service_use()
return [None, None, None]
if len(waypoints) > 25:
service_manager.logger.info("Too many waypoints (max 25)")
service_manager.quota_service.increment_empty_service_use()
return [None, None, None]
waypoint_coords = []
for waypoint in waypoints:
lat = plpy.execute("SELECT ST_Y('%s') AS lat" % waypoint)[0]['lat']
lon = plpy.execute("SELECT ST_X('%s') AS lon" % waypoint)[0]['lon']
waypoint_coords.append(Coordinate(lon,lat))
profile = TRANSPORT_MODE_TO_MAPBOX.get(mode)
options_dict = options_to_dict(options)
if 'mode_type' in options_dict:
plpy.warning('Mapbox provider doesnt support route type parameter')
resp = client.directions(waypoint_coords, profile)
if resp and resp.shape:
shape_linestring = polyline_to_linestring(resp.shape)
if shape_linestring:
service_manager.quota_service.increment_success_service_use()
return [shape_linestring, resp.length, int(round(resp.duration))]
else:
service_manager.quota_service.increment_empty_service_use()
return [None, None, None]
else:
service_manager.quota_service.increment_empty_service_use()
return [None, None, None]
except BaseException as e:
import sys
service_manager.quota_service.increment_failed_service_use()
service_manager.logger.error('Error trying to calculate Mapbox routing', sys.exc_info(), data={"username": username, "orgname": orgname})
raise Exception('Error trying to calculate Mapbox routing')
finally:
service_manager.quota_service.increment_total_service_use()
$$ LANGUAGE plpythonu SECURITY DEFINER STABLE PARALLEL RESTRICTED;
CREATE OR REPLACE FUNCTION cdb_dataservices_server._cdb_tomtom_route_with_waypoints(
username TEXT,
orgname TEXT,
waypoints geometry(Point, 4326)[],
mode TEXT,
options text[] DEFAULT ARRAY[]::text[],
units text DEFAULT 'kilometers')
RETURNS cdb_dataservices_server.simple_route AS $$
from cartodb_services.tools import ServiceManager
from cartodb_services.tomtom import TomTomRouting
from cartodb_services.tomtom.types import TRANSPORT_MODE_TO_TOMTOM, DEFAULT_ROUTE_TYPE, MODE_TYPE_TO_TOMTOM
from cartodb_services.tools import Coordinate
from cartodb_services.tools.polyline import polyline_to_linestring
from cartodb_services.tools.normalize import options_to_dict
from cartodb_services.refactor.service.tomtom_routing_config import TomTomRoutingConfigBuilder
import cartodb_services
cartodb_services.init(plpy, GD)
service_manager = ServiceManager('routing', TomTomRoutingConfigBuilder, username, orgname, GD)
service_manager.assert_within_limits()
try:
client = TomTomRouting(service_manager.config.tomtom_api_key, service_manager.logger, service_manager.config.service_params)
if not waypoints or len(waypoints) < 2:
service_manager.logger.info("Empty origin or destination")
service_manager.quota_service.increment_empty_service_use()
return [None, None, None]
if len(waypoints) > 25:
service_manager.logger.info("Too many waypoints (max 25)")
service_manager.quota_service.increment_empty_service_use()
return [None, None, None]
waypoint_coords = []
for waypoint in waypoints:
lat = plpy.execute("SELECT ST_Y('%s') AS lat" % waypoint)[0]['lat']
lon = plpy.execute("SELECT ST_X('%s') AS lon" % waypoint)[0]['lon']
waypoint_coords.append(Coordinate(lon,lat))
profile = TRANSPORT_MODE_TO_TOMTOM.get(mode)
route_type = DEFAULT_ROUTE_TYPE
options_dict = options_to_dict(options)
if 'mode_type' in options_dict:
route_type = MODE_TYPE_TO_TOMTOM.get(options_dict['mode_type'])
resp = client.directions(waypoint_coords, profile=profile, route_type=route_type)
if resp and resp.shape:
shape_linestring = polyline_to_linestring(resp.shape)
if shape_linestring:
service_manager.quota_service.increment_success_service_use()
return [shape_linestring, resp.length, int(round(resp.duration))]
else:
service_manager.quota_service.increment_empty_service_use()
return [None, None, None]
else:
service_manager.quota_service.increment_empty_service_use()
return [None, None, None]
except BaseException as e:
import sys
service_manager.quota_service.increment_failed_service_use()
service_manager.logger.error('Error trying to calculate TomTom routing', sys.exc_info(), data={"username": username, "orgname": orgname})
raise Exception('Error trying to calculate TomTom routing')
finally:
service_manager.quota_service.increment_total_service_use()
$$ LANGUAGE plpythonu SECURITY DEFINER STABLE PARALLEL RESTRICTED;
CREATE OR REPLACE FUNCTION cdb_dataservices_server.cdb_route_point_to_point(
username TEXT,
orgname TEXT,
origin geometry(Point, 4326),
destination geometry(Point, 4326),
mode TEXT,
options text[] DEFAULT ARRAY[]::text[],
units text DEFAULT 'kilometers')
RETURNS cdb_dataservices_server.simple_route AS $$
from cartodb_services.metrics import metrics
from cartodb_services.tools import Logger
plpy.execute("SELECT cdb_dataservices_server._connect_to_redis('{0}')".format(username))
redis_conn = GD["redis_connection_{0}".format(username)]['redis_metrics_connection']
plpy.execute("SELECT cdb_dataservices_server._get_routing_config({0}, {1})".format(plpy.quote_nullable(username), plpy.quote_nullable(orgname)))
user_routing_config = GD["user_routing_config_{0}".format(username)]
plpy.execute("SELECT cdb_dataservices_server._get_logger_config()")
logger_config = GD["logger_config"]
logger = Logger(logger_config)
params = {'username': username, 'orgname': orgname, 'origin': origin, 'destination': destination, 'mode': mode, 'options': options, 'units': units}
with metrics('cdb_route_with_point', user_routing_config, logger, params):
waypoints = [origin, destination]
if user_routing_config.mapzen_provider:
mapzen_plan = plpy.prepare("SELECT * FROM cdb_dataservices_server._cdb_mapzen_route_with_waypoints($1, $2, $3, $4, $5, $6) as route;", ["text", "text", "geometry(Point, 4326)[]", "text", "text[]", "text"])
result = plpy.execute(mapzen_plan, [username, orgname, waypoints, mode, options, units])
return [result[0]['shape'],result[0]['length'], result[0]['duration']]
elif user_routing_config.mapbox_provider:
mapbox_plan = plpy.prepare("SELECT * FROM cdb_dataservices_server._cdb_mapbox_route_with_waypoints($1, $2, $3, $4, $5, $6) as route;", ["text", "text", "geometry(Point, 4326)[]", "text", "text[]", "text"])
result = plpy.execute(mapbox_plan, [username, orgname, waypoints, mode, options, units])
return [result[0]['shape'],result[0]['length'], result[0]['duration']]
elif user_routing_config.tomtom_provider:
tomtom_plan = plpy.prepare("SELECT * FROM cdb_dataservices_server._cdb_tomtom_route_with_waypoints($1, $2, $3, $4, $5, $6) as route;", ["text", "text", "geometry(Point, 4326)[]", "text", "text[]", "text"])
result = plpy.execute(tomtom_plan, [username, orgname, waypoints, mode, options, units])
return [result[0]['shape'],result[0]['length'], result[0]['duration']]
else:
raise Exception('Requested routing method is not available')
$$ LANGUAGE plpythonu STABLE PARALLEL RESTRICTED;
CREATE OR REPLACE FUNCTION cdb_dataservices_server.cdb_route_with_waypoints(
username TEXT,
orgname TEXT,
waypoints geometry(Point, 4326)[],
mode TEXT,
options text[] DEFAULT ARRAY[]::text[],
units text DEFAULT 'kilometers')
RETURNS cdb_dataservices_server.simple_route AS $$
from cartodb_services.metrics import metrics
from cartodb_services.tools import Logger
plpy.execute("SELECT cdb_dataservices_server._connect_to_redis('{0}')".format(username))
redis_conn = GD["redis_connection_{0}".format(username)]['redis_metrics_connection']
plpy.execute("SELECT cdb_dataservices_server._get_routing_config({0}, {1})".format(plpy.quote_nullable(username), plpy.quote_nullable(orgname)))
user_routing_config = GD["user_routing_config_{0}".format(username)]
plpy.execute("SELECT cdb_dataservices_server._get_logger_config()")
logger_config = GD["logger_config"]
logger = Logger(logger_config)
params = {'username': username, 'orgname': orgname, 'waypoints': waypoints, 'mode': mode, 'options': options, 'units': units}
with metrics('cdb_route_with_waypoints', user_routing_config, logger, params):
if user_routing_config.mapzen_provider:
mapzen_plan = plpy.prepare("SELECT * FROM cdb_dataservices_server._cdb_mapzen_route_with_waypoints($1, $2, $3, $4, $5, $6) as route;", ["text", "text", "geometry(Point, 4326)[]", "text", "text[]", "text"])
result = plpy.execute(mapzen_plan, [username, orgname, waypoints, mode, options, units])
return [result[0]['shape'],result[0]['length'], result[0]['duration']]
elif user_routing_config.mapbox_provider:
mapbox_plan = plpy.prepare("SELECT * FROM cdb_dataservices_server._cdb_mapbox_route_with_waypoints($1, $2, $3, $4, $5, $6) as route;", ["text", "text", "geometry(Point, 4326)[]", "text", "text[]", "text"])
result = plpy.execute(mapbox_plan, [username, orgname, waypoints, mode, options, units])
return [result[0]['shape'],result[0]['length'], result[0]['duration']]
elif user_routing_config.tomtom_provider:
tomtom_plan = plpy.prepare("SELECT * FROM cdb_dataservices_server._cdb_tomtom_route_with_waypoints($1, $2, $3, $4, $5, $6) as route;", ["text", "text", "geometry(Point, 4326)[]", "text", "text[]", "text"])
result = plpy.execute(tomtom_plan, [username, orgname, waypoints, mode, options, units])
return [result[0]['shape'],result[0]['length'], result[0]['duration']]
else:
raise Exception('Requested routing method is not available')
$$ LANGUAGE plpythonu STABLE PARALLEL RESTRICTED;

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,209 @@
--DO NOT MODIFY THIS FILE, IT IS GENERATED AUTOMATICALLY FROM SOURCES
-- Complain if script is sourced in psql, rather than via CREATE EXTENSION
\echo Use "ALTER EXTENSION cdb_dataservices_server UPDATE TO '0.34.2'" to load this file. \quit
-- HERE goes your code to upgrade/downgrade
DROP FUNCTION IF EXISTS cdb_dataservices_server._cdb_mapbox_route_with_waypoints(text, text, geometry(Point, 4326)[], text, text[], text);
DROP FUNCTION IF EXISTS cdb_dataservices_server._cdb_tomtom_route_with_waypoints(text, text, geometry(Point, 4326)[], text, text[], text);
CREATE OR REPLACE FUNCTION cdb_dataservices_server._cdb_mapbox_route_with_waypoints(
username TEXT,
orgname TEXT,
waypoints geometry(Point, 4326)[],
mode TEXT)
RETURNS cdb_dataservices_server.simple_route AS $$
from cartodb_services.tools import ServiceManager
from cartodb_services.mapbox import MapboxRouting
from cartodb_services.mapbox.types import TRANSPORT_MODE_TO_MAPBOX
from cartodb_services.tools import Coordinate
from cartodb_services.tools.polyline import polyline_to_linestring
from cartodb_services.refactor.service.mapbox_routing_config import MapboxRoutingConfigBuilder
import cartodb_services
cartodb_services.init(plpy, GD)
service_manager = ServiceManager('routing', MapboxRoutingConfigBuilder, username, orgname, GD)
service_manager.assert_within_limits()
try:
client = MapboxRouting(service_manager.config.mapbox_api_key, service_manager.logger, service_manager.config.service_params)
if not waypoints or len(waypoints) < 2:
service_manager.logger.info("Empty origin or destination")
service_manager.quota_service.increment_empty_service_use()
return [None, None, None]
if len(waypoints) > 25:
service_manager.logger.info("Too many waypoints (max 25)")
service_manager.quota_service.increment_empty_service_use()
return [None, None, None]
waypoint_coords = []
for waypoint in waypoints:
lat = plpy.execute("SELECT ST_Y('%s') AS lat" % waypoint)[0]['lat']
lon = plpy.execute("SELECT ST_X('%s') AS lon" % waypoint)[0]['lon']
waypoint_coords.append(Coordinate(lon,lat))
profile = TRANSPORT_MODE_TO_MAPBOX.get(mode)
resp = client.directions(waypoint_coords, profile)
if resp and resp.shape:
shape_linestring = polyline_to_linestring(resp.shape)
if shape_linestring:
service_manager.quota_service.increment_success_service_use()
return [shape_linestring, resp.length, int(round(resp.duration))]
else:
service_manager.quota_service.increment_empty_service_use()
return [None, None, None]
else:
service_manager.quota_service.increment_empty_service_use()
return [None, None, None]
except BaseException as e:
import sys
service_manager.quota_service.increment_failed_service_use()
service_manager.logger.error('Error trying to calculate Mapbox routing', sys.exc_info(), data={"username": username, "orgname": orgname})
raise Exception('Error trying to calculate Mapbox routing')
finally:
service_manager.quota_service.increment_total_service_use()
$$ LANGUAGE plpythonu SECURITY DEFINER STABLE PARALLEL RESTRICTED;
CREATE OR REPLACE FUNCTION cdb_dataservices_server._cdb_tomtom_route_with_waypoints(
username TEXT,
orgname TEXT,
waypoints geometry(Point, 4326)[],
mode TEXT)
RETURNS cdb_dataservices_server.simple_route AS $$
from cartodb_services.tools import ServiceManager
from cartodb_services.tomtom import TomTomRouting
from cartodb_services.tomtom.types import TRANSPORT_MODE_TO_TOMTOM
from cartodb_services.tools import Coordinate
from cartodb_services.tools.polyline import polyline_to_linestring
from cartodb_services.refactor.service.tomtom_routing_config import TomTomRoutingConfigBuilder
import cartodb_services
cartodb_services.init(plpy, GD)
service_manager = ServiceManager('routing', TomTomRoutingConfigBuilder, username, orgname, GD)
service_manager.assert_within_limits()
try:
client = TomTomRouting(service_manager.config.tomtom_api_key, service_manager.logger, service_manager.config.service_params)
if not waypoints or len(waypoints) < 2:
service_manager.logger.info("Empty origin or destination")
service_manager.quota_service.increment_empty_service_use()
return [None, None, None]
if len(waypoints) > 25:
service_manager.logger.info("Too many waypoints (max 25)")
service_manager.quota_service.increment_empty_service_use()
return [None, None, None]
waypoint_coords = []
for waypoint in waypoints:
lat = plpy.execute("SELECT ST_Y('%s') AS lat" % waypoint)[0]['lat']
lon = plpy.execute("SELECT ST_X('%s') AS lon" % waypoint)[0]['lon']
waypoint_coords.append(Coordinate(lon,lat))
profile = TRANSPORT_MODE_TO_TOMTOM.get(mode)
resp = client.directions(waypoint_coords, profile)
if resp and resp.shape:
shape_linestring = polyline_to_linestring(resp.shape)
if shape_linestring:
service_manager.quota_service.increment_success_service_use()
return [shape_linestring, resp.length, int(round(resp.duration))]
else:
service_manager.quota_service.increment_empty_service_use()
return [None, None, None]
else:
service_manager.quota_service.increment_empty_service_use()
return [None, None, None]
except BaseException as e:
import sys
service_manager.quota_service.increment_failed_service_use()
service_manager.logger.error('Error trying to calculate TomTom routing', sys.exc_info(), data={"username": username, "orgname": orgname})
raise Exception('Error trying to calculate TomTom routing')
finally:
service_manager.quota_service.increment_total_service_use()
$$ LANGUAGE plpythonu SECURITY DEFINER STABLE PARALLEL RESTRICTED;
CREATE OR REPLACE FUNCTION cdb_dataservices_server.cdb_route_point_to_point(
username TEXT,
orgname TEXT,
origin geometry(Point, 4326),
destination geometry(Point, 4326),
mode TEXT,
options text[] DEFAULT ARRAY[]::text[],
units text DEFAULT 'kilometers')
RETURNS cdb_dataservices_server.simple_route AS $$
from cartodb_services.metrics import metrics
from cartodb_services.tools import Logger
plpy.execute("SELECT cdb_dataservices_server._connect_to_redis('{0}')".format(username))
redis_conn = GD["redis_connection_{0}".format(username)]['redis_metrics_connection']
plpy.execute("SELECT cdb_dataservices_server._get_routing_config({0}, {1})".format(plpy.quote_nullable(username), plpy.quote_nullable(orgname)))
user_routing_config = GD["user_routing_config_{0}".format(username)]
plpy.execute("SELECT cdb_dataservices_server._get_logger_config()")
logger_config = GD["logger_config"]
logger = Logger(logger_config)
params = {'username': username, 'orgname': orgname, 'origin': origin, 'destination': destination, 'mode': mode, 'options': options, 'units': units}
with metrics('cdb_route_with_point', user_routing_config, logger, params):
waypoints = [origin, destination]
if user_routing_config.mapzen_provider:
mapzen_plan = plpy.prepare("SELECT * FROM cdb_dataservices_server._cdb_mapzen_route_with_waypoints($1, $2, $3, $4) as route;", ["text", "text", "geometry(Point, 4326)[]", "text"])
result = plpy.execute(mapzen_plan, [username, orgname, waypoints, mode])
return [result[0]['shape'],result[0]['length'], result[0]['duration']]
elif user_routing_config.mapbox_provider:
mapbox_plan = plpy.prepare("SELECT * FROM cdb_dataservices_server._cdb_mapbox_route_with_waypoints($1, $2, $3, $4) as route;", ["text", "text", "geometry(Point, 4326)[]", "text"])
result = plpy.execute(mapbox_plan, [username, orgname, waypoints, mode])
return [result[0]['shape'],result[0]['length'], result[0]['duration']]
elif user_routing_config.tomtom_provider:
tomtom_plan = plpy.prepare("SELECT * FROM cdb_dataservices_server._cdb_tomtom_route_with_waypoints($1, $2, $3, $4) as route;", ["text", "text", "geometry(Point, 4326)[]", "text"])
result = plpy.execute(tomtom_plan, [username, orgname, waypoints, mode])
return [result[0]['shape'],result[0]['length'], result[0]['duration']]
else:
raise Exception('Requested routing method is not available')
$$ LANGUAGE plpythonu STABLE PARALLEL RESTRICTED;
CREATE OR REPLACE FUNCTION cdb_dataservices_server.cdb_route_with_waypoints(
username TEXT,
orgname TEXT,
waypoints geometry(Point, 4326)[],
mode TEXT,
options text[] DEFAULT ARRAY[]::text[],
units text DEFAULT 'kilometers')
RETURNS cdb_dataservices_server.simple_route AS $$
from cartodb_services.metrics import metrics
from cartodb_services.tools import Logger
plpy.execute("SELECT cdb_dataservices_server._connect_to_redis('{0}')".format(username))
redis_conn = GD["redis_connection_{0}".format(username)]['redis_metrics_connection']
plpy.execute("SELECT cdb_dataservices_server._get_routing_config({0}, {1})".format(plpy.quote_nullable(username), plpy.quote_nullable(orgname)))
user_routing_config = GD["user_routing_config_{0}".format(username)]
plpy.execute("SELECT cdb_dataservices_server._get_logger_config()")
logger_config = GD["logger_config"]
logger = Logger(logger_config)
params = {'username': username, 'orgname': orgname, 'waypoints': waypoints, 'mode': mode, 'options': options, 'units': units}
with metrics('cdb_route_with_waypoints', user_routing_config, logger, params):
if user_routing_config.mapzen_provider:
mapzen_plan = plpy.prepare("SELECT * FROM cdb_dataservices_server._cdb_mapzen_route_with_waypoints($1, $2, $3, $4) as route;", ["text", "text", "geometry(Point, 4326)[]", "text"])
result = plpy.execute(mapzen_plan, [username, orgname, waypoints, mode])
return [result[0]['shape'],result[0]['length'], result[0]['duration']]
elif user_routing_config.mapbox_provider:
mapbox_plan = plpy.prepare("SELECT * FROM cdb_dataservices_server._cdb_mapbox_route_with_waypoints($1, $2, $3, $4) as route;", ["text", "text", "geometry(Point, 4326)[]", "text"])
result = plpy.execute(mapbox_plan, [username, orgname, waypoints, mode])
return [result[0]['shape'],result[0]['length'], result[0]['duration']]
elif user_routing_config.tomtom_provider:
tomtom_plan = plpy.prepare("SELECT * FROM cdb_dataservices_server._cdb_tomtom_route_with_waypoints($1, $2, $3, $4) as route;", ["text", "text", "geometry(Point, 4326)[]", "text"])
result = plpy.execute(tomtom_plan, [username, orgname, waypoints, mode])
return [result[0]['shape'],result[0]['length'], result[0]['duration']]
else:
raise Exception('Requested routing method is not available')
$$ LANGUAGE plpythonu STABLE PARALLEL RESTRICTED;

View File

@@ -0,0 +1,6 @@
--DO NOT MODIFY THIS FILE, IT IS GENERATED AUTOMATICALLY FROM SOURCES
-- Complain if script is sourced in psql, rather than via CREATE EXTENSION
\echo Use "ALTER EXTENSION cdb_dataservices_server UPDATE TO '0.35.1'" to load this file. \quit
-- HERE goes your code to upgrade/downgrade
ALTER TYPE cdb_dataservices_server.geocoding ALTER ATTRIBUTE the_geom TYPE geometry(Point,4326);

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,6 @@
--DO NOT MODIFY THIS FILE, IT IS GENERATED AUTOMATICALLY FROM SOURCES
-- Complain if script is sourced in psql, rather than via CREATE EXTENSION
\echo Use "ALTER EXTENSION cdb_dataservices_server UPDATE TO '0.35.0'" to load this file. \quit
-- HERE goes your code to upgrade/downgrade
ALTER TYPE cdb_dataservices_server.geocoding ALTER ATTRIBUTE the_geom TYPE geometry(MultiPolygon,4326);

File diff suppressed because it is too large Load Diff

View File

@@ -8,13 +8,16 @@ CREATE OR REPLACE FUNCTION cdb_dataservices_server._cdb_mapbox_route_with_waypoi
username TEXT,
orgname TEXT,
waypoints geometry(Point, 4326)[],
mode TEXT)
mode TEXT,
options text[] DEFAULT ARRAY[]::text[],
units text DEFAULT 'kilometers')
RETURNS cdb_dataservices_server.simple_route AS $$
from cartodb_services.tools import ServiceManager
from cartodb_services.mapbox import MapboxRouting
from cartodb_services.mapbox.types import TRANSPORT_MODE_TO_MAPBOX
from cartodb_services.tools import Coordinate
from cartodb_services.tools.polyline import polyline_to_linestring
from cartodb_services.tools.normalize import options_to_dict
from cartodb_services.refactor.service.mapbox_routing_config import MapboxRoutingConfigBuilder
import cartodb_services
@@ -43,6 +46,9 @@ RETURNS cdb_dataservices_server.simple_route AS $$
waypoint_coords.append(Coordinate(lon,lat))
profile = TRANSPORT_MODE_TO_MAPBOX.get(mode)
options_dict = options_to_dict(options)
if 'mode_type' in options_dict:
plpy.warning('Mapbox provider doesnt support route type parameter')
resp = client.directions(waypoint_coords, profile)
if resp and resp.shape:
@@ -69,13 +75,16 @@ CREATE OR REPLACE FUNCTION cdb_dataservices_server._cdb_tomtom_route_with_waypoi
username TEXT,
orgname TEXT,
waypoints geometry(Point, 4326)[],
mode TEXT)
mode TEXT,
options text[] DEFAULT ARRAY[]::text[],
units text DEFAULT 'kilometers')
RETURNS cdb_dataservices_server.simple_route AS $$
from cartodb_services.tools import ServiceManager
from cartodb_services.tomtom import TomTomRouting
from cartodb_services.tomtom.types import TRANSPORT_MODE_TO_TOMTOM
from cartodb_services.tomtom.types import TRANSPORT_MODE_TO_TOMTOM, DEFAULT_ROUTE_TYPE, MODE_TYPE_TO_TOMTOM
from cartodb_services.tools import Coordinate
from cartodb_services.tools.polyline import polyline_to_linestring
from cartodb_services.tools.normalize import options_to_dict
from cartodb_services.refactor.service.tomtom_routing_config import TomTomRoutingConfigBuilder
import cartodb_services
@@ -104,8 +113,12 @@ RETURNS cdb_dataservices_server.simple_route AS $$
waypoint_coords.append(Coordinate(lon,lat))
profile = TRANSPORT_MODE_TO_TOMTOM.get(mode)
route_type = DEFAULT_ROUTE_TYPE
options_dict = options_to_dict(options)
if 'mode_type' in options_dict:
route_type = MODE_TYPE_TO_TOMTOM.get(options_dict['mode_type'])
resp = client.directions(waypoint_coords, profile)
resp = client.directions(waypoint_coords, profile=profile, route_type=route_type)
if resp and resp.shape:
shape_linestring = polyline_to_linestring(resp.shape)
if shape_linestring:

Some files were not shown because too many files have changed in this diff Show More