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
45 GROUP BY un.owner, ur.target;
47 DROP VIEW #PFX#usersnet_narrowskill;
48 CREATE VIEW #PFX#usersnet_narrowskill
49 AS SELECT un.owner AS owner, ur.target AS target, SUM(ur.skill * un.trust) / SUM(un.trust) AS skill,
51 SUM(CASE WHEN ur.friend = 1 THEN 1 ELSE 0 END) AS black -- count number of friend
52 -- blacklisting the target
53 FROM #PFX#usersnet AS un, #PFX#usersnet as ur
54 WHERE un.target = ur.owner AND un.friend = 5 -- ur owner must be bbf of un.owner
55 GROUP BY un.owner, ur.target HAVING SUM(CASE WHEN ur.friend = 1 THEN 1 ELSE 0 END) = 0;
57 DROP VIEW #PFX#usersnet_party;
58 CREATE VIEW #PFX#usersnet_party
59 AS (SELECT ns.* FROM #PFX#usersnet_narrowskill AS ns
60 -- all except targets managed directly by the owner
61 WHERE target NOT IN (SELECT target FROM #PFX#usersnet WHERE owner = ns.owner)
63 (SELECT owner, target, skill, 1 AS count, 0 AS black FROM #PFX#usersnet
64 WHERE friend > 2)) ORDER BY target;