-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path02_basic_functions.sql
More file actions
72 lines (64 loc) · 1.77 KB
/
02_basic_functions.sql
File metadata and controls
72 lines (64 loc) · 1.77 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
-- PostgreSQL Data Anonymization in AWS RDS
-- Basic anonymization functions using pgcrypto
-- Create a function to hash strings (one-way anonymization)
CREATE OR REPLACE FUNCTION anon.hash_string(text)
RETURNS TEXT AS
$$
SELECT encode(digest($1, 'sha256'), 'hex');
$$
LANGUAGE SQL IMMUTABLE;
-- Create a function to partially mask email addresses
CREATE OR REPLACE FUNCTION anon.partial_email(email text)
RETURNS text AS
$$
BEGIN
IF email IS NULL THEN
RETURN NULL;
END IF;
IF position('@' in email) = 0 THEN
RETURN substring(email, 1, 2) || '******';
END IF;
RETURN substring(email, 1, 2) || '******' || substring(email from position('@' in email));
END;
$$
LANGUAGE plpgsql IMMUTABLE;
-- Create a function to partially mask any string
CREATE OR REPLACE FUNCTION anon.partial(text_val text, prefix_len int, mask text, suffix_len int)
RETURNS text AS
$$
BEGIN
IF text_val IS NULL THEN
RETURN NULL;
END IF;
RETURN
substring(text_val, 1, prefix_len) ||
mask ||
substring(text_val, length(text_val) - suffix_len + 1, suffix_len);
END;
$$
LANGUAGE plpgsql IMMUTABLE;
-- Create a function to generate random integers in a range
CREATE OR REPLACE FUNCTION anon.random_int(min_val int, max_val int)
RETURNS int AS
$$
BEGIN
RETURN floor(random() * (max_val - min_val + 1) + min_val)::int;
END;
$$
LANGUAGE plpgsql VOLATILE;
-- Create a function to generate random strings
CREATE OR REPLACE FUNCTION anon.random_string(length int)
RETURNS text AS
$$
DECLARE
chars text := 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
result text := '';
i int := 0;
BEGIN
FOR i IN 1..length LOOP
result := result || substring(chars, anon.random_int(1, length(chars)), 1);
END LOOP;
RETURN result;
END;
$$
LANGUAGE plpgsql VOLATILE;