-
Notifications
You must be signed in to change notification settings - Fork 1
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Merge pull request #448 from ww24/add-bigquery-routine
feat(terraform): add with_geolocation function
- Loading branch information
Showing
2 changed files
with
50 additions
and
1 deletion.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,28 @@ | ||
-- with_geolocation function | ||
-- CREATE OR REPLACE TABLE FUNCTION ${dataset}.with_geolocation(since TIMESTAMP, until TIMESTAMP) AS | ||
WITH | ||
access_logs AS (SELECT * | ||
FROM `${project}.${dataset}.access_log` | ||
WHERE `timestamp` BETWEEN since AND until), | ||
geolocations AS (SELECT * | ||
FROM `${project}.geolite2.GeoLite2_City_*` | ||
WHERE _TABLE_SUFFIX = FORMAT_DATE('%Y%m%d', DATE(since))) | ||
SELECT * FROM access_logs | ||
LEFT JOIN ( | ||
WITH ips AS (SELECT DISTINCT ip FROM access_logs) | ||
-- IPv4 address => country, city | ||
SELECT ip, country, city FROM ( | ||
SELECT NET.IP_TRUNC(NET.SAFE_IP_FROM_STRING(ip), mask) network, * | ||
FROM ips, UNNEST(GENERATE_ARRAY(8,32)) mask | ||
WHERE ip LIKE '%.%' | ||
) | ||
JOIN geolocations USING (network, mask) | ||
UNION ALL | ||
-- IPv6 address => country, city | ||
SELECT ip, country, city FROM ( | ||
SELECT NET.IP_TRUNC(NET.SAFE_IP_FROM_STRING(ip), mask) network, * | ||
FROM ips, UNNEST(GENERATE_ARRAY(19,64)) mask | ||
WHERE ip LIKE '%:%' | ||
) | ||
JOIN geolocations USING (network, mask) | ||
) USING (ip) |