liquid_feedback_core

view core.sql @ 283:a00b58b7a510

Included changed comment on function "delete_private_data"() in core-update.v2.0.11-v2.1.0.sql
author jbe
date Sun Aug 19 18:31:57 2012 +0200 (2012-08-19)
parents 3ac4a5664f5c
children 4f935e989ff6
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 ('2.1.0', 2, 1, 0))
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 show any activity.';
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 "invite_code" TEXT UNIQUE,
88 "invite_code_expiry" TIMESTAMPTZ,
89 "admin_comment" TEXT,
90 "activated" TIMESTAMPTZ,
91 "last_activity" DATE,
92 "last_login" TIMESTAMPTZ,
93 "login" TEXT UNIQUE,
94 "password" TEXT,
95 "locked" BOOLEAN NOT NULL DEFAULT FALSE,
96 "active" BOOLEAN NOT NULL DEFAULT FALSE,
97 "admin" BOOLEAN NOT NULL DEFAULT FALSE,
98 "lang" TEXT,
99 "notify_email" TEXT,
100 "notify_email_unconfirmed" TEXT,
101 "notify_email_secret" TEXT UNIQUE,
102 "notify_email_secret_expiry" TIMESTAMPTZ,
103 "notify_email_lock_expiry" TIMESTAMPTZ,
104 "notify_level" "notify_level",
105 "password_reset_secret" TEXT UNIQUE,
106 "password_reset_secret_expiry" TIMESTAMPTZ,
107 "name" TEXT UNIQUE,
108 "identification" TEXT UNIQUE,
109 "authentication" TEXT,
110 "organizational_unit" TEXT,
111 "internal_posts" TEXT,
112 "realname" TEXT,
113 "birthday" DATE,
114 "address" TEXT,
115 "email" TEXT,
116 "xmpp_address" TEXT,
117 "website" TEXT,
118 "phone" TEXT,
119 "mobile_phone" TEXT,
120 "profession" TEXT,
121 "external_memberships" TEXT,
122 "external_posts" TEXT,
123 "formatting_engine" TEXT,
124 "statement" TEXT,
125 "text_search_data" TSVECTOR,
126 CONSTRAINT "active_requires_activated_and_last_activity"
127 CHECK ("active" = FALSE OR ("activated" NOTNULL AND "last_activity" NOTNULL)),
128 CONSTRAINT "name_not_null_if_activated"
129 CHECK ("activated" ISNULL OR "name" NOTNULL) );
130 CREATE INDEX "member_active_idx" ON "member" ("active");
131 CREATE INDEX "member_text_search_data_idx" ON "member" USING gin ("text_search_data");
132 CREATE TRIGGER "update_text_search_data"
133 BEFORE INSERT OR UPDATE ON "member"
134 FOR EACH ROW EXECUTE PROCEDURE
135 tsvector_update_trigger('text_search_data', 'pg_catalog.simple',
136 "name", "identification", "organizational_unit", "internal_posts",
137 "realname", "external_memberships", "external_posts", "statement" );
139 COMMENT ON TABLE "member" IS 'Users of the system, e.g. members of an organization';
141 COMMENT ON COLUMN "member"."created" IS 'Creation of member record and/or invite code';
142 COMMENT ON COLUMN "member"."invite_code" IS 'Optional invite code, to allow a member to initialize his/her account the first time';
143 COMMENT ON COLUMN "member"."invite_code_expiry" IS 'Expiry data/time for "invite_code"';
144 COMMENT ON COLUMN "member"."admin_comment" IS 'Hidden comment for administrative purposes';
145 COMMENT ON COLUMN "member"."activated" IS 'Timestamp of first activation of account (i.e. usage of "invite_code"); required to be set for "active" members';
146 COMMENT ON COLUMN "member"."last_activity" IS 'Date of last activity of member; required to be set for "active" members';
147 COMMENT ON COLUMN "member"."last_login" IS 'Timestamp of last login';
148 COMMENT ON COLUMN "member"."login" IS 'Login name';
149 COMMENT ON COLUMN "member"."password" IS 'Password (preferably as crypto-hash, depending on the frontend or access layer)';
150 COMMENT ON COLUMN "member"."locked" IS 'Locked members can not log in.';
151 COMMENT ON COLUMN "member"."active" IS 'Memberships, support and votes are taken into account when corresponding members are marked as active. Automatically set to FALSE, if "last_activity" is older than "system_setting"."member_ttl".';
152 COMMENT ON COLUMN "member"."admin" IS 'TRUE for admins, which can administrate other users and setup policies and areas';
153 COMMENT ON COLUMN "member"."lang" IS 'Language code of the preferred language of the member';
154 COMMENT ON COLUMN "member"."notify_email" IS 'Email address where notifications of the system are sent to';
155 COMMENT ON COLUMN "member"."notify_email_unconfirmed" IS 'Unconfirmed email address provided by the member to be copied into "notify_email" field after verification';
156 COMMENT ON COLUMN "member"."notify_email_secret" IS 'Secret sent to the address in "notify_email_unconformed"';
157 COMMENT ON COLUMN "member"."notify_email_secret_expiry" IS 'Expiry date/time for "notify_email_secret"';
158 COMMENT ON COLUMN "member"."notify_email_lock_expiry" IS 'Date/time until no further email confirmation mails may be sent (abuse protection)';
159 COMMENT ON COLUMN "member"."notify_level" IS 'Selects which event notifications are to be sent to the "notify_email" mail address, may be NULL if member did not make any selection yet';
160 COMMENT ON COLUMN "member"."name" IS 'Distinct name of the member, may be NULL if account has not been activated yet';
161 COMMENT ON COLUMN "member"."identification" IS 'Optional identification number or code of the member';
162 COMMENT ON COLUMN "member"."authentication" IS 'Information about how this member was authenticated';
163 COMMENT ON COLUMN "member"."organizational_unit" IS 'Branch or division of the organization the member belongs to';
164 COMMENT ON COLUMN "member"."internal_posts" IS 'Posts (offices) of the member inside the organization';
165 COMMENT ON COLUMN "member"."realname" IS 'Real name of the member, may be identical with "name"';
166 COMMENT ON COLUMN "member"."email" IS 'Published email address of the member; not used for system notifications';
167 COMMENT ON COLUMN "member"."external_memberships" IS 'Other organizations the member is involved in';
168 COMMENT ON COLUMN "member"."external_posts" IS 'Posts (offices) outside the organization';
169 COMMENT ON COLUMN "member"."formatting_engine" IS 'Allows different formatting engines (i.e. wiki formats) to be used for "member"."statement"';
170 COMMENT ON COLUMN "member"."statement" IS 'Freely chosen text of the member for his/her profile';
173 -- DEPRECATED API TABLES --
175 CREATE TYPE "application_access_level" AS ENUM
176 ('member', 'full', 'pseudonymous', 'anonymous');
178 COMMENT ON TYPE "application_access_level" IS 'DEPRECATED, WILL BE REMOVED! Access privileges for applications using the API';
181 CREATE TABLE "member_application" (
182 "id" SERIAL8 PRIMARY KEY,
183 UNIQUE ("member_id", "name"),
184 "member_id" INT4 NOT NULL REFERENCES "member" ("id")
185 ON DELETE CASCADE ON UPDATE CASCADE,
186 "name" TEXT NOT NULL,
187 "comment" TEXT,
188 "access_level" "application_access_level" NOT NULL,
189 "key" TEXT NOT NULL UNIQUE,
190 "last_usage" TIMESTAMPTZ );
192 COMMENT ON TABLE "member_application" IS 'DEPRECATED, WILL BE REMOVED! Registered application being allowed to use the API';
194 -- END OF DEPRECARED API TABLES --
197 CREATE TABLE "member_history" (
198 "id" SERIAL8 PRIMARY KEY,
199 "member_id" INT4 NOT NULL REFERENCES "member" ("id") ON DELETE CASCADE ON UPDATE CASCADE,
200 "until" TIMESTAMPTZ NOT NULL DEFAULT now(),
201 "active" BOOLEAN NOT NULL,
202 "name" TEXT NOT NULL );
203 CREATE INDEX "member_history_member_id_idx" ON "member_history" ("member_id");
205 COMMENT ON TABLE "member_history" IS 'Filled by trigger; keeps information about old names and active flag of members';
207 COMMENT ON COLUMN "member_history"."id" IS 'Primary key, which can be used to sort entries correctly (and time warp resistant)';
208 COMMENT ON COLUMN "member_history"."until" IS 'Timestamp until the data was valid';
211 CREATE TABLE "rendered_member_statement" (
212 PRIMARY KEY ("member_id", "format"),
213 "member_id" INT8 REFERENCES "member" ("id") ON DELETE CASCADE ON UPDATE CASCADE,
214 "format" TEXT,
215 "content" TEXT NOT NULL );
217 COMMENT ON TABLE "rendered_member_statement" IS 'This table may be used by frontends to cache "rendered" member statements (e.g. HTML output generated from wiki text)';
220 CREATE TABLE "setting" (
221 PRIMARY KEY ("member_id", "key"),
222 "member_id" INT4 REFERENCES "member" ("id") ON DELETE CASCADE ON UPDATE CASCADE,
223 "key" TEXT NOT NULL,
224 "value" TEXT NOT NULL );
225 CREATE INDEX "setting_key_idx" ON "setting" ("key");
227 COMMENT ON TABLE "setting" IS 'Place to store a frontend specific setting for members as a string';
229 COMMENT ON COLUMN "setting"."key" IS 'Name of the setting, preceded by a frontend specific prefix';
232 CREATE TABLE "setting_map" (
233 PRIMARY KEY ("member_id", "key", "subkey"),
234 "member_id" INT4 REFERENCES "member" ("id") ON DELETE CASCADE ON UPDATE CASCADE,
235 "key" TEXT NOT NULL,
236 "subkey" TEXT NOT NULL,
237 "value" TEXT NOT NULL );
238 CREATE INDEX "setting_map_key_idx" ON "setting_map" ("key");
240 COMMENT ON TABLE "setting_map" IS 'Place to store a frontend specific setting for members as a map of key value pairs';
242 COMMENT ON COLUMN "setting_map"."key" IS 'Name of the setting, preceded by a frontend specific prefix';
243 COMMENT ON COLUMN "setting_map"."subkey" IS 'Key of a map entry';
244 COMMENT ON COLUMN "setting_map"."value" IS 'Value of a map entry';
247 CREATE TABLE "member_relation_setting" (
248 PRIMARY KEY ("member_id", "key", "other_member_id"),
249 "member_id" INT4 REFERENCES "member" ("id") ON DELETE CASCADE ON UPDATE CASCADE,
250 "key" TEXT NOT NULL,
251 "other_member_id" INT4 REFERENCES "member" ("id") ON DELETE CASCADE ON UPDATE CASCADE,
252 "value" TEXT NOT NULL );
254 COMMENT ON TABLE "member_relation_setting" IS 'Place to store a frontend specific setting related to relations between members as a string';
257 CREATE TYPE "member_image_type" AS ENUM ('photo', 'avatar');
259 COMMENT ON TYPE "member_image_type" IS 'Types of images for a member';
262 CREATE TABLE "member_image" (
263 PRIMARY KEY ("member_id", "image_type", "scaled"),
264 "member_id" INT4 REFERENCES "member" ("id") ON DELETE CASCADE ON UPDATE CASCADE,
265 "image_type" "member_image_type",
266 "scaled" BOOLEAN,
267 "content_type" TEXT,
268 "data" BYTEA NOT NULL );
270 COMMENT ON TABLE "member_image" IS 'Images of members';
272 COMMENT ON COLUMN "member_image"."scaled" IS 'FALSE for original image, TRUE for scaled version of the image';
275 CREATE TABLE "member_count" (
276 "calculated" TIMESTAMPTZ NOT NULL DEFAULT NOW(),
277 "total_count" INT4 NOT NULL );
279 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';
281 COMMENT ON COLUMN "member_count"."calculated" IS 'timestamp indicating when the total member count and area member counts were calculated';
282 COMMENT ON COLUMN "member_count"."total_count" IS 'Total count of active(!) members';
285 CREATE TABLE "contact" (
286 PRIMARY KEY ("member_id", "other_member_id"),
287 "member_id" INT4 REFERENCES "member" ("id") ON DELETE CASCADE ON UPDATE CASCADE,
288 "other_member_id" INT4 REFERENCES "member" ("id") ON DELETE CASCADE ON UPDATE CASCADE,
289 "public" BOOLEAN NOT NULL DEFAULT FALSE,
290 CONSTRAINT "cant_save_yourself_as_contact"
291 CHECK ("member_id" != "other_member_id") );
292 CREATE INDEX "contact_other_member_id_idx" ON "contact" ("other_member_id");
294 COMMENT ON TABLE "contact" IS 'Contact lists';
296 COMMENT ON COLUMN "contact"."member_id" IS 'Member having the contact list';
297 COMMENT ON COLUMN "contact"."other_member_id" IS 'Member referenced in the contact list';
298 COMMENT ON COLUMN "contact"."public" IS 'TRUE = display contact publically';
301 CREATE TABLE "ignored_member" (
302 PRIMARY KEY ("member_id", "other_member_id"),
303 "member_id" INT4 REFERENCES "member" ("id") ON DELETE CASCADE ON UPDATE CASCADE,
304 "other_member_id" INT4 REFERENCES "member" ("id") ON DELETE CASCADE ON UPDATE CASCADE );
305 CREATE INDEX "ignored_member_other_member_id_idx" ON "ignored_member" ("other_member_id");
307 COMMENT ON TABLE "ignored_member" IS 'Possibility to filter other members';
309 COMMENT ON COLUMN "ignored_member"."member_id" IS 'Member ignoring someone';
310 COMMENT ON COLUMN "ignored_member"."other_member_id" IS 'Member being ignored';
313 CREATE TABLE "session" (
314 "ident" TEXT PRIMARY KEY,
315 "additional_secret" TEXT,
316 "expiry" TIMESTAMPTZ NOT NULL DEFAULT now() + '24 hours',
317 "member_id" INT8 REFERENCES "member" ("id") ON DELETE SET NULL,
318 "lang" TEXT );
319 CREATE INDEX "session_expiry_idx" ON "session" ("expiry");
321 COMMENT ON TABLE "session" IS 'Sessions, i.e. for a web-frontend or API layer';
323 COMMENT ON COLUMN "session"."ident" IS 'Secret session identifier (i.e. random string)';
324 COMMENT ON COLUMN "session"."additional_secret" IS 'Additional field to store a secret, which can be used against CSRF attacks';
325 COMMENT ON COLUMN "session"."member_id" IS 'Reference to member, who is logged in';
326 COMMENT ON COLUMN "session"."lang" IS 'Language code of the selected language';
329 CREATE TABLE "policy" (
330 "id" SERIAL4 PRIMARY KEY,
331 "index" INT4 NOT NULL,
332 "active" BOOLEAN NOT NULL DEFAULT TRUE,
333 "name" TEXT NOT NULL UNIQUE,
334 "description" TEXT NOT NULL DEFAULT '',
335 "polling" BOOLEAN NOT NULL DEFAULT FALSE,
336 "admission_time" INTERVAL,
337 "discussion_time" INTERVAL,
338 "verification_time" INTERVAL,
339 "voting_time" INTERVAL,
340 "issue_quorum_num" INT4 NOT NULL,
341 "issue_quorum_den" INT4 NOT NULL,
342 "initiative_quorum_num" INT4 NOT NULL,
343 "initiative_quorum_den" INT4 NOT NULL,
344 "direct_majority_num" INT4 NOT NULL DEFAULT 1,
345 "direct_majority_den" INT4 NOT NULL DEFAULT 2,
346 "direct_majority_strict" BOOLEAN NOT NULL DEFAULT TRUE,
347 "direct_majority_positive" INT4 NOT NULL DEFAULT 0,
348 "direct_majority_non_negative" INT4 NOT NULL DEFAULT 0,
349 "indirect_majority_num" INT4 NOT NULL DEFAULT 1,
350 "indirect_majority_den" INT4 NOT NULL DEFAULT 2,
351 "indirect_majority_strict" BOOLEAN NOT NULL DEFAULT TRUE,
352 "indirect_majority_positive" INT4 NOT NULL DEFAULT 0,
353 "indirect_majority_non_negative" INT4 NOT NULL DEFAULT 0,
354 "no_reverse_beat_path" BOOLEAN NOT NULL DEFAULT TRUE,
355 "no_multistage_majority" BOOLEAN NOT NULL DEFAULT FALSE,
356 CONSTRAINT "timing" CHECK (
357 ( "polling" = FALSE AND
358 "admission_time" NOTNULL AND "discussion_time" NOTNULL AND
359 "verification_time" NOTNULL AND "voting_time" NOTNULL ) OR
360 ( "polling" = TRUE AND
361 "admission_time" ISNULL AND "discussion_time" NOTNULL AND
362 "verification_time" NOTNULL AND "voting_time" NOTNULL ) OR
363 ( "polling" = TRUE AND
364 "admission_time" ISNULL AND "discussion_time" ISNULL AND
365 "verification_time" ISNULL AND "voting_time" ISNULL ) ) );
366 CREATE INDEX "policy_active_idx" ON "policy" ("active");
368 COMMENT ON TABLE "policy" IS 'Policies for a particular proceeding type (timelimits, quorum)';
370 COMMENT ON COLUMN "policy"."index" IS 'Determines the order in listings';
371 COMMENT ON COLUMN "policy"."active" IS 'TRUE = policy can be used for new issues';
372 COMMENT ON COLUMN "policy"."polling" IS 'TRUE = special policy for non-user-generated issues, i.e. polls ("admission_time" MUST be set to NULL, the other timings may be set to NULL altogether, allowing individual timing for issues)';
373 COMMENT ON COLUMN "policy"."admission_time" IS 'Maximum duration of issue state ''admission''; Maximum time an issue stays open without being "accepted"';
374 COMMENT ON COLUMN "policy"."discussion_time" IS 'Duration of issue state ''discussion''; Regular time until an issue is "half_frozen" after being "accepted"';
375 COMMENT ON COLUMN "policy"."verification_time" IS 'Duration of issue state ''verification''; Regular time until an issue is "fully_frozen" (e.g. entering issue state ''voting'') after being "half_frozen"';
376 COMMENT ON COLUMN "policy"."voting_time" IS 'Duration of issue state ''voting''; Time after an issue is "fully_frozen" but not "closed" (duration of issue state ''voting'')';
377 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" and enter issue state ''discussion''';
378 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" and enter issue state ''discussion''';
379 COMMENT ON COLUMN "policy"."initiative_quorum_num" IS 'Numerator of satisfied supporter quorum to be reached by an initiative to be "admitted" for voting';
380 COMMENT ON COLUMN "policy"."initiative_quorum_den" IS 'Denominator of satisfied supporter quorum to be reached by an initiative to be "admitted" for voting';
381 COMMENT ON COLUMN "policy"."direct_majority_num" IS 'Numerator of fraction of neccessary direct majority for initiatives to be attainable as winner';
382 COMMENT ON COLUMN "policy"."direct_majority_den" IS 'Denominator of fraction of neccessary direct majority for initaitives to be attainable as winner';
383 COMMENT ON COLUMN "policy"."direct_majority_strict" IS 'If TRUE, then the direct majority must be strictly greater than "direct_majority_num"/"direct_majority_den", otherwise it may also be equal.';
384 COMMENT ON COLUMN "policy"."direct_majority_positive" IS 'Absolute number of "positive_votes" neccessary for an initiative to be attainable as winner';
385 COMMENT ON COLUMN "policy"."direct_majority_non_negative" IS 'Absolute number of sum of "positive_votes" and abstentions neccessary for an initiative to be attainable as winner';
386 COMMENT ON COLUMN "policy"."indirect_majority_num" IS 'Numerator of fraction of neccessary indirect majority (through beat path) for initiatives to be attainable as winner';
387 COMMENT ON COLUMN "policy"."indirect_majority_den" IS 'Denominator of fraction of neccessary indirect majority (through beat path) for initiatives to be attainable as winner';
388 COMMENT ON COLUMN "policy"."indirect_majority_strict" IS 'If TRUE, then the indirect majority must be strictly greater than "indirect_majority_num"/"indirect_majority_den", otherwise it may also be equal.';
389 COMMENT ON COLUMN "policy"."indirect_majority_positive" IS 'Absolute number of votes in favor of the winner neccessary in a beat path to the status quo for an initaitive to be attainable as winner';
390 COMMENT ON COLUMN "policy"."indirect_majority_non_negative" IS 'Absolute number of sum of votes in favor and abstentions in a beat path to the status quo for an initiative to be attainable as winner';
391 COMMENT ON COLUMN "policy"."no_reverse_beat_path" IS 'Causes initiatives with "reverse_beat_path" flag to not be "eligible", thus disallowing them to be winner. See comment on column "initiative"."reverse_beat_path". This option ensures both that a winning initiative is never tied in a (weak) condorcet paradox with the status quo and a winning initiative always beats the status quo directly with a simple majority.';
392 COMMENT ON COLUMN "policy"."no_multistage_majority" IS 'Causes initiatives with "multistage_majority" flag to not be "eligible", thus disallowing them to be winner. See comment on column "initiative"."multistage_majority". This disqualifies initiatives which could cause an instable result. An instable result in this meaning is a result such that repeating the ballot with same preferences but with the winner of the first ballot as status quo would lead to a different winner in the second ballot. If there are no direct majorities required for the winner, or if in direct comparison only simple majorities are required and "no_reverse_beat_path" is true, then results are always stable and this flag does not have any effect on the winner (but still affects the "eligible" flag of an "initiative").';
395 CREATE TABLE "unit" (
396 "id" SERIAL4 PRIMARY KEY,
397 "parent_id" INT4 REFERENCES "unit" ("id") ON DELETE CASCADE ON UPDATE CASCADE,
398 "active" BOOLEAN NOT NULL DEFAULT TRUE,
399 "name" TEXT NOT NULL,
400 "description" TEXT NOT NULL DEFAULT '',
401 "member_count" INT4,
402 "text_search_data" TSVECTOR );
403 CREATE INDEX "unit_root_idx" ON "unit" ("id") WHERE "parent_id" ISNULL;
404 CREATE INDEX "unit_parent_id_idx" ON "unit" ("parent_id");
405 CREATE INDEX "unit_active_idx" ON "unit" ("active");
406 CREATE INDEX "unit_text_search_data_idx" ON "unit" USING gin ("text_search_data");
407 CREATE TRIGGER "update_text_search_data"
408 BEFORE INSERT OR UPDATE ON "unit"
409 FOR EACH ROW EXECUTE PROCEDURE
410 tsvector_update_trigger('text_search_data', 'pg_catalog.simple',
411 "name", "description" );
413 COMMENT ON TABLE "unit" IS 'Organizational units organized as trees; Delegations are not inherited through these trees.';
415 COMMENT ON COLUMN "unit"."parent_id" IS 'Parent id of tree node; Multiple roots allowed';
416 COMMENT ON COLUMN "unit"."active" IS 'TRUE means new issues can be created in areas of this unit';
417 COMMENT ON COLUMN "unit"."member_count" IS 'Count of members as determined by column "voting_right" in table "privilege"';
420 CREATE TABLE "unit_setting" (
421 PRIMARY KEY ("member_id", "key", "unit_id"),
422 "member_id" INT4 REFERENCES "member" ("id") ON DELETE CASCADE ON UPDATE CASCADE,
423 "key" TEXT NOT NULL,
424 "unit_id" INT4 REFERENCES "unit" ("id") ON DELETE CASCADE ON UPDATE CASCADE,
425 "value" TEXT NOT NULL );
427 COMMENT ON TABLE "unit_setting" IS 'Place for frontend to store unit specific settings of members as strings';
430 CREATE TABLE "area" (
431 "id" SERIAL4 PRIMARY KEY,
432 "unit_id" INT4 NOT NULL REFERENCES "unit" ("id") ON DELETE CASCADE ON UPDATE CASCADE,
433 "active" BOOLEAN NOT NULL DEFAULT TRUE,
434 "name" TEXT NOT NULL,
435 "description" TEXT NOT NULL DEFAULT '',
436 "direct_member_count" INT4,
437 "member_weight" INT4,
438 "text_search_data" TSVECTOR );
439 CREATE INDEX "area_unit_id_idx" ON "area" ("unit_id");
440 CREATE INDEX "area_active_idx" ON "area" ("active");
441 CREATE INDEX "area_text_search_data_idx" ON "area" USING gin ("text_search_data");
442 CREATE TRIGGER "update_text_search_data"
443 BEFORE INSERT OR UPDATE ON "area"
444 FOR EACH ROW EXECUTE PROCEDURE
445 tsvector_update_trigger('text_search_data', 'pg_catalog.simple',
446 "name", "description" );
448 COMMENT ON TABLE "area" IS 'Subject areas';
450 COMMENT ON COLUMN "area"."active" IS 'TRUE means new issues can be created in this area';
451 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"';
452 COMMENT ON COLUMN "area"."member_weight" IS 'Same as "direct_member_count" but respecting delegations';
455 CREATE TABLE "area_setting" (
456 PRIMARY KEY ("member_id", "key", "area_id"),
457 "member_id" INT4 REFERENCES "member" ("id") ON DELETE CASCADE ON UPDATE CASCADE,
458 "key" TEXT NOT NULL,
459 "area_id" INT4 REFERENCES "area" ("id") ON DELETE CASCADE ON UPDATE CASCADE,
460 "value" TEXT NOT NULL );
462 COMMENT ON TABLE "area_setting" IS 'Place for frontend to store area specific settings of members as strings';
465 CREATE TABLE "allowed_policy" (
466 PRIMARY KEY ("area_id", "policy_id"),
467 "area_id" INT4 REFERENCES "area" ("id") ON DELETE CASCADE ON UPDATE CASCADE,
468 "policy_id" INT4 NOT NULL REFERENCES "policy" ("id") ON DELETE CASCADE ON UPDATE CASCADE,
469 "default_policy" BOOLEAN NOT NULL DEFAULT FALSE );
470 CREATE UNIQUE INDEX "allowed_policy_one_default_per_area_idx" ON "allowed_policy" ("area_id") WHERE "default_policy";
472 COMMENT ON TABLE "allowed_policy" IS 'Selects which policies can be used in each area';
474 COMMENT ON COLUMN "allowed_policy"."default_policy" IS 'One policy per area can be set as default.';
477 CREATE TYPE "snapshot_event" AS ENUM ('periodic', 'end_of_admission', 'half_freeze', 'full_freeze');
479 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';
482 CREATE TYPE "issue_state" AS ENUM (
483 'admission', 'discussion', 'verification', 'voting',
484 'canceled_revoked_before_accepted',
485 'canceled_issue_not_accepted',
486 'canceled_after_revocation_during_discussion',
487 'canceled_after_revocation_during_verification',
488 'calculation',
489 'canceled_no_initiative_admitted',
490 'finished_without_winner', 'finished_with_winner');
492 COMMENT ON TYPE "issue_state" IS 'State of issues';
495 CREATE TABLE "issue" (
496 "id" SERIAL4 PRIMARY KEY,
497 "area_id" INT4 NOT NULL REFERENCES "area" ("id") ON DELETE CASCADE ON UPDATE CASCADE,
498 "policy_id" INT4 NOT NULL REFERENCES "policy" ("id") ON DELETE RESTRICT ON UPDATE CASCADE,
499 "state" "issue_state" NOT NULL DEFAULT 'admission',
500 "created" TIMESTAMPTZ NOT NULL DEFAULT now(),
501 "accepted" TIMESTAMPTZ,
502 "half_frozen" TIMESTAMPTZ,
503 "fully_frozen" TIMESTAMPTZ,
504 "closed" TIMESTAMPTZ,
505 "ranks_available" BOOLEAN NOT NULL DEFAULT FALSE,
506 "cleaned" TIMESTAMPTZ,
507 "admission_time" INTERVAL NOT NULL,
508 "discussion_time" INTERVAL NOT NULL,
509 "verification_time" INTERVAL NOT NULL,
510 "voting_time" INTERVAL NOT NULL,
511 "snapshot" TIMESTAMPTZ,
512 "latest_snapshot_event" "snapshot_event",
513 "population" INT4,
514 "voter_count" INT4,
515 "status_quo_schulze_rank" INT4,
516 CONSTRAINT "valid_state" CHECK ((
517 ("accepted" ISNULL AND "half_frozen" ISNULL AND "fully_frozen" ISNULL AND "closed" ISNULL AND "ranks_available" = FALSE) OR
518 ("accepted" ISNULL AND "half_frozen" ISNULL AND "fully_frozen" ISNULL AND "closed" NOTNULL AND "ranks_available" = FALSE) OR
519 ("accepted" NOTNULL AND "half_frozen" ISNULL AND "fully_frozen" ISNULL AND "closed" ISNULL AND "ranks_available" = FALSE) OR
520 ("accepted" NOTNULL AND "half_frozen" ISNULL AND "fully_frozen" ISNULL AND "closed" NOTNULL AND "ranks_available" = FALSE) OR
521 ("accepted" NOTNULL AND "half_frozen" NOTNULL AND "fully_frozen" ISNULL AND "closed" ISNULL AND "ranks_available" = FALSE) OR
522 ("accepted" NOTNULL AND "half_frozen" NOTNULL AND "fully_frozen" ISNULL AND "closed" NOTNULL AND "ranks_available" = FALSE) OR
523 ("accepted" NOTNULL AND "half_frozen" NOTNULL AND "fully_frozen" NOTNULL AND "closed" ISNULL AND "ranks_available" = FALSE) OR
524 ("accepted" NOTNULL AND "half_frozen" NOTNULL AND "fully_frozen" NOTNULL AND "closed" NOTNULL AND "ranks_available" = FALSE) OR
525 ("accepted" NOTNULL AND "half_frozen" NOTNULL AND "fully_frozen" NOTNULL AND "closed" NOTNULL AND "ranks_available" = TRUE)) AND (
526 ("state" = 'admission' AND "closed" ISNULL AND "accepted" ISNULL) OR
527 ("state" = 'discussion' AND "closed" ISNULL AND "accepted" NOTNULL AND "half_frozen" ISNULL) OR
528 ("state" = 'verification' AND "closed" ISNULL AND "half_frozen" NOTNULL AND "fully_frozen" ISNULL) OR
529 ("state" = 'voting' AND "closed" ISNULL AND "fully_frozen" NOTNULL) OR
530 ("state" = 'canceled_revoked_before_accepted' AND "closed" NOTNULL AND "accepted" ISNULL) OR
531 ("state" = 'canceled_issue_not_accepted' AND "closed" NOTNULL AND "accepted" ISNULL) OR
532 ("state" = 'canceled_after_revocation_during_discussion' AND "closed" NOTNULL AND "half_frozen" ISNULL) OR
533 ("state" = 'canceled_after_revocation_during_verification' AND "closed" NOTNULL AND "fully_frozen" ISNULL) OR
534 ("state" = 'calculation' AND "closed" NOTNULL AND "fully_frozen" NOTNULL AND "ranks_available" = FALSE) OR
535 ("state" = 'canceled_no_initiative_admitted' AND "closed" NOTNULL AND "fully_frozen" NOTNULL AND "ranks_available" = TRUE) OR
536 ("state" = 'finished_without_winner' AND "closed" NOTNULL AND "fully_frozen" NOTNULL AND "ranks_available" = TRUE) OR
537 ("state" = 'finished_with_winner' AND "closed" NOTNULL AND "fully_frozen" NOTNULL AND "ranks_available" = TRUE)
538 )),
539 CONSTRAINT "state_change_order" CHECK (
540 "created" <= "accepted" AND
541 "accepted" <= "half_frozen" AND
542 "half_frozen" <= "fully_frozen" AND
543 "fully_frozen" <= "closed" ),
544 CONSTRAINT "only_closed_issues_may_be_cleaned" CHECK (
545 "cleaned" ISNULL OR "closed" NOTNULL ),
546 CONSTRAINT "last_snapshot_on_full_freeze"
547 CHECK ("snapshot" = "fully_frozen"), -- NOTE: snapshot can be set, while frozen is NULL yet
548 CONSTRAINT "freeze_requires_snapshot"
549 CHECK ("fully_frozen" ISNULL OR "snapshot" NOTNULL),
550 CONSTRAINT "set_both_or_none_of_snapshot_and_latest_snapshot_event"
551 CHECK ("snapshot" NOTNULL = "latest_snapshot_event" NOTNULL) );
552 CREATE INDEX "issue_area_id_idx" ON "issue" ("area_id");
553 CREATE INDEX "issue_policy_id_idx" ON "issue" ("policy_id");
554 CREATE INDEX "issue_created_idx" ON "issue" ("created");
555 CREATE INDEX "issue_accepted_idx" ON "issue" ("accepted");
556 CREATE INDEX "issue_half_frozen_idx" ON "issue" ("half_frozen");
557 CREATE INDEX "issue_fully_frozen_idx" ON "issue" ("fully_frozen");
558 CREATE INDEX "issue_closed_idx" ON "issue" ("closed");
559 CREATE INDEX "issue_created_idx_open" ON "issue" ("created") WHERE "closed" ISNULL;
560 CREATE INDEX "issue_closed_idx_canceled" ON "issue" ("closed") WHERE "fully_frozen" ISNULL;
562 COMMENT ON TABLE "issue" IS 'Groups of initiatives';
564 COMMENT ON COLUMN "issue"."accepted" IS 'Point in time, when one initiative of issue reached the "issue_quorum"';
565 COMMENT ON COLUMN "issue"."half_frozen" IS 'Point in time, when "discussion_time" has elapsed; 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.';
566 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.';
567 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.';
568 COMMENT ON COLUMN "issue"."ranks_available" IS 'TRUE = ranks have been calculated';
569 COMMENT ON COLUMN "issue"."cleaned" IS 'Point in time, when discussion data and votes had been deleted';
570 COMMENT ON COLUMN "issue"."admission_time" IS 'Copied from "policy" table at creation of issue';
571 COMMENT ON COLUMN "issue"."discussion_time" IS 'Copied from "policy" table at creation of issue';
572 COMMENT ON COLUMN "issue"."verification_time" IS 'Copied from "policy" table at creation of issue';
573 COMMENT ON COLUMN "issue"."voting_time" IS 'Copied from "policy" table at creation of issue';
574 COMMENT ON COLUMN "issue"."snapshot" IS 'Point in time, when snapshot tables have been updated and "population" and *_count values were precalculated';
575 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';
576 COMMENT ON COLUMN "issue"."population" IS 'Sum of "weight" column in table "direct_population_snapshot"';
577 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';
578 COMMENT ON COLUMN "issue"."status_quo_schulze_rank" IS 'Schulze rank of status quo, as calculated by "calculate_ranks" function';
581 CREATE TABLE "issue_setting" (
582 PRIMARY KEY ("member_id", "key", "issue_id"),
583 "member_id" INT4 REFERENCES "member" ("id") ON DELETE CASCADE ON UPDATE CASCADE,
584 "key" TEXT NOT NULL,
585 "issue_id" INT4 REFERENCES "issue" ("id") ON DELETE CASCADE ON UPDATE CASCADE,
586 "value" TEXT NOT NULL );
588 COMMENT ON TABLE "issue_setting" IS 'Place for frontend to store issue specific settings of members as strings';
591 CREATE TABLE "initiative" (
592 UNIQUE ("issue_id", "id"), -- index needed for foreign-key on table "vote"
593 "issue_id" INT4 NOT NULL REFERENCES "issue" ("id") ON DELETE CASCADE ON UPDATE CASCADE,
594 "id" SERIAL4 PRIMARY KEY,
595 "name" TEXT NOT NULL,
596 "polling" BOOLEAN NOT NULL DEFAULT FALSE,
597 "discussion_url" TEXT,
598 "created" TIMESTAMPTZ NOT NULL DEFAULT now(),
599 "revoked" TIMESTAMPTZ,
600 "revoked_by_member_id" INT4 REFERENCES "member" ("id") ON DELETE RESTRICT ON UPDATE CASCADE,
601 "suggested_initiative_id" INT4 REFERENCES "initiative" ("id") ON DELETE CASCADE ON UPDATE CASCADE,
602 "admitted" BOOLEAN,
603 "supporter_count" INT4,
604 "informed_supporter_count" INT4,
605 "satisfied_supporter_count" INT4,
606 "satisfied_informed_supporter_count" INT4,
607 "positive_votes" INT4,
608 "negative_votes" INT4,
609 "direct_majority" BOOLEAN,
610 "indirect_majority" BOOLEAN,
611 "schulze_rank" INT4,
612 "better_than_status_quo" BOOLEAN,
613 "worse_than_status_quo" BOOLEAN,
614 "reverse_beat_path" BOOLEAN,
615 "multistage_majority" BOOLEAN,
616 "eligible" BOOLEAN,
617 "winner" BOOLEAN,
618 "rank" INT4,
619 "text_search_data" TSVECTOR,
620 CONSTRAINT "all_or_none_of_revoked_and_revoked_by_member_id_must_be_null"
621 CHECK ("revoked" NOTNULL = "revoked_by_member_id" NOTNULL),
622 CONSTRAINT "non_revoked_initiatives_cant_suggest_other"
623 CHECK ("revoked" NOTNULL OR "suggested_initiative_id" ISNULL),
624 CONSTRAINT "revoked_initiatives_cant_be_admitted"
625 CHECK ("revoked" ISNULL OR "admitted" ISNULL),
626 CONSTRAINT "non_admitted_initiatives_cant_contain_voting_results" CHECK (
627 ( "admitted" NOTNULL AND "admitted" = TRUE ) OR
628 ( "positive_votes" ISNULL AND "negative_votes" ISNULL AND
629 "direct_majority" ISNULL AND "indirect_majority" ISNULL AND
630 "schulze_rank" ISNULL AND
631 "better_than_status_quo" ISNULL AND "worse_than_status_quo" ISNULL AND
632 "reverse_beat_path" ISNULL AND "multistage_majority" ISNULL AND
633 "eligible" ISNULL AND "winner" ISNULL AND "rank" ISNULL ) ),
634 CONSTRAINT "better_excludes_worse" CHECK (NOT ("better_than_status_quo" AND "worse_than_status_quo")),
635 CONSTRAINT "minimum_requirement_to_be_eligible" CHECK (
636 "eligible" = FALSE OR
637 ("direct_majority" AND "indirect_majority" AND "better_than_status_quo") ),
638 CONSTRAINT "winner_must_be_eligible" CHECK ("winner"=FALSE OR "eligible"=TRUE),
639 CONSTRAINT "winner_must_have_first_rank" CHECK ("winner"=FALSE OR "rank"=1),
640 CONSTRAINT "eligible_at_first_rank_is_winner" CHECK ("eligible"=FALSE OR "rank"!=1 OR "winner"=TRUE),
641 CONSTRAINT "unique_rank_per_issue" UNIQUE ("issue_id", "rank") );
642 CREATE INDEX "initiative_created_idx" ON "initiative" ("created");
643 CREATE INDEX "initiative_revoked_idx" ON "initiative" ("revoked");
644 CREATE INDEX "initiative_text_search_data_idx" ON "initiative" USING gin ("text_search_data");
645 CREATE TRIGGER "update_text_search_data"
646 BEFORE INSERT OR UPDATE ON "initiative"
647 FOR EACH ROW EXECUTE PROCEDURE
648 tsvector_update_trigger('text_search_data', 'pg_catalog.simple',
649 "name", "discussion_url");
651 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.';
653 COMMENT ON COLUMN "initiative"."polling" IS 'Initiative is an option for a poll (see "policy"."polling"), and does not need to pass the initiative quorum';
654 COMMENT ON COLUMN "initiative"."discussion_url" IS 'URL pointing to a discussion platform for this initiative';
655 COMMENT ON COLUMN "initiative"."revoked" IS 'Point in time, when one initiator decided to revoke the initiative';
656 COMMENT ON COLUMN "initiative"."revoked_by_member_id" IS 'Member, who decided to revoke the initiative';
657 COMMENT ON COLUMN "initiative"."admitted" IS 'TRUE, if initiative reaches the "initiative_quorum" when freezing the issue';
658 COMMENT ON COLUMN "initiative"."supporter_count" IS 'Calculated from table "direct_supporter_snapshot"';
659 COMMENT ON COLUMN "initiative"."informed_supporter_count" IS 'Calculated from table "direct_supporter_snapshot"';
660 COMMENT ON COLUMN "initiative"."satisfied_supporter_count" IS 'Calculated from table "direct_supporter_snapshot"';
661 COMMENT ON COLUMN "initiative"."satisfied_informed_supporter_count" IS 'Calculated from table "direct_supporter_snapshot"';
662 COMMENT ON COLUMN "initiative"."positive_votes" IS 'Calculated from table "direct_voter"';
663 COMMENT ON COLUMN "initiative"."negative_votes" IS 'Calculated from table "direct_voter"';
664 COMMENT ON COLUMN "initiative"."direct_majority" IS 'TRUE, if "positive_votes"/("positive_votes"+"negative_votes") is strictly greater or greater-equal than "direct_majority_num"/"direct_majority_den", and "positive_votes" is greater-equal than "direct_majority_positive", and ("positive_votes"+abstentions) is greater-equal than "direct_majority_non_negative"';
665 COMMENT ON COLUMN "initiative"."indirect_majority" IS 'Same as "direct_majority", but also considering indirect beat paths';
666 COMMENT ON COLUMN "initiative"."schulze_rank" IS 'Schulze-Ranking without tie-breaking';
667 COMMENT ON COLUMN "initiative"."better_than_status_quo" IS 'TRUE, if initiative has a schulze-ranking better than the status quo (without tie-breaking)';
668 COMMENT ON COLUMN "initiative"."worse_than_status_quo" IS 'TRUE, if initiative has a schulze-ranking worse than the status quo (without tie-breaking)';
669 COMMENT ON COLUMN "initiative"."reverse_beat_path" IS 'TRUE, if there is a beat path (may include ties) from this initiative to the status quo';
670 COMMENT ON COLUMN "initiative"."multistage_majority" IS 'TRUE, if either (a) this initiative has no better rank than the status quo, or (b) 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';
671 COMMENT ON COLUMN "initiative"."eligible" IS 'Initiative has a "direct_majority" and an "indirect_majority", is "better_than_status_quo" and depending on selected policy the initiative has no "reverse_beat_path" or "multistage_majority"';
672 COMMENT ON COLUMN "initiative"."winner" IS 'Winner is the "eligible" initiative with best "schulze_rank" and in case of ties with lowest "id"';
673 COMMENT ON COLUMN "initiative"."rank" IS 'Unique ranking for all "admitted" initiatives per issue; lower rank is better; a winner always has rank 1, but rank 1 does not imply that an initiative is winner; initiatives with "direct_majority" AND "indirect_majority" always have a better (lower) rank than other initiatives';
676 CREATE TABLE "battle" (
677 "issue_id" INT4 NOT NULL,
678 "winning_initiative_id" INT4,
679 FOREIGN KEY ("issue_id", "winning_initiative_id") REFERENCES "initiative" ("issue_id", "id") ON DELETE CASCADE ON UPDATE CASCADE,
680 "losing_initiative_id" INT4,
681 FOREIGN KEY ("issue_id", "losing_initiative_id") REFERENCES "initiative" ("issue_id", "id") ON DELETE CASCADE ON UPDATE CASCADE,
682 "count" INT4 NOT NULL,
683 CONSTRAINT "initiative_ids_not_equal" CHECK (
684 "winning_initiative_id" != "losing_initiative_id" OR
685 ( ("winning_initiative_id" NOTNULL AND "losing_initiative_id" ISNULL) OR
686 ("winning_initiative_id" ISNULL AND "losing_initiative_id" NOTNULL) ) ) );
687 CREATE UNIQUE INDEX "battle_winning_losing_idx" ON "battle" ("issue_id", "winning_initiative_id", "losing_initiative_id");
688 CREATE UNIQUE INDEX "battle_winning_null_idx" ON "battle" ("issue_id", "winning_initiative_id") WHERE "losing_initiative_id" ISNULL;
689 CREATE UNIQUE INDEX "battle_null_losing_idx" ON "battle" ("issue_id", "losing_initiative_id") WHERE "winning_initiative_id" ISNULL;
691 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';
694 CREATE TABLE "ignored_initiative" (
695 PRIMARY KEY ("initiative_id", "member_id"),
696 "initiative_id" INT4 REFERENCES "initiative" ("id") ON DELETE CASCADE ON UPDATE CASCADE,
697 "member_id" INT4 REFERENCES "member" ("id") ON DELETE CASCADE ON UPDATE CASCADE );
698 CREATE INDEX "ignored_initiative_member_id_idx" ON "ignored_initiative" ("member_id");
700 COMMENT ON TABLE "ignored_initiative" IS 'Possibility to filter initiatives';
703 CREATE TABLE "initiative_setting" (
704 PRIMARY KEY ("member_id", "key", "initiative_id"),
705 "member_id" INT4 REFERENCES "member" ("id") ON DELETE CASCADE ON UPDATE CASCADE,
706 "key" TEXT NOT NULL,
707 "initiative_id" INT4 REFERENCES "initiative" ("id") ON DELETE CASCADE ON UPDATE CASCADE,
708 "value" TEXT NOT NULL );
710 COMMENT ON TABLE "initiative_setting" IS 'Place for frontend to store initiative specific settings of members as strings';
713 CREATE TABLE "draft" (
714 UNIQUE ("initiative_id", "id"), -- index needed for foreign-key on table "supporter"
715 "initiative_id" INT4 NOT NULL REFERENCES "initiative" ("id") ON DELETE CASCADE ON UPDATE CASCADE,
716 "id" SERIAL8 PRIMARY KEY,
717 "created" TIMESTAMPTZ NOT NULL DEFAULT now(),
718 "author_id" INT4 NOT NULL REFERENCES "member" ("id") ON DELETE RESTRICT ON UPDATE CASCADE,
719 "formatting_engine" TEXT,
720 "content" TEXT NOT NULL,
721 "text_search_data" TSVECTOR );
722 CREATE INDEX "draft_created_idx" ON "draft" ("created");
723 CREATE INDEX "draft_author_id_created_idx" ON "draft" ("author_id", "created");
724 CREATE INDEX "draft_text_search_data_idx" ON "draft" USING gin ("text_search_data");
725 CREATE TRIGGER "update_text_search_data"
726 BEFORE INSERT OR UPDATE ON "draft"
727 FOR EACH ROW EXECUTE PROCEDURE
728 tsvector_update_trigger('text_search_data', 'pg_catalog.simple', "content");
730 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.';
732 COMMENT ON COLUMN "draft"."formatting_engine" IS 'Allows different formatting engines (i.e. wiki formats) to be used';
733 COMMENT ON COLUMN "draft"."content" IS 'Text of the draft in a format depending on the field "formatting_engine"';
736 CREATE TABLE "rendered_draft" (
737 PRIMARY KEY ("draft_id", "format"),
738 "draft_id" INT8 REFERENCES "draft" ("id") ON DELETE CASCADE ON UPDATE CASCADE,
739 "format" TEXT,
740 "content" TEXT NOT NULL );
742 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)';
745 CREATE TABLE "suggestion" (
746 UNIQUE ("initiative_id", "id"), -- index needed for foreign-key on table "opinion"
747 "initiative_id" INT4 NOT NULL REFERENCES "initiative" ("id") ON DELETE CASCADE ON UPDATE CASCADE,
748 "id" SERIAL8 PRIMARY KEY,
749 "draft_id" INT8 NOT NULL,
750 FOREIGN KEY ("initiative_id", "draft_id") REFERENCES "draft" ("initiative_id", "id") ON DELETE NO ACTION ON UPDATE CASCADE,
751 "created" TIMESTAMPTZ NOT NULL DEFAULT now(),
752 "author_id" INT4 NOT NULL REFERENCES "member" ("id") ON DELETE RESTRICT ON UPDATE CASCADE,
753 "name" TEXT NOT NULL,
754 "formatting_engine" TEXT,
755 "content" TEXT NOT NULL DEFAULT '',
756 "text_search_data" TSVECTOR,
757 "minus2_unfulfilled_count" INT4,
758 "minus2_fulfilled_count" INT4,
759 "minus1_unfulfilled_count" INT4,
760 "minus1_fulfilled_count" INT4,
761 "plus1_unfulfilled_count" INT4,
762 "plus1_fulfilled_count" INT4,
763 "plus2_unfulfilled_count" INT4,
764 "plus2_fulfilled_count" INT4 );
765 CREATE INDEX "suggestion_created_idx" ON "suggestion" ("created");
766 CREATE INDEX "suggestion_author_id_created_idx" ON "suggestion" ("author_id", "created");
767 CREATE INDEX "suggestion_text_search_data_idx" ON "suggestion" USING gin ("text_search_data");
768 CREATE TRIGGER "update_text_search_data"
769 BEFORE INSERT OR UPDATE ON "suggestion"
770 FOR EACH ROW EXECUTE PROCEDURE
771 tsvector_update_trigger('text_search_data', 'pg_catalog.simple',
772 "name", "content");
774 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';
776 COMMENT ON COLUMN "suggestion"."draft_id" IS 'Draft, which the author has seen when composing the suggestion; should always be set by a frontend, but defaults to current draft of the initiative (implemented by trigger "default_for_draft_id")';
777 COMMENT ON COLUMN "suggestion"."minus2_unfulfilled_count" IS 'Calculated from table "direct_supporter_snapshot", not requiring informed supporters';
778 COMMENT ON COLUMN "suggestion"."minus2_fulfilled_count" IS 'Calculated from table "direct_supporter_snapshot", not requiring informed supporters';
779 COMMENT ON COLUMN "suggestion"."minus1_unfulfilled_count" IS 'Calculated from table "direct_supporter_snapshot", not requiring informed supporters';
780 COMMENT ON COLUMN "suggestion"."minus1_fulfilled_count" IS 'Calculated from table "direct_supporter_snapshot", not requiring informed supporters';
781 COMMENT ON COLUMN "suggestion"."plus1_unfulfilled_count" IS 'Calculated from table "direct_supporter_snapshot", not requiring informed supporters';
782 COMMENT ON COLUMN "suggestion"."plus1_fulfilled_count" IS 'Calculated from table "direct_supporter_snapshot", not requiring informed supporters';
783 COMMENT ON COLUMN "suggestion"."plus2_unfulfilled_count" IS 'Calculated from table "direct_supporter_snapshot", not requiring informed supporters';
784 COMMENT ON COLUMN "suggestion"."plus2_fulfilled_count" IS 'Calculated from table "direct_supporter_snapshot", not requiring informed supporters';
787 CREATE TABLE "rendered_suggestion" (
788 PRIMARY KEY ("suggestion_id", "format"),
789 "suggestion_id" INT8 REFERENCES "suggestion" ("id") ON DELETE CASCADE ON UPDATE CASCADE,
790 "format" TEXT,
791 "content" TEXT NOT NULL );
793 COMMENT ON TABLE "rendered_suggestion" IS 'This table may be used by frontends to cache "rendered" drafts (e.g. HTML output generated from wiki text)';
796 CREATE TABLE "suggestion_setting" (
797 PRIMARY KEY ("member_id", "key", "suggestion_id"),
798 "member_id" INT4 REFERENCES "member" ("id") ON DELETE CASCADE ON UPDATE CASCADE,
799 "key" TEXT NOT NULL,
800 "suggestion_id" INT8 REFERENCES "suggestion" ("id") ON DELETE CASCADE ON UPDATE CASCADE,
801 "value" TEXT NOT NULL );
803 COMMENT ON TABLE "suggestion_setting" IS 'Place for frontend to store suggestion specific settings of members as strings';
806 CREATE TABLE "privilege" (
807 PRIMARY KEY ("unit_id", "member_id"),
808 "unit_id" INT4 REFERENCES "unit" ("id") ON DELETE CASCADE ON UPDATE CASCADE,
809 "member_id" INT4 REFERENCES "member" ("id") ON DELETE CASCADE ON UPDATE CASCADE,
810 "admin_manager" BOOLEAN NOT NULL DEFAULT FALSE,
811 "unit_manager" BOOLEAN NOT NULL DEFAULT FALSE,
812 "area_manager" BOOLEAN NOT NULL DEFAULT FALSE,
813 "member_manager" BOOLEAN NOT NULL DEFAULT FALSE,
814 "initiative_right" BOOLEAN NOT NULL DEFAULT TRUE,
815 "voting_right" BOOLEAN NOT NULL DEFAULT TRUE,
816 "polling_right" BOOLEAN NOT NULL DEFAULT FALSE );
818 COMMENT ON TABLE "privilege" IS 'Members rights related to each unit';
820 COMMENT ON COLUMN "privilege"."admin_manager" IS 'Grant/revoke any privileges to/from other members';
821 COMMENT ON COLUMN "privilege"."unit_manager" IS 'Create and disable sub units';
822 COMMENT ON COLUMN "privilege"."area_manager" IS 'Create and disable areas and set area parameters';
823 COMMENT ON COLUMN "privilege"."member_manager" IS 'Adding/removing members from the unit, granting or revoking "initiative_right" and "voting_right"';
824 COMMENT ON COLUMN "privilege"."initiative_right" IS 'Right to create an initiative';
825 COMMENT ON COLUMN "privilege"."voting_right" IS 'Right to support initiatives, create and rate suggestions, and to vote';
826 COMMENT ON COLUMN "privilege"."polling_right" IS 'Right to create polls (see "policy"."polling" and "initiative"."polling")';
829 CREATE TABLE "membership" (
830 PRIMARY KEY ("area_id", "member_id"),
831 "area_id" INT4 REFERENCES "area" ("id") ON DELETE CASCADE ON UPDATE CASCADE,
832 "member_id" INT4 REFERENCES "member" ("id") ON DELETE CASCADE ON UPDATE CASCADE );
833 CREATE INDEX "membership_member_id_idx" ON "membership" ("member_id");
835 COMMENT ON TABLE "membership" IS 'Interest of members in topic areas';
838 CREATE TABLE "interest" (
839 PRIMARY KEY ("issue_id", "member_id"),
840 "issue_id" INT4 REFERENCES "issue" ("id") ON DELETE CASCADE ON UPDATE CASCADE,
841 "member_id" INT4 REFERENCES "member" ("id") ON DELETE CASCADE ON UPDATE CASCADE );
842 CREATE INDEX "interest_member_id_idx" ON "interest" ("member_id");
844 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.';
847 CREATE TABLE "initiator" (
848 PRIMARY KEY ("initiative_id", "member_id"),
849 "initiative_id" INT4 REFERENCES "initiative" ("id") ON DELETE CASCADE ON UPDATE CASCADE,
850 "member_id" INT4 REFERENCES "member" ("id") ON DELETE CASCADE ON UPDATE CASCADE,
851 "accepted" BOOLEAN );
852 CREATE INDEX "initiator_member_id_idx" ON "initiator" ("member_id");
854 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.';
856 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.';
859 CREATE TABLE "supporter" (
860 "issue_id" INT4 NOT NULL,
861 PRIMARY KEY ("initiative_id", "member_id"),
862 "initiative_id" INT4,
863 "member_id" INT4,
864 "draft_id" INT8 NOT NULL,
865 FOREIGN KEY ("issue_id", "member_id") REFERENCES "interest" ("issue_id", "member_id") ON DELETE CASCADE ON UPDATE CASCADE,
866 FOREIGN KEY ("initiative_id", "draft_id") REFERENCES "draft" ("initiative_id", "id") ON DELETE NO ACTION ON UPDATE CASCADE );
867 CREATE INDEX "supporter_member_id_idx" ON "supporter" ("member_id");
869 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.';
871 COMMENT ON COLUMN "supporter"."issue_id" IS 'WARNING: No index: For selections use column "initiative_id" and join via table "initiative" where neccessary';
872 COMMENT ON COLUMN "supporter"."draft_id" IS 'Latest seen draft; should always be set by a frontend, but defaults to current draft of the initiative (implemented by trigger "default_for_draft_id")';
875 CREATE TABLE "opinion" (
876 "initiative_id" INT4 NOT NULL,
877 PRIMARY KEY ("suggestion_id", "member_id"),
878 "suggestion_id" INT8,
879 "member_id" INT4,
880 "degree" INT2 NOT NULL CHECK ("degree" >= -2 AND "degree" <= 2 AND "degree" != 0),
881 "fulfilled" BOOLEAN NOT NULL DEFAULT FALSE,
882 FOREIGN KEY ("initiative_id", "suggestion_id") REFERENCES "suggestion" ("initiative_id", "id") ON DELETE CASCADE ON UPDATE CASCADE,
883 FOREIGN KEY ("initiative_id", "member_id") REFERENCES "supporter" ("initiative_id", "member_id") ON DELETE CASCADE ON UPDATE CASCADE );
884 CREATE INDEX "opinion_member_id_initiative_id_idx" ON "opinion" ("member_id", "initiative_id");
886 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.';
888 COMMENT ON COLUMN "opinion"."degree" IS '2 = fulfillment required for support; 1 = fulfillment desired; -1 = fulfillment unwanted; -2 = fulfillment cancels support';
891 CREATE TYPE "delegation_scope" AS ENUM ('unit', 'area', 'issue');
893 COMMENT ON TYPE "delegation_scope" IS 'Scope for delegations: ''unit'', ''area'', or ''issue'' (order is relevant)';
896 CREATE TABLE "delegation" (
897 "id" SERIAL8 PRIMARY KEY,
898 "truster_id" INT4 NOT NULL REFERENCES "member" ("id") ON DELETE CASCADE ON UPDATE CASCADE,
899 "trustee_id" INT4 REFERENCES "member" ("id") ON DELETE CASCADE ON UPDATE CASCADE,
900 "scope" "delegation_scope" NOT NULL,
901 "unit_id" INT4 REFERENCES "unit" ("id") ON DELETE CASCADE ON UPDATE CASCADE,
902 "area_id" INT4 REFERENCES "area" ("id") ON DELETE CASCADE ON UPDATE CASCADE,
903 "issue_id" INT4 REFERENCES "issue" ("id") ON DELETE CASCADE ON UPDATE CASCADE,
904 CONSTRAINT "cant_delegate_to_yourself" CHECK ("truster_id" != "trustee_id"),
905 CONSTRAINT "no_unit_delegation_to_null"
906 CHECK ("trustee_id" NOTNULL OR "scope" != 'unit'),
907 CONSTRAINT "area_id_and_issue_id_set_according_to_scope" CHECK (
908 ("scope" = 'unit' AND "unit_id" NOTNULL AND "area_id" ISNULL AND "issue_id" ISNULL ) OR
909 ("scope" = 'area' AND "unit_id" ISNULL AND "area_id" NOTNULL AND "issue_id" ISNULL ) OR
910 ("scope" = 'issue' AND "unit_id" ISNULL AND "area_id" ISNULL AND "issue_id" NOTNULL) ),
911 UNIQUE ("unit_id", "truster_id"),
912 UNIQUE ("area_id", "truster_id"),
913 UNIQUE ("issue_id", "truster_id") );
914 CREATE INDEX "delegation_truster_id_idx" ON "delegation" ("truster_id");
915 CREATE INDEX "delegation_trustee_id_idx" ON "delegation" ("trustee_id");
917 COMMENT ON TABLE "delegation" IS 'Delegation of vote-weight to other members';
919 COMMENT ON COLUMN "delegation"."unit_id" IS 'Reference to unit, if delegation is unit-wide, otherwise NULL';
920 COMMENT ON COLUMN "delegation"."area_id" IS 'Reference to area, if delegation is area-wide, otherwise NULL';
921 COMMENT ON COLUMN "delegation"."issue_id" IS 'Reference to issue, if delegation is issue-wide, otherwise NULL';
924 CREATE TABLE "direct_population_snapshot" (
925 PRIMARY KEY ("issue_id", "event", "member_id"),
926 "issue_id" INT4 REFERENCES "issue" ("id") ON DELETE CASCADE ON UPDATE CASCADE,
927 "event" "snapshot_event",
928 "member_id" INT4 REFERENCES "member" ("id") ON DELETE RESTRICT ON UPDATE RESTRICT,
929 "weight" INT4 );
930 CREATE INDEX "direct_population_snapshot_member_id_idx" ON "direct_population_snapshot" ("member_id");
932 COMMENT ON TABLE "direct_population_snapshot" IS 'Snapshot of active members having either a "membership" in the "area" or an "interest" in the "issue"';
934 COMMENT ON COLUMN "direct_population_snapshot"."event" IS 'Reason for snapshot, see "snapshot_event" type for details';
935 COMMENT ON COLUMN "direct_population_snapshot"."weight" IS 'Weight of member (1 or higher) according to "delegating_population_snapshot"';
938 CREATE TABLE "delegating_population_snapshot" (
939 PRIMARY KEY ("issue_id", "event", "member_id"),
940 "issue_id" INT4 REFERENCES "issue" ("id") ON DELETE CASCADE ON UPDATE CASCADE,
941 "event" "snapshot_event",
942 "member_id" INT4 REFERENCES "member" ("id") ON DELETE RESTRICT ON UPDATE RESTRICT,
943 "weight" INT4,
944 "scope" "delegation_scope" NOT NULL,
945 "delegate_member_ids" INT4[] NOT NULL );
946 CREATE INDEX "delegating_population_snapshot_member_id_idx" ON "delegating_population_snapshot" ("member_id");
948 COMMENT ON TABLE "direct_population_snapshot" IS 'Delegations increasing the weight of entries in the "direct_population_snapshot" table';
950 COMMENT ON COLUMN "delegating_population_snapshot"."event" IS 'Reason for snapshot, see "snapshot_event" type for details';
951 COMMENT ON COLUMN "delegating_population_snapshot"."member_id" IS 'Delegating member';
952 COMMENT ON COLUMN "delegating_population_snapshot"."weight" IS 'Intermediate weight';
953 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"';
956 CREATE TABLE "direct_interest_snapshot" (
957 PRIMARY KEY ("issue_id", "event", "member_id"),
958 "issue_id" INT4 REFERENCES "issue" ("id") ON DELETE CASCADE ON UPDATE CASCADE,
959 "event" "snapshot_event",
960 "member_id" INT4 REFERENCES "member" ("id") ON DELETE RESTRICT ON UPDATE RESTRICT,
961 "weight" INT4 );
962 CREATE INDEX "direct_interest_snapshot_member_id_idx" ON "direct_interest_snapshot" ("member_id");
964 COMMENT ON TABLE "direct_interest_snapshot" IS 'Snapshot of active members having an "interest" in the "issue"';
966 COMMENT ON COLUMN "direct_interest_snapshot"."event" IS 'Reason for snapshot, see "snapshot_event" type for details';
967 COMMENT ON COLUMN "direct_interest_snapshot"."weight" IS 'Weight of member (1 or higher) according to "delegating_interest_snapshot"';
970 CREATE TABLE "delegating_interest_snapshot" (
971 PRIMARY KEY ("issue_id", "event", "member_id"),
972 "issue_id" INT4 REFERENCES "issue" ("id") ON DELETE CASCADE ON UPDATE CASCADE,
973 "event" "snapshot_event",
974 "member_id" INT4 REFERENCES "member" ("id") ON DELETE RESTRICT ON UPDATE RESTRICT,
975 "weight" INT4,
976 "scope" "delegation_scope" NOT NULL,
977 "delegate_member_ids" INT4[] NOT NULL );
978 CREATE INDEX "delegating_interest_snapshot_member_id_idx" ON "delegating_interest_snapshot" ("member_id");
980 COMMENT ON TABLE "delegating_interest_snapshot" IS 'Delegations increasing the weight of entries in the "direct_interest_snapshot" table';
982 COMMENT ON COLUMN "delegating_interest_snapshot"."event" IS 'Reason for snapshot, see "snapshot_event" type for details';
983 COMMENT ON COLUMN "delegating_interest_snapshot"."member_id" IS 'Delegating member';
984 COMMENT ON COLUMN "delegating_interest_snapshot"."weight" IS 'Intermediate weight';
985 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"';
988 CREATE TABLE "direct_supporter_snapshot" (
989 "issue_id" INT4 NOT NULL,
990 PRIMARY KEY ("initiative_id", "event", "member_id"),
991 "initiative_id" INT4,
992 "event" "snapshot_event",
993 "member_id" INT4 REFERENCES "member" ("id") ON DELETE RESTRICT ON UPDATE RESTRICT,
994 "draft_id" INT8 NOT NULL,
995 "informed" BOOLEAN NOT NULL,
996 "satisfied" BOOLEAN NOT NULL,
997 FOREIGN KEY ("issue_id", "initiative_id") REFERENCES "initiative" ("issue_id", "id") ON DELETE CASCADE ON UPDATE CASCADE,
998 FOREIGN KEY ("initiative_id", "draft_id") REFERENCES "draft" ("initiative_id", "id") ON DELETE NO ACTION ON UPDATE CASCADE,
999 FOREIGN KEY ("issue_id", "event", "member_id") REFERENCES "direct_interest_snapshot" ("issue_id", "event", "member_id") ON DELETE CASCADE ON UPDATE CASCADE );
1000 CREATE INDEX "direct_supporter_snapshot_member_id_idx" ON "direct_supporter_snapshot" ("member_id");
1002 COMMENT ON TABLE "direct_supporter_snapshot" IS 'Snapshot of supporters of initiatives (weight is stored in "direct_interest_snapshot")';
1004 COMMENT ON COLUMN "direct_supporter_snapshot"."issue_id" IS 'WARNING: No index: For selections use column "initiative_id" and join via table "initiative" where neccessary';
1005 COMMENT ON COLUMN "direct_supporter_snapshot"."event" IS 'Reason for snapshot, see "snapshot_event" type for details';
1006 COMMENT ON COLUMN "direct_supporter_snapshot"."informed" IS 'Supporter has seen the latest draft of the initiative';
1007 COMMENT ON COLUMN "direct_supporter_snapshot"."satisfied" IS 'Supporter has no "critical_opinion"s';
1010 CREATE TABLE "non_voter" (
1011 PRIMARY KEY ("issue_id", "member_id"),
1012 "issue_id" INT4 REFERENCES "issue" ("id") ON DELETE CASCADE ON UPDATE CASCADE,
1013 "member_id" INT4 REFERENCES "member" ("id") ON DELETE CASCADE ON UPDATE CASCADE );
1014 CREATE INDEX "non_voter_member_id_idx" ON "non_voter" ("member_id");
1016 COMMENT ON TABLE "non_voter" IS 'Members who decided to not vote directly on an issue';
1019 CREATE TABLE "direct_voter" (
1020 PRIMARY KEY ("issue_id", "member_id"),
1021 "issue_id" INT4 REFERENCES "issue" ("id") ON DELETE CASCADE ON UPDATE CASCADE,
1022 "member_id" INT4 REFERENCES "member" ("id") ON DELETE RESTRICT ON UPDATE RESTRICT,
1023 "weight" INT4 );
1024 CREATE INDEX "direct_voter_member_id_idx" ON "direct_voter" ("member_id");
1026 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.';
1028 COMMENT ON COLUMN "direct_voter"."weight" IS 'Weight of member (1 or higher) according to "delegating_voter" table';
1031 CREATE TABLE "delegating_voter" (
1032 PRIMARY KEY ("issue_id", "member_id"),
1033 "issue_id" INT4 REFERENCES "issue" ("id") ON DELETE CASCADE ON UPDATE CASCADE,
1034 "member_id" INT4 REFERENCES "member" ("id") ON DELETE RESTRICT ON UPDATE RESTRICT,
1035 "weight" INT4,
1036 "scope" "delegation_scope" NOT NULL,
1037 "delegate_member_ids" INT4[] NOT NULL );
1038 CREATE INDEX "delegating_voter_member_id_idx" ON "delegating_voter" ("member_id");
1040 COMMENT ON TABLE "delegating_voter" IS 'Delegations increasing the weight of entries in the "direct_voter" table';
1042 COMMENT ON COLUMN "delegating_voter"."member_id" IS 'Delegating member';
1043 COMMENT ON COLUMN "delegating_voter"."weight" IS 'Intermediate weight';
1044 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"';
1047 CREATE TABLE "vote" (
1048 "issue_id" INT4 NOT NULL,
1049 PRIMARY KEY ("initiative_id", "member_id"),
1050 "initiative_id" INT4,
1051 "member_id" INT4,
1052 "grade" INT4,
1053 FOREIGN KEY ("issue_id", "initiative_id") REFERENCES "initiative" ("issue_id", "id") ON DELETE CASCADE ON UPDATE CASCADE,
1054 FOREIGN KEY ("issue_id", "member_id") REFERENCES "direct_voter" ("issue_id", "member_id") ON DELETE CASCADE ON UPDATE CASCADE );
1055 CREATE INDEX "vote_member_id_idx" ON "vote" ("member_id");
1057 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.';
1059 COMMENT ON COLUMN "vote"."issue_id" IS 'WARNING: No index: For selections use column "initiative_id" and join via table "initiative" where neccessary';
1060 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.';
1063 CREATE TABLE "voting_comment" (
1064 PRIMARY KEY ("issue_id", "member_id"),
1065 "issue_id" INT4 REFERENCES "issue" ("id") ON DELETE CASCADE ON UPDATE CASCADE,
1066 "member_id" INT4 REFERENCES "member" ("id") ON DELETE CASCADE ON UPDATE CASCADE,
1067 "changed" TIMESTAMPTZ,
1068 "formatting_engine" TEXT,
1069 "content" TEXT NOT NULL,
1070 "text_search_data" TSVECTOR );
1071 CREATE INDEX "voting_comment_member_id_idx" ON "voting_comment" ("member_id");
1072 CREATE INDEX "voting_comment_text_search_data_idx" ON "voting_comment" USING gin ("text_search_data");
1073 CREATE TRIGGER "update_text_search_data"
1074 BEFORE INSERT OR UPDATE ON "voting_comment"
1075 FOR EACH ROW EXECUTE PROCEDURE
1076 tsvector_update_trigger('text_search_data', 'pg_catalog.simple', "content");
1078 COMMENT ON TABLE "voting_comment" IS 'Storage for comments of voters to be published after voting has finished.';
1080 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.';
1083 CREATE TABLE "rendered_voting_comment" (
1084 PRIMARY KEY ("issue_id", "member_id", "format"),
1085 FOREIGN KEY ("issue_id", "member_id")
1086 REFERENCES "voting_comment" ("issue_id", "member_id")
1087 ON DELETE CASCADE ON UPDATE CASCADE,
1088 "issue_id" INT4,
1089 "member_id" INT4,
1090 "format" TEXT,
1091 "content" TEXT NOT NULL );
1093 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)';
1096 CREATE TYPE "event_type" AS ENUM (
1097 'issue_state_changed',
1098 'initiative_created_in_new_issue',
1099 'initiative_created_in_existing_issue',
1100 'initiative_revoked',
1101 'new_draft_created',
1102 'suggestion_created');
1104 COMMENT ON TYPE "event_type" IS 'Type used for column "event" of table "event"';
1107 CREATE TABLE "event" (
1108 "id" SERIAL8 PRIMARY KEY,
1109 "occurrence" TIMESTAMPTZ NOT NULL DEFAULT now(),
1110 "event" "event_type" NOT NULL,
1111 "member_id" INT4 REFERENCES "member" ("id") ON DELETE RESTRICT ON UPDATE CASCADE,
1112 "issue_id" INT4 REFERENCES "issue" ("id") ON DELETE CASCADE ON UPDATE CASCADE,
1113 "state" "issue_state" CHECK ("state" != 'calculation'),
1114 "initiative_id" INT4,
1115 "draft_id" INT8,
1116 "suggestion_id" INT8,
1117 FOREIGN KEY ("issue_id", "initiative_id")
1118 REFERENCES "initiative" ("issue_id", "id")
1119 ON DELETE CASCADE ON UPDATE CASCADE,
1120 FOREIGN KEY ("initiative_id", "draft_id")
1121 REFERENCES "draft" ("initiative_id", "id")
1122 ON DELETE CASCADE ON UPDATE CASCADE,
1123 FOREIGN KEY ("initiative_id", "suggestion_id")
1124 REFERENCES "suggestion" ("initiative_id", "id")
1125 ON DELETE CASCADE ON UPDATE CASCADE,
1126 CONSTRAINT "null_constraints_for_issue_state_changed" CHECK (
1127 "event" != 'issue_state_changed' OR (
1128 "member_id" ISNULL AND
1129 "issue_id" NOTNULL AND
1130 "state" NOTNULL AND
1131 "initiative_id" ISNULL AND
1132 "draft_id" ISNULL AND
1133 "suggestion_id" ISNULL )),
1134 CONSTRAINT "null_constraints_for_initiative_creation_or_revocation_or_new_draft" CHECK (
1135 "event" NOT IN (
1136 'initiative_created_in_new_issue',
1137 'initiative_created_in_existing_issue',
1138 'initiative_revoked',
1139 'new_draft_created'
1140 ) OR (
1141 "member_id" NOTNULL AND
1142 "issue_id" NOTNULL AND
1143 "state" NOTNULL AND
1144 "initiative_id" NOTNULL AND
1145 "draft_id" NOTNULL AND
1146 "suggestion_id" ISNULL )),
1147 CONSTRAINT "null_constraints_for_suggestion_creation" CHECK (
1148 "event" != 'suggestion_created' OR (
1149 "member_id" NOTNULL AND
1150 "issue_id" NOTNULL AND
1151 "state" NOTNULL AND
1152 "initiative_id" NOTNULL AND
1153 "draft_id" ISNULL AND
1154 "suggestion_id" NOTNULL )) );
1155 CREATE INDEX "event_occurrence_idx" ON "event" ("occurrence");
1157 COMMENT ON TABLE "event" IS 'Event table, automatically filled by triggers';
1159 COMMENT ON COLUMN "event"."occurrence" IS 'Point in time, when event occurred';
1160 COMMENT ON COLUMN "event"."event" IS 'Type of event (see TYPE "event_type")';
1161 COMMENT ON COLUMN "event"."member_id" IS 'Member who caused the event, if applicable';
1162 COMMENT ON COLUMN "event"."state" IS 'If issue_id is set: state of affected issue; If state changed: new state';
1165 CREATE TABLE "notification_sent" (
1166 "event_id" INT8 NOT NULL );
1167 CREATE UNIQUE INDEX "notification_sent_singleton_idx" ON "notification_sent" ((1));
1169 COMMENT ON TABLE "notification_sent" IS 'This table stores one row with the last event_id, for which notifications have been sent out';
1170 COMMENT ON INDEX "notification_sent_singleton_idx" IS 'This index ensures that "notification_sent" only contains one row maximum.';
1174 ----------------------------------------------
1175 -- Writing of history entries and event log --
1176 ----------------------------------------------
1179 CREATE FUNCTION "write_member_history_trigger"()
1180 RETURNS TRIGGER
1181 LANGUAGE 'plpgsql' VOLATILE AS $$
1182 BEGIN
1183 IF
1184 ( NEW."active" != OLD."active" OR
1185 NEW."name" != OLD."name" ) AND
1186 OLD."activated" NOTNULL
1187 THEN
1188 INSERT INTO "member_history"
1189 ("member_id", "active", "name")
1190 VALUES (NEW."id", OLD."active", OLD."name");
1191 END IF;
1192 RETURN NULL;
1193 END;
1194 $$;
1196 CREATE TRIGGER "write_member_history"
1197 AFTER UPDATE ON "member" FOR EACH ROW EXECUTE PROCEDURE
1198 "write_member_history_trigger"();
1200 COMMENT ON FUNCTION "write_member_history_trigger"() IS 'Implementation of trigger "write_member_history" on table "member"';
1201 COMMENT ON TRIGGER "write_member_history" ON "member" IS 'When changing certain fields of a member, create a history entry in "member_history" table';
1204 CREATE FUNCTION "write_event_issue_state_changed_trigger"()
1205 RETURNS TRIGGER
1206 LANGUAGE 'plpgsql' VOLATILE AS $$
1207 BEGIN
1208 IF NEW."state" != OLD."state" AND NEW."state" != 'calculation' THEN
1209 INSERT INTO "event" ("event", "issue_id", "state")
1210 VALUES ('issue_state_changed', NEW."id", NEW."state");
1211 END IF;
1212 RETURN NULL;
1213 END;
1214 $$;
1216 CREATE TRIGGER "write_event_issue_state_changed"
1217 AFTER UPDATE ON "issue" FOR EACH ROW EXECUTE PROCEDURE
1218 "write_event_issue_state_changed_trigger"();
1220 COMMENT ON FUNCTION "write_event_issue_state_changed_trigger"() IS 'Implementation of trigger "write_event_issue_state_changed" on table "issue"';
1221 COMMENT ON TRIGGER "write_event_issue_state_changed" ON "issue" IS 'Create entry in "event" table on "state" change';
1224 CREATE FUNCTION "write_event_initiative_or_draft_created_trigger"()
1225 RETURNS TRIGGER
1226 LANGUAGE 'plpgsql' VOLATILE AS $$
1227 DECLARE
1228 "initiative_row" "initiative"%ROWTYPE;
1229 "issue_row" "issue"%ROWTYPE;
1230 "event_v" "event_type";
1231 BEGIN
1232 SELECT * INTO "initiative_row" FROM "initiative"
1233 WHERE "id" = NEW."initiative_id";
1234 SELECT * INTO "issue_row" FROM "issue"
1235 WHERE "id" = "initiative_row"."issue_id";
1236 IF EXISTS (
1237 SELECT NULL FROM "draft"
1238 WHERE "initiative_id" = NEW."initiative_id"
1239 AND "id" != NEW."id"
1240 ) THEN
1241 "event_v" := 'new_draft_created';
1242 ELSE
1243 IF EXISTS (
1244 SELECT NULL FROM "initiative"
1245 WHERE "issue_id" = "initiative_row"."issue_id"
1246 AND "id" != "initiative_row"."id"
1247 ) THEN
1248 "event_v" := 'initiative_created_in_existing_issue';
1249 ELSE
1250 "event_v" := 'initiative_created_in_new_issue';
1251 END IF;
1252 END IF;
1253 INSERT INTO "event" (
1254 "event", "member_id",
1255 "issue_id", "state", "initiative_id", "draft_id"
1256 ) VALUES (
1257 "event_v",
1258 NEW."author_id",
1259 "initiative_row"."issue_id",
1260 "issue_row"."state",
1261 "initiative_row"."id",
1262 NEW."id" );
1263 RETURN NULL;
1264 END;
1265 $$;
1267 CREATE TRIGGER "write_event_initiative_or_draft_created"
1268 AFTER INSERT ON "draft" FOR EACH ROW EXECUTE PROCEDURE
1269 "write_event_initiative_or_draft_created_trigger"();
1271 COMMENT ON FUNCTION "write_event_initiative_or_draft_created_trigger"() IS 'Implementation of trigger "write_event_initiative_or_draft_created" on table "issue"';
1272 COMMENT ON TRIGGER "write_event_initiative_or_draft_created" ON "draft" IS 'Create entry in "event" table on draft creation';
1275 CREATE FUNCTION "write_event_initiative_revoked_trigger"()
1276 RETURNS TRIGGER
1277 LANGUAGE 'plpgsql' VOLATILE AS $$
1278 DECLARE
1279 "issue_row" "issue"%ROWTYPE;
1280 "draft_id_v" "draft"."id"%TYPE;
1281 BEGIN
1282 IF OLD."revoked" ISNULL AND NEW."revoked" NOTNULL THEN
1283 SELECT * INTO "issue_row" FROM "issue"
1284 WHERE "id" = NEW."issue_id";
1285 SELECT "id" INTO "draft_id_v" FROM "current_draft"
1286 WHERE "initiative_id" = NEW."id";
1287 INSERT INTO "event" (
1288 "event", "member_id", "issue_id", "state", "initiative_id", "draft_id"
1289 ) VALUES (
1290 'initiative_revoked',
1291 NEW."revoked_by_member_id",
1292 NEW."issue_id",
1293 "issue_row"."state",
1294 NEW."id",
1295 "draft_id_v");
1296 END IF;
1297 RETURN NULL;
1298 END;
1299 $$;
1301 CREATE TRIGGER "write_event_initiative_revoked"
1302 AFTER UPDATE ON "initiative" FOR EACH ROW EXECUTE PROCEDURE
1303 "write_event_initiative_revoked_trigger"();
1305 COMMENT ON FUNCTION "write_event_initiative_revoked_trigger"() IS 'Implementation of trigger "write_event_initiative_revoked" on table "issue"';
1306 COMMENT ON TRIGGER "write_event_initiative_revoked" ON "initiative" IS 'Create entry in "event" table, when an initiative is revoked';
1309 CREATE FUNCTION "write_event_suggestion_created_trigger"()
1310 RETURNS TRIGGER
1311 LANGUAGE 'plpgsql' VOLATILE AS $$
1312 DECLARE
1313 "initiative_row" "initiative"%ROWTYPE;
1314 "issue_row" "issue"%ROWTYPE;
1315 BEGIN
1316 SELECT * INTO "initiative_row" FROM "initiative"
1317 WHERE "id" = NEW."initiative_id";
1318 SELECT * INTO "issue_row" FROM "issue"
1319 WHERE "id" = "initiative_row"."issue_id";
1320 INSERT INTO "event" (
1321 "event", "member_id",
1322 "issue_id", "state", "initiative_id", "suggestion_id"
1323 ) VALUES (
1324 'suggestion_created',
1325 NEW."author_id",
1326 "initiative_row"."issue_id",
1327 "issue_row"."state",
1328 "initiative_row"."id",
1329 NEW."id" );
1330 RETURN NULL;
1331 END;
1332 $$;
1334 CREATE TRIGGER "write_event_suggestion_created"
1335 AFTER INSERT ON "suggestion" FOR EACH ROW EXECUTE PROCEDURE
1336 "write_event_suggestion_created_trigger"();
1338 COMMENT ON FUNCTION "write_event_suggestion_created_trigger"() IS 'Implementation of trigger "write_event_suggestion_created" on table "issue"';
1339 COMMENT ON TRIGGER "write_event_suggestion_created" ON "suggestion" IS 'Create entry in "event" table on suggestion creation';
1343 ----------------------------
1344 -- Additional constraints --
1345 ----------------------------
1348 CREATE FUNCTION "issue_requires_first_initiative_trigger"()
1349 RETURNS TRIGGER
1350 LANGUAGE 'plpgsql' VOLATILE AS $$
1351 BEGIN
1352 IF NOT EXISTS (
1353 SELECT NULL FROM "initiative" WHERE "issue_id" = NEW."id"
1354 ) THEN
1355 --RAISE 'Cannot create issue without an initial initiative.' USING
1356 -- ERRCODE = 'integrity_constraint_violation',
1357 -- HINT = 'Create issue, initiative, and draft within the same transaction.';
1358 RAISE EXCEPTION 'Cannot create issue without an initial initiative.';
1359 END IF;
1360 RETURN NULL;
1361 END;
1362 $$;
1364 CREATE CONSTRAINT TRIGGER "issue_requires_first_initiative"
1365 AFTER INSERT OR UPDATE ON "issue" DEFERRABLE INITIALLY DEFERRED
1366 FOR EACH ROW EXECUTE PROCEDURE
1367 "issue_requires_first_initiative_trigger"();
1369 COMMENT ON FUNCTION "issue_requires_first_initiative_trigger"() IS 'Implementation of trigger "issue_requires_first_initiative" on table "issue"';
1370 COMMENT ON TRIGGER "issue_requires_first_initiative" ON "issue" IS 'Ensure that new issues have at least one initiative';
1373 CREATE FUNCTION "last_initiative_deletes_issue_trigger"()
1374 RETURNS TRIGGER
1375 LANGUAGE 'plpgsql' VOLATILE AS $$
1376 DECLARE
1377 "reference_lost" BOOLEAN;
1378 BEGIN
1379 IF TG_OP = 'DELETE' THEN
1380 "reference_lost" := TRUE;
1381 ELSE
1382 "reference_lost" := NEW."issue_id" != OLD."issue_id";
1383 END IF;
1384 IF
1385 "reference_lost" AND NOT EXISTS (
1386 SELECT NULL FROM "initiative" WHERE "issue_id" = OLD."issue_id"
1388 THEN
1389 DELETE FROM "issue" WHERE "id" = OLD."issue_id";
1390 END IF;
1391 RETURN NULL;
1392 END;
1393 $$;
1395 CREATE CONSTRAINT TRIGGER "last_initiative_deletes_issue"
1396 AFTER UPDATE OR DELETE ON "initiative" DEFERRABLE INITIALLY DEFERRED
1397 FOR EACH ROW EXECUTE PROCEDURE
1398 "last_initiative_deletes_issue_trigger"();
1400 COMMENT ON FUNCTION "last_initiative_deletes_issue_trigger"() IS 'Implementation of trigger "last_initiative_deletes_issue" on table "initiative"';
1401 COMMENT ON TRIGGER "last_initiative_deletes_issue" ON "initiative" IS 'Removing the last initiative of an issue deletes the issue';
1404 CREATE FUNCTION "initiative_requires_first_draft_trigger"()
1405 RETURNS TRIGGER
1406 LANGUAGE 'plpgsql' VOLATILE AS $$
1407 BEGIN
1408 IF NOT EXISTS (
1409 SELECT NULL FROM "draft" WHERE "initiative_id" = NEW."id"
1410 ) THEN
1411 --RAISE 'Cannot create initiative without an initial draft.' USING
1412 -- ERRCODE = 'integrity_constraint_violation',
1413 -- HINT = 'Create issue, initiative and draft within the same transaction.';
1414 RAISE EXCEPTION 'Cannot create initiative without an initial draft.';
1415 END IF;
1416 RETURN NULL;
1417 END;
1418 $$;
1420 CREATE CONSTRAINT TRIGGER "initiative_requires_first_draft"
1421 AFTER INSERT OR UPDATE ON "initiative" DEFERRABLE INITIALLY DEFERRED
1422 FOR EACH ROW EXECUTE PROCEDURE
1423 "initiative_requires_first_draft_trigger"();
1425 COMMENT ON FUNCTION "initiative_requires_first_draft_trigger"() IS 'Implementation of trigger "initiative_requires_first_draft" on table "initiative"';
1426 COMMENT ON TRIGGER "initiative_requires_first_draft" ON "initiative" IS 'Ensure that new initiatives have at least one draft';
1429 CREATE FUNCTION "last_draft_deletes_initiative_trigger"()
1430 RETURNS TRIGGER
1431 LANGUAGE 'plpgsql' VOLATILE AS $$
1432 DECLARE
1433 "reference_lost" BOOLEAN;
1434 BEGIN
1435 IF TG_OP = 'DELETE' THEN
1436 "reference_lost" := TRUE;
1437 ELSE
1438 "reference_lost" := NEW."initiative_id" != OLD."initiative_id";
1439 END IF;
1440 IF
1441 "reference_lost" AND NOT EXISTS (
1442 SELECT NULL FROM "draft" WHERE "initiative_id" = OLD."initiative_id"
1444 THEN
1445 DELETE FROM "initiative" WHERE "id" = OLD."initiative_id";
1446 END IF;
1447 RETURN NULL;
1448 END;
1449 $$;
1451 CREATE CONSTRAINT TRIGGER "last_draft_deletes_initiative"
1452 AFTER UPDATE OR DELETE ON "draft" DEFERRABLE INITIALLY DEFERRED
1453 FOR EACH ROW EXECUTE PROCEDURE
1454 "last_draft_deletes_initiative_trigger"();
1456 COMMENT ON FUNCTION "last_draft_deletes_initiative_trigger"() IS 'Implementation of trigger "last_draft_deletes_initiative" on table "draft"';
1457 COMMENT ON TRIGGER "last_draft_deletes_initiative" ON "draft" IS 'Removing the last draft of an initiative deletes the initiative';
1460 CREATE FUNCTION "suggestion_requires_first_opinion_trigger"()
1461 RETURNS TRIGGER
1462 LANGUAGE 'plpgsql' VOLATILE AS $$
1463 BEGIN
1464 IF NOT EXISTS (
1465 SELECT NULL FROM "opinion" WHERE "suggestion_id" = NEW."id"
1466 ) THEN
1467 RAISE EXCEPTION 'Cannot create a suggestion without an opinion.';
1468 END IF;
1469 RETURN NULL;
1470 END;
1471 $$;
1473 CREATE CONSTRAINT TRIGGER "suggestion_requires_first_opinion"
1474 AFTER INSERT OR UPDATE ON "suggestion" DEFERRABLE INITIALLY DEFERRED
1475 FOR EACH ROW EXECUTE PROCEDURE
1476 "suggestion_requires_first_opinion_trigger"();
1478 COMMENT ON FUNCTION "suggestion_requires_first_opinion_trigger"() IS 'Implementation of trigger "suggestion_requires_first_opinion" on table "suggestion"';
1479 COMMENT ON TRIGGER "suggestion_requires_first_opinion" ON "suggestion" IS 'Ensure that new suggestions have at least one opinion';
1482 CREATE FUNCTION "last_opinion_deletes_suggestion_trigger"()
1483 RETURNS TRIGGER
1484 LANGUAGE 'plpgsql' VOLATILE AS $$
1485 DECLARE
1486 "reference_lost" BOOLEAN;
1487 BEGIN
1488 IF TG_OP = 'DELETE' THEN
1489 "reference_lost" := TRUE;
1490 ELSE
1491 "reference_lost" := NEW."suggestion_id" != OLD."suggestion_id";
1492 END IF;
1493 IF
1494 "reference_lost" AND NOT EXISTS (
1495 SELECT NULL FROM "opinion" WHERE "suggestion_id" = OLD."suggestion_id"
1497 THEN
1498 DELETE FROM "suggestion" WHERE "id" = OLD."suggestion_id";
1499 END IF;
1500 RETURN NULL;
1501 END;
1502 $$;
1504 CREATE CONSTRAINT TRIGGER "last_opinion_deletes_suggestion"
1505 AFTER UPDATE OR DELETE ON "opinion" DEFERRABLE INITIALLY DEFERRED
1506 FOR EACH ROW EXECUTE PROCEDURE
1507 "last_opinion_deletes_suggestion_trigger"();
1509 COMMENT ON FUNCTION "last_opinion_deletes_suggestion_trigger"() IS 'Implementation of trigger "last_opinion_deletes_suggestion" on table "opinion"';
1510 COMMENT ON TRIGGER "last_opinion_deletes_suggestion" ON "opinion" IS 'Removing the last opinion of a suggestion deletes the suggestion';
1514 ---------------------------------------------------------------
1515 -- Ensure that votes are not modified when issues are frozen --
1516 ---------------------------------------------------------------
1518 -- NOTE: Frontends should ensure this anyway, but in case of programming
1519 -- errors the following triggers ensure data integrity.
1522 CREATE FUNCTION "forbid_changes_on_closed_issue_trigger"()
1523 RETURNS TRIGGER
1524 LANGUAGE 'plpgsql' VOLATILE AS $$
1525 DECLARE
1526 "issue_id_v" "issue"."id"%TYPE;
1527 "issue_row" "issue"%ROWTYPE;
1528 BEGIN
1529 IF TG_OP = 'DELETE' THEN
1530 "issue_id_v" := OLD."issue_id";
1531 ELSE
1532 "issue_id_v" := NEW."issue_id";
1533 END IF;
1534 SELECT INTO "issue_row" * FROM "issue"
1535 WHERE "id" = "issue_id_v" FOR SHARE;
1536 IF "issue_row"."closed" NOTNULL THEN
1537 RAISE EXCEPTION 'Tried to modify data belonging to a closed issue.';
1538 END IF;
1539 RETURN NULL;
1540 END;
1541 $$;
1543 CREATE TRIGGER "forbid_changes_on_closed_issue"
1544 AFTER INSERT OR UPDATE OR DELETE ON "direct_voter"
1545 FOR EACH ROW EXECUTE PROCEDURE
1546 "forbid_changes_on_closed_issue_trigger"();
1548 CREATE TRIGGER "forbid_changes_on_closed_issue"
1549 AFTER INSERT OR UPDATE OR DELETE ON "delegating_voter"
1550 FOR EACH ROW EXECUTE PROCEDURE
1551 "forbid_changes_on_closed_issue_trigger"();
1553 CREATE TRIGGER "forbid_changes_on_closed_issue"
1554 AFTER INSERT OR UPDATE OR DELETE ON "vote"
1555 FOR EACH ROW EXECUTE PROCEDURE
1556 "forbid_changes_on_closed_issue_trigger"();
1558 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"';
1559 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';
1560 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';
1561 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';
1565 --------------------------------------------------------------------
1566 -- Auto-retrieval of fields only needed for referential integrity --
1567 --------------------------------------------------------------------
1570 CREATE FUNCTION "autofill_issue_id_trigger"()
1571 RETURNS TRIGGER
1572 LANGUAGE 'plpgsql' VOLATILE AS $$
1573 BEGIN
1574 IF NEW."issue_id" ISNULL THEN
1575 SELECT "issue_id" INTO NEW."issue_id"
1576 FROM "initiative" WHERE "id" = NEW."initiative_id";
1577 END IF;
1578 RETURN NEW;
1579 END;
1580 $$;
1582 CREATE TRIGGER "autofill_issue_id" BEFORE INSERT ON "supporter"
1583 FOR EACH ROW EXECUTE PROCEDURE "autofill_issue_id_trigger"();
1585 CREATE TRIGGER "autofill_issue_id" BEFORE INSERT ON "vote"
1586 FOR EACH ROW EXECUTE PROCEDURE "autofill_issue_id_trigger"();
1588 COMMENT ON FUNCTION "autofill_issue_id_trigger"() IS 'Implementation of triggers "autofill_issue_id" on tables "supporter" and "vote"';
1589 COMMENT ON TRIGGER "autofill_issue_id" ON "supporter" IS 'Set "issue_id" field automatically, if NULL';
1590 COMMENT ON TRIGGER "autofill_issue_id" ON "vote" IS 'Set "issue_id" field automatically, if NULL';
1593 CREATE FUNCTION "autofill_initiative_id_trigger"()
1594 RETURNS TRIGGER
1595 LANGUAGE 'plpgsql' VOLATILE AS $$
1596 BEGIN
1597 IF NEW."initiative_id" ISNULL THEN
1598 SELECT "initiative_id" INTO NEW."initiative_id"
1599 FROM "suggestion" WHERE "id" = NEW."suggestion_id";
1600 END IF;
1601 RETURN NEW;
1602 END;
1603 $$;
1605 CREATE TRIGGER "autofill_initiative_id" BEFORE INSERT ON "opinion"
1606 FOR EACH ROW EXECUTE PROCEDURE "autofill_initiative_id_trigger"();
1608 COMMENT ON FUNCTION "autofill_initiative_id_trigger"() IS 'Implementation of trigger "autofill_initiative_id" on table "opinion"';
1609 COMMENT ON TRIGGER "autofill_initiative_id" ON "opinion" IS 'Set "initiative_id" field automatically, if NULL';
1613 -----------------------------------------------------
1614 -- Automatic calculation of certain default values --
1615 -----------------------------------------------------
1618 CREATE FUNCTION "copy_timings_trigger"()
1619 RETURNS TRIGGER
1620 LANGUAGE 'plpgsql' VOLATILE AS $$
1621 DECLARE
1622 "policy_row" "policy"%ROWTYPE;
1623 BEGIN
1624 SELECT * INTO "policy_row" FROM "policy"
1625 WHERE "id" = NEW."policy_id";
1626 IF NEW."admission_time" ISNULL THEN
1627 NEW."admission_time" := "policy_row"."admission_time";
1628 END IF;
1629 IF NEW."discussion_time" ISNULL THEN
1630 NEW."discussion_time" := "policy_row"."discussion_time";
1631 END IF;
1632 IF NEW."verification_time" ISNULL THEN
1633 NEW."verification_time" := "policy_row"."verification_time";
1634 END IF;
1635 IF NEW."voting_time" ISNULL THEN
1636 NEW."voting_time" := "policy_row"."voting_time";
1637 END IF;
1638 RETURN NEW;
1639 END;
1640 $$;
1642 CREATE TRIGGER "copy_timings" BEFORE INSERT OR UPDATE ON "issue"
1643 FOR EACH ROW EXECUTE PROCEDURE "copy_timings_trigger"();
1645 COMMENT ON FUNCTION "copy_timings_trigger"() IS 'Implementation of trigger "copy_timings" on table "issue"';
1646 COMMENT ON TRIGGER "copy_timings" ON "issue" IS 'If timing fields are NULL, copy values from policy.';
1649 CREATE FUNCTION "default_for_draft_id_trigger"()
1650 RETURNS TRIGGER
1651 LANGUAGE 'plpgsql' VOLATILE AS $$
1652 BEGIN
1653 IF NEW."draft_id" ISNULL THEN
1654 SELECT "id" INTO NEW."draft_id" FROM "current_draft"
1655 WHERE "initiative_id" = NEW."initiative_id";
1656 END IF;
1657 RETURN NEW;
1658 END;
1659 $$;
1661 CREATE TRIGGER "default_for_draft_id" BEFORE INSERT OR UPDATE ON "suggestion"
1662 FOR EACH ROW EXECUTE PROCEDURE "default_for_draft_id_trigger"();
1663 CREATE TRIGGER "default_for_draft_id" BEFORE INSERT OR UPDATE ON "supporter"
1664 FOR EACH ROW EXECUTE PROCEDURE "default_for_draft_id_trigger"();
1666 COMMENT ON FUNCTION "default_for_draft_id_trigger"() IS 'Implementation of trigger "default_for_draft" on tables "supporter" and "suggestion"';
1667 COMMENT ON TRIGGER "default_for_draft_id" ON "suggestion" IS 'If "draft_id" is NULL, then use the current draft of the initiative as default';
1668 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';
1672 ----------------------------------------
1673 -- Automatic creation of dependencies --
1674 ----------------------------------------
1677 CREATE FUNCTION "autocreate_interest_trigger"()
1678 RETURNS TRIGGER
1679 LANGUAGE 'plpgsql' VOLATILE AS $$
1680 BEGIN
1681 IF NOT EXISTS (
1682 SELECT NULL FROM "initiative" JOIN "interest"
1683 ON "initiative"."issue_id" = "interest"."issue_id"
1684 WHERE "initiative"."id" = NEW."initiative_id"
1685 AND "interest"."member_id" = NEW."member_id"
1686 ) THEN
1687 BEGIN
1688 INSERT INTO "interest" ("issue_id", "member_id")
1689 SELECT "issue_id", NEW."member_id"
1690 FROM "initiative" WHERE "id" = NEW."initiative_id";
1691 EXCEPTION WHEN unique_violation THEN END;
1692 END IF;
1693 RETURN NEW;
1694 END;
1695 $$;
1697 CREATE TRIGGER "autocreate_interest" BEFORE INSERT ON "supporter"
1698 FOR EACH ROW EXECUTE PROCEDURE "autocreate_interest_trigger"();
1700 COMMENT ON FUNCTION "autocreate_interest_trigger"() IS 'Implementation of trigger "autocreate_interest" on table "supporter"';
1701 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';
1704 CREATE FUNCTION "autocreate_supporter_trigger"()
1705 RETURNS TRIGGER
1706 LANGUAGE 'plpgsql' VOLATILE AS $$
1707 BEGIN
1708 IF NOT EXISTS (
1709 SELECT NULL FROM "suggestion" JOIN "supporter"
1710 ON "suggestion"."initiative_id" = "supporter"."initiative_id"
1711 WHERE "suggestion"."id" = NEW."suggestion_id"
1712 AND "supporter"."member_id" = NEW."member_id"
1713 ) THEN
1714 BEGIN
1715 INSERT INTO "supporter" ("initiative_id", "member_id")
1716 SELECT "initiative_id", NEW."member_id"
1717 FROM "suggestion" WHERE "id" = NEW."suggestion_id";
1718 EXCEPTION WHEN unique_violation THEN END;
1719 END IF;
1720 RETURN NEW;
1721 END;
1722 $$;
1724 CREATE TRIGGER "autocreate_supporter" BEFORE INSERT ON "opinion"
1725 FOR EACH ROW EXECUTE PROCEDURE "autocreate_supporter_trigger"();
1727 COMMENT ON FUNCTION "autocreate_supporter_trigger"() IS 'Implementation of trigger "autocreate_supporter" on table "opinion"';
1728 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.';
1732 ------------------------------------------
1733 -- Views and helper functions for views --
1734 ------------------------------------------
1737 CREATE VIEW "unit_delegation" AS
1738 SELECT
1739 "unit"."id" AS "unit_id",
1740 "delegation"."id",
1741 "delegation"."truster_id",
1742 "delegation"."trustee_id",
1743 "delegation"."scope"
1744 FROM "unit"
1745 JOIN "delegation"
1746 ON "delegation"."unit_id" = "unit"."id"
1747 JOIN "member"
1748 ON "delegation"."truster_id" = "member"."id"
1749 JOIN "privilege"
1750 ON "delegation"."unit_id" = "privilege"."unit_id"
1751 AND "delegation"."truster_id" = "privilege"."member_id"
1752 WHERE "member"."active" AND "privilege"."voting_right";
1754 COMMENT ON VIEW "unit_delegation" IS 'Unit delegations where trusters are active and have voting right';
1757 CREATE VIEW "area_delegation" AS
1758 SELECT DISTINCT ON ("area"."id", "delegation"."truster_id")
1759 "area"."id" AS "area_id",
1760 "delegation"."id",
1761 "delegation"."truster_id",
1762 "delegation"."trustee_id",
1763 "delegation"."scope"
1764 FROM "area"
1765 JOIN "delegation"
1766 ON "delegation"."unit_id" = "area"."unit_id"
1767 OR "delegation"."area_id" = "area"."id"
1768 JOIN "member"
1769 ON "delegation"."truster_id" = "member"."id"
1770 JOIN "privilege"
1771 ON "area"."unit_id" = "privilege"."unit_id"
1772 AND "delegation"."truster_id" = "privilege"."member_id"
1773 WHERE "member"."active" AND "privilege"."voting_right"
1774 ORDER BY
1775 "area"."id",
1776 "delegation"."truster_id",
1777 "delegation"."scope" DESC;
1779 COMMENT ON VIEW "area_delegation" IS 'Area delegations where trusters are active and have voting right';
1782 CREATE VIEW "issue_delegation" AS
1783 SELECT DISTINCT ON ("issue"."id", "delegation"."truster_id")
1784 "issue"."id" AS "issue_id",
1785 "delegation"."id",
1786 "delegation"."truster_id",
1787 "delegation"."trustee_id",
1788 "delegation"."scope"
1789 FROM "issue"
1790 JOIN "area"
1791 ON "area"."id" = "issue"."area_id"
1792 JOIN "delegation"
1793 ON "delegation"."unit_id" = "area"."unit_id"
1794 OR "delegation"."area_id" = "area"."id"
1795 OR "delegation"."issue_id" = "issue"."id"
1796 JOIN "member"
1797 ON "delegation"."truster_id" = "member"."id"
1798 JOIN "privilege"
1799 ON "area"."unit_id" = "privilege"."unit_id"
1800 AND "delegation"."truster_id" = "privilege"."member_id"
1801 WHERE "member"."active" AND "privilege"."voting_right"
1802 ORDER BY
1803 "issue"."id",
1804 "delegation"."truster_id",
1805 "delegation"."scope" DESC;
1807 COMMENT ON VIEW "issue_delegation" IS 'Issue delegations where trusters are active and have voting right';
1810 CREATE FUNCTION "membership_weight_with_skipping"
1811 ( "area_id_p" "area"."id"%TYPE,
1812 "member_id_p" "member"."id"%TYPE,
1813 "skip_member_ids_p" INT4[] ) -- "member"."id"%TYPE[]
1814 RETURNS INT4
1815 LANGUAGE 'plpgsql' STABLE AS $$
1816 DECLARE
1817 "sum_v" INT4;
1818 "delegation_row" "area_delegation"%ROWTYPE;
1819 BEGIN
1820 "sum_v" := 1;
1821 FOR "delegation_row" IN
1822 SELECT "area_delegation".*
1823 FROM "area_delegation" LEFT JOIN "membership"
1824 ON "membership"."area_id" = "area_id_p"
1825 AND "membership"."member_id" = "area_delegation"."truster_id"
1826 WHERE "area_delegation"."area_id" = "area_id_p"
1827 AND "area_delegation"."trustee_id" = "member_id_p"
1828 AND "membership"."member_id" ISNULL
1829 LOOP
1830 IF NOT
1831 "skip_member_ids_p" @> ARRAY["delegation_row"."truster_id"]
1832 THEN
1833 "sum_v" := "sum_v" + "membership_weight_with_skipping"(
1834 "area_id_p",
1835 "delegation_row"."truster_id",
1836 "skip_member_ids_p" || "delegation_row"."truster_id"
1837 );
1838 END IF;
1839 END LOOP;
1840 RETURN "sum_v";
1841 END;
1842 $$;
1844 COMMENT ON FUNCTION "membership_weight_with_skipping"
1845 ( "area"."id"%TYPE,
1846 "member"."id"%TYPE,
1847 INT4[] )
1848 IS 'Helper function for "membership_weight" function';
1851 CREATE FUNCTION "membership_weight"
1852 ( "area_id_p" "area"."id"%TYPE,
1853 "member_id_p" "member"."id"%TYPE ) -- "member"."id"%TYPE[]
1854 RETURNS INT4
1855 LANGUAGE 'plpgsql' STABLE AS $$
1856 BEGIN
1857 RETURN "membership_weight_with_skipping"(
1858 "area_id_p",
1859 "member_id_p",
1860 ARRAY["member_id_p"]
1861 );
1862 END;
1863 $$;
1865 COMMENT ON FUNCTION "membership_weight"
1866 ( "area"."id"%TYPE,
1867 "member"."id"%TYPE )
1868 IS 'Calculates the potential voting weight of a member in a given area';
1871 CREATE VIEW "member_count_view" AS
1872 SELECT count(1) AS "total_count" FROM "member" WHERE "active";
1874 COMMENT ON VIEW "member_count_view" IS 'View used to update "member_count" table';
1877 CREATE VIEW "unit_member_count" AS
1878 SELECT
1879 "unit"."id" AS "unit_id",
1880 count("member"."id") AS "member_count"
1881 FROM "unit"
1882 LEFT JOIN "privilege"
1883 ON "privilege"."unit_id" = "unit"."id"
1884 AND "privilege"."voting_right"
1885 LEFT JOIN "member"
1886 ON "member"."id" = "privilege"."member_id"
1887 AND "member"."active"
1888 GROUP BY "unit"."id";
1890 COMMENT ON VIEW "unit_member_count" IS 'View used to update "member_count" column of "unit" table';
1893 CREATE VIEW "area_member_count" AS
1894 SELECT
1895 "area"."id" AS "area_id",
1896 count("member"."id") AS "direct_member_count",
1897 coalesce(
1898 sum(
1899 CASE WHEN "member"."id" NOTNULL THEN
1900 "membership_weight"("area"."id", "member"."id")
1901 ELSE 0 END
1903 ) AS "member_weight"
1904 FROM "area"
1905 LEFT JOIN "membership"
1906 ON "area"."id" = "membership"."area_id"
1907 LEFT JOIN "privilege"
1908 ON "privilege"."unit_id" = "area"."unit_id"
1909 AND "privilege"."member_id" = "membership"."member_id"
1910 AND "privilege"."voting_right"
1911 LEFT JOIN "member"
1912 ON "member"."id" = "privilege"."member_id" -- NOTE: no membership here!
1913 AND "member"."active"
1914 GROUP BY "area"."id";
1916 COMMENT ON VIEW "area_member_count" IS 'View used to update "direct_member_count" and "member_weight" columns of table "area"';
1919 CREATE VIEW "opening_draft" AS
1920 SELECT "draft".* FROM (
1921 SELECT
1922 "initiative"."id" AS "initiative_id",
1923 min("draft"."id") AS "draft_id"
1924 FROM "initiative" JOIN "draft"
1925 ON "initiative"."id" = "draft"."initiative_id"
1926 GROUP BY "initiative"."id"
1927 ) AS "subquery"
1928 JOIN "draft" ON "subquery"."draft_id" = "draft"."id";
1930 COMMENT ON VIEW "opening_draft" IS 'First drafts of all initiatives';
1933 CREATE VIEW "current_draft" AS
1934 SELECT "draft".* FROM (
1935 SELECT
1936 "initiative"."id" AS "initiative_id",
1937 max("draft"."id") AS "draft_id"
1938 FROM "initiative" JOIN "draft"
1939 ON "initiative"."id" = "draft"."initiative_id"
1940 GROUP BY "initiative"."id"
1941 ) AS "subquery"
1942 JOIN "draft" ON "subquery"."draft_id" = "draft"."id";
1944 COMMENT ON VIEW "current_draft" IS 'All latest drafts for each initiative';
1947 CREATE VIEW "critical_opinion" AS
1948 SELECT * FROM "opinion"
1949 WHERE ("degree" = 2 AND "fulfilled" = FALSE)
1950 OR ("degree" = -2 AND "fulfilled" = TRUE);
1952 COMMENT ON VIEW "critical_opinion" IS 'Opinions currently causing dissatisfaction';
1955 CREATE VIEW "battle_participant" AS
1956 SELECT "initiative"."id", "initiative"."issue_id"
1957 FROM "issue" JOIN "initiative"
1958 ON "issue"."id" = "initiative"."issue_id"
1959 WHERE "initiative"."admitted"
1960 UNION ALL
1961 SELECT NULL, "id" AS "issue_id"
1962 FROM "issue";
1964 COMMENT ON VIEW "battle_participant" IS 'Helper view for "battle_view" containing admitted initiatives plus virtual "status-quo" initiative denoted by NULL reference';
1967 CREATE VIEW "battle_view" AS
1968 SELECT
1969 "issue"."id" AS "issue_id",
1970 "winning_initiative"."id" AS "winning_initiative_id",
1971 "losing_initiative"."id" AS "losing_initiative_id",
1972 sum(
1973 CASE WHEN
1974 coalesce("better_vote"."grade", 0) >
1975 coalesce("worse_vote"."grade", 0)
1976 THEN "direct_voter"."weight" ELSE 0 END
1977 ) AS "count"
1978 FROM "issue"
1979 LEFT JOIN "direct_voter"
1980 ON "issue"."id" = "direct_voter"."issue_id"
1981 JOIN "battle_participant" AS "winning_initiative"
1982 ON "issue"."id" = "winning_initiative"."issue_id"
1983 JOIN "battle_participant" AS "losing_initiative"
1984 ON "issue"."id" = "losing_initiative"."issue_id"
1985 LEFT JOIN "vote" AS "better_vote"
1986 ON "direct_voter"."member_id" = "better_vote"."member_id"
1987 AND "winning_initiative"."id" = "better_vote"."initiative_id"
1988 LEFT JOIN "vote" AS "worse_vote"
1989 ON "direct_voter"."member_id" = "worse_vote"."member_id"
1990 AND "losing_initiative"."id" = "worse_vote"."initiative_id"
1991 WHERE "issue"."closed" NOTNULL
1992 AND "issue"."cleaned" ISNULL
1993 AND (
1994 "winning_initiative"."id" != "losing_initiative"."id" OR
1995 ( ("winning_initiative"."id" NOTNULL AND "losing_initiative"."id" ISNULL) OR
1996 ("winning_initiative"."id" ISNULL AND "losing_initiative"."id" NOTNULL) ) )
1997 GROUP BY
1998 "issue"."id",
1999 "winning_initiative"."id",
2000 "losing_initiative"."id";
2002 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';
2005 CREATE VIEW "expired_session" AS
2006 SELECT * FROM "session" WHERE now() > "expiry";
2008 CREATE RULE "delete" AS ON DELETE TO "expired_session" DO INSTEAD
2009 DELETE FROM "session" WHERE "ident" = OLD."ident";
2011 COMMENT ON VIEW "expired_session" IS 'View containing all expired sessions where DELETE is possible';
2012 COMMENT ON RULE "delete" ON "expired_session" IS 'Rule allowing DELETE on rows in "expired_session" view, i.e. DELETE FROM "expired_session"';
2015 CREATE VIEW "open_issue" AS
2016 SELECT * FROM "issue" WHERE "closed" ISNULL;
2018 COMMENT ON VIEW "open_issue" IS 'All open issues';
2021 CREATE VIEW "issue_with_ranks_missing" AS
2022 SELECT * FROM "issue"
2023 WHERE "fully_frozen" NOTNULL
2024 AND "closed" NOTNULL
2025 AND "ranks_available" = FALSE;
2027 COMMENT ON VIEW "issue_with_ranks_missing" IS 'Issues where voting was finished, but no ranks have been calculated yet';
2030 CREATE VIEW "member_contingent" AS
2031 SELECT
2032 "member"."id" AS "member_id",
2033 "contingent"."time_frame",
2034 CASE WHEN "contingent"."text_entry_limit" NOTNULL THEN
2036 SELECT count(1) FROM "draft"
2037 WHERE "draft"."author_id" = "member"."id"
2038 AND "draft"."created" > now() - "contingent"."time_frame"
2039 ) + (
2040 SELECT count(1) FROM "suggestion"
2041 WHERE "suggestion"."author_id" = "member"."id"
2042 AND "suggestion"."created" > now() - "contingent"."time_frame"
2044 ELSE NULL END AS "text_entry_count",
2045 "contingent"."text_entry_limit",
2046 CASE WHEN "contingent"."initiative_limit" NOTNULL THEN (
2047 SELECT count(1) FROM "opening_draft"
2048 WHERE "opening_draft"."author_id" = "member"."id"
2049 AND "opening_draft"."created" > now() - "contingent"."time_frame"
2050 ) ELSE NULL END AS "initiative_count",
2051 "contingent"."initiative_limit"
2052 FROM "member" CROSS JOIN "contingent";
2054 COMMENT ON VIEW "member_contingent" IS 'Actual counts of text entries and initiatives are calculated per member for each limit in the "contingent" table.';
2056 COMMENT ON COLUMN "member_contingent"."text_entry_count" IS 'Only calculated when "text_entry_limit" is not null in the same row';
2057 COMMENT ON COLUMN "member_contingent"."initiative_count" IS 'Only calculated when "initiative_limit" is not null in the same row';
2060 CREATE VIEW "member_contingent_left" AS
2061 SELECT
2062 "member_id",
2063 max("text_entry_limit" - "text_entry_count") AS "text_entries_left",
2064 max("initiative_limit" - "initiative_count") AS "initiatives_left"
2065 FROM "member_contingent" GROUP BY "member_id";
2067 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.';
2070 CREATE VIEW "event_seen_by_member" AS
2071 SELECT
2072 "member"."id" AS "seen_by_member_id",
2073 CASE WHEN "event"."state" IN (
2074 'voting',
2075 'finished_without_winner',
2076 'finished_with_winner'
2077 ) THEN
2078 'voting'::"notify_level"
2079 ELSE
2080 CASE WHEN "event"."state" IN (
2081 'verification',
2082 'canceled_after_revocation_during_verification',
2083 'canceled_no_initiative_admitted'
2084 ) THEN
2085 'verification'::"notify_level"
2086 ELSE
2087 CASE WHEN "event"."state" IN (
2088 'discussion',
2089 'canceled_after_revocation_during_discussion'
2090 ) THEN
2091 'discussion'::"notify_level"
2092 ELSE
2093 'all'::"notify_level"
2094 END
2095 END
2096 END AS "notify_level",
2097 "event".*
2098 FROM "member" CROSS JOIN "event"
2099 LEFT JOIN "issue"
2100 ON "event"."issue_id" = "issue"."id"
2101 LEFT JOIN "membership"
2102 ON "member"."id" = "membership"."member_id"
2103 AND "issue"."area_id" = "membership"."area_id"
2104 LEFT JOIN "interest"
2105 ON "member"."id" = "interest"."member_id"
2106 AND "event"."issue_id" = "interest"."issue_id"
2107 LEFT JOIN "supporter"
2108 ON "member"."id" = "supporter"."member_id"
2109 AND "event"."initiative_id" = "supporter"."initiative_id"
2110 LEFT JOIN "ignored_member"
2111 ON "member"."id" = "ignored_member"."member_id"
2112 AND "event"."member_id" = "ignored_member"."other_member_id"
2113 LEFT JOIN "ignored_initiative"
2114 ON "member"."id" = "ignored_initiative"."member_id"
2115 AND "event"."initiative_id" = "ignored_initiative"."initiative_id"
2116 WHERE (
2117 "supporter"."member_id" NOTNULL OR
2118 "interest"."member_id" NOTNULL OR
2119 ( "membership"."member_id" NOTNULL AND
2120 "event"."event" IN (
2121 'issue_state_changed',
2122 'initiative_created_in_new_issue',
2123 'initiative_created_in_existing_issue',
2124 'initiative_revoked' ) ) )
2125 AND "ignored_member"."member_id" ISNULL
2126 AND "ignored_initiative"."member_id" ISNULL;
2128 COMMENT ON VIEW "event_seen_by_member" IS 'Events as seen by a member, depending on its memberships, interests and support, but ignoring members "notify_level"';
2131 CREATE VIEW "selected_event_seen_by_member" AS
2132 SELECT
2133 "member"."id" AS "seen_by_member_id",
2134 CASE WHEN "event"."state" IN (
2135 'voting',
2136 'finished_without_winner',
2137 'finished_with_winner'
2138 ) THEN
2139 'voting'::"notify_level"
2140 ELSE
2141 CASE WHEN "event"."state" IN (
2142 'verification',
2143 'canceled_after_revocation_during_verification',
2144 'canceled_no_initiative_admitted'
2145 ) THEN
2146 'verification'::"notify_level"
2147 ELSE
2148 CASE WHEN "event"."state" IN (
2149 'discussion',
2150 'canceled_after_revocation_during_discussion'
2151 ) THEN
2152 'discussion'::"notify_level"
2153 ELSE
2154 'all'::"notify_level"
2155 END
2156 END
2157 END AS "notify_level",
2158 "event".*
2159 FROM "member" CROSS JOIN "event"
2160 LEFT JOIN "issue"
2161 ON "event"."issue_id" = "issue"."id"
2162 LEFT JOIN "membership"
2163 ON "member"."id" = "membership"."member_id"
2164 AND "issue"."area_id" = "membership"."area_id"
2165 LEFT JOIN "interest"
2166 ON "member"."id" = "interest"."member_id"
2167 AND "event"."issue_id" = "interest"."issue_id"
2168 LEFT JOIN "supporter"
2169 ON "member"."id" = "supporter"."member_id"
2170 AND "event"."initiative_id" = "supporter"."initiative_id"
2171 LEFT JOIN "ignored_member"
2172 ON "member"."id" = "ignored_member"."member_id"
2173 AND "event"."member_id" = "ignored_member"."other_member_id"
2174 LEFT JOIN "ignored_initiative"
2175 ON "member"."id" = "ignored_initiative"."member_id"
2176 AND "event"."initiative_id" = "ignored_initiative"."initiative_id"
2177 WHERE (
2178 ( "member"."notify_level" >= 'all' ) OR
2179 ( "member"."notify_level" >= 'voting' AND
2180 "event"."state" IN (
2181 'voting',
2182 'finished_without_winner',
2183 'finished_with_winner' ) ) OR
2184 ( "member"."notify_level" >= 'verification' AND
2185 "event"."state" IN (
2186 'verification',
2187 'canceled_after_revocation_during_verification',
2188 'canceled_no_initiative_admitted' ) ) OR
2189 ( "member"."notify_level" >= 'discussion' AND
2190 "event"."state" IN (
2191 'discussion',
2192 'canceled_after_revocation_during_discussion' ) ) )
2193 AND (
2194 "supporter"."member_id" NOTNULL OR
2195 "interest"."member_id" NOTNULL OR
2196 ( "membership"."member_id" NOTNULL AND
2197 "event"."event" IN (
2198 'issue_state_changed',
2199 'initiative_created_in_new_issue',
2200 'initiative_created_in_existing_issue',
2201 'initiative_revoked' ) ) )
2202 AND "ignored_member"."member_id" ISNULL
2203 AND "ignored_initiative"."member_id" ISNULL;
2205 COMMENT ON VIEW "selected_event_seen_by_member" IS 'Events as seen by a member, depending on its memberships, interests, support and members "notify_level"';
2208 CREATE TYPE "timeline_event" AS ENUM (
2209 'issue_created',
2210 'issue_canceled',
2211 'issue_accepted',
2212 'issue_half_frozen',
2213 'issue_finished_without_voting',
2214 'issue_voting_started',
2215 'issue_finished_after_voting',
2216 'initiative_created',
2217 'initiative_revoked',
2218 'draft_created',
2219 'suggestion_created');
2221 COMMENT ON TYPE "timeline_event" IS 'Types of event in timeline tables (DEPRECATED)';
2224 CREATE VIEW "timeline_issue" AS
2225 SELECT
2226 "created" AS "occurrence",
2227 'issue_created'::"timeline_event" AS "event",
2228 "id" AS "issue_id"
2229 FROM "issue"
2230 UNION ALL
2231 SELECT
2232 "closed" AS "occurrence",
2233 'issue_canceled'::"timeline_event" AS "event",
2234 "id" AS "issue_id"
2235 FROM "issue" WHERE "closed" NOTNULL AND "fully_frozen" ISNULL
2236 UNION ALL
2237 SELECT
2238 "accepted" AS "occurrence",
2239 'issue_accepted'::"timeline_event" AS "event",
2240 "id" AS "issue_id"
2241 FROM "issue" WHERE "accepted" NOTNULL
2242 UNION ALL
2243 SELECT
2244 "half_frozen" AS "occurrence",
2245 'issue_half_frozen'::"timeline_event" AS "event",
2246 "id" AS "issue_id"
2247 FROM "issue" WHERE "half_frozen" NOTNULL
2248 UNION ALL
2249 SELECT
2250 "fully_frozen" AS "occurrence",
2251 'issue_voting_started'::"timeline_event" AS "event",
2252 "id" AS "issue_id"
2253 FROM "issue"
2254 WHERE "fully_frozen" NOTNULL
2255 AND ("closed" ISNULL OR "closed" != "fully_frozen")
2256 UNION ALL
2257 SELECT
2258 "closed" AS "occurrence",
2259 CASE WHEN "fully_frozen" = "closed" THEN
2260 'issue_finished_without_voting'::"timeline_event"
2261 ELSE
2262 'issue_finished_after_voting'::"timeline_event"
2263 END AS "event",
2264 "id" AS "issue_id"
2265 FROM "issue" WHERE "closed" NOTNULL AND "fully_frozen" NOTNULL;
2267 COMMENT ON VIEW "timeline_issue" IS 'Helper view for "timeline" view (DEPRECATED)';
2270 CREATE VIEW "timeline_initiative" AS
2271 SELECT
2272 "created" AS "occurrence",
2273 'initiative_created'::"timeline_event" AS "event",
2274 "id" AS "initiative_id"
2275 FROM "initiative"
2276 UNION ALL
2277 SELECT
2278 "revoked" AS "occurrence",
2279 'initiative_revoked'::"timeline_event" AS "event",
2280 "id" AS "initiative_id"
2281 FROM "initiative" WHERE "revoked" NOTNULL;
2283 COMMENT ON VIEW "timeline_initiative" IS 'Helper view for "timeline" view (DEPRECATED)';
2286 CREATE VIEW "timeline_draft" AS
2287 SELECT
2288 "created" AS "occurrence",
2289 'draft_created'::"timeline_event" AS "event",
2290 "id" AS "draft_id"
2291 FROM "draft";
2293 COMMENT ON VIEW "timeline_draft" IS 'Helper view for "timeline" view (DEPRECATED)';
2296 CREATE VIEW "timeline_suggestion" AS
2297 SELECT
2298 "created" AS "occurrence",
2299 'suggestion_created'::"timeline_event" AS "event",
2300 "id" AS "suggestion_id"
2301 FROM "suggestion";
2303 COMMENT ON VIEW "timeline_suggestion" IS 'Helper view for "timeline" view (DEPRECATED)';
2306 CREATE VIEW "timeline" AS
2307 SELECT
2308 "occurrence",
2309 "event",
2310 "issue_id",
2311 NULL AS "initiative_id",
2312 NULL::INT8 AS "draft_id", -- TODO: Why do we need a type-cast here? Is this due to 32 bit architecture?
2313 NULL::INT8 AS "suggestion_id"
2314 FROM "timeline_issue"
2315 UNION ALL
2316 SELECT
2317 "occurrence",
2318 "event",
2319 NULL AS "issue_id",
2320 "initiative_id",
2321 NULL AS "draft_id",
2322 NULL AS "suggestion_id"
2323 FROM "timeline_initiative"
2324 UNION ALL
2325 SELECT
2326 "occurrence",
2327 "event",
2328 NULL AS "issue_id",
2329 NULL AS "initiative_id",
2330 "draft_id",
2331 NULL AS "suggestion_id"
2332 FROM "timeline_draft"
2333 UNION ALL
2334 SELECT
2335 "occurrence",
2336 "event",
2337 NULL AS "issue_id",
2338 NULL AS "initiative_id",
2339 NULL AS "draft_id",
2340 "suggestion_id"
2341 FROM "timeline_suggestion";
2343 COMMENT ON VIEW "timeline" IS 'Aggregation of different events in the system (DEPRECATED)';
2347 ------------------------------------------------------
2348 -- Row set returning function for delegation chains --
2349 ------------------------------------------------------
2352 CREATE TYPE "delegation_chain_loop_tag" AS ENUM
2353 ('first', 'intermediate', 'last', 'repetition');
2355 COMMENT ON TYPE "delegation_chain_loop_tag" IS 'Type for loop tags in "delegation_chain_row" type';
2358 CREATE TYPE "delegation_chain_row" AS (
2359 "index" INT4,
2360 "member_id" INT4,
2361 "member_valid" BOOLEAN,
2362 "participation" BOOLEAN,
2363 "overridden" BOOLEAN,
2364 "scope_in" "delegation_scope",
2365 "scope_out" "delegation_scope",
2366 "disabled_out" BOOLEAN,
2367 "loop" "delegation_chain_loop_tag" );
2369 COMMENT ON TYPE "delegation_chain_row" IS 'Type of rows returned by "delegation_chain" function';
2371 COMMENT ON COLUMN "delegation_chain_row"."index" IS 'Index starting with 0 and counting up';
2372 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';
2373 COMMENT ON COLUMN "delegation_chain_row"."overridden" IS 'True, if an entry with lower index has "participation" set to true';
2374 COMMENT ON COLUMN "delegation_chain_row"."scope_in" IS 'Scope of used incoming delegation';
2375 COMMENT ON COLUMN "delegation_chain_row"."scope_out" IS 'Scope of used outgoing delegation';
2376 COMMENT ON COLUMN "delegation_chain_row"."disabled_out" IS 'Outgoing delegation is explicitly disabled by a delegation with trustee_id set to NULL';
2377 COMMENT ON COLUMN "delegation_chain_row"."loop" IS 'Not null, if member is part of a loop, see "delegation_chain_loop_tag" type';
2380 CREATE FUNCTION "delegation_chain_for_closed_issue"
2381 ( "member_id_p" "member"."id"%TYPE,
2382 "issue_id_p" "issue"."id"%TYPE )
2383 RETURNS SETOF "delegation_chain_row"
2384 LANGUAGE 'plpgsql' STABLE AS $$
2385 DECLARE
2386 "output_row" "delegation_chain_row";
2387 "direct_voter_row" "direct_voter"%ROWTYPE;
2388 "delegating_voter_row" "delegating_voter"%ROWTYPE;
2389 BEGIN
2390 "output_row"."index" := 0;
2391 "output_row"."member_id" := "member_id_p";
2392 "output_row"."member_valid" := TRUE;
2393 "output_row"."participation" := FALSE;
2394 "output_row"."overridden" := FALSE;
2395 "output_row"."disabled_out" := FALSE;
2396 LOOP
2397 SELECT INTO "direct_voter_row" * FROM "direct_voter"
2398 WHERE "issue_id" = "issue_id_p"
2399 AND "member_id" = "output_row"."member_id";
2400 IF "direct_voter_row"."member_id" NOTNULL THEN
2401 "output_row"."participation" := TRUE;
2402 "output_row"."scope_out" := NULL;
2403 "output_row"."disabled_out" := NULL;
2404 RETURN NEXT "output_row";
2405 RETURN;
2406 END IF;
2407 SELECT INTO "delegating_voter_row" * FROM "delegating_voter"
2408 WHERE "issue_id" = "issue_id_p"
2409 AND "member_id" = "output_row"."member_id";
2410 IF "delegating_voter_row"."member_id" ISNULL THEN
2411 RETURN;
2412 END IF;
2413 "output_row"."scope_out" := "delegating_voter_row"."scope";
2414 RETURN NEXT "output_row";
2415 "output_row"."member_id" := "delegating_voter_row"."delegate_member_ids"[1];
2416 "output_row"."scope_in" := "output_row"."scope_out";
2417 END LOOP;
2418 END;
2419 $$;
2421 COMMENT ON FUNCTION "delegation_chain_for_closed_issue"
2422 ( "member"."id"%TYPE,
2423 "member"."id"%TYPE )
2424 IS 'Helper function for "delegation_chain" function, handling the special case of closed issues after voting';
2427 CREATE FUNCTION "delegation_chain"
2428 ( "member_id_p" "member"."id"%TYPE,
2429 "unit_id_p" "unit"."id"%TYPE,
2430 "area_id_p" "area"."id"%TYPE,
2431 "issue_id_p" "issue"."id"%TYPE,
2432 "simulate_trustee_id_p" "member"."id"%TYPE DEFAULT NULL,
2433 "simulate_default_p" BOOLEAN DEFAULT FALSE )
2434 RETURNS SETOF "delegation_chain_row"
2435 LANGUAGE 'plpgsql' STABLE AS $$
2436 DECLARE
2437 "scope_v" "delegation_scope";
2438 "unit_id_v" "unit"."id"%TYPE;
2439 "area_id_v" "area"."id"%TYPE;
2440 "issue_row" "issue"%ROWTYPE;
2441 "visited_member_ids" INT4[]; -- "member"."id"%TYPE[]
2442 "loop_member_id_v" "member"."id"%TYPE;
2443 "output_row" "delegation_chain_row";
2444 "output_rows" "delegation_chain_row"[];
2445 "simulate_v" BOOLEAN;
2446 "simulate_here_v" BOOLEAN;
2447 "delegation_row" "delegation"%ROWTYPE;
2448 "row_count" INT4;
2449 "i" INT4;
2450 "loop_v" BOOLEAN;
2451 BEGIN
2452 IF "simulate_trustee_id_p" NOTNULL AND "simulate_default_p" THEN
2453 RAISE EXCEPTION 'Both "simulate_trustee_id_p" is set, and "simulate_default_p" is true';
2454 END IF;
2455 IF "simulate_trustee_id_p" NOTNULL OR "simulate_default_p" THEN
2456 "simulate_v" := TRUE;
2457 ELSE
2458 "simulate_v" := FALSE;
2459 END IF;
2460 IF
2461 "unit_id_p" NOTNULL AND
2462 "area_id_p" ISNULL AND
2463 "issue_id_p" ISNULL
2464 THEN
2465 "scope_v" := 'unit';
2466 "unit_id_v" := "unit_id_p";
2467 ELSIF
2468 "unit_id_p" ISNULL AND
2469 "area_id_p" NOTNULL AND
2470 "issue_id_p" ISNULL
2471 THEN
2472 "scope_v" := 'area';
2473 "area_id_v" := "area_id_p";
2474 SELECT "unit_id" INTO "unit_id_v"
2475 FROM "area" WHERE "id" = "area_id_v";
2476 ELSIF
2477 "unit_id_p" ISNULL AND
2478 "area_id_p" ISNULL AND
2479 "issue_id_p" NOTNULL
2480 THEN
2481 SELECT INTO "issue_row" * FROM "issue" WHERE "id" = "issue_id_p";
2482 IF "issue_row"."id" ISNULL THEN
2483 RETURN;
2484 END IF;
2485 IF "issue_row"."closed" NOTNULL THEN
2486 IF "simulate_v" THEN
2487 RAISE EXCEPTION 'Tried to simulate delegation chain for closed issue.';
2488 END IF;
2489 FOR "output_row" IN
2490 SELECT * FROM
2491 "delegation_chain_for_closed_issue"("member_id_p", "issue_id_p")
2492 LOOP
2493 RETURN NEXT "output_row";
2494 END LOOP;
2495 RETURN;
2496 END IF;
2497 "scope_v" := 'issue';
2498 SELECT "area_id" INTO "area_id_v"
2499 FROM "issue" WHERE "id" = "issue_id_p";
2500 SELECT "unit_id" INTO "unit_id_v"
2501 FROM "area" WHERE "id" = "area_id_v";
2502 ELSE
2503 RAISE EXCEPTION 'Exactly one of unit_id_p, area_id_p, or issue_id_p must be NOTNULL.';
2504 END IF;
2505 "visited_member_ids" := '{}';
2506 "loop_member_id_v" := NULL;
2507 "output_rows" := '{}';
2508 "output_row"."index" := 0;
2509 "output_row"."member_id" := "member_id_p";
2510 "output_row"."member_valid" := TRUE;
2511 "output_row"."participation" := FALSE;
2512 "output_row"."overridden" := FALSE;
2513 "output_row"."disabled_out" := FALSE;
2514 "output_row"."scope_out" := NULL;
2515 LOOP
2516 IF "visited_member_ids" @> ARRAY["output_row"."member_id"] THEN
2517 "loop_member_id_v" := "output_row"."member_id";
2518 ELSE
2519 "visited_member_ids" :=
2520 "visited_member_ids" || "output_row"."member_id";
2521 END IF;
2522 IF "output_row"."participation" ISNULL THEN
2523 "output_row"."overridden" := NULL;
2524 ELSIF "output_row"."participation" THEN
2525 "output_row"."overridden" := TRUE;
2526 END IF;
2527 "output_row"."scope_in" := "output_row"."scope_out";
2528 "output_row"."member_valid" := EXISTS (
2529 SELECT NULL FROM "member" JOIN "privilege"
2530 ON "privilege"."member_id" = "member"."id"
2531 AND "privilege"."unit_id" = "unit_id_v"
2532 WHERE "id" = "output_row"."member_id"
2533 AND "member"."active" AND "privilege"."voting_right"
2534 );
2535 "simulate_here_v" := (
2536 "simulate_v" AND
2537 "output_row"."member_id" = "member_id_p"
2538 );
2539 "delegation_row" := ROW(NULL);
2540 IF "output_row"."member_valid" OR "simulate_here_v" THEN
2541 IF "scope_v" = 'unit' THEN
2542 IF NOT "simulate_here_v" THEN
2543 SELECT * INTO "delegation_row" FROM "delegation"
2544 WHERE "truster_id" = "output_row"."member_id"
2545 AND "unit_id" = "unit_id_v";
2546 END IF;
2547 ELSIF "scope_v" = 'area' THEN
2548 "output_row"."participation" := EXISTS (
2549 SELECT NULL FROM "membership"
2550 WHERE "area_id" = "area_id_p"
2551 AND "member_id" = "output_row"."member_id"
2552 );
2553 IF "simulate_here_v" THEN
2554 IF "simulate_trustee_id_p" ISNULL THEN
2555 SELECT * INTO "delegation_row" FROM "delegation"
2556 WHERE "truster_id" = "output_row"."member_id"
2557 AND "unit_id" = "unit_id_v";
2558 END IF;
2559 ELSE
2560 SELECT * INTO "delegation_row" FROM "delegation"
2561 WHERE "truster_id" = "output_row"."member_id"
2562 AND (
2563 "unit_id" = "unit_id_v" OR
2564 "area_id" = "area_id_v"
2566 ORDER BY "scope" DESC;
2567 END IF;
2568 ELSIF "scope_v" = 'issue' THEN
2569 IF "issue_row"."fully_frozen" ISNULL THEN
2570 "output_row"."participation" := EXISTS (
2571 SELECT NULL FROM "interest"
2572 WHERE "issue_id" = "issue_id_p"
2573 AND "member_id" = "output_row"."member_id"
2574 );
2575 ELSE
2576 IF "output_row"."member_id" = "member_id_p" THEN
2577 "output_row"."participation" := EXISTS (
2578 SELECT NULL FROM "direct_voter"
2579 WHERE "issue_id" = "issue_id_p"
2580 AND "member_id" = "output_row"."member_id"
2581 );
2582 ELSE
2583 "output_row"."participation" := NULL;
2584 END IF;
2585 END IF;
2586 IF "simulate_here_v" THEN
2587 IF "simulate_trustee_id_p" ISNULL THEN
2588 SELECT * INTO "delegation_row" FROM "delegation"
2589 WHERE "truster_id" = "output_row"."member_id"
2590 AND (
2591 "unit_id" = "unit_id_v" OR
2592 "area_id" = "area_id_v"
2594 ORDER BY "scope" DESC;
2595 END IF;
2596 ELSE
2597 SELECT * INTO "delegation_row" FROM "delegation"
2598 WHERE "truster_id" = "output_row"."member_id"
2599 AND (
2600 "unit_id" = "unit_id_v" OR
2601 "area_id" = "area_id_v" OR
2602 "issue_id" = "issue_id_p"
2604 ORDER BY "scope" DESC;
2605 END IF;
2606 END IF;
2607 ELSE
2608 "output_row"."participation" := FALSE;
2609 END IF;
2610 IF "simulate_here_v" AND "simulate_trustee_id_p" NOTNULL THEN
2611 "output_row"."scope_out" := "scope_v";
2612 "output_rows" := "output_rows" || "output_row";
2613 "output_row"."member_id" := "simulate_trustee_id_p";
2614 ELSIF "delegation_row"."trustee_id" NOTNULL THEN
2615 "output_row"."scope_out" := "delegation_row"."scope";
2616 "output_rows" := "output_rows" || "output_row";
2617 "output_row"."member_id" := "delegation_row"."trustee_id";
2618 ELSIF "delegation_row"."scope" NOTNULL THEN
2619 "output_row"."scope_out" := "delegation_row"."scope";
2620 "output_row"."disabled_out" := TRUE;
2621 "output_rows" := "output_rows" || "output_row";
2622 EXIT;
2623 ELSE
2624 "output_row"."scope_out" := NULL;
2625 "output_rows" := "output_rows" || "output_row";
2626 EXIT;
2627 END IF;
2628 EXIT WHEN "loop_member_id_v" NOTNULL;
2629 "output_row"."index" := "output_row"."index" + 1;
2630 END LOOP;
2631 "row_count" := array_upper("output_rows", 1);
2632 "i" := 1;
2633 "loop_v" := FALSE;
2634 LOOP
2635 "output_row" := "output_rows"["i"];
2636 EXIT WHEN "output_row" ISNULL; -- NOTE: ISNULL and NOT ... NOTNULL produce different results!
2637 IF "loop_v" THEN
2638 IF "i" + 1 = "row_count" THEN
2639 "output_row"."loop" := 'last';
2640 ELSIF "i" = "row_count" THEN
2641 "output_row"."loop" := 'repetition';
2642 ELSE
2643 "output_row"."loop" := 'intermediate';
2644 END IF;
2645 ELSIF "output_row"."member_id" = "loop_member_id_v" THEN
2646 "output_row"."loop" := 'first';
2647 "loop_v" := TRUE;
2648 END IF;
2649 IF "scope_v" = 'unit' THEN
2650 "output_row"."participation" := NULL;
2651 END IF;
2652 RETURN NEXT "output_row";
2653 "i" := "i" + 1;
2654 END LOOP;
2655 RETURN;
2656 END;
2657 $$;
2659 COMMENT ON FUNCTION "delegation_chain"
2660 ( "member"."id"%TYPE,
2661 "unit"."id"%TYPE,
2662 "area"."id"%TYPE,
2663 "issue"."id"%TYPE,
2664 "member"."id"%TYPE,
2665 BOOLEAN )
2666 IS 'Shows a delegation chain for unit, area, or issue; See "delegation_chain_row" type for more information';
2670 ---------------------------------------------------------
2671 -- Single row returning function for delegation chains --
2672 ---------------------------------------------------------
2675 CREATE TYPE "delegation_info_loop_type" AS ENUM
2676 ('own', 'first', 'first_ellipsis', 'other', 'other_ellipsis');
2678 COMMENT ON TYPE "delegation_info_loop_type" IS 'Type of "delegation_loop" in "delegation_info_type"; ''own'' means loop to self, ''first'' means loop to first trustee, ''first_ellipsis'' means loop to ellipsis after first trustee, ''other'' means loop to other trustee, ''other_ellipsis'' means loop to ellipsis after other trustee''';
2681 CREATE TYPE "delegation_info_type" AS (
2682 "own_participation" BOOLEAN,
2683 "own_delegation_scope" "delegation_scope",
2684 "first_trustee_id" INT4,
2685 "first_trustee_participation" BOOLEAN,
2686 "first_trustee_ellipsis" BOOLEAN,
2687 "other_trustee_id" INT4,
2688 "other_trustee_participation" BOOLEAN,
2689 "other_trustee_ellipsis" BOOLEAN,
2690 "delegation_loop" "delegation_info_loop_type",
2691 "participating_member_id" INT4 );
2693 COMMENT ON TYPE "delegation_info_type" IS 'Type of result returned by "delegation_info" function; For meaning of "participation" check comment on "delegation_chain_row" type';
2695 COMMENT ON COLUMN "delegation_info_type"."own_participation" IS 'Member is directly participating';
2696 COMMENT ON COLUMN "delegation_info_type"."own_delegation_scope" IS 'Delegation scope of member';
2697 COMMENT ON COLUMN "delegation_info_type"."first_trustee_id" IS 'Direct trustee of member';
2698 COMMENT ON COLUMN "delegation_info_type"."first_trustee_participation" IS 'Direct trustee of member is participating';
2699 COMMENT ON COLUMN "delegation_info_type"."first_trustee_ellipsis" IS 'Ellipsis in delegation chain after "first_trustee"';
2700 COMMENT ON COLUMN "delegation_info_type"."other_trustee_id" IS 'Another relevant trustee (due to participation)';
2701 COMMENT ON COLUMN "delegation_info_type"."other_trustee_participation" IS 'Another trustee is participating (redundant field: if "other_trustee_id" is set, then "other_trustee_participation" is always TRUE, else "other_trustee_participation" is NULL)';
2702 COMMENT ON COLUMN "delegation_info_type"."other_trustee_ellipsis" IS 'Ellipsis in delegation chain after "other_trustee"';
2703 COMMENT ON COLUMN "delegation_info_type"."delegation_loop" IS 'Non-NULL value, if delegation chain contains a circle; See comment on "delegation_info_loop_type" for details';
2704 COMMENT ON COLUMN "delegation_info_type"."participating_member_id" IS 'First participating member in delegation chain';
2707 CREATE FUNCTION "delegation_info"
2708 ( "member_id_p" "member"."id"%TYPE,
2709 "unit_id_p" "unit"."id"%TYPE,
2710 "area_id_p" "area"."id"%TYPE,
2711 "issue_id_p" "issue"."id"%TYPE,
2712 "simulate_trustee_id_p" "member"."id"%TYPE DEFAULT NULL,
2713 "simulate_default_p" BOOLEAN DEFAULT FALSE )
2714 RETURNS "delegation_info_type"
2715 LANGUAGE 'plpgsql' STABLE AS $$
2716 DECLARE
2717 "current_row" "delegation_chain_row";
2718 "result" "delegation_info_type";
2719 BEGIN
2720 "result"."own_participation" := FALSE;
2721 FOR "current_row" IN
2722 SELECT * FROM "delegation_chain"(
2723 "member_id_p",
2724 "unit_id_p", "area_id_p", "issue_id_p",
2725 "simulate_trustee_id_p", "simulate_default_p")
2726 LOOP
2727 IF
2728 "result"."participating_member_id" ISNULL AND
2729 "current_row"."participation"
2730 THEN
2731 "result"."participating_member_id" := "current_row"."member_id";
2732 END IF;
2733 IF "current_row"."member_id" = "member_id_p" THEN
2734 "result"."own_participation" := "current_row"."participation";
2735 "result"."own_delegation_scope" := "current_row"."scope_out";
2736 IF "current_row"."loop" = 'first' THEN
2737 "result"."delegation_loop" := 'own';
2738 END IF;
2739 ELSIF
2740 "current_row"."member_valid" AND
2741 ( "current_row"."loop" ISNULL OR
2742 "current_row"."loop" != 'repetition' )
2743 THEN
2744 IF "result"."first_trustee_id" ISNULL THEN
2745 "result"."first_trustee_id" := "current_row"."member_id";
2746 "result"."first_trustee_participation" := "current_row"."participation";
2747 "result"."first_trustee_ellipsis" := FALSE;
2748 IF "current_row"."loop" = 'first' THEN
2749 "result"."delegation_loop" := 'first';
2750 END IF;
2751 ELSIF "result"."other_trustee_id" ISNULL THEN
2752 IF "current_row"."participation" AND NOT "current_row"."overridden" THEN
2753 "result"."other_trustee_id" := "current_row"."member_id";
2754 "result"."other_trustee_participation" := TRUE;
2755 "result"."other_trustee_ellipsis" := FALSE;
2756 IF "current_row"."loop" = 'first' THEN
2757 "result"."delegation_loop" := 'other';
2758 END IF;
2759 ELSE
2760 "result"."first_trustee_ellipsis" := TRUE;
2761 IF "current_row"."loop" = 'first' THEN
2762 "result"."delegation_loop" := 'first_ellipsis';
2763 END IF;
2764 END IF;
2765 ELSE
2766 "result"."other_trustee_ellipsis" := TRUE;
2767 IF "current_row"."loop" = 'first' THEN
2768 "result"."delegation_loop" := 'other_ellipsis';
2769 END IF;
2770 END IF;
2771 END IF;
2772 END LOOP;
2773 RETURN "result";
2774 END;
2775 $$;
2777 COMMENT ON FUNCTION "delegation_info"
2778 ( "member"."id"%TYPE,
2779 "unit"."id"%TYPE,
2780 "area"."id"%TYPE,
2781 "issue"."id"%TYPE,
2782 "member"."id"%TYPE,
2783 BOOLEAN )
2784 IS 'Notable information about a delegation chain for unit, area, or issue; See "delegation_info_type" for more information';
2788 ------------------------------
2789 -- Comparison by vote count --
2790 ------------------------------
2792 CREATE FUNCTION "vote_ratio"
2793 ( "positive_votes_p" "initiative"."positive_votes"%TYPE,
2794 "negative_votes_p" "initiative"."negative_votes"%TYPE )
2795 RETURNS FLOAT8
2796 LANGUAGE 'plpgsql' STABLE AS $$
2797 BEGIN
2798 IF "positive_votes_p" > 0 AND "negative_votes_p" > 0 THEN
2799 RETURN
2800 "positive_votes_p"::FLOAT8 /
2801 ("positive_votes_p" + "negative_votes_p")::FLOAT8;
2802 ELSIF "positive_votes_p" > 0 THEN
2803 RETURN "positive_votes_p";
2804 ELSIF "negative_votes_p" > 0 THEN
2805 RETURN 1 - "negative_votes_p";
2806 ELSE
2807 RETURN 0.5;
2808 END IF;
2809 END;
2810 $$;
2812 COMMENT ON FUNCTION "vote_ratio"
2813 ( "initiative"."positive_votes"%TYPE,
2814 "initiative"."negative_votes"%TYPE )
2815 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.';
2819 ------------------------------------------------
2820 -- Locking for snapshots and voting procedure --
2821 ------------------------------------------------
2824 CREATE FUNCTION "share_row_lock_issue_trigger"()
2825 RETURNS TRIGGER
2826 LANGUAGE 'plpgsql' VOLATILE AS $$
2827 BEGIN
2828 IF TG_OP = 'UPDATE' OR TG_OP = 'DELETE' THEN
2829 PERFORM NULL FROM "issue" WHERE "id" = OLD."issue_id" FOR SHARE;
2830 END IF;
2831 IF TG_OP = 'INSERT' OR TG_OP = 'UPDATE' THEN
2832 PERFORM NULL FROM "issue" WHERE "id" = NEW."issue_id" FOR SHARE;
2833 RETURN NEW;
2834 ELSE
2835 RETURN OLD;
2836 END IF;
2837 END;
2838 $$;
2840 COMMENT ON FUNCTION "share_row_lock_issue_trigger"() IS 'Implementation of triggers "share_row_lock_issue" on multiple tables';
2843 CREATE FUNCTION "share_row_lock_issue_via_initiative_trigger"()
2844 RETURNS TRIGGER
2845 LANGUAGE 'plpgsql' VOLATILE AS $$
2846 BEGIN
2847 IF TG_OP = 'UPDATE' OR TG_OP = 'DELETE' THEN
2848 PERFORM NULL FROM "issue"
2849 JOIN "initiative" ON "issue"."id" = "initiative"."issue_id"
2850 WHERE "initiative"."id" = OLD."initiative_id"
2851 FOR SHARE OF "issue";
2852 END IF;
2853 IF TG_OP = 'INSERT' OR TG_OP = 'UPDATE' THEN
2854 PERFORM NULL FROM "issue"
2855 JOIN "initiative" ON "issue"."id" = "initiative"."issue_id"
2856 WHERE "initiative"."id" = NEW."initiative_id"
2857 FOR SHARE OF "issue";
2858 RETURN NEW;
2859 ELSE
2860 RETURN OLD;
2861 END IF;
2862 END;
2863 $$;
2865 COMMENT ON FUNCTION "share_row_lock_issue_trigger"() IS 'Implementation of trigger "share_row_lock_issue_via_initiative" on table "opinion"';
2868 CREATE TRIGGER "share_row_lock_issue"
2869 BEFORE INSERT OR UPDATE OR DELETE ON "initiative"
2870 FOR EACH ROW EXECUTE PROCEDURE
2871 "share_row_lock_issue_trigger"();
2873 CREATE TRIGGER "share_row_lock_issue"
2874 BEFORE INSERT OR UPDATE OR DELETE ON "interest"
2875 FOR EACH ROW EXECUTE PROCEDURE
2876 "share_row_lock_issue_trigger"();
2878 CREATE TRIGGER "share_row_lock_issue"
2879 BEFORE INSERT OR UPDATE OR DELETE ON "supporter"
2880 FOR EACH ROW EXECUTE PROCEDURE
2881 "share_row_lock_issue_trigger"();
2883 CREATE TRIGGER "share_row_lock_issue_via_initiative"
2884 BEFORE INSERT OR UPDATE OR DELETE ON "opinion"
2885 FOR EACH ROW EXECUTE PROCEDURE
2886 "share_row_lock_issue_via_initiative_trigger"();
2888 CREATE TRIGGER "share_row_lock_issue"
2889 BEFORE INSERT OR UPDATE OR DELETE ON "direct_voter"
2890 FOR EACH ROW EXECUTE PROCEDURE
2891 "share_row_lock_issue_trigger"();
2893 CREATE TRIGGER "share_row_lock_issue"
2894 BEFORE INSERT OR UPDATE OR DELETE ON "delegating_voter"
2895 FOR EACH ROW EXECUTE PROCEDURE
2896 "share_row_lock_issue_trigger"();
2898 CREATE TRIGGER "share_row_lock_issue"
2899 BEFORE INSERT OR UPDATE OR DELETE ON "vote"
2900 FOR EACH ROW EXECUTE PROCEDURE
2901 "share_row_lock_issue_trigger"();
2903 COMMENT ON TRIGGER "share_row_lock_issue" ON "initiative" IS 'See "lock_issue" function';
2904 COMMENT ON TRIGGER "share_row_lock_issue" ON "interest" IS 'See "lock_issue" function';
2905 COMMENT ON TRIGGER "share_row_lock_issue" ON "supporter" IS 'See "lock_issue" function';
2906 COMMENT ON TRIGGER "share_row_lock_issue_via_initiative" ON "opinion" IS 'See "lock_issue" function';
2907 COMMENT ON TRIGGER "share_row_lock_issue" ON "direct_voter" IS 'See "lock_issue" function';
2908 COMMENT ON TRIGGER "share_row_lock_issue" ON "delegating_voter" IS 'See "lock_issue" function';
2909 COMMENT ON TRIGGER "share_row_lock_issue" ON "vote" IS 'See "lock_issue" function';
2912 CREATE FUNCTION "lock_issue"
2913 ( "issue_id_p" "issue"."id"%TYPE )
2914 RETURNS VOID
2915 LANGUAGE 'plpgsql' VOLATILE AS $$
2916 BEGIN
2917 LOCK TABLE "member" IN SHARE MODE;
2918 LOCK TABLE "privilege" IN SHARE MODE;
2919 LOCK TABLE "membership" IN SHARE MODE;
2920 LOCK TABLE "policy" IN SHARE MODE;
2921 PERFORM NULL FROM "issue" WHERE "id" = "issue_id_p" FOR UPDATE;
2922 -- NOTE: The row-level exclusive lock in combination with the
2923 -- share_row_lock_issue(_via_initiative)_trigger functions (which
2924 -- acquire a row-level share lock on the issue) ensure that no data
2925 -- is changed, which could affect calculation of snapshots or
2926 -- counting of votes. Table "delegation" must be table-level-locked,
2927 -- as it also contains issue- and global-scope delegations.
2928 LOCK TABLE "delegation" IN SHARE MODE;
2929 LOCK TABLE "direct_population_snapshot" IN EXCLUSIVE MODE;
2930 LOCK TABLE "delegating_population_snapshot" IN EXCLUSIVE MODE;
2931 LOCK TABLE "direct_interest_snapshot" IN EXCLUSIVE MODE;
2932 LOCK TABLE "delegating_interest_snapshot" IN EXCLUSIVE MODE;
2933 LOCK TABLE "direct_supporter_snapshot" IN EXCLUSIVE MODE;
2934 RETURN;
2935 END;
2936 $$;
2938 COMMENT ON FUNCTION "lock_issue"
2939 ( "issue"."id"%TYPE )
2940 IS 'Locks the issue and all other data which is used for calculating snapshots or counting votes.';
2944 ------------------------------------------------------------------------
2945 -- Regular tasks, except calculcation of snapshots and voting results --
2946 ------------------------------------------------------------------------
2948 CREATE FUNCTION "check_activity"()
2949 RETURNS VOID
2950 LANGUAGE 'plpgsql' VOLATILE AS $$
2951 DECLARE
2952 "system_setting_row" "system_setting"%ROWTYPE;
2953 BEGIN
2954 SELECT * INTO "system_setting_row" FROM "system_setting";
2955 LOCK TABLE "member" IN SHARE ROW EXCLUSIVE MODE;
2956 IF "system_setting_row"."member_ttl" NOTNULL THEN
2957 UPDATE "member" SET "active" = FALSE
2958 WHERE "active" = TRUE
2959 AND "last_activity" < (now() - "system_setting_row"."member_ttl")::DATE;
2960 END IF;
2961 RETURN;
2962 END;
2963 $$;
2965 COMMENT ON FUNCTION "check_activity"() IS 'Deactivates members when "last_activity" is older than "system_setting"."member_ttl".';
2968 CREATE FUNCTION "calculate_member_counts"()
2969 RETURNS VOID
2970 LANGUAGE 'plpgsql' VOLATILE AS $$
2971 BEGIN
2972 LOCK TABLE "member" IN SHARE MODE;
2973 LOCK TABLE "member_count" IN EXCLUSIVE MODE;
2974 LOCK TABLE "unit" IN EXCLUSIVE MODE;
2975 LOCK TABLE "area" IN EXCLUSIVE MODE;
2976 LOCK TABLE "privilege" IN SHARE MODE;
2977 LOCK TABLE "membership" IN SHARE MODE;
2978 DELETE FROM "member_count";
2979 INSERT INTO "member_count" ("total_count")
2980 SELECT "total_count" FROM "member_count_view";
2981 UPDATE "unit" SET "member_count" = "view"."member_count"
2982 FROM "unit_member_count" AS "view"
2983 WHERE "view"."unit_id" = "unit"."id";
2984 UPDATE "area" SET
2985 "direct_member_count" = "view"."direct_member_count",
2986 "member_weight" = "view"."member_weight"
2987 FROM "area_member_count" AS "view"
2988 WHERE "view"."area_id" = "area"."id";
2989 RETURN;
2990 END;
2991 $$;
2993 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"';
2997 ------------------------------
2998 -- Calculation of snapshots --
2999 ------------------------------
3001 CREATE FUNCTION "weight_of_added_delegations_for_population_snapshot"
3002 ( "issue_id_p" "issue"."id"%TYPE,
3003 "member_id_p" "member"."id"%TYPE,
3004 "delegate_member_ids_p" "delegating_population_snapshot"."delegate_member_ids"%TYPE )
3005 RETURNS "direct_population_snapshot"."weight"%TYPE
3006 LANGUAGE 'plpgsql' VOLATILE AS $$
3007 DECLARE
3008 "issue_delegation_row" "issue_delegation"%ROWTYPE;
3009 "delegate_member_ids_v" "delegating_population_snapshot"."delegate_member_ids"%TYPE;
3010 "weight_v" INT4;
3011 "sub_weight_v" INT4;
3012 BEGIN
3013 "weight_v" := 0;
3014 FOR "issue_delegation_row" IN
3015 SELECT * FROM "issue_delegation"
3016 WHERE "trustee_id" = "member_id_p"
3017 AND "issue_id" = "issue_id_p"
3018 LOOP
3019 IF NOT EXISTS (
3020 SELECT NULL FROM "direct_population_snapshot"
3021 WHERE "issue_id" = "issue_id_p"
3022 AND "event" = 'periodic'
3023 AND "member_id" = "issue_delegation_row"."truster_id"
3024 ) AND NOT EXISTS (
3025 SELECT NULL FROM "delegating_population_snapshot"
3026 WHERE "issue_id" = "issue_id_p"
3027 AND "event" = 'periodic'
3028 AND "member_id" = "issue_delegation_row"."truster_id"
3029 ) THEN
3030 "delegate_member_ids_v" :=
3031 "member_id_p" || "delegate_member_ids_p";
3032 INSERT INTO "delegating_population_snapshot" (
3033 "issue_id",
3034 "event",
3035 "member_id",
3036 "scope",
3037 "delegate_member_ids"
3038 ) VALUES (
3039 "issue_id_p",
3040 'periodic',
3041 "issue_delegation_row"."truster_id",
3042 "issue_delegation_row"."scope",
3043 "delegate_member_ids_v"
3044 );
3045 "sub_weight_v" := 1 +
3046 "weight_of_added_delegations_for_population_snapshot"(
3047 "issue_id_p",
3048 "issue_delegation_row"."truster_id",
3049 "delegate_member_ids_v"
3050 );
3051 UPDATE "delegating_population_snapshot"
3052 SET "weight" = "sub_weight_v"
3053 WHERE "issue_id" = "issue_id_p"
3054 AND "event" = 'periodic'
3055 AND "member_id" = "issue_delegation_row"."truster_id";
3056 "weight_v" := "weight_v" + "sub_weight_v";
3057 END IF;
3058 END LOOP;
3059 RETURN "weight_v";
3060 END;
3061 $$;
3063 COMMENT ON FUNCTION "weight_of_added_delegations_for_population_snapshot"
3064 ( "issue"."id"%TYPE,
3065 "member"."id"%TYPE,
3066 "delegating_population_snapshot"."delegate_member_ids"%TYPE )
3067 IS 'Helper function for "create_population_snapshot" function';
3070 CREATE FUNCTION "create_population_snapshot"
3071 ( "issue_id_p" "issue"."id"%TYPE )
3072 RETURNS VOID
3073 LANGUAGE 'plpgsql' VOLATILE AS $$
3074 DECLARE
3075 "member_id_v" "member"."id"%TYPE;
3076 BEGIN
3077 DELETE FROM "direct_population_snapshot"
3078 WHERE "issue_id" = "issue_id_p"
3079 AND "event" = 'periodic';
3080 DELETE FROM "delegating_population_snapshot"
3081 WHERE "issue_id" = "issue_id_p"
3082 AND "event" = 'periodic';
3083 INSERT INTO "direct_population_snapshot"
3084 ("issue_id", "event", "member_id")
3085 SELECT
3086 "issue_id_p" AS "issue_id",
3087 'periodic'::"snapshot_event" AS "event",
3088 "member"."id" AS "member_id"
3089 FROM "issue"
3090 JOIN "area" ON "issue"."area_id" = "area"."id"
3091 JOIN "membership" ON "area"."id" = "membership"."area_id"
3092 JOIN "member" ON "membership"."member_id" = "member"."id"
3093 JOIN "privilege"
3094 ON "privilege"."unit_id" = "area"."unit_id"
3095 AND "privilege"."member_id" = "member"."id"
3096 WHERE "issue"."id" = "issue_id_p"
3097 AND "member"."active" AND "privilege"."voting_right"
3098 UNION
3099 SELECT
3100 "issue_id_p" AS "issue_id",
3101 'periodic'::"snapshot_event" AS "event",
3102 "member"."id" AS "member_id"
3103 FROM "issue"
3104 JOIN "area" ON "issue"."area_id" = "area"."id"
3105 JOIN "interest" ON "issue"."id" = "interest"."issue_id"
3106 JOIN "member" ON "interest"."member_id" = "member"."id"
3107 JOIN "privilege"
3108 ON "privilege"."unit_id" = "area"."unit_id"
3109 AND "privilege"."member_id" = "member"."id"
3110 WHERE "issue"."id" = "issue_id_p"
3111 AND "member"."active" AND "privilege"."voting_right";
3112 FOR "member_id_v" IN
3113 SELECT "member_id" FROM "direct_population_snapshot"
3114 WHERE "issue_id" = "issue_id_p"
3115 AND "event" = 'periodic'
3116 LOOP
3117 UPDATE "direct_population_snapshot" SET
3118 "weight" = 1 +
3119 "weight_of_added_delegations_for_population_snapshot"(
3120 "issue_id_p",
3121 "member_id_v",
3122 '{}'
3124 WHERE "issue_id" = "issue_id_p"
3125 AND "event" = 'periodic'
3126 AND "member_id" = "member_id_v";
3127 END LOOP;
3128 RETURN;
3129 END;
3130 $$;
3132 COMMENT ON FUNCTION "create_population_snapshot"
3133 ( "issue"."id"%TYPE )
3134 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.';
3137 CREATE FUNCTION "weight_of_added_delegations_for_interest_snapshot"
3138 ( "issue_id_p" "issue"."id"%TYPE,
3139 "member_id_p" "member"."id"%TYPE,
3140 "delegate_member_ids_p" "delegating_interest_snapshot"."delegate_member_ids"%TYPE )
3141 RETURNS "direct_interest_snapshot"."weight"%TYPE
3142 LANGUAGE 'plpgsql' VOLATILE AS $$
3143 DECLARE
3144 "issue_delegation_row" "issue_delegation"%ROWTYPE;
3145 "delegate_member_ids_v" "delegating_interest_snapshot"."delegate_member_ids"%TYPE;
3146 "weight_v" INT4;
3147 "sub_weight_v" INT4;
3148 BEGIN
3149 "weight_v" := 0;
3150 FOR "issue_delegation_row" IN
3151 SELECT * FROM "issue_delegation"
3152 WHERE "trustee_id" = "member_id_p"
3153 AND "issue_id" = "issue_id_p"
3154 LOOP
3155 IF NOT EXISTS (
3156 SELECT NULL FROM "direct_interest_snapshot"
3157 WHERE "issue_id" = "issue_id_p"
3158 AND "event" = 'periodic'
3159 AND "member_id" = "issue_delegation_row"."truster_id"
3160 ) AND NOT EXISTS (
3161 SELECT NULL FROM "delegating_interest_snapshot"
3162 WHERE "issue_id" = "issue_id_p"
3163 AND "event" = 'periodic'
3164 AND "member_id" = "issue_delegation_row"."truster_id"
3165 ) THEN
3166 "delegate_member_ids_v" :=
3167 "member_id_p" || "delegate_member_ids_p";
3168 INSERT INTO "delegating_interest_snapshot" (
3169 "issue_id",
3170 "event",
3171 "member_id",
3172 "scope",
3173 "delegate_member_ids"
3174 ) VALUES (
3175 "issue_id_p",
3176 'periodic',
3177 "issue_delegation_row"."truster_id",
3178 "issue_delegation_row"."scope",
3179 "delegate_member_ids_v"
3180 );
3181 "sub_weight_v" := 1 +
3182 "weight_of_added_delegations_for_interest_snapshot"(
3183 "issue_id_p",
3184 "issue_delegation_row"."truster_id",
3185 "delegate_member_ids_v"
3186 );
3187 UPDATE "delegating_interest_snapshot"
3188 SET "weight" = "sub_weight_v"
3189 WHERE "issue_id" = "issue_id_p"
3190 AND "event" = 'periodic'
3191 AND "member_id" = "issue_delegation_row"."truster_id";
3192 "weight_v" := "weight_v" + "sub_weight_v";
3193 END IF;
3194 END LOOP;
3195 RETURN "weight_v";
3196 END;
3197 $$;
3199 COMMENT ON FUNCTION "weight_of_added_delegations_for_interest_snapshot"
3200 ( "issue"."id"%TYPE,
3201 "member"."id"%TYPE,
3202 "delegating_interest_snapshot"."delegate_member_ids"%TYPE )
3203 IS 'Helper function for "create_interest_snapshot" function';
3206 CREATE FUNCTION "create_interest_snapshot"
3207 ( "issue_id_p" "issue"."id"%TYPE )
3208 RETURNS VOID
3209 LANGUAGE 'plpgsql' VOLATILE AS $$
3210 DECLARE
3211 "member_id_v" "member"."id"%TYPE;
3212 BEGIN
3213 DELETE FROM "direct_interest_snapshot"
3214 WHERE "issue_id" = "issue_id_p"
3215 AND "event" = 'periodic';
3216 DELETE FROM "delegating_interest_snapshot"
3217 WHERE "issue_id" = "issue_id_p"
3218 AND "event" = 'periodic';
3219 DELETE FROM "direct_supporter_snapshot"
3220 WHERE "issue_id" = "issue_id_p"
3221 AND "event" = 'periodic';
3222 INSERT INTO "direct_interest_snapshot"
3223 ("issue_id", "event", "member_id")
3224 SELECT
3225 "issue_id_p" AS "issue_id",
3226 'periodic' AS "event",
3227 "member"."id" AS "member_id"
3228 FROM "issue"
3229 JOIN "area" ON "issue"."area_id" = "area"."id"
3230 JOIN "interest" ON "issue"."id" = "interest"."issue_id"
3231 JOIN "member" ON "interest"."member_id" = "member"."id"
3232 JOIN "privilege"
3233 ON "privilege"."unit_id" = "area"."unit_id"
3234 AND "privilege"."member_id" = "member"."id"
3235 WHERE "issue"."id" = "issue_id_p"
3236 AND "member"."active" AND "privilege"."voting_right";
3237 FOR "member_id_v" IN
3238 SELECT "member_id" FROM "direct_interest_snapshot"
3239 WHERE "issue_id" = "issue_id_p"
3240 AND "event" = 'periodic'
3241 LOOP
3242 UPDATE "direct_interest_snapshot" SET
3243 "weight" = 1 +
3244 "weight_of_added_delegations_for_interest_snapshot"(
3245 "issue_id_p",
3246 "member_id_v",
3247 '{}'
3249 WHERE "issue_id" = "issue_id_p"
3250 AND "event" = 'periodic'
3251 AND "member_id" = "member_id_v";
3252 END LOOP;
3253 INSERT INTO "direct_supporter_snapshot"
3254 ( "issue_id", "initiative_id", "event", "member_id",
3255 "draft_id", "informed", "satisfied" )
3256 SELECT
3257 "issue_id_p" AS "issue_id",
3258 "initiative"."id" AS "initiative_id",
3259 'periodic' AS "event",
3260 "supporter"."member_id" AS "member_id",
3261 "supporter"."draft_id" AS "draft_id",
3262 "supporter"."draft_id" = "current_draft"."id" AS "informed",
3263 NOT EXISTS (
3264 SELECT NULL FROM "critical_opinion"
3265 WHERE "initiative_id" = "initiative"."id"
3266 AND "member_id" = "supporter"."member_id"
3267 ) AS "satisfied"
3268 FROM "initiative"
3269 JOIN "supporter"
3270 ON "supporter"."initiative_id" = "initiative"."id"
3271 JOIN "current_draft"
3272 ON "initiative"."id" = "current_draft"."initiative_id"
3273 JOIN "direct_interest_snapshot"
3274 ON "supporter"."member_id" = "direct_interest_snapshot"."member_id"
3275 AND "initiative"."issue_id" = "direct_interest_snapshot"."issue_id"
3276 AND "event" = 'periodic'
3277 WHERE "initiative"."issue_id" = "issue_id_p";
3278 RETURN;
3279 END;
3280 $$;
3282 COMMENT ON FUNCTION "create_interest_snapshot"
3283 ( "issue"."id"%TYPE )
3284 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.';
3287 CREATE FUNCTION "create_snapshot"
3288 ( "issue_id_p" "issue"."id"%TYPE )
3289 RETURNS VOID
3290 LANGUAGE 'plpgsql' VOLATILE AS $$
3291 DECLARE
3292 "initiative_id_v" "initiative"."id"%TYPE;
3293 "suggestion_id_v" "suggestion"."id"%TYPE;
3294 BEGIN
3295 PERFORM "lock_issue"("issue_id_p");
3296 PERFORM "create_population_snapshot"("issue_id_p");
3297 PERFORM "create_interest_snapshot"("issue_id_p");
3298 UPDATE "issue" SET
3299 "snapshot" = now(),
3300 "latest_snapshot_event" = 'periodic',
3301 "population" = (
3302 SELECT coalesce(sum("weight"), 0)
3303 FROM "direct_population_snapshot"
3304 WHERE "issue_id" = "issue_id_p"
3305 AND "event" = 'periodic'
3307 WHERE "id" = "issue_id_p";
3308 FOR "initiative_id_v" IN
3309 SELECT "id" FROM "initiative" WHERE "issue_id" = "issue_id_p"
3310 LOOP
3311 UPDATE "initiative" SET
3312 "supporter_count" = (
3313 SELECT coalesce(sum("di"."weight"), 0)
3314 FROM "direct_interest_snapshot" AS "di"
3315 JOIN "direct_supporter_snapshot" AS "ds"
3316 ON "di"."member_id" = "ds"."member_id"
3317 WHERE "di"."issue_id" = "issue_id_p"
3318 AND "di"."event" = 'periodic'
3319 AND "ds"."initiative_id" = "initiative_id_v"
3320 AND "ds"."event" = 'periodic'
3321 ),
3322 "informed_supporter_count" = (
3323 SELECT coalesce(sum("di"."weight"), 0)
3324 FROM "direct_interest_snapshot" AS "di"
3325 JOIN "direct_supporter_snapshot" AS "ds"
3326 ON "di"."member_id" = "ds"."member_id"
3327 WHERE "di"."issue_id" = "issue_id_p"
3328 AND "di"."event" = 'periodic'
3329 AND "ds"."initiative_id" = "initiative_id_v"
3330 AND "ds"."event" = 'periodic'
3331 AND "ds"."informed"
3332 ),
3333 "satisfied_supporter_count" = (
3334 SELECT coalesce(sum("di"."weight"), 0)
3335 FROM "direct_interest_snapshot" AS "di"
3336 JOIN "direct_supporter_snapshot" AS "ds"
3337 ON "di"."member_id" = "ds"."member_id"
3338 WHERE "di"."issue_id" = "issue_id_p"
3339 AND "di"."event" = 'periodic'
3340 AND "ds"."initiative_id" = "initiative_id_v"
3341 AND "ds"."event" = 'periodic'
3342 AND "ds"."satisfied"
3343 ),
3344 "satisfied_informed_supporter_count" = (
3345 SELECT coalesce(sum("di"."weight"), 0)
3346 FROM "direct_interest_snapshot" AS "di"
3347 JOIN "direct_supporter_snapshot" AS "ds"
3348 ON "di"."member_id" = "ds"."member_id"
3349 WHERE "di"."issue_id" = "issue_id_p"
3350 AND "di"."event" = 'periodic'
3351 AND "ds"."initiative_id" = "initiative_id_v"
3352 AND "ds"."event" = 'periodic'
3353 AND "ds"."informed"
3354 AND "ds"."satisfied"
3356 WHERE "id" = "initiative_id_v";
3357 FOR "suggestion_id_v" IN
3358 SELECT "id" FROM "suggestion"
3359 WHERE "initiative_id" = "initiative_id_v"
3360 LOOP
3361 UPDATE "suggestion" SET
3362 "minus2_unfulfilled_count" = (
3363 SELECT coalesce(sum("snapshot"."weight"), 0)
3364 FROM "issue" CROSS JOIN "opinion"
3365 JOIN "direct_interest_snapshot" AS "snapshot"
3366 ON "snapshot"."issue_id" = "issue"."id"
3367 AND "snapshot"."event" = "issue"."latest_snapshot_event"
3368 AND "snapshot"."member_id" = "opinion"."member_id"
3369 WHERE "issue"."id" = "issue_id_p"
3370 AND "opinion"."suggestion_id" = "suggestion_id_v"
3371 AND "opinion"."degree" = -2
3372 AND "opinion"."fulfilled" = FALSE
3373 ),
3374 "minus2_fulfilled_count" = (
3375 SELECT coalesce(sum("snapshot"."weight"), 0)
3376 FROM "issue" CROSS JOIN "opinion"
3377 JOIN "direct_interest_snapshot" AS "snapshot"
3378 ON "snapshot"."issue_id" = "issue"."id"
3379 AND "snapshot"."event" = "issue"."latest_snapshot_event"
3380 AND "snapshot"."member_id" = "opinion"."member_id"
3381 WHERE "issue"."id" = "issue_id_p"
3382 AND "opinion"."suggestion_id" = "suggestion_id_v"
3383 AND "opinion"."degree" = -2
3384 AND "opinion"."fulfilled" = TRUE
3385 ),
3386 "minus1_unfulfilled_count" = (
3387 SELECT coalesce(sum("snapshot"."weight"), 0)
3388 FROM "issue" CROSS JOIN "opinion"
3389 JOIN "direct_interest_snapshot" AS "snapshot"
3390 ON "snapshot"."issue_id" = "issue"."id"
3391 AND "snapshot"."event" = "issue"."latest_snapshot_event"
3392 AND "snapshot"."member_id" = "opinion"."member_id"
3393 WHERE "issue"."id" = "issue_id_p"
3394 AND "opinion"."suggestion_id" = "suggestion_id_v"
3395 AND "opinion"."degree" = -1
3396 AND "opinion"."fulfilled" = FALSE
3397 ),
3398 "minus1_fulfilled_count" = (
3399 SELECT coalesce(sum("snapshot"."weight"), 0)
3400 FROM "issue" CROSS JOIN "opinion"
3401 JOIN "direct_interest_snapshot" AS "snapshot"
3402 ON "snapshot"."issue_id" = "issue"."id"
3403 AND "snapshot"."event" = "issue"."latest_snapshot_event"
3404 AND "snapshot"."member_id" = "opinion"."member_id"
3405 WHERE "issue"."id" = "issue_id_p"
3406 AND "opinion"."suggestion_id" = "suggestion_id_v"
3407 AND "opinion"."degree" = -1
3408 AND "opinion"."fulfilled" = TRUE
3409 ),
3410 "plus1_unfulfilled_count" = (
3411 SELECT coalesce(sum("snapshot"."weight"), 0)
3412 FROM "issue" CROSS JOIN "opinion"
3413 JOIN "direct_interest_snapshot" AS "snapshot"
3414 ON "snapshot"."issue_id" = "issue"."id"
3415 AND "snapshot"."event" = "issue"."latest_snapshot_event"
3416 AND "snapshot"."member_id" = "opinion"."member_id"
3417 WHERE "issue"."id" = "issue_id_p"
3418 AND "opinion"."suggestion_id" = "suggestion_id_v"
3419 AND "opinion"."degree" = 1
3420 AND "opinion"."fulfilled" = FALSE
3421 ),
3422 "plus1_fulfilled_count" = (
3423 SELECT coalesce(sum("snapshot"."weight"), 0)
3424 FROM "issue" CROSS JOIN "opinion"
3425 JOIN "direct_interest_snapshot" AS "snapshot"
3426 ON "snapshot"."issue_id" = "issue"."id"
3427 AND "snapshot"."event" = "issue"."latest_snapshot_event"
3428 AND "snapshot"."member_id" = "opinion"."member_id"
3429 WHERE "issue"."id" = "issue_id_p"
3430 AND "opinion"."suggestion_id" = "suggestion_id_v"
3431 AND "opinion"."degree" = 1
3432 AND "opinion"."fulfilled" = TRUE
3433 ),
3434 "plus2_unfulfilled_count" = (
3435 SELECT coalesce(sum("snapshot"."weight"), 0)
3436 FROM "issue" CROSS JOIN "opinion"
3437 JOIN "direct_interest_snapshot" AS "snapshot"
3438 ON "snapshot"."issue_id" = "issue"."id"
3439 AND "snapshot"."event" = "issue"."latest_snapshot_event"
3440 AND "snapshot"."member_id" = "opinion"."member_id"
3441 WHERE "issue"."id" = "issue_id_p"
3442 AND "opinion"."suggestion_id" = "suggestion_id_v"
3443 AND "opinion"."degree" = 2
3444 AND "opinion"."fulfilled" = FALSE
3445 ),
3446 "plus2_fulfilled_count" = (
3447 SELECT coalesce(sum("snapshot"."weight"), 0)
3448 FROM "issue" CROSS JOIN "opinion"
3449 JOIN "direct_interest_snapshot" AS "snapshot"
3450 ON "snapshot"."issue_id" = "issue"."id"
3451 AND "snapshot"."event" = "issue"."latest_snapshot_event"
3452 AND "snapshot"."member_id" = "opinion"."member_id"
3453 WHERE "issue"."id" = "issue_id_p"
3454 AND "opinion"."suggestion_id" = "suggestion_id_v"
3455 AND "opinion"."degree" = 2
3456 AND "opinion"."fulfilled" = TRUE
3458 WHERE "suggestion"."id" = "suggestion_id_v";
3459 END LOOP;
3460 END LOOP;
3461 RETURN;
3462 END;
3463 $$;
3465 COMMENT ON FUNCTION "create_snapshot"
3466 ( "issue"."id"%TYPE )
3467 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.';
3470 CREATE FUNCTION "set_snapshot_event"
3471 ( "issue_id_p" "issue"."id"%TYPE,
3472 "event_p" "snapshot_event" )
3473 RETURNS VOID
3474 LANGUAGE 'plpgsql' VOLATILE AS $$
3475 DECLARE
3476 "event_v" "issue"."latest_snapshot_event"%TYPE;
3477 BEGIN
3478 SELECT "latest_snapshot_event" INTO "event_v" FROM "issue"
3479 WHERE "id" = "issue_id_p" FOR UPDATE;
3480 UPDATE "issue" SET "latest_snapshot_event" = "event_p"
3481 WHERE "id" = "issue_id_p";
3482 UPDATE "direct_population_snapshot" SET "event" = "event_p"
3483 WHERE "issue_id" = "issue_id_p" AND "event" = "event_v";
3484 UPDATE "delegating_population_snapshot" SET "event" = "event_p"
3485 WHERE "issue_id" = "issue_id_p" AND "event" = "event_v";
3486 UPDATE "direct_interest_snapshot" SET "event" = "event_p"
3487 WHERE "issue_id" = "issue_id_p" AND "event" = "event_v";
3488 UPDATE "delegating_interest_snapshot" SET "event" = "event_p"
3489 WHERE "issue_id" = "issue_id_p" AND "event" = "event_v";
3490 UPDATE "direct_supporter_snapshot" SET "event" = "event_p"
3491 WHERE "issue_id" = "issue_id_p" AND "event" = "event_v";
3492 RETURN;
3493 END;
3494 $$;
3496 COMMENT ON FUNCTION "set_snapshot_event"
3497 ( "issue"."id"%TYPE,
3498 "snapshot_event" )
3499 IS 'Change "event" attribute of the previous ''periodic'' snapshot';
3503 ---------------------
3504 -- Freezing issues --
3505 ---------------------
3507 CREATE FUNCTION "freeze_after_snapshot"
3508 ( "issue_id_p" "issue"."id"%TYPE )
3509 RETURNS VOID
3510 LANGUAGE 'plpgsql' VOLATILE AS $$
3511 DECLARE
3512 "issue_row" "issue"%ROWTYPE;
3513 "policy_row" "policy"%ROWTYPE;
3514 "initiative_row" "initiative"%ROWTYPE;
3515 BEGIN
3516 SELECT * INTO "issue_row" FROM "issue" WHERE "id" = "issue_id_p";
3517 SELECT * INTO "policy_row"
3518 FROM "policy" WHERE "id" = "issue_row"."policy_id";
3519 PERFORM "set_snapshot_event"("issue_id_p", 'full_freeze');
3520 FOR "initiative_row" IN
3521 SELECT * FROM "initiative"
3522 WHERE "issue_id" = "issue_id_p" AND "revoked" ISNULL
3523 LOOP
3524 IF
3525 "initiative_row"."polling" OR (
3526 "initiative_row"."satisfied_supporter_count" > 0 AND
3527 "initiative_row"."satisfied_supporter_count" *
3528 "policy_row"."initiative_quorum_den" >=
3529 "issue_row"."population" * "policy_row"."initiative_quorum_num"
3531 THEN
3532 UPDATE "initiative" SET "admitted" = TRUE
3533 WHERE "id" = "initiative_row"."id";
3534 ELSE
3535 UPDATE "initiative" SET "admitted" = FALSE
3536 WHERE "id" = "initiative_row"."id";
3537 END IF;
3538 END LOOP;
3539 IF EXISTS (
3540 SELECT NULL FROM "initiative"
3541 WHERE "issue_id" = "issue_id_p" AND "admitted" = TRUE
3542 ) THEN
3543 UPDATE "issue" SET
3544 "state" = 'voting',
3545 "accepted" = coalesce("accepted", now()),
3546 "half_frozen" = coalesce("half_frozen", now()),
3547 "fully_frozen" = now()
3548 WHERE "id" = "issue_id_p";
3549 ELSE
3550 UPDATE "issue" SET
3551 "state" = 'canceled_no_initiative_admitted',
3552 "accepted" = coalesce("accepted", now()),
3553 "half_frozen" = coalesce("half_frozen", now()),
3554 "fully_frozen" = now(),
3555 "closed" = now(),
3556 "ranks_available" = TRUE
3557 WHERE "id" = "issue_id_p";
3558 -- NOTE: The following DELETE statements have effect only when
3559 -- issue state has been manipulated
3560 DELETE FROM "direct_voter" WHERE "issue_id" = "issue_id_p";
3561 DELETE FROM "delegating_voter" WHERE "issue_id" = "issue_id_p";
3562 DELETE FROM "battle" WHERE "issue_id" = "issue_id_p";
3563 END IF;
3564 RETURN;
3565 END;
3566 $$;
3568 COMMENT ON FUNCTION "freeze_after_snapshot"
3569 ( "issue"."id"%TYPE )
3570 IS 'This function freezes an issue (fully) and starts voting, but must only be called when "create_snapshot" was called in the same transaction.';
3573 CREATE FUNCTION "manual_freeze"("issue_id_p" "issue"."id"%TYPE)
3574 RETURNS VOID
3575 LANGUAGE 'plpgsql' VOLATILE AS $$
3576 DECLARE
3577 "issue_row" "issue"%ROWTYPE;
3578 BEGIN
3579 PERFORM "create_snapshot"("issue_id_p");
3580 PERFORM "freeze_after_snapshot"("issue_id_p");
3581 RETURN;
3582 END;
3583 $$;
3585 COMMENT ON FUNCTION "manual_freeze"
3586 ( "issue"."id"%TYPE )
3587 IS 'Freeze an issue manually (fully) and start voting';
3591 -----------------------
3592 -- Counting of votes --
3593 -----------------------
3596 CREATE FUNCTION "weight_of_added_vote_delegations"
3597 ( "issue_id_p" "issue"."id"%TYPE,
3598 "member_id_p" "member"."id"%TYPE,
3599 "delegate_member_ids_p" "delegating_voter"."delegate_member_ids"%TYPE )
3600 RETURNS "direct_voter"."weight"%TYPE
3601 LANGUAGE 'plpgsql' VOLATILE AS $$
3602 DECLARE
3603 "issue_delegation_row" "issue_delegation"%ROWTYPE;
3604 "delegate_member_ids_v" "delegating_voter"."delegate_member_ids"%TYPE;
3605 "weight_v" INT4;
3606 "sub_weight_v" INT4;
3607 BEGIN
3608 "weight_v" := 0;
3609 FOR "issue_delegation_row" IN
3610 SELECT * FROM "issue_delegation"
3611 WHERE "trustee_id" = "member_id_p"
3612 AND "issue_id" = "issue_id_p"
3613 LOOP
3614 IF NOT EXISTS (
3615 SELECT NULL FROM "direct_voter"
3616 WHERE "member_id" = "issue_delegation_row"."truster_id"
3617 AND "issue_id" = "issue_id_p"
3618 ) AND NOT EXISTS (
3619 SELECT NULL FROM "delegating_voter"
3620 WHERE "member_id" = "issue_delegation_row"."truster_id"
3621 AND "issue_id" = "issue_id_p"
3622 ) THEN
3623 "delegate_member_ids_v" :=
3624 "member_id_p" || "delegate_member_ids_p";
3625 INSERT INTO "delegating_voter" (
3626 "issue_id",
3627 "member_id",
3628 "scope",
3629 "delegate_member_ids"
3630 ) VALUES (
3631 "issue_id_p",
3632 "issue_delegation_row"."truster_id",
3633 "issue_delegation_row"."scope",
3634 "delegate_member_ids_v"
3635 );
3636 "sub_weight_v" := 1 +
3637 "weight_of_added_vote_delegations"(
3638 "issue_id_p",
3639 "issue_delegation_row"."truster_id",
3640 "delegate_member_ids_v"
3641 );
3642 UPDATE "delegating_voter"
3643 SET "weight" = "sub_weight_v"
3644 WHERE "issue_id" = "issue_id_p"
3645 AND "member_id" = "issue_delegation_row"."truster_id";
3646 "weight_v" := "weight_v" + "sub_weight_v";
3647 END IF;
3648 END LOOP;
3649 RETURN "weight_v";
3650 END;
3651 $$;
3653 COMMENT ON FUNCTION "weight_of_added_vote_delegations"
3654 ( "issue"."id"%TYPE,
3655 "member"."id"%TYPE,
3656 "delegating_voter"."delegate_member_ids"%TYPE )
3657 IS 'Helper function for "add_vote_delegations" function';
3660 CREATE FUNCTION "add_vote_delegations"
3661 ( "issue_id_p" "issue"."id"%TYPE )
3662 RETURNS VOID
3663 LANGUAGE 'plpgsql' VOLATILE AS $$
3664 DECLARE
3665 "member_id_v" "member"."id"%TYPE;
3666 BEGIN
3667 FOR "member_id_v" IN
3668 SELECT "member_id" FROM "direct_voter"
3669 WHERE "issue_id" = "issue_id_p"
3670 LOOP
3671 UPDATE "direct_voter" SET
3672 "weight" = "weight" + "weight_of_added_vote_delegations"(
3673 "issue_id_p",
3674 "member_id_v",
3675 '{}'
3677 WHERE "member_id" = "member_id_v"
3678 AND "issue_id" = "issue_id_p";
3679 END LOOP;
3680 RETURN;
3681 END;
3682 $$;
3684 COMMENT ON FUNCTION "add_vote_delegations"
3685 ( "issue_id_p" "issue"."id"%TYPE )
3686 IS 'Helper function for "close_voting" function';
3689 CREATE FUNCTION "close_voting"("issue_id_p" "issue"."id"%TYPE)
3690 RETURNS VOID
3691 LANGUAGE 'plpgsql' VOLATILE AS $$
3692 DECLARE
3693 "area_id_v" "area"."id"%TYPE;
3694 "unit_id_v" "unit"."id"%TYPE;
3695 "member_id_v" "member"."id"%TYPE;
3696 BEGIN
3697 PERFORM "lock_issue"("issue_id_p");
3698 SELECT "area_id" INTO "area_id_v" FROM "issue" WHERE "id" = "issue_id_p";
3699 SELECT "unit_id" INTO "unit_id_v" FROM "area" WHERE "id" = "area_id_v";
3700 -- delete delegating votes (in cases of manual reset of issue state):
3701 DELETE FROM "delegating_voter"
3702 WHERE "issue_id" = "issue_id_p";
3703 -- delete votes from non-privileged voters:
3704 DELETE FROM "direct_voter"
3705 USING (
3706 SELECT
3707 "direct_voter"."member_id"
3708 FROM "direct_voter"
3709 JOIN "member" ON "direct_voter"."member_id" = "member"."id"
3710 LEFT JOIN "privilege"
3711 ON "privilege"."unit_id" = "unit_id_v"
3712 AND "privilege"."member_id" = "direct_voter"."member_id"
3713 WHERE "direct_voter"."issue_id" = "issue_id_p" AND (
3714 "member"."active" = FALSE OR
3715 "privilege"."voting_right" ISNULL OR
3716 "privilege"."voting_right" = FALSE
3718 ) AS "subquery"
3719 WHERE "direct_voter"."issue_id" = "issue_id_p"
3720 AND "direct_voter"."member_id" = "subquery"."member_id";
3721 -- consider delegations:
3722 UPDATE "direct_voter" SET "weight" = 1
3723 WHERE "issue_id" = "issue_id_p";
3724 PERFORM "add_vote_delegations"("issue_id_p");
3725 -- set voter count and mark issue as being calculated:
3726 UPDATE "issue" SET
3727 "state" = 'calculation',
3728 "closed" = now(),
3729 "voter_count" = (
3730 SELECT coalesce(sum("weight"), 0)
3731 FROM "direct_voter" WHERE "issue_id" = "issue_id_p"
3733 WHERE "id" = "issue_id_p";
3734 -- materialize battle_view:
3735 -- NOTE: "closed" column of issue must be set at this point
3736 DELETE FROM "battle" WHERE "issue_id" = "issue_id_p";
3737 INSERT INTO "battle" (
3738 "issue_id",
3739 "winning_initiative_id", "losing_initiative_id",
3740 "count"
3741 ) SELECT
3742 "issue_id",
3743 "winning_initiative_id", "losing_initiative_id",
3744 "count"
3745 FROM "battle_view" WHERE "issue_id" = "issue_id_p";
3746 -- copy "positive_votes" and "negative_votes" from "battle" table:
3747 UPDATE "initiative" SET
3748 "positive_votes" = "battle_win"."count",
3749 "negative_votes" = "battle_lose"."count"
3750 FROM "battle" AS "battle_win", "battle" AS "battle_lose"
3751 WHERE
3752 "battle_win"."issue_id" = "issue_id_p" AND
3753 "battle_win"."winning_initiative_id" = "initiative"."id" AND
3754 "battle_win"."losing_initiative_id" ISNULL AND
3755 "battle_lose"."issue_id" = "issue_id_p" AND
3756 "battle_lose"."losing_initiative_id" = "initiative"."id" AND
3757 "battle_lose"."winning_initiative_id" ISNULL;
3758 END;
3759 $$;
3761 COMMENT ON FUNCTION "close_voting"
3762 ( "issue"."id"%TYPE )
3763 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.';
3766 CREATE FUNCTION "defeat_strength"
3767 ( "positive_votes_p" INT4, "negative_votes_p" INT4 )
3768 RETURNS INT8
3769 LANGUAGE 'plpgsql' IMMUTABLE AS $$
3770 BEGIN
3771 IF "positive_votes_p" > "negative_votes_p" THEN
3772 RETURN ("positive_votes_p"::INT8 << 31) - "negative_votes_p"::INT8;
3773 ELSIF "positive_votes_p" = "negative_votes_p" THEN
3774 RETURN 0;
3775 ELSE
3776 RETURN -1;
3777 END IF;
3778 END;
3779 $$;
3781 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';
3784 CREATE FUNCTION "calculate_ranks"("issue_id_p" "issue"."id"%TYPE)
3785 RETURNS VOID
3786 LANGUAGE 'plpgsql' VOLATILE AS $$
3787 DECLARE
3788 "issue_row" "issue"%ROWTYPE;
3789 "policy_row" "policy"%ROWTYPE;
3790 "dimension_v" INTEGER;
3791 "vote_matrix" INT4[][]; -- absolute votes
3792 "matrix" INT8[][]; -- defeat strength / best paths
3793 "i" INTEGER;
3794 "j" INTEGER;
3795 "k" INTEGER;
3796 "battle_row" "battle"%ROWTYPE;
3797 "rank_ary" INT4[];
3798 "rank_v" INT4;
3799 "done_v" INTEGER;
3800 "winners_ary" INTEGER[];
3801 "initiative_id_v" "initiative"."id"%TYPE;
3802 BEGIN
3803 SELECT * INTO "issue_row"
3804 FROM "issue" WHERE "id" = "issue_id_p"
3805 FOR UPDATE;
3806 SELECT * INTO "policy_row"
3807 FROM "policy" WHERE "id" = "issue_row"."policy_id";
3808 SELECT count(1) INTO "dimension_v"
3809 FROM "battle_participant" WHERE "issue_id" = "issue_id_p";
3810 -- Create "vote_matrix" with absolute number of votes in pairwise
3811 -- comparison:
3812 "vote_matrix" := array_fill(NULL::INT4, ARRAY["dimension_v", "dimension_v"]);
3813 "i" := 1;
3814 "j" := 2;
3815 FOR "battle_row" IN
3816 SELECT * FROM "battle" WHERE "issue_id" = "issue_id_p"
3817 ORDER BY
3818 "winning_initiative_id" NULLS LAST,
3819 "losing_initiative_id" NULLS LAST
3820 LOOP
3821 "vote_matrix"["i"]["j"] := "battle_row"."count";
3822 IF "j" = "dimension_v" THEN
3823 "i" := "i" + 1;
3824 "j" := 1;
3825 ELSE
3826 "j" := "j" + 1;
3827 IF "j" = "i" THEN
3828 "j" := "j" + 1;
3829 END IF;
3830 END IF;
3831 END LOOP;
3832 IF "i" != "dimension_v" OR "j" != "dimension_v" + 1 THEN
3833 RAISE EXCEPTION 'Wrong battle count (should not happen)';
3834 END IF;
3835 -- Store defeat strengths in "matrix" using "defeat_strength"
3836 -- function:
3837 "matrix" := array_fill(NULL::INT8, ARRAY["dimension_v", "dimension_v"]);
3838 "i" := 1;
3839 LOOP
3840 "j" := 1;
3841 LOOP
3842 IF "i" != "j" THEN
3843 "matrix"["i"]["j"] := "defeat_strength"(
3844 "vote_matrix"["i"]["j"],
3845 "vote_matrix"["j"]["i"]
3846 );
3847 END IF;
3848 EXIT WHEN "j" = "dimension_v";
3849 "j" := "j" + 1;
3850 END LOOP;
3851 EXIT WHEN "i" = "dimension_v";
3852 "i" := "i" + 1;
3853 END LOOP;
3854 -- Find best paths:
3855 "i" := 1;
3856 LOOP
3857 "j" := 1;
3858 LOOP
3859 IF "i" != "j" THEN
3860 "k" := 1;
3861 LOOP
3862 IF "i" != "k" AND "j" != "k" THEN
3863 IF "matrix"["j"]["i"] < "matrix"["i"]["k"] THEN
3864 IF "matrix"["j"]["i"] > "matrix"["j"]["k"] THEN
3865 "matrix"["j"]["k"] := "matrix"["j"]["i"];
3866 END IF;
3867 ELSE
3868 IF "matrix"["i"]["k"] > "matrix"["j"]["k"] THEN
3869 "matrix"["j"]["k"] := "matrix"["i"]["k"];
3870 END IF;
3871 END IF;
3872 END IF;
3873 EXIT WHEN "k" = "dimension_v";
3874 "k" := "k" + 1;
3875 END LOOP;
3876 END IF;
3877 EXIT WHEN "j" = "dimension_v";
3878 "j" := "j" + 1;
3879 END LOOP;
3880 EXIT WHEN "i" = "dimension_v";
3881 "i" := "i" + 1;
3882 END LOOP;
3883 -- Determine order of winners:
3884 "rank_ary" := array_fill(NULL::INT4, ARRAY["dimension_v"]);
3885 "rank_v" := 1;
3886 "done_v" := 0;
3887 LOOP
3888 "winners_ary" := '{}';
3889 "i" := 1;
3890 LOOP
3891 IF "rank_ary"["i"] ISNULL THEN
3892 "j" := 1;
3893 LOOP
3894 IF
3895 "i" != "j" AND
3896 "rank_ary"["j"] ISNULL AND
3897 "matrix"["j"]["i"] > "matrix"["i"]["j"]
3898 THEN
3899 -- someone else is better
3900 EXIT;
3901 END IF;
3902 IF "j" = "dimension_v" THEN
3903 -- noone is better
3904 "winners_ary" := "winners_ary" || "i";
3905 EXIT;
3906 END IF;
3907 "j" := "j" + 1;
3908 END LOOP;
3909 END IF;
3910 EXIT WHEN "i" = "dimension_v";
3911 "i" := "i" + 1;
3912 END LOOP;
3913 "i" := 1;
3914 LOOP
3915 "rank_ary"["winners_ary"["i"]] := "rank_v";
3916 "done_v" := "done_v" + 1;
3917 EXIT WHEN "i" = array_upper("winners_ary", 1);
3918 "i" := "i" + 1;
3919 END LOOP;
3920 EXIT WHEN "done_v" = "dimension_v";
3921 "rank_v" := "rank_v" + 1;
3922 END LOOP;
3923 -- write preliminary results:
3924 "i" := 1;
3925 FOR "initiative_id_v" IN
3926 SELECT "id" FROM "initiative"
3927 WHERE "issue_id" = "issue_id_p" AND "admitted"
3928 ORDER BY "id"
3929 LOOP
3930 UPDATE "initiative" SET
3931 "direct_majority" =
3932 CASE WHEN "policy_row"."direct_majority_strict" THEN
3933 "positive_votes" * "policy_row"."direct_majority_den" >
3934 "policy_row"."direct_majority_num" * ("positive_votes"+"negative_votes")
3935 ELSE
3936 "positive_votes" * "policy_row"."direct_majority_den" >=
3937 "policy_row"."direct_majority_num" * ("positive_votes"+"negative_votes")
3938 END
3939 AND "positive_votes" >= "policy_row"."direct_majority_positive"
3940 AND "issue_row"."voter_count"-"negative_votes" >=
3941 "policy_row"."direct_majority_non_negative",
3942 "indirect_majority" =
3943 CASE WHEN "policy_row"."indirect_majority_strict" THEN
3944 "positive_votes" * "policy_row"."indirect_majority_den" >
3945 "policy_row"."indirect_majority_num" * ("positive_votes"+"negative_votes")
3946 ELSE
3947 "positive_votes" * "policy_row"."indirect_majority_den" >=
3948 "policy_row"."indirect_majority_num" * ("positive_votes"+"negative_votes")
3949 END
3950 AND "positive_votes" >= "policy_row"."indirect_majority_positive"
3951 AND "issue_row"."voter_count"-"negative_votes" >=
3952 "policy_row"."indirect_majority_non_negative",
3953 "schulze_rank" = "rank_ary"["i"],
3954 "better_than_status_quo" = "rank_ary"["i"] < "rank_ary"["dimension_v"],
3955 "worse_than_status_quo" = "rank_ary"["i"] > "rank_ary"["dimension_v"],
3956 "multistage_majority" = "rank_ary"["i"] >= "rank_ary"["dimension_v"],
3957 "reverse_beat_path" = "matrix"["dimension_v"]["i"] >= 0,
3958 "eligible" = FALSE,
3959 "winner" = FALSE,
3960 "rank" = NULL -- NOTE: in cases of manual reset of issue state
3961 WHERE "id" = "initiative_id_v";
3962 "i" := "i" + 1;
3963 END LOOP;
3964 IF "i" != "dimension_v" THEN
3965 RAISE EXCEPTION 'Wrong winner count (should not happen)';
3966 END IF;
3967 -- take indirect majorities into account:
3968 LOOP
3969 UPDATE "initiative" SET "indirect_majority" = TRUE
3970 FROM (
3971 SELECT "new_initiative"."id" AS "initiative_id"
3972 FROM "initiative" "old_initiative"
3973 JOIN "initiative" "new_initiative"
3974 ON "new_initiative"."issue_id" = "issue_id_p"
3975 AND "new_initiative"."indirect_majority" = FALSE
3976 JOIN "battle" "battle_win"
3977 ON "battle_win"."issue_id" = "issue_id_p"
3978 AND "battle_win"."winning_initiative_id" = "new_initiative"."id"
3979 AND "battle_win"."losing_initiative_id" = "old_initiative"."id"
3980 JOIN "battle" "battle_lose"
3981 ON "battle_lose"."issue_id" = "issue_id_p"
3982 AND "battle_lose"."losing_initiative_id" = "new_initiative"."id"
3983 AND "battle_lose"."winning_initiative_id" = "old_initiative"."id"
3984 WHERE "old_initiative"."issue_id" = "issue_id_p"
3985 AND "old_initiative"."indirect_majority" = TRUE
3986 AND CASE WHEN "policy_row"."indirect_majority_strict" THEN
3987 "battle_win"."count" * "policy_row"."indirect_majority_den" >
3988 "policy_row"."indirect_majority_num" *
3989 ("battle_win"."count"+"battle_lose"."count")
3990 ELSE
3991 "battle_win"."count" * "policy_row"."indirect_majority_den" >=
3992 "policy_row"."indirect_majority_num" *
3993 ("battle_win"."count"+"battle_lose"."count")
3994 END
3995 AND "battle_win"."count" >= "policy_row"."indirect_majority_positive"
3996 AND "issue_row"."voter_count"-"battle_lose"."count" >=
3997 "policy_row"."indirect_majority_non_negative"
3998 ) AS "subquery"
3999 WHERE "id" = "subquery"."initiative_id";
4000 EXIT WHEN NOT FOUND;
4001 END LOOP;
4002 -- set "multistage_majority" for remaining matching initiatives:
4003 UPDATE "initiative" SET "multistage_majority" = TRUE
4004 FROM (
4005 SELECT "losing_initiative"."id" AS "initiative_id"
4006 FROM "initiative" "losing_initiative"
4007 JOIN "initiative" "winning_initiative"
4008 ON "winning_initiative"."issue_id" = "issue_id_p"
4009 AND "winning_initiative"."admitted"
4010 JOIN "battle" "battle_win"
4011 ON "battle_win"."issue_id" = "issue_id_p"
4012 AND "battle_win"."winning_initiative_id" = "winning_initiative"."id"
4013 AND "battle_win"."losing_initiative_id" = "losing_initiative"."id"
4014 JOIN "battle" "battle_lose"
4015 ON "battle_lose"."issue_id" = "issue_id_p"
4016 AND "battle_lose"."losing_initiative_id" = "winning_initiative"."id"
4017 AND "battle_lose"."winning_initiative_id" = "losing_initiative"."id"
4018 WHERE "losing_initiative"."issue_id" = "issue_id_p"
4019 AND "losing_initiative"."admitted"
4020 AND "winning_initiative"."schulze_rank" <
4021 "losing_initiative"."schulze_rank"
4022 AND "battle_win"."count" > "battle_lose"."count"
4023 AND (
4024 "battle_win"."count" > "winning_initiative"."positive_votes" OR
4025 "battle_lose"."count" < "losing_initiative"."negative_votes" )
4026 ) AS "subquery"
4027 WHERE "id" = "subquery"."initiative_id";
4028 -- mark eligible initiatives:
4029 UPDATE "initiative" SET "eligible" = TRUE
4030 WHERE "issue_id" = "issue_id_p"
4031 AND "initiative"."direct_majority"
4032 AND "initiative"."indirect_majority"
4033 AND "initiative"."better_than_status_quo"
4034 AND (
4035 "policy_row"."no_multistage_majority" = FALSE OR
4036 "initiative"."multistage_majority" = FALSE )
4037 AND (
4038 "policy_row"."no_reverse_beat_path" = FALSE OR
4039 "initiative"."reverse_beat_path" = FALSE );
4040 -- mark final winner:
4041 UPDATE "initiative" SET "winner" = TRUE
4042 FROM (
4043 SELECT "id" AS "initiative_id"
4044 FROM "initiative"
4045 WHERE "issue_id" = "issue_id_p" AND "eligible"
4046 ORDER BY
4047 "schulze_rank",
4048 "vote_ratio"("positive_votes", "negative_votes"),
4049 "id"
4050 LIMIT 1
4051 ) AS "subquery"
4052 WHERE "id" = "subquery"."initiative_id";
4053 -- write (final) ranks:
4054 "rank_v" := 1;
4055 FOR "initiative_id_v" IN
4056 SELECT "id"
4057 FROM "initiative"
4058 WHERE "issue_id" = "issue_id_p" AND "admitted"
4059 ORDER BY
4060 "winner" DESC,
4061 "eligible" DESC,
4062 "schulze_rank",
4063 "vote_ratio"("positive_votes", "negative_votes"),
4064 "id"
4065 LOOP
4066 UPDATE "initiative" SET "rank" = "rank_v"
4067 WHERE "id" = "initiative_id_v";
4068 "rank_v" := "rank_v" + 1;
4069 END LOOP;
4070 -- set schulze rank of status quo and mark issue as finished:
4071 UPDATE "issue" SET
4072 "status_quo_schulze_rank" = "rank_ary"["dimension_v"],
4073 "state" =
4074 CASE WHEN EXISTS (
4075 SELECT NULL FROM "initiative"
4076 WHERE "issue_id" = "issue_id_p" AND "winner"
4077 ) THEN
4078 'finished_with_winner'::"issue_state"
4079 ELSE
4080 'finished_without_winner'::"issue_state"
4081 END,
4082 "ranks_available" = TRUE
4083 WHERE "id" = "issue_id_p";
4084 RETURN;
4085 END;
4086 $$;
4088 COMMENT ON FUNCTION "calculate_ranks"
4089 ( "issue"."id"%TYPE )
4090 IS 'Determine ranking (Votes have to be counted first)';
4094 -----------------------------
4095 -- Automatic state changes --
4096 -----------------------------
4099 CREATE FUNCTION "check_issue"
4100 ( "issue_id_p" "issue"."id"%TYPE )
4101 RETURNS VOID
4102 LANGUAGE 'plpgsql' VOLATILE AS $$
4103 DECLARE
4104 "issue_row" "issue"%ROWTYPE;
4105 "policy_row" "policy"%ROWTYPE;
4106 BEGIN
4107 PERFORM "lock_issue"("issue_id_p");
4108 SELECT * INTO "issue_row" FROM "issue" WHERE "id" = "issue_id_p";
4109 -- only process open issues:
4110 IF "issue_row"."closed" ISNULL THEN
4111 SELECT * INTO "policy_row" FROM "policy"
4112 WHERE "id" = "issue_row"."policy_id";
4113 -- create a snapshot, unless issue is already fully frozen:
4114 IF "issue_row"."fully_frozen" ISNULL THEN
4115 PERFORM "create_snapshot"("issue_id_p");
4116 SELECT * INTO "issue_row" FROM "issue" WHERE "id" = "issue_id_p";
4117 END IF;
4118 -- eventually close or accept issues, which have not been accepted:
4119 IF "issue_row"."accepted" ISNULL THEN
4120 IF EXISTS (
4121 SELECT NULL FROM "initiative"
4122 WHERE "issue_id" = "issue_id_p"
4123 AND "supporter_count" > 0
4124 AND "supporter_count" * "policy_row"."issue_quorum_den"
4125 >= "issue_row"."population" * "policy_row"."issue_quorum_num"
4126 ) THEN
4127 -- accept issues, if supporter count is high enough
4128 PERFORM "set_snapshot_event"("issue_id_p", 'end_of_admission');
4129 -- NOTE: "issue_row" used later
4130 "issue_row"."state" := 'discussion';
4131 "issue_row"."accepted" := now();
4132 UPDATE "issue" SET
4133 "state" = "issue_row"."state",
4134 "accepted" = "issue_row"."accepted"
4135 WHERE "id" = "issue_row"."id";
4136 ELSIF
4137 now() >= "issue_row"."created" + "issue_row"."admission_time"
4138 THEN
4139 -- close issues, if admission time has expired
4140 PERFORM "set_snapshot_event"("issue_id_p", 'end_of_admission');
4141 UPDATE "issue" SET
4142 "state" = 'canceled_issue_not_accepted',
4143 "closed" = now()
4144 WHERE "id" = "issue_row"."id";
4145 END IF;
4146 END IF;
4147 -- eventually half freeze issues:
4148 IF
4149 -- NOTE: issue can't be closed at this point, if it has been accepted
4150 "issue_row"."accepted" NOTNULL AND
4151 "issue_row"."half_frozen" ISNULL
4152 THEN
4153 IF
4154 now() >= "issue_row"."accepted" + "issue_row"."discussion_time"
4155 THEN
4156 PERFORM "set_snapshot_event"("issue_id_p", 'half_freeze');
4157 -- NOTE: "issue_row" used later
4158 "issue_row"."state" := 'verification';
4159 "issue_row"."half_frozen" := now();
4160 UPDATE "issue" SET
4161 "state" = "issue_row"."state",
4162 "half_frozen" = "issue_row"."half_frozen"
4163 WHERE "id" = "issue_row"."id";
4164 END IF;
4165 END IF;
4166 -- close issues after some time, if all initiatives have been revoked:
4167 IF
4168 "issue_row"."closed" ISNULL AND
4169 NOT EXISTS (
4170 -- all initiatives are revoked
4171 SELECT NULL FROM "initiative"
4172 WHERE "issue_id" = "issue_id_p" AND "revoked" ISNULL
4173 ) AND (
4174 -- and issue has not been accepted yet
4175 "issue_row"."accepted" ISNULL OR
4176 NOT EXISTS (
4177 -- or no initiatives have been revoked lately
4178 SELECT NULL FROM "initiative"
4179 WHERE "issue_id" = "issue_id_p"
4180 AND now() < "revoked" + "issue_row"."verification_time"
4181 ) OR (
4182 -- or verification time has elapsed
4183 "issue_row"."half_frozen" NOTNULL AND
4184 "issue_row"."fully_frozen" ISNULL AND
4185 now() >= "issue_row"."half_frozen" + "issue_row"."verification_time"
4188 THEN
4189 -- NOTE: "issue_row" used later
4190 IF "issue_row"."accepted" ISNULL THEN
4191 "issue_row"."state" := 'canceled_revoked_before_accepted';
4192 ELSIF "issue_row"."half_frozen" ISNULL THEN
4193 "issue_row"."state" := 'canceled_after_revocation_during_discussion';
4194 ELSE
4195 "issue_row"."state" := 'canceled_after_revocation_during_verification';
4196 END IF;
4197 "issue_row"."closed" := now();
4198 UPDATE "issue" SET
4199 "state" = "issue_row"."state",
4200 "closed" = "issue_row"."closed"
4201 WHERE "id" = "issue_row"."id";
4202 END IF;
4203 -- fully freeze issue after verification time:
4204 IF
4205 "issue_row"."half_frozen" NOTNULL AND
4206 "issue_row"."fully_frozen" ISNULL AND
4207 "issue_row"."closed" ISNULL AND
4208 now() >= "issue_row"."half_frozen" + "issue_row"."verification_time"
4209 THEN
4210 PERFORM "freeze_after_snapshot"("issue_id_p");
4211 -- NOTE: "issue" might change, thus "issue_row" has to be updated below
4212 END IF;
4213 SELECT * INTO "issue_row" FROM "issue" WHERE "id" = "issue_id_p";
4214 -- close issue by calling close_voting(...) after voting time:
4215 IF
4216 "issue_row"."closed" ISNULL AND
4217 "issue_row"."fully_frozen" NOTNULL AND
4218 now() >= "issue_row"."fully_frozen" + "issue_row"."voting_time"
4219 THEN
4220 PERFORM "close_voting"("issue_id_p");
4221 -- calculate ranks will not consume much time and can be done now
4222 PERFORM "calculate_ranks"("issue_id_p");
4223 END IF;
4224 END IF;
4225 RETURN;
4226 END;
4227 $$;
4229 COMMENT ON FUNCTION "check_issue"
4230 ( "issue"."id"%TYPE )
4231 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.';
4234 CREATE FUNCTION "check_everything"()
4235 RETURNS VOID
4236 LANGUAGE 'plpgsql' VOLATILE AS $$
4237 DECLARE
4238 "issue_id_v" "issue"."id"%TYPE;
4239 BEGIN
4240 DELETE FROM "expired_session";
4241 PERFORM "check_activity"();
4242 PERFORM "calculate_member_counts"();
4243 FOR "issue_id_v" IN SELECT "id" FROM "open_issue" LOOP
4244 PERFORM "check_issue"("issue_id_v");
4245 END LOOP;
4246 FOR "issue_id_v" IN SELECT "id" FROM "issue_with_ranks_missing" LOOP
4247 PERFORM "calculate_ranks"("issue_id_v");
4248 END LOOP;
4249 RETURN;
4250 END;
4251 $$;
4253 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.';
4257 ----------------------
4258 -- Deletion of data --
4259 ----------------------
4262 CREATE FUNCTION "clean_issue"("issue_id_p" "issue"."id"%TYPE)
4263 RETURNS VOID
4264 LANGUAGE 'plpgsql' VOLATILE AS $$
4265 DECLARE
4266 "issue_row" "issue"%ROWTYPE;
4267 BEGIN
4268 SELECT * INTO "issue_row"
4269 FROM "issue" WHERE "id" = "issue_id_p"
4270 FOR UPDATE;
4271 IF "issue_row"."cleaned" ISNULL THEN
4272 UPDATE "issue" SET
4273 "state" = 'voting',
4274 "closed" = NULL,
4275 "ranks_available" = FALSE
4276 WHERE "id" = "issue_id_p";
4277 DELETE FROM "voting_comment"
4278 WHERE "issue_id" = "issue_id_p";
4279 DELETE FROM "delegating_voter"
4280 WHERE "issue_id" = "issue_id_p";
4281 DELETE FROM "direct_voter"
4282 WHERE "issue_id" = "issue_id_p";
4283 DELETE FROM "delegating_interest_snapshot"
4284 WHERE "issue_id" = "issue_id_p";
4285 DELETE FROM "direct_interest_snapshot"
4286 WHERE "issue_id" = "issue_id_p";
4287 DELETE FROM "delegating_population_snapshot"
4288 WHERE "issue_id" = "issue_id_p";
4289 DELETE FROM "direct_population_snapshot"
4290 WHERE "issue_id" = "issue_id_p";
4291 DELETE FROM "non_voter"
4292 WHERE "issue_id" = "issue_id_p";
4293 DELETE FROM "delegation"
4294 WHERE "issue_id" = "issue_id_p";
4295 DELETE FROM "supporter"
4296 WHERE "issue_id" = "issue_id_p";
4297 UPDATE "issue" SET
4298 "state" = "issue_row"."state",
4299 "closed" = "issue_row"."closed",
4300 "ranks_available" = "issue_row"."ranks_available",
4301 "cleaned" = now()
4302 WHERE "id" = "issue_id_p";
4303 END IF;
4304 RETURN;
4305 END;
4306 $$;
4308 COMMENT ON FUNCTION "clean_issue"("issue"."id"%TYPE) IS 'Delete discussion data and votes belonging to an issue';
4311 CREATE FUNCTION "delete_member"("member_id_p" "member"."id"%TYPE)
4312 RETURNS VOID
4313 LANGUAGE 'plpgsql' VOLATILE AS $$
4314 BEGIN
4315 UPDATE "member" SET
4316 "last_login" = NULL,
4317 "login" = NULL,
4318 "password" = NULL,
4319 "locked" = TRUE,
4320 "active" = FALSE,
4321 "notify_email" = NULL,
4322 "notify_email_unconfirmed" = NULL,
4323 "notify_email_secret" = NULL,
4324 "notify_email_secret_expiry" = NULL,
4325 "notify_email_lock_expiry" = NULL,
4326 "password_reset_secret" = NULL,
4327 "password_reset_secret_expiry" = NULL,
4328 "organizational_unit" = NULL,
4329 "internal_posts" = NULL,
4330 "realname" = NULL,
4331 "birthday" = NULL,
4332 "address" = NULL,
4333 "email" = NULL,
4334 "xmpp_address" = NULL,
4335 "website" = NULL,
4336 "phone" = NULL,
4337 "mobile_phone" = NULL,
4338 "profession" = NULL,
4339 "external_memberships" = NULL,
4340 "external_posts" = NULL,
4341 "statement" = NULL
4342 WHERE "id" = "member_id_p";
4343 -- "text_search_data" is updated by triggers
4344 DELETE FROM "setting" WHERE "member_id" = "member_id_p";
4345 DELETE FROM "setting_map" WHERE "member_id" = "member_id_p";
4346 DELETE FROM "member_relation_setting" WHERE "member_id" = "member_id_p";
4347 DELETE FROM "member_image" WHERE "member_id" = "member_id_p";
4348 DELETE FROM "contact" WHERE "member_id" = "member_id_p";
4349 DELETE FROM "ignored_member" WHERE "member_id" = "member_id_p";
4350 DELETE FROM "session" WHERE "member_id" = "member_id_p";
4351 DELETE FROM "area_setting" WHERE "member_id" = "member_id_p";
4352 DELETE FROM "issue_setting" WHERE "member_id" = "member_id_p";
4353 DELETE FROM "ignored_initiative" WHERE "member_id" = "member_id_p";
4354 DELETE FROM "initiative_setting" WHERE "member_id" = "member_id_p";
4355 DELETE FROM "suggestion_setting" WHERE "member_id" = "member_id_p";
4356 DELETE FROM "membership" WHERE "member_id" = "member_id_p";
4357 DELETE FROM "delegation" WHERE "truster_id" = "member_id_p";
4358 DELETE FROM "non_voter" WHERE "member_id" = "member_id_p";
4359 DELETE FROM "direct_voter" USING "issue"
4360 WHERE "direct_voter"."issue_id" = "issue"."id"
4361 AND "issue"."closed" ISNULL
4362 AND "member_id" = "member_id_p";
4363 RETURN;
4364 END;
4365 $$;
4367 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)';
4370 CREATE FUNCTION "delete_private_data"()
4371 RETURNS VOID
4372 LANGUAGE 'plpgsql' VOLATILE AS $$
4373 BEGIN
4374 DELETE FROM "member" WHERE "activated" ISNULL;
4375 UPDATE "member" SET
4376 "invite_code" = NULL,
4377 "invite_code_expiry" = NULL,
4378 "admin_comment" = NULL,
4379 "last_login" = NULL,
4380 "login" = NULL,
4381 "password" = NULL,
4382 "lang" = NULL,
4383 "notify_email" = NULL,
4384 "notify_email_unconfirmed" = NULL,
4385 "notify_email_secret" = NULL,
4386 "notify_email_secret_expiry" = NULL,
4387 "notify_email_lock_expiry" = NULL,
4388 "notify_level" = NULL,
4389 "password_reset_secret" = NULL,
4390 "password_reset_secret_expiry" = NULL,
4391 "organizational_unit" = NULL,
4392 "internal_posts" = NULL,
4393 "realname" = NULL,
4394 "birthday" = NULL,
4395 "address" = NULL,
4396 "email" = NULL,
4397 "xmpp_address" = NULL,
4398 "website" = NULL,
4399 "phone" = NULL,
4400 "mobile_phone" = NULL,
4401 "profession" = NULL,
4402 "external_memberships" = NULL,
4403 "external_posts" = NULL,
4404 "formatting_engine" = NULL,
4405 "statement" = NULL;
4406 -- "text_search_data" is updated by triggers
4407 DELETE FROM "setting";
4408 DELETE FROM "setting_map";
4409 DELETE FROM "member_relation_setting";
4410 DELETE FROM "member_image";
4411 DELETE FROM "contact";
4412 DELETE FROM "ignored_member";
4413 DELETE FROM "session";
4414 DELETE FROM "area_setting";
4415 DELETE FROM "issue_setting";
4416 DELETE FROM "ignored_initiative";
4417 DELETE FROM "initiative_setting";
4418 DELETE FROM "suggestion_setting";
4419 DELETE FROM "non_voter";
4420 DELETE FROM "direct_voter" USING "issue"
4421 WHERE "direct_voter"."issue_id" = "issue"."id"
4422 AND "issue"."closed" ISNULL;
4423 RETURN;
4424 END;
4425 $$;
4427 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. See source code to see which data is deleted. If you need a different behaviour, copy this function and modify lf_export accordingly, to avoid data-leaks after updating.';
4431 COMMIT;

Impressum / About Us