2 -- Table to manage users trust network
4 DROP TABLE IF EXISTS #PFX#usersnet;
5 CREATE TABLE #PFX#usersnet (
6 owner integer REFERENCES #PFX#users (code)
7 ON DELETE cascade ON UPDATE cascade, -- network owner
8 target integer REFERENCES #PFX#users (code)
9 ON DELETE cascade ON UPDATE cascade, -- evaluated user
10 friend integer, -- friendship level
11 -- 1"black", 2"unknown", 3"test", 4"friend", 5"bff"
12 skill float, -- skill level
14 ctime timestamp DEFAULT now(), -- creation time
15 mtime timestamp DEFAULT to_timestamp(0) -- modification time
18 DROP INDEX IF EXISTS #PFX#usersnet_owner_idx;
19 DROP INDEX IF EXISTS #PFX#usersnet_target_idx;
20 DROP INDEX IF EXISTS #PFX#usersnet_owner_target_idx;
22 CREATE INDEX #PFX#usersnet_owner_idx ON #PFX#usersnet (owner);
23 CREATE INDEX #PFX#usersnet_target_idx ON #PFX#usersnet (target);
24 CREATE UNIQUE INDEX #PFX#usersnet_owner_target_idx ON #PFX#usersnet (owner, target);
26 DROP VIEW #PFX#usersnet_widefriend;
27 CREATE VIEW #PFX#usersnet_widefriend
28 AS SELECT un.owner, ur.target, ur.friend, count(*) as count
29 FROM #PFX#usersnet AS un, #PFX#usersnet AS ur
30 WHERE un.target = ur.owner AND un.friend >= 4 -- 'un' is, at least, our friend
31 GROUP BY un.owner, ur.target, ur.friend;
33 DROP VIEW #PFX#usersnet_narrowfriend;
34 CREATE VIEW #PFX#usersnet_narrowfriend
35 AS SELECT un.owner, ur.target, ur.friend, count(*) as count
36 FROM #PFX#usersnet AS un, #PFX#usersnet AS ur
37 WHERE un.target = ur.owner AND un.friend >= 5 -- 'un' is, at least, our friend
38 GROUP BY un.owner, ur.target, ur.friend;
40 DROP VIEW #PFX#usersnet_wideskill;
41 CREATE VIEW #PFX#usersnet_wideskill
42 AS SELECT un.owner, ur.target, SUM(ur.skill * un.trust) / SUM(un.trust) as skill, count(*) as count
43 FROM #PFX#usersnet AS un, #PFX#usersnet AS ur
44 WHERE un.target = ur.owner AND un.friend >= 4 -- 'un' is, at least, our friend
46 GROUP BY un.owner, ur.target;
48 DROP VIEW #PFX#usersnet_narrowskill;
49 CREATE VIEW #PFX#usersnet_narrowskill
53 , SUM(ur.skill * un.trust) / SUM(un.trust) AS skill
55 FROM #PFX#usersnet AS un, #PFX#usersnet as ur
56 WHERE un.target = ur.owner AND un.friend = 5 -- 'ur' owner must be bbf of un.owner
58 GROUP BY un.owner, ur.target;
60 DROP VIEW #PFX#usersnet_narrowblack;
61 CREATE VIEW #PFX#usersnet_narrowblack
62 AS SELECT DISTINCT un.owner AS owner, ur.target AS target, 1 AS black_cnt
63 FROM #PFX#usersnet AS un, #PFX#usersnet as ur
64 WHERE un.target = ur.owner
65 AND un.friend = 5 -- ur owner must be bbf of un.owner
66 AND ur.friend = 1; -- ur must be blacked
68 DROP VIEW #PFX#usersnet_party;
69 CREATE VIEW #PFX#usersnet_party
70 AS (SELECT ns.*, nb.black_cnt FROM #PFX#usersnet_narrowskill AS ns
71 LEFT JOIN #PFX#usersnet_narrowblack AS nb
73 -- all except targets managed directly by the owner
74 WHERE black_cnt is null
75 AND target NOT IN (SELECT target FROM #PFX#usersnet AS du WHERE du.owner = ns.owner)
77 (SELECT owner, target, skill, 1 AS count, null AS black_cnt