liquid_feedback_core

view core.sql @ 54:964cab0880ce

Removed column "interest_exists" from table "direct_population_snapshot"; Replaced function "delete_member_data" by function "delete_member"
author jbe
date Mon Jun 28 15:08:06 2010 +0200 (2010-06-28)
parents 3fbf9e18ee52
children b63515611a60
line source
2 CREATE LANGUAGE plpgsql; -- Triggers are implemented in PL/pgSQL
4 -- NOTE: In PostgreSQL every UNIQUE constraint implies creation of an index
6 BEGIN;
8 CREATE VIEW "liquid_feedback_version" AS
9 SELECT * FROM (VALUES ('1.1.0', 1, 1, 0))
10 AS "subquery"("string", "major", "minor", "revision");
14 ----------------------
15 -- Full text search --
16 ----------------------
19 CREATE FUNCTION "text_search_query"("query_text_p" TEXT)
20 RETURNS TSQUERY
21 LANGUAGE 'plpgsql' IMMUTABLE AS $$
22 BEGIN
23 RETURN plainto_tsquery('pg_catalog.simple', "query_text_p");
24 END;
25 $$;
27 COMMENT ON FUNCTION "text_search_query"(TEXT) IS 'Usage: WHERE "text_search_data" @@ "text_search_query"(''<user query>'')';
30 CREATE FUNCTION "highlight"
31 ( "body_p" TEXT,
32 "query_text_p" TEXT )
33 RETURNS TEXT
34 LANGUAGE 'plpgsql' IMMUTABLE AS $$
35 BEGIN
36 RETURN ts_headline(
37 'pg_catalog.simple',
38 replace(replace("body_p", e'\\', e'\\\\'), '*', e'\\*'),
39 "text_search_query"("query_text_p"),
40 'StartSel=* StopSel=* HighlightAll=TRUE' );
41 END;
42 $$;
44 COMMENT ON FUNCTION "highlight"
45 ( "body_p" TEXT,
46 "query_text_p" TEXT )
47 IS 'For a given a user query this function encapsulates all matches with asterisks. Asterisks and backslashes being already present are preceeded with one extra backslash.';
51 -------------------------
52 -- Tables and indicies --
53 -------------------------
56 CREATE TABLE "member" (
57 "id" SERIAL4 PRIMARY KEY,
58 "created" TIMESTAMPTZ NOT NULL DEFAULT now(),
59 "last_login" TIMESTAMPTZ,
60 "login" TEXT UNIQUE,
61 "password" TEXT,
62 "active" BOOLEAN NOT NULL DEFAULT TRUE,
63 "admin" BOOLEAN NOT NULL DEFAULT FALSE,
64 "notify_email" TEXT,
65 "notify_email_unconfirmed" TEXT,
66 "notify_email_secret" TEXT UNIQUE,
67 "notify_email_secret_expiry" TIMESTAMPTZ,
68 "password_reset_secret" TEXT UNIQUE,
69 "password_reset_secret_expiry" TIMESTAMPTZ,
70 "name" TEXT NOT NULL UNIQUE,
71 "identification" TEXT UNIQUE,
72 "organizational_unit" TEXT,
73 "internal_posts" TEXT,
74 "realname" TEXT,
75 "birthday" DATE,
76 "address" TEXT,
77 "email" TEXT,
78 "xmpp_address" TEXT,
79 "website" TEXT,
80 "phone" TEXT,
81 "mobile_phone" TEXT,
82 "profession" TEXT,
83 "external_memberships" TEXT,
84 "external_posts" TEXT,
85 "statement" TEXT,
86 "text_search_data" TSVECTOR );
87 CREATE INDEX "member_active_idx" ON "member" ("active");
88 CREATE INDEX "member_text_search_data_idx" ON "member" USING gin ("text_search_data");
89 CREATE TRIGGER "update_text_search_data"
90 BEFORE INSERT OR UPDATE ON "member"
91 FOR EACH ROW EXECUTE PROCEDURE
92 tsvector_update_trigger('text_search_data', 'pg_catalog.simple',
93 "name", "identification", "organizational_unit", "internal_posts",
94 "realname", "external_memberships", "external_posts", "statement" );
96 COMMENT ON TABLE "member" IS 'Users of the system, e.g. members of an organization';
98 COMMENT ON COLUMN "member"."login" IS 'Login name';
99 COMMENT ON COLUMN "member"."password" IS 'Password (preferably as crypto-hash, depending on the frontend or access layer)';
100 COMMENT ON COLUMN "member"."active" IS 'Inactive members can not login and their supports/votes are not counted by the system.';
101 COMMENT ON COLUMN "member"."admin" IS 'TRUE for admins, which can administrate other users and setup policies and areas';
102 COMMENT ON COLUMN "member"."notify_email" IS 'Email address where notifications of the system are sent to';
103 COMMENT ON COLUMN "member"."notify_email_unconfirmed" IS 'Unconfirmed email address provided by the member to be copied into "notify_email" field after verification';
104 COMMENT ON COLUMN "member"."notify_email_secret" IS 'Secret sent to the address in "notify_email_unconformed"';
105 COMMENT ON COLUMN "member"."notify_email_secret_expiry" IS 'Expiry date/time for "notify_email_secret"';
106 COMMENT ON COLUMN "member"."name" IS 'Distinct name of the member';
107 COMMENT ON COLUMN "member"."identification" IS 'Optional identification number or code of the member';
108 COMMENT ON COLUMN "member"."organizational_unit" IS 'Branch or division of the organization the member belongs to';
109 COMMENT ON COLUMN "member"."internal_posts" IS 'Posts (offices) of the member inside the organization';
110 COMMENT ON COLUMN "member"."realname" IS 'Real name of the member, may be identical with "name"';
111 COMMENT ON COLUMN "member"."email" IS 'Published email address of the member; not used for system notifications';
112 COMMENT ON COLUMN "member"."external_memberships" IS 'Other organizations the member is involved in';
113 COMMENT ON COLUMN "member"."external_posts" IS 'Posts (offices) outside the organization';
114 COMMENT ON COLUMN "member"."statement" IS 'Freely chosen text of the member for his homepage within the system';
117 CREATE TABLE "member_history" (
118 "id" SERIAL8 PRIMARY KEY,
119 "member_id" INT4 NOT NULL REFERENCES "member" ("id") ON DELETE CASCADE ON UPDATE CASCADE,
120 "until" TIMESTAMPTZ NOT NULL DEFAULT now(),
121 "login" TEXT,
122 "active" BOOLEAN NOT NULL,
123 "name" TEXT NOT NULL );
124 CREATE INDEX "member_history_member_id_idx" ON "member_history" ("member_id");
126 COMMENT ON TABLE "member_history" IS 'Filled by trigger; keeps information about old names, login names and active flag of members';
128 COMMENT ON COLUMN "member_history"."id" IS 'Primary key, which can be used to sort entries correctly (and time warp resistant)';
129 COMMENT ON COLUMN "member_history"."until" IS 'Timestamp until the name and login had been valid';
132 CREATE TABLE "invite_code" (
133 "code" TEXT PRIMARY KEY,
134 "created" TIMESTAMPTZ NOT NULL DEFAULT now(),
135 "used" TIMESTAMPTZ,
136 "member_id" INT4 UNIQUE REFERENCES "member" ("id") ON DELETE SET NULL ON UPDATE CASCADE,
137 "comment" TEXT,
138 CONSTRAINT "only_used_codes_may_refer_to_member" CHECK ("used" NOTNULL OR "member_id" ISNULL) );
140 COMMENT ON TABLE "invite_code" IS 'Invite codes can be used once to create a new member account.';
142 COMMENT ON COLUMN "invite_code"."code" IS 'Secret code';
143 COMMENT ON COLUMN "invite_code"."created" IS 'Time of creation of the secret code';
144 COMMENT ON COLUMN "invite_code"."used" IS 'NULL, if not used yet, otherwise tells when this code was used to create a member account';
145 COMMENT ON COLUMN "invite_code"."member_id" IS 'References the member whose account was created with this code';
146 COMMENT ON COLUMN "invite_code"."comment" IS 'Comment on the code, which is to be used for administrative reasons only';
149 CREATE TABLE "setting" (
150 PRIMARY KEY ("member_id", "key"),
151 "member_id" INT4 REFERENCES "member" ("id") ON DELETE CASCADE ON UPDATE CASCADE,
152 "key" TEXT NOT NULL,
153 "value" TEXT NOT NULL );
154 CREATE INDEX "setting_key_idx" ON "setting" ("key");
156 COMMENT ON TABLE "setting" IS 'Place to store a frontend specific setting for members as a string';
158 COMMENT ON COLUMN "setting"."key" IS 'Name of the setting, preceded by a frontend specific prefix';
161 CREATE TABLE "setting_map" (
162 PRIMARY KEY ("member_id", "key", "subkey"),
163 "member_id" INT4 REFERENCES "member" ("id") ON DELETE CASCADE ON UPDATE CASCADE,
164 "key" TEXT NOT NULL,
165 "subkey" TEXT NOT NULL,
166 "value" TEXT NOT NULL );
167 CREATE INDEX "setting_map_key_idx" ON "setting_map" ("key");
169 COMMENT ON TABLE "setting_map" IS 'Place to store a frontend specific setting for members as a map of key value pairs';
171 COMMENT ON COLUMN "setting_map"."key" IS 'Name of the setting, preceded by a frontend specific prefix';
172 COMMENT ON COLUMN "setting_map"."subkey" IS 'Key of a map entry';
173 COMMENT ON COLUMN "setting_map"."value" IS 'Value of a map entry';
176 CREATE TABLE "member_relation_setting" (
177 PRIMARY KEY ("member_id", "key", "other_member_id"),
178 "member_id" INT4 REFERENCES "member" ("id") ON DELETE CASCADE ON UPDATE CASCADE,
179 "key" TEXT NOT NULL,
180 "other_member_id" INT4 REFERENCES "member" ("id") ON DELETE CASCADE ON UPDATE CASCADE,
181 "value" TEXT NOT NULL );
183 COMMENT ON TABLE "member_relation_setting" IS 'Place to store a frontend specific setting related to relations between members as a string';
186 CREATE TYPE "member_image_type" AS ENUM ('photo', 'avatar');
188 COMMENT ON TYPE "member_image_type" IS 'Types of images for a member';
191 CREATE TABLE "member_image" (
192 PRIMARY KEY ("member_id", "image_type", "scaled"),
193 "member_id" INT4 REFERENCES "member" ("id") ON DELETE CASCADE ON UPDATE CASCADE,
194 "image_type" "member_image_type",
195 "scaled" BOOLEAN,
196 "content_type" TEXT,
197 "data" BYTEA NOT NULL );
199 COMMENT ON TABLE "member_image" IS 'Images of members';
201 COMMENT ON COLUMN "member_image"."scaled" IS 'FALSE for original image, TRUE for scaled version of the image';
204 CREATE TABLE "member_count" (
205 "calculated" TIMESTAMPTZ NOT NULL DEFAULT NOW(),
206 "total_count" INT4 NOT NULL );
208 COMMENT ON TABLE "member_count" IS 'Contains one row which contains the total count of active(!) members and a timestamp indicating when the total member count and area member counts were calculated';
210 COMMENT ON COLUMN "member_count"."calculated" IS 'timestamp indicating when the total member count and area member counts were calculated';
211 COMMENT ON COLUMN "member_count"."total_count" IS 'Total count of active(!) members';
214 CREATE TABLE "contact" (
215 PRIMARY KEY ("member_id", "other_member_id"),
216 "member_id" INT4 REFERENCES "member" ("id") ON DELETE CASCADE ON UPDATE CASCADE,
217 "other_member_id" INT4 REFERENCES "member" ("id") ON DELETE CASCADE ON UPDATE CASCADE,
218 "public" BOOLEAN NOT NULL DEFAULT FALSE,
219 CONSTRAINT "cant_save_yourself_as_contact"
220 CHECK ("member_id" != "other_member_id") );
222 COMMENT ON TABLE "contact" IS 'Contact lists';
224 COMMENT ON COLUMN "contact"."member_id" IS 'Member having the contact list';
225 COMMENT ON COLUMN "contact"."other_member_id" IS 'Member referenced in the contact list';
226 COMMENT ON COLUMN "contact"."public" IS 'TRUE = display contact publically';
229 CREATE TABLE "session" (
230 "ident" TEXT PRIMARY KEY,
231 "additional_secret" TEXT,
232 "expiry" TIMESTAMPTZ NOT NULL DEFAULT now() + '24 hours',
233 "member_id" INT8 REFERENCES "member" ("id") ON DELETE SET NULL,
234 "lang" TEXT );
235 CREATE INDEX "session_expiry_idx" ON "session" ("expiry");
237 COMMENT ON TABLE "session" IS 'Sessions, i.e. for a web-frontend';
239 COMMENT ON COLUMN "session"."ident" IS 'Secret session identifier (i.e. random string)';
240 COMMENT ON COLUMN "session"."additional_secret" IS 'Additional field to store a secret, which can be used against CSRF attacks';
241 COMMENT ON COLUMN "session"."member_id" IS 'Reference to member, who is logged in';
242 COMMENT ON COLUMN "session"."lang" IS 'Language code of the selected language';
245 CREATE TABLE "policy" (
246 "id" SERIAL4 PRIMARY KEY,
247 "index" INT4 NOT NULL,
248 "active" BOOLEAN NOT NULL DEFAULT TRUE,
249 "name" TEXT NOT NULL UNIQUE,
250 "description" TEXT NOT NULL DEFAULT '',
251 "admission_time" INTERVAL NOT NULL,
252 "discussion_time" INTERVAL NOT NULL,
253 "verification_time" INTERVAL NOT NULL,
254 "voting_time" INTERVAL NOT NULL,
255 "issue_quorum_num" INT4 NOT NULL,
256 "issue_quorum_den" INT4 NOT NULL,
257 "initiative_quorum_num" INT4 NOT NULL,
258 "initiative_quorum_den" INT4 NOT NULL,
259 "majority_num" INT4 NOT NULL DEFAULT 1,
260 "majority_den" INT4 NOT NULL DEFAULT 2,
261 "majority_strict" BOOLEAN NOT NULL DEFAULT TRUE );
262 CREATE INDEX "policy_active_idx" ON "policy" ("active");
264 COMMENT ON TABLE "policy" IS 'Policies for a particular proceeding type (timelimits, quorum)';
266 COMMENT ON COLUMN "policy"."index" IS 'Determines the order in listings';
267 COMMENT ON COLUMN "policy"."active" IS 'TRUE = policy can be used for new issues';
268 COMMENT ON COLUMN "policy"."admission_time" IS 'Maximum time an issue stays open without being "accepted"';
269 COMMENT ON COLUMN "policy"."discussion_time" IS 'Regular time until an issue is "half_frozen" after being "accepted"';
270 COMMENT ON COLUMN "policy"."verification_time" IS 'Regular time until an issue is "fully_frozen" after being "half_frozen"';
271 COMMENT ON COLUMN "policy"."voting_time" IS 'Time after an issue is "fully_frozen" but not "closed"';
272 COMMENT ON COLUMN "policy"."issue_quorum_num" IS 'Numerator of potential supporter quorum to be reached by one initiative of an issue to be "accepted"';
273 COMMENT ON COLUMN "policy"."issue_quorum_den" IS 'Denominator of potential supporter quorum to be reached by one initiative of an issue to be "accepted"';
274 COMMENT ON COLUMN "policy"."initiative_quorum_num" IS 'Numerator of satisfied supporter quorum to be reached by an initiative to be "admitted" for voting';
275 COMMENT ON COLUMN "policy"."initiative_quorum_den" IS 'Denominator of satisfied supporter quorum to be reached by an initiative to be "admitted" for voting';
276 COMMENT ON COLUMN "policy"."majority_num" IS 'Numerator of fraction of majority to be reached during voting by an initiative to be aggreed upon';
277 COMMENT ON COLUMN "policy"."majority_den" IS 'Denominator of fraction of majority to be reached during voting by an initiative to be aggreed upon';
278 COMMENT ON COLUMN "policy"."majority_strict" IS 'If TRUE, then the majority must be strictly greater than "majority_num"/"majority_den", otherwise it may also be equal.';
281 CREATE TABLE "area" (
282 "id" SERIAL4 PRIMARY KEY,
283 "active" BOOLEAN NOT NULL DEFAULT TRUE,
284 "name" TEXT NOT NULL,
285 "description" TEXT NOT NULL DEFAULT '',
286 "direct_member_count" INT4,
287 "member_weight" INT4,
288 "autoreject_weight" INT4,
289 "text_search_data" TSVECTOR );
290 CREATE INDEX "area_active_idx" ON "area" ("active");
291 CREATE INDEX "area_text_search_data_idx" ON "area" USING gin ("text_search_data");
292 CREATE TRIGGER "update_text_search_data"
293 BEFORE INSERT OR UPDATE ON "area"
294 FOR EACH ROW EXECUTE PROCEDURE
295 tsvector_update_trigger('text_search_data', 'pg_catalog.simple',
296 "name", "description" );
298 COMMENT ON TABLE "area" IS 'Subject areas';
300 COMMENT ON COLUMN "area"."active" IS 'TRUE means new issues can be created in this area';
301 COMMENT ON COLUMN "area"."direct_member_count" IS 'Number of active members of that area (ignoring their weight), as calculated from view "area_member_count"';
302 COMMENT ON COLUMN "area"."member_weight" IS 'Same as "direct_member_count" but respecting delegations';
303 COMMENT ON COLUMN "area"."autoreject_weight" IS 'Sum of weight of members using the autoreject feature';
306 CREATE TABLE "area_setting" (
307 PRIMARY KEY ("member_id", "key", "area_id"),
308 "member_id" INT4 REFERENCES "member" ("id") ON DELETE CASCADE ON UPDATE CASCADE,
309 "key" TEXT NOT NULL,
310 "area_id" INT4 REFERENCES "area" ("id") ON DELETE CASCADE ON UPDATE CASCADE,
311 "value" TEXT NOT NULL );
313 COMMENT ON TABLE "area_setting" IS 'Place for frontend to store area specific settings of members as strings';
316 CREATE TABLE "allowed_policy" (
317 PRIMARY KEY ("area_id", "policy_id"),
318 "area_id" INT4 REFERENCES "area" ("id") ON DELETE CASCADE ON UPDATE CASCADE,
319 "policy_id" INT4 NOT NULL REFERENCES "policy" ("id") ON DELETE CASCADE ON UPDATE CASCADE,
320 "default_policy" BOOLEAN NOT NULL DEFAULT FALSE );
321 CREATE UNIQUE INDEX "allowed_policy_one_default_per_area_idx" ON "allowed_policy" ("area_id") WHERE "default_policy";
323 COMMENT ON TABLE "allowed_policy" IS 'Selects which policies can be used in each area';
325 COMMENT ON COLUMN "allowed_policy"."default_policy" IS 'One policy per area can be set as default.';
328 CREATE TYPE "snapshot_event" AS ENUM ('periodic', 'end_of_admission', 'half_freeze', 'full_freeze');
330 COMMENT ON TYPE "snapshot_event" IS 'Reason for snapshots: ''periodic'' = due to periodic recalculation, ''end_of_admission'' = saved state at end of admission period, ''half_freeze'' = saved state at end of discussion period, ''full_freeze'' = saved state at end of verification period';
333 CREATE TABLE "issue" (
334 "id" SERIAL4 PRIMARY KEY,
335 "area_id" INT4 NOT NULL REFERENCES "area" ("id") ON DELETE CASCADE ON UPDATE CASCADE,
336 "policy_id" INT4 NOT NULL REFERENCES "policy" ("id") ON DELETE RESTRICT ON UPDATE CASCADE,
337 "created" TIMESTAMPTZ NOT NULL DEFAULT now(),
338 "accepted" TIMESTAMPTZ,
339 "half_frozen" TIMESTAMPTZ,
340 "fully_frozen" TIMESTAMPTZ,
341 "closed" TIMESTAMPTZ,
342 "ranks_available" BOOLEAN NOT NULL DEFAULT FALSE,
343 "admission_time" INTERVAL NOT NULL,
344 "discussion_time" INTERVAL NOT NULL,
345 "verification_time" INTERVAL NOT NULL,
346 "voting_time" INTERVAL NOT NULL,
347 "snapshot" TIMESTAMPTZ,
348 "latest_snapshot_event" "snapshot_event",
349 "population" INT4,
350 "vote_now" INT4,
351 "vote_later" INT4,
352 "voter_count" INT4,
353 CONSTRAINT "valid_state" CHECK (
354 ("accepted" ISNULL AND "half_frozen" ISNULL AND "fully_frozen" ISNULL AND "closed" ISNULL AND "ranks_available" = FALSE) OR
355 ("accepted" ISNULL AND "half_frozen" ISNULL AND "fully_frozen" ISNULL AND "closed" NOTNULL AND "ranks_available" = FALSE) OR
356 ("accepted" NOTNULL AND "half_frozen" ISNULL AND "fully_frozen" ISNULL AND "closed" ISNULL AND "ranks_available" = FALSE) OR
357 ("accepted" NOTNULL AND "half_frozen" ISNULL AND "fully_frozen" ISNULL AND "closed" NOTNULL AND "ranks_available" = FALSE) OR
358 ("accepted" NOTNULL AND "half_frozen" NOTNULL AND "fully_frozen" ISNULL AND "closed" ISNULL AND "ranks_available" = FALSE) OR
359 ("accepted" NOTNULL AND "half_frozen" NOTNULL AND "fully_frozen" ISNULL AND "closed" NOTNULL AND "ranks_available" = FALSE) OR
360 ("accepted" NOTNULL AND "half_frozen" NOTNULL AND "fully_frozen" NOTNULL AND "closed" ISNULL AND "ranks_available" = FALSE) OR
361 ("accepted" NOTNULL AND "half_frozen" NOTNULL AND "fully_frozen" NOTNULL AND "closed" NOTNULL AND "ranks_available" = FALSE) OR
362 ("accepted" NOTNULL AND "half_frozen" NOTNULL AND "fully_frozen" NOTNULL AND "closed" NOTNULL AND "ranks_available" = TRUE) ),
363 CONSTRAINT "state_change_order" CHECK (
364 "created" <= "accepted" AND
365 "accepted" <= "half_frozen" AND
366 "half_frozen" <= "fully_frozen" AND
367 "fully_frozen" <= "closed" ),
368 CONSTRAINT "last_snapshot_on_full_freeze"
369 CHECK ("snapshot" = "fully_frozen"), -- NOTE: snapshot can be set, while frozen is NULL yet
370 CONSTRAINT "freeze_requires_snapshot"
371 CHECK ("fully_frozen" ISNULL OR "snapshot" NOTNULL),
372 CONSTRAINT "set_both_or_none_of_snapshot_and_latest_snapshot_event"
373 CHECK ("snapshot" NOTNULL = "latest_snapshot_event" NOTNULL) );
374 CREATE INDEX "issue_area_id_idx" ON "issue" ("area_id");
375 CREATE INDEX "issue_policy_id_idx" ON "issue" ("policy_id");
376 CREATE INDEX "issue_created_idx" ON "issue" ("created");
377 CREATE INDEX "issue_accepted_idx" ON "issue" ("accepted");
378 CREATE INDEX "issue_half_frozen_idx" ON "issue" ("half_frozen");
379 CREATE INDEX "issue_fully_frozen_idx" ON "issue" ("fully_frozen");
380 CREATE INDEX "issue_closed_idx" ON "issue" ("closed");
381 CREATE INDEX "issue_created_idx_open" ON "issue" ("created") WHERE "closed" ISNULL;
382 CREATE INDEX "issue_closed_idx_canceled" ON "issue" ("closed") WHERE "fully_frozen" ISNULL;
384 COMMENT ON TABLE "issue" IS 'Groups of initiatives';
386 COMMENT ON COLUMN "issue"."accepted" IS 'Point in time, when one initiative of issue reached the "issue_quorum"';
387 COMMENT ON COLUMN "issue"."half_frozen" IS 'Point in time, when "discussion_time" has elapsed, or members voted for voting; Frontends must ensure that for half_frozen issues a) initiatives are not revoked, b) no new drafts are created, c) no initiators are added or removed.';
388 COMMENT ON COLUMN "issue"."fully_frozen" IS 'Point in time, when "verification_time" has elapsed; Frontends must ensure that for fully_frozen issues additionally to the restrictions for half_frozen issues a) initiatives are not created, b) no interest is created or removed, c) no supporters are added or removed, d) no opinions are created, changed or deleted.';
389 COMMENT ON COLUMN "issue"."closed" IS 'Point in time, when "admission_time" or "voting_time" have elapsed, and issue is no longer active; Frontends must ensure that for closed issues additionally to the restrictions for half_frozen and fully_frozen issues a) no voter is added or removed to/from the direct_voter table, b) no votes are added, modified or removed.';
390 COMMENT ON COLUMN "issue"."ranks_available" IS 'TRUE = ranks have been calculated';
391 COMMENT ON COLUMN "issue"."admission_time" IS 'Copied from "policy" table at creation of issue';
392 COMMENT ON COLUMN "issue"."discussion_time" IS 'Copied from "policy" table at creation of issue';
393 COMMENT ON COLUMN "issue"."verification_time" IS 'Copied from "policy" table at creation of issue';
394 COMMENT ON COLUMN "issue"."voting_time" IS 'Copied from "policy" table at creation of issue';
395 COMMENT ON COLUMN "issue"."snapshot" IS 'Point in time, when snapshot tables have been updated and "population", "vote_now", "vote_later" and *_count values were precalculated';
396 COMMENT ON COLUMN "issue"."latest_snapshot_event" IS 'Event type of latest snapshot for issue; Can be used to select the latest snapshot data in the snapshot tables';
397 COMMENT ON COLUMN "issue"."population" IS 'Sum of "weight" column in table "direct_population_snapshot"';
398 COMMENT ON COLUMN "issue"."vote_now" IS 'Number of votes in favor of voting now, as calculated from table "direct_interest_snapshot"';
399 COMMENT ON COLUMN "issue"."vote_later" IS 'Number of votes against voting now, as calculated from table "direct_interest_snapshot"';
400 COMMENT ON COLUMN "issue"."voter_count" IS 'Total number of direct and delegating voters; This value is related to the final voting, while "population" is related to snapshots before the final voting';
403 CREATE TABLE "issue_setting" (
404 PRIMARY KEY ("member_id", "key", "issue_id"),
405 "member_id" INT4 REFERENCES "member" ("id") ON DELETE CASCADE ON UPDATE CASCADE,
406 "key" TEXT NOT NULL,
407 "issue_id" INT4 REFERENCES "issue" ("id") ON DELETE CASCADE ON UPDATE CASCADE,
408 "value" TEXT NOT NULL );
410 COMMENT ON TABLE "issue_setting" IS 'Place for frontend to store issue specific settings of members as strings';
413 CREATE TABLE "initiative" (
414 UNIQUE ("issue_id", "id"), -- index needed for foreign-key on table "vote"
415 "issue_id" INT4 NOT NULL REFERENCES "issue" ("id") ON DELETE CASCADE ON UPDATE CASCADE,
416 "id" SERIAL4 PRIMARY KEY,
417 "name" TEXT NOT NULL,
418 "discussion_url" TEXT,
419 "created" TIMESTAMPTZ NOT NULL DEFAULT now(),
420 "revoked" TIMESTAMPTZ,
421 "suggested_initiative_id" INT4 REFERENCES "initiative" ("id") ON DELETE CASCADE ON UPDATE CASCADE,
422 "admitted" BOOLEAN,
423 "supporter_count" INT4,
424 "informed_supporter_count" INT4,
425 "satisfied_supporter_count" INT4,
426 "satisfied_informed_supporter_count" INT4,
427 "positive_votes" INT4,
428 "negative_votes" INT4,
429 "agreed" BOOLEAN,
430 "rank" INT4,
431 "text_search_data" TSVECTOR,
432 CONSTRAINT "non_revoked_initiatives_cant_suggest_other"
433 CHECK ("revoked" NOTNULL OR "suggested_initiative_id" ISNULL),
434 CONSTRAINT "revoked_initiatives_cant_be_admitted"
435 CHECK ("revoked" ISNULL OR "admitted" ISNULL),
436 CONSTRAINT "non_admitted_initiatives_cant_contain_voting_results"
437 CHECK (("admitted" NOTNULL AND "admitted" = TRUE) OR ("positive_votes" ISNULL AND "negative_votes" ISNULL AND "agreed" ISNULL)),
438 CONSTRAINT "all_or_none_of_positive_votes_negative_votes_and_agreed_must_be_null"
439 CHECK ("positive_votes" NOTNULL = "negative_votes" NOTNULL AND "positive_votes" NOTNULL = "agreed" NOTNULL),
440 CONSTRAINT "non_agreed_initiatives_cant_get_a_rank"
441 CHECK (("agreed" NOTNULL AND "agreed" = TRUE) OR "rank" ISNULL) );
442 CREATE INDEX "initiative_created_idx" ON "initiative" ("created");
443 CREATE INDEX "initiative_revoked_idx" ON "initiative" ("revoked");
444 CREATE INDEX "initiative_text_search_data_idx" ON "initiative" USING gin ("text_search_data");
445 CREATE TRIGGER "update_text_search_data"
446 BEFORE INSERT OR UPDATE ON "initiative"
447 FOR EACH ROW EXECUTE PROCEDURE
448 tsvector_update_trigger('text_search_data', 'pg_catalog.simple',
449 "name", "discussion_url");
451 COMMENT ON TABLE "initiative" IS 'Group of members publishing drafts for resolutions to be passed; Frontends must ensure that initiatives of half_frozen issues are not revoked, and that initiatives of fully_frozen or closed issues are neither revoked nor created.';
453 COMMENT ON COLUMN "initiative"."discussion_url" IS 'URL pointing to a discussion platform for this initiative';
454 COMMENT ON COLUMN "initiative"."revoked" IS 'Point in time, when one initiator decided to revoke the initiative';
455 COMMENT ON COLUMN "initiative"."admitted" IS 'TRUE, if initiative reaches the "initiative_quorum" when freezing the issue';
456 COMMENT ON COLUMN "initiative"."supporter_count" IS 'Calculated from table "direct_supporter_snapshot"';
457 COMMENT ON COLUMN "initiative"."informed_supporter_count" IS 'Calculated from table "direct_supporter_snapshot"';
458 COMMENT ON COLUMN "initiative"."satisfied_supporter_count" IS 'Calculated from table "direct_supporter_snapshot"';
459 COMMENT ON COLUMN "initiative"."satisfied_informed_supporter_count" IS 'Calculated from table "direct_supporter_snapshot"';
460 COMMENT ON COLUMN "initiative"."positive_votes" IS 'Calculated from table "direct_voter"';
461 COMMENT ON COLUMN "initiative"."negative_votes" IS 'Calculated from table "direct_voter"';
462 COMMENT ON COLUMN "initiative"."agreed" IS 'TRUE, if "positive_votes"/("positive_votes"+"negative_votes") is strictly greater or greater-equal than "majority_num"/"majority_den"';
463 COMMENT ON COLUMN "initiative"."rank" IS 'Rank of approved initiatives (winner is 1), calculated from table "direct_voter"';
466 CREATE TABLE "initiative_setting" (
467 PRIMARY KEY ("member_id", "key", "initiative_id"),
468 "member_id" INT4 REFERENCES "member" ("id") ON DELETE CASCADE ON UPDATE CASCADE,
469 "key" TEXT NOT NULL,
470 "initiative_id" INT4 REFERENCES "initiative" ("id") ON DELETE CASCADE ON UPDATE CASCADE,
471 "value" TEXT NOT NULL );
473 COMMENT ON TABLE "initiative_setting" IS 'Place for frontend to store initiative specific settings of members as strings';
476 CREATE TABLE "draft" (
477 UNIQUE ("initiative_id", "id"), -- index needed for foreign-key on table "supporter"
478 "initiative_id" INT4 NOT NULL REFERENCES "initiative" ("id") ON DELETE CASCADE ON UPDATE CASCADE,
479 "id" SERIAL8 PRIMARY KEY,
480 "created" TIMESTAMPTZ NOT NULL DEFAULT now(),
481 "author_id" INT4 NOT NULL REFERENCES "member" ("id") ON DELETE RESTRICT ON UPDATE CASCADE,
482 "formatting_engine" TEXT,
483 "content" TEXT NOT NULL,
484 "text_search_data" TSVECTOR );
485 CREATE INDEX "draft_created_idx" ON "draft" ("created");
486 CREATE INDEX "draft_author_id_created_idx" ON "draft" ("author_id", "created");
487 CREATE INDEX "draft_text_search_data_idx" ON "draft" USING gin ("text_search_data");
488 CREATE TRIGGER "update_text_search_data"
489 BEFORE INSERT OR UPDATE ON "draft"
490 FOR EACH ROW EXECUTE PROCEDURE
491 tsvector_update_trigger('text_search_data', 'pg_catalog.simple', "content");
493 COMMENT ON TABLE "draft" IS 'Drafts of initiatives to solve issues; Frontends must ensure that new drafts for initiatives of half_frozen, fully_frozen or closed issues can''t be created.';
495 COMMENT ON COLUMN "draft"."formatting_engine" IS 'Allows different formatting engines (i.e. wiki formats) to be used';
496 COMMENT ON COLUMN "draft"."content" IS 'Text of the draft in a format depending on the field "formatting_engine"';
499 CREATE TABLE "suggestion" (
500 UNIQUE ("initiative_id", "id"), -- index needed for foreign-key on table "opinion"
501 "initiative_id" INT4 NOT NULL REFERENCES "initiative" ("id") ON DELETE CASCADE ON UPDATE CASCADE,
502 "id" SERIAL8 PRIMARY KEY,
503 "created" TIMESTAMPTZ NOT NULL DEFAULT now(),
504 "author_id" INT4 NOT NULL REFERENCES "member" ("id") ON DELETE RESTRICT ON UPDATE CASCADE,
505 "name" TEXT NOT NULL,
506 "description" TEXT NOT NULL DEFAULT '',
507 "text_search_data" TSVECTOR,
508 "minus2_unfulfilled_count" INT4,
509 "minus2_fulfilled_count" INT4,
510 "minus1_unfulfilled_count" INT4,
511 "minus1_fulfilled_count" INT4,
512 "plus1_unfulfilled_count" INT4,
513 "plus1_fulfilled_count" INT4,
514 "plus2_unfulfilled_count" INT4,
515 "plus2_fulfilled_count" INT4 );
516 CREATE INDEX "suggestion_created_idx" ON "suggestion" ("created");
517 CREATE INDEX "suggestion_author_id_created_idx" ON "suggestion" ("author_id", "created");
518 CREATE INDEX "suggestion_text_search_data_idx" ON "suggestion" USING gin ("text_search_data");
519 CREATE TRIGGER "update_text_search_data"
520 BEFORE INSERT OR UPDATE ON "suggestion"
521 FOR EACH ROW EXECUTE PROCEDURE
522 tsvector_update_trigger('text_search_data', 'pg_catalog.simple',
523 "name", "description");
525 COMMENT ON TABLE "suggestion" IS 'Suggestions to initiators, to change the current draft; must not be deleted explicitly, as they vanish automatically if the last opinion is deleted';
527 COMMENT ON COLUMN "suggestion"."minus2_unfulfilled_count" IS 'Calculated from table "direct_supporter_snapshot", not requiring informed supporters';
528 COMMENT ON COLUMN "suggestion"."minus2_fulfilled_count" IS 'Calculated from table "direct_supporter_snapshot", not requiring informed supporters';
529 COMMENT ON COLUMN "suggestion"."minus1_unfulfilled_count" IS 'Calculated from table "direct_supporter_snapshot", not requiring informed supporters';
530 COMMENT ON COLUMN "suggestion"."minus1_fulfilled_count" IS 'Calculated from table "direct_supporter_snapshot", not requiring informed supporters';
531 COMMENT ON COLUMN "suggestion"."plus1_unfulfilled_count" IS 'Calculated from table "direct_supporter_snapshot", not requiring informed supporters';
532 COMMENT ON COLUMN "suggestion"."plus1_fulfilled_count" IS 'Calculated from table "direct_supporter_snapshot", not requiring informed supporters';
533 COMMENT ON COLUMN "suggestion"."plus2_unfulfilled_count" IS 'Calculated from table "direct_supporter_snapshot", not requiring informed supporters';
534 COMMENT ON COLUMN "suggestion"."plus2_fulfilled_count" IS 'Calculated from table "direct_supporter_snapshot", not requiring informed supporters';
537 CREATE TABLE "suggestion_setting" (
538 PRIMARY KEY ("member_id", "key", "suggestion_id"),
539 "member_id" INT4 REFERENCES "member" ("id") ON DELETE CASCADE ON UPDATE CASCADE,
540 "key" TEXT NOT NULL,
541 "suggestion_id" INT8 REFERENCES "suggestion" ("id") ON DELETE CASCADE ON UPDATE CASCADE,
542 "value" TEXT NOT NULL );
544 COMMENT ON TABLE "suggestion_setting" IS 'Place for frontend to store suggestion specific settings of members as strings';
547 CREATE TABLE "membership" (
548 PRIMARY KEY ("area_id", "member_id"),
549 "area_id" INT4 REFERENCES "area" ("id") ON DELETE CASCADE ON UPDATE CASCADE,
550 "member_id" INT4 REFERENCES "member" ("id") ON DELETE CASCADE ON UPDATE CASCADE,
551 "autoreject" BOOLEAN NOT NULL DEFAULT FALSE );
552 CREATE INDEX "membership_member_id_idx" ON "membership" ("member_id");
554 COMMENT ON TABLE "membership" IS 'Interest of members in topic areas';
556 COMMENT ON COLUMN "membership"."autoreject" IS 'TRUE = member votes against all initiatives in case of not explicitly taking part in the voting procedure; If there exists an "interest" entry, the interest entry has precedence';
559 CREATE TABLE "interest" (
560 PRIMARY KEY ("issue_id", "member_id"),
561 "issue_id" INT4 REFERENCES "issue" ("id") ON DELETE CASCADE ON UPDATE CASCADE,
562 "member_id" INT4 REFERENCES "member" ("id") ON DELETE CASCADE ON UPDATE CASCADE,
563 "autoreject" BOOLEAN NOT NULL,
564 "voting_requested" BOOLEAN );
565 CREATE INDEX "interest_member_id_idx" ON "interest" ("member_id");
567 COMMENT ON TABLE "interest" IS 'Interest of members in a particular issue; Frontends must ensure that interest for fully_frozen or closed issues is not added or removed.';
569 COMMENT ON COLUMN "interest"."autoreject" IS 'TRUE = member votes against all initiatives in case of not explicitly taking part in the voting procedure';
570 COMMENT ON COLUMN "interest"."voting_requested" IS 'TRUE = member wants to vote now, FALSE = member wants to vote later, NULL = policy rules should apply';
573 CREATE TABLE "initiator" (
574 PRIMARY KEY ("initiative_id", "member_id"),
575 "initiative_id" INT4 REFERENCES "initiative" ("id") ON DELETE CASCADE ON UPDATE CASCADE,
576 "member_id" INT4 REFERENCES "member" ("id") ON DELETE CASCADE ON UPDATE CASCADE,
577 "accepted" BOOLEAN );
578 CREATE INDEX "initiator_member_id_idx" ON "initiator" ("member_id");
580 COMMENT ON TABLE "initiator" IS 'Members who are allowed to post new drafts; Frontends must ensure that initiators are not added or removed from half_frozen, fully_frozen or closed initiatives.';
582 COMMENT ON COLUMN "initiator"."accepted" IS 'If "accepted" is NULL, then the member was invited to be a co-initiator, but has not answered yet. If it is TRUE, the member has accepted the invitation, if it is FALSE, the member has rejected the invitation.';
585 CREATE TABLE "supporter" (
586 "issue_id" INT4 NOT NULL,
587 PRIMARY KEY ("initiative_id", "member_id"),
588 "initiative_id" INT4,
589 "member_id" INT4,
590 "draft_id" INT8 NOT NULL,
591 FOREIGN KEY ("issue_id", "member_id") REFERENCES "interest" ("issue_id", "member_id") ON DELETE CASCADE ON UPDATE CASCADE,
592 FOREIGN KEY ("initiative_id", "draft_id") REFERENCES "draft" ("initiative_id", "id") ON DELETE CASCADE ON UPDATE CASCADE );
593 CREATE INDEX "supporter_member_id_idx" ON "supporter" ("member_id");
595 COMMENT ON TABLE "supporter" IS 'Members who support an initiative (conditionally); Frontends must ensure that supporters are not added or removed from fully_frozen or closed initiatives.';
597 COMMENT ON COLUMN "supporter"."draft_id" IS 'Latest seen draft, defaults to current draft of the initiative (implemented by trigger "default_for_draft_id")';
600 CREATE TABLE "opinion" (
601 "initiative_id" INT4 NOT NULL,
602 PRIMARY KEY ("suggestion_id", "member_id"),
603 "suggestion_id" INT8,
604 "member_id" INT4,
605 "degree" INT2 NOT NULL CHECK ("degree" >= -2 AND "degree" <= 2 AND "degree" != 0),
606 "fulfilled" BOOLEAN NOT NULL DEFAULT FALSE,
607 FOREIGN KEY ("initiative_id", "suggestion_id") REFERENCES "suggestion" ("initiative_id", "id") ON DELETE CASCADE ON UPDATE CASCADE,
608 FOREIGN KEY ("initiative_id", "member_id") REFERENCES "supporter" ("initiative_id", "member_id") ON DELETE CASCADE ON UPDATE CASCADE );
609 CREATE INDEX "opinion_member_id_initiative_id_idx" ON "opinion" ("member_id", "initiative_id");
611 COMMENT ON TABLE "opinion" IS 'Opinion on suggestions (criticism related to initiatives); Frontends must ensure that opinions are not created modified or deleted when related to fully_frozen or closed issues.';
613 COMMENT ON COLUMN "opinion"."degree" IS '2 = fulfillment required for support; 1 = fulfillment desired; -1 = fulfillment unwanted; -2 = fulfillment cancels support';
616 CREATE TYPE "delegation_scope" AS ENUM ('global', 'area', 'issue');
618 COMMENT ON TYPE "delegation_scope" IS 'Scope for delegations: ''global'', ''area'', or ''issue'' (order is relevant)';
621 CREATE TABLE "delegation" (
622 "id" SERIAL8 PRIMARY KEY,
623 "truster_id" INT4 NOT NULL REFERENCES "member" ("id") ON DELETE CASCADE ON UPDATE CASCADE,
624 "trustee_id" INT4 NOT NULL REFERENCES "member" ("id") ON DELETE CASCADE ON UPDATE CASCADE,
625 "scope" "delegation_scope" NOT NULL,
626 "area_id" INT4 REFERENCES "area" ("id") ON DELETE CASCADE ON UPDATE CASCADE,
627 "issue_id" INT4 REFERENCES "issue" ("id") ON DELETE CASCADE ON UPDATE CASCADE,
628 CONSTRAINT "cant_delegate_to_yourself" CHECK ("truster_id" != "trustee_id"),
629 CONSTRAINT "area_id_and_issue_id_set_according_to_scope" CHECK (
630 ("scope" = 'global' AND "area_id" ISNULL AND "issue_id" ISNULL ) OR
631 ("scope" = 'area' AND "area_id" NOTNULL AND "issue_id" ISNULL ) OR
632 ("scope" = 'issue' AND "area_id" ISNULL AND "issue_id" NOTNULL) ),
633 UNIQUE ("area_id", "truster_id", "trustee_id"),
634 UNIQUE ("issue_id", "truster_id", "trustee_id") );
635 CREATE UNIQUE INDEX "delegation_global_truster_id_trustee_id_unique_idx"
636 ON "delegation" ("truster_id", "trustee_id") WHERE "scope" = 'global';
637 CREATE INDEX "delegation_truster_id_idx" ON "delegation" ("truster_id");
638 CREATE INDEX "delegation_trustee_id_idx" ON "delegation" ("trustee_id");
640 COMMENT ON TABLE "delegation" IS 'Delegation of vote-weight to other members';
642 COMMENT ON COLUMN "delegation"."area_id" IS 'Reference to area, if delegation is area-wide, otherwise NULL';
643 COMMENT ON COLUMN "delegation"."issue_id" IS 'Reference to issue, if delegation is issue-wide, otherwise NULL';
646 CREATE TABLE "direct_population_snapshot" (
647 PRIMARY KEY ("issue_id", "event", "member_id"),
648 "issue_id" INT4 REFERENCES "issue" ("id") ON DELETE CASCADE ON UPDATE CASCADE,
649 "event" "snapshot_event",
650 "member_id" INT4 REFERENCES "member" ("id") ON DELETE RESTRICT ON UPDATE RESTRICT,
651 "weight" INT4 );
652 CREATE INDEX "direct_population_snapshot_member_id_idx" ON "direct_population_snapshot" ("member_id");
654 COMMENT ON TABLE "direct_population_snapshot" IS 'Snapshot of active members having either a "membership" in the "area" or an "interest" in the "issue"';
656 COMMENT ON COLUMN "direct_population_snapshot"."event" IS 'Reason for snapshot, see "snapshot_event" type for details';
657 COMMENT ON COLUMN "direct_population_snapshot"."weight" IS 'Weight of member (1 or higher) according to "delegating_population_snapshot"';
660 CREATE TABLE "delegating_population_snapshot" (
661 PRIMARY KEY ("issue_id", "event", "member_id"),
662 "issue_id" INT4 REFERENCES "issue" ("id") ON DELETE CASCADE ON UPDATE CASCADE,
663 "event" "snapshot_event",
664 "member_id" INT4 REFERENCES "member" ("id") ON DELETE RESTRICT ON UPDATE RESTRICT,
665 "weight" INT4,
666 "scope" "delegation_scope" NOT NULL,
667 "delegate_member_ids" INT4[] NOT NULL );
668 CREATE INDEX "delegating_population_snapshot_member_id_idx" ON "delegating_population_snapshot" ("member_id");
670 COMMENT ON TABLE "direct_population_snapshot" IS 'Delegations increasing the weight of entries in the "direct_population_snapshot" table';
672 COMMENT ON COLUMN "delegating_population_snapshot"."event" IS 'Reason for snapshot, see "snapshot_event" type for details';
673 COMMENT ON COLUMN "delegating_population_snapshot"."member_id" IS 'Delegating member';
674 COMMENT ON COLUMN "delegating_population_snapshot"."weight" IS 'Intermediate weight';
675 COMMENT ON COLUMN "delegating_population_snapshot"."delegate_member_ids" IS 'Chain of members who act as delegates; last entry referes to "member_id" column of table "direct_population_snapshot"';
678 CREATE TABLE "direct_interest_snapshot" (
679 PRIMARY KEY ("issue_id", "event", "member_id"),
680 "issue_id" INT4 REFERENCES "issue" ("id") ON DELETE CASCADE ON UPDATE CASCADE,
681 "event" "snapshot_event",
682 "member_id" INT4 REFERENCES "member" ("id") ON DELETE RESTRICT ON UPDATE RESTRICT,
683 "weight" INT4,
684 "voting_requested" BOOLEAN );
685 CREATE INDEX "direct_interest_snapshot_member_id_idx" ON "direct_interest_snapshot" ("member_id");
687 COMMENT ON TABLE "direct_interest_snapshot" IS 'Snapshot of active members having an "interest" in the "issue"';
689 COMMENT ON COLUMN "direct_interest_snapshot"."event" IS 'Reason for snapshot, see "snapshot_event" type for details';
690 COMMENT ON COLUMN "direct_interest_snapshot"."weight" IS 'Weight of member (1 or higher) according to "delegating_interest_snapshot"';
691 COMMENT ON COLUMN "direct_interest_snapshot"."voting_requested" IS 'Copied from column "voting_requested" of table "interest"';
694 CREATE TABLE "delegating_interest_snapshot" (
695 PRIMARY KEY ("issue_id", "event", "member_id"),
696 "issue_id" INT4 REFERENCES "issue" ("id") ON DELETE CASCADE ON UPDATE CASCADE,
697 "event" "snapshot_event",
698 "member_id" INT4 REFERENCES "member" ("id") ON DELETE RESTRICT ON UPDATE RESTRICT,
699 "weight" INT4,
700 "scope" "delegation_scope" NOT NULL,
701 "delegate_member_ids" INT4[] NOT NULL );
702 CREATE INDEX "delegating_interest_snapshot_member_id_idx" ON "delegating_interest_snapshot" ("member_id");
704 COMMENT ON TABLE "delegating_interest_snapshot" IS 'Delegations increasing the weight of entries in the "direct_interest_snapshot" table';
706 COMMENT ON COLUMN "delegating_interest_snapshot"."event" IS 'Reason for snapshot, see "snapshot_event" type for details';
707 COMMENT ON COLUMN "delegating_interest_snapshot"."member_id" IS 'Delegating member';
708 COMMENT ON COLUMN "delegating_interest_snapshot"."weight" IS 'Intermediate weight';
709 COMMENT ON COLUMN "delegating_interest_snapshot"."delegate_member_ids" IS 'Chain of members who act as delegates; last entry referes to "member_id" column of table "direct_interest_snapshot"';
712 CREATE TABLE "direct_supporter_snapshot" (
713 "issue_id" INT4 NOT NULL,
714 PRIMARY KEY ("initiative_id", "event", "member_id"),
715 "initiative_id" INT4,
716 "event" "snapshot_event",
717 "member_id" INT4 REFERENCES "member" ("id") ON DELETE RESTRICT ON UPDATE RESTRICT,
718 "informed" BOOLEAN NOT NULL,
719 "satisfied" BOOLEAN NOT NULL,
720 FOREIGN KEY ("issue_id", "initiative_id") REFERENCES "initiative" ("issue_id", "id") ON DELETE CASCADE ON UPDATE CASCADE,
721 FOREIGN KEY ("issue_id", "event", "member_id") REFERENCES "direct_interest_snapshot" ("issue_id", "event", "member_id") ON DELETE CASCADE ON UPDATE CASCADE );
722 CREATE INDEX "direct_supporter_snapshot_member_id_idx" ON "direct_supporter_snapshot" ("member_id");
724 COMMENT ON TABLE "direct_supporter_snapshot" IS 'Snapshot of supporters of initiatives (weight is stored in "direct_interest_snapshot")';
726 COMMENT ON COLUMN "direct_supporter_snapshot"."event" IS 'Reason for snapshot, see "snapshot_event" type for details';
727 COMMENT ON COLUMN "direct_supporter_snapshot"."informed" IS 'Supporter has seen the latest draft of the initiative';
728 COMMENT ON COLUMN "direct_supporter_snapshot"."satisfied" IS 'Supporter has no "critical_opinion"s';
731 CREATE TABLE "direct_voter" (
732 PRIMARY KEY ("issue_id", "member_id"),
733 "issue_id" INT4 REFERENCES "issue" ("id") ON DELETE CASCADE ON UPDATE CASCADE,
734 "member_id" INT4 REFERENCES "member" ("id") ON DELETE RESTRICT ON UPDATE RESTRICT,
735 "weight" INT4,
736 "autoreject" BOOLEAN NOT NULL DEFAULT FALSE );
737 CREATE INDEX "direct_voter_member_id_idx" ON "direct_voter" ("member_id");
739 COMMENT ON TABLE "direct_voter" IS 'Members having directly voted for/against initiatives of an issue; Frontends must ensure that no voters are added or removed to/from this table when the issue has been closed.';
741 COMMENT ON COLUMN "direct_voter"."weight" IS 'Weight of member (1 or higher) according to "delegating_voter" table';
742 COMMENT ON COLUMN "direct_voter"."autoreject" IS 'Votes were inserted due to "autoreject" feature';
745 CREATE TABLE "delegating_voter" (
746 PRIMARY KEY ("issue_id", "member_id"),
747 "issue_id" INT4 REFERENCES "issue" ("id") ON DELETE CASCADE ON UPDATE CASCADE,
748 "member_id" INT4 REFERENCES "member" ("id") ON DELETE RESTRICT ON UPDATE RESTRICT,
749 "weight" INT4,
750 "scope" "delegation_scope" NOT NULL,
751 "delegate_member_ids" INT4[] NOT NULL );
752 CREATE INDEX "delegating_voter_member_id_idx" ON "delegating_voter" ("member_id");
754 COMMENT ON TABLE "delegating_voter" IS 'Delegations increasing the weight of entries in the "direct_voter" table';
756 COMMENT ON COLUMN "delegating_voter"."member_id" IS 'Delegating member';
757 COMMENT ON COLUMN "delegating_voter"."weight" IS 'Intermediate weight';
758 COMMENT ON COLUMN "delegating_voter"."delegate_member_ids" IS 'Chain of members who act as delegates; last entry referes to "member_id" column of table "direct_voter"';
761 CREATE TABLE "vote" (
762 "issue_id" INT4 NOT NULL,
763 PRIMARY KEY ("initiative_id", "member_id"),
764 "initiative_id" INT4,
765 "member_id" INT4,
766 "grade" INT4,
767 FOREIGN KEY ("issue_id", "initiative_id") REFERENCES "initiative" ("issue_id", "id") ON DELETE CASCADE ON UPDATE CASCADE,
768 FOREIGN KEY ("issue_id", "member_id") REFERENCES "direct_voter" ("issue_id", "member_id") ON DELETE CASCADE ON UPDATE CASCADE );
769 CREATE INDEX "vote_member_id_idx" ON "vote" ("member_id");
771 COMMENT ON TABLE "vote" IS 'Manual and delegated votes without abstentions; Frontends must ensure that no votes are added modified or removed when the issue has been closed.';
773 COMMENT ON COLUMN "vote"."grade" IS 'Values smaller than zero mean reject, values greater than zero mean acceptance, zero or missing row means abstention. Preferences are expressed by different positive or negative numbers.';
776 CREATE TABLE "contingent" (
777 "time_frame" INTERVAL PRIMARY KEY,
778 "text_entry_limit" INT4,
779 "initiative_limit" INT4 );
781 COMMENT ON TABLE "contingent" IS 'Amount of text entries or initiatives a user may create within a given time frame. Only one row needs to be fulfilled for a member to be allowed to post. This table must not be empty.';
783 COMMENT ON COLUMN "contingent"."text_entry_limit" IS 'Number of new drafts or suggestions to be submitted by each member within the given time frame';
784 COMMENT ON COLUMN "contingent"."initiative_limit" IS 'Number of new initiatives to be opened by each member within a given time frame';
788 --------------------------------
789 -- Writing of history entries --
790 --------------------------------
792 CREATE FUNCTION "write_member_history_trigger"()
793 RETURNS TRIGGER
794 LANGUAGE 'plpgsql' VOLATILE AS $$
795 BEGIN
796 IF
797 ( NEW."login" NOTNULL AND OLD."login" NOTNULL AND
798 NEW."login" != OLD."login" ) OR
799 ( NEW."login" NOTNULL AND OLD."login" ISNULL ) OR
800 ( NEW."login" ISNULL AND OLD."login" NOTNULL ) OR
801 NEW."active" != OLD."active" OR
802 NEW."name" != OLD."name"
803 THEN
804 INSERT INTO "member_history"
805 ("member_id", "login", "active", "name")
806 VALUES (NEW."id", OLD."login", OLD."active", OLD."name");
807 END IF;
808 RETURN NULL;
809 END;
810 $$;
812 CREATE TRIGGER "write_member_history"
813 AFTER UPDATE ON "member" FOR EACH ROW EXECUTE PROCEDURE
814 "write_member_history_trigger"();
816 COMMENT ON FUNCTION "write_member_history_trigger"() IS 'Implementation of trigger "write_member_history" on table "member"';
817 COMMENT ON TRIGGER "write_member_history" ON "member" IS 'When changing name or login of a member, create a history entry in "member_history" table';
821 ----------------------------
822 -- Additional constraints --
823 ----------------------------
826 CREATE FUNCTION "issue_requires_first_initiative_trigger"()
827 RETURNS TRIGGER
828 LANGUAGE 'plpgsql' VOLATILE AS $$
829 BEGIN
830 IF NOT EXISTS (
831 SELECT NULL FROM "initiative" WHERE "issue_id" = NEW."id"
832 ) THEN
833 --RAISE 'Cannot create issue without an initial initiative.' USING
834 -- ERRCODE = 'integrity_constraint_violation',
835 -- HINT = 'Create issue, initiative, and draft within the same transaction.';
836 RAISE EXCEPTION 'Cannot create issue without an initial initiative.';
837 END IF;
838 RETURN NULL;
839 END;
840 $$;
842 CREATE CONSTRAINT TRIGGER "issue_requires_first_initiative"
843 AFTER INSERT OR UPDATE ON "issue" DEFERRABLE INITIALLY DEFERRED
844 FOR EACH ROW EXECUTE PROCEDURE
845 "issue_requires_first_initiative_trigger"();
847 COMMENT ON FUNCTION "issue_requires_first_initiative_trigger"() IS 'Implementation of trigger "issue_requires_first_initiative" on table "issue"';
848 COMMENT ON TRIGGER "issue_requires_first_initiative" ON "issue" IS 'Ensure that new issues have at least one initiative';
851 CREATE FUNCTION "last_initiative_deletes_issue_trigger"()
852 RETURNS TRIGGER
853 LANGUAGE 'plpgsql' VOLATILE AS $$
854 DECLARE
855 "reference_lost" BOOLEAN;
856 BEGIN
857 IF TG_OP = 'DELETE' THEN
858 "reference_lost" := TRUE;
859 ELSE
860 "reference_lost" := NEW."issue_id" != OLD."issue_id";
861 END IF;
862 IF
863 "reference_lost" AND NOT EXISTS (
864 SELECT NULL FROM "initiative" WHERE "issue_id" = OLD."issue_id"
865 )
866 THEN
867 DELETE FROM "issue" WHERE "id" = OLD."issue_id";
868 END IF;
869 RETURN NULL;
870 END;
871 $$;
873 CREATE CONSTRAINT TRIGGER "last_initiative_deletes_issue"
874 AFTER UPDATE OR DELETE ON "initiative" DEFERRABLE INITIALLY DEFERRED
875 FOR EACH ROW EXECUTE PROCEDURE
876 "last_initiative_deletes_issue_trigger"();
878 COMMENT ON FUNCTION "last_initiative_deletes_issue_trigger"() IS 'Implementation of trigger "last_initiative_deletes_issue" on table "initiative"';
879 COMMENT ON TRIGGER "last_initiative_deletes_issue" ON "initiative" IS 'Removing the last initiative of an issue deletes the issue';
882 CREATE FUNCTION "initiative_requires_first_draft_trigger"()
883 RETURNS TRIGGER
884 LANGUAGE 'plpgsql' VOLATILE AS $$
885 BEGIN
886 IF NOT EXISTS (
887 SELECT NULL FROM "draft" WHERE "initiative_id" = NEW."id"
888 ) THEN
889 --RAISE 'Cannot create initiative without an initial draft.' USING
890 -- ERRCODE = 'integrity_constraint_violation',
891 -- HINT = 'Create issue, initiative and draft within the same transaction.';
892 RAISE EXCEPTION 'Cannot create initiative without an initial draft.';
893 END IF;
894 RETURN NULL;
895 END;
896 $$;
898 CREATE CONSTRAINT TRIGGER "initiative_requires_first_draft"
899 AFTER INSERT OR UPDATE ON "initiative" DEFERRABLE INITIALLY DEFERRED
900 FOR EACH ROW EXECUTE PROCEDURE
901 "initiative_requires_first_draft_trigger"();
903 COMMENT ON FUNCTION "initiative_requires_first_draft_trigger"() IS 'Implementation of trigger "initiative_requires_first_draft" on table "initiative"';
904 COMMENT ON TRIGGER "initiative_requires_first_draft" ON "initiative" IS 'Ensure that new initiatives have at least one draft';
907 CREATE FUNCTION "last_draft_deletes_initiative_trigger"()
908 RETURNS TRIGGER
909 LANGUAGE 'plpgsql' VOLATILE AS $$
910 DECLARE
911 "reference_lost" BOOLEAN;
912 BEGIN
913 IF TG_OP = 'DELETE' THEN
914 "reference_lost" := TRUE;
915 ELSE
916 "reference_lost" := NEW."initiative_id" != OLD."initiative_id";
917 END IF;
918 IF
919 "reference_lost" AND NOT EXISTS (
920 SELECT NULL FROM "draft" WHERE "initiative_id" = OLD."initiative_id"
921 )
922 THEN
923 DELETE FROM "initiative" WHERE "id" = OLD."initiative_id";
924 END IF;
925 RETURN NULL;
926 END;
927 $$;
929 CREATE CONSTRAINT TRIGGER "last_draft_deletes_initiative"
930 AFTER UPDATE OR DELETE ON "draft" DEFERRABLE INITIALLY DEFERRED
931 FOR EACH ROW EXECUTE PROCEDURE
932 "last_draft_deletes_initiative_trigger"();
934 COMMENT ON FUNCTION "last_draft_deletes_initiative_trigger"() IS 'Implementation of trigger "last_draft_deletes_initiative" on table "draft"';
935 COMMENT ON TRIGGER "last_draft_deletes_initiative" ON "draft" IS 'Removing the last draft of an initiative deletes the initiative';
938 CREATE FUNCTION "suggestion_requires_first_opinion_trigger"()
939 RETURNS TRIGGER
940 LANGUAGE 'plpgsql' VOLATILE AS $$
941 BEGIN
942 IF NOT EXISTS (
943 SELECT NULL FROM "opinion" WHERE "suggestion_id" = NEW."id"
944 ) THEN
945 RAISE EXCEPTION 'Cannot create a suggestion without an opinion.';
946 END IF;
947 RETURN NULL;
948 END;
949 $$;
951 CREATE CONSTRAINT TRIGGER "suggestion_requires_first_opinion"
952 AFTER INSERT OR UPDATE ON "suggestion" DEFERRABLE INITIALLY DEFERRED
953 FOR EACH ROW EXECUTE PROCEDURE
954 "suggestion_requires_first_opinion_trigger"();
956 COMMENT ON FUNCTION "suggestion_requires_first_opinion_trigger"() IS 'Implementation of trigger "suggestion_requires_first_opinion" on table "suggestion"';
957 COMMENT ON TRIGGER "suggestion_requires_first_opinion" ON "suggestion" IS 'Ensure that new suggestions have at least one opinion';
960 CREATE FUNCTION "last_opinion_deletes_suggestion_trigger"()
961 RETURNS TRIGGER
962 LANGUAGE 'plpgsql' VOLATILE AS $$
963 DECLARE
964 "reference_lost" BOOLEAN;
965 BEGIN
966 IF TG_OP = 'DELETE' THEN
967 "reference_lost" := TRUE;
968 ELSE
969 "reference_lost" := NEW."suggestion_id" != OLD."suggestion_id";
970 END IF;
971 IF
972 "reference_lost" AND NOT EXISTS (
973 SELECT NULL FROM "opinion" WHERE "suggestion_id" = OLD."suggestion_id"
974 )
975 THEN
976 DELETE FROM "suggestion" WHERE "id" = OLD."suggestion_id";
977 END IF;
978 RETURN NULL;
979 END;
980 $$;
982 CREATE CONSTRAINT TRIGGER "last_opinion_deletes_suggestion"
983 AFTER UPDATE OR DELETE ON "opinion" DEFERRABLE INITIALLY DEFERRED
984 FOR EACH ROW EXECUTE PROCEDURE
985 "last_opinion_deletes_suggestion_trigger"();
987 COMMENT ON FUNCTION "last_opinion_deletes_suggestion_trigger"() IS 'Implementation of trigger "last_opinion_deletes_suggestion" on table "opinion"';
988 COMMENT ON TRIGGER "last_opinion_deletes_suggestion" ON "opinion" IS 'Removing the last opinion of a suggestion deletes the suggestion';
992 ---------------------------------------------------------------
993 -- Ensure that votes are not modified when issues are frozen --
994 ---------------------------------------------------------------
996 -- NOTE: Frontends should ensure this anyway, but in case of programming
997 -- errors the following triggers ensure data integrity.
1000 CREATE FUNCTION "forbid_changes_on_closed_issue_trigger"()
1001 RETURNS TRIGGER
1002 LANGUAGE 'plpgsql' VOLATILE AS $$
1003 DECLARE
1004 "issue_id_v" "issue"."id"%TYPE;
1005 "issue_row" "issue"%ROWTYPE;
1006 BEGIN
1007 IF TG_OP = 'DELETE' THEN
1008 "issue_id_v" := OLD."issue_id";
1009 ELSE
1010 "issue_id_v" := NEW."issue_id";
1011 END IF;
1012 SELECT INTO "issue_row" * FROM "issue"
1013 WHERE "id" = "issue_id_v" FOR SHARE;
1014 IF "issue_row"."closed" NOTNULL THEN
1015 RAISE EXCEPTION 'Tried to modify data belonging to a closed issue.';
1016 END IF;
1017 RETURN NULL;
1018 END;
1019 $$;
1021 CREATE TRIGGER "forbid_changes_on_closed_issue"
1022 AFTER INSERT OR UPDATE OR DELETE ON "direct_voter"
1023 FOR EACH ROW EXECUTE PROCEDURE
1024 "forbid_changes_on_closed_issue_trigger"();
1026 CREATE TRIGGER "forbid_changes_on_closed_issue"
1027 AFTER INSERT OR UPDATE OR DELETE ON "delegating_voter"
1028 FOR EACH ROW EXECUTE PROCEDURE
1029 "forbid_changes_on_closed_issue_trigger"();
1031 CREATE TRIGGER "forbid_changes_on_closed_issue"
1032 AFTER INSERT OR UPDATE OR DELETE ON "vote"
1033 FOR EACH ROW EXECUTE PROCEDURE
1034 "forbid_changes_on_closed_issue_trigger"();
1036 COMMENT ON FUNCTION "forbid_changes_on_closed_issue_trigger"() IS 'Implementation of triggers "forbid_changes_on_closed_issue" on tables "direct_voter", "delegating_voter" and "vote"';
1037 COMMENT ON TRIGGER "forbid_changes_on_closed_issue" ON "direct_voter" IS 'Ensures that frontends can''t tamper with votings of closed issues, in case of programming errors';
1038 COMMENT ON TRIGGER "forbid_changes_on_closed_issue" ON "delegating_voter" IS 'Ensures that frontends can''t tamper with votings of closed issues, in case of programming errors';
1039 COMMENT ON TRIGGER "forbid_changes_on_closed_issue" ON "vote" IS 'Ensures that frontends can''t tamper with votings of closed issues, in case of programming errors';
1043 --------------------------------------------------------------------
1044 -- Auto-retrieval of fields only needed for referential integrity --
1045 --------------------------------------------------------------------
1048 CREATE FUNCTION "autofill_issue_id_trigger"()
1049 RETURNS TRIGGER
1050 LANGUAGE 'plpgsql' VOLATILE AS $$
1051 BEGIN
1052 IF NEW."issue_id" ISNULL THEN
1053 SELECT "issue_id" INTO NEW."issue_id"
1054 FROM "initiative" WHERE "id" = NEW."initiative_id";
1055 END IF;
1056 RETURN NEW;
1057 END;
1058 $$;
1060 CREATE TRIGGER "autofill_issue_id" BEFORE INSERT ON "supporter"
1061 FOR EACH ROW EXECUTE PROCEDURE "autofill_issue_id_trigger"();
1063 CREATE TRIGGER "autofill_issue_id" BEFORE INSERT ON "vote"
1064 FOR EACH ROW EXECUTE PROCEDURE "autofill_issue_id_trigger"();
1066 COMMENT ON FUNCTION "autofill_issue_id_trigger"() IS 'Implementation of triggers "autofill_issue_id" on tables "supporter" and "vote"';
1067 COMMENT ON TRIGGER "autofill_issue_id" ON "supporter" IS 'Set "issue_id" field automatically, if NULL';
1068 COMMENT ON TRIGGER "autofill_issue_id" ON "vote" IS 'Set "issue_id" field automatically, if NULL';
1071 CREATE FUNCTION "autofill_initiative_id_trigger"()
1072 RETURNS TRIGGER
1073 LANGUAGE 'plpgsql' VOLATILE AS $$
1074 BEGIN
1075 IF NEW."initiative_id" ISNULL THEN
1076 SELECT "initiative_id" INTO NEW."initiative_id"
1077 FROM "suggestion" WHERE "id" = NEW."suggestion_id";
1078 END IF;
1079 RETURN NEW;
1080 END;
1081 $$;
1083 CREATE TRIGGER "autofill_initiative_id" BEFORE INSERT ON "opinion"
1084 FOR EACH ROW EXECUTE PROCEDURE "autofill_initiative_id_trigger"();
1086 COMMENT ON FUNCTION "autofill_initiative_id_trigger"() IS 'Implementation of trigger "autofill_initiative_id" on table "opinion"';
1087 COMMENT ON TRIGGER "autofill_initiative_id" ON "opinion" IS 'Set "initiative_id" field automatically, if NULL';
1091 -----------------------------------------------------
1092 -- Automatic calculation of certain default values --
1093 -----------------------------------------------------
1096 CREATE FUNCTION "copy_timings_trigger"()
1097 RETURNS TRIGGER
1098 LANGUAGE 'plpgsql' VOLATILE AS $$
1099 DECLARE
1100 "policy_row" "policy"%ROWTYPE;
1101 BEGIN
1102 SELECT * INTO "policy_row" FROM "policy"
1103 WHERE "id" = NEW."policy_id";
1104 IF NEW."admission_time" ISNULL THEN
1105 NEW."admission_time" := "policy_row"."admission_time";
1106 END IF;
1107 IF NEW."discussion_time" ISNULL THEN
1108 NEW."discussion_time" := "policy_row"."discussion_time";
1109 END IF;
1110 IF NEW."verification_time" ISNULL THEN
1111 NEW."verification_time" := "policy_row"."verification_time";
1112 END IF;
1113 IF NEW."voting_time" ISNULL THEN
1114 NEW."voting_time" := "policy_row"."voting_time";
1115 END IF;
1116 RETURN NEW;
1117 END;
1118 $$;
1120 CREATE TRIGGER "copy_timings" BEFORE INSERT OR UPDATE ON "issue"
1121 FOR EACH ROW EXECUTE PROCEDURE "copy_timings_trigger"();
1123 COMMENT ON FUNCTION "copy_timings_trigger"() IS 'Implementation of trigger "copy_timings" on table "issue"';
1124 COMMENT ON TRIGGER "copy_timings" ON "issue" IS 'If timing fields are NULL, copy values from policy.';
1127 CREATE FUNCTION "copy_autoreject_trigger"()
1128 RETURNS TRIGGER
1129 LANGUAGE 'plpgsql' VOLATILE AS $$
1130 BEGIN
1131 IF NEW."autoreject" ISNULL THEN
1132 SELECT "membership"."autoreject" INTO NEW."autoreject"
1133 FROM "issue" JOIN "membership"
1134 ON "issue"."area_id" = "membership"."area_id"
1135 WHERE "issue"."id" = NEW."issue_id"
1136 AND "membership"."member_id" = NEW."member_id";
1137 END IF;
1138 IF NEW."autoreject" ISNULL THEN
1139 NEW."autoreject" := FALSE;
1140 END IF;
1141 RETURN NEW;
1142 END;
1143 $$;
1145 CREATE TRIGGER "copy_autoreject" BEFORE INSERT OR UPDATE ON "interest"
1146 FOR EACH ROW EXECUTE PROCEDURE "copy_autoreject_trigger"();
1148 COMMENT ON FUNCTION "copy_autoreject_trigger"() IS 'Implementation of trigger "copy_autoreject" on table "interest"';
1149 COMMENT ON TRIGGER "copy_autoreject" ON "interest" IS 'If "autoreject" is NULL, then copy it from the area setting, or set to FALSE, if no membership existent';
1152 CREATE FUNCTION "supporter_default_for_draft_id_trigger"()
1153 RETURNS TRIGGER
1154 LANGUAGE 'plpgsql' VOLATILE AS $$
1155 BEGIN
1156 IF NEW."draft_id" ISNULL THEN
1157 SELECT "id" INTO NEW."draft_id" FROM "current_draft"
1158 WHERE "initiative_id" = NEW."initiative_id";
1159 END IF;
1160 RETURN NEW;
1161 END;
1162 $$;
1164 CREATE TRIGGER "default_for_draft_id" BEFORE INSERT OR UPDATE ON "supporter"
1165 FOR EACH ROW EXECUTE PROCEDURE "supporter_default_for_draft_id_trigger"();
1167 COMMENT ON FUNCTION "supporter_default_for_draft_id_trigger"() IS 'Implementation of trigger "default_for_draft" on table "supporter"';
1168 COMMENT ON TRIGGER "default_for_draft_id" ON "supporter" IS 'If "draft_id" is NULL, then use the current draft of the initiative as default';
1172 ----------------------------------------
1173 -- Automatic creation of dependencies --
1174 ----------------------------------------
1177 CREATE FUNCTION "autocreate_interest_trigger"()
1178 RETURNS TRIGGER
1179 LANGUAGE 'plpgsql' VOLATILE AS $$
1180 BEGIN
1181 IF NOT EXISTS (
1182 SELECT NULL FROM "initiative" JOIN "interest"
1183 ON "initiative"."issue_id" = "interest"."issue_id"
1184 WHERE "initiative"."id" = NEW."initiative_id"
1185 AND "interest"."member_id" = NEW."member_id"
1186 ) THEN
1187 BEGIN
1188 INSERT INTO "interest" ("issue_id", "member_id")
1189 SELECT "issue_id", NEW."member_id"
1190 FROM "initiative" WHERE "id" = NEW."initiative_id";
1191 EXCEPTION WHEN unique_violation THEN END;
1192 END IF;
1193 RETURN NEW;
1194 END;
1195 $$;
1197 CREATE TRIGGER "autocreate_interest" BEFORE INSERT ON "supporter"
1198 FOR EACH ROW EXECUTE PROCEDURE "autocreate_interest_trigger"();
1200 COMMENT ON FUNCTION "autocreate_interest_trigger"() IS 'Implementation of trigger "autocreate_interest" on table "supporter"';
1201 COMMENT ON TRIGGER "autocreate_interest" ON "supporter" IS 'Supporting an initiative implies interest in the issue, thus automatically creates an entry in the "interest" table';
1204 CREATE FUNCTION "autocreate_supporter_trigger"()
1205 RETURNS TRIGGER
1206 LANGUAGE 'plpgsql' VOLATILE AS $$
1207 BEGIN
1208 IF NOT EXISTS (
1209 SELECT NULL FROM "suggestion" JOIN "supporter"
1210 ON "suggestion"."initiative_id" = "supporter"."initiative_id"
1211 WHERE "suggestion"."id" = NEW."suggestion_id"
1212 AND "supporter"."member_id" = NEW."member_id"
1213 ) THEN
1214 BEGIN
1215 INSERT INTO "supporter" ("initiative_id", "member_id")
1216 SELECT "initiative_id", NEW."member_id"
1217 FROM "suggestion" WHERE "id" = NEW."suggestion_id";
1218 EXCEPTION WHEN unique_violation THEN END;
1219 END IF;
1220 RETURN NEW;
1221 END;
1222 $$;
1224 CREATE TRIGGER "autocreate_supporter" BEFORE INSERT ON "opinion"
1225 FOR EACH ROW EXECUTE PROCEDURE "autocreate_supporter_trigger"();
1227 COMMENT ON FUNCTION "autocreate_supporter_trigger"() IS 'Implementation of trigger "autocreate_supporter" on table "opinion"';
1228 COMMENT ON TRIGGER "autocreate_supporter" ON "opinion" IS 'Opinions can only be added for supported initiatives. This trigger automatrically creates an entry in the "supporter" table, if not existent yet.';
1232 ------------------------------------------
1233 -- Views and helper functions for views --
1234 ------------------------------------------
1237 CREATE VIEW "global_delegation" AS
1238 SELECT
1239 "delegation"."id",
1240 "delegation"."truster_id",
1241 "delegation"."trustee_id"
1242 FROM "delegation" JOIN "member"
1243 ON "delegation"."trustee_id" = "member"."id"
1244 WHERE "delegation"."scope" = 'global' AND "member"."active";
1246 COMMENT ON VIEW "global_delegation" IS 'Global delegations to active members';
1249 CREATE VIEW "area_delegation" AS
1250 SELECT "subquery".* FROM (
1251 SELECT DISTINCT ON ("area"."id", "delegation"."truster_id")
1252 "area"."id" AS "area_id",
1253 "delegation"."id",
1254 "delegation"."truster_id",
1255 "delegation"."trustee_id",
1256 "delegation"."scope"
1257 FROM "area" JOIN "delegation"
1258 ON "delegation"."scope" = 'global'
1259 OR "delegation"."area_id" = "area"."id"
1260 ORDER BY
1261 "area"."id",
1262 "delegation"."truster_id",
1263 "delegation"."scope" DESC
1264 ) AS "subquery"
1265 JOIN "member" ON "subquery"."trustee_id" = "member"."id"
1266 WHERE "member"."active";
1268 COMMENT ON VIEW "area_delegation" IS 'Active delegations for areas';
1271 CREATE VIEW "issue_delegation" AS
1272 SELECT "subquery".* FROM (
1273 SELECT DISTINCT ON ("issue"."id", "delegation"."truster_id")
1274 "issue"."id" AS "issue_id",
1275 "delegation"."id",
1276 "delegation"."truster_id",
1277 "delegation"."trustee_id",
1278 "delegation"."scope"
1279 FROM "issue" JOIN "delegation"
1280 ON "delegation"."scope" = 'global'
1281 OR "delegation"."area_id" = "issue"."area_id"
1282 OR "delegation"."issue_id" = "issue"."id"
1283 ORDER BY
1284 "issue"."id",
1285 "delegation"."truster_id",
1286 "delegation"."scope" DESC
1287 ) AS "subquery"
1288 JOIN "member" ON "subquery"."trustee_id" = "member"."id"
1289 WHERE "member"."active";
1291 COMMENT ON VIEW "issue_delegation" IS 'Active delegations for issues';
1294 CREATE FUNCTION "membership_weight_with_skipping"
1295 ( "area_id_p" "area"."id"%TYPE,
1296 "member_id_p" "member"."id"%TYPE,
1297 "skip_member_ids_p" INT4[] ) -- "member"."id"%TYPE[]
1298 RETURNS INT4
1299 LANGUAGE 'plpgsql' STABLE AS $$
1300 DECLARE
1301 "sum_v" INT4;
1302 "delegation_row" "area_delegation"%ROWTYPE;
1303 BEGIN
1304 "sum_v" := 1;
1305 FOR "delegation_row" IN
1306 SELECT "area_delegation".*
1307 FROM "area_delegation" LEFT JOIN "membership"
1308 ON "membership"."area_id" = "area_id_p"
1309 AND "membership"."member_id" = "area_delegation"."truster_id"
1310 WHERE "area_delegation"."area_id" = "area_id_p"
1311 AND "area_delegation"."trustee_id" = "member_id_p"
1312 AND "membership"."member_id" ISNULL
1313 LOOP
1314 IF NOT
1315 "skip_member_ids_p" @> ARRAY["delegation_row"."truster_id"]
1316 THEN
1317 "sum_v" := "sum_v" + "membership_weight_with_skipping"(
1318 "area_id_p",
1319 "delegation_row"."truster_id",
1320 "skip_member_ids_p" || "delegation_row"."truster_id"
1321 );
1322 END IF;
1323 END LOOP;
1324 RETURN "sum_v";
1325 END;
1326 $$;
1328 COMMENT ON FUNCTION "membership_weight_with_skipping"
1329 ( "area"."id"%TYPE,
1330 "member"."id"%TYPE,
1331 INT4[] )
1332 IS 'Helper function for "membership_weight" function';
1335 CREATE FUNCTION "membership_weight"
1336 ( "area_id_p" "area"."id"%TYPE,
1337 "member_id_p" "member"."id"%TYPE ) -- "member"."id"%TYPE[]
1338 RETURNS INT4
1339 LANGUAGE 'plpgsql' STABLE AS $$
1340 BEGIN
1341 RETURN "membership_weight_with_skipping"(
1342 "area_id_p",
1343 "member_id_p",
1344 ARRAY["member_id_p"]
1345 );
1346 END;
1347 $$;
1349 COMMENT ON FUNCTION "membership_weight"
1350 ( "area"."id"%TYPE,
1351 "member"."id"%TYPE )
1352 IS 'Calculates the potential voting weight of a member in a given area';
1355 CREATE VIEW "member_count_view" AS
1356 SELECT count(1) AS "total_count" FROM "member" WHERE "active";
1358 COMMENT ON VIEW "member_count_view" IS 'View used to update "member_count" table';
1361 CREATE VIEW "area_member_count" AS
1362 SELECT
1363 "area"."id" AS "area_id",
1364 count("member"."id") AS "direct_member_count",
1365 coalesce(
1366 sum(
1367 CASE WHEN "member"."id" NOTNULL THEN
1368 "membership_weight"("area"."id", "member"."id")
1369 ELSE 0 END
1371 ) AS "member_weight",
1372 coalesce(
1373 sum(
1374 CASE WHEN "member"."id" NOTNULL AND "membership"."autoreject" THEN
1375 "membership_weight"("area"."id", "member"."id")
1376 ELSE 0 END
1378 ) AS "autoreject_weight"
1379 FROM "area"
1380 LEFT JOIN "membership"
1381 ON "area"."id" = "membership"."area_id"
1382 LEFT JOIN "member"
1383 ON "membership"."member_id" = "member"."id"
1384 AND "member"."active"
1385 GROUP BY "area"."id";
1387 COMMENT ON VIEW "area_member_count" IS 'View used to update "member_count" column of table "area"';
1390 CREATE VIEW "opening_draft" AS
1391 SELECT "draft".* FROM (
1392 SELECT
1393 "initiative"."id" AS "initiative_id",
1394 min("draft"."id") AS "draft_id"
1395 FROM "initiative" JOIN "draft"
1396 ON "initiative"."id" = "draft"."initiative_id"
1397 GROUP BY "initiative"."id"
1398 ) AS "subquery"
1399 JOIN "draft" ON "subquery"."draft_id" = "draft"."id";
1401 COMMENT ON VIEW "opening_draft" IS 'First drafts of all initiatives';
1404 CREATE VIEW "current_draft" AS
1405 SELECT "draft".* FROM (
1406 SELECT
1407 "initiative"."id" AS "initiative_id",
1408 max("draft"."id") AS "draft_id"
1409 FROM "initiative" JOIN "draft"
1410 ON "initiative"."id" = "draft"."initiative_id"
1411 GROUP BY "initiative"."id"
1412 ) AS "subquery"
1413 JOIN "draft" ON "subquery"."draft_id" = "draft"."id";
1415 COMMENT ON VIEW "current_draft" IS 'All latest drafts for each initiative';
1418 CREATE VIEW "critical_opinion" AS
1419 SELECT * FROM "opinion"
1420 WHERE ("degree" = 2 AND "fulfilled" = FALSE)
1421 OR ("degree" = -2 AND "fulfilled" = TRUE);
1423 COMMENT ON VIEW "critical_opinion" IS 'Opinions currently causing dissatisfaction';
1426 CREATE VIEW "battle" AS
1427 SELECT
1428 "issue"."id" AS "issue_id",
1429 "winning_initiative"."id" AS "winning_initiative_id",
1430 "losing_initiative"."id" AS "losing_initiative_id",
1431 sum(
1432 CASE WHEN
1433 coalesce("better_vote"."grade", 0) >
1434 coalesce("worse_vote"."grade", 0)
1435 THEN "direct_voter"."weight" ELSE 0 END
1436 ) AS "count"
1437 FROM "issue"
1438 LEFT JOIN "direct_voter"
1439 ON "issue"."id" = "direct_voter"."issue_id"
1440 JOIN "initiative" AS "winning_initiative"
1441 ON "issue"."id" = "winning_initiative"."issue_id"
1442 AND "winning_initiative"."agreed"
1443 JOIN "initiative" AS "losing_initiative"
1444 ON "issue"."id" = "losing_initiative"."issue_id"
1445 AND "losing_initiative"."agreed"
1446 LEFT JOIN "vote" AS "better_vote"
1447 ON "direct_voter"."member_id" = "better_vote"."member_id"
1448 AND "winning_initiative"."id" = "better_vote"."initiative_id"
1449 LEFT JOIN "vote" AS "worse_vote"
1450 ON "direct_voter"."member_id" = "worse_vote"."member_id"
1451 AND "losing_initiative"."id" = "worse_vote"."initiative_id"
1452 WHERE
1453 "winning_initiative"."id" != "losing_initiative"."id"
1454 GROUP BY
1455 "issue"."id",
1456 "winning_initiative"."id",
1457 "losing_initiative"."id";
1459 COMMENT ON VIEW "battle" IS 'Number of members preferring one initiative over another';
1462 CREATE VIEW "expired_session" AS
1463 SELECT * FROM "session" WHERE now() > "expiry";
1465 CREATE RULE "delete" AS ON DELETE TO "expired_session" DO INSTEAD
1466 DELETE FROM "session" WHERE "ident" = OLD."ident";
1468 COMMENT ON VIEW "expired_session" IS 'View containing all expired sessions where DELETE is possible';
1469 COMMENT ON RULE "delete" ON "expired_session" IS 'Rule allowing DELETE on rows in "expired_session" view, i.e. DELETE FROM "expired_session"';
1472 CREATE VIEW "open_issue" AS
1473 SELECT * FROM "issue" WHERE "closed" ISNULL;
1475 COMMENT ON VIEW "open_issue" IS 'All open issues';
1478 CREATE VIEW "issue_with_ranks_missing" AS
1479 SELECT * FROM "issue"
1480 WHERE "fully_frozen" NOTNULL
1481 AND "closed" NOTNULL
1482 AND "ranks_available" = FALSE;
1484 COMMENT ON VIEW "issue_with_ranks_missing" IS 'Issues where voting was finished, but no ranks have been calculated yet';
1487 CREATE VIEW "member_contingent" AS
1488 SELECT
1489 "member"."id" AS "member_id",
1490 "contingent"."time_frame",
1491 CASE WHEN "contingent"."text_entry_limit" NOTNULL THEN
1493 SELECT count(1) FROM "draft"
1494 WHERE "draft"."author_id" = "member"."id"
1495 AND "draft"."created" > now() - "contingent"."time_frame"
1496 ) + (
1497 SELECT count(1) FROM "suggestion"
1498 WHERE "suggestion"."author_id" = "member"."id"
1499 AND "suggestion"."created" > now() - "contingent"."time_frame"
1501 ELSE NULL END AS "text_entry_count",
1502 "contingent"."text_entry_limit",
1503 CASE WHEN "contingent"."initiative_limit" NOTNULL THEN (
1504 SELECT count(1) FROM "opening_draft"
1505 WHERE "opening_draft"."author_id" = "member"."id"
1506 AND "opening_draft"."created" > now() - "contingent"."time_frame"
1507 ) ELSE NULL END AS "initiative_count",
1508 "contingent"."initiative_limit"
1509 FROM "member" CROSS JOIN "contingent";
1511 COMMENT ON VIEW "member_contingent" IS 'Actual counts of text entries and initiatives are calculated per member for each limit in the "contingent" table.';
1513 COMMENT ON COLUMN "member_contingent"."text_entry_count" IS 'Only calculated when "text_entry_limit" is not null in the same row';
1514 COMMENT ON COLUMN "member_contingent"."initiative_count" IS 'Only calculated when "initiative_limit" is not null in the same row';
1517 CREATE VIEW "member_contingent_left" AS
1518 SELECT
1519 "member_id",
1520 max("text_entry_limit" - "text_entry_count") AS "text_entries_left",
1521 max("initiative_limit" - "initiative_count") AS "initiatives_left"
1522 FROM "member_contingent" GROUP BY "member_id";
1524 COMMENT ON VIEW "member_contingent_left" IS 'Amount of text entries or initiatives which can be posted now instantly by a member. This view should be used by a frontend to determine, if the contingent for posting is exhausted.';
1527 CREATE TYPE "timeline_event" AS ENUM (
1528 'issue_created',
1529 'issue_canceled',
1530 'issue_accepted',
1531 'issue_half_frozen',
1532 'issue_finished_without_voting',
1533 'issue_voting_started',
1534 'issue_finished_after_voting',
1535 'initiative_created',
1536 'initiative_revoked',
1537 'draft_created',
1538 'suggestion_created');
1540 COMMENT ON TYPE "timeline_event" IS 'Types of event in timeline tables';
1543 CREATE VIEW "timeline_issue" AS
1544 SELECT
1545 "created" AS "occurrence",
1546 'issue_created'::"timeline_event" AS "event",
1547 "id" AS "issue_id"
1548 FROM "issue"
1549 UNION ALL
1550 SELECT
1551 "closed" AS "occurrence",
1552 'issue_canceled'::"timeline_event" AS "event",
1553 "id" AS "issue_id"
1554 FROM "issue" WHERE "closed" NOTNULL AND "fully_frozen" ISNULL
1555 UNION ALL
1556 SELECT
1557 "accepted" AS "occurrence",
1558 'issue_accepted'::"timeline_event" AS "event",
1559 "id" AS "issue_id"
1560 FROM "issue" WHERE "accepted" NOTNULL
1561 UNION ALL
1562 SELECT
1563 "half_frozen" AS "occurrence",
1564 'issue_half_frozen'::"timeline_event" AS "event",
1565 "id" AS "issue_id"
1566 FROM "issue" WHERE "half_frozen" NOTNULL
1567 UNION ALL
1568 SELECT
1569 "fully_frozen" AS "occurrence",
1570 'issue_voting_started'::"timeline_event" AS "event",
1571 "id" AS "issue_id"
1572 FROM "issue"
1573 WHERE "fully_frozen" NOTNULL
1574 AND ("closed" ISNULL OR "closed" != "fully_frozen")
1575 UNION ALL
1576 SELECT
1577 "closed" AS "occurrence",
1578 CASE WHEN "fully_frozen" = "closed" THEN
1579 'issue_finished_without_voting'::"timeline_event"
1580 ELSE
1581 'issue_finished_after_voting'::"timeline_event"
1582 END AS "event",
1583 "id" AS "issue_id"
1584 FROM "issue" WHERE "closed" NOTNULL AND "fully_frozen" NOTNULL;
1586 COMMENT ON VIEW "timeline_issue" IS 'Helper view for "timeline" view';
1589 CREATE VIEW "timeline_initiative" AS
1590 SELECT
1591 "created" AS "occurrence",
1592 'initiative_created'::"timeline_event" AS "event",
1593 "id" AS "initiative_id"
1594 FROM "initiative"
1595 UNION ALL
1596 SELECT
1597 "revoked" AS "occurrence",
1598 'initiative_revoked'::"timeline_event" AS "event",
1599 "id" AS "initiative_id"
1600 FROM "initiative" WHERE "revoked" NOTNULL;
1602 COMMENT ON VIEW "timeline_initiative" IS 'Helper view for "timeline" view';
1605 CREATE VIEW "timeline_draft" AS
1606 SELECT
1607 "created" AS "occurrence",
1608 'draft_created'::"timeline_event" AS "event",
1609 "id" AS "draft_id"
1610 FROM "draft";
1612 COMMENT ON VIEW "timeline_draft" IS 'Helper view for "timeline" view';
1615 CREATE VIEW "timeline_suggestion" AS
1616 SELECT
1617 "created" AS "occurrence",
1618 'suggestion_created'::"timeline_event" AS "event",
1619 "id" AS "suggestion_id"
1620 FROM "suggestion";
1622 COMMENT ON VIEW "timeline_suggestion" IS 'Helper view for "timeline" view';
1625 CREATE VIEW "timeline" AS
1626 SELECT
1627 "occurrence",
1628 "event",
1629 "issue_id",
1630 NULL AS "initiative_id",
1631 NULL::INT8 AS "draft_id", -- TODO: Why do we need a type-cast here? Is this due to 32 bit architecture?
1632 NULL::INT8 AS "suggestion_id"
1633 FROM "timeline_issue"
1634 UNION ALL
1635 SELECT
1636 "occurrence",
1637 "event",
1638 NULL AS "issue_id",
1639 "initiative_id",
1640 NULL AS "draft_id",
1641 NULL AS "suggestion_id"
1642 FROM "timeline_initiative"
1643 UNION ALL
1644 SELECT
1645 "occurrence",
1646 "event",
1647 NULL AS "issue_id",
1648 NULL AS "initiative_id",
1649 "draft_id",
1650 NULL AS "suggestion_id"
1651 FROM "timeline_draft"
1652 UNION ALL
1653 SELECT
1654 "occurrence",
1655 "event",
1656 NULL AS "issue_id",
1657 NULL AS "initiative_id",
1658 NULL AS "draft_id",
1659 "suggestion_id"
1660 FROM "timeline_suggestion";
1662 COMMENT ON VIEW "timeline" IS 'Aggregation of different events in the system';
1666 --------------------------------------------------
1667 -- Set returning function for delegation chains --
1668 --------------------------------------------------
1671 CREATE TYPE "delegation_chain_loop_tag" AS ENUM
1672 ('first', 'intermediate', 'last', 'repetition');
1674 COMMENT ON TYPE "delegation_chain_loop_tag" IS 'Type for loop tags in "delegation_chain_row" type';
1677 CREATE TYPE "delegation_chain_row" AS (
1678 "index" INT4,
1679 "member_id" INT4,
1680 "member_active" BOOLEAN,
1681 "participation" BOOLEAN,
1682 "overridden" BOOLEAN,
1683 "scope_in" "delegation_scope",
1684 "scope_out" "delegation_scope",
1685 "loop" "delegation_chain_loop_tag" );
1687 COMMENT ON TYPE "delegation_chain_row" IS 'Type of rows returned by "delegation_chain"(...) functions';
1689 COMMENT ON COLUMN "delegation_chain_row"."index" IS 'Index starting with 0 and counting up';
1690 COMMENT ON COLUMN "delegation_chain_row"."participation" IS 'In case of delegation chains for issues: interest, for areas: membership, for global delegation chains: always null';
1691 COMMENT ON COLUMN "delegation_chain_row"."overridden" IS 'True, if an entry with lower index has "participation" set to true';
1692 COMMENT ON COLUMN "delegation_chain_row"."scope_in" IS 'Scope of used incoming delegation';
1693 COMMENT ON COLUMN "delegation_chain_row"."scope_out" IS 'Scope of used outgoing delegation';
1694 COMMENT ON COLUMN "delegation_chain_row"."loop" IS 'Not null, if member is part of a loop, see "delegation_chain_loop_tag" type';
1697 CREATE FUNCTION "delegation_chain"
1698 ( "member_id_p" "member"."id"%TYPE,
1699 "area_id_p" "area"."id"%TYPE,
1700 "issue_id_p" "issue"."id"%TYPE,
1701 "simulate_trustee_id_p" "member"."id"%TYPE )
1702 RETURNS SETOF "delegation_chain_row"
1703 LANGUAGE 'plpgsql' STABLE AS $$
1704 DECLARE
1705 "issue_row" "issue"%ROWTYPE;
1706 "visited_member_ids" INT4[]; -- "member"."id"%TYPE[]
1707 "loop_member_id_v" "member"."id"%TYPE;
1708 "output_row" "delegation_chain_row";
1709 "output_rows" "delegation_chain_row"[];
1710 "delegation_row" "delegation"%ROWTYPE;
1711 "row_count" INT4;
1712 "i" INT4;
1713 "loop_v" BOOLEAN;
1714 BEGIN
1715 SELECT * INTO "issue_row" FROM "issue" WHERE "id" = "issue_id_p";
1716 "visited_member_ids" := '{}';
1717 "loop_member_id_v" := NULL;
1718 "output_rows" := '{}';
1719 "output_row"."index" := 0;
1720 "output_row"."member_id" := "member_id_p";
1721 "output_row"."member_active" := TRUE;
1722 "output_row"."participation" := FALSE;
1723 "output_row"."overridden" := FALSE;
1724 "output_row"."scope_out" := NULL;
1725 LOOP
1726 IF "visited_member_ids" @> ARRAY["output_row"."member_id"] THEN
1727 "loop_member_id_v" := "output_row"."member_id";
1728 ELSE
1729 "visited_member_ids" :=
1730 "visited_member_ids" || "output_row"."member_id";
1731 END IF;
1732 IF "output_row"."participation" THEN
1733 "output_row"."overridden" := TRUE;
1734 END IF;
1735 "output_row"."scope_in" := "output_row"."scope_out";
1736 IF EXISTS (
1737 SELECT NULL FROM "member"
1738 WHERE "id" = "output_row"."member_id" AND "active"
1739 ) THEN
1740 IF "area_id_p" ISNULL AND "issue_id_p" ISNULL THEN
1741 SELECT * INTO "delegation_row" FROM "delegation"
1742 WHERE "truster_id" = "output_row"."member_id"
1743 AND "scope" = 'global';
1744 ELSIF "area_id_p" NOTNULL AND "issue_id_p" ISNULL THEN
1745 "output_row"."participation" := EXISTS (
1746 SELECT NULL FROM "membership"
1747 WHERE "area_id" = "area_id_p"
1748 AND "member_id" = "output_row"."member_id"
1749 );
1750 SELECT * INTO "delegation_row" FROM "delegation"
1751 WHERE "truster_id" = "output_row"."member_id"
1752 AND ("scope" = 'global' OR "area_id" = "area_id_p")
1753 ORDER BY "scope" DESC;
1754 ELSIF "area_id_p" ISNULL AND "issue_id_p" NOTNULL THEN
1755 "output_row"."participation" := EXISTS (
1756 SELECT NULL FROM "interest"
1757 WHERE "issue_id" = "issue_id_p"
1758 AND "member_id" = "output_row"."member_id"
1759 );
1760 SELECT * INTO "delegation_row" FROM "delegation"
1761 WHERE "truster_id" = "output_row"."member_id"
1762 AND ("scope" = 'global' OR
1763 "area_id" = "issue_row"."area_id" OR
1764 "issue_id" = "issue_id_p"
1766 ORDER BY "scope" DESC;
1767 ELSE
1768 RAISE EXCEPTION 'Either area_id or issue_id or both must be NULL.';
1769 END IF;
1770 ELSE
1771 "output_row"."member_active" := FALSE;
1772 "output_row"."participation" := FALSE;
1773 "output_row"."scope_out" := NULL;
1774 "delegation_row" := ROW(NULL);
1775 END IF;
1776 IF
1777 "output_row"."member_id" = "member_id_p" AND
1778 "simulate_trustee_id_p" NOTNULL
1779 THEN
1780 "output_row"."scope_out" := CASE
1781 WHEN "area_id_p" ISNULL AND "issue_id_p" ISNULL THEN 'global'
1782 WHEN "area_id_p" NOTNULL AND "issue_id_p" ISNULL THEN 'area'
1783 WHEN "area_id_p" ISNULL AND "issue_id_p" NOTNULL THEN 'issue'
1784 END;
1785 "output_rows" := "output_rows" || "output_row";
1786 "output_row"."member_id" := "simulate_trustee_id_p";
1787 ELSIF "delegation_row"."trustee_id" NOTNULL THEN
1788 "output_row"."scope_out" := "delegation_row"."scope";
1789 "output_rows" := "output_rows" || "output_row";
1790 "output_row"."member_id" := "delegation_row"."trustee_id";
1791 ELSE
1792 "output_row"."scope_out" := NULL;
1793 "output_rows" := "output_rows" || "output_row";
1794 EXIT;
1795 END IF;
1796 EXIT WHEN "loop_member_id_v" NOTNULL;
1797 "output_row"."index" := "output_row"."index" + 1;
1798 END LOOP;
1799 "row_count" := array_upper("output_rows", 1);
1800 "i" := 1;
1801 "loop_v" := FALSE;
1802 LOOP
1803 "output_row" := "output_rows"["i"];
1804 EXIT WHEN "output_row"."member_id" ISNULL;
1805 IF "loop_v" THEN
1806 IF "i" + 1 = "row_count" THEN
1807 "output_row"."loop" := 'last';
1808 ELSIF "i" = "row_count" THEN
1809 "output_row"."loop" := 'repetition';
1810 ELSE
1811 "output_row"."loop" := 'intermediate';
1812 END IF;
1813 ELSIF "output_row"."member_id" = "loop_member_id_v" THEN
1814 "output_row"."loop" := 'first';
1815 "loop_v" := TRUE;
1816 END IF;
1817 IF "area_id_p" ISNULL AND "issue_id_p" ISNULL THEN
1818 "output_row"."participation" := NULL;
1819 END IF;
1820 RETURN NEXT "output_row";
1821 "i" := "i" + 1;
1822 END LOOP;
1823 RETURN;
1824 END;
1825 $$;
1827 COMMENT ON FUNCTION "delegation_chain"
1828 ( "member"."id"%TYPE,
1829 "area"."id"%TYPE,
1830 "issue"."id"%TYPE,
1831 "member"."id"%TYPE )
1832 IS 'Helper function for frontends to display delegation chains; Not part of internal voting logic';
1834 CREATE FUNCTION "delegation_chain"
1835 ( "member_id_p" "member"."id"%TYPE,
1836 "area_id_p" "area"."id"%TYPE,
1837 "issue_id_p" "issue"."id"%TYPE )
1838 RETURNS SETOF "delegation_chain_row"
1839 LANGUAGE 'plpgsql' STABLE AS $$
1840 DECLARE
1841 "result_row" "delegation_chain_row";
1842 BEGIN
1843 FOR "result_row" IN
1844 SELECT * FROM "delegation_chain"(
1845 "member_id_p", "area_id_p", "issue_id_p", NULL
1847 LOOP
1848 RETURN NEXT "result_row";
1849 END LOOP;
1850 RETURN;
1851 END;
1852 $$;
1854 COMMENT ON FUNCTION "delegation_chain"
1855 ( "member"."id"%TYPE,
1856 "area"."id"%TYPE,
1857 "issue"."id"%TYPE )
1858 IS 'Shortcut for "delegation_chain"(...) function where 4th parameter is null';
1862 ------------------------------
1863 -- Comparison by vote count --
1864 ------------------------------
1866 CREATE FUNCTION "vote_ratio"
1867 ( "positive_votes_p" "initiative"."positive_votes"%TYPE,
1868 "negative_votes_p" "initiative"."negative_votes"%TYPE )
1869 RETURNS FLOAT8
1870 LANGUAGE 'plpgsql' STABLE AS $$
1871 BEGIN
1872 IF "positive_votes_p" > 0 AND "negative_votes_p" > 0 THEN
1873 RETURN
1874 "positive_votes_p"::FLOAT8 /
1875 ("positive_votes_p" + "negative_votes_p")::FLOAT8;
1876 ELSIF "positive_votes_p" > 0 THEN
1877 RETURN "positive_votes_p";
1878 ELSIF "negative_votes_p" > 0 THEN
1879 RETURN 1 - "negative_votes_p";
1880 ELSE
1881 RETURN 0.5;
1882 END IF;
1883 END;
1884 $$;
1886 COMMENT ON FUNCTION "vote_ratio"
1887 ( "initiative"."positive_votes"%TYPE,
1888 "initiative"."negative_votes"%TYPE )
1889 IS 'Returns a number, which can be used for comparison of initiatives based on count of approvals and disapprovals. Greater numbers indicate a better result. This function is NOT injective.';
1893 ------------------------------------------------
1894 -- Locking for snapshots and voting procedure --
1895 ------------------------------------------------
1897 CREATE FUNCTION "global_lock"() RETURNS VOID
1898 LANGUAGE 'plpgsql' VOLATILE AS $$
1899 BEGIN
1900 -- NOTE: PostgreSQL allows reading, while tables are locked in
1901 -- exclusive move. Transactions should be kept short anyway!
1902 LOCK TABLE "member" IN EXCLUSIVE MODE;
1903 LOCK TABLE "area" IN EXCLUSIVE MODE;
1904 LOCK TABLE "membership" IN EXCLUSIVE MODE;
1905 -- NOTE: "member", "area" and "membership" are locked first to
1906 -- prevent deadlocks in combination with "calculate_member_counts"()
1907 LOCK TABLE "policy" IN EXCLUSIVE MODE;
1908 LOCK TABLE "issue" IN EXCLUSIVE MODE;
1909 LOCK TABLE "initiative" IN EXCLUSIVE MODE;
1910 LOCK TABLE "draft" IN EXCLUSIVE MODE;
1911 LOCK TABLE "suggestion" IN EXCLUSIVE MODE;
1912 LOCK TABLE "interest" IN EXCLUSIVE MODE;
1913 LOCK TABLE "initiator" IN EXCLUSIVE MODE;
1914 LOCK TABLE "supporter" IN EXCLUSIVE MODE;
1915 LOCK TABLE "opinion" IN EXCLUSIVE MODE;
1916 LOCK TABLE "delegation" IN EXCLUSIVE MODE;
1917 LOCK TABLE "direct_population_snapshot" IN EXCLUSIVE MODE;
1918 LOCK TABLE "delegating_population_snapshot" IN EXCLUSIVE MODE;
1919 LOCK TABLE "direct_interest_snapshot" IN EXCLUSIVE MODE;
1920 LOCK TABLE "delegating_interest_snapshot" IN EXCLUSIVE MODE;
1921 LOCK TABLE "direct_supporter_snapshot" IN EXCLUSIVE MODE;
1922 LOCK TABLE "direct_voter" IN EXCLUSIVE MODE;
1923 LOCK TABLE "delegating_voter" IN EXCLUSIVE MODE;
1924 LOCK TABLE "vote" IN EXCLUSIVE MODE;
1925 RETURN;
1926 END;
1927 $$;
1929 COMMENT ON FUNCTION "global_lock"() IS 'Locks all tables related to support/voting until end of transaction; read access is still possible though';
1933 -------------------------------
1934 -- Materialize member counts --
1935 -------------------------------
1937 CREATE FUNCTION "calculate_member_counts"()
1938 RETURNS VOID
1939 LANGUAGE 'plpgsql' VOLATILE AS $$
1940 BEGIN
1941 LOCK TABLE "member" IN EXCLUSIVE MODE;
1942 LOCK TABLE "area" IN EXCLUSIVE MODE;
1943 LOCK TABLE "membership" IN EXCLUSIVE MODE;
1944 DELETE FROM "member_count";
1945 INSERT INTO "member_count" ("total_count")
1946 SELECT "total_count" FROM "member_count_view";
1947 UPDATE "area" SET
1948 "direct_member_count" = "view"."direct_member_count",
1949 "member_weight" = "view"."member_weight",
1950 "autoreject_weight" = "view"."autoreject_weight"
1951 FROM "area_member_count" AS "view"
1952 WHERE "view"."area_id" = "area"."id";
1953 RETURN;
1954 END;
1955 $$;
1957 COMMENT ON FUNCTION "calculate_member_counts"() IS 'Updates "member_count" table and "member_count" column of table "area" by materializing data from views "member_count_view" and "area_member_count"';
1961 ------------------------------
1962 -- Calculation of snapshots --
1963 ------------------------------
1965 CREATE FUNCTION "weight_of_added_delegations_for_population_snapshot"
1966 ( "issue_id_p" "issue"."id"%TYPE,
1967 "member_id_p" "member"."id"%TYPE,
1968 "delegate_member_ids_p" "delegating_population_snapshot"."delegate_member_ids"%TYPE )
1969 RETURNS "direct_population_snapshot"."weight"%TYPE
1970 LANGUAGE 'plpgsql' VOLATILE AS $$
1971 DECLARE
1972 "issue_delegation_row" "issue_delegation"%ROWTYPE;
1973 "delegate_member_ids_v" "delegating_population_snapshot"."delegate_member_ids"%TYPE;
1974 "weight_v" INT4;
1975 "sub_weight_v" INT4;
1976 BEGIN
1977 "weight_v" := 0;
1978 FOR "issue_delegation_row" IN
1979 SELECT * FROM "issue_delegation"
1980 WHERE "trustee_id" = "member_id_p"
1981 AND "issue_id" = "issue_id_p"
1982 LOOP
1983 IF NOT EXISTS (
1984 SELECT NULL FROM "direct_population_snapshot"
1985 WHERE "issue_id" = "issue_id_p"
1986 AND "event" = 'periodic'
1987 AND "member_id" = "issue_delegation_row"."truster_id"
1988 ) AND NOT EXISTS (
1989 SELECT NULL FROM "delegating_population_snapshot"
1990 WHERE "issue_id" = "issue_id_p"
1991 AND "event" = 'periodic'
1992 AND "member_id" = "issue_delegation_row"."truster_id"
1993 ) THEN
1994 "delegate_member_ids_v" :=
1995 "member_id_p" || "delegate_member_ids_p";
1996 INSERT INTO "delegating_population_snapshot" (
1997 "issue_id",
1998 "event",
1999 "member_id",
2000 "scope",
2001 "delegate_member_ids"
2002 ) VALUES (
2003 "issue_id_p",
2004 'periodic',
2005 "issue_delegation_row"."truster_id",
2006 "issue_delegation_row"."scope",
2007 "delegate_member_ids_v"
2008 );
2009 "sub_weight_v" := 1 +
2010 "weight_of_added_delegations_for_population_snapshot"(
2011 "issue_id_p",
2012 "issue_delegation_row"."truster_id",
2013 "delegate_member_ids_v"
2014 );
2015 UPDATE "delegating_population_snapshot"
2016 SET "weight" = "sub_weight_v"
2017 WHERE "issue_id" = "issue_id_p"
2018 AND "event" = 'periodic'
2019 AND "member_id" = "issue_delegation_row"."truster_id";
2020 "weight_v" := "weight_v" + "sub_weight_v";
2021 END IF;
2022 END LOOP;
2023 RETURN "weight_v";
2024 END;
2025 $$;
2027 COMMENT ON FUNCTION "weight_of_added_delegations_for_population_snapshot"
2028 ( "issue"."id"%TYPE,
2029 "member"."id"%TYPE,
2030 "delegating_population_snapshot"."delegate_member_ids"%TYPE )
2031 IS 'Helper function for "create_population_snapshot" function';
2034 CREATE FUNCTION "create_population_snapshot"
2035 ( "issue_id_p" "issue"."id"%TYPE )
2036 RETURNS VOID
2037 LANGUAGE 'plpgsql' VOLATILE AS $$
2038 DECLARE
2039 "member_id_v" "member"."id"%TYPE;
2040 BEGIN
2041 DELETE FROM "direct_population_snapshot"
2042 WHERE "issue_id" = "issue_id_p"
2043 AND "event" = 'periodic';
2044 DELETE FROM "delegating_population_snapshot"
2045 WHERE "issue_id" = "issue_id_p"
2046 AND "event" = 'periodic';
2047 INSERT INTO "direct_population_snapshot"
2048 ("issue_id", "event", "member_id")
2049 SELECT
2050 "issue_id_p" AS "issue_id",
2051 'periodic'::"snapshot_event" AS "event",
2052 "member"."id" AS "member_id"
2053 FROM "issue"
2054 JOIN "area" ON "issue"."area_id" = "area"."id"
2055 JOIN "membership" ON "area"."id" = "membership"."area_id"
2056 JOIN "member" ON "membership"."member_id" = "member"."id"
2057 WHERE "issue"."id" = "issue_id_p"
2058 AND "member"."active"
2059 UNION
2060 SELECT
2061 "issue_id_p" AS "issue_id",
2062 'periodic'::"snapshot_event" AS "event",
2063 "member"."id" AS "member_id"
2064 FROM "interest" JOIN "member"
2065 ON "interest"."member_id" = "member"."id"
2066 WHERE "interest"."issue_id" = "issue_id_p"
2067 AND "member"."active";
2068 FOR "member_id_v" IN
2069 SELECT "member_id" FROM "direct_population_snapshot"
2070 WHERE "issue_id" = "issue_id_p"
2071 AND "event" = 'periodic'
2072 LOOP
2073 UPDATE "direct_population_snapshot" SET
2074 "weight" = 1 +
2075 "weight_of_added_delegations_for_population_snapshot"(
2076 "issue_id_p",
2077 "member_id_v",
2078 '{}'
2080 WHERE "issue_id" = "issue_id_p"
2081 AND "event" = 'periodic'
2082 AND "member_id" = "member_id_v";
2083 END LOOP;
2084 RETURN;
2085 END;
2086 $$;
2088 COMMENT ON FUNCTION "create_population_snapshot"
2089 ( "issue_id_p" "issue"."id"%TYPE )
2090 IS 'This function creates a new ''periodic'' population snapshot for the given issue. It does neither lock any tables, nor updates precalculated values in other tables.';
2093 CREATE FUNCTION "weight_of_added_delegations_for_interest_snapshot"
2094 ( "issue_id_p" "issue"."id"%TYPE,
2095 "member_id_p" "member"."id"%TYPE,
2096 "delegate_member_ids_p" "delegating_interest_snapshot"."delegate_member_ids"%TYPE )
2097 RETURNS "direct_interest_snapshot"."weight"%TYPE
2098 LANGUAGE 'plpgsql' VOLATILE AS $$
2099 DECLARE
2100 "issue_delegation_row" "issue_delegation"%ROWTYPE;
2101 "delegate_member_ids_v" "delegating_interest_snapshot"."delegate_member_ids"%TYPE;
2102 "weight_v" INT4;
2103 "sub_weight_v" INT4;
2104 BEGIN
2105 "weight_v" := 0;
2106 FOR "issue_delegation_row" IN
2107 SELECT * FROM "issue_delegation"
2108 WHERE "trustee_id" = "member_id_p"
2109 AND "issue_id" = "issue_id_p"
2110 LOOP
2111 IF NOT EXISTS (
2112 SELECT NULL FROM "direct_interest_snapshot"
2113 WHERE "issue_id" = "issue_id_p"
2114 AND "event" = 'periodic'
2115 AND "member_id" = "issue_delegation_row"."truster_id"
2116 ) AND NOT EXISTS (
2117 SELECT NULL FROM "delegating_interest_snapshot"
2118 WHERE "issue_id" = "issue_id_p"
2119 AND "event" = 'periodic'
2120 AND "member_id" = "issue_delegation_row"."truster_id"
2121 ) THEN
2122 "delegate_member_ids_v" :=
2123 "member_id_p" || "delegate_member_ids_p";
2124 INSERT INTO "delegating_interest_snapshot" (
2125 "issue_id",
2126 "event",
2127 "member_id",
2128 "scope",
2129 "delegate_member_ids"
2130 ) VALUES (
2131 "issue_id_p",
2132 'periodic',
2133 "issue_delegation_row"."truster_id",
2134 "issue_delegation_row"."scope",
2135 "delegate_member_ids_v"
2136 );
2137 "sub_weight_v" := 1 +
2138 "weight_of_added_delegations_for_interest_snapshot"(
2139 "issue_id_p",
2140 "issue_delegation_row"."truster_id",
2141 "delegate_member_ids_v"
2142 );
2143 UPDATE "delegating_interest_snapshot"
2144 SET "weight" = "sub_weight_v"
2145 WHERE "issue_id" = "issue_id_p"
2146 AND "event" = 'periodic'
2147 AND "member_id" = "issue_delegation_row"."truster_id";
2148 "weight_v" := "weight_v" + "sub_weight_v";
2149 END IF;
2150 END LOOP;
2151 RETURN "weight_v";
2152 END;
2153 $$;
2155 COMMENT ON FUNCTION "weight_of_added_delegations_for_interest_snapshot"
2156 ( "issue"."id"%TYPE,
2157 "member"."id"%TYPE,
2158 "delegating_interest_snapshot"."delegate_member_ids"%TYPE )
2159 IS 'Helper function for "create_interest_snapshot" function';
2162 CREATE FUNCTION "create_interest_snapshot"
2163 ( "issue_id_p" "issue"."id"%TYPE )
2164 RETURNS VOID
2165 LANGUAGE 'plpgsql' VOLATILE AS $$
2166 DECLARE
2167 "member_id_v" "member"."id"%TYPE;
2168 BEGIN
2169 DELETE FROM "direct_interest_snapshot"
2170 WHERE "issue_id" = "issue_id_p"
2171 AND "event" = 'periodic';
2172 DELETE FROM "delegating_interest_snapshot"
2173 WHERE "issue_id" = "issue_id_p"
2174 AND "event" = 'periodic';
2175 DELETE FROM "direct_supporter_snapshot"
2176 WHERE "issue_id" = "issue_id_p"
2177 AND "event" = 'periodic';
2178 INSERT INTO "direct_interest_snapshot"
2179 ("issue_id", "event", "member_id", "voting_requested")
2180 SELECT
2181 "issue_id_p" AS "issue_id",
2182 'periodic' AS "event",
2183 "member"."id" AS "member_id",
2184 "interest"."voting_requested"
2185 FROM "interest" JOIN "member"
2186 ON "interest"."member_id" = "member"."id"
2187 WHERE "interest"."issue_id" = "issue_id_p"
2188 AND "member"."active";
2189 FOR "member_id_v" IN
2190 SELECT "member_id" FROM "direct_interest_snapshot"
2191 WHERE "issue_id" = "issue_id_p"
2192 AND "event" = 'periodic'
2193 LOOP
2194 UPDATE "direct_interest_snapshot" SET
2195 "weight" = 1 +
2196 "weight_of_added_delegations_for_interest_snapshot"(
2197 "issue_id_p",
2198 "member_id_v",
2199 '{}'
2201 WHERE "issue_id" = "issue_id_p"
2202 AND "event" = 'periodic'
2203 AND "member_id" = "member_id_v";
2204 END LOOP;
2205 INSERT INTO "direct_supporter_snapshot"
2206 ( "issue_id", "initiative_id", "event", "member_id",
2207 "informed", "satisfied" )
2208 SELECT
2209 "issue_id_p" AS "issue_id",
2210 "initiative"."id" AS "initiative_id",
2211 'periodic' AS "event",
2212 "member"."id" AS "member_id",
2213 "supporter"."draft_id" = "current_draft"."id" AS "informed",
2214 NOT EXISTS (
2215 SELECT NULL FROM "critical_opinion"
2216 WHERE "initiative_id" = "initiative"."id"
2217 AND "member_id" = "member"."id"
2218 ) AS "satisfied"
2219 FROM "supporter"
2220 JOIN "member"
2221 ON "supporter"."member_id" = "member"."id"
2222 JOIN "initiative"
2223 ON "supporter"."initiative_id" = "initiative"."id"
2224 JOIN "current_draft"
2225 ON "initiative"."id" = "current_draft"."initiative_id"
2226 JOIN "direct_interest_snapshot"
2227 ON "member"."id" = "direct_interest_snapshot"."member_id"
2228 AND "initiative"."issue_id" = "direct_interest_snapshot"."issue_id"
2229 AND "event" = 'periodic'
2230 WHERE "member"."active"
2231 AND "initiative"."issue_id" = "issue_id_p";
2232 RETURN;
2233 END;
2234 $$;
2236 COMMENT ON FUNCTION "create_interest_snapshot"
2237 ( "issue"."id"%TYPE )
2238 IS 'This function creates a new ''periodic'' interest/supporter snapshot for the given issue. It does neither lock any tables, nor updates precalculated values in other tables.';
2241 CREATE FUNCTION "create_snapshot"
2242 ( "issue_id_p" "issue"."id"%TYPE )
2243 RETURNS VOID
2244 LANGUAGE 'plpgsql' VOLATILE AS $$
2245 DECLARE
2246 "initiative_id_v" "initiative"."id"%TYPE;
2247 "suggestion_id_v" "suggestion"."id"%TYPE;
2248 BEGIN
2249 PERFORM "global_lock"();
2250 PERFORM "create_population_snapshot"("issue_id_p");
2251 PERFORM "create_interest_snapshot"("issue_id_p");
2252 UPDATE "issue" SET
2253 "snapshot" = now(),
2254 "latest_snapshot_event" = 'periodic',
2255 "population" = (
2256 SELECT coalesce(sum("weight"), 0)
2257 FROM "direct_population_snapshot"
2258 WHERE "issue_id" = "issue_id_p"
2259 AND "event" = 'periodic'
2260 ),
2261 "vote_now" = (
2262 SELECT coalesce(sum("weight"), 0)
2263 FROM "direct_interest_snapshot"
2264 WHERE "issue_id" = "issue_id_p"
2265 AND "event" = 'periodic'
2266 AND "voting_requested" = TRUE
2267 ),
2268 "vote_later" = (
2269 SELECT coalesce(sum("weight"), 0)
2270 FROM "direct_interest_snapshot"
2271 WHERE "issue_id" = "issue_id_p"
2272 AND "event" = 'periodic'
2273 AND "voting_requested" = FALSE
2275 WHERE "id" = "issue_id_p";
2276 FOR "initiative_id_v" IN
2277 SELECT "id" FROM "initiative" WHERE "issue_id" = "issue_id_p"
2278 LOOP
2279 UPDATE "initiative" SET
2280 "supporter_count" = (
2281 SELECT coalesce(sum("di"."weight"), 0)
2282 FROM "direct_interest_snapshot" AS "di"
2283 JOIN "direct_supporter_snapshot" AS "ds"
2284 ON "di"."member_id" = "ds"."member_id"
2285 WHERE "di"."issue_id" = "issue_id_p"
2286 AND "di"."event" = 'periodic'
2287 AND "ds"."initiative_id" = "initiative_id_v"
2288 AND "ds"."event" = 'periodic'
2289 ),
2290 "informed_supporter_count" = (
2291 SELECT coalesce(sum("di"."weight"), 0)
2292 FROM "direct_interest_snapshot" AS "di"
2293 JOIN "direct_supporter_snapshot" AS "ds"
2294 ON "di"."member_id" = "ds"."member_id"
2295 WHERE "di"."issue_id" = "issue_id_p"
2296 AND "di"."event" = 'periodic'
2297 AND "ds"."initiative_id" = "initiative_id_v"
2298 AND "ds"."event" = 'periodic'
2299 AND "ds"."informed"
2300 ),
2301 "satisfied_supporter_count" = (
2302 SELECT coalesce(sum("di"."weight"), 0)
2303 FROM "direct_interest_snapshot" AS "di"
2304 JOIN "direct_supporter_snapshot" AS "ds"
2305 ON "di"."member_id" = "ds"."member_id"
2306 WHERE "di"."issue_id" = "issue_id_p"
2307 AND "di"."event" = 'periodic'
2308 AND "ds"."initiative_id" = "initiative_id_v"
2309 AND "ds"."event" = 'periodic'
2310 AND "ds"."satisfied"
2311 ),
2312 "satisfied_informed_supporter_count" = (
2313 SELECT coalesce(sum("di"."weight"), 0)
2314 FROM "direct_interest_snapshot" AS "di"
2315 JOIN "direct_supporter_snapshot" AS "ds"
2316 ON "di"."member_id" = "ds"."member_id"
2317 WHERE "di"."issue_id" = "issue_id_p"
2318 AND "di"."event" = 'periodic'
2319 AND "ds"."initiative_id" = "initiative_id_v"
2320 AND "ds"."event" = 'periodic'
2321 AND "ds"."informed"
2322 AND "ds"."satisfied"
2324 WHERE "id" = "initiative_id_v";
2325 FOR "suggestion_id_v" IN
2326 SELECT "id" FROM "suggestion"
2327 WHERE "initiative_id" = "initiative_id_v"
2328 LOOP
2329 UPDATE "suggestion" SET
2330 "minus2_unfulfilled_count" = (
2331 SELECT coalesce(sum("snapshot"."weight"), 0)
2332 FROM "issue" CROSS JOIN "opinion"
2333 JOIN "direct_interest_snapshot" AS "snapshot"
2334 ON "snapshot"."issue_id" = "issue"."id"
2335 AND "snapshot"."event" = "issue"."latest_snapshot_event"
2336 AND "snapshot"."member_id" = "opinion"."member_id"
2337 WHERE "issue"."id" = "issue_id_p"
2338 AND "opinion"."suggestion_id" = "suggestion_id_v"
2339 AND "opinion"."degree" = -2
2340 AND "opinion"."fulfilled" = FALSE
2341 ),
2342 "minus2_fulfilled_count" = (
2343 SELECT coalesce(sum("snapshot"."weight"), 0)
2344 FROM "issue" CROSS JOIN "opinion"
2345 JOIN "direct_interest_snapshot" AS "snapshot"
2346 ON "snapshot"."issue_id" = "issue"."id"
2347 AND "snapshot"."event" = "issue"."latest_snapshot_event"
2348 AND "snapshot"."member_id" = "opinion"."member_id"
2349 WHERE "issue"."id" = "issue_id_p"
2350 AND "opinion"."suggestion_id" = "suggestion_id_v"
2351 AND "opinion"."degree" = -2
2352 AND "opinion"."fulfilled" = TRUE
2353 ),
2354 "minus1_unfulfilled_count" = (
2355 SELECT coalesce(sum("snapshot"."weight"), 0)
2356 FROM "issue" CROSS JOIN "opinion"
2357 JOIN "direct_interest_snapshot" AS "snapshot"
2358 ON "snapshot"."issue_id" = "issue"."id"
2359 AND "snapshot"."event" = "issue"."latest_snapshot_event"
2360 AND "snapshot"."member_id" = "opinion"."member_id"
2361 WHERE "issue"."id" = "issue_id_p"
2362 AND "opinion"."suggestion_id" = "suggestion_id_v"
2363 AND "opinion"."degree" = -1
2364 AND "opinion"."fulfilled" = FALSE
2365 ),
2366 "minus1_fulfilled_count" = (
2367 SELECT coalesce(sum("snapshot"."weight"), 0)
2368 FROM "issue" CROSS JOIN "opinion"
2369 JOIN "direct_interest_snapshot" AS "snapshot"
2370 ON "snapshot"."issue_id" = "issue"."id"
2371 AND "snapshot"."event" = "issue"."latest_snapshot_event"
2372 AND "snapshot"."member_id" = "opinion"."member_id"
2373 WHERE "issue"."id" = "issue_id_p"
2374 AND "opinion"."suggestion_id" = "suggestion_id_v"
2375 AND "opinion"."degree" = -1
2376 AND "opinion"."fulfilled" = TRUE
2377 ),
2378 "plus1_unfulfilled_count" = (
2379 SELECT coalesce(sum("snapshot"."weight"), 0)
2380 FROM "issue" CROSS JOIN "opinion"
2381 JOIN "direct_interest_snapshot" AS "snapshot"
2382 ON "snapshot"."issue_id" = "issue"."id"
2383 AND "snapshot"."event" = "issue"."latest_snapshot_event"
2384 AND "snapshot"."member_id" = "opinion"."member_id"
2385 WHERE "issue"."id" = "issue_id_p"
2386 AND "opinion"."suggestion_id" = "suggestion_id_v"
2387 AND "opinion"."degree" = 1
2388 AND "opinion"."fulfilled" = FALSE
2389 ),
2390 "plus1_fulfilled_count" = (
2391 SELECT coalesce(sum("snapshot"."weight"), 0)
2392 FROM "issue" CROSS JOIN "opinion"
2393 JOIN "direct_interest_snapshot" AS "snapshot"
2394 ON "snapshot"."issue_id" = "issue"."id"
2395 AND "snapshot"."event" = "issue"."latest_snapshot_event"
2396 AND "snapshot"."member_id" = "opinion"."member_id"
2397 WHERE "issue"."id" = "issue_id_p"
2398 AND "opinion"."suggestion_id" = "suggestion_id_v"
2399 AND "opinion"."degree" = 1
2400 AND "opinion"."fulfilled" = TRUE
2401 ),
2402 "plus2_unfulfilled_count" = (
2403 SELECT coalesce(sum("snapshot"."weight"), 0)
2404 FROM "issue" CROSS JOIN "opinion"
2405 JOIN "direct_interest_snapshot" AS "snapshot"
2406 ON "snapshot"."issue_id" = "issue"."id"
2407 AND "snapshot"."event" = "issue"."latest_snapshot_event"
2408 AND "snapshot"."member_id" = "opinion"."member_id"
2409 WHERE "issue"."id" = "issue_id_p"
2410 AND "opinion"."suggestion_id" = "suggestion_id_v"
2411 AND "opinion"."degree" = 2
2412 AND "opinion"."fulfilled" = FALSE
2413 ),
2414 "plus2_fulfilled_count" = (
2415 SELECT coalesce(sum("snapshot"."weight"), 0)
2416 FROM "issue" CROSS JOIN "opinion"
2417 JOIN "direct_interest_snapshot" AS "snapshot"
2418 ON "snapshot"."issue_id" = "issue"."id"
2419 AND "snapshot"."event" = "issue"."latest_snapshot_event"
2420 AND "snapshot"."member_id" = "opinion"."member_id"
2421 WHERE "issue"."id" = "issue_id_p"
2422 AND "opinion"."suggestion_id" = "suggestion_id_v"
2423 AND "opinion"."degree" = 2
2424 AND "opinion"."fulfilled" = TRUE
2426 WHERE "suggestion"."id" = "suggestion_id_v";
2427 END LOOP;
2428 END LOOP;
2429 RETURN;
2430 END;
2431 $$;
2433 COMMENT ON FUNCTION "create_snapshot"
2434 ( "issue"."id"%TYPE )
2435 IS 'This function creates a complete new ''periodic'' snapshot of population, interest and support for the given issue. All involved tables are locked, and after completion precalculated values in the source tables are updated.';
2438 CREATE FUNCTION "set_snapshot_event"
2439 ( "issue_id_p" "issue"."id"%TYPE,
2440 "event_p" "snapshot_event" )
2441 RETURNS VOID
2442 LANGUAGE 'plpgsql' VOLATILE AS $$
2443 DECLARE
2444 "event_v" "issue"."latest_snapshot_event"%TYPE;
2445 BEGIN
2446 SELECT "latest_snapshot_event" INTO "event_v" FROM "issue"
2447 WHERE "id" = "issue_id_p" FOR UPDATE;
2448 UPDATE "issue" SET "latest_snapshot_event" = "event_p"
2449 WHERE "id" = "issue_id_p";
2450 UPDATE "direct_population_snapshot" SET "event" = "event_p"
2451 WHERE "issue_id" = "issue_id_p" AND "event" = "event_v";
2452 UPDATE "delegating_population_snapshot" SET "event" = "event_p"
2453 WHERE "issue_id" = "issue_id_p" AND "event" = "event_v";
2454 UPDATE "direct_interest_snapshot" SET "event" = "event_p"
2455 WHERE "issue_id" = "issue_id_p" AND "event" = "event_v";
2456 UPDATE "delegating_interest_snapshot" SET "event" = "event_p"
2457 WHERE "issue_id" = "issue_id_p" AND "event" = "event_v";
2458 UPDATE "direct_supporter_snapshot" SET "event" = "event_p"
2459 WHERE "issue_id" = "issue_id_p" AND "event" = "event_v";
2460 RETURN;
2461 END;
2462 $$;
2464 COMMENT ON FUNCTION "set_snapshot_event"
2465 ( "issue"."id"%TYPE,
2466 "snapshot_event" )
2467 IS 'Change "event" attribute of the previous ''periodic'' snapshot';
2471 ---------------------
2472 -- Freezing issues --
2473 ---------------------
2475 CREATE FUNCTION "freeze_after_snapshot"
2476 ( "issue_id_p" "issue"."id"%TYPE )
2477 RETURNS VOID
2478 LANGUAGE 'plpgsql' VOLATILE AS $$
2479 DECLARE
2480 "issue_row" "issue"%ROWTYPE;
2481 "policy_row" "policy"%ROWTYPE;
2482 "initiative_row" "initiative"%ROWTYPE;
2483 BEGIN
2484 SELECT * INTO "issue_row" FROM "issue" WHERE "id" = "issue_id_p";
2485 SELECT * INTO "policy_row"
2486 FROM "policy" WHERE "id" = "issue_row"."policy_id";
2487 PERFORM "set_snapshot_event"("issue_id_p", 'full_freeze');
2488 UPDATE "issue" SET
2489 "accepted" = coalesce("accepted", now()),
2490 "half_frozen" = coalesce("half_frozen", now()),
2491 "fully_frozen" = now()
2492 WHERE "id" = "issue_id_p";
2493 FOR "initiative_row" IN
2494 SELECT * FROM "initiative"
2495 WHERE "issue_id" = "issue_id_p" AND "revoked" ISNULL
2496 LOOP
2497 IF
2498 "initiative_row"."satisfied_supporter_count" > 0 AND
2499 "initiative_row"."satisfied_supporter_count" *
2500 "policy_row"."initiative_quorum_den" >=
2501 "issue_row"."population" * "policy_row"."initiative_quorum_num"
2502 THEN
2503 UPDATE "initiative" SET "admitted" = TRUE
2504 WHERE "id" = "initiative_row"."id";
2505 ELSE
2506 UPDATE "initiative" SET "admitted" = FALSE
2507 WHERE "id" = "initiative_row"."id";
2508 END IF;
2509 END LOOP;
2510 IF NOT EXISTS (
2511 SELECT NULL FROM "initiative"
2512 WHERE "issue_id" = "issue_id_p" AND "admitted" = TRUE
2513 ) THEN
2514 PERFORM "close_voting"("issue_id_p");
2515 END IF;
2516 RETURN;
2517 END;
2518 $$;
2520 COMMENT ON FUNCTION "freeze_after_snapshot"
2521 ( "issue"."id"%TYPE )
2522 IS 'This function freezes an issue (fully) and starts voting, but must only be called when "create_snapshot" was called in the same transaction.';
2525 CREATE FUNCTION "manual_freeze"("issue_id_p" "issue"."id"%TYPE)
2526 RETURNS VOID
2527 LANGUAGE 'plpgsql' VOLATILE AS $$
2528 DECLARE
2529 "issue_row" "issue"%ROWTYPE;
2530 BEGIN
2531 PERFORM "create_snapshot"("issue_id_p");
2532 PERFORM "freeze_after_snapshot"("issue_id_p");
2533 RETURN;
2534 END;
2535 $$;
2537 COMMENT ON FUNCTION "freeze_after_snapshot"
2538 ( "issue"."id"%TYPE )
2539 IS 'Freeze an issue manually (fully) and start voting';
2543 -----------------------
2544 -- Counting of votes --
2545 -----------------------
2548 CREATE FUNCTION "weight_of_added_vote_delegations"
2549 ( "issue_id_p" "issue"."id"%TYPE,
2550 "member_id_p" "member"."id"%TYPE,
2551 "delegate_member_ids_p" "delegating_voter"."delegate_member_ids"%TYPE )
2552 RETURNS "direct_voter"."weight"%TYPE
2553 LANGUAGE 'plpgsql' VOLATILE AS $$
2554 DECLARE
2555 "issue_delegation_row" "issue_delegation"%ROWTYPE;
2556 "delegate_member_ids_v" "delegating_voter"."delegate_member_ids"%TYPE;
2557 "weight_v" INT4;
2558 "sub_weight_v" INT4;
2559 BEGIN
2560 "weight_v" := 0;
2561 FOR "issue_delegation_row" IN
2562 SELECT * FROM "issue_delegation"
2563 WHERE "trustee_id" = "member_id_p"
2564 AND "issue_id" = "issue_id_p"
2565 LOOP
2566 IF NOT EXISTS (
2567 SELECT NULL FROM "direct_voter"
2568 WHERE "member_id" = "issue_delegation_row"."truster_id"
2569 AND "issue_id" = "issue_id_p"
2570 ) AND NOT EXISTS (
2571 SELECT NULL FROM "delegating_voter"
2572 WHERE "member_id" = "issue_delegation_row"."truster_id"
2573 AND "issue_id" = "issue_id_p"
2574 ) THEN
2575 "delegate_member_ids_v" :=
2576 "member_id_p" || "delegate_member_ids_p";
2577 INSERT INTO "delegating_voter" (
2578 "issue_id",
2579 "member_id",
2580 "scope",
2581 "delegate_member_ids"
2582 ) VALUES (
2583 "issue_id_p",
2584 "issue_delegation_row"."truster_id",
2585 "issue_delegation_row"."scope",
2586 "delegate_member_ids_v"
2587 );
2588 "sub_weight_v" := 1 +
2589 "weight_of_added_vote_delegations"(
2590 "issue_id_p",
2591 "issue_delegation_row"."truster_id",
2592 "delegate_member_ids_v"
2593 );
2594 UPDATE "delegating_voter"
2595 SET "weight" = "sub_weight_v"
2596 WHERE "issue_id" = "issue_id_p"
2597 AND "member_id" = "issue_delegation_row"."truster_id";
2598 "weight_v" := "weight_v" + "sub_weight_v";
2599 END IF;
2600 END LOOP;
2601 RETURN "weight_v";
2602 END;
2603 $$;
2605 COMMENT ON FUNCTION "weight_of_added_vote_delegations"
2606 ( "issue"."id"%TYPE,
2607 "member"."id"%TYPE,
2608 "delegating_voter"."delegate_member_ids"%TYPE )
2609 IS 'Helper function for "add_vote_delegations" function';
2612 CREATE FUNCTION "add_vote_delegations"
2613 ( "issue_id_p" "issue"."id"%TYPE )
2614 RETURNS VOID
2615 LANGUAGE 'plpgsql' VOLATILE AS $$
2616 DECLARE
2617 "member_id_v" "member"."id"%TYPE;
2618 BEGIN
2619 FOR "member_id_v" IN
2620 SELECT "member_id" FROM "direct_voter"
2621 WHERE "issue_id" = "issue_id_p"
2622 LOOP
2623 UPDATE "direct_voter" SET
2624 "weight" = "weight" + "weight_of_added_vote_delegations"(
2625 "issue_id_p",
2626 "member_id_v",
2627 '{}'
2629 WHERE "member_id" = "member_id_v"
2630 AND "issue_id" = "issue_id_p";
2631 END LOOP;
2632 RETURN;
2633 END;
2634 $$;
2636 COMMENT ON FUNCTION "add_vote_delegations"
2637 ( "issue_id_p" "issue"."id"%TYPE )
2638 IS 'Helper function for "close_voting" function';
2641 CREATE FUNCTION "close_voting"("issue_id_p" "issue"."id"%TYPE)
2642 RETURNS VOID
2643 LANGUAGE 'plpgsql' VOLATILE AS $$
2644 DECLARE
2645 "issue_row" "issue"%ROWTYPE;
2646 "member_id_v" "member"."id"%TYPE;
2647 BEGIN
2648 PERFORM "global_lock"();
2649 SELECT * INTO "issue_row" FROM "issue" WHERE "id" = "issue_id_p";
2650 DELETE FROM "delegating_voter"
2651 WHERE "issue_id" = "issue_id_p";
2652 DELETE FROM "direct_voter"
2653 WHERE "issue_id" = "issue_id_p"
2654 AND "autoreject" = TRUE;
2655 DELETE FROM "direct_voter" USING "member"
2656 WHERE "direct_voter"."member_id" = "member"."id"
2657 AND "direct_voter"."issue_id" = "issue_id_p"
2658 AND "member"."active" = FALSE;
2659 UPDATE "direct_voter" SET "weight" = 1
2660 WHERE "issue_id" = "issue_id_p";
2661 PERFORM "add_vote_delegations"("issue_id_p");
2662 FOR "member_id_v" IN
2663 SELECT "interest"."member_id"
2664 FROM "interest"
2665 LEFT JOIN "direct_voter"
2666 ON "interest"."member_id" = "direct_voter"."member_id"
2667 AND "interest"."issue_id" = "direct_voter"."issue_id"
2668 LEFT JOIN "delegating_voter"
2669 ON "interest"."member_id" = "delegating_voter"."member_id"
2670 AND "interest"."issue_id" = "delegating_voter"."issue_id"
2671 WHERE "interest"."issue_id" = "issue_id_p"
2672 AND "interest"."autoreject" = TRUE
2673 AND "direct_voter"."member_id" ISNULL
2674 AND "delegating_voter"."member_id" ISNULL
2675 UNION SELECT "membership"."member_id"
2676 FROM "membership"
2677 LEFT JOIN "interest"
2678 ON "membership"."member_id" = "interest"."member_id"
2679 AND "interest"."issue_id" = "issue_id_p"
2680 LEFT JOIN "direct_voter"
2681 ON "membership"."member_id" = "direct_voter"."member_id"
2682 AND "direct_voter"."issue_id" = "issue_id_p"
2683 LEFT JOIN "delegating_voter"
2684 ON "membership"."member_id" = "delegating_voter"."member_id"
2685 AND "delegating_voter"."issue_id" = "issue_id_p"
2686 WHERE "membership"."area_id" = "issue_row"."area_id"
2687 AND "membership"."autoreject" = TRUE
2688 AND "interest"."autoreject" ISNULL
2689 AND "direct_voter"."member_id" ISNULL
2690 AND "delegating_voter"."member_id" ISNULL
2691 LOOP
2692 INSERT INTO "direct_voter"
2693 ("member_id", "issue_id", "weight", "autoreject") VALUES
2694 ("member_id_v", "issue_id_p", 1, TRUE);
2695 INSERT INTO "vote" (
2696 "member_id",
2697 "issue_id",
2698 "initiative_id",
2699 "grade"
2700 ) SELECT
2701 "member_id_v" AS "member_id",
2702 "issue_id_p" AS "issue_id",
2703 "id" AS "initiative_id",
2704 -1 AS "grade"
2705 FROM "initiative" WHERE "issue_id" = "issue_id_p";
2706 END LOOP;
2707 PERFORM "add_vote_delegations"("issue_id_p");
2708 UPDATE "issue" SET
2709 "voter_count" = (
2710 SELECT coalesce(sum("weight"), 0)
2711 FROM "direct_voter" WHERE "issue_id" = "issue_id_p"
2713 WHERE "id" = "issue_id_p";
2714 UPDATE "initiative" SET
2715 "positive_votes" = "vote_counts"."positive_votes",
2716 "negative_votes" = "vote_counts"."negative_votes",
2717 "agreed" = CASE WHEN "majority_strict" THEN
2718 "vote_counts"."positive_votes" * "majority_den" >
2719 "majority_num" *
2720 ("vote_counts"."positive_votes"+"vote_counts"."negative_votes")
2721 ELSE
2722 "vote_counts"."positive_votes" * "majority_den" >=
2723 "majority_num" *
2724 ("vote_counts"."positive_votes"+"vote_counts"."negative_votes")
2725 END
2726 FROM
2727 ( SELECT
2728 "initiative"."id" AS "initiative_id",
2729 coalesce(
2730 sum(
2731 CASE WHEN "grade" > 0 THEN "direct_voter"."weight" ELSE 0 END
2732 ),
2734 ) AS "positive_votes",
2735 coalesce(
2736 sum(
2737 CASE WHEN "grade" < 0 THEN "direct_voter"."weight" ELSE 0 END
2738 ),
2740 ) AS "negative_votes"
2741 FROM "initiative"
2742 JOIN "issue" ON "initiative"."issue_id" = "issue"."id"
2743 JOIN "policy" ON "issue"."policy_id" = "policy"."id"
2744 LEFT JOIN "direct_voter"
2745 ON "direct_voter"."issue_id" = "initiative"."issue_id"
2746 LEFT JOIN "vote"
2747 ON "vote"."initiative_id" = "initiative"."id"
2748 AND "vote"."member_id" = "direct_voter"."member_id"
2749 WHERE "initiative"."issue_id" = "issue_id_p"
2750 AND "initiative"."admitted" -- NOTE: NULL case is handled too
2751 GROUP BY "initiative"."id"
2752 ) AS "vote_counts",
2753 "issue",
2754 "policy"
2755 WHERE "vote_counts"."initiative_id" = "initiative"."id"
2756 AND "issue"."id" = "initiative"."issue_id"
2757 AND "policy"."id" = "issue"."policy_id";
2758 UPDATE "issue" SET "closed" = now() WHERE "id" = "issue_id_p";
2759 END;
2760 $$;
2762 COMMENT ON FUNCTION "close_voting"
2763 ( "issue"."id"%TYPE )
2764 IS 'Closes the voting on an issue, and calculates positive and negative votes for each initiative; The ranking is not calculated yet, to keep the (locking) transaction short.';
2767 CREATE FUNCTION "defeat_strength"
2768 ( "positive_votes_p" INT4, "negative_votes_p" INT4 )
2769 RETURNS INT8
2770 LANGUAGE 'plpgsql' IMMUTABLE AS $$
2771 BEGIN
2772 IF "positive_votes_p" > "negative_votes_p" THEN
2773 RETURN ("positive_votes_p"::INT8 << 31) - "negative_votes_p"::INT8;
2774 ELSIF "positive_votes_p" = "negative_votes_p" THEN
2775 RETURN 0;
2776 ELSE
2777 RETURN -1;
2778 END IF;
2779 END;
2780 $$;
2782 COMMENT ON FUNCTION "defeat_strength"(INT4, INT4) IS 'Calculates defeat strength (INT8!) of a pairwise defeat primarily by the absolute number of votes for the winner and secondarily by the absolute number of votes for the loser';
2785 CREATE FUNCTION "array_init_string"("dim_p" INTEGER)
2786 RETURNS TEXT
2787 LANGUAGE 'plpgsql' IMMUTABLE AS $$
2788 DECLARE
2789 "i" INTEGER;
2790 "ary_text_v" TEXT;
2791 BEGIN
2792 IF "dim_p" >= 1 THEN
2793 "ary_text_v" := '{NULL';
2794 "i" := "dim_p";
2795 LOOP
2796 "i" := "i" - 1;
2797 EXIT WHEN "i" = 0;
2798 "ary_text_v" := "ary_text_v" || ',NULL';
2799 END LOOP;
2800 "ary_text_v" := "ary_text_v" || '}';
2801 RETURN "ary_text_v";
2802 ELSE
2803 RAISE EXCEPTION 'Dimension needs to be at least 1.';
2804 END IF;
2805 END;
2806 $$;
2808 COMMENT ON FUNCTION "array_init_string"(INTEGER) IS 'Needed for PostgreSQL < 8.4, due to missing "array_fill" function';
2811 CREATE FUNCTION "square_matrix_init_string"("dim_p" INTEGER)
2812 RETURNS TEXT
2813 LANGUAGE 'plpgsql' IMMUTABLE AS $$
2814 DECLARE
2815 "i" INTEGER;
2816 "row_text_v" TEXT;
2817 "ary_text_v" TEXT;
2818 BEGIN
2819 IF "dim_p" >= 1 THEN
2820 "row_text_v" := '{NULL';
2821 "i" := "dim_p";
2822 LOOP
2823 "i" := "i" - 1;
2824 EXIT WHEN "i" = 0;
2825 "row_text_v" := "row_text_v" || ',NULL';
2826 END LOOP;
2827 "row_text_v" := "row_text_v" || '}';
2828 "ary_text_v" := '{' || "row_text_v";
2829 "i" := "dim_p";
2830 LOOP
2831 "i" := "i" - 1;
2832 EXIT WHEN "i" = 0;
2833 "ary_text_v" := "ary_text_v" || ',' || "row_text_v";
2834 END LOOP;
2835 "ary_text_v" := "ary_text_v" || '}';
2836 RETURN "ary_text_v";
2837 ELSE
2838 RAISE EXCEPTION 'Dimension needs to be at least 1.';
2839 END IF;
2840 END;
2841 $$;
2843 COMMENT ON FUNCTION "square_matrix_init_string"(INTEGER) IS 'Needed for PostgreSQL < 8.4, due to missing "array_fill" function';
2846 CREATE FUNCTION "calculate_ranks"("issue_id_p" "issue"."id"%TYPE)
2847 RETURNS VOID
2848 LANGUAGE 'plpgsql' VOLATILE AS $$
2849 DECLARE
2850 "dimension_v" INTEGER;
2851 "vote_matrix" INT4[][]; -- absolute votes
2852 "matrix" INT8[][]; -- defeat strength / best paths
2853 "i" INTEGER;
2854 "j" INTEGER;
2855 "k" INTEGER;
2856 "battle_row" "battle"%ROWTYPE;
2857 "rank_ary" INT4[];
2858 "rank_v" INT4;
2859 "done_v" INTEGER;
2860 "winners_ary" INTEGER[];
2861 "initiative_id_v" "initiative"."id"%TYPE;
2862 BEGIN
2863 PERFORM NULL FROM "issue" WHERE "id" = "issue_id_p" FOR UPDATE;
2864 SELECT count(1) INTO "dimension_v" FROM "initiative"
2865 WHERE "issue_id" = "issue_id_p" AND "agreed";
2866 IF "dimension_v" = 1 THEN
2867 UPDATE "initiative" SET "rank" = 1
2868 WHERE "issue_id" = "issue_id_p" AND "agreed";
2869 ELSIF "dimension_v" > 1 THEN
2870 -- Create "vote_matrix" with absolute number of votes in pairwise
2871 -- comparison:
2872 "vote_matrix" := "square_matrix_init_string"("dimension_v"); -- TODO: replace by "array_fill" function (PostgreSQL 8.4)
2873 "i" := 1;
2874 "j" := 2;
2875 FOR "battle_row" IN
2876 SELECT * FROM "battle" WHERE "issue_id" = "issue_id_p"
2877 ORDER BY "winning_initiative_id", "losing_initiative_id"
2878 LOOP
2879 "vote_matrix"["i"]["j"] := "battle_row"."count";
2880 IF "j" = "dimension_v" THEN
2881 "i" := "i" + 1;
2882 "j" := 1;
2883 ELSE
2884 "j" := "j" + 1;
2885 IF "j" = "i" THEN
2886 "j" := "j" + 1;
2887 END IF;
2888 END IF;
2889 END LOOP;
2890 IF "i" != "dimension_v" OR "j" != "dimension_v" + 1 THEN
2891 RAISE EXCEPTION 'Wrong battle count (should not happen)';
2892 END IF;
2893 -- Store defeat strengths in "matrix" using "defeat_strength"
2894 -- function:
2895 "matrix" := "square_matrix_init_string"("dimension_v"); -- TODO: replace by "array_fill" function (PostgreSQL 8.4)
2896 "i" := 1;
2897 LOOP
2898 "j" := 1;
2899 LOOP
2900 IF "i" != "j" THEN
2901 "matrix"["i"]["j"] := "defeat_strength"(
2902 "vote_matrix"["i"]["j"],
2903 "vote_matrix"["j"]["i"]
2904 );
2905 END IF;
2906 EXIT WHEN "j" = "dimension_v";
2907 "j" := "j" + 1;
2908 END LOOP;
2909 EXIT WHEN "i" = "dimension_v";
2910 "i" := "i" + 1;
2911 END LOOP;
2912 -- Find best paths:
2913 "i" := 1;
2914 LOOP
2915 "j" := 1;
2916 LOOP
2917 IF "i" != "j" THEN
2918 "k" := 1;
2919 LOOP
2920 IF "i" != "k" AND "j" != "k" THEN
2921 IF "matrix"["j"]["i"] < "matrix"["i"]["k"] THEN
2922 IF "matrix"["j"]["i"] > "matrix"["j"]["k"] THEN
2923 "matrix"["j"]["k"] := "matrix"["j"]["i"];
2924 END IF;
2925 ELSE
2926 IF "matrix"["i"]["k"] > "matrix"["j"]["k"] THEN
2927 "matrix"["j"]["k"] := "matrix"["i"]["k"];
2928 END IF;
2929 END IF;
2930 END IF;
2931 EXIT WHEN "k" = "dimension_v";
2932 "k" := "k" + 1;
2933 END LOOP;
2934 END IF;
2935 EXIT WHEN "j" = "dimension_v";
2936 "j" := "j" + 1;
2937 END LOOP;
2938 EXIT WHEN "i" = "dimension_v";
2939 "i" := "i" + 1;
2940 END LOOP;
2941 -- Determine order of winners:
2942 "rank_ary" := "array_init_string"("dimension_v"); -- TODO: replace by "array_fill" function (PostgreSQL 8.4)
2943 "rank_v" := 1;
2944 "done_v" := 0;
2945 LOOP
2946 "winners_ary" := '{}';
2947 "i" := 1;
2948 LOOP
2949 IF "rank_ary"["i"] ISNULL THEN
2950 "j" := 1;
2951 LOOP
2952 IF
2953 "i" != "j" AND
2954 "rank_ary"["j"] ISNULL AND
2955 "matrix"["j"]["i"] > "matrix"["i"]["j"]
2956 THEN
2957 -- someone else is better
2958 EXIT;
2959 END IF;
2960 IF "j" = "dimension_v" THEN
2961 -- noone is better
2962 "winners_ary" := "winners_ary" || "i";
2963 EXIT;
2964 END IF;
2965 "j" := "j" + 1;
2966 END LOOP;
2967 END IF;
2968 EXIT WHEN "i" = "dimension_v";
2969 "i" := "i" + 1;
2970 END LOOP;
2971 "i" := 1;
2972 LOOP
2973 "rank_ary"["winners_ary"["i"]] := "rank_v";
2974 "done_v" := "done_v" + 1;
2975 EXIT WHEN "i" = array_upper("winners_ary", 1);
2976 "i" := "i" + 1;
2977 END LOOP;
2978 EXIT WHEN "done_v" = "dimension_v";
2979 "rank_v" := "rank_v" + 1;
2980 END LOOP;
2981 -- write preliminary ranks:
2982 "i" := 1;
2983 FOR "initiative_id_v" IN
2984 SELECT "id" FROM "initiative"
2985 WHERE "issue_id" = "issue_id_p" AND "agreed"
2986 ORDER BY "id"
2987 LOOP
2988 UPDATE "initiative" SET "rank" = "rank_ary"["i"]
2989 WHERE "id" = "initiative_id_v";
2990 "i" := "i" + 1;
2991 END LOOP;
2992 IF "i" != "dimension_v" + 1 THEN
2993 RAISE EXCEPTION 'Wrong winner count (should not happen)';
2994 END IF;
2995 -- straighten ranks (start counting with 1, no equal ranks):
2996 "rank_v" := 1;
2997 FOR "initiative_id_v" IN
2998 SELECT "id" FROM "initiative"
2999 WHERE "issue_id" = "issue_id_p" AND "rank" NOTNULL
3000 ORDER BY
3001 "rank",
3002 "vote_ratio"("positive_votes", "negative_votes") DESC,
3003 "id"
3004 LOOP
3005 UPDATE "initiative" SET "rank" = "rank_v"
3006 WHERE "id" = "initiative_id_v";
3007 "rank_v" := "rank_v" + 1;
3008 END LOOP;
3009 END IF;
3010 -- mark issue as finished
3011 UPDATE "issue" SET "ranks_available" = TRUE
3012 WHERE "id" = "issue_id_p";
3013 RETURN;
3014 END;
3015 $$;
3017 COMMENT ON FUNCTION "calculate_ranks"
3018 ( "issue"."id"%TYPE )
3019 IS 'Determine ranking (Votes have to be counted first)';
3023 -----------------------------
3024 -- Automatic state changes --
3025 -----------------------------
3028 CREATE FUNCTION "check_issue"
3029 ( "issue_id_p" "issue"."id"%TYPE )
3030 RETURNS VOID
3031 LANGUAGE 'plpgsql' VOLATILE AS $$
3032 DECLARE
3033 "issue_row" "issue"%ROWTYPE;
3034 "policy_row" "policy"%ROWTYPE;
3035 "voting_requested_v" BOOLEAN;
3036 BEGIN
3037 PERFORM "global_lock"();
3038 SELECT * INTO "issue_row" FROM "issue" WHERE "id" = "issue_id_p";
3039 -- only process open issues:
3040 IF "issue_row"."closed" ISNULL THEN
3041 SELECT * INTO "policy_row" FROM "policy"
3042 WHERE "id" = "issue_row"."policy_id";
3043 -- create a snapshot, unless issue is already fully frozen:
3044 IF "issue_row"."fully_frozen" ISNULL THEN
3045 PERFORM "create_snapshot"("issue_id_p");
3046 SELECT * INTO "issue_row" FROM "issue" WHERE "id" = "issue_id_p";
3047 END IF;
3048 -- eventually close or accept issues, which have not been accepted:
3049 IF "issue_row"."accepted" ISNULL THEN
3050 IF EXISTS (
3051 SELECT NULL FROM "initiative"
3052 WHERE "issue_id" = "issue_id_p"
3053 AND "supporter_count" > 0
3054 AND "supporter_count" * "policy_row"."issue_quorum_den"
3055 >= "issue_row"."population" * "policy_row"."issue_quorum_num"
3056 ) THEN
3057 -- accept issues, if supporter count is high enough
3058 PERFORM "set_snapshot_event"("issue_id_p", 'end_of_admission');
3059 "issue_row"."accepted" = now(); -- NOTE: "issue_row" used later
3060 UPDATE "issue" SET "accepted" = "issue_row"."accepted"
3061 WHERE "id" = "issue_row"."id";
3062 ELSIF
3063 now() >= "issue_row"."created" + "issue_row"."admission_time"
3064 THEN
3065 -- close issues, if admission time has expired
3066 PERFORM "set_snapshot_event"("issue_id_p", 'end_of_admission');
3067 UPDATE "issue" SET "closed" = now()
3068 WHERE "id" = "issue_row"."id";
3069 END IF;
3070 END IF;
3071 -- eventually half freeze issues:
3072 IF
3073 -- NOTE: issue can't be closed at this point, if it has been accepted
3074 "issue_row"."accepted" NOTNULL AND
3075 "issue_row"."half_frozen" ISNULL
3076 THEN
3077 SELECT
3078 CASE
3079 WHEN "vote_now" * 2 > "issue_row"."population" THEN
3080 TRUE
3081 WHEN "vote_later" * 2 > "issue_row"."population" THEN
3082 FALSE
3083 ELSE NULL
3084 END
3085 INTO "voting_requested_v"
3086 FROM "issue" WHERE "id" = "issue_id_p";
3087 IF
3088 "voting_requested_v" OR (
3089 "voting_requested_v" ISNULL AND
3090 now() >= "issue_row"."accepted" + "issue_row"."discussion_time"
3092 THEN
3093 PERFORM "set_snapshot_event"("issue_id_p", 'half_freeze');
3094 "issue_row"."half_frozen" = now(); -- NOTE: "issue_row" used later
3095 UPDATE "issue" SET "half_frozen" = "issue_row"."half_frozen"
3096 WHERE "id" = "issue_row"."id";
3097 END IF;
3098 END IF;
3099 -- close issues after some time, if all initiatives have been revoked:
3100 IF
3101 "issue_row"."closed" ISNULL AND
3102 NOT EXISTS (
3103 -- all initiatives are revoked
3104 SELECT NULL FROM "initiative"
3105 WHERE "issue_id" = "issue_id_p" AND "revoked" ISNULL
3106 ) AND (
3107 NOT EXISTS (
3108 -- and no initiatives have been revoked lately
3109 SELECT NULL FROM "initiative"
3110 WHERE "issue_id" = "issue_id_p"
3111 AND now() < "revoked" + "issue_row"."verification_time"
3112 ) OR (
3113 -- or verification time has elapsed
3114 "issue_row"."half_frozen" NOTNULL AND
3115 "issue_row"."fully_frozen" ISNULL AND
3116 now() >= "issue_row"."half_frozen" + "issue_row"."verification_time"
3119 THEN
3120 "issue_row"."closed" = now(); -- NOTE: "issue_row" used later
3121 UPDATE "issue" SET "closed" = "issue_row"."closed"
3122 WHERE "id" = "issue_row"."id";
3123 END IF;
3124 -- fully freeze issue after verification time:
3125 IF
3126 "issue_row"."half_frozen" NOTNULL AND
3127 "issue_row"."fully_frozen" ISNULL AND
3128 "issue_row"."closed" ISNULL AND
3129 now() >= "issue_row"."half_frozen" + "issue_row"."verification_time"
3130 THEN
3131 PERFORM "freeze_after_snapshot"("issue_id_p");
3132 -- NOTE: "issue" might change, thus "issue_row" has to be updated below
3133 END IF;
3134 SELECT * INTO "issue_row" FROM "issue" WHERE "id" = "issue_id_p";
3135 -- close issue by calling close_voting(...) after voting time:
3136 IF
3137 "issue_row"."closed" ISNULL AND
3138 "issue_row"."fully_frozen" NOTNULL AND
3139 now() >= "issue_row"."fully_frozen" + "issue_row"."voting_time"
3140 THEN
3141 PERFORM "close_voting"("issue_id_p");
3142 END IF;
3143 END IF;
3144 RETURN;
3145 END;
3146 $$;
3148 COMMENT ON FUNCTION "check_issue"
3149 ( "issue"."id"%TYPE )
3150 IS 'Precalculate supporter counts etc. for a given issue, and check, if status change is required; At end of voting the ranking is not calculated by this function, but must be calculated in a seperate transaction using the "calculate_ranks" function.';
3153 CREATE FUNCTION "check_everything"()
3154 RETURNS VOID
3155 LANGUAGE 'plpgsql' VOLATILE AS $$
3156 DECLARE
3157 "issue_id_v" "issue"."id"%TYPE;
3158 BEGIN
3159 DELETE FROM "expired_session";
3160 PERFORM "calculate_member_counts"();
3161 FOR "issue_id_v" IN SELECT "id" FROM "open_issue" LOOP
3162 PERFORM "check_issue"("issue_id_v");
3163 END LOOP;
3164 FOR "issue_id_v" IN SELECT "id" FROM "issue_with_ranks_missing" LOOP
3165 PERFORM "calculate_ranks"("issue_id_v");
3166 END LOOP;
3167 RETURN;
3168 END;
3169 $$;
3171 COMMENT ON FUNCTION "check_everything"() IS 'Perform "check_issue" for every open issue, and if possible, automatically calculate ranks. Use this function only for development and debugging purposes, as long transactions with exclusive locking may result.';
3175 ------------------------------
3176 -- Deletion of private data --
3177 ------------------------------
3180 CREATE FUNCTION "delete_member"("member_id_p" "member"."id"%TYPE)
3181 RETURNS VOID
3182 LANGUAGE 'plpgsql' VOLATILE AS $$
3183 BEGIN
3184 UPDATE "member" SET
3185 "login" = NULL,
3186 "password" = NULL,
3187 "active" = FALSE,
3188 "notify_email" = NULL,
3189 "notify_email_unconfirmed" = NULL,
3190 "notify_email_secret" = NULL,
3191 "notify_email_secret_expiry" = NULL,
3192 "password_reset_secret" = NULL,
3193 "password_reset_secret_expiry" = NULL,
3194 "organizational_unit" = NULL,
3195 "internal_posts" = NULL,
3196 "realname" = NULL,
3197 "birthday" = NULL,
3198 "address" = NULL,
3199 "email" = NULL,
3200 "xmpp_address" = NULL,
3201 "website" = NULL,
3202 "phone" = NULL,
3203 "mobile_phone" = NULL,
3204 "profession" = NULL,
3205 "external_memberships" = NULL,
3206 "external_posts" = NULL,
3207 "statement" = NULL
3208 WHERE "id" = "member_id_p";
3209 -- "text_search_data" is updated by triggers
3210 UPDATE "member_history" SET "login" = NULL
3211 WHERE "member_id" = "member_id_p";
3212 DELETE FROM "setting" WHERE "member_id" = "member_id_p";
3213 DELETE FROM "setting_map" WHERE "member_id" = "member_id_p";
3214 DELETE FROM "member_relation_setting" WHERE "member_id" = "member_id_p";
3215 DELETE FROM "member_image" WHERE "member_id" = "member_id_p";
3216 DELETE FROM "contact" WHERE "member_id" = "member_id_p";
3217 DELETE FROM "area_setting" WHERE "member_id" = "member_id_p";
3218 DELETE FROM "issue_setting" WHERE "member_id" = "member_id_p";
3219 DELETE FROM "initiative_setting" WHERE "member_id" = "member_id_p";
3220 DELETE FROM "suggestion_setting" WHERE "member_id" = "member_id_p";
3221 DELETE FROM "membership" WHERE "member_id" = "member_id_p";
3222 DELETE FROM "delegation" WHERE "truster_id" = "member_id_p";
3223 RETURN;
3224 END;
3225 $$;
3227 COMMENT ON FUNCTION "delete_member"("member_id_p" "member"."id"%TYPE) IS 'Clear certain settings and data of a particular member (data protection)';
3230 CREATE FUNCTION "delete_private_data"()
3231 RETURNS VOID
3232 LANGUAGE 'plpgsql' VOLATILE AS $$
3233 BEGIN
3234 UPDATE "member" SET
3235 "login" = NULL,
3236 "password" = NULL,
3237 "notify_email" = NULL,
3238 "notify_email_unconfirmed" = NULL,
3239 "notify_email_secret" = NULL,
3240 "notify_email_secret_expiry" = NULL,
3241 "password_reset_secret" = NULL,
3242 "password_reset_secret_expiry" = NULL,
3243 "organizational_unit" = NULL,
3244 "internal_posts" = NULL,
3245 "realname" = NULL,
3246 "birthday" = NULL,
3247 "address" = NULL,
3248 "email" = NULL,
3249 "xmpp_address" = NULL,
3250 "website" = NULL,
3251 "phone" = NULL,
3252 "mobile_phone" = NULL,
3253 "profession" = NULL,
3254 "external_memberships" = NULL,
3255 "external_posts" = NULL,
3256 "statement" = NULL;
3257 -- "text_search_data" is updated by triggers
3258 UPDATE "member_history" SET "login" = NULL;
3259 DELETE FROM "invite_code";
3260 DELETE FROM "setting";
3261 DELETE FROM "setting_map";
3262 DELETE FROM "member_relation_setting";
3263 DELETE FROM "member_image";
3264 DELETE FROM "contact";
3265 DELETE FROM "session";
3266 DELETE FROM "area_setting";
3267 DELETE FROM "issue_setting";
3268 DELETE FROM "initiative_setting";
3269 DELETE FROM "suggestion_setting";
3270 DELETE FROM "direct_voter" USING "issue"
3271 WHERE "direct_voter"."issue_id" = "issue"."id"
3272 AND "issue"."closed" ISNULL;
3273 RETURN;
3274 END;
3275 $$;
3277 COMMENT ON FUNCTION "delete_private_data"() IS 'DO NOT USE on productive database, but only on a copy! This function deletes all data which should not be publicly available, and can be used to create a database dump for publication.';
3281 COMMIT;

Impressum / About Us