liquid_feedback_core

view core.sql @ 149:a07cfe298806

Dropped backwards compatiblity functions "array_init_string" and "square_matrix_init_string"
author jbe
date Thu Jun 02 02:07:50 2011 +0200 (2011-06-02)
parents ec1fdf2fc8c9
children a426ce0124a2
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 "majority_positive" INT4 NOT NULL DEFAULT 0,
315 "majority_non_negative" INT4 NOT NULL DEFAULT 0 );
316 CREATE INDEX "policy_active_idx" ON "policy" ("active");
318 COMMENT ON TABLE "policy" IS 'Policies for a particular proceeding type (timelimits, quorum)';
320 COMMENT ON COLUMN "policy"."index" IS 'Determines the order in listings';
321 COMMENT ON COLUMN "policy"."active" IS 'TRUE = policy can be used for new issues';
322 COMMENT ON COLUMN "policy"."admission_time" IS 'Maximum time an issue stays open without being "accepted"';
323 COMMENT ON COLUMN "policy"."discussion_time" IS 'Regular time until an issue is "half_frozen" after being "accepted"';
324 COMMENT ON COLUMN "policy"."verification_time" IS 'Regular time until an issue is "fully_frozen" after being "half_frozen"';
325 COMMENT ON COLUMN "policy"."voting_time" IS 'Time after an issue is "fully_frozen" but not "closed"';
326 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"';
327 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"';
328 COMMENT ON COLUMN "policy"."initiative_quorum_num" IS 'Numerator of satisfied supporter quorum to be reached by an initiative to be "admitted" for voting';
329 COMMENT ON COLUMN "policy"."initiative_quorum_den" IS 'Denominator of satisfied supporter quorum to be reached by an initiative to be "admitted" for voting';
330 COMMENT ON COLUMN "policy"."majority_num" IS 'Numerator of fraction of majority to be reached during voting by an initiative to be "attainable"';
331 COMMENT ON COLUMN "policy"."majority_den" IS 'Denominator of fraction of majority to be reached during voting by an initiative to be "attainable"';
332 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 COMMENT ON COLUMN "policy"."majority_positive" IS 'Absolute number of "positive_votes" neccessary for an initiative to be "attainable".';
334 COMMENT ON COLUMN "policy"."majority_non_negative" IS 'Absolute number of sum of "positive_votes" and abstentions neccessary for an initiative to be "attainable".';
337 CREATE TABLE "unit" (
338 "id" SERIAL4 PRIMARY KEY,
339 "parent_id" INT4 REFERENCES "unit" ("id") ON DELETE CASCADE ON UPDATE CASCADE,
340 "active" BOOLEAN NOT NULL DEFAULT TRUE,
341 "name" TEXT NOT NULL,
342 "description" TEXT NOT NULL DEFAULT '',
343 "member_count" INT4,
344 "text_search_data" TSVECTOR );
345 CREATE INDEX "unit_root_idx" ON "unit" ("id") WHERE "parent_id" ISNULL;
346 CREATE INDEX "unit_parent_id_idx" ON "unit" ("parent_id");
347 CREATE INDEX "unit_active_idx" ON "unit" ("active");
348 CREATE INDEX "unit_text_search_data_idx" ON "unit" USING gin ("text_search_data");
349 CREATE TRIGGER "update_text_search_data"
350 BEFORE INSERT OR UPDATE ON "unit"
351 FOR EACH ROW EXECUTE PROCEDURE
352 tsvector_update_trigger('text_search_data', 'pg_catalog.simple',
353 "name", "description" );
355 COMMENT ON TABLE "unit" IS 'Organizational units organized as trees; Delegations are not inherited through these trees.';
357 COMMENT ON COLUMN "unit"."parent_id" IS 'Parent id of tree node; Multiple roots allowed';
358 COMMENT ON COLUMN "unit"."active" IS 'TRUE means new issues can be created in units of this area';
359 COMMENT ON COLUMN "unit"."member_count" IS 'Count of members as determined by column "voting_right" in table "privilege"';
362 CREATE TABLE "area" (
363 "id" SERIAL4 PRIMARY KEY,
364 "unit_id" INT4 NOT NULL REFERENCES "unit" ("id") ON DELETE CASCADE ON UPDATE CASCADE,
365 "active" BOOLEAN NOT NULL DEFAULT TRUE,
366 "name" TEXT NOT NULL,
367 "description" TEXT NOT NULL DEFAULT '',
368 "direct_member_count" INT4,
369 "member_weight" INT4,
370 "autoreject_weight" INT4,
371 "text_search_data" TSVECTOR );
372 CREATE INDEX "area_unit_id_idx" ON "area" ("unit_id");
373 CREATE INDEX "area_active_idx" ON "area" ("active");
374 CREATE INDEX "area_text_search_data_idx" ON "area" USING gin ("text_search_data");
375 CREATE TRIGGER "update_text_search_data"
376 BEFORE INSERT OR UPDATE ON "area"
377 FOR EACH ROW EXECUTE PROCEDURE
378 tsvector_update_trigger('text_search_data', 'pg_catalog.simple',
379 "name", "description" );
381 COMMENT ON TABLE "area" IS 'Subject areas';
383 COMMENT ON COLUMN "area"."active" IS 'TRUE means new issues can be created in this area';
384 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"';
385 COMMENT ON COLUMN "area"."member_weight" IS 'Same as "direct_member_count" but respecting delegations';
386 COMMENT ON COLUMN "area"."autoreject_weight" IS 'Sum of weight of members using the autoreject feature';
389 CREATE TABLE "area_setting" (
390 PRIMARY KEY ("member_id", "key", "area_id"),
391 "member_id" INT4 REFERENCES "member" ("id") ON DELETE CASCADE ON UPDATE CASCADE,
392 "key" TEXT NOT NULL,
393 "area_id" INT4 REFERENCES "area" ("id") ON DELETE CASCADE ON UPDATE CASCADE,
394 "value" TEXT NOT NULL );
396 COMMENT ON TABLE "area_setting" IS 'Place for frontend to store area specific settings of members as strings';
399 CREATE TABLE "allowed_policy" (
400 PRIMARY KEY ("area_id", "policy_id"),
401 "area_id" INT4 REFERENCES "area" ("id") ON DELETE CASCADE ON UPDATE CASCADE,
402 "policy_id" INT4 NOT NULL REFERENCES "policy" ("id") ON DELETE CASCADE ON UPDATE CASCADE,
403 "default_policy" BOOLEAN NOT NULL DEFAULT FALSE );
404 CREATE UNIQUE INDEX "allowed_policy_one_default_per_area_idx" ON "allowed_policy" ("area_id") WHERE "default_policy";
406 COMMENT ON TABLE "allowed_policy" IS 'Selects which policies can be used in each area';
408 COMMENT ON COLUMN "allowed_policy"."default_policy" IS 'One policy per area can be set as default.';
411 CREATE TYPE "snapshot_event" AS ENUM ('periodic', 'end_of_admission', 'half_freeze', 'full_freeze');
413 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';
416 CREATE TYPE "issue_state" AS ENUM (
417 'admission', 'discussion', 'verification', 'voting',
418 'canceled_revoked_before_accepted',
419 'canceled_issue_not_accepted',
420 'canceled_after_revocation_during_discussion',
421 'canceled_after_revocation_during_verification',
422 'calculation',
423 'canceled_no_initiative_admitted',
424 'finished_without_winner', 'finished_with_winner');
426 COMMENT ON TYPE "issue_state" IS 'State of issues';
429 CREATE TABLE "issue" (
430 "id" SERIAL4 PRIMARY KEY,
431 "area_id" INT4 NOT NULL REFERENCES "area" ("id") ON DELETE CASCADE ON UPDATE CASCADE,
432 "policy_id" INT4 NOT NULL REFERENCES "policy" ("id") ON DELETE RESTRICT ON UPDATE CASCADE,
433 "state" "issue_state" NOT NULL DEFAULT 'admission',
434 "created" TIMESTAMPTZ NOT NULL DEFAULT now(),
435 "accepted" TIMESTAMPTZ,
436 "half_frozen" TIMESTAMPTZ,
437 "fully_frozen" TIMESTAMPTZ,
438 "closed" TIMESTAMPTZ,
439 "ranks_available" BOOLEAN NOT NULL DEFAULT FALSE,
440 "cleaned" TIMESTAMPTZ,
441 "admission_time" INTERVAL NOT NULL,
442 "discussion_time" INTERVAL NOT NULL,
443 "verification_time" INTERVAL NOT NULL,
444 "voting_time" INTERVAL NOT NULL,
445 "snapshot" TIMESTAMPTZ,
446 "latest_snapshot_event" "snapshot_event",
447 "population" INT4,
448 "voter_count" INT4,
449 CONSTRAINT "valid_state" CHECK ((
450 ("accepted" ISNULL AND "half_frozen" ISNULL AND "fully_frozen" ISNULL AND "closed" ISNULL AND "ranks_available" = FALSE) OR
451 ("accepted" ISNULL AND "half_frozen" ISNULL AND "fully_frozen" ISNULL AND "closed" NOTNULL AND "ranks_available" = FALSE) OR
452 ("accepted" NOTNULL AND "half_frozen" ISNULL AND "fully_frozen" ISNULL AND "closed" ISNULL AND "ranks_available" = FALSE) OR
453 ("accepted" NOTNULL AND "half_frozen" ISNULL AND "fully_frozen" ISNULL AND "closed" NOTNULL AND "ranks_available" = FALSE) OR
454 ("accepted" NOTNULL AND "half_frozen" NOTNULL AND "fully_frozen" ISNULL AND "closed" ISNULL AND "ranks_available" = FALSE) OR
455 ("accepted" NOTNULL AND "half_frozen" NOTNULL AND "fully_frozen" ISNULL AND "closed" NOTNULL AND "ranks_available" = FALSE) OR
456 ("accepted" NOTNULL AND "half_frozen" NOTNULL AND "fully_frozen" NOTNULL AND "closed" ISNULL AND "ranks_available" = FALSE) OR
457 ("accepted" NOTNULL AND "half_frozen" NOTNULL AND "fully_frozen" NOTNULL AND "closed" NOTNULL AND "ranks_available" = FALSE) OR
458 ("accepted" NOTNULL AND "half_frozen" NOTNULL AND "fully_frozen" NOTNULL AND "closed" NOTNULL AND "ranks_available" = TRUE)) AND (
459 ("state" = 'admission' AND "closed" ISNULL AND "accepted" ISNULL) OR
460 ("state" = 'discussion' AND "closed" ISNULL AND "accepted" NOTNULL AND "half_frozen" ISNULL) OR
461 ("state" = 'verification' AND "closed" ISNULL AND "half_frozen" NOTNULL AND "fully_frozen" ISNULL) OR
462 ("state" = 'voting' AND "closed" ISNULL AND "fully_frozen" NOTNULL) OR
463 ("state" = 'canceled_revoked_before_accepted' AND "closed" NOTNULL AND "accepted" ISNULL) OR
464 ("state" = 'canceled_issue_not_accepted' AND "closed" NOTNULL AND "accepted" ISNULL) OR
465 ("state" = 'canceled_after_revocation_during_discussion' AND "closed" NOTNULL AND "half_frozen" ISNULL) OR
466 ("state" = 'canceled_after_revocation_during_verification' AND "closed" NOTNULL AND "fully_frozen" ISNULL) OR
467 ("state" = 'calculation' AND "closed" NOTNULL AND "fully_frozen" NOTNULL AND "ranks_available" = FALSE) OR
468 ("state" = 'canceled_no_initiative_admitted' AND "closed" NOTNULL AND "fully_frozen" NOTNULL AND "ranks_available" = TRUE) OR
469 ("state" = 'finished_without_winner' AND "closed" NOTNULL AND "fully_frozen" NOTNULL AND "ranks_available" = TRUE) OR
470 ("state" = 'finished_with_winner' AND "closed" NOTNULL AND "fully_frozen" NOTNULL AND "ranks_available" = TRUE)
471 )),
472 CONSTRAINT "state_change_order" CHECK (
473 "created" <= "accepted" AND
474 "accepted" <= "half_frozen" AND
475 "half_frozen" <= "fully_frozen" AND
476 "fully_frozen" <= "closed" ),
477 CONSTRAINT "only_closed_issues_may_be_cleaned" CHECK (
478 "cleaned" ISNULL OR "closed" NOTNULL ),
479 CONSTRAINT "last_snapshot_on_full_freeze"
480 CHECK ("snapshot" = "fully_frozen"), -- NOTE: snapshot can be set, while frozen is NULL yet
481 CONSTRAINT "freeze_requires_snapshot"
482 CHECK ("fully_frozen" ISNULL OR "snapshot" NOTNULL),
483 CONSTRAINT "set_both_or_none_of_snapshot_and_latest_snapshot_event"
484 CHECK ("snapshot" NOTNULL = "latest_snapshot_event" NOTNULL) );
485 CREATE INDEX "issue_area_id_idx" ON "issue" ("area_id");
486 CREATE INDEX "issue_policy_id_idx" ON "issue" ("policy_id");
487 CREATE INDEX "issue_created_idx" ON "issue" ("created");
488 CREATE INDEX "issue_accepted_idx" ON "issue" ("accepted");
489 CREATE INDEX "issue_half_frozen_idx" ON "issue" ("half_frozen");
490 CREATE INDEX "issue_fully_frozen_idx" ON "issue" ("fully_frozen");
491 CREATE INDEX "issue_closed_idx" ON "issue" ("closed");
492 CREATE INDEX "issue_created_idx_open" ON "issue" ("created") WHERE "closed" ISNULL;
493 CREATE INDEX "issue_closed_idx_canceled" ON "issue" ("closed") WHERE "fully_frozen" ISNULL;
495 COMMENT ON TABLE "issue" IS 'Groups of initiatives';
497 COMMENT ON COLUMN "issue"."accepted" IS 'Point in time, when one initiative of issue reached the "issue_quorum"';
498 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.';
499 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.';
500 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.';
501 COMMENT ON COLUMN "issue"."ranks_available" IS 'TRUE = ranks have been calculated';
502 COMMENT ON COLUMN "issue"."cleaned" IS 'Point in time, when discussion data and votes had been deleted';
503 COMMENT ON COLUMN "issue"."admission_time" IS 'Copied from "policy" table at creation of issue';
504 COMMENT ON COLUMN "issue"."discussion_time" IS 'Copied from "policy" table at creation of issue';
505 COMMENT ON COLUMN "issue"."verification_time" IS 'Copied from "policy" table at creation of issue';
506 COMMENT ON COLUMN "issue"."voting_time" IS 'Copied from "policy" table at creation of issue';
507 COMMENT ON COLUMN "issue"."snapshot" IS 'Point in time, when snapshot tables have been updated and "population" and *_count values were precalculated';
508 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';
509 COMMENT ON COLUMN "issue"."population" IS 'Sum of "weight" column in table "direct_population_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", and "positive_votes" is greater-equal than "majority_positive", and ("positive_votes"+abstentions) is greater-equal than "majority_non_negative"';
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 either (a) has no better rank than the status quo, or (b) because there exists a better ranked initiative X, which directly beats this initiative, and either more voters prefer X to this initiative than voters preferring X to the status quo or less voters prefer this initiative to X than voters preferring the status quo to X';
588 COMMENT ON COLUMN "initiative"."winner" IS 'TRUE, if initiative is final winner (best ranked initiative being "attainable" 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/she is neither direct_ or delegating_voter; Entries in the "issue_autoreject" 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 CREATE INDEX "interest_member_id_idx" ON "interest" ("member_id");
753 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.';
756 CREATE TABLE "issue_autoreject" (
757 PRIMARY KEY ("issue_id", "member_id"),
758 "issue_id" INT4 REFERENCES "issue" ("id") ON DELETE CASCADE ON UPDATE CASCADE,
759 "member_id" INT4 REFERENCES "member" ("id") ON DELETE CASCADE ON UPDATE CASCADE,
760 "autoreject" BOOLEAN NOT NULL );
761 CREATE INDEX "issue_autoreject_member_id_idx" ON "issue_autoreject" ("member_id");
763 COMMENT ON TABLE "issue_autoreject" IS 'If autoreject=TRUE, then member votes against all initiatives, if he/she is neither direct_ or delegating_voter; Values of either TRUE or FALSE override settings in "membership" table.';
766 CREATE TABLE "initiator" (
767 PRIMARY KEY ("initiative_id", "member_id"),
768 "initiative_id" INT4 REFERENCES "initiative" ("id") ON DELETE CASCADE ON UPDATE CASCADE,
769 "member_id" INT4 REFERENCES "member" ("id") ON DELETE CASCADE ON UPDATE CASCADE,
770 "accepted" BOOLEAN );
771 CREATE INDEX "initiator_member_id_idx" ON "initiator" ("member_id");
773 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.';
775 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.';
778 CREATE TABLE "supporter" (
779 "issue_id" INT4 NOT NULL,
780 PRIMARY KEY ("initiative_id", "member_id"),
781 "initiative_id" INT4,
782 "member_id" INT4,
783 "draft_id" INT8 NOT NULL,
784 FOREIGN KEY ("issue_id", "member_id") REFERENCES "interest" ("issue_id", "member_id") ON DELETE CASCADE ON UPDATE CASCADE,
785 FOREIGN KEY ("initiative_id", "draft_id") REFERENCES "draft" ("initiative_id", "id") ON DELETE CASCADE ON UPDATE CASCADE );
786 CREATE INDEX "supporter_member_id_idx" ON "supporter" ("member_id");
788 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.';
790 COMMENT ON COLUMN "supporter"."draft_id" IS 'Latest seen draft, defaults to current draft of the initiative (implemented by trigger "default_for_draft_id")';
793 CREATE TABLE "opinion" (
794 "initiative_id" INT4 NOT NULL,
795 PRIMARY KEY ("suggestion_id", "member_id"),
796 "suggestion_id" INT8,
797 "member_id" INT4,
798 "degree" INT2 NOT NULL CHECK ("degree" >= -2 AND "degree" <= 2 AND "degree" != 0),
799 "fulfilled" BOOLEAN NOT NULL DEFAULT FALSE,
800 FOREIGN KEY ("initiative_id", "suggestion_id") REFERENCES "suggestion" ("initiative_id", "id") ON DELETE CASCADE ON UPDATE CASCADE,
801 FOREIGN KEY ("initiative_id", "member_id") REFERENCES "supporter" ("initiative_id", "member_id") ON DELETE CASCADE ON UPDATE CASCADE );
802 CREATE INDEX "opinion_member_id_initiative_id_idx" ON "opinion" ("member_id", "initiative_id");
804 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.';
806 COMMENT ON COLUMN "opinion"."degree" IS '2 = fulfillment required for support; 1 = fulfillment desired; -1 = fulfillment unwanted; -2 = fulfillment cancels support';
809 CREATE TYPE "delegation_scope" AS ENUM ('unit', 'area', 'issue');
811 COMMENT ON TYPE "delegation_scope" IS 'Scope for delegations: ''unit'', ''area'', or ''issue'' (order is relevant)';
814 CREATE TABLE "delegation" (
815 "id" SERIAL8 PRIMARY KEY,
816 "truster_id" INT4 NOT NULL REFERENCES "member" ("id") ON DELETE CASCADE ON UPDATE CASCADE,
817 "trustee_id" INT4 REFERENCES "member" ("id") ON DELETE CASCADE ON UPDATE CASCADE,
818 "scope" "delegation_scope" NOT NULL,
819 "unit_id" INT4 REFERENCES "unit" ("id") ON DELETE CASCADE ON UPDATE CASCADE,
820 "area_id" INT4 REFERENCES "area" ("id") ON DELETE CASCADE ON UPDATE CASCADE,
821 "issue_id" INT4 REFERENCES "issue" ("id") ON DELETE CASCADE ON UPDATE CASCADE,
822 CONSTRAINT "cant_delegate_to_yourself" CHECK ("truster_id" != "trustee_id"),
823 CONSTRAINT "no_unit_delegation_to_null"
824 CHECK ("trustee_id" NOTNULL OR "scope" != 'unit'),
825 CONSTRAINT "area_id_and_issue_id_set_according_to_scope" CHECK (
826 ("scope" = 'unit' AND "unit_id" NOTNULL AND "area_id" ISNULL AND "issue_id" ISNULL ) OR
827 ("scope" = 'area' AND "unit_id" ISNULL AND "area_id" NOTNULL AND "issue_id" ISNULL ) OR
828 ("scope" = 'issue' AND "unit_id" ISNULL AND "area_id" ISNULL AND "issue_id" NOTNULL) ),
829 UNIQUE ("unit_id", "truster_id"),
830 UNIQUE ("area_id", "truster_id"),
831 UNIQUE ("issue_id", "truster_id") );
832 CREATE INDEX "delegation_truster_id_idx" ON "delegation" ("truster_id");
833 CREATE INDEX "delegation_trustee_id_idx" ON "delegation" ("trustee_id");
835 COMMENT ON TABLE "delegation" IS 'Delegation of vote-weight to other members';
837 COMMENT ON COLUMN "delegation"."unit_id" IS 'Reference to unit, if delegation is unit-wide, otherwise NULL';
838 COMMENT ON COLUMN "delegation"."area_id" IS 'Reference to area, if delegation is area-wide, otherwise NULL';
839 COMMENT ON COLUMN "delegation"."issue_id" IS 'Reference to issue, if delegation is issue-wide, otherwise NULL';
842 CREATE TABLE "direct_population_snapshot" (
843 PRIMARY KEY ("issue_id", "event", "member_id"),
844 "issue_id" INT4 REFERENCES "issue" ("id") ON DELETE CASCADE ON UPDATE CASCADE,
845 "event" "snapshot_event",
846 "member_id" INT4 REFERENCES "member" ("id") ON DELETE RESTRICT ON UPDATE RESTRICT,
847 "weight" INT4 );
848 CREATE INDEX "direct_population_snapshot_member_id_idx" ON "direct_population_snapshot" ("member_id");
850 COMMENT ON TABLE "direct_population_snapshot" IS 'Snapshot of active members having either a "membership" in the "area", an "interest" in the "issue", or "issue_autoreject"."autoreject" set to TRUE';
852 COMMENT ON COLUMN "direct_population_snapshot"."event" IS 'Reason for snapshot, see "snapshot_event" type for details';
853 COMMENT ON COLUMN "direct_population_snapshot"."weight" IS 'Weight of member (1 or higher) according to "delegating_population_snapshot"';
856 CREATE TABLE "delegating_population_snapshot" (
857 PRIMARY KEY ("issue_id", "event", "member_id"),
858 "issue_id" INT4 REFERENCES "issue" ("id") ON DELETE CASCADE ON UPDATE CASCADE,
859 "event" "snapshot_event",
860 "member_id" INT4 REFERENCES "member" ("id") ON DELETE RESTRICT ON UPDATE RESTRICT,
861 "weight" INT4,
862 "scope" "delegation_scope" NOT NULL,
863 "delegate_member_ids" INT4[] NOT NULL );
864 CREATE INDEX "delegating_population_snapshot_member_id_idx" ON "delegating_population_snapshot" ("member_id");
866 COMMENT ON TABLE "direct_population_snapshot" IS 'Delegations increasing the weight of entries in the "direct_population_snapshot" table';
868 COMMENT ON COLUMN "delegating_population_snapshot"."event" IS 'Reason for snapshot, see "snapshot_event" type for details';
869 COMMENT ON COLUMN "delegating_population_snapshot"."member_id" IS 'Delegating member';
870 COMMENT ON COLUMN "delegating_population_snapshot"."weight" IS 'Intermediate weight';
871 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"';
874 CREATE TABLE "direct_interest_snapshot" (
875 PRIMARY KEY ("issue_id", "event", "member_id"),
876 "issue_id" INT4 REFERENCES "issue" ("id") ON DELETE CASCADE ON UPDATE CASCADE,
877 "event" "snapshot_event",
878 "member_id" INT4 REFERENCES "member" ("id") ON DELETE RESTRICT ON UPDATE RESTRICT,
879 "weight" INT4 );
880 CREATE INDEX "direct_interest_snapshot_member_id_idx" ON "direct_interest_snapshot" ("member_id");
882 COMMENT ON TABLE "direct_interest_snapshot" IS 'Snapshot of active members having an "interest" in the "issue"';
884 COMMENT ON COLUMN "direct_interest_snapshot"."event" IS 'Reason for snapshot, see "snapshot_event" type for details';
885 COMMENT ON COLUMN "direct_interest_snapshot"."weight" IS 'Weight of member (1 or higher) according to "delegating_interest_snapshot"';
888 CREATE TABLE "delegating_interest_snapshot" (
889 PRIMARY KEY ("issue_id", "event", "member_id"),
890 "issue_id" INT4 REFERENCES "issue" ("id") ON DELETE CASCADE ON UPDATE CASCADE,
891 "event" "snapshot_event",
892 "member_id" INT4 REFERENCES "member" ("id") ON DELETE RESTRICT ON UPDATE RESTRICT,
893 "weight" INT4,
894 "scope" "delegation_scope" NOT NULL,
895 "delegate_member_ids" INT4[] NOT NULL );
896 CREATE INDEX "delegating_interest_snapshot_member_id_idx" ON "delegating_interest_snapshot" ("member_id");
898 COMMENT ON TABLE "delegating_interest_snapshot" IS 'Delegations increasing the weight of entries in the "direct_interest_snapshot" table';
900 COMMENT ON COLUMN "delegating_interest_snapshot"."event" IS 'Reason for snapshot, see "snapshot_event" type for details';
901 COMMENT ON COLUMN "delegating_interest_snapshot"."member_id" IS 'Delegating member';
902 COMMENT ON COLUMN "delegating_interest_snapshot"."weight" IS 'Intermediate weight';
903 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"';
906 CREATE TABLE "direct_supporter_snapshot" (
907 "issue_id" INT4 NOT NULL,
908 PRIMARY KEY ("initiative_id", "event", "member_id"),
909 "initiative_id" INT4,
910 "event" "snapshot_event",
911 "member_id" INT4 REFERENCES "member" ("id") ON DELETE RESTRICT ON UPDATE RESTRICT,
912 "informed" BOOLEAN NOT NULL,
913 "satisfied" BOOLEAN NOT NULL,
914 FOREIGN KEY ("issue_id", "initiative_id") REFERENCES "initiative" ("issue_id", "id") ON DELETE CASCADE ON UPDATE CASCADE,
915 FOREIGN KEY ("issue_id", "event", "member_id") REFERENCES "direct_interest_snapshot" ("issue_id", "event", "member_id") ON DELETE CASCADE ON UPDATE CASCADE );
916 CREATE INDEX "direct_supporter_snapshot_member_id_idx" ON "direct_supporter_snapshot" ("member_id");
918 COMMENT ON TABLE "direct_supporter_snapshot" IS 'Snapshot of supporters of initiatives (weight is stored in "direct_interest_snapshot")';
920 COMMENT ON COLUMN "direct_supporter_snapshot"."event" IS 'Reason for snapshot, see "snapshot_event" type for details';
921 COMMENT ON COLUMN "direct_supporter_snapshot"."informed" IS 'Supporter has seen the latest draft of the initiative';
922 COMMENT ON COLUMN "direct_supporter_snapshot"."satisfied" IS 'Supporter has no "critical_opinion"s';
925 CREATE TABLE "non_voter" (
926 PRIMARY KEY ("issue_id", "member_id"),
927 "issue_id" INT4 REFERENCES "issue" ("id") ON DELETE CASCADE ON UPDATE CASCADE,
928 "member_id" INT4 REFERENCES "member" ("id") ON DELETE CASCADE ON UPDATE CASCADE );
929 CREATE INDEX "non_voter_member_id_idx" ON "non_voter" ("member_id");
931 COMMENT ON TABLE "non_voter" IS 'Members who decided to not vote directly on an issue';
934 CREATE TABLE "direct_voter" (
935 PRIMARY KEY ("issue_id", "member_id"),
936 "issue_id" INT4 REFERENCES "issue" ("id") ON DELETE CASCADE ON UPDATE CASCADE,
937 "member_id" INT4 REFERENCES "member" ("id") ON DELETE RESTRICT ON UPDATE RESTRICT,
938 "weight" INT4,
939 "autoreject" BOOLEAN NOT NULL DEFAULT FALSE );
940 CREATE INDEX "direct_voter_member_id_idx" ON "direct_voter" ("member_id");
942 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.';
944 COMMENT ON COLUMN "direct_voter"."weight" IS 'Weight of member (1 or higher) according to "delegating_voter" table';
945 COMMENT ON COLUMN "direct_voter"."autoreject" IS 'Votes were inserted due to "autoreject" feature';
948 CREATE TABLE "delegating_voter" (
949 PRIMARY KEY ("issue_id", "member_id"),
950 "issue_id" INT4 REFERENCES "issue" ("id") ON DELETE CASCADE ON UPDATE CASCADE,
951 "member_id" INT4 REFERENCES "member" ("id") ON DELETE RESTRICT ON UPDATE RESTRICT,
952 "weight" INT4,
953 "scope" "delegation_scope" NOT NULL,
954 "delegate_member_ids" INT4[] NOT NULL );
955 CREATE INDEX "delegating_voter_member_id_idx" ON "delegating_voter" ("member_id");
957 COMMENT ON TABLE "delegating_voter" IS 'Delegations increasing the weight of entries in the "direct_voter" table';
959 COMMENT ON COLUMN "delegating_voter"."member_id" IS 'Delegating member';
960 COMMENT ON COLUMN "delegating_voter"."weight" IS 'Intermediate weight';
961 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"';
964 CREATE TABLE "vote" (
965 "issue_id" INT4 NOT NULL,
966 PRIMARY KEY ("initiative_id", "member_id"),
967 "initiative_id" INT4,
968 "member_id" INT4,
969 "grade" INT4,
970 FOREIGN KEY ("issue_id", "initiative_id") REFERENCES "initiative" ("issue_id", "id") ON DELETE CASCADE ON UPDATE CASCADE,
971 FOREIGN KEY ("issue_id", "member_id") REFERENCES "direct_voter" ("issue_id", "member_id") ON DELETE CASCADE ON UPDATE CASCADE );
972 CREATE INDEX "vote_member_id_idx" ON "vote" ("member_id");
974 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.';
976 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.';
979 CREATE TABLE "issue_comment" (
980 PRIMARY KEY ("issue_id", "member_id"),
981 "issue_id" INT4 REFERENCES "issue" ("id") ON DELETE CASCADE ON UPDATE CASCADE,
982 "member_id" INT4 REFERENCES "member" ("id") ON DELETE CASCADE ON UPDATE CASCADE,
983 "changed" TIMESTAMPTZ NOT NULL DEFAULT now(),
984 "formatting_engine" TEXT,
985 "content" TEXT NOT NULL,
986 "text_search_data" TSVECTOR );
987 CREATE INDEX "issue_comment_member_id_idx" ON "issue_comment" ("member_id");
988 CREATE INDEX "issue_comment_text_search_data_idx" ON "issue_comment" USING gin ("text_search_data");
989 CREATE TRIGGER "update_text_search_data"
990 BEFORE INSERT OR UPDATE ON "issue_comment"
991 FOR EACH ROW EXECUTE PROCEDURE
992 tsvector_update_trigger('text_search_data', 'pg_catalog.simple', "content");
994 COMMENT ON TABLE "issue_comment" IS 'Place to store free comments of members related to issues';
996 COMMENT ON COLUMN "issue_comment"."changed" IS 'Time the comment was last changed';
999 CREATE TABLE "rendered_issue_comment" (
1000 PRIMARY KEY ("issue_id", "member_id", "format"),
1001 FOREIGN KEY ("issue_id", "member_id")
1002 REFERENCES "issue_comment" ("issue_id", "member_id")
1003 ON DELETE CASCADE ON UPDATE CASCADE,
1004 "issue_id" INT4,
1005 "member_id" INT4,
1006 "format" TEXT,
1007 "content" TEXT NOT NULL );
1009 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)';
1012 CREATE TABLE "voting_comment" (
1013 PRIMARY KEY ("issue_id", "member_id"),
1014 "issue_id" INT4 REFERENCES "issue" ("id") ON DELETE CASCADE ON UPDATE CASCADE,
1015 "member_id" INT4 REFERENCES "member" ("id") ON DELETE CASCADE ON UPDATE CASCADE,
1016 "changed" TIMESTAMPTZ,
1017 "formatting_engine" TEXT,
1018 "content" TEXT NOT NULL,
1019 "text_search_data" TSVECTOR );
1020 CREATE INDEX "voting_comment_member_id_idx" ON "voting_comment" ("member_id");
1021 CREATE INDEX "voting_comment_text_search_data_idx" ON "voting_comment" USING gin ("text_search_data");
1022 CREATE TRIGGER "update_text_search_data"
1023 BEFORE INSERT OR UPDATE ON "voting_comment"
1024 FOR EACH ROW EXECUTE PROCEDURE
1025 tsvector_update_trigger('text_search_data', 'pg_catalog.simple', "content");
1027 COMMENT ON TABLE "voting_comment" IS 'Storage for comments of voters to be published after voting has finished.';
1029 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.';
1032 CREATE TABLE "rendered_voting_comment" (
1033 PRIMARY KEY ("issue_id", "member_id", "format"),
1034 FOREIGN KEY ("issue_id", "member_id")
1035 REFERENCES "voting_comment" ("issue_id", "member_id")
1036 ON DELETE CASCADE ON UPDATE CASCADE,
1037 "issue_id" INT4,
1038 "member_id" INT4,
1039 "format" TEXT,
1040 "content" TEXT NOT NULL );
1042 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)';
1045 CREATE TYPE "event_type" AS ENUM (
1046 'issue_state_changed',
1047 'initiative_created_in_new_issue',
1048 'initiative_created_in_existing_issue',
1049 'initiative_revoked',
1050 'new_draft_created',
1051 'suggestion_created');
1053 COMMENT ON TYPE "event_type" IS 'Type used for column "event" of table "event"';
1056 CREATE TABLE "event" (
1057 "id" SERIAL8 PRIMARY KEY,
1058 "occurrence" TIMESTAMPTZ NOT NULL DEFAULT now(),
1059 "event" "event_type" NOT NULL,
1060 "member_id" INT4 REFERENCES "member" ("id") ON DELETE RESTRICT ON UPDATE CASCADE,
1061 "issue_id" INT4 REFERENCES "issue" ("id") ON DELETE CASCADE ON UPDATE CASCADE,
1062 "state" "issue_state" CHECK ("state" != 'calculation'),
1063 "initiative_id" INT4,
1064 "draft_id" INT8,
1065 "suggestion_id" INT8,
1066 FOREIGN KEY ("issue_id", "initiative_id")
1067 REFERENCES "initiative" ("issue_id", "id")
1068 ON DELETE CASCADE ON UPDATE CASCADE,
1069 FOREIGN KEY ("initiative_id", "draft_id")
1070 REFERENCES "draft" ("initiative_id", "id")
1071 ON DELETE CASCADE ON UPDATE CASCADE,
1072 FOREIGN KEY ("initiative_id", "suggestion_id")
1073 REFERENCES "suggestion" ("initiative_id", "id")
1074 ON DELETE CASCADE ON UPDATE CASCADE,
1075 CONSTRAINT "null_constraints_for_issue_state_changed" CHECK (
1076 "event" != 'issue_state_changed' OR (
1077 "member_id" ISNULL AND
1078 "issue_id" NOTNULL AND
1079 "state" NOTNULL AND
1080 "initiative_id" ISNULL AND
1081 "draft_id" ISNULL AND
1082 "suggestion_id" ISNULL )),
1083 CONSTRAINT "null_constraints_for_initiative_creation_or_revocation_or_new_draft" CHECK (
1084 "event" NOT IN (
1085 'initiative_created_in_new_issue',
1086 'initiative_created_in_existing_issue',
1087 'initiative_revoked',
1088 'new_draft_created'
1089 ) OR (
1090 "member_id" NOTNULL AND
1091 "issue_id" NOTNULL AND
1092 "state" NOTNULL AND
1093 "initiative_id" NOTNULL AND
1094 "draft_id" NOTNULL AND
1095 "suggestion_id" ISNULL )),
1096 CONSTRAINT "null_constraints_for_suggestion_creation" CHECK (
1097 "event" != 'suggestion_created' OR (
1098 "member_id" NOTNULL AND
1099 "issue_id" NOTNULL AND
1100 "state" NOTNULL AND
1101 "initiative_id" NOTNULL AND
1102 "draft_id" ISNULL AND
1103 "suggestion_id" NOTNULL )) );
1105 COMMENT ON TABLE "event" IS 'Event table, automatically filled by triggers';
1107 COMMENT ON COLUMN "event"."occurrence" IS 'Point in time, when event occurred';
1108 COMMENT ON COLUMN "event"."event" IS 'Type of event (see TYPE "event_type")';
1109 COMMENT ON COLUMN "event"."member_id" IS 'Member who caused the event, if applicable';
1110 COMMENT ON COLUMN "event"."state" IS 'If issue_id is set: state of affected issue; If state changed: new state';
1114 ----------------------------------------------
1115 -- Writing of history entries and event log --
1116 ----------------------------------------------
1118 CREATE FUNCTION "write_member_history_trigger"()
1119 RETURNS TRIGGER
1120 LANGUAGE 'plpgsql' VOLATILE AS $$
1121 BEGIN
1122 IF
1123 NEW."active" != OLD."active" OR
1124 NEW."name" != OLD."name"
1125 THEN
1126 INSERT INTO "member_history"
1127 ("member_id", "active", "name")
1128 VALUES (NEW."id", OLD."active", OLD."name");
1129 END IF;
1130 RETURN NULL;
1131 END;
1132 $$;
1134 CREATE TRIGGER "write_member_history"
1135 AFTER UPDATE ON "member" FOR EACH ROW EXECUTE PROCEDURE
1136 "write_member_history_trigger"();
1138 COMMENT ON FUNCTION "write_member_history_trigger"() IS 'Implementation of trigger "write_member_history" on table "member"';
1139 COMMENT ON TRIGGER "write_member_history" ON "member" IS 'When changing certain fields of a member, create a history entry in "member_history" table';
1142 CREATE FUNCTION "write_event_issue_state_changed_trigger"()
1143 RETURNS TRIGGER
1144 LANGUAGE 'plpgsql' VOLATILE AS $$
1145 BEGIN
1146 IF NEW."state" != OLD."state" AND NEW."state" != 'calculation' THEN
1147 INSERT INTO "event" ("event", "issue_id", "state")
1148 VALUES ('issue_state_changed', NEW."id", NEW."state");
1149 END IF;
1150 RETURN NULL;
1151 END;
1152 $$;
1154 CREATE TRIGGER "write_event_issue_state_changed"
1155 AFTER UPDATE ON "issue" FOR EACH ROW EXECUTE PROCEDURE
1156 "write_event_issue_state_changed_trigger"();
1158 COMMENT ON FUNCTION "write_event_issue_state_changed_trigger"() IS 'Implementation of trigger "write_event_issue_state_changed" on table "issue"';
1159 COMMENT ON TRIGGER "write_event_issue_state_changed" ON "issue" IS 'Create entry in "event" table on "state" change';
1162 CREATE FUNCTION "write_event_initiative_or_draft_created_trigger"()
1163 RETURNS TRIGGER
1164 LANGUAGE 'plpgsql' VOLATILE AS $$
1165 DECLARE
1166 "initiative_row" "initiative"%ROWTYPE;
1167 "issue_row" "issue"%ROWTYPE;
1168 "event_v" "event_type";
1169 BEGIN
1170 SELECT * INTO "initiative_row" FROM "initiative"
1171 WHERE "id" = NEW."initiative_id";
1172 SELECT * INTO "issue_row" FROM "issue"
1173 WHERE "id" = "initiative_row"."issue_id";
1174 IF EXISTS (
1175 SELECT NULL FROM "draft"
1176 WHERE "initiative_id" = NEW."initiative_id"
1177 AND "id" != NEW."id"
1178 ) THEN
1179 "event_v" := 'new_draft_created';
1180 ELSE
1181 IF EXISTS (
1182 SELECT NULL FROM "initiative"
1183 WHERE "issue_id" = "initiative_row"."issue_id"
1184 AND "id" != "initiative_row"."id"
1185 ) THEN
1186 "event_v" := 'initiative_created_in_existing_issue';
1187 ELSE
1188 "event_v" := 'initiative_created_in_new_issue';
1189 END IF;
1190 END IF;
1191 INSERT INTO "event" (
1192 "event", "member_id",
1193 "issue_id", "state", "initiative_id", "draft_id"
1194 ) VALUES (
1195 "event_v",
1196 NEW."author_id",
1197 "initiative_row"."issue_id",
1198 "issue_row"."state",
1199 "initiative_row"."id",
1200 NEW."id" );
1201 RETURN NULL;
1202 END;
1203 $$;
1205 CREATE TRIGGER "write_event_initiative_or_draft_created"
1206 AFTER INSERT ON "draft" FOR EACH ROW EXECUTE PROCEDURE
1207 "write_event_initiative_or_draft_created_trigger"();
1209 COMMENT ON FUNCTION "write_event_initiative_or_draft_created_trigger"() IS 'Implementation of trigger "write_event_initiative_or_draft_created" on table "issue"';
1210 COMMENT ON TRIGGER "write_event_initiative_or_draft_created" ON "draft" IS 'Create entry in "event" table on draft creation';
1213 CREATE FUNCTION "write_event_initiative_revoked_trigger"()
1214 RETURNS TRIGGER
1215 LANGUAGE 'plpgsql' VOLATILE AS $$
1216 DECLARE
1217 "issue_row" "issue"%ROWTYPE;
1218 BEGIN
1219 SELECT * INTO "issue_row" FROM "issue"
1220 WHERE "id" = NEW."issue_id";
1221 IF OLD."revoked" ISNULL AND NEW."revoked" NOTNULL THEN
1222 INSERT INTO "event" (
1223 "event", "member_id", "issue_id", "state", "initiative_id"
1224 ) VALUES (
1225 'initiative_revoked',
1226 NEW."revoked_by_member_id",
1227 NEW."issue_id",
1228 "issue_row"."state",
1229 NEW."id" );
1230 END IF;
1231 RETURN NULL;
1232 END;
1233 $$;
1235 CREATE TRIGGER "write_event_initiative_revoked"
1236 AFTER UPDATE ON "initiative" FOR EACH ROW EXECUTE PROCEDURE
1237 "write_event_initiative_revoked_trigger"();
1239 COMMENT ON FUNCTION "write_event_initiative_revoked_trigger"() IS 'Implementation of trigger "write_event_initiative_revoked" on table "issue"';
1240 COMMENT ON TRIGGER "write_event_initiative_revoked" ON "initiative" IS 'Create entry in "event" table, when an initiative is revoked';
1243 CREATE FUNCTION "write_event_suggestion_created_trigger"()
1244 RETURNS TRIGGER
1245 LANGUAGE 'plpgsql' VOLATILE AS $$
1246 DECLARE
1247 "initiative_row" "initiative"%ROWTYPE;
1248 "issue_row" "issue"%ROWTYPE;
1249 BEGIN
1250 SELECT * INTO "initiative_row" FROM "initiative"
1251 WHERE "id" = NEW."initiative_id";
1252 SELECT * INTO "issue_row" FROM "issue"
1253 WHERE "id" = "initiative_row"."issue_id";
1254 INSERT INTO "event" (
1255 "event", "member_id",
1256 "issue_id", "state", "initiative_id", "suggestion_id"
1257 ) VALUES (
1258 'suggestion_created',
1259 NEW."author_id",
1260 "initiative_row"."issue_id",
1261 "issue_row"."state",
1262 "initiative_row"."id",
1263 NEW."id" );
1264 RETURN NULL;
1265 END;
1266 $$;
1268 CREATE TRIGGER "write_event_suggestion_created"
1269 AFTER INSERT ON "suggestion" FOR EACH ROW EXECUTE PROCEDURE
1270 "write_event_suggestion_created_trigger"();
1272 COMMENT ON FUNCTION "write_event_suggestion_created_trigger"() IS 'Implementation of trigger "write_event_suggestion_created" on table "issue"';
1273 COMMENT ON TRIGGER "write_event_suggestion_created" ON "suggestion" IS 'Create entry in "event" table on suggestion creation';
1277 ----------------------------
1278 -- Additional constraints --
1279 ----------------------------
1282 CREATE FUNCTION "issue_requires_first_initiative_trigger"()
1283 RETURNS TRIGGER
1284 LANGUAGE 'plpgsql' VOLATILE AS $$
1285 BEGIN
1286 IF NOT EXISTS (
1287 SELECT NULL FROM "initiative" WHERE "issue_id" = NEW."id"
1288 ) THEN
1289 --RAISE 'Cannot create issue without an initial initiative.' USING
1290 -- ERRCODE = 'integrity_constraint_violation',
1291 -- HINT = 'Create issue, initiative, and draft within the same transaction.';
1292 RAISE EXCEPTION 'Cannot create issue without an initial initiative.';
1293 END IF;
1294 RETURN NULL;
1295 END;
1296 $$;
1298 CREATE CONSTRAINT TRIGGER "issue_requires_first_initiative"
1299 AFTER INSERT OR UPDATE ON "issue" DEFERRABLE INITIALLY DEFERRED
1300 FOR EACH ROW EXECUTE PROCEDURE
1301 "issue_requires_first_initiative_trigger"();
1303 COMMENT ON FUNCTION "issue_requires_first_initiative_trigger"() IS 'Implementation of trigger "issue_requires_first_initiative" on table "issue"';
1304 COMMENT ON TRIGGER "issue_requires_first_initiative" ON "issue" IS 'Ensure that new issues have at least one initiative';
1307 CREATE FUNCTION "last_initiative_deletes_issue_trigger"()
1308 RETURNS TRIGGER
1309 LANGUAGE 'plpgsql' VOLATILE AS $$
1310 DECLARE
1311 "reference_lost" BOOLEAN;
1312 BEGIN
1313 IF TG_OP = 'DELETE' THEN
1314 "reference_lost" := TRUE;
1315 ELSE
1316 "reference_lost" := NEW."issue_id" != OLD."issue_id";
1317 END IF;
1318 IF
1319 "reference_lost" AND NOT EXISTS (
1320 SELECT NULL FROM "initiative" WHERE "issue_id" = OLD."issue_id"
1322 THEN
1323 DELETE FROM "issue" WHERE "id" = OLD."issue_id";
1324 END IF;
1325 RETURN NULL;
1326 END;
1327 $$;
1329 CREATE CONSTRAINT TRIGGER "last_initiative_deletes_issue"
1330 AFTER UPDATE OR DELETE ON "initiative" DEFERRABLE INITIALLY DEFERRED
1331 FOR EACH ROW EXECUTE PROCEDURE
1332 "last_initiative_deletes_issue_trigger"();
1334 COMMENT ON FUNCTION "last_initiative_deletes_issue_trigger"() IS 'Implementation of trigger "last_initiative_deletes_issue" on table "initiative"';
1335 COMMENT ON TRIGGER "last_initiative_deletes_issue" ON "initiative" IS 'Removing the last initiative of an issue deletes the issue';
1338 CREATE FUNCTION "initiative_requires_first_draft_trigger"()
1339 RETURNS TRIGGER
1340 LANGUAGE 'plpgsql' VOLATILE AS $$
1341 BEGIN
1342 IF NOT EXISTS (
1343 SELECT NULL FROM "draft" WHERE "initiative_id" = NEW."id"
1344 ) THEN
1345 --RAISE 'Cannot create initiative without an initial draft.' USING
1346 -- ERRCODE = 'integrity_constraint_violation',
1347 -- HINT = 'Create issue, initiative and draft within the same transaction.';
1348 RAISE EXCEPTION 'Cannot create initiative without an initial draft.';
1349 END IF;
1350 RETURN NULL;
1351 END;
1352 $$;
1354 CREATE CONSTRAINT TRIGGER "initiative_requires_first_draft"
1355 AFTER INSERT OR UPDATE ON "initiative" DEFERRABLE INITIALLY DEFERRED
1356 FOR EACH ROW EXECUTE PROCEDURE
1357 "initiative_requires_first_draft_trigger"();
1359 COMMENT ON FUNCTION "initiative_requires_first_draft_trigger"() IS 'Implementation of trigger "initiative_requires_first_draft" on table "initiative"';
1360 COMMENT ON TRIGGER "initiative_requires_first_draft" ON "initiative" IS 'Ensure that new initiatives have at least one draft';
1363 CREATE FUNCTION "last_draft_deletes_initiative_trigger"()
1364 RETURNS TRIGGER
1365 LANGUAGE 'plpgsql' VOLATILE AS $$
1366 DECLARE
1367 "reference_lost" BOOLEAN;
1368 BEGIN
1369 IF TG_OP = 'DELETE' THEN
1370 "reference_lost" := TRUE;
1371 ELSE
1372 "reference_lost" := NEW."initiative_id" != OLD."initiative_id";
1373 END IF;
1374 IF
1375 "reference_lost" AND NOT EXISTS (
1376 SELECT NULL FROM "draft" WHERE "initiative_id" = OLD."initiative_id"
1378 THEN
1379 DELETE FROM "initiative" WHERE "id" = OLD."initiative_id";
1380 END IF;
1381 RETURN NULL;
1382 END;
1383 $$;
1385 CREATE CONSTRAINT TRIGGER "last_draft_deletes_initiative"
1386 AFTER UPDATE OR DELETE ON "draft" DEFERRABLE INITIALLY DEFERRED
1387 FOR EACH ROW EXECUTE PROCEDURE
1388 "last_draft_deletes_initiative_trigger"();
1390 COMMENT ON FUNCTION "last_draft_deletes_initiative_trigger"() IS 'Implementation of trigger "last_draft_deletes_initiative" on table "draft"';
1391 COMMENT ON TRIGGER "last_draft_deletes_initiative" ON "draft" IS 'Removing the last draft of an initiative deletes the initiative';
1394 CREATE FUNCTION "suggestion_requires_first_opinion_trigger"()
1395 RETURNS TRIGGER
1396 LANGUAGE 'plpgsql' VOLATILE AS $$
1397 BEGIN
1398 IF NOT EXISTS (
1399 SELECT NULL FROM "opinion" WHERE "suggestion_id" = NEW."id"
1400 ) THEN
1401 RAISE EXCEPTION 'Cannot create a suggestion without an opinion.';
1402 END IF;
1403 RETURN NULL;
1404 END;
1405 $$;
1407 CREATE CONSTRAINT TRIGGER "suggestion_requires_first_opinion"
1408 AFTER INSERT OR UPDATE ON "suggestion" DEFERRABLE INITIALLY DEFERRED
1409 FOR EACH ROW EXECUTE PROCEDURE
1410 "suggestion_requires_first_opinion_trigger"();
1412 COMMENT ON FUNCTION "suggestion_requires_first_opinion_trigger"() IS 'Implementation of trigger "suggestion_requires_first_opinion" on table "suggestion"';
1413 COMMENT ON TRIGGER "suggestion_requires_first_opinion" ON "suggestion" IS 'Ensure that new suggestions have at least one opinion';
1416 CREATE FUNCTION "last_opinion_deletes_suggestion_trigger"()
1417 RETURNS TRIGGER
1418 LANGUAGE 'plpgsql' VOLATILE AS $$
1419 DECLARE
1420 "reference_lost" BOOLEAN;
1421 BEGIN
1422 IF TG_OP = 'DELETE' THEN
1423 "reference_lost" := TRUE;
1424 ELSE
1425 "reference_lost" := NEW."suggestion_id" != OLD."suggestion_id";
1426 END IF;
1427 IF
1428 "reference_lost" AND NOT EXISTS (
1429 SELECT NULL FROM "opinion" WHERE "suggestion_id" = OLD."suggestion_id"
1431 THEN
1432 DELETE FROM "suggestion" WHERE "id" = OLD."suggestion_id";
1433 END IF;
1434 RETURN NULL;
1435 END;
1436 $$;
1438 CREATE CONSTRAINT TRIGGER "last_opinion_deletes_suggestion"
1439 AFTER UPDATE OR DELETE ON "opinion" DEFERRABLE INITIALLY DEFERRED
1440 FOR EACH ROW EXECUTE PROCEDURE
1441 "last_opinion_deletes_suggestion_trigger"();
1443 COMMENT ON FUNCTION "last_opinion_deletes_suggestion_trigger"() IS 'Implementation of trigger "last_opinion_deletes_suggestion" on table "opinion"';
1444 COMMENT ON TRIGGER "last_opinion_deletes_suggestion" ON "opinion" IS 'Removing the last opinion of a suggestion deletes the suggestion';
1448 ---------------------------------------------------------------
1449 -- Ensure that votes are not modified when issues are frozen --
1450 ---------------------------------------------------------------
1452 -- NOTE: Frontends should ensure this anyway, but in case of programming
1453 -- errors the following triggers ensure data integrity.
1456 CREATE FUNCTION "forbid_changes_on_closed_issue_trigger"()
1457 RETURNS TRIGGER
1458 LANGUAGE 'plpgsql' VOLATILE AS $$
1459 DECLARE
1460 "issue_id_v" "issue"."id"%TYPE;
1461 "issue_row" "issue"%ROWTYPE;
1462 BEGIN
1463 IF TG_OP = 'DELETE' THEN
1464 "issue_id_v" := OLD."issue_id";
1465 ELSE
1466 "issue_id_v" := NEW."issue_id";
1467 END IF;
1468 SELECT INTO "issue_row" * FROM "issue"
1469 WHERE "id" = "issue_id_v" FOR SHARE;
1470 IF "issue_row"."closed" NOTNULL THEN
1471 RAISE EXCEPTION 'Tried to modify data belonging to a closed issue.';
1472 END IF;
1473 RETURN NULL;
1474 END;
1475 $$;
1477 CREATE TRIGGER "forbid_changes_on_closed_issue"
1478 AFTER INSERT OR UPDATE OR DELETE ON "direct_voter"
1479 FOR EACH ROW EXECUTE PROCEDURE
1480 "forbid_changes_on_closed_issue_trigger"();
1482 CREATE TRIGGER "forbid_changes_on_closed_issue"
1483 AFTER INSERT OR UPDATE OR DELETE ON "delegating_voter"
1484 FOR EACH ROW EXECUTE PROCEDURE
1485 "forbid_changes_on_closed_issue_trigger"();
1487 CREATE TRIGGER "forbid_changes_on_closed_issue"
1488 AFTER INSERT OR UPDATE OR DELETE ON "vote"
1489 FOR EACH ROW EXECUTE PROCEDURE
1490 "forbid_changes_on_closed_issue_trigger"();
1492 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"';
1493 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';
1494 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';
1495 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';
1499 --------------------------------------------------------------------
1500 -- Auto-retrieval of fields only needed for referential integrity --
1501 --------------------------------------------------------------------
1504 CREATE FUNCTION "autofill_issue_id_trigger"()
1505 RETURNS TRIGGER
1506 LANGUAGE 'plpgsql' VOLATILE AS $$
1507 BEGIN
1508 IF NEW."issue_id" ISNULL THEN
1509 SELECT "issue_id" INTO NEW."issue_id"
1510 FROM "initiative" WHERE "id" = NEW."initiative_id";
1511 END IF;
1512 RETURN NEW;
1513 END;
1514 $$;
1516 CREATE TRIGGER "autofill_issue_id" BEFORE INSERT ON "supporter"
1517 FOR EACH ROW EXECUTE PROCEDURE "autofill_issue_id_trigger"();
1519 CREATE TRIGGER "autofill_issue_id" BEFORE INSERT ON "vote"
1520 FOR EACH ROW EXECUTE PROCEDURE "autofill_issue_id_trigger"();
1522 COMMENT ON FUNCTION "autofill_issue_id_trigger"() IS 'Implementation of triggers "autofill_issue_id" on tables "supporter" and "vote"';
1523 COMMENT ON TRIGGER "autofill_issue_id" ON "supporter" IS 'Set "issue_id" field automatically, if NULL';
1524 COMMENT ON TRIGGER "autofill_issue_id" ON "vote" IS 'Set "issue_id" field automatically, if NULL';
1527 CREATE FUNCTION "autofill_initiative_id_trigger"()
1528 RETURNS TRIGGER
1529 LANGUAGE 'plpgsql' VOLATILE AS $$
1530 BEGIN
1531 IF NEW."initiative_id" ISNULL THEN
1532 SELECT "initiative_id" INTO NEW."initiative_id"
1533 FROM "suggestion" WHERE "id" = NEW."suggestion_id";
1534 END IF;
1535 RETURN NEW;
1536 END;
1537 $$;
1539 CREATE TRIGGER "autofill_initiative_id" BEFORE INSERT ON "opinion"
1540 FOR EACH ROW EXECUTE PROCEDURE "autofill_initiative_id_trigger"();
1542 COMMENT ON FUNCTION "autofill_initiative_id_trigger"() IS 'Implementation of trigger "autofill_initiative_id" on table "opinion"';
1543 COMMENT ON TRIGGER "autofill_initiative_id" ON "opinion" IS 'Set "initiative_id" field automatically, if NULL';
1547 -----------------------------------------------------
1548 -- Automatic calculation of certain default values --
1549 -----------------------------------------------------
1552 CREATE FUNCTION "copy_timings_trigger"()
1553 RETURNS TRIGGER
1554 LANGUAGE 'plpgsql' VOLATILE AS $$
1555 DECLARE
1556 "policy_row" "policy"%ROWTYPE;
1557 BEGIN
1558 SELECT * INTO "policy_row" FROM "policy"
1559 WHERE "id" = NEW."policy_id";
1560 IF NEW."admission_time" ISNULL THEN
1561 NEW."admission_time" := "policy_row"."admission_time";
1562 END IF;
1563 IF NEW."discussion_time" ISNULL THEN
1564 NEW."discussion_time" := "policy_row"."discussion_time";
1565 END IF;
1566 IF NEW."verification_time" ISNULL THEN
1567 NEW."verification_time" := "policy_row"."verification_time";
1568 END IF;
1569 IF NEW."voting_time" ISNULL THEN
1570 NEW."voting_time" := "policy_row"."voting_time";
1571 END IF;
1572 RETURN NEW;
1573 END;
1574 $$;
1576 CREATE TRIGGER "copy_timings" BEFORE INSERT OR UPDATE ON "issue"
1577 FOR EACH ROW EXECUTE PROCEDURE "copy_timings_trigger"();
1579 COMMENT ON FUNCTION "copy_timings_trigger"() IS 'Implementation of trigger "copy_timings" on table "issue"';
1580 COMMENT ON TRIGGER "copy_timings" ON "issue" IS 'If timing fields are NULL, copy values from policy.';
1583 CREATE FUNCTION "supporter_default_for_draft_id_trigger"()
1584 RETURNS TRIGGER
1585 LANGUAGE 'plpgsql' VOLATILE AS $$
1586 BEGIN
1587 IF NEW."draft_id" ISNULL THEN
1588 SELECT "id" INTO NEW."draft_id" FROM "current_draft"
1589 WHERE "initiative_id" = NEW."initiative_id";
1590 END IF;
1591 RETURN NEW;
1592 END;
1593 $$;
1595 CREATE TRIGGER "default_for_draft_id" BEFORE INSERT OR UPDATE ON "supporter"
1596 FOR EACH ROW EXECUTE PROCEDURE "supporter_default_for_draft_id_trigger"();
1598 COMMENT ON FUNCTION "supporter_default_for_draft_id_trigger"() IS 'Implementation of trigger "default_for_draft" on table "supporter"';
1599 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';
1603 ----------------------------------------
1604 -- Automatic creation of dependencies --
1605 ----------------------------------------
1608 CREATE FUNCTION "autocreate_interest_trigger"()
1609 RETURNS TRIGGER
1610 LANGUAGE 'plpgsql' VOLATILE AS $$
1611 BEGIN
1612 IF NOT EXISTS (
1613 SELECT NULL FROM "initiative" JOIN "interest"
1614 ON "initiative"."issue_id" = "interest"."issue_id"
1615 WHERE "initiative"."id" = NEW."initiative_id"
1616 AND "interest"."member_id" = NEW."member_id"
1617 ) THEN
1618 BEGIN
1619 INSERT INTO "interest" ("issue_id", "member_id")
1620 SELECT "issue_id", NEW."member_id"
1621 FROM "initiative" WHERE "id" = NEW."initiative_id";
1622 EXCEPTION WHEN unique_violation THEN END;
1623 END IF;
1624 RETURN NEW;
1625 END;
1626 $$;
1628 CREATE TRIGGER "autocreate_interest" BEFORE INSERT ON "supporter"
1629 FOR EACH ROW EXECUTE PROCEDURE "autocreate_interest_trigger"();
1631 COMMENT ON FUNCTION "autocreate_interest_trigger"() IS 'Implementation of trigger "autocreate_interest" on table "supporter"';
1632 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';
1635 CREATE FUNCTION "autocreate_supporter_trigger"()
1636 RETURNS TRIGGER
1637 LANGUAGE 'plpgsql' VOLATILE AS $$
1638 BEGIN
1639 IF NOT EXISTS (
1640 SELECT NULL FROM "suggestion" JOIN "supporter"
1641 ON "suggestion"."initiative_id" = "supporter"."initiative_id"
1642 WHERE "suggestion"."id" = NEW."suggestion_id"
1643 AND "supporter"."member_id" = NEW."member_id"
1644 ) THEN
1645 BEGIN
1646 INSERT INTO "supporter" ("initiative_id", "member_id")
1647 SELECT "initiative_id", NEW."member_id"
1648 FROM "suggestion" WHERE "id" = NEW."suggestion_id";
1649 EXCEPTION WHEN unique_violation THEN END;
1650 END IF;
1651 RETURN NEW;
1652 END;
1653 $$;
1655 CREATE TRIGGER "autocreate_supporter" BEFORE INSERT ON "opinion"
1656 FOR EACH ROW EXECUTE PROCEDURE "autocreate_supporter_trigger"();
1658 COMMENT ON FUNCTION "autocreate_supporter_trigger"() IS 'Implementation of trigger "autocreate_supporter" on table "opinion"';
1659 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.';
1663 ------------------------------------------
1664 -- Views and helper functions for views --
1665 ------------------------------------------
1668 CREATE VIEW "unit_delegation" AS
1669 SELECT
1670 "unit"."id" AS "unit_id",
1671 "delegation"."id",
1672 "delegation"."truster_id",
1673 "delegation"."trustee_id",
1674 "delegation"."scope"
1675 FROM "unit"
1676 JOIN "delegation"
1677 ON "delegation"."unit_id" = "unit"."id"
1678 JOIN "member"
1679 ON "delegation"."truster_id" = "member"."id"
1680 JOIN "privilege"
1681 ON "delegation"."unit_id" = "privilege"."unit_id"
1682 AND "delegation"."truster_id" = "privilege"."member_id"
1683 WHERE "member"."active" AND "privilege"."voting_right";
1685 COMMENT ON VIEW "unit_delegation" IS 'Unit delegations where trusters are active and have voting right';
1688 CREATE VIEW "area_delegation" AS
1689 SELECT DISTINCT ON ("area"."id", "delegation"."truster_id")
1690 "area"."id" AS "area_id",
1691 "delegation"."id",
1692 "delegation"."truster_id",
1693 "delegation"."trustee_id",
1694 "delegation"."scope"
1695 FROM "area"
1696 JOIN "delegation"
1697 ON "delegation"."unit_id" = "area"."unit_id"
1698 OR "delegation"."area_id" = "area"."id"
1699 JOIN "member"
1700 ON "delegation"."truster_id" = "member"."id"
1701 JOIN "privilege"
1702 ON "area"."unit_id" = "privilege"."unit_id"
1703 AND "delegation"."truster_id" = "privilege"."member_id"
1704 WHERE "member"."active" AND "privilege"."voting_right"
1705 ORDER BY
1706 "area"."id",
1707 "delegation"."truster_id",
1708 "delegation"."scope" DESC;
1710 COMMENT ON VIEW "area_delegation" IS 'Area delegations where trusters are active and have voting right';
1713 CREATE VIEW "issue_delegation" AS
1714 SELECT DISTINCT ON ("issue"."id", "delegation"."truster_id")
1715 "issue"."id" AS "issue_id",
1716 "delegation"."id",
1717 "delegation"."truster_id",
1718 "delegation"."trustee_id",
1719 "delegation"."scope"
1720 FROM "issue"
1721 JOIN "area"
1722 ON "area"."id" = "issue"."area_id"
1723 JOIN "delegation"
1724 ON "delegation"."unit_id" = "area"."unit_id"
1725 OR "delegation"."area_id" = "area"."id"
1726 OR "delegation"."issue_id" = "issue"."id"
1727 JOIN "member"
1728 ON "delegation"."truster_id" = "member"."id"
1729 JOIN "privilege"
1730 ON "area"."unit_id" = "privilege"."unit_id"
1731 AND "delegation"."truster_id" = "privilege"."member_id"
1732 WHERE "member"."active" AND "privilege"."voting_right"
1733 ORDER BY
1734 "issue"."id",
1735 "delegation"."truster_id",
1736 "delegation"."scope" DESC;
1738 COMMENT ON VIEW "issue_delegation" IS 'Issue delegations where trusters are active and have voting right';
1741 CREATE FUNCTION "membership_weight_with_skipping"
1742 ( "area_id_p" "area"."id"%TYPE,
1743 "member_id_p" "member"."id"%TYPE,
1744 "skip_member_ids_p" INT4[] ) -- "member"."id"%TYPE[]
1745 RETURNS INT4
1746 LANGUAGE 'plpgsql' STABLE AS $$
1747 DECLARE
1748 "sum_v" INT4;
1749 "delegation_row" "area_delegation"%ROWTYPE;
1750 BEGIN
1751 "sum_v" := 1;
1752 FOR "delegation_row" IN
1753 SELECT "area_delegation".*
1754 FROM "area_delegation" LEFT JOIN "membership"
1755 ON "membership"."area_id" = "area_id_p"
1756 AND "membership"."member_id" = "area_delegation"."truster_id"
1757 WHERE "area_delegation"."area_id" = "area_id_p"
1758 AND "area_delegation"."trustee_id" = "member_id_p"
1759 AND "membership"."member_id" ISNULL
1760 LOOP
1761 IF NOT
1762 "skip_member_ids_p" @> ARRAY["delegation_row"."truster_id"]
1763 THEN
1764 "sum_v" := "sum_v" + "membership_weight_with_skipping"(
1765 "area_id_p",
1766 "delegation_row"."truster_id",
1767 "skip_member_ids_p" || "delegation_row"."truster_id"
1768 );
1769 END IF;
1770 END LOOP;
1771 RETURN "sum_v";
1772 END;
1773 $$;
1775 COMMENT ON FUNCTION "membership_weight_with_skipping"
1776 ( "area"."id"%TYPE,
1777 "member"."id"%TYPE,
1778 INT4[] )
1779 IS 'Helper function for "membership_weight" function';
1782 CREATE FUNCTION "membership_weight"
1783 ( "area_id_p" "area"."id"%TYPE,
1784 "member_id_p" "member"."id"%TYPE ) -- "member"."id"%TYPE[]
1785 RETURNS INT4
1786 LANGUAGE 'plpgsql' STABLE AS $$
1787 BEGIN
1788 RETURN "membership_weight_with_skipping"(
1789 "area_id_p",
1790 "member_id_p",
1791 ARRAY["member_id_p"]
1792 );
1793 END;
1794 $$;
1796 COMMENT ON FUNCTION "membership_weight"
1797 ( "area"."id"%TYPE,
1798 "member"."id"%TYPE )
1799 IS 'Calculates the potential voting weight of a member in a given area';
1802 CREATE VIEW "member_count_view" AS
1803 SELECT count(1) AS "total_count" FROM "member" WHERE "active";
1805 COMMENT ON VIEW "member_count_view" IS 'View used to update "member_count" table';
1808 CREATE VIEW "unit_member_count" AS
1809 SELECT
1810 "unit"."id" AS "unit_id",
1811 sum("member"."id") AS "member_count"
1812 FROM "unit"
1813 LEFT JOIN "privilege"
1814 ON "privilege"."unit_id" = "unit"."id"
1815 AND "privilege"."voting_right"
1816 LEFT JOIN "member"
1817 ON "member"."id" = "privilege"."member_id"
1818 AND "member"."active"
1819 GROUP BY "unit"."id";
1821 COMMENT ON VIEW "unit_member_count" IS 'View used to update "member_count" column of "unit" table';
1824 CREATE VIEW "area_member_count" AS
1825 SELECT
1826 "area"."id" AS "area_id",
1827 count("member"."id") AS "direct_member_count",
1828 coalesce(
1829 sum(
1830 CASE WHEN "member"."id" NOTNULL THEN
1831 "membership_weight"("area"."id", "member"."id")
1832 ELSE 0 END
1834 ) AS "member_weight",
1835 coalesce(
1836 sum(
1837 CASE WHEN "member"."id" NOTNULL AND "membership"."autoreject" THEN
1838 "membership_weight"("area"."id", "member"."id")
1839 ELSE 0 END
1841 ) AS "autoreject_weight"
1842 FROM "area"
1843 LEFT JOIN "membership"
1844 ON "area"."id" = "membership"."area_id"
1845 LEFT JOIN "privilege"
1846 ON "privilege"."unit_id" = "area"."unit_id"
1847 AND "privilege"."member_id" = "membership"."member_id"
1848 AND "privilege"."voting_right"
1849 LEFT JOIN "member"
1850 ON "member"."id" = "privilege"."member_id" -- NOTE: no membership here!
1851 AND "member"."active"
1852 GROUP BY "area"."id";
1854 COMMENT ON VIEW "area_member_count" IS 'View used to update "direct_member_count", "member_weight" and "autoreject_weight" columns of table "area"';
1857 CREATE VIEW "opening_draft" AS
1858 SELECT "draft".* FROM (
1859 SELECT
1860 "initiative"."id" AS "initiative_id",
1861 min("draft"."id") AS "draft_id"
1862 FROM "initiative" JOIN "draft"
1863 ON "initiative"."id" = "draft"."initiative_id"
1864 GROUP BY "initiative"."id"
1865 ) AS "subquery"
1866 JOIN "draft" ON "subquery"."draft_id" = "draft"."id";
1868 COMMENT ON VIEW "opening_draft" IS 'First drafts of all initiatives';
1871 CREATE VIEW "current_draft" AS
1872 SELECT "draft".* FROM (
1873 SELECT
1874 "initiative"."id" AS "initiative_id",
1875 max("draft"."id") AS "draft_id"
1876 FROM "initiative" JOIN "draft"
1877 ON "initiative"."id" = "draft"."initiative_id"
1878 GROUP BY "initiative"."id"
1879 ) AS "subquery"
1880 JOIN "draft" ON "subquery"."draft_id" = "draft"."id";
1882 COMMENT ON VIEW "current_draft" IS 'All latest drafts for each initiative';
1885 CREATE VIEW "critical_opinion" AS
1886 SELECT * FROM "opinion"
1887 WHERE ("degree" = 2 AND "fulfilled" = FALSE)
1888 OR ("degree" = -2 AND "fulfilled" = TRUE);
1890 COMMENT ON VIEW "critical_opinion" IS 'Opinions currently causing dissatisfaction';
1893 CREATE VIEW "battle_participant" AS
1894 SELECT "initiative"."id", "initiative"."issue_id"
1895 FROM "issue" JOIN "initiative"
1896 ON "issue"."id" = "initiative"."issue_id"
1897 WHERE "initiative"."admitted"
1898 UNION ALL
1899 SELECT NULL, "id" AS "issue_id"
1900 FROM "issue";
1902 COMMENT ON VIEW "battle_participant" IS 'Helper view for "battle_view" containing admitted initiatives plus virtual "status-quo" initiative denoted by NULL reference';
1905 CREATE VIEW "battle_view" AS
1906 SELECT
1907 "issue"."id" AS "issue_id",
1908 "winning_initiative"."id" AS "winning_initiative_id",
1909 "losing_initiative"."id" AS "losing_initiative_id",
1910 sum(
1911 CASE WHEN
1912 coalesce("better_vote"."grade", 0) >
1913 coalesce("worse_vote"."grade", 0)
1914 THEN "direct_voter"."weight" ELSE 0 END
1915 ) AS "count"
1916 FROM "issue"
1917 LEFT JOIN "direct_voter"
1918 ON "issue"."id" = "direct_voter"."issue_id"
1919 JOIN "battle_participant" AS "winning_initiative"
1920 ON "issue"."id" = "winning_initiative"."issue_id"
1921 JOIN "battle_participant" AS "losing_initiative"
1922 ON "issue"."id" = "losing_initiative"."issue_id"
1923 LEFT JOIN "vote" AS "better_vote"
1924 ON "direct_voter"."member_id" = "better_vote"."member_id"
1925 AND "winning_initiative"."id" = "better_vote"."initiative_id"
1926 LEFT JOIN "vote" AS "worse_vote"
1927 ON "direct_voter"."member_id" = "worse_vote"."member_id"
1928 AND "losing_initiative"."id" = "worse_vote"."initiative_id"
1929 WHERE "issue"."closed" NOTNULL
1930 AND "issue"."cleaned" ISNULL
1931 AND (
1932 "winning_initiative"."id" != "losing_initiative"."id" OR
1933 ( ("winning_initiative"."id" NOTNULL AND "losing_initiative"."id" ISNULL) OR
1934 ("winning_initiative"."id" ISNULL AND "losing_initiative"."id" NOTNULL) ) )
1935 GROUP BY
1936 "issue"."id",
1937 "winning_initiative"."id",
1938 "losing_initiative"."id";
1940 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';
1943 CREATE VIEW "expired_session" AS
1944 SELECT * FROM "session" WHERE now() > "expiry";
1946 CREATE RULE "delete" AS ON DELETE TO "expired_session" DO INSTEAD
1947 DELETE FROM "session" WHERE "ident" = OLD."ident";
1949 COMMENT ON VIEW "expired_session" IS 'View containing all expired sessions where DELETE is possible';
1950 COMMENT ON RULE "delete" ON "expired_session" IS 'Rule allowing DELETE on rows in "expired_session" view, i.e. DELETE FROM "expired_session"';
1953 CREATE VIEW "open_issue" AS
1954 SELECT * FROM "issue" WHERE "closed" ISNULL;
1956 COMMENT ON VIEW "open_issue" IS 'All open issues';
1959 CREATE VIEW "issue_with_ranks_missing" AS
1960 SELECT * FROM "issue"
1961 WHERE "fully_frozen" NOTNULL
1962 AND "closed" NOTNULL
1963 AND "ranks_available" = FALSE;
1965 COMMENT ON VIEW "issue_with_ranks_missing" IS 'Issues where voting was finished, but no ranks have been calculated yet';
1968 CREATE VIEW "member_contingent" AS
1969 SELECT
1970 "member"."id" AS "member_id",
1971 "contingent"."time_frame",
1972 CASE WHEN "contingent"."text_entry_limit" NOTNULL THEN
1974 SELECT count(1) FROM "draft"
1975 WHERE "draft"."author_id" = "member"."id"
1976 AND "draft"."created" > now() - "contingent"."time_frame"
1977 ) + (
1978 SELECT count(1) FROM "suggestion"
1979 WHERE "suggestion"."author_id" = "member"."id"
1980 AND "suggestion"."created" > now() - "contingent"."time_frame"
1982 ELSE NULL END AS "text_entry_count",
1983 "contingent"."text_entry_limit",
1984 CASE WHEN "contingent"."initiative_limit" NOTNULL THEN (
1985 SELECT count(1) FROM "opening_draft"
1986 WHERE "opening_draft"."author_id" = "member"."id"
1987 AND "opening_draft"."created" > now() - "contingent"."time_frame"
1988 ) ELSE NULL END AS "initiative_count",
1989 "contingent"."initiative_limit"
1990 FROM "member" CROSS JOIN "contingent";
1992 COMMENT ON VIEW "member_contingent" IS 'Actual counts of text entries and initiatives are calculated per member for each limit in the "contingent" table.';
1994 COMMENT ON COLUMN "member_contingent"."text_entry_count" IS 'Only calculated when "text_entry_limit" is not null in the same row';
1995 COMMENT ON COLUMN "member_contingent"."initiative_count" IS 'Only calculated when "initiative_limit" is not null in the same row';
1998 CREATE VIEW "member_contingent_left" AS
1999 SELECT
2000 "member_id",
2001 max("text_entry_limit" - "text_entry_count") AS "text_entries_left",
2002 max("initiative_limit" - "initiative_count") AS "initiatives_left"
2003 FROM "member_contingent" GROUP BY "member_id";
2005 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.';
2008 CREATE VIEW "event_seen_by_member" AS
2009 SELECT
2010 "member"."id" AS "seen_by_member_id",
2011 CASE WHEN "event"."state" IN (
2012 'voting',
2013 'finished_without_winner',
2014 'finished_with_winner'
2015 ) THEN
2016 'voting'::"notify_level"
2017 ELSE
2018 CASE WHEN "event"."state" IN (
2019 'verification',
2020 'canceled_after_revocation_during_verification',
2021 'canceled_no_initiative_admitted'
2022 ) THEN
2023 'verification'::"notify_level"
2024 ELSE
2025 CASE WHEN "event"."state" IN (
2026 'discussion',
2027 'canceled_after_revocation_during_discussion'
2028 ) THEN
2029 'discussion'::"notify_level"
2030 ELSE
2031 'all'::"notify_level"
2032 END
2033 END
2034 END AS "notify_level",
2035 "event".*
2036 FROM "member" CROSS JOIN "event"
2037 LEFT JOIN "issue"
2038 ON "event"."issue_id" = "issue"."id"
2039 LEFT JOIN "membership"
2040 ON "member"."id" = "membership"."member_id"
2041 AND "issue"."area_id" = "membership"."area_id"
2042 LEFT JOIN "interest"
2043 ON "member"."id" = "interest"."member_id"
2044 AND "event"."issue_id" = "interest"."issue_id"
2045 LEFT JOIN "supporter"
2046 ON "member"."id" = "supporter"."member_id"
2047 AND "event"."initiative_id" = "supporter"."initiative_id"
2048 LEFT JOIN "ignored_member"
2049 ON "member"."id" = "ignored_member"."member_id"
2050 AND "event"."member_id" = "ignored_member"."other_member_id"
2051 LEFT JOIN "ignored_initiative"
2052 ON "member"."id" = "ignored_initiative"."member_id"
2053 AND "event"."initiative_id" = "ignored_initiative"."initiative_id"
2054 WHERE (
2055 "supporter"."member_id" NOTNULL OR
2056 "interest"."member_id" NOTNULL OR
2057 ( "membership"."member_id" NOTNULL AND
2058 "event"."event" IN (
2059 'issue_state_changed',
2060 'initiative_created_in_new_issue',
2061 'initiative_created_in_existing_issue',
2062 'initiative_revoked' ) ) )
2063 AND "ignored_member"."member_id" ISNULL
2064 AND "ignored_initiative"."member_id" ISNULL;
2066 COMMENT ON VIEW "event_seen_by_member" IS 'Events as seen by a member, depending on its memberships, interests and support';
2069 CREATE VIEW "pending_notification" AS
2070 SELECT
2071 "member"."id" AS "seen_by_member_id",
2072 "event".*
2073 FROM "member" CROSS JOIN "event"
2074 LEFT JOIN "issue"
2075 ON "event"."issue_id" = "issue"."id"
2076 LEFT JOIN "membership"
2077 ON "member"."id" = "membership"."member_id"
2078 AND "issue"."area_id" = "membership"."area_id"
2079 LEFT JOIN "interest"
2080 ON "member"."id" = "interest"."member_id"
2081 AND "event"."issue_id" = "interest"."issue_id"
2082 LEFT JOIN "supporter"
2083 ON "member"."id" = "supporter"."member_id"
2084 AND "event"."initiative_id" = "supporter"."initiative_id"
2085 LEFT JOIN "ignored_member"
2086 ON "member"."id" = "ignored_member"."member_id"
2087 AND "event"."member_id" = "ignored_member"."other_member_id"
2088 LEFT JOIN "ignored_initiative"
2089 ON "member"."id" = "ignored_initiative"."member_id"
2090 AND "event"."initiative_id" = "ignored_initiative"."initiative_id"
2091 WHERE (
2092 "member"."notify_event_id" ISNULL OR
2093 ( "member"."notify_event_id" NOTNULL AND
2094 "member"."notify_event_id" < "event"."id" ) )
2095 AND (
2096 ( "member"."notify_level" >= 'all' ) OR
2097 ( "member"."notify_level" >= 'voting' AND
2098 "event"."state" IN (
2099 'voting',
2100 'finished_without_winner',
2101 'finished_with_winner' ) ) OR
2102 ( "member"."notify_level" >= 'verification' AND
2103 "event"."state" IN (
2104 'verification',
2105 'canceled_after_revocation_during_verification',
2106 'canceled_no_initiative_admitted' ) ) OR
2107 ( "member"."notify_level" >= 'discussion' AND
2108 "event"."state" IN (
2109 'discussion',
2110 'canceled_after_revocation_during_discussion' ) ) )
2111 AND (
2112 "supporter"."member_id" NOTNULL OR
2113 "interest"."member_id" NOTNULL OR
2114 ( "membership"."member_id" NOTNULL AND
2115 "event"."event" IN (
2116 'issue_state_changed',
2117 'initiative_created_in_new_issue',
2118 'initiative_created_in_existing_issue',
2119 'initiative_revoked' ) ) )
2120 AND "ignored_member"."member_id" ISNULL
2121 AND "ignored_initiative"."member_id" ISNULL;
2123 COMMENT ON VIEW "pending_notification" IS 'Events to be sent to "notify_email" address of member referred to by "seen_by_member_id"';
2126 CREATE TYPE "timeline_event" AS ENUM (
2127 'issue_created',
2128 'issue_canceled',
2129 'issue_accepted',
2130 'issue_half_frozen',
2131 'issue_finished_without_voting',
2132 'issue_voting_started',
2133 'issue_finished_after_voting',
2134 'initiative_created',
2135 'initiative_revoked',
2136 'draft_created',
2137 'suggestion_created');
2139 COMMENT ON TYPE "timeline_event" IS 'Types of event in timeline tables (DEPRECATED)';
2142 CREATE VIEW "timeline_issue" AS
2143 SELECT
2144 "created" AS "occurrence",
2145 'issue_created'::"timeline_event" AS "event",
2146 "id" AS "issue_id"
2147 FROM "issue"
2148 UNION ALL
2149 SELECT
2150 "closed" AS "occurrence",
2151 'issue_canceled'::"timeline_event" AS "event",
2152 "id" AS "issue_id"
2153 FROM "issue" WHERE "closed" NOTNULL AND "fully_frozen" ISNULL
2154 UNION ALL
2155 SELECT
2156 "accepted" AS "occurrence",
2157 'issue_accepted'::"timeline_event" AS "event",
2158 "id" AS "issue_id"
2159 FROM "issue" WHERE "accepted" NOTNULL
2160 UNION ALL
2161 SELECT
2162 "half_frozen" AS "occurrence",
2163 'issue_half_frozen'::"timeline_event" AS "event",
2164 "id" AS "issue_id"
2165 FROM "issue" WHERE "half_frozen" NOTNULL
2166 UNION ALL
2167 SELECT
2168 "fully_frozen" AS "occurrence",
2169 'issue_voting_started'::"timeline_event" AS "event",
2170 "id" AS "issue_id"
2171 FROM "issue"
2172 WHERE "fully_frozen" NOTNULL
2173 AND ("closed" ISNULL OR "closed" != "fully_frozen")
2174 UNION ALL
2175 SELECT
2176 "closed" AS "occurrence",
2177 CASE WHEN "fully_frozen" = "closed" THEN
2178 'issue_finished_without_voting'::"timeline_event"
2179 ELSE
2180 'issue_finished_after_voting'::"timeline_event"
2181 END AS "event",
2182 "id" AS "issue_id"
2183 FROM "issue" WHERE "closed" NOTNULL AND "fully_frozen" NOTNULL;
2185 COMMENT ON VIEW "timeline_issue" IS 'Helper view for "timeline" view (DEPRECATED)';
2188 CREATE VIEW "timeline_initiative" AS
2189 SELECT
2190 "created" AS "occurrence",
2191 'initiative_created'::"timeline_event" AS "event",
2192 "id" AS "initiative_id"
2193 FROM "initiative"
2194 UNION ALL
2195 SELECT
2196 "revoked" AS "occurrence",
2197 'initiative_revoked'::"timeline_event" AS "event",
2198 "id" AS "initiative_id"
2199 FROM "initiative" WHERE "revoked" NOTNULL;
2201 COMMENT ON VIEW "timeline_initiative" IS 'Helper view for "timeline" view (DEPRECATED)';
2204 CREATE VIEW "timeline_draft" AS
2205 SELECT
2206 "created" AS "occurrence",
2207 'draft_created'::"timeline_event" AS "event",
2208 "id" AS "draft_id"
2209 FROM "draft";
2211 COMMENT ON VIEW "timeline_draft" IS 'Helper view for "timeline" view (DEPRECATED)';
2214 CREATE VIEW "timeline_suggestion" AS
2215 SELECT
2216 "created" AS "occurrence",
2217 'suggestion_created'::"timeline_event" AS "event",
2218 "id" AS "suggestion_id"
2219 FROM "suggestion";
2221 COMMENT ON VIEW "timeline_suggestion" IS 'Helper view for "timeline" view (DEPRECATED)';
2224 CREATE VIEW "timeline" AS
2225 SELECT
2226 "occurrence",
2227 "event",
2228 "issue_id",
2229 NULL AS "initiative_id",
2230 NULL::INT8 AS "draft_id", -- TODO: Why do we need a type-cast here? Is this due to 32 bit architecture?
2231 NULL::INT8 AS "suggestion_id"
2232 FROM "timeline_issue"
2233 UNION ALL
2234 SELECT
2235 "occurrence",
2236 "event",
2237 NULL AS "issue_id",
2238 "initiative_id",
2239 NULL AS "draft_id",
2240 NULL AS "suggestion_id"
2241 FROM "timeline_initiative"
2242 UNION ALL
2243 SELECT
2244 "occurrence",
2245 "event",
2246 NULL AS "issue_id",
2247 NULL AS "initiative_id",
2248 "draft_id",
2249 NULL AS "suggestion_id"
2250 FROM "timeline_draft"
2251 UNION ALL
2252 SELECT
2253 "occurrence",
2254 "event",
2255 NULL AS "issue_id",
2256 NULL AS "initiative_id",
2257 NULL AS "draft_id",
2258 "suggestion_id"
2259 FROM "timeline_suggestion";
2261 COMMENT ON VIEW "timeline" IS 'Aggregation of different events in the system (DEPRECATED)';
2265 --------------------------------------------------
2266 -- Set returning function for delegation chains --
2267 --------------------------------------------------
2270 CREATE TYPE "delegation_chain_loop_tag" AS ENUM
2271 ('first', 'intermediate', 'last', 'repetition');
2273 COMMENT ON TYPE "delegation_chain_loop_tag" IS 'Type for loop tags in "delegation_chain_row" type';
2276 CREATE TYPE "delegation_chain_row" AS (
2277 "index" INT4,
2278 "member_id" INT4,
2279 "member_valid" BOOLEAN,
2280 "participation" BOOLEAN,
2281 "overridden" BOOLEAN,
2282 "scope_in" "delegation_scope",
2283 "scope_out" "delegation_scope",
2284 "disabled_out" BOOLEAN,
2285 "loop" "delegation_chain_loop_tag" );
2287 COMMENT ON TYPE "delegation_chain_row" IS 'Type of rows returned by "delegation_chain"(...) functions';
2289 COMMENT ON COLUMN "delegation_chain_row"."index" IS 'Index starting with 0 and counting up';
2290 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';
2291 COMMENT ON COLUMN "delegation_chain_row"."overridden" IS 'True, if an entry with lower index has "participation" set to true';
2292 COMMENT ON COLUMN "delegation_chain_row"."scope_in" IS 'Scope of used incoming delegation';
2293 COMMENT ON COLUMN "delegation_chain_row"."scope_out" IS 'Scope of used outgoing delegation';
2294 COMMENT ON COLUMN "delegation_chain_row"."disabled_out" IS 'Outgoing delegation is explicitly disabled by a delegation with trustee_id set to NULL';
2295 COMMENT ON COLUMN "delegation_chain_row"."loop" IS 'Not null, if member is part of a loop, see "delegation_chain_loop_tag" type';
2298 CREATE FUNCTION "delegation_chain"
2299 ( "member_id_p" "member"."id"%TYPE,
2300 "unit_id_p" "unit"."id"%TYPE,
2301 "area_id_p" "area"."id"%TYPE,
2302 "issue_id_p" "issue"."id"%TYPE,
2303 "simulate_trustee_id_p" "member"."id"%TYPE )
2304 RETURNS SETOF "delegation_chain_row"
2305 LANGUAGE 'plpgsql' STABLE AS $$
2306 DECLARE
2307 "scope_v" "delegation_scope";
2308 "unit_id_v" "unit"."id"%TYPE;
2309 "area_id_v" "area"."id"%TYPE;
2310 "visited_member_ids" INT4[]; -- "member"."id"%TYPE[]
2311 "loop_member_id_v" "member"."id"%TYPE;
2312 "output_row" "delegation_chain_row";
2313 "output_rows" "delegation_chain_row"[];
2314 "delegation_row" "delegation"%ROWTYPE;
2315 "row_count" INT4;
2316 "i" INT4;
2317 "loop_v" BOOLEAN;
2318 BEGIN
2319 IF
2320 "unit_id_p" NOTNULL AND
2321 "area_id_p" ISNULL AND
2322 "issue_id_p" ISNULL
2323 THEN
2324 "scope_v" := 'unit';
2325 "unit_id_v" := "unit_id_p";
2326 ELSIF
2327 "unit_id_p" ISNULL AND
2328 "area_id_p" NOTNULL AND
2329 "issue_id_p" ISNULL
2330 THEN
2331 "scope_v" := 'area';
2332 "area_id_v" := "area_id_p";
2333 SELECT "unit_id" INTO "unit_id_v"
2334 FROM "area" WHERE "id" = "area_id_v";
2335 ELSIF
2336 "unit_id_p" ISNULL AND
2337 "area_id_p" ISNULL AND
2338 "issue_id_p" NOTNULL
2339 THEN
2340 "scope_v" := 'issue';
2341 SELECT "area_id" INTO "area_id_v"
2342 FROM "issue" WHERE "id" = "issue_id_p";
2343 SELECT "unit_id" INTO "unit_id_v"
2344 FROM "area" WHERE "id" = "area_id_v";
2345 ELSE
2346 RAISE EXCEPTION 'Exactly one of unit_id_p, area_id_p, or issue_id_p must be NOTNULL.';
2347 END IF;
2348 "visited_member_ids" := '{}';
2349 "loop_member_id_v" := NULL;
2350 "output_rows" := '{}';
2351 "output_row"."index" := 0;
2352 "output_row"."member_id" := "member_id_p";
2353 "output_row"."member_valid" := TRUE;
2354 "output_row"."participation" := FALSE;
2355 "output_row"."overridden" := FALSE;
2356 "output_row"."disabled_out" := FALSE;
2357 "output_row"."scope_out" := NULL;
2358 LOOP
2359 IF "visited_member_ids" @> ARRAY["output_row"."member_id"] THEN
2360 "loop_member_id_v" := "output_row"."member_id";
2361 ELSE
2362 "visited_member_ids" :=
2363 "visited_member_ids" || "output_row"."member_id";
2364 END IF;
2365 IF "output_row"."participation" THEN
2366 "output_row"."overridden" := TRUE;
2367 END IF;
2368 "output_row"."scope_in" := "output_row"."scope_out";
2369 IF EXISTS (
2370 SELECT NULL FROM "member" JOIN "privilege"
2371 ON "privilege"."member_id" = "member"."id"
2372 AND "privilege"."unit_id" = "unit_id_v"
2373 WHERE "id" = "output_row"."member_id"
2374 AND "member"."active" AND "privilege"."voting_right"
2375 ) THEN
2376 IF "scope_v" = 'unit' THEN
2377 SELECT * INTO "delegation_row" FROM "delegation"
2378 WHERE "truster_id" = "output_row"."member_id"
2379 AND "unit_id" = "unit_id_v";
2380 ELSIF "scope_v" = 'area' THEN
2381 "output_row"."participation" := EXISTS (
2382 SELECT NULL FROM "membership"
2383 WHERE "area_id" = "area_id_p"
2384 AND "member_id" = "output_row"."member_id"
2385 );
2386 SELECT * INTO "delegation_row" FROM "delegation"
2387 WHERE "truster_id" = "output_row"."member_id"
2388 AND (
2389 "unit_id" = "unit_id_v" OR
2390 "area_id" = "area_id_v"
2392 ORDER BY "scope" DESC;
2393 ELSIF "scope_v" = 'issue' THEN
2394 "output_row"."participation" := EXISTS (
2395 SELECT NULL FROM "interest"
2396 WHERE "issue_id" = "issue_id_p"
2397 AND "member_id" = "output_row"."member_id"
2398 );
2399 SELECT * INTO "delegation_row" FROM "delegation"
2400 WHERE "truster_id" = "output_row"."member_id"
2401 AND (
2402 "unit_id" = "unit_id_v" OR
2403 "area_id" = "area_id_v" OR
2404 "issue_id" = "issue_id_p"
2406 ORDER BY "scope" DESC;
2407 END IF;
2408 ELSE
2409 "output_row"."member_valid" := FALSE;
2410 "output_row"."participation" := FALSE;
2411 "output_row"."scope_out" := NULL;
2412 "delegation_row" := ROW(NULL);
2413 END IF;
2414 IF
2415 "output_row"."member_id" = "member_id_p" AND
2416 "simulate_trustee_id_p" NOTNULL
2417 THEN
2418 "output_row"."scope_out" := "scope_v";
2419 "output_rows" := "output_rows" || "output_row";
2420 "output_row"."member_id" := "simulate_trustee_id_p";
2421 ELSIF "delegation_row"."trustee_id" NOTNULL THEN
2422 "output_row"."scope_out" := "delegation_row"."scope";
2423 "output_rows" := "output_rows" || "output_row";
2424 "output_row"."member_id" := "delegation_row"."trustee_id";
2425 ELSIF "delegation_row"."scope" NOTNULL THEN
2426 "output_row"."scope_out" := "delegation_row"."scope";
2427 "output_row"."disabled_out" := TRUE;
2428 "output_rows" := "output_rows" || "output_row";
2429 EXIT;
2430 ELSE
2431 "output_row"."scope_out" := NULL;
2432 "output_rows" := "output_rows" || "output_row";
2433 EXIT;
2434 END IF;
2435 EXIT WHEN "loop_member_id_v" NOTNULL;
2436 "output_row"."index" := "output_row"."index" + 1;
2437 END LOOP;
2438 "row_count" := array_upper("output_rows", 1);
2439 "i" := 1;
2440 "loop_v" := FALSE;
2441 LOOP
2442 "output_row" := "output_rows"["i"];
2443 EXIT WHEN "output_row" ISNULL; -- NOTE: ISNULL and NOT ... NOTNULL produce different results!
2444 IF "loop_v" THEN
2445 IF "i" + 1 = "row_count" THEN
2446 "output_row"."loop" := 'last';
2447 ELSIF "i" = "row_count" THEN
2448 "output_row"."loop" := 'repetition';
2449 ELSE
2450 "output_row"."loop" := 'intermediate';
2451 END IF;
2452 ELSIF "output_row"."member_id" = "loop_member_id_v" THEN
2453 "output_row"."loop" := 'first';
2454 "loop_v" := TRUE;
2455 END IF;
2456 IF "scope_v" = 'unit' THEN
2457 "output_row"."participation" := NULL;
2458 END IF;
2459 RETURN NEXT "output_row";
2460 "i" := "i" + 1;
2461 END LOOP;
2462 RETURN;
2463 END;
2464 $$;
2466 COMMENT ON FUNCTION "delegation_chain"
2467 ( "member"."id"%TYPE,
2468 "unit"."id"%TYPE,
2469 "area"."id"%TYPE,
2470 "issue"."id"%TYPE,
2471 "member"."id"%TYPE )
2472 IS 'Helper function for frontends to display delegation chains; Not part of internal voting logic';
2475 CREATE FUNCTION "delegation_chain"
2476 ( "member_id_p" "member"."id"%TYPE,
2477 "unit_id_p" "unit"."id"%TYPE,
2478 "area_id_p" "area"."id"%TYPE,
2479 "issue_id_p" "issue"."id"%TYPE )
2480 RETURNS SETOF "delegation_chain_row"
2481 LANGUAGE 'plpgsql' STABLE AS $$
2482 DECLARE
2483 "result_row" "delegation_chain_row";
2484 BEGIN
2485 FOR "result_row" IN
2486 SELECT * FROM "delegation_chain"(
2487 "member_id_p", "unit_id_p", "area_id_p", "issue_id_p", NULL
2489 LOOP
2490 RETURN NEXT "result_row";
2491 END LOOP;
2492 RETURN;
2493 END;
2494 $$;
2496 COMMENT ON FUNCTION "delegation_chain"
2497 ( "member"."id"%TYPE,
2498 "unit"."id"%TYPE,
2499 "area"."id"%TYPE,
2500 "issue"."id"%TYPE )
2501 IS 'Shortcut for "delegation_chain"(...) function where 4th parameter is null';
2505 ------------------------------
2506 -- Comparison by vote count --
2507 ------------------------------
2509 CREATE FUNCTION "vote_ratio"
2510 ( "positive_votes_p" "initiative"."positive_votes"%TYPE,
2511 "negative_votes_p" "initiative"."negative_votes"%TYPE )
2512 RETURNS FLOAT8
2513 LANGUAGE 'plpgsql' STABLE AS $$
2514 BEGIN
2515 IF "positive_votes_p" > 0 AND "negative_votes_p" > 0 THEN
2516 RETURN
2517 "positive_votes_p"::FLOAT8 /
2518 ("positive_votes_p" + "negative_votes_p")::FLOAT8;
2519 ELSIF "positive_votes_p" > 0 THEN
2520 RETURN "positive_votes_p";
2521 ELSIF "negative_votes_p" > 0 THEN
2522 RETURN 1 - "negative_votes_p";
2523 ELSE
2524 RETURN 0.5;
2525 END IF;
2526 END;
2527 $$;
2529 COMMENT ON FUNCTION "vote_ratio"
2530 ( "initiative"."positive_votes"%TYPE,
2531 "initiative"."negative_votes"%TYPE )
2532 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.';
2536 ------------------------------------------------
2537 -- Locking for snapshots and voting procedure --
2538 ------------------------------------------------
2541 CREATE FUNCTION "share_row_lock_issue_trigger"()
2542 RETURNS TRIGGER
2543 LANGUAGE 'plpgsql' VOLATILE AS $$
2544 BEGIN
2545 IF TG_OP = 'UPDATE' OR TG_OP = 'DELETE' THEN
2546 PERFORM NULL FROM "issue" WHERE "id" = OLD."issue_id" FOR SHARE;
2547 END IF;
2548 IF TG_OP = 'INSERT' OR TG_OP = 'UPDATE' THEN
2549 PERFORM NULL FROM "issue" WHERE "id" = NEW."issue_id" FOR SHARE;
2550 RETURN NEW;
2551 ELSE
2552 RETURN OLD;
2553 END IF;
2554 END;
2555 $$;
2557 COMMENT ON FUNCTION "share_row_lock_issue_trigger"() IS 'Implementation of triggers "share_row_lock_issue" on multiple tables';
2560 CREATE FUNCTION "share_row_lock_issue_via_initiative_trigger"()
2561 RETURNS TRIGGER
2562 LANGUAGE 'plpgsql' VOLATILE AS $$
2563 BEGIN
2564 IF TG_OP = 'UPDATE' OR TG_OP = 'DELETE' THEN
2565 PERFORM NULL FROM "issue"
2566 JOIN "initiative" ON "issue"."id" = "initiative"."issue_id"
2567 WHERE "initiative"."id" = OLD."initiative_id"
2568 FOR SHARE OF "issue";
2569 END IF;
2570 IF TG_OP = 'INSERT' OR TG_OP = 'UPDATE' THEN
2571 PERFORM NULL FROM "issue"
2572 JOIN "initiative" ON "issue"."id" = "initiative"."issue_id"
2573 WHERE "initiative"."id" = NEW."initiative_id"
2574 FOR SHARE OF "issue";
2575 RETURN NEW;
2576 ELSE
2577 RETURN OLD;
2578 END IF;
2579 END;
2580 $$;
2582 COMMENT ON FUNCTION "share_row_lock_issue_trigger"() IS 'Implementation of trigger "share_row_lock_issue_via_initiative" on table "opinion"';
2585 CREATE TRIGGER "share_row_lock_issue"
2586 BEFORE INSERT OR UPDATE OR DELETE ON "initiative"
2587 FOR EACH ROW EXECUTE PROCEDURE
2588 "share_row_lock_issue_trigger"();
2590 CREATE TRIGGER "share_row_lock_issue"
2591 BEFORE INSERT OR UPDATE OR DELETE ON "interest"
2592 FOR EACH ROW EXECUTE PROCEDURE
2593 "share_row_lock_issue_trigger"();
2595 CREATE TRIGGER "share_row_lock_issue"
2596 BEFORE INSERT OR UPDATE OR DELETE ON "supporter"
2597 FOR EACH ROW EXECUTE PROCEDURE
2598 "share_row_lock_issue_trigger"();
2600 CREATE TRIGGER "share_row_lock_issue_via_initiative"
2601 BEFORE INSERT OR UPDATE OR DELETE ON "opinion"
2602 FOR EACH ROW EXECUTE PROCEDURE
2603 "share_row_lock_issue_via_initiative_trigger"();
2605 CREATE TRIGGER "share_row_lock_issue"
2606 BEFORE INSERT OR UPDATE OR DELETE ON "direct_voter"
2607 FOR EACH ROW EXECUTE PROCEDURE
2608 "share_row_lock_issue_trigger"();
2610 CREATE TRIGGER "share_row_lock_issue"
2611 BEFORE INSERT OR UPDATE OR DELETE ON "delegating_voter"
2612 FOR EACH ROW EXECUTE PROCEDURE
2613 "share_row_lock_issue_trigger"();
2615 CREATE TRIGGER "share_row_lock_issue"
2616 BEFORE INSERT OR UPDATE OR DELETE ON "vote"
2617 FOR EACH ROW EXECUTE PROCEDURE
2618 "share_row_lock_issue_trigger"();
2620 COMMENT ON TRIGGER "share_row_lock_issue" ON "initiative" IS 'See "lock_issue" function';
2621 COMMENT ON TRIGGER "share_row_lock_issue" ON "interest" IS 'See "lock_issue" function';
2622 COMMENT ON TRIGGER "share_row_lock_issue" ON "supporter" IS 'See "lock_issue" function';
2623 COMMENT ON TRIGGER "share_row_lock_issue_via_initiative" ON "opinion" IS 'See "lock_issue" function';
2624 COMMENT ON TRIGGER "share_row_lock_issue" ON "direct_voter" IS 'See "lock_issue" function';
2625 COMMENT ON TRIGGER "share_row_lock_issue" ON "delegating_voter" IS 'See "lock_issue" function';
2626 COMMENT ON TRIGGER "share_row_lock_issue" ON "vote" IS 'See "lock_issue" function';
2629 CREATE FUNCTION "lock_issue"
2630 ( "issue_id_p" "issue"."id"%TYPE )
2631 RETURNS VOID
2632 LANGUAGE 'plpgsql' VOLATILE AS $$
2633 BEGIN
2634 LOCK TABLE "member" IN SHARE MODE;
2635 LOCK TABLE "privilege" IN SHARE MODE;
2636 LOCK TABLE "membership" IN SHARE MODE;
2637 LOCK TABLE "policy" IN SHARE MODE;
2638 PERFORM NULL FROM "issue" WHERE "id" = "issue_id_p" FOR UPDATE;
2639 -- NOTE: The row-level exclusive lock in combination with the
2640 -- share_row_lock_issue(_via_initiative)_trigger functions (which
2641 -- acquire a row-level share lock on the issue) ensure that no data
2642 -- is changed, which could affect calculation of snapshots or
2643 -- counting of votes. Table "delegation" must be table-level-locked,
2644 -- as it also contains issue- and global-scope delegations.
2645 LOCK TABLE "delegation" IN SHARE MODE;
2646 LOCK TABLE "direct_population_snapshot" IN EXCLUSIVE MODE;
2647 LOCK TABLE "delegating_population_snapshot" IN EXCLUSIVE MODE;
2648 LOCK TABLE "direct_interest_snapshot" IN EXCLUSIVE MODE;
2649 LOCK TABLE "delegating_interest_snapshot" IN EXCLUSIVE MODE;
2650 LOCK TABLE "direct_supporter_snapshot" IN EXCLUSIVE MODE;
2651 RETURN;
2652 END;
2653 $$;
2655 COMMENT ON FUNCTION "lock_issue"
2656 ( "issue"."id"%TYPE )
2657 IS 'Locks the issue and all other data which is used for calculating snapshots or counting votes.';
2661 ------------------------------------------------------------------------
2662 -- Regular tasks, except calculcation of snapshots and voting results --
2663 ------------------------------------------------------------------------
2665 CREATE FUNCTION "check_last_login"()
2666 RETURNS VOID
2667 LANGUAGE 'plpgsql' VOLATILE AS $$
2668 DECLARE
2669 "system_setting_row" "system_setting"%ROWTYPE;
2670 BEGIN
2671 SELECT * INTO "system_setting_row" FROM "system_setting";
2672 LOCK TABLE "member" IN SHARE ROW EXCLUSIVE MODE;
2673 UPDATE "member" SET "last_login_public" = "last_login"::date
2674 FROM (
2675 SELECT DISTINCT "member"."id"
2676 FROM "member" LEFT JOIN "member_history"
2677 ON "member"."id" = "member_history"."member_id"
2678 WHERE "member"."last_login"::date < 'today' OR (
2679 "member_history"."until"::date >= 'today' AND
2680 "member_history"."active" = FALSE AND "member"."active" = TRUE
2682 ) AS "subquery"
2683 WHERE "member"."id" = "subquery"."id";
2684 IF "system_setting_row"."member_ttl" NOTNULL THEN
2685 UPDATE "member" SET "active" = FALSE
2686 WHERE "active" = TRUE
2687 AND "last_login"::date < 'today'
2688 AND "last_login_public" <
2689 (now() - "system_setting_row"."member_ttl")::date;
2690 END IF;
2691 RETURN;
2692 END;
2693 $$;
2695 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).';
2698 CREATE FUNCTION "calculate_member_counts"()
2699 RETURNS VOID
2700 LANGUAGE 'plpgsql' VOLATILE AS $$
2701 BEGIN
2702 LOCK TABLE "member" IN SHARE MODE;
2703 LOCK TABLE "member_count" IN EXCLUSIVE MODE;
2704 LOCK TABLE "unit" IN EXCLUSIVE MODE;
2705 LOCK TABLE "area" IN EXCLUSIVE MODE;
2706 LOCK TABLE "privilege" IN SHARE MODE;
2707 LOCK TABLE "membership" IN SHARE MODE;
2708 DELETE FROM "member_count";
2709 INSERT INTO "member_count" ("total_count")
2710 SELECT "total_count" FROM "member_count_view";
2711 UPDATE "unit" SET "member_count" = "view"."member_count"
2712 FROM "unit_member_count" AS "view"
2713 WHERE "view"."unit_id" = "unit"."id";
2714 UPDATE "area" SET
2715 "direct_member_count" = "view"."direct_member_count",
2716 "member_weight" = "view"."member_weight",
2717 "autoreject_weight" = "view"."autoreject_weight"
2718 FROM "area_member_count" AS "view"
2719 WHERE "view"."area_id" = "area"."id";
2720 RETURN;
2721 END;
2722 $$;
2724 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"';
2728 ------------------------------
2729 -- Calculation of snapshots --
2730 ------------------------------
2732 CREATE FUNCTION "weight_of_added_delegations_for_population_snapshot"
2733 ( "issue_id_p" "issue"."id"%TYPE,
2734 "member_id_p" "member"."id"%TYPE,
2735 "delegate_member_ids_p" "delegating_population_snapshot"."delegate_member_ids"%TYPE )
2736 RETURNS "direct_population_snapshot"."weight"%TYPE
2737 LANGUAGE 'plpgsql' VOLATILE AS $$
2738 DECLARE
2739 "issue_delegation_row" "issue_delegation"%ROWTYPE;
2740 "delegate_member_ids_v" "delegating_population_snapshot"."delegate_member_ids"%TYPE;
2741 "weight_v" INT4;
2742 "sub_weight_v" INT4;
2743 BEGIN
2744 "weight_v" := 0;
2745 FOR "issue_delegation_row" IN
2746 SELECT * FROM "issue_delegation"
2747 WHERE "trustee_id" = "member_id_p"
2748 AND "issue_id" = "issue_id_p"
2749 LOOP
2750 IF NOT EXISTS (
2751 SELECT NULL FROM "direct_population_snapshot"
2752 WHERE "issue_id" = "issue_id_p"
2753 AND "event" = 'periodic'
2754 AND "member_id" = "issue_delegation_row"."truster_id"
2755 ) AND NOT EXISTS (
2756 SELECT NULL FROM "delegating_population_snapshot"
2757 WHERE "issue_id" = "issue_id_p"
2758 AND "event" = 'periodic'
2759 AND "member_id" = "issue_delegation_row"."truster_id"
2760 ) THEN
2761 "delegate_member_ids_v" :=
2762 "member_id_p" || "delegate_member_ids_p";
2763 INSERT INTO "delegating_population_snapshot" (
2764 "issue_id",
2765 "event",
2766 "member_id",
2767 "scope",
2768 "delegate_member_ids"
2769 ) VALUES (
2770 "issue_id_p",
2771 'periodic',
2772 "issue_delegation_row"."truster_id",
2773 "issue_delegation_row"."scope",
2774 "delegate_member_ids_v"
2775 );
2776 "sub_weight_v" := 1 +
2777 "weight_of_added_delegations_for_population_snapshot"(
2778 "issue_id_p",
2779 "issue_delegation_row"."truster_id",
2780 "delegate_member_ids_v"
2781 );
2782 UPDATE "delegating_population_snapshot"
2783 SET "weight" = "sub_weight_v"
2784 WHERE "issue_id" = "issue_id_p"
2785 AND "event" = 'periodic'
2786 AND "member_id" = "issue_delegation_row"."truster_id";
2787 "weight_v" := "weight_v" + "sub_weight_v";
2788 END IF;
2789 END LOOP;
2790 RETURN "weight_v";
2791 END;
2792 $$;
2794 COMMENT ON FUNCTION "weight_of_added_delegations_for_population_snapshot"
2795 ( "issue"."id"%TYPE,
2796 "member"."id"%TYPE,
2797 "delegating_population_snapshot"."delegate_member_ids"%TYPE )
2798 IS 'Helper function for "create_population_snapshot" function';
2801 CREATE FUNCTION "create_population_snapshot"
2802 ( "issue_id_p" "issue"."id"%TYPE )
2803 RETURNS VOID
2804 LANGUAGE 'plpgsql' VOLATILE AS $$
2805 DECLARE
2806 "member_id_v" "member"."id"%TYPE;
2807 BEGIN
2808 DELETE FROM "direct_population_snapshot"
2809 WHERE "issue_id" = "issue_id_p"
2810 AND "event" = 'periodic';
2811 DELETE FROM "delegating_population_snapshot"
2812 WHERE "issue_id" = "issue_id_p"
2813 AND "event" = 'periodic';
2814 INSERT INTO "direct_population_snapshot"
2815 ("issue_id", "event", "member_id")
2816 SELECT
2817 "issue_id_p" AS "issue_id",
2818 'periodic'::"snapshot_event" AS "event",
2819 "member"."id" AS "member_id"
2820 FROM "issue"
2821 JOIN "area" ON "issue"."area_id" = "area"."id"
2822 JOIN "membership" ON "area"."id" = "membership"."area_id"
2823 JOIN "member" ON "membership"."member_id" = "member"."id"
2824 JOIN "privilege"
2825 ON "privilege"."unit_id" = "area"."unit_id"
2826 AND "privilege"."member_id" = "member"."id"
2827 WHERE "issue"."id" = "issue_id_p"
2828 AND "member"."active" AND "privilege"."voting_right"
2829 UNION
2830 SELECT
2831 "issue_id_p" AS "issue_id",
2832 'periodic'::"snapshot_event" AS "event",
2833 "member"."id" AS "member_id"
2834 FROM "issue"
2835 JOIN "area" ON "issue"."area_id" = "area"."id"
2836 JOIN "interest" ON "issue"."id" = "interest"."issue_id"
2837 JOIN "member" ON "interest"."member_id" = "member"."id"
2838 JOIN "privilege"
2839 ON "privilege"."unit_id" = "area"."unit_id"
2840 AND "privilege"."member_id" = "member"."id"
2841 WHERE "issue"."id" = "issue_id_p"
2842 AND "member"."active" AND "privilege"."voting_right"
2843 UNION
2844 SELECT
2845 "issue_id_p" AS "issue_id",
2846 'periodic'::"snapshot_event" AS "event",
2847 "member"."id" AS "member_id"
2848 FROM "issue"
2849 JOIN "area" ON "issue"."area_id" = "area"."id"
2850 JOIN "issue_autoreject" ON "issue"."id" = "issue_autoreject"."issue_id"
2851 JOIN "member" ON "issue_autoreject"."member_id" = "member"."id"
2852 JOIN "privilege"
2853 ON "privilege"."unit_id" = "area"."unit_id"
2854 AND "privilege"."member_id" = "member"."id"
2855 WHERE "issue"."id" = "issue_id_p"
2856 AND "member"."active" AND "privilege"."voting_right";
2857 FOR "member_id_v" IN
2858 SELECT "member_id" FROM "direct_population_snapshot"
2859 WHERE "issue_id" = "issue_id_p"
2860 AND "event" = 'periodic'
2861 LOOP
2862 UPDATE "direct_population_snapshot" SET
2863 "weight" = 1 +
2864 "weight_of_added_delegations_for_population_snapshot"(
2865 "issue_id_p",
2866 "member_id_v",
2867 '{}'
2869 WHERE "issue_id" = "issue_id_p"
2870 AND "event" = 'periodic'
2871 AND "member_id" = "member_id_v";
2872 END LOOP;
2873 RETURN;
2874 END;
2875 $$;
2877 COMMENT ON FUNCTION "create_population_snapshot"
2878 ( "issue"."id"%TYPE )
2879 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.';
2882 CREATE FUNCTION "weight_of_added_delegations_for_interest_snapshot"
2883 ( "issue_id_p" "issue"."id"%TYPE,
2884 "member_id_p" "member"."id"%TYPE,
2885 "delegate_member_ids_p" "delegating_interest_snapshot"."delegate_member_ids"%TYPE )
2886 RETURNS "direct_interest_snapshot"."weight"%TYPE
2887 LANGUAGE 'plpgsql' VOLATILE AS $$
2888 DECLARE
2889 "issue_delegation_row" "issue_delegation"%ROWTYPE;
2890 "delegate_member_ids_v" "delegating_interest_snapshot"."delegate_member_ids"%TYPE;
2891 "weight_v" INT4;
2892 "sub_weight_v" INT4;
2893 BEGIN
2894 "weight_v" := 0;
2895 FOR "issue_delegation_row" IN
2896 SELECT * FROM "issue_delegation"
2897 WHERE "trustee_id" = "member_id_p"
2898 AND "issue_id" = "issue_id_p"
2899 LOOP
2900 IF NOT EXISTS (
2901 SELECT NULL FROM "direct_interest_snapshot"
2902 WHERE "issue_id" = "issue_id_p"
2903 AND "event" = 'periodic'
2904 AND "member_id" = "issue_delegation_row"."truster_id"
2905 ) AND NOT EXISTS (
2906 SELECT NULL FROM "delegating_interest_snapshot"
2907 WHERE "issue_id" = "issue_id_p"
2908 AND "event" = 'periodic'
2909 AND "member_id" = "issue_delegation_row"."truster_id"
2910 ) THEN
2911 "delegate_member_ids_v" :=
2912 "member_id_p" || "delegate_member_ids_p";
2913 INSERT INTO "delegating_interest_snapshot" (
2914 "issue_id",
2915 "event",
2916 "member_id",
2917 "scope",
2918 "delegate_member_ids"
2919 ) VALUES (
2920 "issue_id_p",
2921 'periodic',
2922 "issue_delegation_row"."truster_id",
2923 "issue_delegation_row"."scope",
2924 "delegate_member_ids_v"
2925 );
2926 "sub_weight_v" := 1 +
2927 "weight_of_added_delegations_for_interest_snapshot"(
2928 "issue_id_p",
2929 "issue_delegation_row"."truster_id",
2930 "delegate_member_ids_v"
2931 );
2932 UPDATE "delegating_interest_snapshot"
2933 SET "weight" = "sub_weight_v"
2934 WHERE "issue_id" = "issue_id_p"
2935 AND "event" = 'periodic'
2936 AND "member_id" = "issue_delegation_row"."truster_id";
2937 "weight_v" := "weight_v" + "sub_weight_v";
2938 END IF;
2939 END LOOP;
2940 RETURN "weight_v";
2941 END;
2942 $$;
2944 COMMENT ON FUNCTION "weight_of_added_delegations_for_interest_snapshot"
2945 ( "issue"."id"%TYPE,
2946 "member"."id"%TYPE,
2947 "delegating_interest_snapshot"."delegate_member_ids"%TYPE )
2948 IS 'Helper function for "create_interest_snapshot" function';
2951 CREATE FUNCTION "create_interest_snapshot"
2952 ( "issue_id_p" "issue"."id"%TYPE )
2953 RETURNS VOID
2954 LANGUAGE 'plpgsql' VOLATILE AS $$
2955 DECLARE
2956 "member_id_v" "member"."id"%TYPE;
2957 BEGIN
2958 DELETE FROM "direct_interest_snapshot"
2959 WHERE "issue_id" = "issue_id_p"
2960 AND "event" = 'periodic';
2961 DELETE FROM "delegating_interest_snapshot"
2962 WHERE "issue_id" = "issue_id_p"
2963 AND "event" = 'periodic';
2964 DELETE FROM "direct_supporter_snapshot"
2965 WHERE "issue_id" = "issue_id_p"
2966 AND "event" = 'periodic';
2967 INSERT INTO "direct_interest_snapshot"
2968 ("issue_id", "event", "member_id")
2969 SELECT
2970 "issue_id_p" AS "issue_id",
2971 'periodic' AS "event",
2972 "member"."id" AS "member_id"
2973 FROM "issue"
2974 JOIN "area" ON "issue"."area_id" = "area"."id"
2975 JOIN "interest" ON "issue"."id" = "interest"."issue_id"
2976 JOIN "member" ON "interest"."member_id" = "member"."id"
2977 JOIN "privilege"
2978 ON "privilege"."unit_id" = "area"."unit_id"
2979 AND "privilege"."member_id" = "member"."id"
2980 WHERE "issue"."id" = "issue_id_p"
2981 AND "member"."active" AND "privilege"."voting_right";
2982 FOR "member_id_v" IN
2983 SELECT "member_id" FROM "direct_interest_snapshot"
2984 WHERE "issue_id" = "issue_id_p"
2985 AND "event" = 'periodic'
2986 LOOP
2987 UPDATE "direct_interest_snapshot" SET
2988 "weight" = 1 +
2989 "weight_of_added_delegations_for_interest_snapshot"(
2990 "issue_id_p",
2991 "member_id_v",
2992 '{}'
2994 WHERE "issue_id" = "issue_id_p"
2995 AND "event" = 'periodic'
2996 AND "member_id" = "member_id_v";
2997 END LOOP;
2998 INSERT INTO "direct_supporter_snapshot"
2999 ( "issue_id", "initiative_id", "event", "member_id",
3000 "informed", "satisfied" )
3001 SELECT
3002 "issue_id_p" AS "issue_id",
3003 "initiative"."id" AS "initiative_id",
3004 'periodic' AS "event",
3005 "supporter"."member_id" AS "member_id",
3006 "supporter"."draft_id" = "current_draft"."id" AS "informed",
3007 NOT EXISTS (
3008 SELECT NULL FROM "critical_opinion"
3009 WHERE "initiative_id" = "initiative"."id"
3010 AND "member_id" = "supporter"."member_id"
3011 ) AS "satisfied"
3012 FROM "initiative"
3013 JOIN "supporter"
3014 ON "supporter"."initiative_id" = "initiative"."id"
3015 JOIN "current_draft"
3016 ON "initiative"."id" = "current_draft"."initiative_id"
3017 JOIN "direct_interest_snapshot"
3018 ON "supporter"."member_id" = "direct_interest_snapshot"."member_id"
3019 AND "initiative"."issue_id" = "direct_interest_snapshot"."issue_id"
3020 AND "event" = 'periodic'
3021 WHERE "initiative"."issue_id" = "issue_id_p";
3022 RETURN;
3023 END;
3024 $$;
3026 COMMENT ON FUNCTION "create_interest_snapshot"
3027 ( "issue"."id"%TYPE )
3028 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.';
3031 CREATE FUNCTION "create_snapshot"
3032 ( "issue_id_p" "issue"."id"%TYPE )
3033 RETURNS VOID
3034 LANGUAGE 'plpgsql' VOLATILE AS $$
3035 DECLARE
3036 "initiative_id_v" "initiative"."id"%TYPE;
3037 "suggestion_id_v" "suggestion"."id"%TYPE;
3038 BEGIN
3039 PERFORM "lock_issue"("issue_id_p");
3040 PERFORM "create_population_snapshot"("issue_id_p");
3041 PERFORM "create_interest_snapshot"("issue_id_p");
3042 UPDATE "issue" SET
3043 "snapshot" = now(),
3044 "latest_snapshot_event" = 'periodic',
3045 "population" = (
3046 SELECT coalesce(sum("weight"), 0)
3047 FROM "direct_population_snapshot"
3048 WHERE "issue_id" = "issue_id_p"
3049 AND "event" = 'periodic'
3051 WHERE "id" = "issue_id_p";
3052 FOR "initiative_id_v" IN
3053 SELECT "id" FROM "initiative" WHERE "issue_id" = "issue_id_p"
3054 LOOP
3055 UPDATE "initiative" SET
3056 "supporter_count" = (
3057 SELECT coalesce(sum("di"."weight"), 0)
3058 FROM "direct_interest_snapshot" AS "di"
3059 JOIN "direct_supporter_snapshot" AS "ds"
3060 ON "di"."member_id" = "ds"."member_id"
3061 WHERE "di"."issue_id" = "issue_id_p"
3062 AND "di"."event" = 'periodic'
3063 AND "ds"."initiative_id" = "initiative_id_v"
3064 AND "ds"."event" = 'periodic'
3065 ),
3066 "informed_supporter_count" = (
3067 SELECT coalesce(sum("di"."weight"), 0)
3068 FROM "direct_interest_snapshot" AS "di"
3069 JOIN "direct_supporter_snapshot" AS "ds"
3070 ON "di"."member_id" = "ds"."member_id"
3071 WHERE "di"."issue_id" = "issue_id_p"
3072 AND "di"."event" = 'periodic'
3073 AND "ds"."initiative_id" = "initiative_id_v"
3074 AND "ds"."event" = 'periodic'
3075 AND "ds"."informed"
3076 ),
3077 "satisfied_supporter_count" = (
3078 SELECT coalesce(sum("di"."weight"), 0)
3079 FROM "direct_interest_snapshot" AS "di"
3080 JOIN "direct_supporter_snapshot" AS "ds"
3081 ON "di"."member_id" = "ds"."member_id"
3082 WHERE "di"."issue_id" = "issue_id_p"
3083 AND "di"."event" = 'periodic'
3084 AND "ds"."initiative_id" = "initiative_id_v"
3085 AND "ds"."event" = 'periodic'
3086 AND "ds"."satisfied"
3087 ),
3088 "satisfied_informed_supporter_count" = (
3089 SELECT coalesce(sum("di"."weight"), 0)
3090 FROM "direct_interest_snapshot" AS "di"
3091 JOIN "direct_supporter_snapshot" AS "ds"
3092 ON "di"."member_id" = "ds"."member_id"
3093 WHERE "di"."issue_id" = "issue_id_p"
3094 AND "di"."event" = 'periodic'
3095 AND "ds"."initiative_id" = "initiative_id_v"
3096 AND "ds"."event" = 'periodic'
3097 AND "ds"."informed"
3098 AND "ds"."satisfied"
3100 WHERE "id" = "initiative_id_v";
3101 FOR "suggestion_id_v" IN
3102 SELECT "id" FROM "suggestion"
3103 WHERE "initiative_id" = "initiative_id_v"
3104 LOOP
3105 UPDATE "suggestion" SET
3106 "minus2_unfulfilled_count" = (
3107 SELECT coalesce(sum("snapshot"."weight"), 0)
3108 FROM "issue" CROSS JOIN "opinion"
3109 JOIN "direct_interest_snapshot" AS "snapshot"
3110 ON "snapshot"."issue_id" = "issue"."id"
3111 AND "snapshot"."event" = "issue"."latest_snapshot_event"
3112 AND "snapshot"."member_id" = "opinion"."member_id"
3113 WHERE "issue"."id" = "issue_id_p"
3114 AND "opinion"."suggestion_id" = "suggestion_id_v"
3115 AND "opinion"."degree" = -2
3116 AND "opinion"."fulfilled" = FALSE
3117 ),
3118 "minus2_fulfilled_count" = (
3119 SELECT coalesce(sum("snapshot"."weight"), 0)
3120 FROM "issue" CROSS JOIN "opinion"
3121 JOIN "direct_interest_snapshot" AS "snapshot"
3122 ON "snapshot"."issue_id" = "issue"."id"
3123 AND "snapshot"."event" = "issue"."latest_snapshot_event"
3124 AND "snapshot"."member_id" = "opinion"."member_id"
3125 WHERE "issue"."id" = "issue_id_p"
3126 AND "opinion"."suggestion_id" = "suggestion_id_v"
3127 AND "opinion"."degree" = -2
3128 AND "opinion"."fulfilled" = TRUE
3129 ),
3130 "minus1_unfulfilled_count" = (
3131 SELECT coalesce(sum("snapshot"."weight"), 0)
3132 FROM "issue" CROSS JOIN "opinion"
3133 JOIN "direct_interest_snapshot" AS "snapshot"
3134 ON "snapshot"."issue_id" = "issue"."id"
3135 AND "snapshot"."event" = "issue"."latest_snapshot_event"
3136 AND "snapshot"."member_id" = "opinion"."member_id"
3137 WHERE "issue"."id" = "issue_id_p"
3138 AND "opinion"."suggestion_id" = "suggestion_id_v"
3139 AND "opinion"."degree" = -1
3140 AND "opinion"."fulfilled" = FALSE
3141 ),
3142 "minus1_fulfilled_count" = (
3143 SELECT coalesce(sum("snapshot"."weight"), 0)
3144 FROM "issue" CROSS JOIN "opinion"
3145 JOIN "direct_interest_snapshot" AS "snapshot"
3146 ON "snapshot"."issue_id" = "issue"."id"
3147 AND "snapshot"."event" = "issue"."latest_snapshot_event"
3148 AND "snapshot"."member_id" = "opinion"."member_id"
3149 WHERE "issue"."id" = "issue_id_p"
3150 AND "opinion"."suggestion_id" = "suggestion_id_v"
3151 AND "opinion"."degree" = -1
3152 AND "opinion"."fulfilled" = TRUE
3153 ),
3154 "plus1_unfulfilled_count" = (
3155 SELECT coalesce(sum("snapshot"."weight"), 0)
3156 FROM "issue" CROSS JOIN "opinion"
3157 JOIN "direct_interest_snapshot" AS "snapshot"
3158 ON "snapshot"."issue_id" = "issue"."id"
3159 AND "snapshot"."event" = "issue"."latest_snapshot_event"
3160 AND "snapshot"."member_id" = "opinion"."member_id"
3161 WHERE "issue"."id" = "issue_id_p"
3162 AND "opinion"."suggestion_id" = "suggestion_id_v"
3163 AND "opinion"."degree" = 1
3164 AND "opinion"."fulfilled" = FALSE
3165 ),
3166 "plus1_fulfilled_count" = (
3167 SELECT coalesce(sum("snapshot"."weight"), 0)
3168 FROM "issue" CROSS JOIN "opinion"
3169 JOIN "direct_interest_snapshot" AS "snapshot"
3170 ON "snapshot"."issue_id" = "issue"."id"
3171 AND "snapshot"."event" = "issue"."latest_snapshot_event"
3172 AND "snapshot"."member_id" = "opinion"."member_id"
3173 WHERE "issue"."id" = "issue_id_p"
3174 AND "opinion"."suggestion_id" = "suggestion_id_v"
3175 AND "opinion"."degree" = 1
3176 AND "opinion"."fulfilled" = TRUE
3177 ),
3178 "plus2_unfulfilled_count" = (
3179 SELECT coalesce(sum("snapshot"."weight"), 0)
3180 FROM "issue" CROSS JOIN "opinion"
3181 JOIN "direct_interest_snapshot" AS "snapshot"
3182 ON "snapshot"."issue_id" = "issue"."id"
3183 AND "snapshot"."event" = "issue"."latest_snapshot_event"
3184 AND "snapshot"."member_id" = "opinion"."member_id"
3185 WHERE "issue"."id" = "issue_id_p"
3186 AND "opinion"."suggestion_id" = "suggestion_id_v"
3187 AND "opinion"."degree" = 2
3188 AND "opinion"."fulfilled" = FALSE
3189 ),
3190 "plus2_fulfilled_count" = (
3191 SELECT coalesce(sum("snapshot"."weight"), 0)
3192 FROM "issue" CROSS JOIN "opinion"
3193 JOIN "direct_interest_snapshot" AS "snapshot"
3194 ON "snapshot"."issue_id" = "issue"."id"
3195 AND "snapshot"."event" = "issue"."latest_snapshot_event"
3196 AND "snapshot"."member_id" = "opinion"."member_id"
3197 WHERE "issue"."id" = "issue_id_p"
3198 AND "opinion"."suggestion_id" = "suggestion_id_v"
3199 AND "opinion"."degree" = 2
3200 AND "opinion"."fulfilled" = TRUE
3202 WHERE "suggestion"."id" = "suggestion_id_v";
3203 END LOOP;
3204 END LOOP;
3205 RETURN;
3206 END;
3207 $$;
3209 COMMENT ON FUNCTION "create_snapshot"
3210 ( "issue"."id"%TYPE )
3211 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.';
3214 CREATE FUNCTION "set_snapshot_event"
3215 ( "issue_id_p" "issue"."id"%TYPE,
3216 "event_p" "snapshot_event" )
3217 RETURNS VOID
3218 LANGUAGE 'plpgsql' VOLATILE AS $$
3219 DECLARE
3220 "event_v" "issue"."latest_snapshot_event"%TYPE;
3221 BEGIN
3222 SELECT "latest_snapshot_event" INTO "event_v" FROM "issue"
3223 WHERE "id" = "issue_id_p" FOR UPDATE;
3224 UPDATE "issue" SET "latest_snapshot_event" = "event_p"
3225 WHERE "id" = "issue_id_p";
3226 UPDATE "direct_population_snapshot" SET "event" = "event_p"
3227 WHERE "issue_id" = "issue_id_p" AND "event" = "event_v";
3228 UPDATE "delegating_population_snapshot" SET "event" = "event_p"
3229 WHERE "issue_id" = "issue_id_p" AND "event" = "event_v";
3230 UPDATE "direct_interest_snapshot" SET "event" = "event_p"
3231 WHERE "issue_id" = "issue_id_p" AND "event" = "event_v";
3232 UPDATE "delegating_interest_snapshot" SET "event" = "event_p"
3233 WHERE "issue_id" = "issue_id_p" AND "event" = "event_v";
3234 UPDATE "direct_supporter_snapshot" SET "event" = "event_p"
3235 WHERE "issue_id" = "issue_id_p" AND "event" = "event_v";
3236 RETURN;
3237 END;
3238 $$;
3240 COMMENT ON FUNCTION "set_snapshot_event"
3241 ( "issue"."id"%TYPE,
3242 "snapshot_event" )
3243 IS 'Change "event" attribute of the previous ''periodic'' snapshot';
3247 ---------------------
3248 -- Freezing issues --
3249 ---------------------
3251 CREATE FUNCTION "freeze_after_snapshot"
3252 ( "issue_id_p" "issue"."id"%TYPE )
3253 RETURNS VOID
3254 LANGUAGE 'plpgsql' VOLATILE AS $$
3255 DECLARE
3256 "issue_row" "issue"%ROWTYPE;
3257 "policy_row" "policy"%ROWTYPE;
3258 "initiative_row" "initiative"%ROWTYPE;
3259 BEGIN
3260 SELECT * INTO "issue_row" FROM "issue" WHERE "id" = "issue_id_p";
3261 SELECT * INTO "policy_row"
3262 FROM "policy" WHERE "id" = "issue_row"."policy_id";
3263 PERFORM "set_snapshot_event"("issue_id_p", 'full_freeze');
3264 FOR "initiative_row" IN
3265 SELECT * FROM "initiative"
3266 WHERE "issue_id" = "issue_id_p" AND "revoked" ISNULL
3267 LOOP
3268 IF
3269 "initiative_row"."satisfied_supporter_count" > 0 AND
3270 "initiative_row"."satisfied_supporter_count" *
3271 "policy_row"."initiative_quorum_den" >=
3272 "issue_row"."population" * "policy_row"."initiative_quorum_num"
3273 THEN
3274 UPDATE "initiative" SET "admitted" = TRUE
3275 WHERE "id" = "initiative_row"."id";
3276 ELSE
3277 UPDATE "initiative" SET "admitted" = FALSE
3278 WHERE "id" = "initiative_row"."id";
3279 END IF;
3280 END LOOP;
3281 IF EXISTS (
3282 SELECT NULL FROM "initiative"
3283 WHERE "issue_id" = "issue_id_p" AND "admitted" = TRUE
3284 ) THEN
3285 UPDATE "issue" SET
3286 "state" = 'voting',
3287 "accepted" = coalesce("accepted", now()),
3288 "half_frozen" = coalesce("half_frozen", now()),
3289 "fully_frozen" = now()
3290 WHERE "id" = "issue_id_p";
3291 ELSE
3292 UPDATE "issue" SET
3293 "state" = 'canceled_no_initiative_admitted',
3294 "accepted" = coalesce("accepted", now()),
3295 "half_frozen" = coalesce("half_frozen", now()),
3296 "fully_frozen" = now(),
3297 "closed" = now(),
3298 "ranks_available" = TRUE
3299 WHERE "id" = "issue_id_p";
3300 -- NOTE: The following DELETE statements have effect only when
3301 -- issue state has been manipulated
3302 DELETE FROM "direct_voter" WHERE "issue_id" = "issue_id_p";
3303 DELETE FROM "delegating_voter" WHERE "issue_id" = "issue_id_p";
3304 DELETE FROM "battle" WHERE "issue_id" = "issue_id_p";
3305 END IF;
3306 RETURN;
3307 END;
3308 $$;
3310 COMMENT ON FUNCTION "freeze_after_snapshot"
3311 ( "issue"."id"%TYPE )
3312 IS 'This function freezes an issue (fully) and starts voting, but must only be called when "create_snapshot" was called in the same transaction.';
3315 CREATE FUNCTION "manual_freeze"("issue_id_p" "issue"."id"%TYPE)
3316 RETURNS VOID
3317 LANGUAGE 'plpgsql' VOLATILE AS $$
3318 DECLARE
3319 "issue_row" "issue"%ROWTYPE;
3320 BEGIN
3321 PERFORM "create_snapshot"("issue_id_p");
3322 PERFORM "freeze_after_snapshot"("issue_id_p");
3323 RETURN;
3324 END;
3325 $$;
3327 COMMENT ON FUNCTION "manual_freeze"
3328 ( "issue"."id"%TYPE )
3329 IS 'Freeze an issue manually (fully) and start voting';
3333 -----------------------
3334 -- Counting of votes --
3335 -----------------------
3338 CREATE FUNCTION "weight_of_added_vote_delegations"
3339 ( "issue_id_p" "issue"."id"%TYPE,
3340 "member_id_p" "member"."id"%TYPE,
3341 "delegate_member_ids_p" "delegating_voter"."delegate_member_ids"%TYPE )
3342 RETURNS "direct_voter"."weight"%TYPE
3343 LANGUAGE 'plpgsql' VOLATILE AS $$
3344 DECLARE
3345 "issue_delegation_row" "issue_delegation"%ROWTYPE;
3346 "delegate_member_ids_v" "delegating_voter"."delegate_member_ids"%TYPE;
3347 "weight_v" INT4;
3348 "sub_weight_v" INT4;
3349 BEGIN
3350 "weight_v" := 0;
3351 FOR "issue_delegation_row" IN
3352 SELECT * FROM "issue_delegation"
3353 WHERE "trustee_id" = "member_id_p"
3354 AND "issue_id" = "issue_id_p"
3355 LOOP
3356 IF NOT EXISTS (
3357 SELECT NULL FROM "direct_voter"
3358 WHERE "member_id" = "issue_delegation_row"."truster_id"
3359 AND "issue_id" = "issue_id_p"
3360 ) AND NOT EXISTS (
3361 SELECT NULL FROM "delegating_voter"
3362 WHERE "member_id" = "issue_delegation_row"."truster_id"
3363 AND "issue_id" = "issue_id_p"
3364 ) THEN
3365 "delegate_member_ids_v" :=
3366 "member_id_p" || "delegate_member_ids_p";
3367 INSERT INTO "delegating_voter" (
3368 "issue_id",
3369 "member_id",
3370 "scope",
3371 "delegate_member_ids"
3372 ) VALUES (
3373 "issue_id_p",
3374 "issue_delegation_row"."truster_id",
3375 "issue_delegation_row"."scope",
3376 "delegate_member_ids_v"
3377 );
3378 "sub_weight_v" := 1 +
3379 "weight_of_added_vote_delegations"(
3380 "issue_id_p",
3381 "issue_delegation_row"."truster_id",
3382 "delegate_member_ids_v"
3383 );
3384 UPDATE "delegating_voter"
3385 SET "weight" = "sub_weight_v"
3386 WHERE "issue_id" = "issue_id_p"
3387 AND "member_id" = "issue_delegation_row"."truster_id";
3388 "weight_v" := "weight_v" + "sub_weight_v";
3389 END IF;
3390 END LOOP;
3391 RETURN "weight_v";
3392 END;
3393 $$;
3395 COMMENT ON FUNCTION "weight_of_added_vote_delegations"
3396 ( "issue"."id"%TYPE,
3397 "member"."id"%TYPE,
3398 "delegating_voter"."delegate_member_ids"%TYPE )
3399 IS 'Helper function for "add_vote_delegations" function';
3402 CREATE FUNCTION "add_vote_delegations"
3403 ( "issue_id_p" "issue"."id"%TYPE )
3404 RETURNS VOID
3405 LANGUAGE 'plpgsql' VOLATILE AS $$
3406 DECLARE
3407 "member_id_v" "member"."id"%TYPE;
3408 BEGIN
3409 FOR "member_id_v" IN
3410 SELECT "member_id" FROM "direct_voter"
3411 WHERE "issue_id" = "issue_id_p"
3412 LOOP
3413 UPDATE "direct_voter" SET
3414 "weight" = "weight" + "weight_of_added_vote_delegations"(
3415 "issue_id_p",
3416 "member_id_v",
3417 '{}'
3419 WHERE "member_id" = "member_id_v"
3420 AND "issue_id" = "issue_id_p";
3421 END LOOP;
3422 RETURN;
3423 END;
3424 $$;
3426 COMMENT ON FUNCTION "add_vote_delegations"
3427 ( "issue_id_p" "issue"."id"%TYPE )
3428 IS 'Helper function for "close_voting" function';
3431 CREATE FUNCTION "close_voting"("issue_id_p" "issue"."id"%TYPE)
3432 RETURNS VOID
3433 LANGUAGE 'plpgsql' VOLATILE AS $$
3434 DECLARE
3435 "area_id_v" "area"."id"%TYPE;
3436 "unit_id_v" "unit"."id"%TYPE;
3437 "member_id_v" "member"."id"%TYPE;
3438 BEGIN
3439 PERFORM "lock_issue"("issue_id_p");
3440 SELECT "area_id" INTO "area_id_v" FROM "issue" WHERE "id" = "issue_id_p";
3441 SELECT "unit_id" INTO "unit_id_v" FROM "area" WHERE "id" = "area_id_v";
3442 -- consider delegations and auto-reject:
3443 DELETE FROM "delegating_voter"
3444 WHERE "issue_id" = "issue_id_p";
3445 DELETE FROM "direct_voter"
3446 WHERE "issue_id" = "issue_id_p"
3447 AND "autoreject" = TRUE;
3448 DELETE FROM "direct_voter"
3449 USING (
3450 SELECT
3451 "direct_voter"."member_id"
3452 FROM "direct_voter"
3453 JOIN "member" ON "direct_voter"."member_id" = "member"."id"
3454 LEFT JOIN "privilege"
3455 ON "privilege"."unit_id" = "unit_id_v"
3456 AND "privilege"."member_id" = "direct_voter"."member_id"
3457 WHERE "direct_voter"."issue_id" = "issue_id_p" AND (
3458 "member"."active" = FALSE OR
3459 "privilege"."voting_right" ISNULL OR
3460 "privilege"."voting_right" = FALSE
3462 ) AS "subquery"
3463 WHERE "direct_voter"."issue_id" = "issue_id_p"
3464 AND "direct_voter"."member_id" = "subquery"."member_id";
3465 UPDATE "direct_voter" SET "weight" = 1
3466 WHERE "issue_id" = "issue_id_p";
3467 PERFORM "add_vote_delegations"("issue_id_p");
3468 FOR "member_id_v" IN
3469 SELECT "issue_autoreject"."member_id"
3470 FROM "issue_autoreject"
3471 JOIN "member"
3472 ON "issue_autoreject"."member_id" = "member"."id"
3473 JOIN "privilege"
3474 ON "privilege"."unit_id" = "unit_id_v"
3475 AND "privilege"."member_id" = "member"."id"
3476 LEFT JOIN "direct_voter"
3477 ON "issue_autoreject"."member_id" = "direct_voter"."member_id"
3478 AND "issue_autoreject"."issue_id" = "direct_voter"."issue_id"
3479 LEFT JOIN "delegating_voter"
3480 ON "issue_autoreject"."member_id" = "delegating_voter"."member_id"
3481 AND "issue_autoreject"."issue_id" = "delegating_voter"."issue_id"
3482 WHERE "issue_autoreject"."issue_id" = "issue_id_p"
3483 AND "issue_autoreject"."autoreject" = TRUE
3484 AND "member"."active"
3485 AND "privilege"."voting_right"
3486 AND "direct_voter"."member_id" ISNULL
3487 AND "delegating_voter"."member_id" ISNULL
3488 UNION
3489 SELECT "membership"."member_id"
3490 FROM "membership"
3491 JOIN "member"
3492 ON "membership"."member_id" = "member"."id"
3493 JOIN "privilege"
3494 ON "privilege"."unit_id" = "unit_id_v"
3495 AND "privilege"."member_id" = "member"."id"
3496 LEFT JOIN "issue_autoreject"
3497 ON "membership"."member_id" = "issue_autoreject"."member_id"
3498 AND "issue_autoreject"."issue_id" = "issue_id_p"
3499 LEFT JOIN "direct_voter"
3500 ON "membership"."member_id" = "direct_voter"."member_id"
3501 AND "direct_voter"."issue_id" = "issue_id_p"
3502 LEFT JOIN "delegating_voter"
3503 ON "membership"."member_id" = "delegating_voter"."member_id"
3504 AND "delegating_voter"."issue_id" = "issue_id_p"
3505 WHERE "membership"."area_id" = "area_id_v"
3506 AND "membership"."autoreject" = TRUE
3507 AND "member"."active"
3508 AND "privilege"."voting_right"
3509 AND "issue_autoreject"."autoreject" ISNULL
3510 AND "direct_voter"."member_id" ISNULL
3511 AND "delegating_voter"."member_id" ISNULL
3512 LOOP
3513 INSERT INTO "direct_voter"
3514 ("member_id", "issue_id", "weight", "autoreject") VALUES
3515 ("member_id_v", "issue_id_p", 1, TRUE);
3516 INSERT INTO "vote" (
3517 "member_id",
3518 "issue_id",
3519 "initiative_id",
3520 "grade"
3521 ) SELECT
3522 "member_id_v" AS "member_id",
3523 "issue_id_p" AS "issue_id",
3524 "id" AS "initiative_id",
3525 -1 AS "grade"
3526 FROM "initiative" WHERE "issue_id" = "issue_id_p";
3527 -- TODO: admitted initiatives only?
3528 END LOOP;
3529 PERFORM "add_vote_delegations"("issue_id_p");
3530 -- set voter count and mark issue as being calculated:
3531 UPDATE "issue" SET
3532 "state" = 'calculation',
3533 "closed" = now(),
3534 "voter_count" = (
3535 SELECT coalesce(sum("weight"), 0)
3536 FROM "direct_voter" WHERE "issue_id" = "issue_id_p"
3538 WHERE "id" = "issue_id_p";
3539 -- calculate "positive_votes", "negative_votes" and "attainable":
3540 UPDATE "initiative" SET
3541 "positive_votes" = "vote_counts"."positive_votes",
3542 "negative_votes" = "vote_counts"."negative_votes",
3543 "attainable" =
3544 CASE WHEN "majority_strict" THEN
3545 "vote_counts"."positive_votes" * "majority_den" >
3546 "majority_num" *
3547 ("vote_counts"."positive_votes"+"vote_counts"."negative_votes")
3548 ELSE
3549 "vote_counts"."positive_votes" * "majority_den" >=
3550 "majority_num" *
3551 ("vote_counts"."positive_votes"+"vote_counts"."negative_votes")
3552 END
3553 AND "vote_counts"."positive_votes" >= "policy"."majority_positive"
3554 AND "issue"."voter_count"-"vote_counts"."negative_votes" >=
3555 "policy"."majority_non_negative"
3556 FROM
3557 ( SELECT
3558 "initiative"."id" AS "initiative_id",
3559 coalesce(
3560 sum(
3561 CASE WHEN "grade" > 0 THEN "direct_voter"."weight" ELSE 0 END
3562 ),
3564 ) AS "positive_votes",
3565 coalesce(
3566 sum(
3567 CASE WHEN "grade" < 0 THEN "direct_voter"."weight" ELSE 0 END
3568 ),
3570 ) AS "negative_votes"
3571 FROM "initiative"
3572 JOIN "issue" ON "initiative"."issue_id" = "issue"."id"
3573 JOIN "policy" ON "issue"."policy_id" = "policy"."id"
3574 LEFT JOIN "direct_voter"
3575 ON "direct_voter"."issue_id" = "initiative"."issue_id"
3576 LEFT JOIN "vote"
3577 ON "vote"."initiative_id" = "initiative"."id"
3578 AND "vote"."member_id" = "direct_voter"."member_id"
3579 WHERE "initiative"."issue_id" = "issue_id_p"
3580 AND "initiative"."admitted" -- NOTE: NULL case is handled too
3581 GROUP BY "initiative"."id"
3582 ) AS "vote_counts",
3583 "issue",
3584 "policy"
3585 WHERE "vote_counts"."initiative_id" = "initiative"."id"
3586 AND "issue"."id" = "initiative"."issue_id"
3587 AND "policy"."id" = "issue"."policy_id";
3588 -- materialize battle_view:
3589 -- NOTE: "closed" column of issue must be set at this point
3590 DELETE FROM "battle" WHERE "issue_id" = "issue_id_p";
3591 INSERT INTO "battle" (
3592 "issue_id",
3593 "winning_initiative_id", "losing_initiative_id",
3594 "count"
3595 ) SELECT
3596 "issue_id",
3597 "winning_initiative_id", "losing_initiative_id",
3598 "count"
3599 FROM "battle_view" WHERE "issue_id" = "issue_id_p";
3600 END;
3601 $$;
3603 COMMENT ON FUNCTION "close_voting"
3604 ( "issue"."id"%TYPE )
3605 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.';
3608 CREATE FUNCTION "defeat_strength"
3609 ( "positive_votes_p" INT4, "negative_votes_p" INT4 )
3610 RETURNS INT8
3611 LANGUAGE 'plpgsql' IMMUTABLE AS $$
3612 BEGIN
3613 IF "positive_votes_p" > "negative_votes_p" THEN
3614 RETURN ("positive_votes_p"::INT8 << 31) - "negative_votes_p"::INT8;
3615 ELSIF "positive_votes_p" = "negative_votes_p" THEN
3616 RETURN 0;
3617 ELSE
3618 RETURN -1;
3619 END IF;
3620 END;
3621 $$;
3623 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';
3626 CREATE FUNCTION "calculate_ranks"("issue_id_p" "issue"."id"%TYPE)
3627 RETURNS VOID
3628 LANGUAGE 'plpgsql' VOLATILE AS $$
3629 DECLARE
3630 "dimension_v" INTEGER;
3631 "vote_matrix" INT4[][]; -- absolute votes
3632 "matrix" INT8[][]; -- defeat strength / best paths
3633 "i" INTEGER;
3634 "j" INTEGER;
3635 "k" INTEGER;
3636 "battle_row" "battle"%ROWTYPE;
3637 "rank_ary" INT4[];
3638 "rank_v" INT4;
3639 "done_v" INTEGER;
3640 "winners_ary" INTEGER[];
3641 "initiative_id_v" "initiative"."id"%TYPE;
3642 BEGIN
3643 PERFORM NULL FROM "issue" WHERE "id" = "issue_id_p" FOR UPDATE;
3644 SELECT count(1) INTO "dimension_v"
3645 FROM "battle_participant" WHERE "issue_id" = "issue_id_p";
3646 IF "dimension_v" > 1 THEN
3647 -- Create "vote_matrix" with absolute number of votes in pairwise
3648 -- comparison:
3649 "vote_matrix" := array_fill(NULL::INT4, ARRAY["dimension_v", "dimension_v"]);
3650 "i" := 1;
3651 "j" := 2;
3652 FOR "battle_row" IN
3653 SELECT * FROM "battle" WHERE "issue_id" = "issue_id_p"
3654 ORDER BY
3655 "winning_initiative_id" NULLS LAST,
3656 "losing_initiative_id" NULLS LAST
3657 LOOP
3658 "vote_matrix"["i"]["j"] := "battle_row"."count";
3659 IF "j" = "dimension_v" THEN
3660 "i" := "i" + 1;
3661 "j" := 1;
3662 ELSE
3663 "j" := "j" + 1;
3664 IF "j" = "i" THEN
3665 "j" := "j" + 1;
3666 END IF;
3667 END IF;
3668 END LOOP;
3669 IF "i" != "dimension_v" OR "j" != "dimension_v" + 1 THEN
3670 RAISE EXCEPTION 'Wrong battle count (should not happen)';
3671 END IF;
3672 -- Store defeat strengths in "matrix" using "defeat_strength"
3673 -- function:
3674 "matrix" := array_fill(NULL::INT8, ARRAY["dimension_v", "dimension_v"]);
3675 "i" := 1;
3676 LOOP
3677 "j" := 1;
3678 LOOP
3679 IF "i" != "j" THEN
3680 "matrix"["i"]["j"] := "defeat_strength"(
3681 "vote_matrix"["i"]["j"],
3682 "vote_matrix"["j"]["i"]
3683 );
3684 END IF;
3685 EXIT WHEN "j" = "dimension_v";
3686 "j" := "j" + 1;
3687 END LOOP;
3688 EXIT WHEN "i" = "dimension_v";
3689 "i" := "i" + 1;
3690 END LOOP;
3691 -- Find best paths:
3692 "i" := 1;
3693 LOOP
3694 "j" := 1;
3695 LOOP
3696 IF "i" != "j" THEN
3697 "k" := 1;
3698 LOOP
3699 IF "i" != "k" AND "j" != "k" THEN
3700 IF "matrix"["j"]["i"] < "matrix"["i"]["k"] THEN
3701 IF "matrix"["j"]["i"] > "matrix"["j"]["k"] THEN
3702 "matrix"["j"]["k"] := "matrix"["j"]["i"];
3703 END IF;
3704 ELSE
3705 IF "matrix"["i"]["k"] > "matrix"["j"]["k"] THEN
3706 "matrix"["j"]["k"] := "matrix"["i"]["k"];
3707 END IF;
3708 END IF;
3709 END IF;
3710 EXIT WHEN "k" = "dimension_v";
3711 "k" := "k" + 1;
3712 END LOOP;
3713 END IF;
3714 EXIT WHEN "j" = "dimension_v";
3715 "j" := "j" + 1;
3716 END LOOP;
3717 EXIT WHEN "i" = "dimension_v";
3718 "i" := "i" + 1;
3719 END LOOP;
3720 -- Determine order of winners:
3721 "rank_ary" := array_fill(NULL::INT4, ARRAY["dimension_v"]);
3722 "rank_v" := 1;
3723 "done_v" := 0;
3724 LOOP
3725 "winners_ary" := '{}';
3726 "i" := 1;
3727 LOOP
3728 IF "rank_ary"["i"] ISNULL THEN
3729 "j" := 1;
3730 LOOP
3731 IF
3732 "i" != "j" AND
3733 "rank_ary"["j"] ISNULL AND
3734 "matrix"["j"]["i"] > "matrix"["i"]["j"]
3735 THEN
3736 -- someone else is better
3737 EXIT;
3738 END IF;
3739 IF "j" = "dimension_v" THEN
3740 -- noone is better
3741 "winners_ary" := "winners_ary" || "i";
3742 EXIT;
3743 END IF;
3744 "j" := "j" + 1;
3745 END LOOP;
3746 END IF;
3747 EXIT WHEN "i" = "dimension_v";
3748 "i" := "i" + 1;
3749 END LOOP;
3750 "i" := 1;
3751 LOOP
3752 "rank_ary"["winners_ary"["i"]] := "rank_v";
3753 "done_v" := "done_v" + 1;
3754 EXIT WHEN "i" = array_upper("winners_ary", 1);
3755 "i" := "i" + 1;
3756 END LOOP;
3757 EXIT WHEN "done_v" = "dimension_v";
3758 "rank_v" := "rank_v" + 1;
3759 END LOOP;
3760 -- write preliminary results:
3761 "i" := 1;
3762 FOR "initiative_id_v" IN
3763 SELECT "id" FROM "initiative"
3764 WHERE "issue_id" = "issue_id_p" AND "admitted"
3765 ORDER BY "id"
3766 LOOP
3767 UPDATE "initiative" SET
3768 "favored" = "rank_ary"["i"] < "rank_ary"["dimension_v"],
3769 "unfavored" = "rank_ary"["i"] > "rank_ary"["dimension_v"],
3770 "preliminary_rank" = "rank_ary"["i"],
3771 "disqualified" = "rank_ary"["i"] >= "rank_ary"["dimension_v"],
3772 "winner" = FALSE
3773 WHERE "id" = "initiative_id_v";
3774 "i" := "i" + 1;
3775 END LOOP;
3776 IF "i" != "dimension_v" THEN
3777 RAISE EXCEPTION 'Wrong winner count (should not happen)';
3778 END IF;
3779 -- remove possible gap in preliminary ranks:
3780 IF NOT EXISTS (
3781 SELECT NULL FROM "initiative"
3782 WHERE "issue_id" = "issue_id_p"
3783 AND "favored"=FALSE AND "unfavored"=FALSE
3784 ) THEN
3785 UPDATE "initiative" SET "preliminary_rank" = "preliminary_rank" - 1
3786 WHERE "issue_id" = "issue_id_p" AND "unfavored";
3787 END IF;
3788 -- disqualify certain initiatives to enforce a stable result:
3789 UPDATE "initiative" SET "disqualified" = TRUE
3790 FROM (
3791 SELECT "losing_initiative"."id" AS "initiative_id"
3792 FROM "initiative" "losing_initiative"
3793 JOIN "initiative" "winning_initiative"
3794 ON "winning_initiative"."issue_id" = "issue_id_p"
3795 AND "winning_initiative"."admitted"
3796 JOIN "battle" "battle_win"
3797 ON "battle_win"."issue_id" = "issue_id_p"
3798 AND "battle_win"."winning_initiative_id" = "winning_initiative"."id"
3799 AND "battle_win"."losing_initiative_id" = "losing_initiative"."id"
3800 JOIN "battle" "battle_lose"
3801 ON "battle_lose"."issue_id" = "issue_id_p"
3802 AND "battle_lose"."losing_initiative_id" = "winning_initiative"."id"
3803 AND "battle_lose"."winning_initiative_id" = "losing_initiative"."id"
3804 WHERE "losing_initiative"."issue_id" = "issue_id_p"
3805 AND "losing_initiative"."admitted"
3806 AND "winning_initiative"."preliminary_rank" <
3807 "losing_initiative"."preliminary_rank"
3808 AND "battle_win"."count" > "battle_lose"."count"
3809 AND (
3810 "battle_win"."count" > "winning_initiative"."positive_votes" OR
3811 "battle_lose"."count" < "losing_initiative"."negative_votes" )
3812 ) AS "subquery"
3813 WHERE "id" = "subquery"."initiative_id";
3814 -- calculate final ranks (start counting with 1, no equal ranks):
3815 "rank_v" := 1;
3816 FOR "initiative_id_v" IN
3817 SELECT "id" FROM "initiative"
3818 WHERE "issue_id" = "issue_id_p" AND "admitted"
3819 ORDER BY "preliminary_rank", "id"
3820 LOOP
3821 UPDATE "initiative" SET "final_rank" = "rank_v"
3822 WHERE "id" = "initiative_id_v";
3823 "rank_v" := "rank_v" + 1;
3824 END LOOP;
3825 -- mark final winner:
3826 UPDATE "initiative" SET "winner" = TRUE
3827 FROM (
3828 SELECT "id" AS "initiative_id"
3829 FROM "initiative"
3830 WHERE "issue_id" = "issue_id_p"
3831 AND "attainable" AND NOT "disqualified"
3832 ORDER BY "final_rank"
3833 LIMIT 1
3834 ) AS "subquery"
3835 WHERE "id" = "subquery"."initiative_id";
3836 END IF;
3837 -- mark issue as finished:
3838 UPDATE "issue" SET
3839 "state" =
3840 CASE WHEN EXISTS (
3841 SELECT NULL FROM "initiative"
3842 WHERE "issue_id" = "issue_id_p" AND "winner"
3843 ) THEN
3844 'finished_with_winner'::"issue_state"
3845 ELSE
3846 'finished_without_winner'::"issue_state"
3847 END,
3848 "ranks_available" = TRUE
3849 WHERE "id" = "issue_id_p";
3850 RETURN;
3851 END;
3852 $$;
3854 COMMENT ON FUNCTION "calculate_ranks"
3855 ( "issue"."id"%TYPE )
3856 IS 'Determine ranking (Votes have to be counted first)';
3860 -----------------------------
3861 -- Automatic state changes --
3862 -----------------------------
3865 CREATE FUNCTION "check_issue"
3866 ( "issue_id_p" "issue"."id"%TYPE )
3867 RETURNS VOID
3868 LANGUAGE 'plpgsql' VOLATILE AS $$
3869 DECLARE
3870 "issue_row" "issue"%ROWTYPE;
3871 "policy_row" "policy"%ROWTYPE;
3872 BEGIN
3873 PERFORM "lock_issue"("issue_id_p");
3874 SELECT * INTO "issue_row" FROM "issue" WHERE "id" = "issue_id_p";
3875 -- only process open issues:
3876 IF "issue_row"."closed" ISNULL THEN
3877 SELECT * INTO "policy_row" FROM "policy"
3878 WHERE "id" = "issue_row"."policy_id";
3879 -- create a snapshot, unless issue is already fully frozen:
3880 IF "issue_row"."fully_frozen" ISNULL THEN
3881 PERFORM "create_snapshot"("issue_id_p");
3882 SELECT * INTO "issue_row" FROM "issue" WHERE "id" = "issue_id_p";
3883 END IF;
3884 -- eventually close or accept issues, which have not been accepted:
3885 IF "issue_row"."accepted" ISNULL THEN
3886 IF EXISTS (
3887 SELECT NULL FROM "initiative"
3888 WHERE "issue_id" = "issue_id_p"
3889 AND "supporter_count" > 0
3890 AND "supporter_count" * "policy_row"."issue_quorum_den"
3891 >= "issue_row"."population" * "policy_row"."issue_quorum_num"
3892 ) THEN
3893 -- accept issues, if supporter count is high enough
3894 PERFORM "set_snapshot_event"("issue_id_p", 'end_of_admission');
3895 -- NOTE: "issue_row" used later
3896 "issue_row"."state" := 'discussion';
3897 "issue_row"."accepted" := now();
3898 UPDATE "issue" SET
3899 "state" = "issue_row"."state",
3900 "accepted" = "issue_row"."accepted"
3901 WHERE "id" = "issue_row"."id";
3902 ELSIF
3903 now() >= "issue_row"."created" + "issue_row"."admission_time"
3904 THEN
3905 -- close issues, if admission time has expired
3906 PERFORM "set_snapshot_event"("issue_id_p", 'end_of_admission');
3907 UPDATE "issue" SET
3908 "state" = 'canceled_issue_not_accepted',
3909 "closed" = now()
3910 WHERE "id" = "issue_row"."id";
3911 END IF;
3912 END IF;
3913 -- eventually half freeze issues:
3914 IF
3915 -- NOTE: issue can't be closed at this point, if it has been accepted
3916 "issue_row"."accepted" NOTNULL AND
3917 "issue_row"."half_frozen" ISNULL
3918 THEN
3919 IF
3920 now() >= "issue_row"."accepted" + "issue_row"."discussion_time"
3921 THEN
3922 PERFORM "set_snapshot_event"("issue_id_p", 'half_freeze');
3923 -- NOTE: "issue_row" used later
3924 "issue_row"."state" := 'verification';
3925 "issue_row"."half_frozen" := now();
3926 UPDATE "issue" SET
3927 "state" = "issue_row"."state",
3928 "half_frozen" = "issue_row"."half_frozen"
3929 WHERE "id" = "issue_row"."id";
3930 END IF;
3931 END IF;
3932 -- close issues after some time, if all initiatives have been revoked:
3933 IF
3934 "issue_row"."closed" ISNULL AND
3935 NOT EXISTS (
3936 -- all initiatives are revoked
3937 SELECT NULL FROM "initiative"
3938 WHERE "issue_id" = "issue_id_p" AND "revoked" ISNULL
3939 ) AND (
3940 -- and issue has not been accepted yet
3941 "issue_row"."accepted" ISNULL OR
3942 NOT EXISTS (
3943 -- or no initiatives have been revoked lately
3944 SELECT NULL FROM "initiative"
3945 WHERE "issue_id" = "issue_id_p"
3946 AND now() < "revoked" + "issue_row"."verification_time"
3947 ) OR (
3948 -- or verification time has elapsed
3949 "issue_row"."half_frozen" NOTNULL AND
3950 "issue_row"."fully_frozen" ISNULL AND
3951 now() >= "issue_row"."half_frozen" + "issue_row"."verification_time"
3954 THEN
3955 -- NOTE: "issue_row" used later
3956 IF "issue_row"."accepted" ISNULL THEN
3957 "issue_row"."state" := 'canceled_revoked_before_accepted';
3958 ELSIF "issue_row"."half_frozen" ISNULL THEN
3959 "issue_row"."state" := 'canceled_after_revocation_during_discussion';
3960 ELSE
3961 "issue_row"."state" := 'canceled_after_revocation_during_verification';
3962 END IF;
3963 "issue_row"."closed" := now();
3964 UPDATE "issue" SET
3965 "state" = "issue_row"."state",
3966 "closed" = "issue_row"."closed"
3967 WHERE "id" = "issue_row"."id";
3968 END IF;
3969 -- fully freeze issue after verification time:
3970 IF
3971 "issue_row"."half_frozen" NOTNULL AND
3972 "issue_row"."fully_frozen" ISNULL AND
3973 "issue_row"."closed" ISNULL AND
3974 now() >= "issue_row"."half_frozen" + "issue_row"."verification_time"
3975 THEN
3976 PERFORM "freeze_after_snapshot"("issue_id_p");
3977 -- NOTE: "issue" might change, thus "issue_row" has to be updated below
3978 END IF;
3979 SELECT * INTO "issue_row" FROM "issue" WHERE "id" = "issue_id_p";
3980 -- close issue by calling close_voting(...) after voting time:
3981 IF
3982 "issue_row"."closed" ISNULL AND
3983 "issue_row"."fully_frozen" NOTNULL AND
3984 now() >= "issue_row"."fully_frozen" + "issue_row"."voting_time"
3985 THEN
3986 PERFORM "close_voting"("issue_id_p");
3987 -- calculate ranks will not consume much time and can be done now
3988 PERFORM "calculate_ranks"("issue_id_p");
3989 END IF;
3990 END IF;
3991 RETURN;
3992 END;
3993 $$;
3995 COMMENT ON FUNCTION "check_issue"
3996 ( "issue"."id"%TYPE )
3997 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.';
4000 CREATE FUNCTION "check_everything"()
4001 RETURNS VOID
4002 LANGUAGE 'plpgsql' VOLATILE AS $$
4003 DECLARE
4004 "issue_id_v" "issue"."id"%TYPE;
4005 BEGIN
4006 DELETE FROM "expired_session";
4007 PERFORM "check_last_login"();
4008 PERFORM "calculate_member_counts"();
4009 FOR "issue_id_v" IN SELECT "id" FROM "open_issue" LOOP
4010 PERFORM "check_issue"("issue_id_v");
4011 END LOOP;
4012 FOR "issue_id_v" IN SELECT "id" FROM "issue_with_ranks_missing" LOOP
4013 PERFORM "calculate_ranks"("issue_id_v");
4014 END LOOP;
4015 RETURN;
4016 END;
4017 $$;
4019 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.';
4023 ----------------------
4024 -- Deletion of data --
4025 ----------------------
4028 CREATE FUNCTION "clean_issue"("issue_id_p" "issue"."id"%TYPE)
4029 RETURNS VOID
4030 LANGUAGE 'plpgsql' VOLATILE AS $$
4031 DECLARE
4032 "issue_row" "issue"%ROWTYPE;
4033 BEGIN
4034 SELECT * INTO "issue_row"
4035 FROM "issue" WHERE "id" = "issue_id_p"
4036 FOR UPDATE;
4037 IF "issue_row"."cleaned" ISNULL THEN
4038 -- TODO: might be broken due to new constraints!
4039 UPDATE "issue" SET
4040 "closed" = NULL,
4041 "ranks_available" = FALSE
4042 WHERE "id" = "issue_id_p";
4043 DELETE FROM "delegating_voter"
4044 WHERE "issue_id" = "issue_id_p";
4045 DELETE FROM "direct_voter"
4046 WHERE "issue_id" = "issue_id_p";
4047 DELETE FROM "delegating_interest_snapshot"
4048 WHERE "issue_id" = "issue_id_p";
4049 DELETE FROM "direct_interest_snapshot"
4050 WHERE "issue_id" = "issue_id_p";
4051 DELETE FROM "delegating_population_snapshot"
4052 WHERE "issue_id" = "issue_id_p";
4053 DELETE FROM "direct_population_snapshot"
4054 WHERE "issue_id" = "issue_id_p";
4055 DELETE FROM "non_voter"
4056 WHERE "issue_id" = "issue_id_p";
4057 DELETE FROM "delegation"
4058 WHERE "issue_id" = "issue_id_p";
4059 DELETE FROM "supporter"
4060 WHERE "issue_id" = "issue_id_p";
4061 UPDATE "issue" SET
4062 "closed" = "issue_row"."closed",
4063 "ranks_available" = "issue_row"."ranks_available",
4064 "cleaned" = now()
4065 WHERE "id" = "issue_id_p";
4066 END IF;
4067 RETURN;
4068 END;
4069 $$;
4071 COMMENT ON FUNCTION "clean_issue"("issue"."id"%TYPE) IS 'Delete discussion data and votes belonging to an issue';
4074 CREATE FUNCTION "delete_member"("member_id_p" "member"."id"%TYPE)
4075 RETURNS VOID
4076 LANGUAGE 'plpgsql' VOLATILE AS $$
4077 BEGIN
4078 UPDATE "member" SET
4079 "last_login" = NULL,
4080 "last_login_public" = NULL,
4081 "login" = NULL,
4082 "password" = NULL,
4083 "locked" = TRUE,
4084 "active" = FALSE,
4085 "notify_email" = NULL,
4086 "notify_email_unconfirmed" = NULL,
4087 "notify_email_secret" = NULL,
4088 "notify_email_secret_expiry" = NULL,
4089 "notify_email_lock_expiry" = NULL,
4090 "password_reset_secret" = NULL,
4091 "password_reset_secret_expiry" = NULL,
4092 "organizational_unit" = NULL,
4093 "internal_posts" = NULL,
4094 "realname" = NULL,
4095 "birthday" = NULL,
4096 "address" = NULL,
4097 "email" = NULL,
4098 "xmpp_address" = NULL,
4099 "website" = NULL,
4100 "phone" = NULL,
4101 "mobile_phone" = NULL,
4102 "profession" = NULL,
4103 "external_memberships" = NULL,
4104 "external_posts" = NULL,
4105 "statement" = NULL
4106 WHERE "id" = "member_id_p";
4107 -- "text_search_data" is updated by triggers
4108 DELETE FROM "setting" WHERE "member_id" = "member_id_p";
4109 DELETE FROM "setting_map" WHERE "member_id" = "member_id_p";
4110 DELETE FROM "member_relation_setting" WHERE "member_id" = "member_id_p";
4111 DELETE FROM "member_image" WHERE "member_id" = "member_id_p";
4112 DELETE FROM "contact" WHERE "member_id" = "member_id_p";
4113 DELETE FROM "ignored_member" WHERE "member_id" = "member_id_p";
4114 DELETE FROM "session" WHERE "member_id" = "member_id_p";
4115 DELETE FROM "area_setting" WHERE "member_id" = "member_id_p";
4116 DELETE FROM "issue_setting" WHERE "member_id" = "member_id_p";
4117 DELETE FROM "ignored_initiative" WHERE "member_id" = "member_id_p";
4118 DELETE FROM "initiative_setting" WHERE "member_id" = "member_id_p";
4119 DELETE FROM "suggestion_setting" WHERE "member_id" = "member_id_p";
4120 DELETE FROM "membership" WHERE "member_id" = "member_id_p";
4121 DELETE FROM "delegation" WHERE "truster_id" = "member_id_p";
4122 DELETE FROM "non_voter" WHERE "member_id" = "member_id_p";
4123 DELETE FROM "direct_voter" USING "issue"
4124 WHERE "direct_voter"."issue_id" = "issue"."id"
4125 AND "issue"."closed" ISNULL
4126 AND "member_id" = "member_id_p";
4127 RETURN;
4128 END;
4129 $$;
4131 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)';
4134 CREATE FUNCTION "delete_private_data"()
4135 RETURNS VOID
4136 LANGUAGE 'plpgsql' VOLATILE AS $$
4137 BEGIN
4138 UPDATE "member" SET
4139 "last_login" = NULL,
4140 "login" = NULL,
4141 "password" = NULL,
4142 "notify_email" = NULL,
4143 "notify_email_unconfirmed" = NULL,
4144 "notify_email_secret" = NULL,
4145 "notify_email_secret_expiry" = NULL,
4146 "notify_email_lock_expiry" = NULL,
4147 "password_reset_secret" = NULL,
4148 "password_reset_secret_expiry" = NULL,
4149 "organizational_unit" = NULL,
4150 "internal_posts" = NULL,
4151 "realname" = NULL,
4152 "birthday" = NULL,
4153 "address" = NULL,
4154 "email" = NULL,
4155 "xmpp_address" = NULL,
4156 "website" = NULL,
4157 "phone" = NULL,
4158 "mobile_phone" = NULL,
4159 "profession" = NULL,
4160 "external_memberships" = NULL,
4161 "external_posts" = NULL,
4162 "statement" = NULL;
4163 -- "text_search_data" is updated by triggers
4164 DELETE FROM "invite_code";
4165 DELETE FROM "setting";
4166 DELETE FROM "setting_map";
4167 DELETE FROM "member_relation_setting";
4168 DELETE FROM "member_image";
4169 DELETE FROM "contact";
4170 DELETE FROM "ignored_member";
4171 DELETE FROM "session";
4172 DELETE FROM "area_setting";
4173 DELETE FROM "issue_setting";
4174 DELETE FROM "ignored_initiative";
4175 DELETE FROM "initiative_setting";
4176 DELETE FROM "suggestion_setting";
4177 DELETE FROM "non_voter";
4178 DELETE FROM "direct_voter" USING "issue"
4179 WHERE "direct_voter"."issue_id" = "issue"."id"
4180 AND "issue"."closed" ISNULL;
4181 RETURN;
4182 END;
4183 $$;
4185 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.';
4189 COMMIT;

Impressum / About Us