-
Notifications
You must be signed in to change notification settings - Fork 2
/
upsert_sql.go
94 lines (89 loc) · 2.6 KB
/
upsert_sql.go
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
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
package bloomdb
var upsertSql = `
{{if ne .ParentKey ""}}
--- 1) Move Main Table - Temp Table (using Parent Key to limit) into version table
INSERT INTO {{.Table}}_revisions (
{{range $i, $e := .Columns}}{{$e}},{{end}}
bloom_created_at,
bloom_updated_at,
bloom_action
)
SELECT
{{range $i, $e := .Columns}}{{$e}},{{end}}
bloom_created_at,
'{{.UpdatedAt}}' AS bloom_updated_at,
'DELETE' AS bloom_action
FROM {{.Table}}
WHERE EXISTS (
SELECT 1 FROM (
SELECT id FROM (
SELECT *
FROM {{.Table}}
WHERE EXISTS (
SELECT 1
FROM {{.Table}}_temp
WHERE {{.Table}}_temp.{{.ParentKey}} = {{.Table}}.{{.ParentKey}})) AS j
EXCEPT
SELECT id from {{.Table}}_temp) AS f
WHERE f.id = {{.Table}}.id);
--- 2) Delete Main Table - Temp Table (using Parent Key to limit) from Main Table
DELETE FROM {{.Table}}
WHERE EXISTS (
SELECT 1 FROM (
SELECT id FROM (
SELECT *
FROM {{.Table}}
WHERE EXISTS (
SELECT 1
FROM {{.Table}}_temp
WHERE {{.Table}}_temp.{{.ParentKey}} = {{.Table}}.{{.ParentKey}})) AS j
EXCEPT
SELECT id from {{.Table}}_temp) AS f
WHERE f.id = {{.Table}}.id);
{{end}}
--- 3) INSERT Main Table INTERSECT Temp Table into version table (to be updated)
INSERT INTO {{.Table}}_revisions (
{{range $i, $e := .Columns}}{{$e}},{{end}}
bloom_created_at,
bloom_updated_at,
bloom_action
)
(SELECT
{{range $i, $e := .Columns}}{{$e}},{{end}}
bloom_created_at,
'{{.UpdatedAt}}' AS bloom_updated_at,
'UPDATE' AS bloom_action
FROM {{.Table}}
WHERE EXISTS(
SELECT 1
FROM {{.Table}}_temp
WHERE {{.Table}}_temp.id = {{.Table}}.id
AND {{.Table}}_temp.revision != {{.Table}}.revision));
--- 4) Update Main Table from Temp Table
UPDATE {{.Table}}
SET
{{range $i, $e := .Columns}}{{$e}} = {{$.Table}}_temp.{{$e}},{{end}}
bloom_created_at = '{{.CreatedAt}}'
FROM {{.Table}}_temp
WHERE {{.Table}}_temp.id = {{.Table}}.id
AND EXISTS(
SELECT 1
FROM {{.Table}}_temp
WHERE {{.Table}}_temp.id = {{.Table}}.id
AND {{.Table}}_temp.revision != {{.Table}}.revision);
--- 5) Insert New records into Main Table
INSERT INTO {{.Table}} (
{{range $i, $e := .Columns}}{{$e}},{{end}}
bloom_created_at
)
SELECT DISTINCT ON ({{.Table}}_temp.id)
{{range $i, $e := .Columns}}{{$e}},{{end}}
'{{.CreatedAt}}' AS bloom_created_at
FROM {{.Table}}_temp
WHERE EXISTS (
SELECT 1 FROM (
SELECT id FROM {{.Table}}_temp
EXCEPT
SELECT id FROM {{.Table}}) AS f
WHERE f.id = {{.Table}}_temp.id);
`