liquid_feedback_core

view core.sql @ 139:e3bfa2d7954c

Always ensure stable voting results by disqualifying certain initiatives, and bugfix related to setting "issue_state" in "calculate_ranks"

- Removed column "majority_indirect" from table "policy"
- Removed column "eligible" from table "initiative" ("eligible" can be calculated as "attainable"=TRUE AND "favored"=TRUE AND "disqualified"=FALSE)
- Split "rank" column of table "initiative" into columns "preliminary_rank" and "final_rank"
- Added column "disqualified" to table "initiative"
- Removed column "promising" from table "initiative"
- Removed constraints from table "initiative"
- Updated functions "close_voting" and "calculate_ranks"
- Added TODO notice in function "clean_issue"
author jbe
date Sun May 29 19:51:16 2011 +0200 (2011-05-29)
parents 1542ffbc7ddb
children c6a47e32b2fb
line source
2 -- Execute the following command manually for PostgreSQL prior version 9.0:
3 -- CREATE LANGUAGE plpgsql;
5 -- NOTE: In PostgreSQL every UNIQUE constraint implies creation of an index
7 BEGIN;
9 CREATE VIEW "liquid_feedback_version" AS
10 SELECT * FROM (VALUES ('1.4.0_rc1', 1, 4, -1))
11 AS "subquery"("string", "major", "minor", "revision");
15 ----------------------
16 -- Full text search --
17 ----------------------
20 CREATE FUNCTION "text_search_query"("query_text_p" TEXT)
21 RETURNS TSQUERY
22 LANGUAGE 'plpgsql' IMMUTABLE AS $$
23 BEGIN
24 RETURN plainto_tsquery('pg_catalog.simple', "query_text_p");
25 END;
26 $$;
28 COMMENT ON FUNCTION "text_search_query"(TEXT) IS 'Usage: WHERE "text_search_data" @@ "text_search_query"(''<user query>'')';
31 CREATE FUNCTION "highlight"
32 ( "body_p" TEXT,
33 "query_text_p" TEXT )
34 RETURNS TEXT
35 LANGUAGE 'plpgsql' IMMUTABLE AS $$
36 BEGIN
37 RETURN ts_headline(
38 'pg_catalog.simple',
39 replace(replace("body_p", e'\\', e'\\\\'), '*', e'\\*'),
40 "text_search_query"("query_text_p"),
41 'StartSel=* StopSel=* HighlightAll=TRUE' );
42 END;
43 $$;
45 COMMENT ON FUNCTION "highlight"
46 ( "body_p" TEXT,
47 "query_text_p" TEXT )
48 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.';
52 -------------------------
53 -- Tables and indicies --
54 -------------------------
57 CREATE TABLE "system_setting" (
58 "member_ttl" INTERVAL );
59 CREATE UNIQUE INDEX "system_setting_singleton_idx" ON "system_setting" ((1));
61 COMMENT ON TABLE "system_setting" IS 'This table contains only one row with different settings in each column.';
62 COMMENT ON INDEX "system_setting_singleton_idx" IS 'This index ensures that "system_setting" only contains one row maximum.';
64 COMMENT ON COLUMN "system_setting"."member_ttl" IS 'Time after members get their "active" flag set to FALSE, if they do not login anymore.';
67 CREATE TABLE "contingent" (
68 "time_frame" INTERVAL PRIMARY KEY,
69 "text_entry_limit" INT4,
70 "initiative_limit" INT4 );
72 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.';
74 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';
75 COMMENT ON COLUMN "contingent"."initiative_limit" IS 'Number of new initiatives to be opened by each member within a given time frame';
78 CREATE TYPE "notify_level" AS ENUM
79 ('none', 'voting', 'verification', 'discussion', 'all');
81 COMMENT ON TYPE "notify_level" IS 'Level of notification: ''none'' = no notifications, ''voting'' = notifications about finished issues and issues in voting, ''verification'' = notifications about finished issues, issues in voting and verification phase, ''discussion'' = notifications about everything except issues in admission phase, ''all'' = notifications about everything';
84 CREATE TABLE "member" (
85 "id" SERIAL4 PRIMARY KEY,
86 "created" TIMESTAMPTZ NOT NULL DEFAULT now(),
87 "last_login" TIMESTAMPTZ,
88 "last_login_public" DATE,
89 "login" TEXT UNIQUE,
90 "password" TEXT,
91 "locked" BOOLEAN NOT NULL DEFAULT FALSE,
92 "active" BOOLEAN NOT NULL DEFAULT TRUE,
93 "admin" BOOLEAN NOT NULL DEFAULT FALSE,
94 "notify_email" TEXT,
95 "notify_email_unconfirmed" TEXT,
96 "notify_email_secret" TEXT UNIQUE,
97 "notify_email_secret_expiry" TIMESTAMPTZ,
98 "notify_email_lock_expiry" TIMESTAMPTZ,
99 "notify_level" "notify_level" NOT NULL DEFAULT 'none',
100 "notify_event_id" INT8,
101 "password_reset_secret" TEXT UNIQUE,
102 "password_reset_secret_expiry" TIMESTAMPTZ,
103 "name" TEXT NOT NULL UNIQUE,
104 "identification" TEXT UNIQUE,
105 "organizational_unit" TEXT,
106 "internal_posts" TEXT,
107 "realname" TEXT,
108 "birthday" DATE,
109 "address" TEXT,
110 "email" TEXT,
111 "xmpp_address" TEXT,
112 "website" TEXT,
113 "phone" TEXT,
114 "mobile_phone" TEXT,
115 "profession" TEXT,
116 "external_memberships" TEXT,
117 "external_posts" TEXT,
118 "statement" TEXT,
119 "text_search_data" TSVECTOR );
120 CREATE INDEX "member_active_idx" ON "member" ("active");
121 CREATE INDEX "member_text_search_data_idx" ON "member" USING gin ("text_search_data");
122 CREATE TRIGGER "update_text_search_data"
123 BEFORE INSERT OR UPDATE ON "member"
124 FOR EACH ROW EXECUTE PROCEDURE
125 tsvector_update_trigger('text_search_data', 'pg_catalog.simple',
126 "name", "identification", "organizational_unit", "internal_posts",
127 "realname", "external_memberships", "external_posts", "statement" );
129 COMMENT ON TABLE "member" IS 'Users of the system, e.g. members of an organization';
131 COMMENT ON COLUMN "member"."last_login" IS 'Timestamp of last login';
132 COMMENT ON COLUMN "member"."last_login_public" IS 'Date of last login (time stripped for privacy reasons, updated only after day change)';
133 COMMENT ON COLUMN "member"."login" IS 'Login name';
134 COMMENT ON COLUMN "member"."password" IS 'Password (preferably as crypto-hash, depending on the frontend or access layer)';
135 COMMENT ON COLUMN "member"."locked" IS 'Locked members can not log in.';
136 COMMENT ON COLUMN "member"."active" IS 'Memberships, support and votes are taken into account when corresponding members are marked as active. When the user does not log in for an extended period of time, this flag may be set to FALSE. If the user is not locked, he/she may reset the active flag by logging in.';
137 COMMENT ON COLUMN "member"."admin" IS 'TRUE for admins, which can administrate other users and setup policies and areas';
138 COMMENT ON COLUMN "member"."notify_email" IS 'Email address where notifications of the system are sent to';
139 COMMENT ON COLUMN "member"."notify_email_unconfirmed" IS 'Unconfirmed email address provided by the member to be copied into "notify_email" field after verification';
140 COMMENT ON COLUMN "member"."notify_email_secret" IS 'Secret sent to the address in "notify_email_unconformed"';
141 COMMENT ON COLUMN "member"."notify_email_secret_expiry" IS 'Expiry date/time for "notify_email_secret"';
142 COMMENT ON COLUMN "member"."notify_email_lock_expiry" IS 'Date/time until no further email confirmation mails may be sent (abuse protection)';
143 COMMENT ON COLUMN "member"."notify_level" IS 'Selects which event notifications are to be sent to the "notify_email" mail address';
144 COMMENT ON COLUMN "member"."notify_event_id" IS 'Latest "id" of an "event" the member was notified about';
145 COMMENT ON COLUMN "member"."name" IS 'Distinct name of the member';
146 COMMENT ON COLUMN "member"."identification" IS 'Optional identification number or code of the member';
147 COMMENT ON COLUMN "member"."organizational_unit" IS 'Branch or division of the organization the member belongs to';
148 COMMENT ON COLUMN "member"."internal_posts" IS 'Posts (offices) of the member inside the organization';
149 COMMENT ON COLUMN "member"."realname" IS 'Real name of the member, may be identical with "name"';
150 COMMENT ON COLUMN "member"."email" IS 'Published email address of the member; not used for system notifications';
151 COMMENT ON COLUMN "member"."external_memberships" IS 'Other organizations the member is involved in';
152 COMMENT ON COLUMN "member"."external_posts" IS 'Posts (offices) outside the organization';
153 COMMENT ON COLUMN "member"."statement" IS 'Freely chosen text of the member for his homepage within the system';
156 CREATE TABLE "member_history" (
157 "id" SERIAL8 PRIMARY KEY,
158 "member_id" INT4 NOT NULL REFERENCES "member" ("id") ON DELETE CASCADE ON UPDATE CASCADE,
159 "until" TIMESTAMPTZ NOT NULL DEFAULT now(),
160 "active" BOOLEAN NOT NULL,
161 "name" TEXT NOT NULL );
162 CREATE INDEX "member_history_member_id_idx" ON "member_history" ("member_id");
164 COMMENT ON TABLE "member_history" IS 'Filled by trigger; keeps information about old names and active flag of members';
166 COMMENT ON COLUMN "member_history"."id" IS 'Primary key, which can be used to sort entries correctly (and time warp resistant)';
167 COMMENT ON COLUMN "member_history"."until" IS 'Timestamp until the data was valid';
170 CREATE TABLE "invite_code" (
171 "id" SERIAL8 PRIMARY KEY,
172 "code" TEXT NOT NULL UNIQUE,
173 "created" TIMESTAMPTZ NOT NULL DEFAULT now(),
174 "used" TIMESTAMPTZ,
175 "member_id" INT4 UNIQUE REFERENCES "member" ("id") ON DELETE SET NULL ON UPDATE CASCADE,
176 "comment" TEXT,
177 CONSTRAINT "only_used_codes_may_refer_to_member" CHECK ("used" NOTNULL OR "member_id" ISNULL) );
179 COMMENT ON TABLE "invite_code" IS 'Invite codes can be used once to create a new member account.';
181 COMMENT ON COLUMN "invite_code"."code" IS 'Secret code';
182 COMMENT ON COLUMN "invite_code"."created" IS 'Time of creation of the secret code';
183 COMMENT ON COLUMN "invite_code"."used" IS 'NULL, if not used yet, otherwise tells when this code was used to create a member account';
184 COMMENT ON COLUMN "invite_code"."member_id" IS 'References the member whose account was created with this code';
185 COMMENT ON COLUMN "invite_code"."comment" IS 'Comment on the code, which is to be used for administrative reasons only';
188 CREATE TABLE "setting" (
189 PRIMARY KEY ("member_id", "key"),
190 "member_id" INT4 REFERENCES "member" ("id") ON DELETE CASCADE ON UPDATE CASCADE,
191 "key" TEXT NOT NULL,
192 "value" TEXT NOT NULL );
193 CREATE INDEX "setting_key_idx" ON "setting" ("key");
195 COMMENT ON TABLE "setting" IS 'Place to store a frontend specific setting for members as a string';
197 COMMENT ON COLUMN "setting"."key" IS 'Name of the setting, preceded by a frontend specific prefix';
200 CREATE TABLE "setting_map" (
201 PRIMARY KEY ("member_id", "key", "subkey"),
202 "member_id" INT4 REFERENCES "member" ("id") ON DELETE CASCADE ON UPDATE CASCADE,
203 "key" TEXT NOT NULL,
204 "subkey" TEXT NOT NULL,
205 "value" TEXT NOT NULL );
206 CREATE INDEX "setting_map_key_idx" ON "setting_map" ("key");
208 COMMENT ON TABLE "setting_map" IS 'Place to store a frontend specific setting for members as a map of key value pairs';
210 COMMENT ON COLUMN "setting_map"."key" IS 'Name of the setting, preceded by a frontend specific prefix';
211 COMMENT ON COLUMN "setting_map"."subkey" IS 'Key of a map entry';
212 COMMENT ON COLUMN "setting_map"."value" IS 'Value of a map entry';
215 CREATE TABLE "member_relation_setting" (
216 PRIMARY KEY ("member_id", "key", "other_member_id"),
217 "member_id" INT4 REFERENCES "member" ("id") ON DELETE CASCADE ON UPDATE CASCADE,
218 "key" TEXT NOT NULL,
219 "other_member_id" INT4 REFERENCES "member" ("id") ON DELETE CASCADE ON UPDATE CASCADE,
220 "value" TEXT NOT NULL );
222 COMMENT ON TABLE "member_relation_setting" IS 'Place to store a frontend specific setting related to relations between members as a string';
225 CREATE TYPE "member_image_type" AS ENUM ('photo', 'avatar');
227 COMMENT ON TYPE "member_image_type" IS 'Types of images for a member';
230 CREATE TABLE "member_image" (
231 PRIMARY KEY ("member_id", "image_type", "scaled"),
232 "member_id" INT4 REFERENCES "member" ("id") ON DELETE CASCADE ON UPDATE CASCADE,
233 "image_type" "member_image_type",
234 "scaled" BOOLEAN,
235 "content_type" TEXT,
236 "data" BYTEA NOT NULL );
238 COMMENT ON TABLE "member_image" IS 'Images of members';
240 COMMENT ON COLUMN "member_image"."scaled" IS 'FALSE for original image, TRUE for scaled version of the image';
243 CREATE TABLE "member_count" (
244 "calculated" TIMESTAMPTZ NOT NULL DEFAULT NOW(),
245 "total_count" INT4 NOT NULL );
247 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';
249 COMMENT ON COLUMN "member_count"."calculated" IS 'timestamp indicating when the total member count and area member counts were calculated';
250 COMMENT ON COLUMN "member_count"."total_count" IS 'Total count of active(!) members';
253 CREATE TABLE "contact" (
254 PRIMARY KEY ("member_id", "other_member_id"),
255 "member_id" INT4 REFERENCES "member" ("id") ON DELETE CASCADE ON UPDATE CASCADE,
256 "other_member_id" INT4 REFERENCES "member" ("id") ON DELETE CASCADE ON UPDATE CASCADE,
257 "public" BOOLEAN NOT NULL DEFAULT FALSE,
258 CONSTRAINT "cant_save_yourself_as_contact"
259 CHECK ("member_id" != "other_member_id") );
260 CREATE INDEX "contact_other_member_id_idx" ON "contact" ("other_member_id");
262 COMMENT ON TABLE "contact" IS 'Contact lists';
264 COMMENT ON COLUMN "contact"."member_id" IS 'Member having the contact list';
265 COMMENT ON COLUMN "contact"."other_member_id" IS 'Member referenced in the contact list';
266 COMMENT ON COLUMN "contact"."public" IS 'TRUE = display contact publically';
269 CREATE TABLE "ignored_member" (
270 PRIMARY KEY ("member_id", "other_member_id"),
271 "member_id" INT4 REFERENCES "member" ("id") ON DELETE CASCADE ON UPDATE CASCADE,
272 "other_member_id" INT4 REFERENCES "member" ("id") ON DELETE CASCADE ON UPDATE CASCADE );
273 CREATE INDEX "ignored_member_other_member_id_idx" ON "ignored_member" ("other_member_id");
275 COMMENT ON TABLE "ignored_member" IS 'Possibility to filter other members';
277 COMMENT ON COLUMN "ignored_member"."member_id" IS 'Member ignoring someone';
278 COMMENT ON COLUMN "ignored_member"."other_member_id" IS 'Member being ignored';
281 CREATE TABLE "session" (
282 "ident" TEXT PRIMARY KEY,
283 "additional_secret" TEXT,
284 "expiry" TIMESTAMPTZ NOT NULL DEFAULT now() + '24 hours',
285 "member_id" INT8 REFERENCES "member" ("id") ON DELETE SET NULL,
286 "lang" TEXT );
287 CREATE INDEX "session_expiry_idx" ON "session" ("expiry");
289 COMMENT ON TABLE "session" IS 'Sessions, i.e. for a web-frontend';
291 COMMENT ON COLUMN "session"."ident" IS 'Secret session identifier (i.e. random string)';
292 COMMENT ON COLUMN "session"."additional_secret" IS 'Additional field to store a secret, which can be used against CSRF attacks';
293 COMMENT ON COLUMN "session"."member_id" IS 'Reference to member, who is logged in';
294 COMMENT ON COLUMN "session"."lang" IS 'Language code of the selected language';
297 CREATE TABLE "policy" (
298 "id" SERIAL4 PRIMARY KEY,
299 "index" INT4 NOT NULL,
300 "active" BOOLEAN NOT NULL DEFAULT TRUE,
301 "name" TEXT NOT NULL UNIQUE,
302 "description" TEXT NOT NULL DEFAULT '',
303 "admission_time" INTERVAL NOT NULL,
304 "discussion_time" INTERVAL NOT NULL,
305 "verification_time" INTERVAL NOT NULL,
306 "voting_time" INTERVAL NOT NULL,
307 "issue_quorum_num" INT4 NOT NULL,
308 "issue_quorum_den" INT4 NOT NULL,
309 "initiative_quorum_num" INT4 NOT NULL,
310 "initiative_quorum_den" INT4 NOT NULL,
311 "majority_num" INT4 NOT NULL DEFAULT 1,
312 "majority_den" INT4 NOT NULL DEFAULT 2,
313 "majority_strict" BOOLEAN NOT NULL DEFAULT TRUE );
314 CREATE INDEX "policy_active_idx" ON "policy" ("active");
316 COMMENT ON TABLE "policy" IS 'Policies for a particular proceeding type (timelimits, quorum)';
318 COMMENT ON COLUMN "policy"."index" IS 'Determines the order in listings';
319 COMMENT ON COLUMN "policy"."active" IS 'TRUE = policy can be used for new issues';
320 COMMENT ON COLUMN "policy"."admission_time" IS 'Maximum time an issue stays open without being "accepted"';
321 COMMENT ON COLUMN "policy"."discussion_time" IS 'Regular time until an issue is "half_frozen" after being "accepted"';
322 COMMENT ON COLUMN "policy"."verification_time" IS 'Regular time until an issue is "fully_frozen" after being "half_frozen"';
323 COMMENT ON COLUMN "policy"."voting_time" IS 'Time after an issue is "fully_frozen" but not "closed"';
324 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"';
325 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"';
326 COMMENT ON COLUMN "policy"."initiative_quorum_num" IS 'Numerator of satisfied supporter quorum to be reached by an initiative to be "admitted" for voting';
327 COMMENT ON COLUMN "policy"."initiative_quorum_den" IS 'Denominator of satisfied supporter quorum to be reached by an initiative to be "admitted" for voting';
328 COMMENT ON COLUMN "policy"."majority_num" IS 'Numerator of fraction of majority to be reached during voting by an initiative to be aggreed upon';
329 COMMENT ON COLUMN "policy"."majority_den" IS 'Denominator of fraction of majority to be reached during voting by an initiative to be aggreed upon';
330 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.';
333 CREATE TABLE "unit" (
334 "id" SERIAL4 PRIMARY KEY,
335 "parent_id" INT4 REFERENCES "unit" ("id") ON DELETE CASCADE ON UPDATE CASCADE,
336 "active" BOOLEAN NOT NULL DEFAULT TRUE,
337 "name" TEXT NOT NULL,
338 "description" TEXT NOT NULL DEFAULT '',
339 "member_count" INT4,
340 "text_search_data" TSVECTOR );
341 CREATE INDEX "unit_root_idx" ON "unit" ("id") WHERE "parent_id" ISNULL;
342 CREATE INDEX "unit_parent_id_idx" ON "unit" ("parent_id");
343 CREATE INDEX "unit_active_idx" ON "unit" ("active");
344 CREATE INDEX "unit_text_search_data_idx" ON "unit" USING gin ("text_search_data");
345 CREATE TRIGGER "update_text_search_data"
346 BEFORE INSERT OR UPDATE ON "unit"
347 FOR EACH ROW EXECUTE PROCEDURE
348 tsvector_update_trigger('text_search_data', 'pg_catalog.simple',
349 "name", "description" );
351 COMMENT ON TABLE "unit" IS 'Organizational units organized as trees; Delegations are not inherited through these trees.';
353 COMMENT ON COLUMN "unit"."parent_id" IS 'Parent id of tree node; Multiple roots allowed';
354 COMMENT ON COLUMN "unit"."active" IS 'TRUE means new issues can be created in units of this area';
355 COMMENT ON COLUMN "unit"."member_count" IS 'Count of members as determined by column "voting_right" in table "privilege"';
358 CREATE TABLE "area" (
359 "id" SERIAL4 PRIMARY KEY,
360 "unit_id" INT4 NOT NULL REFERENCES "unit" ("id") ON DELETE CASCADE ON UPDATE CASCADE,
361 "active" BOOLEAN NOT NULL DEFAULT TRUE,
362 "name" TEXT NOT NULL,
363 "description" TEXT NOT NULL DEFAULT '',
364 "direct_member_count" INT4,
365 "member_weight" INT4,
366 "autoreject_weight" INT4,
367 "text_search_data" TSVECTOR );
368 CREATE INDEX "area_unit_id_idx" ON "area" ("unit_id");
369 CREATE INDEX "area_active_idx" ON "area" ("active");
370 CREATE INDEX "area_text_search_data_idx" ON "area" USING gin ("text_search_data");
371 CREATE TRIGGER "update_text_search_data"
372 BEFORE INSERT OR UPDATE ON "area"
373 FOR EACH ROW EXECUTE PROCEDURE
374 tsvector_update_trigger('text_search_data', 'pg_catalog.simple',
375 "name", "description" );
377 COMMENT ON TABLE "area" IS 'Subject areas';
379 COMMENT ON COLUMN "area"."active" IS 'TRUE means new issues can be created in this area';
380 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"';
381 COMMENT ON COLUMN "area"."member_weight" IS 'Same as "direct_member_count" but respecting delegations';
382 COMMENT ON COLUMN "area"."autoreject_weight" IS 'Sum of weight of members using the autoreject feature';
385 CREATE TABLE "area_setting" (
386 PRIMARY KEY ("member_id", "key", "area_id"),
387 "member_id" INT4 REFERENCES "member" ("id") ON DELETE CASCADE ON UPDATE CASCADE,
388 "key" TEXT NOT NULL,
389 "area_id" INT4 REFERENCES "area" ("id") ON DELETE CASCADE ON UPDATE CASCADE,
390 "value" TEXT NOT NULL );
392 COMMENT ON TABLE "area_setting" IS 'Place for frontend to store area specific settings of members as strings';
395 CREATE TABLE "allowed_policy" (
396 PRIMARY KEY ("area_id", "policy_id"),
397 "area_id" INT4 REFERENCES "area" ("id") ON DELETE CASCADE ON UPDATE CASCADE,
398 "policy_id" INT4 NOT NULL REFERENCES "policy" ("id") ON DELETE CASCADE ON UPDATE CASCADE,
399 "default_policy" BOOLEAN NOT NULL DEFAULT FALSE );
400 CREATE UNIQUE INDEX "allowed_policy_one_default_per_area_idx" ON "allowed_policy" ("area_id") WHERE "default_policy";
402 COMMENT ON TABLE "allowed_policy" IS 'Selects which policies can be used in each area';
404 COMMENT ON COLUMN "allowed_policy"."default_policy" IS 'One policy per area can be set as default.';
407 CREATE TYPE "snapshot_event" AS ENUM ('periodic', 'end_of_admission', 'half_freeze', 'full_freeze');
409 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';
412 CREATE TYPE "issue_state" AS ENUM (
413 'admission', 'discussion', 'verification', 'voting',
414 'canceled_revoked_before_accepted',
415 'canceled_issue_not_accepted',
416 'canceled_after_revocation_during_discussion',
417 'canceled_after_revocation_during_verification',
418 'calculation',
419 'canceled_no_initiative_admitted',
420 'finished_without_winner', 'finished_with_winner');
422 COMMENT ON TYPE "issue_state" IS 'State of issues';
425 CREATE TABLE "issue" (
426 "id" SERIAL4 PRIMARY KEY,
427 "area_id" INT4 NOT NULL REFERENCES "area" ("id") ON DELETE CASCADE ON UPDATE CASCADE,
428 "policy_id" INT4 NOT NULL REFERENCES "policy" ("id") ON DELETE RESTRICT ON UPDATE CASCADE,
429 "state" "issue_state" NOT NULL DEFAULT 'admission',
430 "created" TIMESTAMPTZ NOT NULL DEFAULT now(),
431 "accepted" TIMESTAMPTZ,
432 "half_frozen" TIMESTAMPTZ,
433 "fully_frozen" TIMESTAMPTZ,
434 "closed" TIMESTAMPTZ,
435 "ranks_available" BOOLEAN NOT NULL DEFAULT FALSE,
436 "cleaned" TIMESTAMPTZ,
437 "admission_time" INTERVAL NOT NULL,
438 "discussion_time" INTERVAL NOT NULL,
439 "verification_time" INTERVAL NOT NULL,
440 "voting_time" INTERVAL NOT NULL,
441 "snapshot" TIMESTAMPTZ,
442 "latest_snapshot_event" "snapshot_event",
443 "population" INT4,
444 "vote_now" INT4,
445 "vote_later" INT4,
446 "voter_count" INT4,
447 CONSTRAINT "valid_state" CHECK ((
448 ("accepted" ISNULL AND "half_frozen" ISNULL AND "fully_frozen" ISNULL AND "closed" ISNULL AND "ranks_available" = FALSE) OR
449 ("accepted" ISNULL AND "half_frozen" ISNULL AND "fully_frozen" ISNULL AND "closed" NOTNULL AND "ranks_available" = FALSE) OR
450 ("accepted" NOTNULL AND "half_frozen" ISNULL AND "fully_frozen" ISNULL AND "closed" ISNULL AND "ranks_available" = FALSE) OR
451 ("accepted" NOTNULL AND "half_frozen" ISNULL AND "fully_frozen" ISNULL AND "closed" NOTNULL AND "ranks_available" = FALSE) OR
452 ("accepted" NOTNULL AND "half_frozen" NOTNULL AND "fully_frozen" ISNULL AND "closed" ISNULL AND "ranks_available" = FALSE) OR
453 ("accepted" NOTNULL AND "half_frozen" NOTNULL AND "fully_frozen" ISNULL AND "closed" NOTNULL AND "ranks_available" = FALSE) OR
454 ("accepted" NOTNULL AND "half_frozen" NOTNULL AND "fully_frozen" NOTNULL AND "closed" ISNULL AND "ranks_available" = FALSE) OR
455 ("accepted" NOTNULL AND "half_frozen" NOTNULL AND "fully_frozen" NOTNULL AND "closed" NOTNULL AND "ranks_available" = FALSE) OR
456 ("accepted" NOTNULL AND "half_frozen" NOTNULL AND "fully_frozen" NOTNULL AND "closed" NOTNULL AND "ranks_available" = TRUE)) AND (
457 ("state" = 'admission' AND "closed" ISNULL AND "accepted" ISNULL) OR
458 ("state" = 'discussion' AND "closed" ISNULL AND "accepted" NOTNULL AND "half_frozen" ISNULL) OR
459 ("state" = 'verification' AND "closed" ISNULL AND "half_frozen" NOTNULL AND "fully_frozen" ISNULL) OR
460 ("state" = 'voting' AND "closed" ISNULL AND "fully_frozen" NOTNULL) OR
461 ("state" = 'canceled_revoked_before_accepted' AND "closed" NOTNULL AND "accepted" ISNULL) OR
462 ("state" = 'canceled_issue_not_accepted' AND "closed" NOTNULL AND "accepted" ISNULL) OR
463 ("state" = 'canceled_after_revocation_during_discussion' AND "closed" NOTNULL AND "half_frozen" ISNULL) OR
464 ("state" = 'canceled_after_revocation_during_verification' AND "closed" NOTNULL AND "fully_frozen" ISNULL) OR
465 ("state" = 'calculation' AND "closed" NOTNULL AND "fully_frozen" NOTNULL AND "ranks_available" = FALSE) OR
466 ("state" = 'canceled_no_initiative_admitted' AND "closed" NOTNULL AND "fully_frozen" NOTNULL AND "ranks_available" = TRUE) OR
467 ("state" = 'finished_without_winner' AND "closed" NOTNULL AND "fully_frozen" NOTNULL AND "ranks_available" = TRUE) OR
468 ("state" = 'finished_with_winner' AND "closed" NOTNULL AND "fully_frozen" NOTNULL AND "ranks_available" = TRUE)
469 )),
470 CONSTRAINT "state_change_order" CHECK (
471 "created" <= "accepted" AND
472 "accepted" <= "half_frozen" AND
473 "half_frozen" <= "fully_frozen" AND
474 "fully_frozen" <= "closed" ),
475 CONSTRAINT "only_closed_issues_may_be_cleaned" CHECK (
476 "cleaned" ISNULL OR "closed" NOTNULL ),
477 CONSTRAINT "last_snapshot_on_full_freeze"
478 CHECK ("snapshot" = "fully_frozen"), -- NOTE: snapshot can be set, while frozen is NULL yet
479 CONSTRAINT "freeze_requires_snapshot"
480 CHECK ("fully_frozen" ISNULL OR "snapshot" NOTNULL),
481 CONSTRAINT "set_both_or_none_of_snapshot_and_latest_snapshot_event"
482 CHECK ("snapshot" NOTNULL = "latest_snapshot_event" NOTNULL) );
483 CREATE INDEX "issue_area_id_idx" ON "issue" ("area_id");
484 CREATE INDEX "issue_policy_id_idx" ON "issue" ("policy_id");
485 CREATE INDEX "issue_created_idx" ON "issue" ("created");
486 CREATE INDEX "issue_accepted_idx" ON "issue" ("accepted");
487 CREATE INDEX "issue_half_frozen_idx" ON "issue" ("half_frozen");
488 CREATE INDEX "issue_fully_frozen_idx" ON "issue" ("fully_frozen");
489 CREATE INDEX "issue_closed_idx" ON "issue" ("closed");
490 CREATE INDEX "issue_created_idx_open" ON "issue" ("created") WHERE "closed" ISNULL;
491 CREATE INDEX "issue_closed_idx_canceled" ON "issue" ("closed") WHERE "fully_frozen" ISNULL;
493 COMMENT ON TABLE "issue" IS 'Groups of initiatives';
495 COMMENT ON COLUMN "issue"."accepted" IS 'Point in time, when one initiative of issue reached the "issue_quorum"';
496 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.';
497 COMMENT ON COLUMN "issue"."fully_frozen" IS 'Point in time, when "verification_time" has elapsed and voting has started; 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.';
498 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.';
499 COMMENT ON COLUMN "issue"."ranks_available" IS 'TRUE = ranks have been calculated';
500 COMMENT ON COLUMN "issue"."cleaned" IS 'Point in time, when discussion data and votes had been deleted';
501 COMMENT ON COLUMN "issue"."admission_time" IS 'Copied from "policy" table at creation of issue';
502 COMMENT ON COLUMN "issue"."discussion_time" IS 'Copied from "policy" table at creation of issue';
503 COMMENT ON COLUMN "issue"."verification_time" IS 'Copied from "policy" table at creation of issue';
504 COMMENT ON COLUMN "issue"."voting_time" IS 'Copied from "policy" table at creation of issue';
505 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';
506 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';
507 COMMENT ON COLUMN "issue"."population" IS 'Sum of "weight" column in table "direct_population_snapshot"';
508 COMMENT ON COLUMN "issue"."vote_now" IS 'Number of votes in favor of voting now, as calculated from table "direct_interest_snapshot"';
509 COMMENT ON COLUMN "issue"."vote_later" IS 'Number of votes against voting now, as calculated from table "direct_interest_snapshot"';
510 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';
513 CREATE TABLE "issue_setting" (
514 PRIMARY KEY ("member_id", "key", "issue_id"),
515 "member_id" INT4 REFERENCES "member" ("id") ON DELETE CASCADE ON UPDATE CASCADE,
516 "key" TEXT NOT NULL,
517 "issue_id" INT4 REFERENCES "issue" ("id") ON DELETE CASCADE ON UPDATE CASCADE,
518 "value" TEXT NOT NULL );
520 COMMENT ON TABLE "issue_setting" IS 'Place for frontend to store issue specific settings of members as strings';
523 CREATE TABLE "initiative" (
524 UNIQUE ("issue_id", "id"), -- index needed for foreign-key on table "vote"
525 "issue_id" INT4 NOT NULL REFERENCES "issue" ("id") ON DELETE CASCADE ON UPDATE CASCADE,
526 "id" SERIAL4 PRIMARY KEY,
527 "name" TEXT NOT NULL,
528 "discussion_url" TEXT,
529 "created" TIMESTAMPTZ NOT NULL DEFAULT now(),
530 "revoked" TIMESTAMPTZ,
531 "revoked_by_member_id" INT4 REFERENCES "member" ("id") ON DELETE RESTRICT ON UPDATE CASCADE,
532 "suggested_initiative_id" INT4 REFERENCES "initiative" ("id") ON DELETE CASCADE ON UPDATE CASCADE,
533 "admitted" BOOLEAN,
534 "supporter_count" INT4,
535 "informed_supporter_count" INT4,
536 "satisfied_supporter_count" INT4,
537 "satisfied_informed_supporter_count" INT4,
538 "positive_votes" INT4,
539 "negative_votes" INT4,
540 "attainable" BOOLEAN,
541 "favored" BOOLEAN,
542 "unfavored" BOOLEAN,
543 "preliminary_rank" INT4,
544 "final_rank" INT4,
545 "disqualified" BOOLEAN,
546 "winner" BOOLEAN,
547 "text_search_data" TSVECTOR,
548 CONSTRAINT "all_or_none_of_revoked_and_revoked_by_member_id_must_be_null"
549 CHECK ("revoked" NOTNULL = "revoked_by_member_id" NOTNULL),
550 CONSTRAINT "non_revoked_initiatives_cant_suggest_other"
551 CHECK ("revoked" NOTNULL OR "suggested_initiative_id" ISNULL),
552 CONSTRAINT "revoked_initiatives_cant_be_admitted"
553 CHECK ("revoked" ISNULL OR "admitted" ISNULL),
554 CONSTRAINT "non_admitted_initiatives_cant_contain_voting_results" CHECK (
555 ( "admitted" NOTNULL AND "admitted" = TRUE ) OR
556 ( "positive_votes" ISNULL AND "negative_votes" ISNULL AND
557 "attainable" ISNULL AND "favored" ISNULL AND "unfavored" ISNULL AND
558 "disqualified" ISNULL AND "preliminary_rank" ISNULL AND
559 "final_rank" ISNULL AND "winner" ISNULL ) ),
560 CONSTRAINT "favored_excludes_unfavored" CHECK (NOT ("favored" AND "unfavored")) );
561 CREATE INDEX "initiative_created_idx" ON "initiative" ("created");
562 CREATE INDEX "initiative_revoked_idx" ON "initiative" ("revoked");
563 CREATE INDEX "initiative_text_search_data_idx" ON "initiative" USING gin ("text_search_data");
564 CREATE TRIGGER "update_text_search_data"
565 BEFORE INSERT OR UPDATE ON "initiative"
566 FOR EACH ROW EXECUTE PROCEDURE
567 tsvector_update_trigger('text_search_data', 'pg_catalog.simple',
568 "name", "discussion_url");
570 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.';
572 COMMENT ON COLUMN "initiative"."discussion_url" IS 'URL pointing to a discussion platform for this initiative';
573 COMMENT ON COLUMN "initiative"."revoked" IS 'Point in time, when one initiator decided to revoke the initiative';
574 COMMENT ON COLUMN "initiative"."revoked_by_member_id" IS 'Member, who decided to revoked the initiative';
575 COMMENT ON COLUMN "initiative"."admitted" IS 'TRUE, if initiative reaches the "initiative_quorum" when freezing the issue';
576 COMMENT ON COLUMN "initiative"."supporter_count" IS 'Calculated from table "direct_supporter_snapshot"';
577 COMMENT ON COLUMN "initiative"."informed_supporter_count" IS 'Calculated from table "direct_supporter_snapshot"';
578 COMMENT ON COLUMN "initiative"."satisfied_supporter_count" IS 'Calculated from table "direct_supporter_snapshot"';
579 COMMENT ON COLUMN "initiative"."satisfied_informed_supporter_count" IS 'Calculated from table "direct_supporter_snapshot"';
580 COMMENT ON COLUMN "initiative"."positive_votes" IS 'Calculated from table "direct_voter"';
581 COMMENT ON COLUMN "initiative"."negative_votes" IS 'Calculated from table "direct_voter"';
582 COMMENT ON COLUMN "initiative"."attainable" IS 'TRUE, if "positive_votes"/("positive_votes"+"negative_votes") is strictly greater or greater-equal than "majority_num"/"majority_den"';
583 COMMENT ON COLUMN "initiative"."favored" IS 'TRUE, if initiative has a schulze-ranking better than the status quo (without tie-breaking)';
584 COMMENT ON COLUMN "initiative"."unfavored" IS 'TRUE, if initiative has a schulze-ranking worse than the status quo (without tie-breaking)';
585 COMMENT ON COLUMN "initiative"."preliminary_rank" IS 'Schulze-Ranking without tie-breaking';
586 COMMENT ON COLUMN "initiative"."final_rank" IS 'Schulze-Ranking after tie-breaking';
587 COMMENT ON COLUMN "initiative"."disqualified" IS 'TRUE, if initiative may not win, because it is directly beaten with a simple majority by a better ranked initiative or by a better ranked status quo (without tie-breaking)';
588 COMMENT ON COLUMN "initiative"."winner" IS 'TRUE, if initiative is final winner (best ranked initiative being "attainable", "favored", and not "disqualified")';
591 CREATE TABLE "battle" (
592 "issue_id" INT4 NOT NULL,
593 "winning_initiative_id" INT4,
594 FOREIGN KEY ("issue_id", "winning_initiative_id") REFERENCES "initiative" ("issue_id", "id") ON DELETE CASCADE ON UPDATE CASCADE,
595 "losing_initiative_id" INT4,
596 FOREIGN KEY ("issue_id", "losing_initiative_id") REFERENCES "initiative" ("issue_id", "id") ON DELETE CASCADE ON UPDATE CASCADE,
597 "count" INT4 NOT NULL,
598 CONSTRAINT "initiative_ids_not_equal" CHECK (
599 "winning_initiative_id" != "losing_initiative_id" OR
600 ( ("winning_initiative_id" NOTNULL AND "losing_initiative_id" ISNULL) OR
601 ("winning_initiative_id" ISNULL AND "losing_initiative_id" NOTNULL) ) ) );
602 CREATE UNIQUE INDEX "battle_winning_losing_idx" ON "battle" ("issue_id", "winning_initiative_id", "losing_initiative_id");
603 CREATE UNIQUE INDEX "battle_winning_null_idx" ON "battle" ("issue_id", "winning_initiative_id") WHERE "losing_initiative_id" ISNULL;
604 CREATE UNIQUE INDEX "battle_null_losing_idx" ON "battle" ("issue_id", "losing_initiative_id") WHERE "winning_initiative_id" ISNULL;
606 COMMENT ON TABLE "battle" IS 'Number of members preferring one initiative to another; Filled by "battle_view" when closing an issue; NULL as initiative_id denotes virtual "status-quo" initiative';
609 CREATE TABLE "ignored_initiative" (
610 PRIMARY KEY ("initiative_id", "member_id"),
611 "initiative_id" INT4 REFERENCES "initiative" ("id") ON DELETE CASCADE ON UPDATE CASCADE,
612 "member_id" INT4 REFERENCES "member" ("id") ON DELETE CASCADE ON UPDATE CASCADE );
613 CREATE INDEX "ignored_initiative_member_id_idx" ON "ignored_initiative" ("member_id");
615 COMMENT ON TABLE "ignored_initiative" IS 'Possibility to filter initiatives';
618 CREATE TABLE "initiative_setting" (
619 PRIMARY KEY ("member_id", "key", "initiative_id"),
620 "member_id" INT4 REFERENCES "member" ("id") ON DELETE CASCADE ON UPDATE CASCADE,
621 "key" TEXT NOT NULL,
622 "initiative_id" INT4 REFERENCES "initiative" ("id") ON DELETE CASCADE ON UPDATE CASCADE,
623 "value" TEXT NOT NULL );
625 COMMENT ON TABLE "initiative_setting" IS 'Place for frontend to store initiative specific settings of members as strings';
628 CREATE TABLE "draft" (
629 UNIQUE ("initiative_id", "id"), -- index needed for foreign-key on table "supporter"
630 "initiative_id" INT4 NOT NULL REFERENCES "initiative" ("id") ON DELETE CASCADE ON UPDATE CASCADE,
631 "id" SERIAL8 PRIMARY KEY,
632 "created" TIMESTAMPTZ NOT NULL DEFAULT now(),
633 "author_id" INT4 NOT NULL REFERENCES "member" ("id") ON DELETE RESTRICT ON UPDATE CASCADE,
634 "formatting_engine" TEXT,
635 "content" TEXT NOT NULL,
636 "text_search_data" TSVECTOR );
637 CREATE INDEX "draft_created_idx" ON "draft" ("created");
638 CREATE INDEX "draft_author_id_created_idx" ON "draft" ("author_id", "created");
639 CREATE INDEX "draft_text_search_data_idx" ON "draft" USING gin ("text_search_data");
640 CREATE TRIGGER "update_text_search_data"
641 BEFORE INSERT OR UPDATE ON "draft"
642 FOR EACH ROW EXECUTE PROCEDURE
643 tsvector_update_trigger('text_search_data', 'pg_catalog.simple', "content");
645 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.';
647 COMMENT ON COLUMN "draft"."formatting_engine" IS 'Allows different formatting engines (i.e. wiki formats) to be used';
648 COMMENT ON COLUMN "draft"."content" IS 'Text of the draft in a format depending on the field "formatting_engine"';
651 CREATE TABLE "rendered_draft" (
652 PRIMARY KEY ("draft_id", "format"),
653 "draft_id" INT8 REFERENCES "draft" ("id") ON DELETE CASCADE ON UPDATE CASCADE,
654 "format" TEXT,
655 "content" TEXT NOT NULL );
657 COMMENT ON TABLE "rendered_draft" IS 'This table may be used by frontends to cache "rendered" drafts (e.g. HTML output generated from wiki text)';
660 CREATE TABLE "suggestion" (
661 UNIQUE ("initiative_id", "id"), -- index needed for foreign-key on table "opinion"
662 "initiative_id" INT4 NOT NULL REFERENCES "initiative" ("id") ON DELETE CASCADE ON UPDATE CASCADE,
663 "id" SERIAL8 PRIMARY KEY,
664 "created" TIMESTAMPTZ NOT NULL DEFAULT now(),
665 "author_id" INT4 NOT NULL REFERENCES "member" ("id") ON DELETE RESTRICT ON UPDATE CASCADE,
666 "name" TEXT NOT NULL,
667 "description" TEXT NOT NULL DEFAULT '',
668 "text_search_data" TSVECTOR,
669 "minus2_unfulfilled_count" INT4,
670 "minus2_fulfilled_count" INT4,
671 "minus1_unfulfilled_count" INT4,
672 "minus1_fulfilled_count" INT4,
673 "plus1_unfulfilled_count" INT4,
674 "plus1_fulfilled_count" INT4,
675 "plus2_unfulfilled_count" INT4,
676 "plus2_fulfilled_count" INT4 );
677 CREATE INDEX "suggestion_created_idx" ON "suggestion" ("created");
678 CREATE INDEX "suggestion_author_id_created_idx" ON "suggestion" ("author_id", "created");
679 CREATE INDEX "suggestion_text_search_data_idx" ON "suggestion" USING gin ("text_search_data");
680 CREATE TRIGGER "update_text_search_data"
681 BEFORE INSERT OR UPDATE ON "suggestion"
682 FOR EACH ROW EXECUTE PROCEDURE
683 tsvector_update_trigger('text_search_data', 'pg_catalog.simple',
684 "name", "description");
686 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';
688 COMMENT ON COLUMN "suggestion"."minus2_unfulfilled_count" IS 'Calculated from table "direct_supporter_snapshot", not requiring informed supporters';
689 COMMENT ON COLUMN "suggestion"."minus2_fulfilled_count" IS 'Calculated from table "direct_supporter_snapshot", not requiring informed supporters';
690 COMMENT ON COLUMN "suggestion"."minus1_unfulfilled_count" IS 'Calculated from table "direct_supporter_snapshot", not requiring informed supporters';
691 COMMENT ON COLUMN "suggestion"."minus1_fulfilled_count" IS 'Calculated from table "direct_supporter_snapshot", not requiring informed supporters';
692 COMMENT ON COLUMN "suggestion"."plus1_unfulfilled_count" IS 'Calculated from table "direct_supporter_snapshot", not requiring informed supporters';
693 COMMENT ON COLUMN "suggestion"."plus1_fulfilled_count" IS 'Calculated from table "direct_supporter_snapshot", not requiring informed supporters';
694 COMMENT ON COLUMN "suggestion"."plus2_unfulfilled_count" IS 'Calculated from table "direct_supporter_snapshot", not requiring informed supporters';
695 COMMENT ON COLUMN "suggestion"."plus2_fulfilled_count" IS 'Calculated from table "direct_supporter_snapshot", not requiring informed supporters';
698 CREATE TABLE "suggestion_setting" (
699 PRIMARY KEY ("member_id", "key", "suggestion_id"),
700 "member_id" INT4 REFERENCES "member" ("id") ON DELETE CASCADE ON UPDATE CASCADE,
701 "key" TEXT NOT NULL,
702 "suggestion_id" INT8 REFERENCES "suggestion" ("id") ON DELETE CASCADE ON UPDATE CASCADE,
703 "value" TEXT NOT NULL );
705 COMMENT ON TABLE "suggestion_setting" IS 'Place for frontend to store suggestion specific settings of members as strings';
708 CREATE TABLE "invite_code_unit" (
709 PRIMARY KEY ("invite_code_id", "unit_id"),
710 "invite_code_id" INT8 REFERENCES "invite_code" ("id") ON DELETE CASCADE ON UPDATE CASCADE,
711 "unit_id" INT4 REFERENCES "unit" ("id") ON DELETE CASCADE ON UPDATE CASCADE );
713 COMMENT ON TABLE "invite_code_unit" IS 'Units where accounts created with a given invite codes get voting rights';
716 CREATE TABLE "privilege" (
717 PRIMARY KEY ("unit_id", "member_id"),
718 "unit_id" INT4 REFERENCES "unit" ("id") ON DELETE CASCADE ON UPDATE CASCADE,
719 "member_id" INT4 REFERENCES "member" ("id") ON DELETE CASCADE ON UPDATE CASCADE,
720 "admin_manager" BOOLEAN NOT NULL DEFAULT FALSE,
721 "unit_manager" BOOLEAN NOT NULL DEFAULT FALSE,
722 "area_manager" BOOLEAN NOT NULL DEFAULT FALSE,
723 "voting_right_manager" BOOLEAN NOT NULL DEFAULT FALSE,
724 "voting_right" BOOLEAN NOT NULL DEFAULT TRUE );
726 COMMENT ON TABLE "privilege" IS 'Members rights related to each unit';
728 COMMENT ON COLUMN "privilege"."admin_manager" IS 'Grant/revoke admin privileges to/from other users';
729 COMMENT ON COLUMN "privilege"."unit_manager" IS 'Create or lock sub units';
730 COMMENT ON COLUMN "privilege"."area_manager" IS 'Create or lock areas and set area parameters';
731 COMMENT ON COLUMN "privilege"."voting_right_manager" IS 'Select which members are allowed to discuss and vote inside the unit';
732 COMMENT ON COLUMN "privilege"."voting_right" IS 'Right to discuss and vote';
735 CREATE TABLE "membership" (
736 PRIMARY KEY ("area_id", "member_id"),
737 "area_id" INT4 REFERENCES "area" ("id") ON DELETE CASCADE ON UPDATE CASCADE,
738 "member_id" INT4 REFERENCES "member" ("id") ON DELETE CASCADE ON UPDATE CASCADE,
739 "autoreject" BOOLEAN NOT NULL DEFAULT FALSE );
740 CREATE INDEX "membership_member_id_idx" ON "membership" ("member_id");
742 COMMENT ON TABLE "membership" IS 'Interest of members in topic areas';
744 COMMENT ON COLUMN "membership"."autoreject" IS 'TRUE = member votes against all initiatives, if he is neither direct_ or delegating_voter; Entries in the "interest" table can override this setting.';
747 CREATE TABLE "interest" (
748 PRIMARY KEY ("issue_id", "member_id"),
749 "issue_id" INT4 REFERENCES "issue" ("id") ON DELETE CASCADE ON UPDATE CASCADE,
750 "member_id" INT4 REFERENCES "member" ("id") ON DELETE CASCADE ON UPDATE CASCADE,
751 "autoreject" BOOLEAN,
752 "voting_requested" BOOLEAN );
753 CREATE INDEX "interest_member_id_idx" ON "interest" ("member_id");
755 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.';
757 COMMENT ON COLUMN "interest"."autoreject" IS 'TRUE = member votes against all initiatives in case of not explicitly taking part in the voting procedure';
758 COMMENT ON COLUMN "interest"."voting_requested" IS 'TRUE = member wants to vote now, FALSE = member wants to vote later, NULL = policy rules should apply';
761 CREATE TABLE "initiator" (
762 PRIMARY KEY ("initiative_id", "member_id"),
763 "initiative_id" INT4 REFERENCES "initiative" ("id") ON DELETE CASCADE ON UPDATE CASCADE,
764 "member_id" INT4 REFERENCES "member" ("id") ON DELETE CASCADE ON UPDATE CASCADE,
765 "accepted" BOOLEAN );
766 CREATE INDEX "initiator_member_id_idx" ON "initiator" ("member_id");
768 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.';
770 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.';
773 CREATE TABLE "supporter" (
774 "issue_id" INT4 NOT NULL,
775 PRIMARY KEY ("initiative_id", "member_id"),
776 "initiative_id" INT4,
777 "member_id" INT4,
778 "draft_id" INT8 NOT NULL,
779 FOREIGN KEY ("issue_id", "member_id") REFERENCES "interest" ("issue_id", "member_id") ON DELETE CASCADE ON UPDATE CASCADE,
780 FOREIGN KEY ("initiative_id", "draft_id") REFERENCES "draft" ("initiative_id", "id") ON DELETE CASCADE ON UPDATE CASCADE );
781 CREATE INDEX "supporter_member_id_idx" ON "supporter" ("member_id");
783 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.';
785 COMMENT ON COLUMN "supporter"."draft_id" IS 'Latest seen draft, defaults to current draft of the initiative (implemented by trigger "default_for_draft_id")';
788 CREATE TABLE "opinion" (
789 "initiative_id" INT4 NOT NULL,
790 PRIMARY KEY ("suggestion_id", "member_id"),
791 "suggestion_id" INT8,
792 "member_id" INT4,
793 "degree" INT2 NOT NULL CHECK ("degree" >= -2 AND "degree" <= 2 AND "degree" != 0),
794 "fulfilled" BOOLEAN NOT NULL DEFAULT FALSE,
795 FOREIGN KEY ("initiative_id", "suggestion_id") REFERENCES "suggestion" ("initiative_id", "id") ON DELETE CASCADE ON UPDATE CASCADE,
796 FOREIGN KEY ("initiative_id", "member_id") REFERENCES "supporter" ("initiative_id", "member_id") ON DELETE CASCADE ON UPDATE CASCADE );
797 CREATE INDEX "opinion_member_id_initiative_id_idx" ON "opinion" ("member_id", "initiative_id");
799 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.';
801 COMMENT ON COLUMN "opinion"."degree" IS '2 = fulfillment required for support; 1 = fulfillment desired; -1 = fulfillment unwanted; -2 = fulfillment cancels support';
804 CREATE TYPE "delegation_scope" AS ENUM ('unit', 'area', 'issue');
806 COMMENT ON TYPE "delegation_scope" IS 'Scope for delegations: ''unit'', ''area'', or ''issue'' (order is relevant)';
809 CREATE TABLE "delegation" (
810 "id" SERIAL8 PRIMARY KEY,
811 "truster_id" INT4 NOT NULL REFERENCES "member" ("id") ON DELETE CASCADE ON UPDATE CASCADE,
812 "trustee_id" INT4 REFERENCES "member" ("id") ON DELETE CASCADE ON UPDATE CASCADE,
813 "scope" "delegation_scope" NOT NULL,
814 "unit_id" INT4 REFERENCES "unit" ("id") ON DELETE CASCADE ON UPDATE CASCADE,
815 "area_id" INT4 REFERENCES "area" ("id") ON DELETE CASCADE ON UPDATE CASCADE,
816 "issue_id" INT4 REFERENCES "issue" ("id") ON DELETE CASCADE ON UPDATE CASCADE,
817 CONSTRAINT "cant_delegate_to_yourself" CHECK ("truster_id" != "trustee_id"),
818 CONSTRAINT "no_unit_delegation_to_null"
819 CHECK ("trustee_id" NOTNULL OR "scope" != 'unit'),
820 CONSTRAINT "area_id_and_issue_id_set_according_to_scope" CHECK (
821 ("scope" = 'unit' AND "unit_id" NOTNULL AND "area_id" ISNULL AND "issue_id" ISNULL ) OR
822 ("scope" = 'area' AND "unit_id" ISNULL AND "area_id" NOTNULL AND "issue_id" ISNULL ) OR
823 ("scope" = 'issue' AND "unit_id" ISNULL AND "area_id" ISNULL AND "issue_id" NOTNULL) ),
824 UNIQUE ("unit_id", "truster_id"),
825 UNIQUE ("area_id", "truster_id"),
826 UNIQUE ("issue_id", "truster_id") );
827 CREATE INDEX "delegation_truster_id_idx" ON "delegation" ("truster_id");
828 CREATE INDEX "delegation_trustee_id_idx" ON "delegation" ("trustee_id");
830 COMMENT ON TABLE "delegation" IS 'Delegation of vote-weight to other members';
832 COMMENT ON COLUMN "delegation"."unit_id" IS 'Reference to unit, if delegation is unit-wide, otherwise NULL';
833 COMMENT ON COLUMN "delegation"."area_id" IS 'Reference to area, if delegation is area-wide, otherwise NULL';
834 COMMENT ON COLUMN "delegation"."issue_id" IS 'Reference to issue, if delegation is issue-wide, otherwise NULL';
837 CREATE TABLE "direct_population_snapshot" (
838 PRIMARY KEY ("issue_id", "event", "member_id"),
839 "issue_id" INT4 REFERENCES "issue" ("id") ON DELETE CASCADE ON UPDATE CASCADE,
840 "event" "snapshot_event",
841 "member_id" INT4 REFERENCES "member" ("id") ON DELETE RESTRICT ON UPDATE RESTRICT,
842 "weight" INT4 );
843 CREATE INDEX "direct_population_snapshot_member_id_idx" ON "direct_population_snapshot" ("member_id");
845 COMMENT ON TABLE "direct_population_snapshot" IS 'Snapshot of active members having either a "membership" in the "area" or an "interest" in the "issue"';
847 COMMENT ON COLUMN "direct_population_snapshot"."event" IS 'Reason for snapshot, see "snapshot_event" type for details';
848 COMMENT ON COLUMN "direct_population_snapshot"."weight" IS 'Weight of member (1 or higher) according to "delegating_population_snapshot"';
851 CREATE TABLE "delegating_population_snapshot" (
852 PRIMARY KEY ("issue_id", "event", "member_id"),
853 "issue_id" INT4 REFERENCES "issue" ("id") ON DELETE CASCADE ON UPDATE CASCADE,
854 "event" "snapshot_event",
855 "member_id" INT4 REFERENCES "member" ("id") ON DELETE RESTRICT ON UPDATE RESTRICT,
856 "weight" INT4,
857 "scope" "delegation_scope" NOT NULL,
858 "delegate_member_ids" INT4[] NOT NULL );
859 CREATE INDEX "delegating_population_snapshot_member_id_idx" ON "delegating_population_snapshot" ("member_id");
861 COMMENT ON TABLE "direct_population_snapshot" IS 'Delegations increasing the weight of entries in the "direct_population_snapshot" table';
863 COMMENT ON COLUMN "delegating_population_snapshot"."event" IS 'Reason for snapshot, see "snapshot_event" type for details';
864 COMMENT ON COLUMN "delegating_population_snapshot"."member_id" IS 'Delegating member';
865 COMMENT ON COLUMN "delegating_population_snapshot"."weight" IS 'Intermediate weight';
866 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"';
869 CREATE TABLE "direct_interest_snapshot" (
870 PRIMARY KEY ("issue_id", "event", "member_id"),
871 "issue_id" INT4 REFERENCES "issue" ("id") ON DELETE CASCADE ON UPDATE CASCADE,
872 "event" "snapshot_event",
873 "member_id" INT4 REFERENCES "member" ("id") ON DELETE RESTRICT ON UPDATE RESTRICT,
874 "weight" INT4,
875 "voting_requested" BOOLEAN );
876 CREATE INDEX "direct_interest_snapshot_member_id_idx" ON "direct_interest_snapshot" ("member_id");
878 COMMENT ON TABLE "direct_interest_snapshot" IS 'Snapshot of active members having an "interest" in the "issue"';
880 COMMENT ON COLUMN "direct_interest_snapshot"."event" IS 'Reason for snapshot, see "snapshot_event" type for details';
881 COMMENT ON COLUMN "direct_interest_snapshot"."weight" IS 'Weight of member (1 or higher) according to "delegating_interest_snapshot"';
882 COMMENT ON COLUMN "direct_interest_snapshot"."voting_requested" IS 'Copied from column "voting_requested" of table "interest"';
885 CREATE TABLE "delegating_interest_snapshot" (
886 PRIMARY KEY ("issue_id", "event", "member_id"),
887 "issue_id" INT4 REFERENCES "issue" ("id") ON DELETE CASCADE ON UPDATE CASCADE,
888 "event" "snapshot_event",
889 "member_id" INT4 REFERENCES "member" ("id") ON DELETE RESTRICT ON UPDATE RESTRICT,
890 "weight" INT4,
891 "scope" "delegation_scope" NOT NULL,
892 "delegate_member_ids" INT4[] NOT NULL );
893 CREATE INDEX "delegating_interest_snapshot_member_id_idx" ON "delegating_interest_snapshot" ("member_id");
895 COMMENT ON TABLE "delegating_interest_snapshot" IS 'Delegations increasing the weight of entries in the "direct_interest_snapshot" table';
897 COMMENT ON COLUMN "delegating_interest_snapshot"."event" IS 'Reason for snapshot, see "snapshot_event" type for details';
898 COMMENT ON COLUMN "delegating_interest_snapshot"."member_id" IS 'Delegating member';
899 COMMENT ON COLUMN "delegating_interest_snapshot"."weight" IS 'Intermediate weight';
900 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"';
903 CREATE TABLE "direct_supporter_snapshot" (
904 "issue_id" INT4 NOT NULL,
905 PRIMARY KEY ("initiative_id", "event", "member_id"),
906 "initiative_id" INT4,
907 "event" "snapshot_event",
908 "member_id" INT4 REFERENCES "member" ("id") ON DELETE RESTRICT ON UPDATE RESTRICT,
909 "informed" BOOLEAN NOT NULL,
910 "satisfied" BOOLEAN NOT NULL,
911 FOREIGN KEY ("issue_id", "initiative_id") REFERENCES "initiative" ("issue_id", "id") ON DELETE CASCADE ON UPDATE CASCADE,
912 FOREIGN KEY ("issue_id", "event", "member_id") REFERENCES "direct_interest_snapshot" ("issue_id", "event", "member_id") ON DELETE CASCADE ON UPDATE CASCADE );
913 CREATE INDEX "direct_supporter_snapshot_member_id_idx" ON "direct_supporter_snapshot" ("member_id");
915 COMMENT ON TABLE "direct_supporter_snapshot" IS 'Snapshot of supporters of initiatives (weight is stored in "direct_interest_snapshot")';
917 COMMENT ON COLUMN "direct_supporter_snapshot"."event" IS 'Reason for snapshot, see "snapshot_event" type for details';
918 COMMENT ON COLUMN "direct_supporter_snapshot"."informed" IS 'Supporter has seen the latest draft of the initiative';
919 COMMENT ON COLUMN "direct_supporter_snapshot"."satisfied" IS 'Supporter has no "critical_opinion"s';
922 CREATE TABLE "non_voter" (
923 PRIMARY KEY ("issue_id", "member_id"),
924 "issue_id" INT4 REFERENCES "issue" ("id") ON DELETE CASCADE ON UPDATE CASCADE,
925 "member_id" INT4 REFERENCES "member" ("id") ON DELETE CASCADE ON UPDATE CASCADE );
926 CREATE INDEX "non_voter_member_id_idx" ON "non_voter" ("member_id");
928 COMMENT ON TABLE "non_voter" IS 'Members who decided to not vote directly on an issue';
931 CREATE TABLE "direct_voter" (
932 PRIMARY KEY ("issue_id", "member_id"),
933 "issue_id" INT4 REFERENCES "issue" ("id") ON DELETE CASCADE ON UPDATE CASCADE,
934 "member_id" INT4 REFERENCES "member" ("id") ON DELETE RESTRICT ON UPDATE RESTRICT,
935 "weight" INT4,
936 "autoreject" BOOLEAN NOT NULL DEFAULT FALSE );
937 CREATE INDEX "direct_voter_member_id_idx" ON "direct_voter" ("member_id");
939 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.';
941 COMMENT ON COLUMN "direct_voter"."weight" IS 'Weight of member (1 or higher) according to "delegating_voter" table';
942 COMMENT ON COLUMN "direct_voter"."autoreject" IS 'Votes were inserted due to "autoreject" feature';
945 CREATE TABLE "delegating_voter" (
946 PRIMARY KEY ("issue_id", "member_id"),
947 "issue_id" INT4 REFERENCES "issue" ("id") ON DELETE CASCADE ON UPDATE CASCADE,
948 "member_id" INT4 REFERENCES "member" ("id") ON DELETE RESTRICT ON UPDATE RESTRICT,
949 "weight" INT4,
950 "scope" "delegation_scope" NOT NULL,
951 "delegate_member_ids" INT4[] NOT NULL );
952 CREATE INDEX "delegating_voter_member_id_idx" ON "delegating_voter" ("member_id");
954 COMMENT ON TABLE "delegating_voter" IS 'Delegations increasing the weight of entries in the "direct_voter" table';
956 COMMENT ON COLUMN "delegating_voter"."member_id" IS 'Delegating member';
957 COMMENT ON COLUMN "delegating_voter"."weight" IS 'Intermediate weight';
958 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"';
961 CREATE TABLE "vote" (
962 "issue_id" INT4 NOT NULL,
963 PRIMARY KEY ("initiative_id", "member_id"),
964 "initiative_id" INT4,
965 "member_id" INT4,
966 "grade" INT4,
967 FOREIGN KEY ("issue_id", "initiative_id") REFERENCES "initiative" ("issue_id", "id") ON DELETE CASCADE ON UPDATE CASCADE,
968 FOREIGN KEY ("issue_id", "member_id") REFERENCES "direct_voter" ("issue_id", "member_id") ON DELETE CASCADE ON UPDATE CASCADE );
969 CREATE INDEX "vote_member_id_idx" ON "vote" ("member_id");
971 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.';
973 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.';
976 CREATE TABLE "issue_comment" (
977 PRIMARY KEY ("issue_id", "member_id"),
978 "issue_id" INT4 REFERENCES "issue" ("id") ON DELETE CASCADE ON UPDATE CASCADE,
979 "member_id" INT4 REFERENCES "member" ("id") ON DELETE CASCADE ON UPDATE CASCADE,
980 "changed" TIMESTAMPTZ NOT NULL DEFAULT now(),
981 "formatting_engine" TEXT,
982 "content" TEXT NOT NULL,
983 "text_search_data" TSVECTOR );
984 CREATE INDEX "issue_comment_member_id_idx" ON "issue_comment" ("member_id");
985 CREATE INDEX "issue_comment_text_search_data_idx" ON "issue_comment" USING gin ("text_search_data");
986 CREATE TRIGGER "update_text_search_data"
987 BEFORE INSERT OR UPDATE ON "issue_comment"
988 FOR EACH ROW EXECUTE PROCEDURE
989 tsvector_update_trigger('text_search_data', 'pg_catalog.simple', "content");
991 COMMENT ON TABLE "issue_comment" IS 'Place to store free comments of members related to issues';
993 COMMENT ON COLUMN "issue_comment"."changed" IS 'Time the comment was last changed';
996 CREATE TABLE "rendered_issue_comment" (
997 PRIMARY KEY ("issue_id", "member_id", "format"),
998 FOREIGN KEY ("issue_id", "member_id")
999 REFERENCES "issue_comment" ("issue_id", "member_id")
1000 ON DELETE CASCADE ON UPDATE CASCADE,
1001 "issue_id" INT4,
1002 "member_id" INT4,
1003 "format" TEXT,
1004 "content" TEXT NOT NULL );
1006 COMMENT ON TABLE "rendered_issue_comment" IS 'This table may be used by frontends to cache "rendered" issue comments (e.g. HTML output generated from wiki text)';
1009 CREATE TABLE "voting_comment" (
1010 PRIMARY KEY ("issue_id", "member_id"),
1011 "issue_id" INT4 REFERENCES "issue" ("id") ON DELETE CASCADE ON UPDATE CASCADE,
1012 "member_id" INT4 REFERENCES "member" ("id") ON DELETE CASCADE ON UPDATE CASCADE,
1013 "changed" TIMESTAMPTZ,
1014 "formatting_engine" TEXT,
1015 "content" TEXT NOT NULL,
1016 "text_search_data" TSVECTOR );
1017 CREATE INDEX "voting_comment_member_id_idx" ON "voting_comment" ("member_id");
1018 CREATE INDEX "voting_comment_text_search_data_idx" ON "voting_comment" USING gin ("text_search_data");
1019 CREATE TRIGGER "update_text_search_data"
1020 BEFORE INSERT OR UPDATE ON "voting_comment"
1021 FOR EACH ROW EXECUTE PROCEDURE
1022 tsvector_update_trigger('text_search_data', 'pg_catalog.simple', "content");
1024 COMMENT ON TABLE "voting_comment" IS 'Storage for comments of voters to be published after voting has finished.';
1026 COMMENT ON COLUMN "voting_comment"."changed" IS 'Is to be set or updated by the frontend, if comment was inserted or updated AFTER the issue has been closed. Otherwise it shall be set to NULL.';
1029 CREATE TABLE "rendered_voting_comment" (
1030 PRIMARY KEY ("issue_id", "member_id", "format"),
1031 FOREIGN KEY ("issue_id", "member_id")
1032 REFERENCES "voting_comment" ("issue_id", "member_id")
1033 ON DELETE CASCADE ON UPDATE CASCADE,
1034 "issue_id" INT4,
1035 "member_id" INT4,
1036 "format" TEXT,
1037 "content" TEXT NOT NULL );
1039 COMMENT ON TABLE "rendered_voting_comment" IS 'This table may be used by frontends to cache "rendered" voting comments (e.g. HTML output generated from wiki text)';
1042 CREATE TYPE "event_type" AS ENUM (
1043 'issue_state_changed',
1044 'initiative_created_in_new_issue',
1045 'initiative_created_in_existing_issue',
1046 'initiative_revoked',
1047 'new_draft_created',
1048 'suggestion_created');
1050 COMMENT ON TYPE "event_type" IS 'Type used for column "event" of table "event"';
1053 CREATE TABLE "event" (
1054 "id" SERIAL8 PRIMARY KEY,
1055 "occurrence" TIMESTAMPTZ NOT NULL DEFAULT now(),
1056 "event" "event_type" NOT NULL,
1057 "member_id" INT4 REFERENCES "member" ("id") ON DELETE RESTRICT ON UPDATE CASCADE,
1058 "issue_id" INT4 REFERENCES "issue" ("id") ON DELETE CASCADE ON UPDATE CASCADE,
1059 "state" "issue_state" CHECK ("state" != 'calculation'),
1060 "initiative_id" INT4,
1061 "draft_id" INT8,
1062 "suggestion_id" INT8,
1063 FOREIGN KEY ("issue_id", "initiative_id")
1064 REFERENCES "initiative" ("issue_id", "id")
1065 ON DELETE CASCADE ON UPDATE CASCADE,
1066 FOREIGN KEY ("initiative_id", "draft_id")
1067 REFERENCES "draft" ("initiative_id", "id")
1068 ON DELETE CASCADE ON UPDATE CASCADE,
1069 FOREIGN KEY ("initiative_id", "suggestion_id")
1070 REFERENCES "suggestion" ("initiative_id", "id")
1071 ON DELETE CASCADE ON UPDATE CASCADE,
1072 CONSTRAINT "null_constraints_for_issue_state_changed" CHECK (
1073 "event" != 'issue_state_changed' OR (
1074 "member_id" ISNULL AND
1075 "issue_id" NOTNULL AND
1076 "state" NOTNULL AND
1077 "initiative_id" ISNULL AND
1078 "draft_id" ISNULL AND
1079 "suggestion_id" ISNULL )),
1080 CONSTRAINT "null_constraints_for_initiative_creation_or_revocation_or_new_draft" CHECK (
1081 "event" NOT IN (
1082 'initiative_created_in_new_issue',
1083 'initiative_created_in_existing_issue',
1084 'initiative_revoked',
1085 'new_draft_created'
1086 ) OR (
1087 "member_id" NOTNULL AND
1088 "issue_id" NOTNULL AND
1089 "state" NOTNULL AND
1090 "initiative_id" NOTNULL AND
1091 "draft_id" NOTNULL AND
1092 "suggestion_id" ISNULL )),
1093 CONSTRAINT "null_constraints_for_suggestion_creation" CHECK (
1094 "event" != 'suggestion_created' OR (
1095 "member_id" NOTNULL AND
1096 "issue_id" NOTNULL AND
1097 "state" NOTNULL AND
1098 "initiative_id" NOTNULL AND
1099 "draft_id" ISNULL AND
1100 "suggestion_id" NOTNULL )) );
1102 COMMENT ON TABLE "event" IS 'Event table, automatically filled by triggers';
1104 COMMENT ON COLUMN "event"."occurrence" IS 'Point in time, when event occurred';
1105 COMMENT ON COLUMN "event"."event" IS 'Type of event (see TYPE "event_type")';
1106 COMMENT ON COLUMN "event"."member_id" IS 'Member who caused the event, if applicable';
1107 COMMENT ON COLUMN "event"."state" IS 'If issue_id is set: state of affected issue; If state changed: new state';
1111 ----------------------------------------------
1112 -- Writing of history entries and event log --
1113 ----------------------------------------------
1115 CREATE FUNCTION "write_member_history_trigger"()
1116 RETURNS TRIGGER
1117 LANGUAGE 'plpgsql' VOLATILE AS $$
1118 BEGIN
1119 IF
1120 NEW."active" != OLD."active" OR
1121 NEW."name" != OLD."name"
1122 THEN
1123 INSERT INTO "member_history"
1124 ("member_id", "active", "name")
1125 VALUES (NEW."id", OLD."active", OLD."name");
1126 END IF;
1127 RETURN NULL;
1128 END;
1129 $$;
1131 CREATE TRIGGER "write_member_history"
1132 AFTER UPDATE ON "member" FOR EACH ROW EXECUTE PROCEDURE
1133 "write_member_history_trigger"();
1135 COMMENT ON FUNCTION "write_member_history_trigger"() IS 'Implementation of trigger "write_member_history" on table "member"';
1136 COMMENT ON TRIGGER "write_member_history" ON "member" IS 'When changing certain fields of a member, create a history entry in "member_history" table';
1139 CREATE FUNCTION "write_event_issue_state_changed_trigger"()
1140 RETURNS TRIGGER
1141 LANGUAGE 'plpgsql' VOLATILE AS $$
1142 BEGIN
1143 IF NEW."state" != OLD."state" AND NEW."state" != 'calculation' THEN
1144 INSERT INTO "event" ("event", "issue_id", "state")
1145 VALUES ('issue_state_changed', NEW."id", NEW."state");
1146 END IF;
1147 RETURN NULL;
1148 END;
1149 $$;
1151 CREATE TRIGGER "write_event_issue_state_changed"
1152 AFTER UPDATE ON "issue" FOR EACH ROW EXECUTE PROCEDURE
1153 "write_event_issue_state_changed_trigger"();
1155 COMMENT ON FUNCTION "write_event_issue_state_changed_trigger"() IS 'Implementation of trigger "write_event_issue_state_changed" on table "issue"';
1156 COMMENT ON TRIGGER "write_event_issue_state_changed" ON "issue" IS 'Create entry in "event" table on "state" change';
1159 CREATE FUNCTION "write_event_initiative_or_draft_created_trigger"()
1160 RETURNS TRIGGER
1161 LANGUAGE 'plpgsql' VOLATILE AS $$
1162 DECLARE
1163 "initiative_row" "initiative"%ROWTYPE;
1164 "issue_row" "issue"%ROWTYPE;
1165 "event_v" "event_type";
1166 BEGIN
1167 SELECT * INTO "initiative_row" FROM "initiative"
1168 WHERE "id" = NEW."initiative_id";
1169 SELECT * INTO "issue_row" FROM "issue"
1170 WHERE "id" = "initiative_row"."issue_id";
1171 IF EXISTS (
1172 SELECT NULL FROM "draft"
1173 WHERE "initiative_id" = NEW."initiative_id"
1174 AND "id" != NEW."id"
1175 ) THEN
1176 "event_v" := 'new_draft_created';
1177 ELSE
1178 IF EXISTS (
1179 SELECT NULL FROM "initiative"
1180 WHERE "issue_id" = "initiative_row"."issue_id"
1181 AND "id" != "initiative_row"."id"
1182 ) THEN
1183 "event_v" := 'initiative_created_in_existing_issue';
1184 ELSE
1185 "event_v" := 'initiative_created_in_new_issue';
1186 END IF;
1187 END IF;
1188 INSERT INTO "event" (
1189 "event", "member_id",
1190 "issue_id", "state", "initiative_id", "draft_id"
1191 ) VALUES (
1192 "event_v",
1193 NEW."author_id",
1194 "initiative_row"."issue_id",
1195 "issue_row"."state",
1196 "initiative_row"."id",
1197 NEW."id" );
1198 RETURN NULL;
1199 END;
1200 $$;
1202 CREATE TRIGGER "write_event_initiative_or_draft_created"
1203 AFTER INSERT ON "draft" FOR EACH ROW EXECUTE PROCEDURE
1204 "write_event_initiative_or_draft_created_trigger"();
1206 COMMENT ON FUNCTION "write_event_initiative_or_draft_created_trigger"() IS 'Implementation of trigger "write_event_initiative_or_draft_created" on table "issue"';
1207 COMMENT ON TRIGGER "write_event_initiative_or_draft_created" ON "draft" IS 'Create entry in "event" table on draft creation';
1210 CREATE FUNCTION "write_event_initiative_revoked_trigger"()
1211 RETURNS TRIGGER
1212 LANGUAGE 'plpgsql' VOLATILE AS $$
1213 DECLARE
1214 "issue_row" "issue"%ROWTYPE;
1215 BEGIN
1216 SELECT * INTO "issue_row" FROM "issue"
1217 WHERE "id" = NEW."issue_id";
1218 IF OLD."revoked" ISNULL AND NEW."revoked" NOTNULL THEN
1219 INSERT INTO "event" (
1220 "event", "member_id", "issue_id", "state", "initiative_id"
1221 ) VALUES (
1222 'initiative_revoked',
1223 NEW."revoked_by_member_id",
1224 NEW."issue_id",
1225 "issue_row"."state",
1226 NEW."id" );
1227 END IF;
1228 RETURN NULL;
1229 END;
1230 $$;
1232 CREATE TRIGGER "write_event_initiative_revoked"
1233 AFTER UPDATE ON "initiative" FOR EACH ROW EXECUTE PROCEDURE
1234 "write_event_initiative_revoked_trigger"();
1236 COMMENT ON FUNCTION "write_event_initiative_revoked_trigger"() IS 'Implementation of trigger "write_event_initiative_revoked" on table "issue"';
1237 COMMENT ON TRIGGER "write_event_initiative_revoked" ON "initiative" IS 'Create entry in "event" table, when an initiative is revoked';
1240 CREATE FUNCTION "write_event_suggestion_created_trigger"()
1241 RETURNS TRIGGER
1242 LANGUAGE 'plpgsql' VOLATILE AS $$
1243 DECLARE
1244 "initiative_row" "initiative"%ROWTYPE;
1245 "issue_row" "issue"%ROWTYPE;
1246 BEGIN
1247 SELECT * INTO "initiative_row" FROM "initiative"
1248 WHERE "id" = NEW."initiative_id";
1249 SELECT * INTO "issue_row" FROM "issue"
1250 WHERE "id" = "initiative_row"."issue_id";
1251 INSERT INTO "event" (
1252 "event", "member_id",
1253 "issue_id", "state", "initiative_id", "suggestion_id"
1254 ) VALUES (
1255 'suggestion_created',
1256 NEW."author_id",
1257 "initiative_row"."issue_id",
1258 "issue_row"."state",
1259 "initiative_row"."id",
1260 NEW."id" );
1261 RETURN NULL;
1262 END;
1263 $$;
1265 CREATE TRIGGER "write_event_suggestion_created"
1266 AFTER INSERT ON "suggestion" FOR EACH ROW EXECUTE PROCEDURE
1267 "write_event_suggestion_created_trigger"();
1269 COMMENT ON FUNCTION "write_event_suggestion_created_trigger"() IS 'Implementation of trigger "write_event_suggestion_created" on table "issue"';
1270 COMMENT ON TRIGGER "write_event_suggestion_created" ON "suggestion" IS 'Create entry in "event" table on suggestion creation';
1274 ----------------------------
1275 -- Additional constraints --
1276 ----------------------------
1279 CREATE FUNCTION "issue_requires_first_initiative_trigger"()
1280 RETURNS TRIGGER
1281 LANGUAGE 'plpgsql' VOLATILE AS $$
1282 BEGIN
1283 IF NOT EXISTS (
1284 SELECT NULL FROM "initiative" WHERE "issue_id" = NEW."id"
1285 ) THEN
1286 --RAISE 'Cannot create issue without an initial initiative.' USING
1287 -- ERRCODE = 'integrity_constraint_violation',
1288 -- HINT = 'Create issue, initiative, and draft within the same transaction.';
1289 RAISE EXCEPTION 'Cannot create issue without an initial initiative.';
1290 END IF;
1291 RETURN NULL;
1292 END;
1293 $$;
1295 CREATE CONSTRAINT TRIGGER "issue_requires_first_initiative"
1296 AFTER INSERT OR UPDATE ON "issue" DEFERRABLE INITIALLY DEFERRED
1297 FOR EACH ROW EXECUTE PROCEDURE
1298 "issue_requires_first_initiative_trigger"();
1300 COMMENT ON FUNCTION "issue_requires_first_initiative_trigger"() IS 'Implementation of trigger "issue_requires_first_initiative" on table "issue"';
1301 COMMENT ON TRIGGER "issue_requires_first_initiative" ON "issue" IS 'Ensure that new issues have at least one initiative';
1304 CREATE FUNCTION "last_initiative_deletes_issue_trigger"()
1305 RETURNS TRIGGER
1306 LANGUAGE 'plpgsql' VOLATILE AS $$
1307 DECLARE
1308 "reference_lost" BOOLEAN;
1309 BEGIN
1310 IF TG_OP = 'DELETE' THEN
1311 "reference_lost" := TRUE;
1312 ELSE
1313 "reference_lost" := NEW."issue_id" != OLD."issue_id";
1314 END IF;
1315 IF
1316 "reference_lost" AND NOT EXISTS (
1317 SELECT NULL FROM "initiative" WHERE "issue_id" = OLD."issue_id"
1319 THEN
1320 DELETE FROM "issue" WHERE "id" = OLD."issue_id";
1321 END IF;
1322 RETURN NULL;
1323 END;
1324 $$;
1326 CREATE CONSTRAINT TRIGGER "last_initiative_deletes_issue"
1327 AFTER UPDATE OR DELETE ON "initiative" DEFERRABLE INITIALLY DEFERRED
1328 FOR EACH ROW EXECUTE PROCEDURE
1329 "last_initiative_deletes_issue_trigger"();
1331 COMMENT ON FUNCTION "last_initiative_deletes_issue_trigger"() IS 'Implementation of trigger "last_initiative_deletes_issue" on table "initiative"';
1332 COMMENT ON TRIGGER "last_initiative_deletes_issue" ON "initiative" IS 'Removing the last initiative of an issue deletes the issue';
1335 CREATE FUNCTION "initiative_requires_first_draft_trigger"()
1336 RETURNS TRIGGER
1337 LANGUAGE 'plpgsql' VOLATILE AS $$
1338 BEGIN
1339 IF NOT EXISTS (
1340 SELECT NULL FROM "draft" WHERE "initiative_id" = NEW."id"
1341 ) THEN
1342 --RAISE 'Cannot create initiative without an initial draft.' USING
1343 -- ERRCODE = 'integrity_constraint_violation',
1344 -- HINT = 'Create issue, initiative and draft within the same transaction.';
1345 RAISE EXCEPTION 'Cannot create initiative without an initial draft.';
1346 END IF;
1347 RETURN NULL;
1348 END;
1349 $$;
1351 CREATE CONSTRAINT TRIGGER "initiative_requires_first_draft"
1352 AFTER INSERT OR UPDATE ON "initiative" DEFERRABLE INITIALLY DEFERRED
1353 FOR EACH ROW EXECUTE PROCEDURE
1354 "initiative_requires_first_draft_trigger"();
1356 COMMENT ON FUNCTION "initiative_requires_first_draft_trigger"() IS 'Implementation of trigger "initiative_requires_first_draft" on table "initiative"';
1357 COMMENT ON TRIGGER "initiative_requires_first_draft" ON "initiative" IS 'Ensure that new initiatives have at least one draft';
1360 CREATE FUNCTION "last_draft_deletes_initiative_trigger"()
1361 RETURNS TRIGGER
1362 LANGUAGE 'plpgsql' VOLATILE AS $$
1363 DECLARE
1364 "reference_lost" BOOLEAN;
1365 BEGIN
1366 IF TG_OP = 'DELETE' THEN
1367 "reference_lost" := TRUE;
1368 ELSE
1369 "reference_lost" := NEW."initiative_id" != OLD."initiative_id";
1370 END IF;
1371 IF
1372 "reference_lost" AND NOT EXISTS (
1373 SELECT NULL FROM "draft" WHERE "initiative_id" = OLD."initiative_id"
1375 THEN
1376 DELETE FROM "initiative" WHERE "id" = OLD."initiative_id";
1377 END IF;
1378 RETURN NULL;
1379 END;
1380 $$;
1382 CREATE CONSTRAINT TRIGGER "last_draft_deletes_initiative"
1383 AFTER UPDATE OR DELETE ON "draft" DEFERRABLE INITIALLY DEFERRED
1384 FOR EACH ROW EXECUTE PROCEDURE
1385 "last_draft_deletes_initiative_trigger"();
1387 COMMENT ON FUNCTION "last_draft_deletes_initiative_trigger"() IS 'Implementation of trigger "last_draft_deletes_initiative" on table "draft"';
1388 COMMENT ON TRIGGER "last_draft_deletes_initiative" ON "draft" IS 'Removing the last draft of an initiative deletes the initiative';
1391 CREATE FUNCTION "suggestion_requires_first_opinion_trigger"()
1392 RETURNS TRIGGER
1393 LANGUAGE 'plpgsql' VOLATILE AS $$
1394 BEGIN
1395 IF NOT EXISTS (
1396 SELECT NULL FROM "opinion" WHERE "suggestion_id" = NEW."id"
1397 ) THEN
1398 RAISE EXCEPTION 'Cannot create a suggestion without an opinion.';
1399 END IF;
1400 RETURN NULL;
1401 END;
1402 $$;
1404 CREATE CONSTRAINT TRIGGER "suggestion_requires_first_opinion"
1405 AFTER INSERT OR UPDATE ON "suggestion" DEFERRABLE INITIALLY DEFERRED
1406 FOR EACH ROW EXECUTE PROCEDURE
1407 "suggestion_requires_first_opinion_trigger"();
1409 COMMENT ON FUNCTION "suggestion_requires_first_opinion_trigger"() IS 'Implementation of trigger "suggestion_requires_first_opinion" on table "suggestion"';
1410 COMMENT ON TRIGGER "suggestion_requires_first_opinion" ON "suggestion" IS 'Ensure that new suggestions have at least one opinion';
1413 CREATE FUNCTION "last_opinion_deletes_suggestion_trigger"()
1414 RETURNS TRIGGER
1415 LANGUAGE 'plpgsql' VOLATILE AS $$
1416 DECLARE
1417 "reference_lost" BOOLEAN;
1418 BEGIN
1419 IF TG_OP = 'DELETE' THEN
1420 "reference_lost" := TRUE;
1421 ELSE
1422 "reference_lost" := NEW."suggestion_id" != OLD."suggestion_id";
1423 END IF;
1424 IF
1425 "reference_lost" AND NOT EXISTS (
1426 SELECT NULL FROM "opinion" WHERE "suggestion_id" = OLD."suggestion_id"
1428 THEN
1429 DELETE FROM "suggestion" WHERE "id" = OLD."suggestion_id";
1430 END IF;
1431 RETURN NULL;
1432 END;
1433 $$;
1435 CREATE CONSTRAINT TRIGGER "last_opinion_deletes_suggestion"
1436 AFTER UPDATE OR DELETE ON "opinion" DEFERRABLE INITIALLY DEFERRED
1437 FOR EACH ROW EXECUTE PROCEDURE
1438 "last_opinion_deletes_suggestion_trigger"();
1440 COMMENT ON FUNCTION "last_opinion_deletes_suggestion_trigger"() IS 'Implementation of trigger "last_opinion_deletes_suggestion" on table "opinion"';
1441 COMMENT ON TRIGGER "last_opinion_deletes_suggestion" ON "opinion" IS 'Removing the last opinion of a suggestion deletes the suggestion';
1445 ---------------------------------------------------------------
1446 -- Ensure that votes are not modified when issues are frozen --
1447 ---------------------------------------------------------------
1449 -- NOTE: Frontends should ensure this anyway, but in case of programming
1450 -- errors the following triggers ensure data integrity.
1453 CREATE FUNCTION "forbid_changes_on_closed_issue_trigger"()
1454 RETURNS TRIGGER
1455 LANGUAGE 'plpgsql' VOLATILE AS $$
1456 DECLARE
1457 "issue_id_v" "issue"."id"%TYPE;
1458 "issue_row" "issue"%ROWTYPE;
1459 BEGIN
1460 IF TG_OP = 'DELETE' THEN
1461 "issue_id_v" := OLD."issue_id";
1462 ELSE
1463 "issue_id_v" := NEW."issue_id";
1464 END IF;
1465 SELECT INTO "issue_row" * FROM "issue"
1466 WHERE "id" = "issue_id_v" FOR SHARE;
1467 IF "issue_row"."closed" NOTNULL THEN
1468 RAISE EXCEPTION 'Tried to modify data belonging to a closed issue.';
1469 END IF;
1470 RETURN NULL;
1471 END;
1472 $$;
1474 CREATE TRIGGER "forbid_changes_on_closed_issue"
1475 AFTER INSERT OR UPDATE OR DELETE ON "direct_voter"
1476 FOR EACH ROW EXECUTE PROCEDURE
1477 "forbid_changes_on_closed_issue_trigger"();
1479 CREATE TRIGGER "forbid_changes_on_closed_issue"
1480 AFTER INSERT OR UPDATE OR DELETE ON "delegating_voter"
1481 FOR EACH ROW EXECUTE PROCEDURE
1482 "forbid_changes_on_closed_issue_trigger"();
1484 CREATE TRIGGER "forbid_changes_on_closed_issue"
1485 AFTER INSERT OR UPDATE OR DELETE ON "vote"
1486 FOR EACH ROW EXECUTE PROCEDURE
1487 "forbid_changes_on_closed_issue_trigger"();
1489 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"';
1490 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';
1491 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';
1492 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';
1496 --------------------------------------------------------------------
1497 -- Auto-retrieval of fields only needed for referential integrity --
1498 --------------------------------------------------------------------
1501 CREATE FUNCTION "autofill_issue_id_trigger"()
1502 RETURNS TRIGGER
1503 LANGUAGE 'plpgsql' VOLATILE AS $$
1504 BEGIN
1505 IF NEW."issue_id" ISNULL THEN
1506 SELECT "issue_id" INTO NEW."issue_id"
1507 FROM "initiative" WHERE "id" = NEW."initiative_id";
1508 END IF;
1509 RETURN NEW;
1510 END;
1511 $$;
1513 CREATE TRIGGER "autofill_issue_id" BEFORE INSERT ON "supporter"
1514 FOR EACH ROW EXECUTE PROCEDURE "autofill_issue_id_trigger"();
1516 CREATE TRIGGER "autofill_issue_id" BEFORE INSERT ON "vote"
1517 FOR EACH ROW EXECUTE PROCEDURE "autofill_issue_id_trigger"();
1519 COMMENT ON FUNCTION "autofill_issue_id_trigger"() IS 'Implementation of triggers "autofill_issue_id" on tables "supporter" and "vote"';
1520 COMMENT ON TRIGGER "autofill_issue_id" ON "supporter" IS 'Set "issue_id" field automatically, if NULL';
1521 COMMENT ON TRIGGER "autofill_issue_id" ON "vote" IS 'Set "issue_id" field automatically, if NULL';
1524 CREATE FUNCTION "autofill_initiative_id_trigger"()
1525 RETURNS TRIGGER
1526 LANGUAGE 'plpgsql' VOLATILE AS $$
1527 BEGIN
1528 IF NEW."initiative_id" ISNULL THEN
1529 SELECT "initiative_id" INTO NEW."initiative_id"
1530 FROM "suggestion" WHERE "id" = NEW."suggestion_id";
1531 END IF;
1532 RETURN NEW;
1533 END;
1534 $$;
1536 CREATE TRIGGER "autofill_initiative_id" BEFORE INSERT ON "opinion"
1537 FOR EACH ROW EXECUTE PROCEDURE "autofill_initiative_id_trigger"();
1539 COMMENT ON FUNCTION "autofill_initiative_id_trigger"() IS 'Implementation of trigger "autofill_initiative_id" on table "opinion"';
1540 COMMENT ON TRIGGER "autofill_initiative_id" ON "opinion" IS 'Set "initiative_id" field automatically, if NULL';
1544 -----------------------------------------------------
1545 -- Automatic calculation of certain default values --
1546 -----------------------------------------------------
1549 CREATE FUNCTION "copy_timings_trigger"()
1550 RETURNS TRIGGER
1551 LANGUAGE 'plpgsql' VOLATILE AS $$
1552 DECLARE
1553 "policy_row" "policy"%ROWTYPE;
1554 BEGIN
1555 SELECT * INTO "policy_row" FROM "policy"
1556 WHERE "id" = NEW."policy_id";
1557 IF NEW."admission_time" ISNULL THEN
1558 NEW."admission_time" := "policy_row"."admission_time";
1559 END IF;
1560 IF NEW."discussion_time" ISNULL THEN
1561 NEW."discussion_time" := "policy_row"."discussion_time";
1562 END IF;
1563 IF NEW."verification_time" ISNULL THEN
1564 NEW."verification_time" := "policy_row"."verification_time";
1565 END IF;
1566 IF NEW."voting_time" ISNULL THEN
1567 NEW."voting_time" := "policy_row"."voting_time";
1568 END IF;
1569 RETURN NEW;
1570 END;
1571 $$;
1573 CREATE TRIGGER "copy_timings" BEFORE INSERT OR UPDATE ON "issue"
1574 FOR EACH ROW EXECUTE PROCEDURE "copy_timings_trigger"();
1576 COMMENT ON FUNCTION "copy_timings_trigger"() IS 'Implementation of trigger "copy_timings" on table "issue"';
1577 COMMENT ON TRIGGER "copy_timings" ON "issue" IS 'If timing fields are NULL, copy values from policy.';
1580 CREATE FUNCTION "supporter_default_for_draft_id_trigger"()
1581 RETURNS TRIGGER
1582 LANGUAGE 'plpgsql' VOLATILE AS $$
1583 BEGIN
1584 IF NEW."draft_id" ISNULL THEN
1585 SELECT "id" INTO NEW."draft_id" FROM "current_draft"
1586 WHERE "initiative_id" = NEW."initiative_id";
1587 END IF;
1588 RETURN NEW;
1589 END;
1590 $$;
1592 CREATE TRIGGER "default_for_draft_id" BEFORE INSERT OR UPDATE ON "supporter"
1593 FOR EACH ROW EXECUTE PROCEDURE "supporter_default_for_draft_id_trigger"();
1595 COMMENT ON FUNCTION "supporter_default_for_draft_id_trigger"() IS 'Implementation of trigger "default_for_draft" on table "supporter"';
1596 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';
1600 ----------------------------------------
1601 -- Automatic creation of dependencies --
1602 ----------------------------------------
1605 CREATE FUNCTION "autocreate_interest_trigger"()
1606 RETURNS TRIGGER
1607 LANGUAGE 'plpgsql' VOLATILE AS $$
1608 BEGIN
1609 IF NOT EXISTS (
1610 SELECT NULL FROM "initiative" JOIN "interest"
1611 ON "initiative"."issue_id" = "interest"."issue_id"
1612 WHERE "initiative"."id" = NEW."initiative_id"
1613 AND "interest"."member_id" = NEW."member_id"
1614 ) THEN
1615 BEGIN
1616 INSERT INTO "interest" ("issue_id", "member_id")
1617 SELECT "issue_id", NEW."member_id"
1618 FROM "initiative" WHERE "id" = NEW."initiative_id";
1619 EXCEPTION WHEN unique_violation THEN END;
1620 END IF;
1621 RETURN NEW;
1622 END;
1623 $$;
1625 CREATE TRIGGER "autocreate_interest" BEFORE INSERT ON "supporter"
1626 FOR EACH ROW EXECUTE PROCEDURE "autocreate_interest_trigger"();
1628 COMMENT ON FUNCTION "autocreate_interest_trigger"() IS 'Implementation of trigger "autocreate_interest" on table "supporter"';
1629 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';
1632 CREATE FUNCTION "autocreate_supporter_trigger"()
1633 RETURNS TRIGGER
1634 LANGUAGE 'plpgsql' VOLATILE AS $$
1635 BEGIN
1636 IF NOT EXISTS (
1637 SELECT NULL FROM "suggestion" JOIN "supporter"
1638 ON "suggestion"."initiative_id" = "supporter"."initiative_id"
1639 WHERE "suggestion"."id" = NEW."suggestion_id"
1640 AND "supporter"."member_id" = NEW."member_id"
1641 ) THEN
1642 BEGIN
1643 INSERT INTO "supporter" ("initiative_id", "member_id")
1644 SELECT "initiative_id", NEW."member_id"
1645 FROM "suggestion" WHERE "id" = NEW."suggestion_id";
1646 EXCEPTION WHEN unique_violation THEN END;
1647 END IF;
1648 RETURN NEW;
1649 END;
1650 $$;
1652 CREATE TRIGGER "autocreate_supporter" BEFORE INSERT ON "opinion"
1653 FOR EACH ROW EXECUTE PROCEDURE "autocreate_supporter_trigger"();
1655 COMMENT ON FUNCTION "autocreate_supporter_trigger"() IS 'Implementation of trigger "autocreate_supporter" on table "opinion"';
1656 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.';
1660 ------------------------------------------
1661 -- Views and helper functions for views --
1662 ------------------------------------------
1665 CREATE VIEW "unit_delegation" AS
1666 SELECT
1667 "unit"."id" AS "unit_id",
1668 "delegation"."id",
1669 "delegation"."truster_id",
1670 "delegation"."trustee_id",
1671 "delegation"."scope"
1672 FROM "unit"
1673 JOIN "delegation"
1674 ON "delegation"."unit_id" = "unit"."id"
1675 JOIN "member"
1676 ON "delegation"."truster_id" = "member"."id"
1677 JOIN "privilege"
1678 ON "delegation"."unit_id" = "privilege"."unit_id"
1679 AND "delegation"."truster_id" = "privilege"."member_id"
1680 WHERE "member"."active" AND "privilege"."voting_right";
1682 COMMENT ON VIEW "unit_delegation" IS 'Unit delegations where trusters are active and have voting right';
1685 CREATE VIEW "area_delegation" AS
1686 SELECT DISTINCT ON ("area"."id", "delegation"."truster_id")
1687 "area"."id" AS "area_id",
1688 "delegation"."id",
1689 "delegation"."truster_id",
1690 "delegation"."trustee_id",
1691 "delegation"."scope"
1692 FROM "area"
1693 JOIN "delegation"
1694 ON "delegation"."unit_id" = "area"."unit_id"
1695 OR "delegation"."area_id" = "area"."id"
1696 JOIN "member"
1697 ON "delegation"."truster_id" = "member"."id"
1698 JOIN "privilege"
1699 ON "area"."unit_id" = "privilege"."unit_id"
1700 AND "delegation"."truster_id" = "privilege"."member_id"
1701 WHERE "member"."active" AND "privilege"."voting_right"
1702 ORDER BY
1703 "area"."id",
1704 "delegation"."truster_id",
1705 "delegation"."scope" DESC;
1707 COMMENT ON VIEW "area_delegation" IS 'Area delegations where trusters are active and have voting right';
1710 CREATE VIEW "issue_delegation" AS
1711 SELECT DISTINCT ON ("issue"."id", "delegation"."truster_id")
1712 "issue"."id" AS "issue_id",
1713 "delegation"."id",
1714 "delegation"."truster_id",
1715 "delegation"."trustee_id",
1716 "delegation"."scope"
1717 FROM "issue"
1718 JOIN "area"
1719 ON "area"."id" = "issue"."area_id"
1720 JOIN "delegation"
1721 ON "delegation"."unit_id" = "area"."unit_id"
1722 OR "delegation"."area_id" = "area"."id"
1723 OR "delegation"."issue_id" = "issue"."id"
1724 JOIN "member"
1725 ON "delegation"."truster_id" = "member"."id"
1726 JOIN "privilege"
1727 ON "area"."unit_id" = "privilege"."unit_id"
1728 AND "delegation"."truster_id" = "privilege"."member_id"
1729 WHERE "member"."active" AND "privilege"."voting_right"
1730 ORDER BY
1731 "issue"."id",
1732 "delegation"."truster_id",
1733 "delegation"."scope" DESC;
1735 COMMENT ON VIEW "issue_delegation" IS 'Issue delegations where trusters are active and have voting right';
1738 CREATE FUNCTION "membership_weight_with_skipping"
1739 ( "area_id_p" "area"."id"%TYPE,
1740 "member_id_p" "member"."id"%TYPE,
1741 "skip_member_ids_p" INT4[] ) -- "member"."id"%TYPE[]
1742 RETURNS INT4
1743 LANGUAGE 'plpgsql' STABLE AS $$
1744 DECLARE
1745 "sum_v" INT4;
1746 "delegation_row" "area_delegation"%ROWTYPE;
1747 BEGIN
1748 "sum_v" := 1;
1749 FOR "delegation_row" IN
1750 SELECT "area_delegation".*
1751 FROM "area_delegation" LEFT JOIN "membership"
1752 ON "membership"."area_id" = "area_id_p"
1753 AND "membership"."member_id" = "area_delegation"."truster_id"
1754 WHERE "area_delegation"."area_id" = "area_id_p"
1755 AND "area_delegation"."trustee_id" = "member_id_p"
1756 AND "membership"."member_id" ISNULL
1757 LOOP
1758 IF NOT
1759 "skip_member_ids_p" @> ARRAY["delegation_row"."truster_id"]
1760 THEN
1761 "sum_v" := "sum_v" + "membership_weight_with_skipping"(
1762 "area_id_p",
1763 "delegation_row"."truster_id",
1764 "skip_member_ids_p" || "delegation_row"."truster_id"
1765 );
1766 END IF;
1767 END LOOP;
1768 RETURN "sum_v";
1769 END;
1770 $$;
1772 COMMENT ON FUNCTION "membership_weight_with_skipping"
1773 ( "area"."id"%TYPE,
1774 "member"."id"%TYPE,
1775 INT4[] )
1776 IS 'Helper function for "membership_weight" function';
1779 CREATE FUNCTION "membership_weight"
1780 ( "area_id_p" "area"."id"%TYPE,
1781 "member_id_p" "member"."id"%TYPE ) -- "member"."id"%TYPE[]
1782 RETURNS INT4
1783 LANGUAGE 'plpgsql' STABLE AS $$
1784 BEGIN
1785 RETURN "membership_weight_with_skipping"(
1786 "area_id_p",
1787 "member_id_p",
1788 ARRAY["member_id_p"]
1789 );
1790 END;
1791 $$;
1793 COMMENT ON FUNCTION "membership_weight"
1794 ( "area"."id"%TYPE,
1795 "member"."id"%TYPE )
1796 IS 'Calculates the potential voting weight of a member in a given area';
1799 CREATE VIEW "member_count_view" AS
1800 SELECT count(1) AS "total_count" FROM "member" WHERE "active";
1802 COMMENT ON VIEW "member_count_view" IS 'View used to update "member_count" table';
1805 CREATE VIEW "unit_member_count" AS
1806 SELECT
1807 "unit"."id" AS "unit_id",
1808 sum("member"."id") AS "member_count"
1809 FROM "unit"
1810 LEFT JOIN "privilege"
1811 ON "privilege"."unit_id" = "unit"."id"
1812 AND "privilege"."voting_right"
1813 LEFT JOIN "member"
1814 ON "member"."id" = "privilege"."member_id"
1815 AND "member"."active"
1816 GROUP BY "unit"."id";
1818 COMMENT ON VIEW "unit_member_count" IS 'View used to update "member_count" column of "unit" table';
1821 CREATE VIEW "area_member_count" AS
1822 SELECT
1823 "area"."id" AS "area_id",
1824 count("member"."id") AS "direct_member_count",
1825 coalesce(
1826 sum(
1827 CASE WHEN "member"."id" NOTNULL THEN
1828 "membership_weight"("area"."id", "member"."id")
1829 ELSE 0 END
1831 ) AS "member_weight",
1832 coalesce(
1833 sum(
1834 CASE WHEN "member"."id" NOTNULL AND "membership"."autoreject" THEN
1835 "membership_weight"("area"."id", "member"."id")
1836 ELSE 0 END
1838 ) AS "autoreject_weight"
1839 FROM "area"
1840 LEFT JOIN "membership"
1841 ON "area"."id" = "membership"."area_id"
1842 LEFT JOIN "privilege"
1843 ON "privilege"."unit_id" = "area"."unit_id"
1844 AND "privilege"."member_id" = "membership"."member_id"
1845 AND "privilege"."voting_right"
1846 LEFT JOIN "member"
1847 ON "member"."id" = "privilege"."member_id" -- NOTE: no membership here!
1848 AND "member"."active"
1849 GROUP BY "area"."id";
1851 COMMENT ON VIEW "area_member_count" IS 'View used to update "direct_member_count", "member_weight" and "autoreject_weight" columns of table "area"';
1854 CREATE VIEW "opening_draft" AS
1855 SELECT "draft".* FROM (
1856 SELECT
1857 "initiative"."id" AS "initiative_id",
1858 min("draft"."id") AS "draft_id"
1859 FROM "initiative" JOIN "draft"
1860 ON "initiative"."id" = "draft"."initiative_id"
1861 GROUP BY "initiative"."id"
1862 ) AS "subquery"
1863 JOIN "draft" ON "subquery"."draft_id" = "draft"."id";
1865 COMMENT ON VIEW "opening_draft" IS 'First drafts of all initiatives';
1868 CREATE VIEW "current_draft" AS
1869 SELECT "draft".* FROM (
1870 SELECT
1871 "initiative"."id" AS "initiative_id",
1872 max("draft"."id") AS "draft_id"
1873 FROM "initiative" JOIN "draft"
1874 ON "initiative"."id" = "draft"."initiative_id"
1875 GROUP BY "initiative"."id"
1876 ) AS "subquery"
1877 JOIN "draft" ON "subquery"."draft_id" = "draft"."id";
1879 COMMENT ON VIEW "current_draft" IS 'All latest drafts for each initiative';
1882 CREATE VIEW "critical_opinion" AS
1883 SELECT * FROM "opinion"
1884 WHERE ("degree" = 2 AND "fulfilled" = FALSE)
1885 OR ("degree" = -2 AND "fulfilled" = TRUE);
1887 COMMENT ON VIEW "critical_opinion" IS 'Opinions currently causing dissatisfaction';
1890 CREATE VIEW "battle_participant" AS
1891 SELECT "initiative"."id", "initiative"."issue_id"
1892 FROM "issue" JOIN "initiative"
1893 ON "issue"."id" = "initiative"."issue_id"
1894 WHERE "initiative"."admitted"
1895 UNION ALL
1896 SELECT NULL, "id" AS "issue_id"
1897 FROM "issue";
1899 COMMENT ON VIEW "battle_participant" IS 'Helper view for "battle_view" containing admitted initiatives plus virtual "status-quo" initiative denoted by NULL reference';
1902 CREATE VIEW "battle_view" AS
1903 SELECT
1904 "issue"."id" AS "issue_id",
1905 "winning_initiative"."id" AS "winning_initiative_id",
1906 "losing_initiative"."id" AS "losing_initiative_id",
1907 sum(
1908 CASE WHEN
1909 coalesce("better_vote"."grade", 0) >
1910 coalesce("worse_vote"."grade", 0)
1911 THEN "direct_voter"."weight" ELSE 0 END
1912 ) AS "count"
1913 FROM "issue"
1914 LEFT JOIN "direct_voter"
1915 ON "issue"."id" = "direct_voter"."issue_id"
1916 JOIN "battle_participant" AS "winning_initiative"
1917 ON "issue"."id" = "winning_initiative"."issue_id"
1918 JOIN "battle_participant" AS "losing_initiative"
1919 ON "issue"."id" = "losing_initiative"."issue_id"
1920 LEFT JOIN "vote" AS "better_vote"
1921 ON "direct_voter"."member_id" = "better_vote"."member_id"
1922 AND "winning_initiative"."id" = "better_vote"."initiative_id"
1923 LEFT JOIN "vote" AS "worse_vote"
1924 ON "direct_voter"."member_id" = "worse_vote"."member_id"
1925 AND "losing_initiative"."id" = "worse_vote"."initiative_id"
1926 WHERE "issue"."closed" NOTNULL
1927 AND "issue"."cleaned" ISNULL
1928 AND (
1929 "winning_initiative"."id" != "losing_initiative"."id" OR
1930 ( ("winning_initiative"."id" NOTNULL AND "losing_initiative"."id" ISNULL) OR
1931 ("winning_initiative"."id" ISNULL AND "losing_initiative"."id" NOTNULL) ) )
1932 GROUP BY
1933 "issue"."id",
1934 "winning_initiative"."id",
1935 "losing_initiative"."id";
1937 COMMENT ON VIEW "battle_view" IS 'Number of members preferring one initiative (or status-quo) to another initiative (or status-quo); Used to fill "battle" table';
1940 CREATE VIEW "expired_session" AS
1941 SELECT * FROM "session" WHERE now() > "expiry";
1943 CREATE RULE "delete" AS ON DELETE TO "expired_session" DO INSTEAD
1944 DELETE FROM "session" WHERE "ident" = OLD."ident";
1946 COMMENT ON VIEW "expired_session" IS 'View containing all expired sessions where DELETE is possible';
1947 COMMENT ON RULE "delete" ON "expired_session" IS 'Rule allowing DELETE on rows in "expired_session" view, i.e. DELETE FROM "expired_session"';
1950 CREATE VIEW "open_issue" AS
1951 SELECT * FROM "issue" WHERE "closed" ISNULL;
1953 COMMENT ON VIEW "open_issue" IS 'All open issues';
1956 CREATE VIEW "issue_with_ranks_missing" AS
1957 SELECT * FROM "issue"
1958 WHERE "fully_frozen" NOTNULL
1959 AND "closed" NOTNULL
1960 AND "ranks_available" = FALSE;
1962 COMMENT ON VIEW "issue_with_ranks_missing" IS 'Issues where voting was finished, but no ranks have been calculated yet';
1965 CREATE VIEW "member_contingent" AS
1966 SELECT
1967 "member"."id" AS "member_id",
1968 "contingent"."time_frame",
1969 CASE WHEN "contingent"."text_entry_limit" NOTNULL THEN
1971 SELECT count(1) FROM "draft"
1972 WHERE "draft"."author_id" = "member"."id"
1973 AND "draft"."created" > now() - "contingent"."time_frame"
1974 ) + (
1975 SELECT count(1) FROM "suggestion"
1976 WHERE "suggestion"."author_id" = "member"."id"
1977 AND "suggestion"."created" > now() - "contingent"."time_frame"
1979 ELSE NULL END AS "text_entry_count",
1980 "contingent"."text_entry_limit",
1981 CASE WHEN "contingent"."initiative_limit" NOTNULL THEN (
1982 SELECT count(1) FROM "opening_draft"
1983 WHERE "opening_draft"."author_id" = "member"."id"
1984 AND "opening_draft"."created" > now() - "contingent"."time_frame"
1985 ) ELSE NULL END AS "initiative_count",
1986 "contingent"."initiative_limit"
1987 FROM "member" CROSS JOIN "contingent";
1989 COMMENT ON VIEW "member_contingent" IS 'Actual counts of text entries and initiatives are calculated per member for each limit in the "contingent" table.';
1991 COMMENT ON COLUMN "member_contingent"."text_entry_count" IS 'Only calculated when "text_entry_limit" is not null in the same row';
1992 COMMENT ON COLUMN "member_contingent"."initiative_count" IS 'Only calculated when "initiative_limit" is not null in the same row';
1995 CREATE VIEW "member_contingent_left" AS
1996 SELECT
1997 "member_id",
1998 max("text_entry_limit" - "text_entry_count") AS "text_entries_left",
1999 max("initiative_limit" - "initiative_count") AS "initiatives_left"
2000 FROM "member_contingent" GROUP BY "member_id";
2002 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.';
2005 CREATE VIEW "event_seen_by_member" AS
2006 SELECT
2007 "member"."id" AS "seen_by_member_id",
2008 CASE WHEN "event"."state" IN (
2009 'voting',
2010 'finished_without_winner',
2011 'finished_with_winner'
2012 ) THEN
2013 'voting'::"notify_level"
2014 ELSE
2015 CASE WHEN "event"."state" IN (
2016 'verification',
2017 'canceled_after_revocation_during_verification',
2018 'canceled_no_initiative_admitted'
2019 ) THEN
2020 'verification'::"notify_level"
2021 ELSE
2022 CASE WHEN "event"."state" IN (
2023 'discussion',
2024 'canceled_after_revocation_during_discussion'
2025 ) THEN
2026 'discussion'::"notify_level"
2027 ELSE
2028 'all'::"notify_level"
2029 END
2030 END
2031 END AS "notify_level",
2032 "event".*
2033 FROM "member" CROSS JOIN "event"
2034 LEFT JOIN "issue"
2035 ON "event"."issue_id" = "issue"."id"
2036 LEFT JOIN "membership"
2037 ON "member"."id" = "membership"."member_id"
2038 AND "issue"."area_id" = "membership"."area_id"
2039 LEFT JOIN "interest"
2040 ON "member"."id" = "interest"."member_id"
2041 AND "event"."issue_id" = "interest"."issue_id"
2042 LEFT JOIN "supporter"
2043 ON "member"."id" = "supporter"."member_id"
2044 AND "event"."initiative_id" = "supporter"."initiative_id"
2045 LEFT JOIN "ignored_member"
2046 ON "member"."id" = "ignored_member"."member_id"
2047 AND "event"."member_id" = "ignored_member"."other_member_id"
2048 LEFT JOIN "ignored_initiative"
2049 ON "member"."id" = "ignored_initiative"."member_id"
2050 AND "event"."initiative_id" = "ignored_initiative"."initiative_id"
2051 WHERE (
2052 "supporter"."member_id" NOTNULL OR
2053 "interest"."member_id" NOTNULL OR
2054 ( "membership"."member_id" NOTNULL AND
2055 "event"."event" IN (
2056 'issue_state_changed',
2057 'initiative_created_in_new_issue',
2058 'initiative_created_in_existing_issue',
2059 'initiative_revoked' ) ) )
2060 AND "ignored_member"."member_id" ISNULL
2061 AND "ignored_initiative"."member_id" ISNULL;
2063 COMMENT ON VIEW "event_seen_by_member" IS 'Events as seen by a member, depending on its memberships, interests and support';
2066 CREATE VIEW "pending_notification" AS
2067 SELECT
2068 "member"."id" AS "seen_by_member_id",
2069 "event".*
2070 FROM "member" CROSS JOIN "event"
2071 LEFT JOIN "issue"
2072 ON "event"."issue_id" = "issue"."id"
2073 LEFT JOIN "membership"
2074 ON "member"."id" = "membership"."member_id"
2075 AND "issue"."area_id" = "membership"."area_id"
2076 LEFT JOIN "interest"
2077 ON "member"."id" = "interest"."member_id"
2078 AND "event"."issue_id" = "interest"."issue_id"
2079 LEFT JOIN "supporter"
2080 ON "member"."id" = "supporter"."member_id"
2081 AND "event"."initiative_id" = "supporter"."initiative_id"
2082 LEFT JOIN "ignored_member"
2083 ON "member"."id" = "ignored_member"."member_id"
2084 AND "event"."member_id" = "ignored_member"."other_member_id"
2085 LEFT JOIN "ignored_initiative"
2086 ON "member"."id" = "ignored_initiative"."member_id"
2087 AND "event"."initiative_id" = "ignored_initiative"."initiative_id"
2088 WHERE (
2089 "member"."notify_event_id" ISNULL OR
2090 ( "member"."notify_event_id" NOTNULL AND
2091 "member"."notify_event_id" < "event"."id" ) )
2092 AND (
2093 ( "member"."notify_level" >= 'all' ) OR
2094 ( "member"."notify_level" >= 'voting' AND
2095 "event"."state" IN (
2096 'voting',
2097 'finished_without_winner',
2098 'finished_with_winner' ) ) OR
2099 ( "member"."notify_level" >= 'verification' AND
2100 "event"."state" IN (
2101 'verification',
2102 'canceled_after_revocation_during_verification',
2103 'canceled_no_initiative_admitted' ) ) OR
2104 ( "member"."notify_level" >= 'discussion' AND
2105 "event"."state" IN (
2106 'discussion',
2107 'canceled_after_revocation_during_discussion' ) ) )
2108 AND (
2109 "supporter"."member_id" NOTNULL OR
2110 "interest"."member_id" NOTNULL OR
2111 ( "membership"."member_id" NOTNULL AND
2112 "event"."event" IN (
2113 'issue_state_changed',
2114 'initiative_created_in_new_issue',
2115 'initiative_created_in_existing_issue',
2116 'initiative_revoked' ) ) )
2117 AND "ignored_member"."member_id" ISNULL
2118 AND "ignored_initiative"."member_id" ISNULL;
2120 COMMENT ON VIEW "pending_notification" IS 'Events to be sent to "notify_email" address of member referred to by "seen_by_member_id"';
2123 CREATE TYPE "timeline_event" AS ENUM (
2124 'issue_created',
2125 'issue_canceled',
2126 'issue_accepted',
2127 'issue_half_frozen',
2128 'issue_finished_without_voting',
2129 'issue_voting_started',
2130 'issue_finished_after_voting',
2131 'initiative_created',
2132 'initiative_revoked',
2133 'draft_created',
2134 'suggestion_created');
2136 COMMENT ON TYPE "timeline_event" IS 'Types of event in timeline tables (DEPRECATED)';
2139 CREATE VIEW "timeline_issue" AS
2140 SELECT
2141 "created" AS "occurrence",
2142 'issue_created'::"timeline_event" AS "event",
2143 "id" AS "issue_id"
2144 FROM "issue"
2145 UNION ALL
2146 SELECT
2147 "closed" AS "occurrence",
2148 'issue_canceled'::"timeline_event" AS "event",
2149 "id" AS "issue_id"
2150 FROM "issue" WHERE "closed" NOTNULL AND "fully_frozen" ISNULL
2151 UNION ALL
2152 SELECT
2153 "accepted" AS "occurrence",
2154 'issue_accepted'::"timeline_event" AS "event",
2155 "id" AS "issue_id"
2156 FROM "issue" WHERE "accepted" NOTNULL
2157 UNION ALL
2158 SELECT
2159 "half_frozen" AS "occurrence",
2160 'issue_half_frozen'::"timeline_event" AS "event",
2161 "id" AS "issue_id"
2162 FROM "issue" WHERE "half_frozen" NOTNULL
2163 UNION ALL
2164 SELECT
2165 "fully_frozen" AS "occurrence",
2166 'issue_voting_started'::"timeline_event" AS "event",
2167 "id" AS "issue_id"
2168 FROM "issue"
2169 WHERE "fully_frozen" NOTNULL
2170 AND ("closed" ISNULL OR "closed" != "fully_frozen")
2171 UNION ALL
2172 SELECT
2173 "closed" AS "occurrence",
2174 CASE WHEN "fully_frozen" = "closed" THEN
2175 'issue_finished_without_voting'::"timeline_event"
2176 ELSE
2177 'issue_finished_after_voting'::"timeline_event"
2178 END AS "event",
2179 "id" AS "issue_id"
2180 FROM "issue" WHERE "closed" NOTNULL AND "fully_frozen" NOTNULL;
2182 COMMENT ON VIEW "timeline_issue" IS 'Helper view for "timeline" view (DEPRECATED)';
2185 CREATE VIEW "timeline_initiative" AS
2186 SELECT
2187 "created" AS "occurrence",
2188 'initiative_created'::"timeline_event" AS "event",
2189 "id" AS "initiative_id"
2190 FROM "initiative"
2191 UNION ALL
2192 SELECT
2193 "revoked" AS "occurrence",
2194 'initiative_revoked'::"timeline_event" AS "event",
2195 "id" AS "initiative_id"
2196 FROM "initiative" WHERE "revoked" NOTNULL;
2198 COMMENT ON VIEW "timeline_initiative" IS 'Helper view for "timeline" view (DEPRECATED)';
2201 CREATE VIEW "timeline_draft" AS
2202 SELECT
2203 "created" AS "occurrence",
2204 'draft_created'::"timeline_event" AS "event",
2205 "id" AS "draft_id"
2206 FROM "draft";
2208 COMMENT ON VIEW "timeline_draft" IS 'Helper view for "timeline" view (DEPRECATED)';
2211 CREATE VIEW "timeline_suggestion" AS
2212 SELECT
2213 "created" AS "occurrence",
2214 'suggestion_created'::"timeline_event" AS "event",
2215 "id" AS "suggestion_id"
2216 FROM "suggestion";
2218 COMMENT ON VIEW "timeline_suggestion" IS 'Helper view for "timeline" view (DEPRECATED)';
2221 CREATE VIEW "timeline" AS
2222 SELECT
2223 "occurrence",
2224 "event",
2225 "issue_id",
2226 NULL AS "initiative_id",
2227 NULL::INT8 AS "draft_id", -- TODO: Why do we need a type-cast here? Is this due to 32 bit architecture?
2228 NULL::INT8 AS "suggestion_id"
2229 FROM "timeline_issue"
2230 UNION ALL
2231 SELECT
2232 "occurrence",
2233 "event",
2234 NULL AS "issue_id",
2235 "initiative_id",
2236 NULL AS "draft_id",
2237 NULL AS "suggestion_id"
2238 FROM "timeline_initiative"
2239 UNION ALL
2240 SELECT
2241 "occurrence",
2242 "event",
2243 NULL AS "issue_id",
2244 NULL AS "initiative_id",
2245 "draft_id",
2246 NULL AS "suggestion_id"
2247 FROM "timeline_draft"
2248 UNION ALL
2249 SELECT
2250 "occurrence",
2251 "event",
2252 NULL AS "issue_id",
2253 NULL AS "initiative_id",
2254 NULL AS "draft_id",
2255 "suggestion_id"
2256 FROM "timeline_suggestion";
2258 COMMENT ON VIEW "timeline" IS 'Aggregation of different events in the system (DEPRECATED)';
2262 --------------------------------------------------
2263 -- Set returning function for delegation chains --
2264 --------------------------------------------------
2267 CREATE TYPE "delegation_chain_loop_tag" AS ENUM
2268 ('first', 'intermediate', 'last', 'repetition');
2270 COMMENT ON TYPE "delegation_chain_loop_tag" IS 'Type for loop tags in "delegation_chain_row" type';
2273 CREATE TYPE "delegation_chain_row" AS (
2274 "index" INT4,
2275 "member_id" INT4,
2276 "member_valid" BOOLEAN,
2277 "participation" BOOLEAN,
2278 "overridden" BOOLEAN,
2279 "scope_in" "delegation_scope",
2280 "scope_out" "delegation_scope",
2281 "disabled_out" BOOLEAN,
2282 "loop" "delegation_chain_loop_tag" );
2284 COMMENT ON TYPE "delegation_chain_row" IS 'Type of rows returned by "delegation_chain"(...) functions';
2286 COMMENT ON COLUMN "delegation_chain_row"."index" IS 'Index starting with 0 and counting up';
2287 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';
2288 COMMENT ON COLUMN "delegation_chain_row"."overridden" IS 'True, if an entry with lower index has "participation" set to true';
2289 COMMENT ON COLUMN "delegation_chain_row"."scope_in" IS 'Scope of used incoming delegation';
2290 COMMENT ON COLUMN "delegation_chain_row"."scope_out" IS 'Scope of used outgoing delegation';
2291 COMMENT ON COLUMN "delegation_chain_row"."disabled_out" IS 'Outgoing delegation is explicitly disabled by a delegation with trustee_id set to NULL';
2292 COMMENT ON COLUMN "delegation_chain_row"."loop" IS 'Not null, if member is part of a loop, see "delegation_chain_loop_tag" type';
2295 CREATE FUNCTION "delegation_chain"
2296 ( "member_id_p" "member"."id"%TYPE,
2297 "unit_id_p" "unit"."id"%TYPE,
2298 "area_id_p" "area"."id"%TYPE,
2299 "issue_id_p" "issue"."id"%TYPE,
2300 "simulate_trustee_id_p" "member"."id"%TYPE )
2301 RETURNS SETOF "delegation_chain_row"
2302 LANGUAGE 'plpgsql' STABLE AS $$
2303 DECLARE
2304 "scope_v" "delegation_scope";
2305 "unit_id_v" "unit"."id"%TYPE;
2306 "area_id_v" "area"."id"%TYPE;
2307 "visited_member_ids" INT4[]; -- "member"."id"%TYPE[]
2308 "loop_member_id_v" "member"."id"%TYPE;
2309 "output_row" "delegation_chain_row";
2310 "output_rows" "delegation_chain_row"[];
2311 "delegation_row" "delegation"%ROWTYPE;
2312 "row_count" INT4;
2313 "i" INT4;
2314 "loop_v" BOOLEAN;
2315 BEGIN
2316 IF
2317 "unit_id_p" NOTNULL AND
2318 "area_id_p" ISNULL AND
2319 "issue_id_p" ISNULL
2320 THEN
2321 "scope_v" := 'unit';
2322 "unit_id_v" := "unit_id_p";
2323 ELSIF
2324 "unit_id_p" ISNULL AND
2325 "area_id_p" NOTNULL AND
2326 "issue_id_p" ISNULL
2327 THEN
2328 "scope_v" := 'area';
2329 "area_id_v" := "area_id_p";
2330 SELECT "unit_id" INTO "unit_id_v"
2331 FROM "area" WHERE "id" = "area_id_v";
2332 ELSIF
2333 "unit_id_p" ISNULL AND
2334 "area_id_p" ISNULL AND
2335 "issue_id_p" NOTNULL
2336 THEN
2337 "scope_v" := 'issue';
2338 SELECT "area_id" INTO "area_id_v"
2339 FROM "issue" WHERE "id" = "issue_id_p";
2340 SELECT "unit_id" INTO "unit_id_v"
2341 FROM "area" WHERE "id" = "area_id_v";
2342 ELSE
2343 RAISE EXCEPTION 'Exactly one of unit_id_p, area_id_p, or issue_id_p must be NOTNULL.';
2344 END IF;
2345 "visited_member_ids" := '{}';
2346 "loop_member_id_v" := NULL;
2347 "output_rows" := '{}';
2348 "output_row"."index" := 0;
2349 "output_row"."member_id" := "member_id_p";
2350 "output_row"."member_valid" := TRUE;
2351 "output_row"."participation" := FALSE;
2352 "output_row"."overridden" := FALSE;
2353 "output_row"."disabled_out" := FALSE;
2354 "output_row"."scope_out" := NULL;
2355 LOOP
2356 IF "visited_member_ids" @> ARRAY["output_row"."member_id"] THEN
2357 "loop_member_id_v" := "output_row"."member_id";
2358 ELSE
2359 "visited_member_ids" :=
2360 "visited_member_ids" || "output_row"."member_id";
2361 END IF;
2362 IF "output_row"."participation" THEN
2363 "output_row"."overridden" := TRUE;
2364 END IF;
2365 "output_row"."scope_in" := "output_row"."scope_out";
2366 IF EXISTS (
2367 SELECT NULL FROM "member" JOIN "privilege"
2368 ON "privilege"."member_id" = "member"."id"
2369 AND "privilege"."unit_id" = "unit_id_v"
2370 WHERE "id" = "output_row"."member_id"
2371 AND "member"."active" AND "privilege"."voting_right"
2372 ) THEN
2373 IF "scope_v" = 'unit' THEN
2374 SELECT * INTO "delegation_row" FROM "delegation"
2375 WHERE "truster_id" = "output_row"."member_id"
2376 AND "unit_id" = "unit_id_v";
2377 ELSIF "scope_v" = 'area' THEN
2378 "output_row"."participation" := EXISTS (
2379 SELECT NULL FROM "membership"
2380 WHERE "area_id" = "area_id_p"
2381 AND "member_id" = "output_row"."member_id"
2382 );
2383 SELECT * INTO "delegation_row" FROM "delegation"
2384 WHERE "truster_id" = "output_row"."member_id"
2385 AND (
2386 "unit_id" = "unit_id_v" OR
2387 "area_id" = "area_id_v"
2389 ORDER BY "scope" DESC;
2390 ELSIF "scope_v" = 'issue' THEN
2391 "output_row"."participation" := EXISTS (
2392 SELECT NULL FROM "interest"
2393 WHERE "issue_id" = "issue_id_p"
2394 AND "member_id" = "output_row"."member_id"
2395 );
2396 SELECT * INTO "delegation_row" FROM "delegation"
2397 WHERE "truster_id" = "output_row"."member_id"
2398 AND (
2399 "unit_id" = "unit_id_v" OR
2400 "area_id" = "area_id_v" OR
2401 "issue_id" = "issue_id_p"
2403 ORDER BY "scope" DESC;
2404 END IF;
2405 ELSE
2406 "output_row"."member_valid" := FALSE;
2407 "output_row"."participation" := FALSE;
2408 "output_row"."scope_out" := NULL;
2409 "delegation_row" := ROW(NULL);
2410 END IF;
2411 IF
2412 "output_row"."member_id" = "member_id_p" AND
2413 "simulate_trustee_id_p" NOTNULL
2414 THEN
2415 "output_row"."scope_out" := "scope_v";
2416 "output_rows" := "output_rows" || "output_row";
2417 "output_row"."member_id" := "simulate_trustee_id_p";
2418 ELSIF "delegation_row"."trustee_id" NOTNULL THEN
2419 "output_row"."scope_out" := "delegation_row"."scope";
2420 "output_rows" := "output_rows" || "output_row";
2421 "output_row"."member_id" := "delegation_row"."trustee_id";
2422 ELSIF "delegation_row"."scope" NOTNULL THEN
2423 "output_row"."scope_out" := "delegation_row"."scope";
2424 "output_row"."disabled_out" := TRUE;
2425 "output_rows" := "output_rows" || "output_row";
2426 EXIT;
2427 ELSE
2428 "output_row"."scope_out" := NULL;
2429 "output_rows" := "output_rows" || "output_row";
2430 EXIT;
2431 END IF;
2432 EXIT WHEN "loop_member_id_v" NOTNULL;
2433 "output_row"."index" := "output_row"."index" + 1;
2434 END LOOP;
2435 "row_count" := array_upper("output_rows", 1);
2436 "i" := 1;
2437 "loop_v" := FALSE;
2438 LOOP
2439 "output_row" := "output_rows"["i"];
2440 EXIT WHEN "output_row" ISNULL; -- NOTE: ISNULL and NOT ... NOTNULL produce different results!
2441 IF "loop_v" THEN
2442 IF "i" + 1 = "row_count" THEN
2443 "output_row"."loop" := 'last';
2444 ELSIF "i" = "row_count" THEN
2445 "output_row"."loop" := 'repetition';
2446 ELSE
2447 "output_row"."loop" := 'intermediate';
2448 END IF;
2449 ELSIF "output_row"."member_id" = "loop_member_id_v" THEN
2450 "output_row"."loop" := 'first';
2451 "loop_v" := TRUE;
2452 END IF;
2453 IF "scope_v" = 'unit' THEN
2454 "output_row"."participation" := NULL;
2455 END IF;
2456 RETURN NEXT "output_row";
2457 "i" := "i" + 1;
2458 END LOOP;
2459 RETURN;
2460 END;
2461 $$;
2463 COMMENT ON FUNCTION "delegation_chain"
2464 ( "member"."id"%TYPE,
2465 "unit"."id"%TYPE,
2466 "area"."id"%TYPE,
2467 "issue"."id"%TYPE,
2468 "member"."id"%TYPE )
2469 IS 'Helper function for frontends to display delegation chains; Not part of internal voting logic';
2472 CREATE FUNCTION "delegation_chain"
2473 ( "member_id_p" "member"."id"%TYPE,
2474 "unit_id_p" "unit"."id"%TYPE,
2475 "area_id_p" "area"."id"%TYPE,
2476 "issue_id_p" "issue"."id"%TYPE )
2477 RETURNS SETOF "delegation_chain_row"
2478 LANGUAGE 'plpgsql' STABLE AS $$
2479 DECLARE
2480 "result_row" "delegation_chain_row";
2481 BEGIN
2482 FOR "result_row" IN
2483 SELECT * FROM "delegation_chain"(
2484 "member_id_p", "unit_id_p", "area_id_p", "issue_id_p", NULL
2486 LOOP
2487 RETURN NEXT "result_row";
2488 END LOOP;
2489 RETURN;
2490 END;
2491 $$;
2493 COMMENT ON FUNCTION "delegation_chain"
2494 ( "member"."id"%TYPE,
2495 "unit"."id"%TYPE,
2496 "area"."id"%TYPE,
2497 "issue"."id"%TYPE )
2498 IS 'Shortcut for "delegation_chain"(...) function where 4th parameter is null';
2502 ------------------------------
2503 -- Comparison by vote count --
2504 ------------------------------
2506 CREATE FUNCTION "vote_ratio"
2507 ( "positive_votes_p" "initiative"."positive_votes"%TYPE,
2508 "negative_votes_p" "initiative"."negative_votes"%TYPE )
2509 RETURNS FLOAT8
2510 LANGUAGE 'plpgsql' STABLE AS $$
2511 BEGIN
2512 IF "positive_votes_p" > 0 AND "negative_votes_p" > 0 THEN
2513 RETURN
2514 "positive_votes_p"::FLOAT8 /
2515 ("positive_votes_p" + "negative_votes_p")::FLOAT8;
2516 ELSIF "positive_votes_p" > 0 THEN
2517 RETURN "positive_votes_p";
2518 ELSIF "negative_votes_p" > 0 THEN
2519 RETURN 1 - "negative_votes_p";
2520 ELSE
2521 RETURN 0.5;
2522 END IF;
2523 END;
2524 $$;
2526 COMMENT ON FUNCTION "vote_ratio"
2527 ( "initiative"."positive_votes"%TYPE,
2528 "initiative"."negative_votes"%TYPE )
2529 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.';
2533 ------------------------------------------------
2534 -- Locking for snapshots and voting procedure --
2535 ------------------------------------------------
2538 CREATE FUNCTION "share_row_lock_issue_trigger"()
2539 RETURNS TRIGGER
2540 LANGUAGE 'plpgsql' VOLATILE AS $$
2541 BEGIN
2542 IF TG_OP = 'UPDATE' OR TG_OP = 'DELETE' THEN
2543 PERFORM NULL FROM "issue" WHERE "id" = OLD."issue_id" FOR SHARE;
2544 END IF;
2545 IF TG_OP = 'INSERT' OR TG_OP = 'UPDATE' THEN
2546 PERFORM NULL FROM "issue" WHERE "id" = NEW."issue_id" FOR SHARE;
2547 RETURN NEW;
2548 ELSE
2549 RETURN OLD;
2550 END IF;
2551 END;
2552 $$;
2554 COMMENT ON FUNCTION "share_row_lock_issue_trigger"() IS 'Implementation of triggers "share_row_lock_issue" on multiple tables';
2557 CREATE FUNCTION "share_row_lock_issue_via_initiative_trigger"()
2558 RETURNS TRIGGER
2559 LANGUAGE 'plpgsql' VOLATILE AS $$
2560 BEGIN
2561 IF TG_OP = 'UPDATE' OR TG_OP = 'DELETE' THEN
2562 PERFORM NULL FROM "issue"
2563 JOIN "initiative" ON "issue"."id" = "initiative"."issue_id"
2564 WHERE "initiative"."id" = OLD."initiative_id"
2565 FOR SHARE OF "issue";
2566 END IF;
2567 IF TG_OP = 'INSERT' OR TG_OP = 'UPDATE' THEN
2568 PERFORM NULL FROM "issue"
2569 JOIN "initiative" ON "issue"."id" = "initiative"."issue_id"
2570 WHERE "initiative"."id" = NEW."initiative_id"
2571 FOR SHARE OF "issue";
2572 RETURN NEW;
2573 ELSE
2574 RETURN OLD;
2575 END IF;
2576 END;
2577 $$;
2579 COMMENT ON FUNCTION "share_row_lock_issue_trigger"() IS 'Implementation of trigger "share_row_lock_issue_via_initiative" on table "opinion"';
2582 CREATE TRIGGER "share_row_lock_issue"
2583 BEFORE INSERT OR UPDATE OR DELETE ON "initiative"
2584 FOR EACH ROW EXECUTE PROCEDURE
2585 "share_row_lock_issue_trigger"();
2587 CREATE TRIGGER "share_row_lock_issue"
2588 BEFORE INSERT OR UPDATE OR DELETE ON "interest"
2589 FOR EACH ROW EXECUTE PROCEDURE
2590 "share_row_lock_issue_trigger"();
2592 CREATE TRIGGER "share_row_lock_issue"
2593 BEFORE INSERT OR UPDATE OR DELETE ON "supporter"
2594 FOR EACH ROW EXECUTE PROCEDURE
2595 "share_row_lock_issue_trigger"();
2597 CREATE TRIGGER "share_row_lock_issue_via_initiative"
2598 BEFORE INSERT OR UPDATE OR DELETE ON "opinion"
2599 FOR EACH ROW EXECUTE PROCEDURE
2600 "share_row_lock_issue_via_initiative_trigger"();
2602 CREATE TRIGGER "share_row_lock_issue"
2603 BEFORE INSERT OR UPDATE OR DELETE ON "direct_voter"
2604 FOR EACH ROW EXECUTE PROCEDURE
2605 "share_row_lock_issue_trigger"();
2607 CREATE TRIGGER "share_row_lock_issue"
2608 BEFORE INSERT OR UPDATE OR DELETE ON "delegating_voter"
2609 FOR EACH ROW EXECUTE PROCEDURE
2610 "share_row_lock_issue_trigger"();
2612 CREATE TRIGGER "share_row_lock_issue"
2613 BEFORE INSERT OR UPDATE OR DELETE ON "vote"
2614 FOR EACH ROW EXECUTE PROCEDURE
2615 "share_row_lock_issue_trigger"();
2617 COMMENT ON TRIGGER "share_row_lock_issue" ON "initiative" IS 'See "lock_issue" function';
2618 COMMENT ON TRIGGER "share_row_lock_issue" ON "interest" IS 'See "lock_issue" function';
2619 COMMENT ON TRIGGER "share_row_lock_issue" ON "supporter" IS 'See "lock_issue" function';
2620 COMMENT ON TRIGGER "share_row_lock_issue_via_initiative" ON "opinion" IS 'See "lock_issue" function';
2621 COMMENT ON TRIGGER "share_row_lock_issue" ON "direct_voter" IS 'See "lock_issue" function';
2622 COMMENT ON TRIGGER "share_row_lock_issue" ON "delegating_voter" IS 'See "lock_issue" function';
2623 COMMENT ON TRIGGER "share_row_lock_issue" ON "vote" IS 'See "lock_issue" function';
2626 CREATE FUNCTION "lock_issue"
2627 ( "issue_id_p" "issue"."id"%TYPE )
2628 RETURNS VOID
2629 LANGUAGE 'plpgsql' VOLATILE AS $$
2630 BEGIN
2631 LOCK TABLE "member" IN SHARE MODE;
2632 LOCK TABLE "privilege" IN SHARE MODE;
2633 LOCK TABLE "membership" IN SHARE MODE;
2634 LOCK TABLE "policy" IN SHARE MODE;
2635 PERFORM NULL FROM "issue" WHERE "id" = "issue_id_p" FOR UPDATE;
2636 -- NOTE: The row-level exclusive lock in combination with the
2637 -- share_row_lock_issue(_via_initiative)_trigger functions (which
2638 -- acquire a row-level share lock on the issue) ensure that no data
2639 -- is changed, which could affect calculation of snapshots or
2640 -- counting of votes. Table "delegation" must be table-level-locked,
2641 -- as it also contains issue- and global-scope delegations.
2642 LOCK TABLE "delegation" IN SHARE MODE;
2643 LOCK TABLE "direct_population_snapshot" IN EXCLUSIVE MODE;
2644 LOCK TABLE "delegating_population_snapshot" IN EXCLUSIVE MODE;
2645 LOCK TABLE "direct_interest_snapshot" IN EXCLUSIVE MODE;
2646 LOCK TABLE "delegating_interest_snapshot" IN EXCLUSIVE MODE;
2647 LOCK TABLE "direct_supporter_snapshot" IN EXCLUSIVE MODE;
2648 RETURN;
2649 END;
2650 $$;
2652 COMMENT ON FUNCTION "lock_issue"
2653 ( "issue"."id"%TYPE )
2654 IS 'Locks the issue and all other data which is used for calculating snapshots or counting votes.';
2658 ------------------------------------------------------------------------
2659 -- Regular tasks, except calculcation of snapshots and voting results --
2660 ------------------------------------------------------------------------
2662 CREATE FUNCTION "check_last_login"()
2663 RETURNS VOID
2664 LANGUAGE 'plpgsql' VOLATILE AS $$
2665 DECLARE
2666 "system_setting_row" "system_setting"%ROWTYPE;
2667 BEGIN
2668 SELECT * INTO "system_setting_row" FROM "system_setting";
2669 LOCK TABLE "member" IN SHARE ROW EXCLUSIVE MODE;
2670 UPDATE "member" SET "last_login_public" = "last_login"::date
2671 FROM (
2672 SELECT DISTINCT "member"."id"
2673 FROM "member" LEFT JOIN "member_history"
2674 ON "member"."id" = "member_history"."member_id"
2675 WHERE "member"."last_login"::date < 'today' OR (
2676 "member_history"."until"::date >= 'today' AND
2677 "member_history"."active" = FALSE AND "member"."active" = TRUE
2679 ) AS "subquery"
2680 WHERE "member"."id" = "subquery"."id";
2681 IF "system_setting_row"."member_ttl" NOTNULL THEN
2682 UPDATE "member" SET "active" = FALSE
2683 WHERE "active" = TRUE
2684 AND "last_login"::date < 'today'
2685 AND "last_login_public" <
2686 (now() - "system_setting_row"."member_ttl")::date;
2687 END IF;
2688 RETURN;
2689 END;
2690 $$;
2692 COMMENT ON FUNCTION "check_last_login"() IS 'Updates "last_login_public" field, which contains the date but not the time of the last login, and deactivates members who do not login for the time specified in "system_setting"."member_ttl". For privacy reasons this function does not update "last_login_public", if the last login of a member has been today (except when member was reactivated today).';
2695 CREATE FUNCTION "calculate_member_counts"()
2696 RETURNS VOID
2697 LANGUAGE 'plpgsql' VOLATILE AS $$
2698 BEGIN
2699 LOCK TABLE "member" IN SHARE MODE;
2700 LOCK TABLE "member_count" IN EXCLUSIVE MODE;
2701 LOCK TABLE "unit" IN EXCLUSIVE MODE;
2702 LOCK TABLE "area" IN EXCLUSIVE MODE;
2703 LOCK TABLE "privilege" IN SHARE MODE;
2704 LOCK TABLE "membership" IN SHARE MODE;
2705 DELETE FROM "member_count";
2706 INSERT INTO "member_count" ("total_count")
2707 SELECT "total_count" FROM "member_count_view";
2708 UPDATE "unit" SET "member_count" = "view"."member_count"
2709 FROM "unit_member_count" AS "view"
2710 WHERE "view"."unit_id" = "unit"."id";
2711 UPDATE "area" SET
2712 "direct_member_count" = "view"."direct_member_count",
2713 "member_weight" = "view"."member_weight",
2714 "autoreject_weight" = "view"."autoreject_weight"
2715 FROM "area_member_count" AS "view"
2716 WHERE "view"."area_id" = "area"."id";
2717 RETURN;
2718 END;
2719 $$;
2721 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"';
2725 ------------------------------
2726 -- Calculation of snapshots --
2727 ------------------------------
2729 CREATE FUNCTION "weight_of_added_delegations_for_population_snapshot"
2730 ( "issue_id_p" "issue"."id"%TYPE,
2731 "member_id_p" "member"."id"%TYPE,
2732 "delegate_member_ids_p" "delegating_population_snapshot"."delegate_member_ids"%TYPE )
2733 RETURNS "direct_population_snapshot"."weight"%TYPE
2734 LANGUAGE 'plpgsql' VOLATILE AS $$
2735 DECLARE
2736 "issue_delegation_row" "issue_delegation"%ROWTYPE;
2737 "delegate_member_ids_v" "delegating_population_snapshot"."delegate_member_ids"%TYPE;
2738 "weight_v" INT4;
2739 "sub_weight_v" INT4;
2740 BEGIN
2741 "weight_v" := 0;
2742 FOR "issue_delegation_row" IN
2743 SELECT * FROM "issue_delegation"
2744 WHERE "trustee_id" = "member_id_p"
2745 AND "issue_id" = "issue_id_p"
2746 LOOP
2747 IF NOT EXISTS (
2748 SELECT NULL FROM "direct_population_snapshot"
2749 WHERE "issue_id" = "issue_id_p"
2750 AND "event" = 'periodic'
2751 AND "member_id" = "issue_delegation_row"."truster_id"
2752 ) AND NOT EXISTS (
2753 SELECT NULL FROM "delegating_population_snapshot"
2754 WHERE "issue_id" = "issue_id_p"
2755 AND "event" = 'periodic'
2756 AND "member_id" = "issue_delegation_row"."truster_id"
2757 ) THEN
2758 "delegate_member_ids_v" :=
2759 "member_id_p" || "delegate_member_ids_p";
2760 INSERT INTO "delegating_population_snapshot" (
2761 "issue_id",
2762 "event",
2763 "member_id",
2764 "scope",
2765 "delegate_member_ids"
2766 ) VALUES (
2767 "issue_id_p",
2768 'periodic',
2769 "issue_delegation_row"."truster_id",
2770 "issue_delegation_row"."scope",
2771 "delegate_member_ids_v"
2772 );
2773 "sub_weight_v" := 1 +
2774 "weight_of_added_delegations_for_population_snapshot"(
2775 "issue_id_p",
2776 "issue_delegation_row"."truster_id",
2777 "delegate_member_ids_v"
2778 );
2779 UPDATE "delegating_population_snapshot"
2780 SET "weight" = "sub_weight_v"
2781 WHERE "issue_id" = "issue_id_p"
2782 AND "event" = 'periodic'
2783 AND "member_id" = "issue_delegation_row"."truster_id";
2784 "weight_v" := "weight_v" + "sub_weight_v";
2785 END IF;
2786 END LOOP;
2787 RETURN "weight_v";
2788 END;
2789 $$;
2791 COMMENT ON FUNCTION "weight_of_added_delegations_for_population_snapshot"
2792 ( "issue"."id"%TYPE,
2793 "member"."id"%TYPE,
2794 "delegating_population_snapshot"."delegate_member_ids"%TYPE )
2795 IS 'Helper function for "create_population_snapshot" function';
2798 CREATE FUNCTION "create_population_snapshot"
2799 ( "issue_id_p" "issue"."id"%TYPE )
2800 RETURNS VOID
2801 LANGUAGE 'plpgsql' VOLATILE AS $$
2802 DECLARE
2803 "member_id_v" "member"."id"%TYPE;
2804 BEGIN
2805 DELETE FROM "direct_population_snapshot"
2806 WHERE "issue_id" = "issue_id_p"
2807 AND "event" = 'periodic';
2808 DELETE FROM "delegating_population_snapshot"
2809 WHERE "issue_id" = "issue_id_p"
2810 AND "event" = 'periodic';
2811 INSERT INTO "direct_population_snapshot"
2812 ("issue_id", "event", "member_id")
2813 SELECT
2814 "issue_id_p" AS "issue_id",
2815 'periodic'::"snapshot_event" AS "event",
2816 "member"."id" AS "member_id"
2817 FROM "issue"
2818 JOIN "area" ON "issue"."area_id" = "area"."id"
2819 JOIN "membership" ON "area"."id" = "membership"."area_id"
2820 JOIN "member" ON "membership"."member_id" = "member"."id"
2821 JOIN "privilege"
2822 ON "privilege"."unit_id" = "area"."unit_id"
2823 AND "privilege"."member_id" = "member"."id"
2824 WHERE "issue"."id" = "issue_id_p"
2825 AND "member"."active" AND "privilege"."voting_right"
2826 UNION
2827 SELECT
2828 "issue_id_p" AS "issue_id",
2829 'periodic'::"snapshot_event" AS "event",
2830 "member"."id" AS "member_id"
2831 FROM "issue"
2832 JOIN "area" ON "issue"."area_id" = "area"."id"
2833 JOIN "interest" ON "issue"."id" = "interest"."issue_id"
2834 JOIN "member" ON "interest"."member_id" = "member"."id"
2835 JOIN "privilege"
2836 ON "privilege"."unit_id" = "area"."unit_id"
2837 AND "privilege"."member_id" = "member"."id"
2838 WHERE "issue"."id" = "issue_id_p"
2839 AND "member"."active" AND "privilege"."voting_right";
2840 FOR "member_id_v" IN
2841 SELECT "member_id" FROM "direct_population_snapshot"
2842 WHERE "issue_id" = "issue_id_p"
2843 AND "event" = 'periodic'
2844 LOOP
2845 UPDATE "direct_population_snapshot" SET
2846 "weight" = 1 +
2847 "weight_of_added_delegations_for_population_snapshot"(
2848 "issue_id_p",
2849 "member_id_v",
2850 '{}'
2852 WHERE "issue_id" = "issue_id_p"
2853 AND "event" = 'periodic'
2854 AND "member_id" = "member_id_v";
2855 END LOOP;
2856 RETURN;
2857 END;
2858 $$;
2860 COMMENT ON FUNCTION "create_population_snapshot"
2861 ( "issue"."id"%TYPE )
2862 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.';
2865 CREATE FUNCTION "weight_of_added_delegations_for_interest_snapshot"
2866 ( "issue_id_p" "issue"."id"%TYPE,
2867 "member_id_p" "member"."id"%TYPE,
2868 "delegate_member_ids_p" "delegating_interest_snapshot"."delegate_member_ids"%TYPE )
2869 RETURNS "direct_interest_snapshot"."weight"%TYPE
2870 LANGUAGE 'plpgsql' VOLATILE AS $$
2871 DECLARE
2872 "issue_delegation_row" "issue_delegation"%ROWTYPE;
2873 "delegate_member_ids_v" "delegating_interest_snapshot"."delegate_member_ids"%TYPE;
2874 "weight_v" INT4;
2875 "sub_weight_v" INT4;
2876 BEGIN
2877 "weight_v" := 0;
2878 FOR "issue_delegation_row" IN
2879 SELECT * FROM "issue_delegation"
2880 WHERE "trustee_id" = "member_id_p"
2881 AND "issue_id" = "issue_id_p"
2882 LOOP
2883 IF NOT EXISTS (
2884 SELECT NULL FROM "direct_interest_snapshot"
2885 WHERE "issue_id" = "issue_id_p"
2886 AND "event" = 'periodic'
2887 AND "member_id" = "issue_delegation_row"."truster_id"
2888 ) AND NOT EXISTS (
2889 SELECT NULL FROM "delegating_interest_snapshot"
2890 WHERE "issue_id" = "issue_id_p"
2891 AND "event" = 'periodic'
2892 AND "member_id" = "issue_delegation_row"."truster_id"
2893 ) THEN
2894 "delegate_member_ids_v" :=
2895 "member_id_p" || "delegate_member_ids_p";
2896 INSERT INTO "delegating_interest_snapshot" (
2897 "issue_id",
2898 "event",
2899 "member_id",
2900 "scope",
2901 "delegate_member_ids"
2902 ) VALUES (
2903 "issue_id_p",
2904 'periodic',
2905 "issue_delegation_row"."truster_id",
2906 "issue_delegation_row"."scope",
2907 "delegate_member_ids_v"
2908 );
2909 "sub_weight_v" := 1 +
2910 "weight_of_added_delegations_for_interest_snapshot"(
2911 "issue_id_p",
2912 "issue_delegation_row"."truster_id",
2913 "delegate_member_ids_v"
2914 );
2915 UPDATE "delegating_interest_snapshot"
2916 SET "weight" = "sub_weight_v"
2917 WHERE "issue_id" = "issue_id_p"
2918 AND "event" = 'periodic'
2919 AND "member_id" = "issue_delegation_row"."truster_id";
2920 "weight_v" := "weight_v" + "sub_weight_v";
2921 END IF;
2922 END LOOP;
2923 RETURN "weight_v";
2924 END;
2925 $$;
2927 COMMENT ON FUNCTION "weight_of_added_delegations_for_interest_snapshot"
2928 ( "issue"."id"%TYPE,
2929 "member"."id"%TYPE,
2930 "delegating_interest_snapshot"."delegate_member_ids"%TYPE )
2931 IS 'Helper function for "create_interest_snapshot" function';
2934 CREATE FUNCTION "create_interest_snapshot"
2935 ( "issue_id_p" "issue"."id"%TYPE )
2936 RETURNS VOID
2937 LANGUAGE 'plpgsql' VOLATILE AS $$
2938 DECLARE
2939 "member_id_v" "member"."id"%TYPE;
2940 BEGIN
2941 DELETE FROM "direct_interest_snapshot"
2942 WHERE "issue_id" = "issue_id_p"
2943 AND "event" = 'periodic';
2944 DELETE FROM "delegating_interest_snapshot"
2945 WHERE "issue_id" = "issue_id_p"
2946 AND "event" = 'periodic';
2947 DELETE FROM "direct_supporter_snapshot"
2948 WHERE "issue_id" = "issue_id_p"
2949 AND "event" = 'periodic';
2950 INSERT INTO "direct_interest_snapshot"
2951 ("issue_id", "event", "member_id", "voting_requested")
2952 SELECT
2953 "issue_id_p" AS "issue_id",
2954 'periodic' AS "event",
2955 "member"."id" AS "member_id",
2956 "interest"."voting_requested"
2957 FROM "issue"
2958 JOIN "area" ON "issue"."area_id" = "area"."id"
2959 JOIN "interest" ON "issue"."id" = "interest"."issue_id"
2960 JOIN "member" ON "interest"."member_id" = "member"."id"
2961 JOIN "privilege"
2962 ON "privilege"."unit_id" = "area"."unit_id"
2963 AND "privilege"."member_id" = "member"."id"
2964 WHERE "issue"."id" = "issue_id_p"
2965 AND "member"."active" AND "privilege"."voting_right";
2966 FOR "member_id_v" IN
2967 SELECT "member_id" FROM "direct_interest_snapshot"
2968 WHERE "issue_id" = "issue_id_p"
2969 AND "event" = 'periodic'
2970 LOOP
2971 UPDATE "direct_interest_snapshot" SET
2972 "weight" = 1 +
2973 "weight_of_added_delegations_for_interest_snapshot"(
2974 "issue_id_p",
2975 "member_id_v",
2976 '{}'
2978 WHERE "issue_id" = "issue_id_p"
2979 AND "event" = 'periodic'
2980 AND "member_id" = "member_id_v";
2981 END LOOP;
2982 INSERT INTO "direct_supporter_snapshot"
2983 ( "issue_id", "initiative_id", "event", "member_id",
2984 "informed", "satisfied" )
2985 SELECT
2986 "issue_id_p" AS "issue_id",
2987 "initiative"."id" AS "initiative_id",
2988 'periodic' AS "event",
2989 "supporter"."member_id" AS "member_id",
2990 "supporter"."draft_id" = "current_draft"."id" AS "informed",
2991 NOT EXISTS (
2992 SELECT NULL FROM "critical_opinion"
2993 WHERE "initiative_id" = "initiative"."id"
2994 AND "member_id" = "supporter"."member_id"
2995 ) AS "satisfied"
2996 FROM "initiative"
2997 JOIN "supporter"
2998 ON "supporter"."initiative_id" = "initiative"."id"
2999 JOIN "current_draft"
3000 ON "initiative"."id" = "current_draft"."initiative_id"
3001 JOIN "direct_interest_snapshot"
3002 ON "supporter"."member_id" = "direct_interest_snapshot"."member_id"
3003 AND "initiative"."issue_id" = "direct_interest_snapshot"."issue_id"
3004 AND "event" = 'periodic'
3005 WHERE "initiative"."issue_id" = "issue_id_p";
3006 RETURN;
3007 END;
3008 $$;
3010 COMMENT ON FUNCTION "create_interest_snapshot"
3011 ( "issue"."id"%TYPE )
3012 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.';
3015 CREATE FUNCTION "create_snapshot"
3016 ( "issue_id_p" "issue"."id"%TYPE )
3017 RETURNS VOID
3018 LANGUAGE 'plpgsql' VOLATILE AS $$
3019 DECLARE
3020 "initiative_id_v" "initiative"."id"%TYPE;
3021 "suggestion_id_v" "suggestion"."id"%TYPE;
3022 BEGIN
3023 PERFORM "lock_issue"("issue_id_p");
3024 PERFORM "create_population_snapshot"("issue_id_p");
3025 PERFORM "create_interest_snapshot"("issue_id_p");
3026 UPDATE "issue" SET
3027 "snapshot" = now(),
3028 "latest_snapshot_event" = 'periodic',
3029 "population" = (
3030 SELECT coalesce(sum("weight"), 0)
3031 FROM "direct_population_snapshot"
3032 WHERE "issue_id" = "issue_id_p"
3033 AND "event" = 'periodic'
3034 ),
3035 "vote_now" = (
3036 SELECT coalesce(sum("weight"), 0)
3037 FROM "direct_interest_snapshot"
3038 WHERE "issue_id" = "issue_id_p"
3039 AND "event" = 'periodic'
3040 AND "voting_requested" = TRUE
3041 ),
3042 "vote_later" = (
3043 SELECT coalesce(sum("weight"), 0)
3044 FROM "direct_interest_snapshot"
3045 WHERE "issue_id" = "issue_id_p"
3046 AND "event" = 'periodic'
3047 AND "voting_requested" = FALSE
3049 WHERE "id" = "issue_id_p";
3050 FOR "initiative_id_v" IN
3051 SELECT "id" FROM "initiative" WHERE "issue_id" = "issue_id_p"
3052 LOOP
3053 UPDATE "initiative" SET
3054 "supporter_count" = (
3055 SELECT coalesce(sum("di"."weight"), 0)
3056 FROM "direct_interest_snapshot" AS "di"
3057 JOIN "direct_supporter_snapshot" AS "ds"
3058 ON "di"."member_id" = "ds"."member_id"
3059 WHERE "di"."issue_id" = "issue_id_p"
3060 AND "di"."event" = 'periodic'
3061 AND "ds"."initiative_id" = "initiative_id_v"
3062 AND "ds"."event" = 'periodic'
3063 ),
3064 "informed_supporter_count" = (
3065 SELECT coalesce(sum("di"."weight"), 0)
3066 FROM "direct_interest_snapshot" AS "di"
3067 JOIN "direct_supporter_snapshot" AS "ds"
3068 ON "di"."member_id" = "ds"."member_id"
3069 WHERE "di"."issue_id" = "issue_id_p"
3070 AND "di"."event" = 'periodic'
3071 AND "ds"."initiative_id" = "initiative_id_v"
3072 AND "ds"."event" = 'periodic'
3073 AND "ds"."informed"
3074 ),
3075 "satisfied_supporter_count" = (
3076 SELECT coalesce(sum("di"."weight"), 0)
3077 FROM "direct_interest_snapshot" AS "di"
3078 JOIN "direct_supporter_snapshot" AS "ds"
3079 ON "di"."member_id" = "ds"."member_id"
3080 WHERE "di"."issue_id" = "issue_id_p"
3081 AND "di"."event" = 'periodic'
3082 AND "ds"."initiative_id" = "initiative_id_v"
3083 AND "ds"."event" = 'periodic'
3084 AND "ds"."satisfied"
3085 ),
3086 "satisfied_informed_supporter_count" = (
3087 SELECT coalesce(sum("di"."weight"), 0)
3088 FROM "direct_interest_snapshot" AS "di"
3089 JOIN "direct_supporter_snapshot" AS "ds"
3090 ON "di"."member_id" = "ds"."member_id"
3091 WHERE "di"."issue_id" = "issue_id_p"
3092 AND "di"."event" = 'periodic'
3093 AND "ds"."initiative_id" = "initiative_id_v"
3094 AND "ds"."event" = 'periodic'
3095 AND "ds"."informed"
3096 AND "ds"."satisfied"
3098 WHERE "id" = "initiative_id_v";
3099 FOR "suggestion_id_v" IN
3100 SELECT "id" FROM "suggestion"
3101 WHERE "initiative_id" = "initiative_id_v"
3102 LOOP
3103 UPDATE "suggestion" SET
3104 "minus2_unfulfilled_count" = (
3105 SELECT coalesce(sum("snapshot"."weight"), 0)
3106 FROM "issue" CROSS JOIN "opinion"
3107 JOIN "direct_interest_snapshot" AS "snapshot"
3108 ON "snapshot"."issue_id" = "issue"."id"
3109 AND "snapshot"."event" = "issue"."latest_snapshot_event"
3110 AND "snapshot"."member_id" = "opinion"."member_id"
3111 WHERE "issue"."id" = "issue_id_p"
3112 AND "opinion"."suggestion_id" = "suggestion_id_v"
3113 AND "opinion"."degree" = -2
3114 AND "opinion"."fulfilled" = FALSE
3115 ),
3116 "minus2_fulfilled_count" = (
3117 SELECT coalesce(sum("snapshot"."weight"), 0)
3118 FROM "issue" CROSS JOIN "opinion"
3119 JOIN "direct_interest_snapshot" AS "snapshot"
3120 ON "snapshot"."issue_id" = "issue"."id"
3121 AND "snapshot"."event" = "issue"."latest_snapshot_event"
3122 AND "snapshot"."member_id" = "opinion"."member_id"
3123 WHERE "issue"."id" = "issue_id_p"
3124 AND "opinion"."suggestion_id" = "suggestion_id_v"
3125 AND "opinion"."degree" = -2
3126 AND "opinion"."fulfilled" = TRUE
3127 ),
3128 "minus1_unfulfilled_count" = (
3129 SELECT coalesce(sum("snapshot"."weight"), 0)
3130 FROM "issue" CROSS JOIN "opinion"
3131 JOIN "direct_interest_snapshot" AS "snapshot"
3132 ON "snapshot"."issue_id" = "issue"."id"
3133 AND "snapshot"."event" = "issue"."latest_snapshot_event"
3134 AND "snapshot"."member_id" = "opinion"."member_id"
3135 WHERE "issue"."id" = "issue_id_p"
3136 AND "opinion"."suggestion_id" = "suggestion_id_v"
3137 AND "opinion"."degree" = -1
3138 AND "opinion"."fulfilled" = FALSE
3139 ),
3140 "minus1_fulfilled_count" = (
3141 SELECT coalesce(sum("snapshot"."weight"), 0)
3142 FROM "issue" CROSS JOIN "opinion"
3143 JOIN "direct_interest_snapshot" AS "snapshot"
3144 ON "snapshot"."issue_id" = "issue"."id"
3145 AND "snapshot"."event" = "issue"."latest_snapshot_event"
3146 AND "snapshot"."member_id" = "opinion"."member_id"
3147 WHERE "issue"."id" = "issue_id_p"
3148 AND "opinion"."suggestion_id" = "suggestion_id_v"
3149 AND "opinion"."degree" = -1
3150 AND "opinion"."fulfilled" = TRUE
3151 ),
3152 "plus1_unfulfilled_count" = (
3153 SELECT coalesce(sum("snapshot"."weight"), 0)
3154 FROM "issue" CROSS JOIN "opinion"
3155 JOIN "direct_interest_snapshot" AS "snapshot"
3156 ON "snapshot"."issue_id" = "issue"."id"
3157 AND "snapshot"."event" = "issue"."latest_snapshot_event"
3158 AND "snapshot"."member_id" = "opinion"."member_id"
3159 WHERE "issue"."id" = "issue_id_p"
3160 AND "opinion"."suggestion_id" = "suggestion_id_v"
3161 AND "opinion"."degree" = 1
3162 AND "opinion"."fulfilled" = FALSE
3163 ),
3164 "plus1_fulfilled_count" = (
3165 SELECT coalesce(sum("snapshot"."weight"), 0)
3166 FROM "issue" CROSS JOIN "opinion"
3167 JOIN "direct_interest_snapshot" AS "snapshot"
3168 ON "snapshot"."issue_id" = "issue"."id"
3169 AND "snapshot"."event" = "issue"."latest_snapshot_event"
3170 AND "snapshot"."member_id" = "opinion"."member_id"
3171 WHERE "issue"."id" = "issue_id_p"
3172 AND "opinion"."suggestion_id" = "suggestion_id_v"
3173 AND "opinion"."degree" = 1
3174 AND "opinion"."fulfilled" = TRUE
3175 ),
3176 "plus2_unfulfilled_count" = (
3177 SELECT coalesce(sum("snapshot"."weight"), 0)
3178 FROM "issue" CROSS JOIN "opinion"
3179 JOIN "direct_interest_snapshot" AS "snapshot"
3180 ON "snapshot"."issue_id" = "issue"."id"
3181 AND "snapshot"."event" = "issue"."latest_snapshot_event"
3182 AND "snapshot"."member_id" = "opinion"."member_id"
3183 WHERE "issue"."id" = "issue_id_p"
3184 AND "opinion"."suggestion_id" = "suggestion_id_v"
3185 AND "opinion"."degree" = 2
3186 AND "opinion"."fulfilled" = FALSE
3187 ),
3188 "plus2_fulfilled_count" = (
3189 SELECT coalesce(sum("snapshot"."weight"), 0)
3190 FROM "issue" CROSS JOIN "opinion"
3191 JOIN "direct_interest_snapshot" AS "snapshot"
3192 ON "snapshot"."issue_id" = "issue"."id"
3193 AND "snapshot"."event" = "issue"."latest_snapshot_event"
3194 AND "snapshot"."member_id" = "opinion"."member_id"
3195 WHERE "issue"."id" = "issue_id_p"
3196 AND "opinion"."suggestion_id" = "suggestion_id_v"
3197 AND "opinion"."degree" = 2
3198 AND "opinion"."fulfilled" = TRUE
3200 WHERE "suggestion"."id" = "suggestion_id_v";
3201 END LOOP;
3202 END LOOP;
3203 RETURN;
3204 END;
3205 $$;
3207 COMMENT ON FUNCTION "create_snapshot"
3208 ( "issue"."id"%TYPE )
3209 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.';
3212 CREATE FUNCTION "set_snapshot_event"
3213 ( "issue_id_p" "issue"."id"%TYPE,
3214 "event_p" "snapshot_event" )
3215 RETURNS VOID
3216 LANGUAGE 'plpgsql' VOLATILE AS $$
3217 DECLARE
3218 "event_v" "issue"."latest_snapshot_event"%TYPE;
3219 BEGIN
3220 SELECT "latest_snapshot_event" INTO "event_v" FROM "issue"
3221 WHERE "id" = "issue_id_p" FOR UPDATE;
3222 UPDATE "issue" SET "latest_snapshot_event" = "event_p"
3223 WHERE "id" = "issue_id_p";
3224 UPDATE "direct_population_snapshot" SET "event" = "event_p"
3225 WHERE "issue_id" = "issue_id_p" AND "event" = "event_v";
3226 UPDATE "delegating_population_snapshot" SET "event" = "event_p"
3227 WHERE "issue_id" = "issue_id_p" AND "event" = "event_v";
3228 UPDATE "direct_interest_snapshot" SET "event" = "event_p"
3229 WHERE "issue_id" = "issue_id_p" AND "event" = "event_v";
3230 UPDATE "delegating_interest_snapshot" SET "event" = "event_p"
3231 WHERE "issue_id" = "issue_id_p" AND "event" = "event_v";
3232 UPDATE "direct_supporter_snapshot" SET "event" = "event_p"
3233 WHERE "issue_id" = "issue_id_p" AND "event" = "event_v";
3234 RETURN;
3235 END;
3236 $$;
3238 COMMENT ON FUNCTION "set_snapshot_event"
3239 ( "issue"."id"%TYPE,
3240 "snapshot_event" )
3241 IS 'Change "event" attribute of the previous ''periodic'' snapshot';
3245 ---------------------
3246 -- Freezing issues --
3247 ---------------------
3249 CREATE FUNCTION "freeze_after_snapshot"
3250 ( "issue_id_p" "issue"."id"%TYPE )
3251 RETURNS VOID
3252 LANGUAGE 'plpgsql' VOLATILE AS $$
3253 DECLARE
3254 "issue_row" "issue"%ROWTYPE;
3255 "policy_row" "policy"%ROWTYPE;
3256 "initiative_row" "initiative"%ROWTYPE;
3257 BEGIN
3258 SELECT * INTO "issue_row" FROM "issue" WHERE "id" = "issue_id_p";
3259 SELECT * INTO "policy_row"
3260 FROM "policy" WHERE "id" = "issue_row"."policy_id";
3261 PERFORM "set_snapshot_event"("issue_id_p", 'full_freeze');
3262 FOR "initiative_row" IN
3263 SELECT * FROM "initiative"
3264 WHERE "issue_id" = "issue_id_p" AND "revoked" ISNULL
3265 LOOP
3266 IF
3267 "initiative_row"."satisfied_supporter_count" > 0 AND
3268 "initiative_row"."satisfied_supporter_count" *
3269 "policy_row"."initiative_quorum_den" >=
3270 "issue_row"."population" * "policy_row"."initiative_quorum_num"
3271 THEN
3272 UPDATE "initiative" SET "admitted" = TRUE
3273 WHERE "id" = "initiative_row"."id";
3274 ELSE
3275 UPDATE "initiative" SET "admitted" = FALSE
3276 WHERE "id" = "initiative_row"."id";
3277 END IF;
3278 END LOOP;
3279 IF EXISTS (
3280 SELECT NULL FROM "initiative"
3281 WHERE "issue_id" = "issue_id_p" AND "admitted" = TRUE
3282 ) THEN
3283 UPDATE "issue" SET
3284 "state" = 'voting',
3285 "accepted" = coalesce("accepted", now()),
3286 "half_frozen" = coalesce("half_frozen", now()),
3287 "fully_frozen" = now()
3288 WHERE "id" = "issue_id_p";
3289 ELSE
3290 UPDATE "issue" SET
3291 "state" = 'canceled_no_initiative_admitted',
3292 "accepted" = coalesce("accepted", now()),
3293 "half_frozen" = coalesce("half_frozen", now()),
3294 "fully_frozen" = now(),
3295 "closed" = now(),
3296 "ranks_available" = TRUE
3297 WHERE "id" = "issue_id_p";
3298 -- NOTE: The following DELETE statements have effect only when
3299 -- issue state has been manipulated
3300 DELETE FROM "direct_voter" WHERE "issue_id" = "issue_id_p";
3301 DELETE FROM "delegating_voter" WHERE "issue_id" = "issue_id_p";
3302 DELETE FROM "battle" WHERE "issue_id" = "issue_id_p";
3303 END IF;
3304 RETURN;
3305 END;
3306 $$;
3308 COMMENT ON FUNCTION "freeze_after_snapshot"
3309 ( "issue"."id"%TYPE )
3310 IS 'This function freezes an issue (fully) and starts voting, but must only be called when "create_snapshot" was called in the same transaction.';
3313 CREATE FUNCTION "manual_freeze"("issue_id_p" "issue"."id"%TYPE)
3314 RETURNS VOID
3315 LANGUAGE 'plpgsql' VOLATILE AS $$
3316 DECLARE
3317 "issue_row" "issue"%ROWTYPE;
3318 BEGIN
3319 PERFORM "create_snapshot"("issue_id_p");
3320 PERFORM "freeze_after_snapshot"("issue_id_p");
3321 RETURN;
3322 END;
3323 $$;
3325 COMMENT ON FUNCTION "manual_freeze"
3326 ( "issue"."id"%TYPE )
3327 IS 'Freeze an issue manually (fully) and start voting';
3331 -----------------------
3332 -- Counting of votes --
3333 -----------------------
3336 CREATE FUNCTION "weight_of_added_vote_delegations"
3337 ( "issue_id_p" "issue"."id"%TYPE,
3338 "member_id_p" "member"."id"%TYPE,
3339 "delegate_member_ids_p" "delegating_voter"."delegate_member_ids"%TYPE )
3340 RETURNS "direct_voter"."weight"%TYPE
3341 LANGUAGE 'plpgsql' VOLATILE AS $$
3342 DECLARE
3343 "issue_delegation_row" "issue_delegation"%ROWTYPE;
3344 "delegate_member_ids_v" "delegating_voter"."delegate_member_ids"%TYPE;
3345 "weight_v" INT4;
3346 "sub_weight_v" INT4;
3347 BEGIN
3348 "weight_v" := 0;
3349 FOR "issue_delegation_row" IN
3350 SELECT * FROM "issue_delegation"
3351 WHERE "trustee_id" = "member_id_p"
3352 AND "issue_id" = "issue_id_p"
3353 LOOP
3354 IF NOT EXISTS (
3355 SELECT NULL FROM "direct_voter"
3356 WHERE "member_id" = "issue_delegation_row"."truster_id"
3357 AND "issue_id" = "issue_id_p"
3358 ) AND NOT EXISTS (
3359 SELECT NULL FROM "delegating_voter"
3360 WHERE "member_id" = "issue_delegation_row"."truster_id"
3361 AND "issue_id" = "issue_id_p"
3362 ) THEN
3363 "delegate_member_ids_v" :=
3364 "member_id_p" || "delegate_member_ids_p";
3365 INSERT INTO "delegating_voter" (
3366 "issue_id",
3367 "member_id",
3368 "scope",
3369 "delegate_member_ids"
3370 ) VALUES (
3371 "issue_id_p",
3372 "issue_delegation_row"."truster_id",
3373 "issue_delegation_row"."scope",
3374 "delegate_member_ids_v"
3375 );
3376 "sub_weight_v" := 1 +
3377 "weight_of_added_vote_delegations"(
3378 "issue_id_p",
3379 "issue_delegation_row"."truster_id",
3380 "delegate_member_ids_v"
3381 );
3382 UPDATE "delegating_voter"
3383 SET "weight" = "sub_weight_v"
3384 WHERE "issue_id" = "issue_id_p"
3385 AND "member_id" = "issue_delegation_row"."truster_id";
3386 "weight_v" := "weight_v" + "sub_weight_v";
3387 END IF;
3388 END LOOP;
3389 RETURN "weight_v";
3390 END;
3391 $$;
3393 COMMENT ON FUNCTION "weight_of_added_vote_delegations"
3394 ( "issue"."id"%TYPE,
3395 "member"."id"%TYPE,
3396 "delegating_voter"."delegate_member_ids"%TYPE )
3397 IS 'Helper function for "add_vote_delegations" function';
3400 CREATE FUNCTION "add_vote_delegations"
3401 ( "issue_id_p" "issue"."id"%TYPE )
3402 RETURNS VOID
3403 LANGUAGE 'plpgsql' VOLATILE AS $$
3404 DECLARE
3405 "member_id_v" "member"."id"%TYPE;
3406 BEGIN
3407 FOR "member_id_v" IN
3408 SELECT "member_id" FROM "direct_voter"
3409 WHERE "issue_id" = "issue_id_p"
3410 LOOP
3411 UPDATE "direct_voter" SET
3412 "weight" = "weight" + "weight_of_added_vote_delegations"(
3413 "issue_id_p",
3414 "member_id_v",
3415 '{}'
3417 WHERE "member_id" = "member_id_v"
3418 AND "issue_id" = "issue_id_p";
3419 END LOOP;
3420 RETURN;
3421 END;
3422 $$;
3424 COMMENT ON FUNCTION "add_vote_delegations"
3425 ( "issue_id_p" "issue"."id"%TYPE )
3426 IS 'Helper function for "close_voting" function';
3429 CREATE FUNCTION "close_voting"("issue_id_p" "issue"."id"%TYPE)
3430 RETURNS VOID
3431 LANGUAGE 'plpgsql' VOLATILE AS $$
3432 DECLARE
3433 "area_id_v" "area"."id"%TYPE;
3434 "unit_id_v" "unit"."id"%TYPE;
3435 "member_id_v" "member"."id"%TYPE;
3436 BEGIN
3437 PERFORM "lock_issue"("issue_id_p");
3438 SELECT "area_id" INTO "area_id_v" FROM "issue" WHERE "id" = "issue_id_p";
3439 SELECT "unit_id" INTO "unit_id_v" FROM "area" WHERE "id" = "area_id_v";
3440 -- consider delegations and auto-reject:
3441 DELETE FROM "delegating_voter"
3442 WHERE "issue_id" = "issue_id_p";
3443 DELETE FROM "direct_voter"
3444 WHERE "issue_id" = "issue_id_p"
3445 AND "autoreject" = TRUE;
3446 DELETE FROM "direct_voter"
3447 USING (
3448 SELECT
3449 "direct_voter"."member_id"
3450 FROM "direct_voter"
3451 JOIN "member" ON "direct_voter"."member_id" = "member"."id"
3452 LEFT JOIN "privilege"
3453 ON "privilege"."unit_id" = "unit_id_v"
3454 AND "privilege"."member_id" = "direct_voter"."member_id"
3455 WHERE "direct_voter"."issue_id" = "issue_id_p" AND (
3456 "member"."active" = FALSE OR
3457 "privilege"."voting_right" ISNULL OR
3458 "privilege"."voting_right" = FALSE
3460 ) AS "subquery"
3461 WHERE "direct_voter"."issue_id" = "issue_id_p"
3462 AND "direct_voter"."member_id" = "subquery"."member_id";
3463 UPDATE "direct_voter" SET "weight" = 1
3464 WHERE "issue_id" = "issue_id_p";
3465 PERFORM "add_vote_delegations"("issue_id_p");
3466 FOR "member_id_v" IN
3467 SELECT "interest"."member_id"
3468 FROM "interest"
3469 JOIN "member"
3470 ON "interest"."member_id" = "member"."id"
3471 LEFT JOIN "direct_voter"
3472 ON "interest"."member_id" = "direct_voter"."member_id"
3473 AND "interest"."issue_id" = "direct_voter"."issue_id"
3474 LEFT JOIN "delegating_voter"
3475 ON "interest"."member_id" = "delegating_voter"."member_id"
3476 AND "interest"."issue_id" = "delegating_voter"."issue_id"
3477 WHERE "interest"."issue_id" = "issue_id_p"
3478 AND "interest"."autoreject" = TRUE
3479 AND "member"."active"
3480 AND "direct_voter"."member_id" ISNULL
3481 AND "delegating_voter"."member_id" ISNULL
3482 UNION SELECT "membership"."member_id"
3483 FROM "membership"
3484 JOIN "member"
3485 ON "membership"."member_id" = "member"."id"
3486 LEFT JOIN "interest"
3487 ON "membership"."member_id" = "interest"."member_id"
3488 AND "interest"."issue_id" = "issue_id_p"
3489 LEFT JOIN "direct_voter"
3490 ON "membership"."member_id" = "direct_voter"."member_id"
3491 AND "direct_voter"."issue_id" = "issue_id_p"
3492 LEFT JOIN "delegating_voter"
3493 ON "membership"."member_id" = "delegating_voter"."member_id"
3494 AND "delegating_voter"."issue_id" = "issue_id_p"
3495 WHERE "membership"."area_id" = "area_id_v"
3496 AND "membership"."autoreject" = TRUE
3497 AND "member"."active"
3498 AND "interest"."autoreject" ISNULL
3499 AND "direct_voter"."member_id" ISNULL
3500 AND "delegating_voter"."member_id" ISNULL
3501 LOOP
3502 INSERT INTO "direct_voter"
3503 ("member_id", "issue_id", "weight", "autoreject") VALUES
3504 ("member_id_v", "issue_id_p", 1, TRUE);
3505 INSERT INTO "vote" (
3506 "member_id",
3507 "issue_id",
3508 "initiative_id",
3509 "grade"
3510 ) SELECT
3511 "member_id_v" AS "member_id",
3512 "issue_id_p" AS "issue_id",
3513 "id" AS "initiative_id",
3514 -1 AS "grade"
3515 FROM "initiative" WHERE "issue_id" = "issue_id_p";
3516 END LOOP;
3517 PERFORM "add_vote_delegations"("issue_id_p");
3518 -- set voter count and mark issue as being calculated:
3519 UPDATE "issue" SET
3520 "state" = 'calculation',
3521 "closed" = now(),
3522 "voter_count" = (
3523 SELECT coalesce(sum("weight"), 0)
3524 FROM "direct_voter" WHERE "issue_id" = "issue_id_p"
3526 WHERE "id" = "issue_id_p";
3527 -- calculate "positive_votes", "negative_votes" and "attainable":
3528 UPDATE "initiative" SET
3529 "positive_votes" = "vote_counts"."positive_votes",
3530 "negative_votes" = "vote_counts"."negative_votes",
3531 "attainable" = CASE WHEN "majority_strict" THEN
3532 "vote_counts"."positive_votes" * "majority_den" >
3533 "majority_num" *
3534 ("vote_counts"."positive_votes"+"vote_counts"."negative_votes")
3535 ELSE
3536 "vote_counts"."positive_votes" * "majority_den" >=
3537 "majority_num" *
3538 ("vote_counts"."positive_votes"+"vote_counts"."negative_votes")
3539 END
3540 FROM
3541 ( SELECT
3542 "initiative"."id" AS "initiative_id",
3543 coalesce(
3544 sum(
3545 CASE WHEN "grade" > 0 THEN "direct_voter"."weight" ELSE 0 END
3546 ),
3548 ) AS "positive_votes",
3549 coalesce(
3550 sum(
3551 CASE WHEN "grade" < 0 THEN "direct_voter"."weight" ELSE 0 END
3552 ),
3554 ) AS "negative_votes"
3555 FROM "initiative"
3556 JOIN "issue" ON "initiative"."issue_id" = "issue"."id"
3557 JOIN "policy" ON "issue"."policy_id" = "policy"."id"
3558 LEFT JOIN "direct_voter"
3559 ON "direct_voter"."issue_id" = "initiative"."issue_id"
3560 LEFT JOIN "vote"
3561 ON "vote"."initiative_id" = "initiative"."id"
3562 AND "vote"."member_id" = "direct_voter"."member_id"
3563 WHERE "initiative"."issue_id" = "issue_id_p"
3564 AND "initiative"."admitted" -- NOTE: NULL case is handled too
3565 GROUP BY "initiative"."id"
3566 ) AS "vote_counts",
3567 "issue",
3568 "policy"
3569 WHERE "vote_counts"."initiative_id" = "initiative"."id"
3570 AND "issue"."id" = "initiative"."issue_id"
3571 AND "policy"."id" = "issue"."policy_id";
3572 -- materialize battle_view:
3573 -- NOTE: "closed" column of issue must be set at this point
3574 DELETE FROM "battle" WHERE "issue_id" = "issue_id_p";
3575 INSERT INTO "battle" (
3576 "issue_id",
3577 "winning_initiative_id", "losing_initiative_id",
3578 "count"
3579 ) SELECT
3580 "issue_id",
3581 "winning_initiative_id", "losing_initiative_id",
3582 "count"
3583 FROM "battle_view" WHERE "issue_id" = "issue_id_p";
3584 END;
3585 $$;
3587 COMMENT ON FUNCTION "close_voting"
3588 ( "issue"."id"%TYPE )
3589 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.';
3592 CREATE FUNCTION "defeat_strength"
3593 ( "positive_votes_p" INT4, "negative_votes_p" INT4 )
3594 RETURNS INT8
3595 LANGUAGE 'plpgsql' IMMUTABLE AS $$
3596 BEGIN
3597 IF "positive_votes_p" > "negative_votes_p" THEN
3598 RETURN ("positive_votes_p"::INT8 << 31) - "negative_votes_p"::INT8;
3599 ELSIF "positive_votes_p" = "negative_votes_p" THEN
3600 RETURN 0;
3601 ELSE
3602 RETURN -1;
3603 END IF;
3604 END;
3605 $$;
3607 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';
3610 CREATE FUNCTION "array_init_string"("dim_p" INTEGER)
3611 RETURNS TEXT
3612 LANGUAGE 'plpgsql' IMMUTABLE AS $$
3613 DECLARE
3614 "i" INTEGER;
3615 "ary_text_v" TEXT;
3616 BEGIN
3617 IF "dim_p" >= 1 THEN
3618 "ary_text_v" := '{NULL';
3619 "i" := "dim_p";
3620 LOOP
3621 "i" := "i" - 1;
3622 EXIT WHEN "i" = 0;
3623 "ary_text_v" := "ary_text_v" || ',NULL';
3624 END LOOP;
3625 "ary_text_v" := "ary_text_v" || '}';
3626 RETURN "ary_text_v";
3627 ELSE
3628 RAISE EXCEPTION 'Dimension needs to be at least 1.';
3629 END IF;
3630 END;
3631 $$;
3633 COMMENT ON FUNCTION "array_init_string"(INTEGER) IS 'Needed for PostgreSQL < 8.4, due to missing "array_fill" function';
3636 CREATE FUNCTION "square_matrix_init_string"("dim_p" INTEGER)
3637 RETURNS TEXT
3638 LANGUAGE 'plpgsql' IMMUTABLE AS $$
3639 DECLARE
3640 "i" INTEGER;
3641 "row_text_v" TEXT;
3642 "ary_text_v" TEXT;
3643 BEGIN
3644 IF "dim_p" >= 1 THEN
3645 "row_text_v" := '{NULL';
3646 "i" := "dim_p";
3647 LOOP
3648 "i" := "i" - 1;
3649 EXIT WHEN "i" = 0;
3650 "row_text_v" := "row_text_v" || ',NULL';
3651 END LOOP;
3652 "row_text_v" := "row_text_v" || '}';
3653 "ary_text_v" := '{' || "row_text_v";
3654 "i" := "dim_p";
3655 LOOP
3656 "i" := "i" - 1;
3657 EXIT WHEN "i" = 0;
3658 "ary_text_v" := "ary_text_v" || ',' || "row_text_v";
3659 END LOOP;
3660 "ary_text_v" := "ary_text_v" || '}';
3661 RETURN "ary_text_v";
3662 ELSE
3663 RAISE EXCEPTION 'Dimension needs to be at least 1.';
3664 END IF;
3665 END;
3666 $$;
3668 COMMENT ON FUNCTION "square_matrix_init_string"(INTEGER) IS 'Needed for PostgreSQL < 8.4, due to missing "array_fill" function';
3671 CREATE FUNCTION "calculate_ranks"("issue_id_p" "issue"."id"%TYPE)
3672 RETURNS VOID
3673 LANGUAGE 'plpgsql' VOLATILE AS $$
3674 DECLARE
3675 "dimension_v" INTEGER;
3676 "vote_matrix" INT4[][]; -- absolute votes
3677 "matrix" INT8[][]; -- defeat strength / best paths
3678 "i" INTEGER;
3679 "j" INTEGER;
3680 "k" INTEGER;
3681 "battle_row" "battle"%ROWTYPE;
3682 "rank_ary" INT4[];
3683 "rank_v" INT4;
3684 "done_v" INTEGER;
3685 "winners_ary" INTEGER[];
3686 "initiative_id_v" "initiative"."id"%TYPE;
3687 BEGIN
3688 PERFORM NULL FROM "issue" WHERE "id" = "issue_id_p" FOR UPDATE;
3689 SELECT count(1) INTO "dimension_v"
3690 FROM "battle_participant" WHERE "issue_id" = "issue_id_p";
3691 IF "dimension_v" > 1 THEN
3692 -- Create "vote_matrix" with absolute number of votes in pairwise
3693 -- comparison:
3694 "vote_matrix" := "square_matrix_init_string"("dimension_v"); -- TODO: replace by "array_fill" function (PostgreSQL 8.4)
3695 "i" := 1;
3696 "j" := 2;
3697 FOR "battle_row" IN
3698 SELECT * FROM "battle" WHERE "issue_id" = "issue_id_p"
3699 ORDER BY
3700 "winning_initiative_id" NULLS LAST,
3701 "losing_initiative_id" NULLS LAST
3702 LOOP
3703 "vote_matrix"["i"]["j"] := "battle_row"."count";
3704 IF "j" = "dimension_v" THEN
3705 "i" := "i" + 1;
3706 "j" := 1;
3707 ELSE
3708 "j" := "j" + 1;
3709 IF "j" = "i" THEN
3710 "j" := "j" + 1;
3711 END IF;
3712 END IF;
3713 END LOOP;
3714 IF "i" != "dimension_v" OR "j" != "dimension_v" + 1 THEN
3715 RAISE EXCEPTION 'Wrong battle count (should not happen)';
3716 END IF;
3717 -- Store defeat strengths in "matrix" using "defeat_strength"
3718 -- function:
3719 "matrix" := "square_matrix_init_string"("dimension_v"); -- TODO: replace by "array_fill" function (PostgreSQL 8.4)
3720 "i" := 1;
3721 LOOP
3722 "j" := 1;
3723 LOOP
3724 IF "i" != "j" THEN
3725 "matrix"["i"]["j"] := "defeat_strength"(
3726 "vote_matrix"["i"]["j"],
3727 "vote_matrix"["j"]["i"]
3728 );
3729 END IF;
3730 EXIT WHEN "j" = "dimension_v";
3731 "j" := "j" + 1;
3732 END LOOP;
3733 EXIT WHEN "i" = "dimension_v";
3734 "i" := "i" + 1;
3735 END LOOP;
3736 -- Find best paths:
3737 "i" := 1;
3738 LOOP
3739 "j" := 1;
3740 LOOP
3741 IF "i" != "j" THEN
3742 "k" := 1;
3743 LOOP
3744 IF "i" != "k" AND "j" != "k" THEN
3745 IF "matrix"["j"]["i"] < "matrix"["i"]["k"] THEN
3746 IF "matrix"["j"]["i"] > "matrix"["j"]["k"] THEN
3747 "matrix"["j"]["k"] := "matrix"["j"]["i"];
3748 END IF;
3749 ELSE
3750 IF "matrix"["i"]["k"] > "matrix"["j"]["k"] THEN
3751 "matrix"["j"]["k"] := "matrix"["i"]["k"];
3752 END IF;
3753 END IF;
3754 END IF;
3755 EXIT WHEN "k" = "dimension_v";
3756 "k" := "k" + 1;
3757 END LOOP;
3758 END IF;
3759 EXIT WHEN "j" = "dimension_v";
3760 "j" := "j" + 1;
3761 END LOOP;
3762 EXIT WHEN "i" = "dimension_v";
3763 "i" := "i" + 1;
3764 END LOOP;
3765 -- Determine order of winners:
3766 "rank_ary" := "array_init_string"("dimension_v"); -- TODO: replace by "array_fill" function (PostgreSQL 8.4)
3767 "rank_v" := 1;
3768 "done_v" := 0;
3769 LOOP
3770 "winners_ary" := '{}';
3771 "i" := 1;
3772 LOOP
3773 IF "rank_ary"["i"] ISNULL THEN
3774 "j" := 1;
3775 LOOP
3776 IF
3777 "i" != "j" AND
3778 "rank_ary"["j"] ISNULL AND
3779 "matrix"["j"]["i"] > "matrix"["i"]["j"]
3780 THEN
3781 -- someone else is better
3782 EXIT;
3783 END IF;
3784 IF "j" = "dimension_v" THEN
3785 -- noone is better
3786 "winners_ary" := "winners_ary" || "i";
3787 EXIT;
3788 END IF;
3789 "j" := "j" + 1;
3790 END LOOP;
3791 END IF;
3792 EXIT WHEN "i" = "dimension_v";
3793 "i" := "i" + 1;
3794 END LOOP;
3795 "i" := 1;
3796 LOOP
3797 "rank_ary"["winners_ary"["i"]] := "rank_v";
3798 "done_v" := "done_v" + 1;
3799 EXIT WHEN "i" = array_upper("winners_ary", 1);
3800 "i" := "i" + 1;
3801 END LOOP;
3802 EXIT WHEN "done_v" = "dimension_v";
3803 "rank_v" := "rank_v" + 1;
3804 END LOOP;
3805 -- write preliminary results:
3806 "i" := 1;
3807 FOR "initiative_id_v" IN
3808 SELECT "id" FROM "initiative"
3809 WHERE "issue_id" = "issue_id_p" AND "admitted"
3810 ORDER BY "id"
3811 LOOP
3812 UPDATE "initiative" SET
3813 "favored" = "rank_ary"["i"] < "rank_ary"["dimension_v"],
3814 "unfavored" = "rank_ary"["i"] > "rank_ary"["dimension_v"],
3815 "preliminary_rank" = "rank_ary"["i"],
3816 "disqualified" = FALSE,
3817 "winner" = FALSE
3818 WHERE "id" = "initiative_id_v";
3819 "i" := "i" + 1;
3820 END LOOP;
3821 IF "i" != "dimension_v" THEN
3822 RAISE EXCEPTION 'Wrong winner count (should not happen)';
3823 END IF;
3824 -- remove possible gap in preliminary ranks:
3825 IF NOT EXISTS (
3826 SELECT NULL FROM "initiative"
3827 WHERE "issue_id" = "issue_id_p"
3828 AND "favored"=FALSE AND "unfavored"=FALSE
3829 ) THEN
3830 UPDATE "initiative" SET "preliminary_rank" = "preliminary_rank" - 1
3831 WHERE "issue_id" = "issue_id_p" AND "unfavored";
3832 END IF;
3833 -- disqualify certain initiatives to enforce a stable result:
3834 UPDATE "initiative" SET "disqualified" = TRUE
3835 FROM (
3836 SELECT "losing_initiative"."id" AS "initiative_id"
3837 FROM "issue"
3838 JOIN "policy" ON "issue"."policy_id" = "policy"."id"
3839 JOIN "initiative" "losing_initiative"
3840 ON "losing_initiative"."issue_id" = "issue_id_p"
3841 AND "losing_initiative"."admitted"
3842 JOIN "battle_participant" "winning_participant"
3843 ON "winning_participant"."issue_id" = "issue_id_p"
3844 LEFT JOIN "initiative" "winning_initiative"
3845 ON "winning_initiative"."id" = "winning_participant"."id"
3846 -- NOTE: winner may be status quo:
3847 -- "losing_initiative"."id" is always NOTNULL
3848 -- while "winning_initiative"."id" may be NULL
3849 JOIN "battle" "battle_win"
3850 ON "battle_win"."issue_id" = "issue_id_p"
3851 AND (
3852 "battle_win"."winning_initiative_id" = "winning_initiative"."id" OR
3853 ( "battle_win"."winning_initiative_id" ISNULL AND
3854 "winning_initiative"."id" ISNULL ) )
3855 AND "battle_win"."losing_initiative_id" = "losing_initiative"."id"
3856 JOIN "battle" "battle_lose"
3857 ON "battle_lose"."issue_id" = "issue_id_p"
3858 AND (
3859 "battle_lose"."losing_initiative_id" = "winning_initiative"."id" OR
3860 ( "battle_lose"."losing_initiative_id" ISNULL AND
3861 "winning_initiative"."id" ISNULL ) )
3862 AND "battle_lose"."winning_initiative_id" = "losing_initiative"."id"
3863 WHERE "issue"."id" = "issue_id_p"
3864 AND (
3865 ("winning_initiative"."id" ISNULL AND "losing_initiative"."unfavored") OR
3866 ( "winning_initiative"."preliminary_rank" <
3867 "losing_initiative"."preliminary_rank" ) )
3868 AND CASE WHEN "policy"."majority_strict" THEN
3869 "battle_win"."count" * "policy"."majority_den" >
3870 "policy"."majority_num" *
3871 ("battle_win"."count"+"battle_lose"."count")
3872 ELSE
3873 "battle_win"."count" * "policy"."majority_den" >=
3874 "policy"."majority_num" *
3875 ("battle_win"."count"+"battle_lose"."count")
3876 END
3877 ) AS "subquery"
3878 WHERE "id" = "subquery"."initiative_id";
3879 -- calculate final ranks (start counting with 1, no equal ranks):
3880 "rank_v" := 1;
3881 FOR "initiative_id_v" IN
3882 SELECT "id" FROM "initiative"
3883 WHERE "issue_id" = "issue_id_p" AND "admitted"
3884 ORDER BY "preliminary_rank", "id"
3885 LOOP
3886 UPDATE "initiative" SET "final_rank" = "rank_v"
3887 WHERE "id" = "initiative_id_v";
3888 "rank_v" := "rank_v" + 1;
3889 END LOOP;
3890 -- mark final winner:
3891 UPDATE "initiative" SET "winner" = TRUE
3892 FROM (
3893 SELECT "id" AS "initiative_id"
3894 FROM "initiative"
3895 WHERE "issue_id" = "issue_id_p"
3896 AND "attainable" AND "favored" AND NOT "disqualified"
3897 ORDER BY "final_rank"
3898 LIMIT 1
3899 ) AS "subquery"
3900 WHERE "id" = "subquery"."initiative_id";
3901 END IF;
3902 -- mark issue as finished:
3903 UPDATE "issue" SET
3904 "state" =
3905 CASE WHEN EXISTS (
3906 SELECT NULL FROM "initiative"
3907 WHERE "issue_id" = "issue_id_p" AND "winner"
3908 ) THEN
3909 'finished_with_winner'::"issue_state"
3910 ELSE
3911 'finished_without_winner'::"issue_state"
3912 END,
3913 "ranks_available" = TRUE
3914 WHERE "id" = "issue_id_p";
3915 RETURN;
3916 END;
3917 $$;
3919 COMMENT ON FUNCTION "calculate_ranks"
3920 ( "issue"."id"%TYPE )
3921 IS 'Determine ranking (Votes have to be counted first)';
3925 -----------------------------
3926 -- Automatic state changes --
3927 -----------------------------
3930 CREATE FUNCTION "check_issue"
3931 ( "issue_id_p" "issue"."id"%TYPE )
3932 RETURNS VOID
3933 LANGUAGE 'plpgsql' VOLATILE AS $$
3934 DECLARE
3935 "issue_row" "issue"%ROWTYPE;
3936 "policy_row" "policy"%ROWTYPE;
3937 "voting_requested_v" BOOLEAN;
3938 BEGIN
3939 PERFORM "lock_issue"("issue_id_p");
3940 SELECT * INTO "issue_row" FROM "issue" WHERE "id" = "issue_id_p";
3941 -- only process open issues:
3942 IF "issue_row"."closed" ISNULL THEN
3943 SELECT * INTO "policy_row" FROM "policy"
3944 WHERE "id" = "issue_row"."policy_id";
3945 -- create a snapshot, unless issue is already fully frozen:
3946 IF "issue_row"."fully_frozen" ISNULL THEN
3947 PERFORM "create_snapshot"("issue_id_p");
3948 SELECT * INTO "issue_row" FROM "issue" WHERE "id" = "issue_id_p";
3949 END IF;
3950 -- eventually close or accept issues, which have not been accepted:
3951 IF "issue_row"."accepted" ISNULL THEN
3952 IF EXISTS (
3953 SELECT NULL FROM "initiative"
3954 WHERE "issue_id" = "issue_id_p"
3955 AND "supporter_count" > 0
3956 AND "supporter_count" * "policy_row"."issue_quorum_den"
3957 >= "issue_row"."population" * "policy_row"."issue_quorum_num"
3958 ) THEN
3959 -- accept issues, if supporter count is high enough
3960 PERFORM "set_snapshot_event"("issue_id_p", 'end_of_admission');
3961 -- NOTE: "issue_row" used later
3962 "issue_row"."state" := 'discussion';
3963 "issue_row"."accepted" := now();
3964 UPDATE "issue" SET
3965 "state" = "issue_row"."state",
3966 "accepted" = "issue_row"."accepted"
3967 WHERE "id" = "issue_row"."id";
3968 ELSIF
3969 now() >= "issue_row"."created" + "issue_row"."admission_time"
3970 THEN
3971 -- close issues, if admission time has expired
3972 PERFORM "set_snapshot_event"("issue_id_p", 'end_of_admission');
3973 UPDATE "issue" SET
3974 "state" = 'canceled_issue_not_accepted',
3975 "closed" = now()
3976 WHERE "id" = "issue_row"."id";
3977 END IF;
3978 END IF;
3979 -- eventually half freeze issues:
3980 IF
3981 -- NOTE: issue can't be closed at this point, if it has been accepted
3982 "issue_row"."accepted" NOTNULL AND
3983 "issue_row"."half_frozen" ISNULL
3984 THEN
3985 SELECT
3986 CASE
3987 WHEN "vote_now" * 2 > "issue_row"."population" THEN
3988 TRUE
3989 WHEN "vote_later" * 2 > "issue_row"."population" THEN
3990 FALSE
3991 ELSE NULL
3992 END
3993 INTO "voting_requested_v"
3994 FROM "issue" WHERE "id" = "issue_id_p";
3995 IF
3996 "voting_requested_v" OR (
3997 "voting_requested_v" ISNULL AND
3998 now() >= "issue_row"."accepted" + "issue_row"."discussion_time"
4000 THEN
4001 PERFORM "set_snapshot_event"("issue_id_p", 'half_freeze');
4002 -- NOTE: "issue_row" used later
4003 "issue_row"."state" := 'verification';
4004 "issue_row"."half_frozen" := now();
4005 UPDATE "issue" SET
4006 "state" = "issue_row"."state",
4007 "half_frozen" = "issue_row"."half_frozen"
4008 WHERE "id" = "issue_row"."id";
4009 END IF;
4010 END IF;
4011 -- close issues after some time, if all initiatives have been revoked:
4012 IF
4013 "issue_row"."closed" ISNULL AND
4014 NOT EXISTS (
4015 -- all initiatives are revoked
4016 SELECT NULL FROM "initiative"
4017 WHERE "issue_id" = "issue_id_p" AND "revoked" ISNULL
4018 ) AND (
4019 -- and issue has not been accepted yet
4020 "issue_row"."accepted" ISNULL OR
4021 NOT EXISTS (
4022 -- or no initiatives have been revoked lately
4023 SELECT NULL FROM "initiative"
4024 WHERE "issue_id" = "issue_id_p"
4025 AND now() < "revoked" + "issue_row"."verification_time"
4026 ) OR (
4027 -- or verification time has elapsed
4028 "issue_row"."half_frozen" NOTNULL AND
4029 "issue_row"."fully_frozen" ISNULL AND
4030 now() >= "issue_row"."half_frozen" + "issue_row"."verification_time"
4033 THEN
4034 -- NOTE: "issue_row" used later
4035 IF "issue_row"."accepted" ISNULL THEN
4036 "issue_row"."state" := 'canceled_revoked_before_accepted';
4037 ELSIF "issue_row"."half_frozen" ISNULL THEN
4038 "issue_row"."state" := 'canceled_after_revocation_during_discussion';
4039 ELSE
4040 "issue_row"."state" := 'canceled_after_revocation_during_verification';
4041 END IF;
4042 "issue_row"."closed" := now();
4043 UPDATE "issue" SET
4044 "state" = "issue_row"."state",
4045 "closed" = "issue_row"."closed"
4046 WHERE "id" = "issue_row"."id";
4047 END IF;
4048 -- fully freeze issue after verification time:
4049 IF
4050 "issue_row"."half_frozen" NOTNULL AND
4051 "issue_row"."fully_frozen" ISNULL AND
4052 "issue_row"."closed" ISNULL AND
4053 now() >= "issue_row"."half_frozen" + "issue_row"."verification_time"
4054 THEN
4055 PERFORM "freeze_after_snapshot"("issue_id_p");
4056 -- NOTE: "issue" might change, thus "issue_row" has to be updated below
4057 END IF;
4058 SELECT * INTO "issue_row" FROM "issue" WHERE "id" = "issue_id_p";
4059 -- close issue by calling close_voting(...) after voting time:
4060 IF
4061 "issue_row"."closed" ISNULL AND
4062 "issue_row"."fully_frozen" NOTNULL AND
4063 now() >= "issue_row"."fully_frozen" + "issue_row"."voting_time"
4064 THEN
4065 PERFORM "close_voting"("issue_id_p");
4066 -- calculate ranks will not consume much time and can be done now
4067 PERFORM "calculate_ranks"("issue_id_p");
4068 END IF;
4069 END IF;
4070 RETURN;
4071 END;
4072 $$;
4074 COMMENT ON FUNCTION "check_issue"
4075 ( "issue"."id"%TYPE )
4076 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.';
4079 CREATE FUNCTION "check_everything"()
4080 RETURNS VOID
4081 LANGUAGE 'plpgsql' VOLATILE AS $$
4082 DECLARE
4083 "issue_id_v" "issue"."id"%TYPE;
4084 BEGIN
4085 DELETE FROM "expired_session";
4086 PERFORM "check_last_login"();
4087 PERFORM "calculate_member_counts"();
4088 FOR "issue_id_v" IN SELECT "id" FROM "open_issue" LOOP
4089 PERFORM "check_issue"("issue_id_v");
4090 END LOOP;
4091 FOR "issue_id_v" IN SELECT "id" FROM "issue_with_ranks_missing" LOOP
4092 PERFORM "calculate_ranks"("issue_id_v");
4093 END LOOP;
4094 RETURN;
4095 END;
4096 $$;
4098 COMMENT ON FUNCTION "check_everything"() IS 'Amongst other regular tasks this function performs "check_issue" for every open issue, and if possible, automatically calculates ranks. Use this function only for development and debugging purposes, as long transactions with exclusive locking may result. In productive environments you should call the lf_update program instead.';
4102 ----------------------
4103 -- Deletion of data --
4104 ----------------------
4107 CREATE FUNCTION "clean_issue"("issue_id_p" "issue"."id"%TYPE)
4108 RETURNS VOID
4109 LANGUAGE 'plpgsql' VOLATILE AS $$
4110 DECLARE
4111 "issue_row" "issue"%ROWTYPE;
4112 BEGIN
4113 SELECT * INTO "issue_row"
4114 FROM "issue" WHERE "id" = "issue_id_p"
4115 FOR UPDATE;
4116 IF "issue_row"."cleaned" ISNULL THEN
4117 -- TODO: might be broken due to new constraints!
4118 UPDATE "issue" SET
4119 "closed" = NULL,
4120 "ranks_available" = FALSE
4121 WHERE "id" = "issue_id_p";
4122 DELETE FROM "delegating_voter"
4123 WHERE "issue_id" = "issue_id_p";
4124 DELETE FROM "direct_voter"
4125 WHERE "issue_id" = "issue_id_p";
4126 DELETE FROM "delegating_interest_snapshot"
4127 WHERE "issue_id" = "issue_id_p";
4128 DELETE FROM "direct_interest_snapshot"
4129 WHERE "issue_id" = "issue_id_p";
4130 DELETE FROM "delegating_population_snapshot"
4131 WHERE "issue_id" = "issue_id_p";
4132 DELETE FROM "direct_population_snapshot"
4133 WHERE "issue_id" = "issue_id_p";
4134 DELETE FROM "non_voter"
4135 WHERE "issue_id" = "issue_id_p";
4136 DELETE FROM "delegation"
4137 WHERE "issue_id" = "issue_id_p";
4138 DELETE FROM "supporter"
4139 WHERE "issue_id" = "issue_id_p";
4140 UPDATE "issue" SET
4141 "closed" = "issue_row"."closed",
4142 "ranks_available" = "issue_row"."ranks_available",
4143 "cleaned" = now()
4144 WHERE "id" = "issue_id_p";
4145 END IF;
4146 RETURN;
4147 END;
4148 $$;
4150 COMMENT ON FUNCTION "clean_issue"("issue"."id"%TYPE) IS 'Delete discussion data and votes belonging to an issue';
4153 CREATE FUNCTION "delete_member"("member_id_p" "member"."id"%TYPE)
4154 RETURNS VOID
4155 LANGUAGE 'plpgsql' VOLATILE AS $$
4156 BEGIN
4157 UPDATE "member" SET
4158 "last_login" = NULL,
4159 "last_login_public" = NULL,
4160 "login" = NULL,
4161 "password" = NULL,
4162 "locked" = TRUE,
4163 "active" = FALSE,
4164 "notify_email" = NULL,
4165 "notify_email_unconfirmed" = NULL,
4166 "notify_email_secret" = NULL,
4167 "notify_email_secret_expiry" = NULL,
4168 "notify_email_lock_expiry" = NULL,
4169 "password_reset_secret" = NULL,
4170 "password_reset_secret_expiry" = NULL,
4171 "organizational_unit" = NULL,
4172 "internal_posts" = NULL,
4173 "realname" = NULL,
4174 "birthday" = NULL,
4175 "address" = NULL,
4176 "email" = NULL,
4177 "xmpp_address" = NULL,
4178 "website" = NULL,
4179 "phone" = NULL,
4180 "mobile_phone" = NULL,
4181 "profession" = NULL,
4182 "external_memberships" = NULL,
4183 "external_posts" = NULL,
4184 "statement" = NULL
4185 WHERE "id" = "member_id_p";
4186 -- "text_search_data" is updated by triggers
4187 DELETE FROM "setting" WHERE "member_id" = "member_id_p";
4188 DELETE FROM "setting_map" WHERE "member_id" = "member_id_p";
4189 DELETE FROM "member_relation_setting" WHERE "member_id" = "member_id_p";
4190 DELETE FROM "member_image" WHERE "member_id" = "member_id_p";
4191 DELETE FROM "contact" WHERE "member_id" = "member_id_p";
4192 DELETE FROM "ignored_member" WHERE "member_id" = "member_id_p";
4193 DELETE FROM "session" WHERE "member_id" = "member_id_p";
4194 DELETE FROM "area_setting" WHERE "member_id" = "member_id_p";
4195 DELETE FROM "issue_setting" WHERE "member_id" = "member_id_p";
4196 DELETE FROM "ignored_initiative" WHERE "member_id" = "member_id_p";
4197 DELETE FROM "initiative_setting" WHERE "member_id" = "member_id_p";
4198 DELETE FROM "suggestion_setting" WHERE "member_id" = "member_id_p";
4199 DELETE FROM "membership" WHERE "member_id" = "member_id_p";
4200 DELETE FROM "delegation" WHERE "truster_id" = "member_id_p";
4201 DELETE FROM "non_voter" WHERE "member_id" = "member_id_p";
4202 DELETE FROM "direct_voter" USING "issue"
4203 WHERE "direct_voter"."issue_id" = "issue"."id"
4204 AND "issue"."closed" ISNULL
4205 AND "member_id" = "member_id_p";
4206 RETURN;
4207 END;
4208 $$;
4210 COMMENT ON FUNCTION "delete_member"("member_id_p" "member"."id"%TYPE) IS 'Deactivate member and clear certain settings and data of this member (data protection)';
4213 CREATE FUNCTION "delete_private_data"()
4214 RETURNS VOID
4215 LANGUAGE 'plpgsql' VOLATILE AS $$
4216 BEGIN
4217 UPDATE "member" SET
4218 "last_login" = NULL,
4219 "login" = NULL,
4220 "password" = NULL,
4221 "notify_email" = NULL,
4222 "notify_email_unconfirmed" = NULL,
4223 "notify_email_secret" = NULL,
4224 "notify_email_secret_expiry" = NULL,
4225 "notify_email_lock_expiry" = NULL,
4226 "password_reset_secret" = NULL,
4227 "password_reset_secret_expiry" = NULL,
4228 "organizational_unit" = NULL,
4229 "internal_posts" = NULL,
4230 "realname" = NULL,
4231 "birthday" = NULL,
4232 "address" = NULL,
4233 "email" = NULL,
4234 "xmpp_address" = NULL,
4235 "website" = NULL,
4236 "phone" = NULL,
4237 "mobile_phone" = NULL,
4238 "profession" = NULL,
4239 "external_memberships" = NULL,
4240 "external_posts" = NULL,
4241 "statement" = NULL;
4242 -- "text_search_data" is updated by triggers
4243 DELETE FROM "invite_code";
4244 DELETE FROM "setting";
4245 DELETE FROM "setting_map";
4246 DELETE FROM "member_relation_setting";
4247 DELETE FROM "member_image";
4248 DELETE FROM "contact";
4249 DELETE FROM "ignored_member";
4250 DELETE FROM "session";
4251 DELETE FROM "area_setting";
4252 DELETE FROM "issue_setting";
4253 DELETE FROM "ignored_initiative";
4254 DELETE FROM "initiative_setting";
4255 DELETE FROM "suggestion_setting";
4256 DELETE FROM "non_voter";
4257 DELETE FROM "direct_voter" USING "issue"
4258 WHERE "direct_voter"."issue_id" = "issue"."id"
4259 AND "issue"."closed" ISNULL;
4260 RETURN;
4261 END;
4262 $$;
4264 COMMENT ON FUNCTION "delete_private_data"() IS 'Used by lf_export script. 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.';
4268 COMMIT;

Impressum / About Us