liquid_feedback_core

view core.sql @ 278:0a42a2600a2b

Included old API tables maked as "deprecated" to allow testing with alpha api and preliminary authorization interface after core update to v2.1
author jbe
date Fri Aug 10 21:39:50 2012 +0200 (2012-08-10)
parents 028a52d23e56
children 03897de17853
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 CREATE TYPE "application_access_level" AS ENUM
174 ('member', 'full', 'pseudonymous', 'anonymous');
176 COMMENT ON TYPE "application_access_level" IS 'DEPRECATED, WILL BE REMOVED! Access privileges for applications using the API';
179 CREATE TABLE "member_application" (
180 "id" SERIAL8 PRIMARY KEY,
181 UNIQUE ("member_id", "name"),
182 "member_id" INT4 NOT NULL REFERENCES "member" ("id")
183 ON DELETE CASCADE ON UPDATE CASCADE,
184 "name" TEXT NOT NULL,
185 "comment" TEXT,
186 "access_level" "application_access_level" NOT NULL,
187 "key" TEXT NOT NULL UNIQUE,
188 "last_usage" TIMESTAMPTZ );
190 COMMENT ON TABLE "member_application" IS 'DEPRECATED, WILL BE REMOVED! Registered application being allowed to use the API';
193 CREATE TYPE "api_access_level" AS ENUM (
194 'none', 'anonymous', 'authors_pseudonymous', 'all_pseudonymous', 'everything', 'member' );
196 COMMENT ON TYPE "api_access_level" IS 'PRELIMINARY, SUBJECT TO CHANGE! Access scope for API consumers.';
199 CREATE TABLE "api_client" (
200 "id" SERIAL8 PRIMARY KEY,
201 "name" TEXT,
202 UNIQUE ("member_id", "client_identifier"),
203 "member_id" INT4 REFERENCES "member" ("id")
204 ON DELETE CASCADE ON UPDATE CASCADE,
205 "client_identifier" TEXT NOT NULL,
206 "client_secret" TEXT,
207 "code_grant" BOOLEAN NOT NULL,
208 "implicit_grant" BOOLEAN NOT NULL,
209 "client_grant" BOOLEAN NOT NULL,
210 "code_grant_validity_period" INTERVAL,
211 "code_grant_multiple" BOOLEAN,
212 "access_level" "api_access_level",
213 "client_grant_access_level" "api_access_level",
214 "last_usage" TIMESTAMPTZ NOT NULL,
215 CONSTRAINT "system_clients_require_name"
216 CHECK ("name" NOTNULL OR "member_id" ISNULL),
217 CONSTRAINT "code_grant_requires_validity_period"
218 CHECK ("code_grant"=FALSE OR "code_grant_validity_period" NOTNULL),
219 CONSTRAINT "code_or_implicit_grant_requires_access_level"
220 CHECK (("code_grant"=FALSE AND "implicit_grant"=FALSE) OR "access_level" NOTNULL),
221 CONSTRAINT "client_grant_requires_client_grant_access_level"
222 CHECK ("client_grant"=FALSE OR "client_grant_access_level" NOTNULL) );
223 CREATE UNIQUE INDEX "api_client_non_member_client_identifier_idx"
224 ON "api_client" ("client_identifier") WHERE "member_id" ISNULL;
226 COMMENT ON TABLE "api_client" IS 'PRELIMINARY, SUBJECT TO CHANGE! Registered OAuth2 client for a member';
228 COMMENT ON COLUMN "api_client"."name" IS 'Name of the client as chosen by member or administrator, NULL is allowed for unnamed member-registered clients';
229 COMMENT ON COLUMN "api_client"."member_id" IS 'Member, who registered the client for him/herself, or NULL for clients registered by administrator';
230 COMMENT ON COLUMN "api_client"."client_identifier" IS 'OAuth2 client id, also used as redirection endpoint if "code_grant" or "implicit_grant" is set to TRUE';
231 COMMENT ON COLUMN "api_client"."client_secret" IS 'Secret for client authentication';
232 COMMENT ON COLUMN "api_client"."code_grant" IS 'Enable OAuth2 Authorization Code Grant';
233 COMMENT ON COLUMN "api_client"."implicit_grant" IS 'Enable OAuth2 Implicit Grant';
234 COMMENT ON COLUMN "api_client"."client_grant" IS 'Enable OAuth2 Client Credentials Grant';
235 COMMENT ON COLUMN "api_client"."code_grant_validity_period" IS 'Maximum validity period of OAuth2 Authorization Code Grant, after which no more refresh is possible';
236 COMMENT ON COLUMN "api_client"."code_grant_multiple" IS 'If set to FALSE, invalidates previously issued OAuth2 Refresh Tokens during authorization; If set to NULL, the member is asked interactively during authorization, whether previously issued authorizations shall be revoked';
237 COMMENT ON COLUMN "api_client"."access_level" IS 'Maximum access level for OAuth2 Authorization Code Grant and Implicit Grant';
238 COMMENT ON COLUMN "api_client"."client_grant_access_level" IS 'Maximum access level for OAuth2 Authorization Code Grant and Implicit Grant';
239 COMMENT ON COLUMN "api_client"."last_usage" IS 'Date/time when this client registration was last used';
242 CREATE TABLE "api_code_grant" (
243 "id" SERIAL8 PRIMARY KEY,
244 "api_client_id" INT8 NOT NULL REFERENCES "api_client" ("id")
245 ON DELETE CASCADE ON UPDATE CASCADE,
246 "member_id" INT4 REFERENCES "member" ("id")
247 ON DELETE CASCADE ON UPDATE CASCADE,
248 "access_level" "api_access_level" NOT NULL,
249 "validity_period" INTERVAL NOT NULL,
250 "created" TIMESTAMPTZ NOT NULL DEFAULT now(),
251 "authorization_code" TEXT,
252 "refreshed" TIMESTAMPTZ,
253 "refresh_token" TEXT,
254 "old_refresh_token" TEXT,
255 CONSTRAINT "one_of_authorization_code_and_refresh_token_set"
256 CHECK ("authorization_code" NOTNULL OR "refresh_token" NOTNULL),
257 CONSTRAINT "refresh_token_if_and_only_if_refreshed"
258 CHECK ("refreshed" NOTNULL = "refresh_token" NOTNULL),
259 CONSTRAINT "old_refresh_token_requires_current_refresh_token"
260 CHECK ("refresh_token" NOTNULL OR "old_refresh_token" ISNULL) );
262 COMMENT ON TABLE "api_code_grant" IS 'PRELIMINARY, SUBJECT TO CHANGE! Issued OAuth2 authorization codes and refresh tokens';
264 COMMENT ON COLUMN "api_code_grant"."validity_period" IS 'Period after which no more refreshing is possible';
265 COMMENT ON COLUMN "api_code_grant"."created" IS 'Date/time when authorization code (or first refresh token when there is no authorization code) has been created';
266 COMMENT ON COLUMN "api_code_grant"."authorization_code" IS 'OAuth2 authorization code (only valid for a very short time after it has been created)';
267 COMMENT ON COLUMN "api_code_grant"."refreshed" IS 'Date/time of last refresh';
268 COMMENT ON COLUMN "api_code_grant"."refresh_token" IS 'OAuth2 refresh token';
271 CREATE TABLE "member_history" (
272 "id" SERIAL8 PRIMARY KEY,
273 "member_id" INT4 NOT NULL REFERENCES "member" ("id") ON DELETE CASCADE ON UPDATE CASCADE,
274 "until" TIMESTAMPTZ NOT NULL DEFAULT now(),
275 "active" BOOLEAN NOT NULL,
276 "name" TEXT NOT NULL );
277 CREATE INDEX "member_history_member_id_idx" ON "member_history" ("member_id");
279 COMMENT ON TABLE "member_history" IS 'Filled by trigger; keeps information about old names and active flag of members';
281 COMMENT ON COLUMN "member_history"."id" IS 'Primary key, which can be used to sort entries correctly (and time warp resistant)';
282 COMMENT ON COLUMN "member_history"."until" IS 'Timestamp until the data was valid';
285 CREATE TABLE "rendered_member_statement" (
286 PRIMARY KEY ("member_id", "format"),
287 "member_id" INT8 REFERENCES "member" ("id") ON DELETE CASCADE ON UPDATE CASCADE,
288 "format" TEXT,
289 "content" TEXT NOT NULL );
291 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)';
294 CREATE TABLE "setting" (
295 PRIMARY KEY ("member_id", "key"),
296 "member_id" INT4 REFERENCES "member" ("id") ON DELETE CASCADE ON UPDATE CASCADE,
297 "key" TEXT NOT NULL,
298 "value" TEXT NOT NULL );
299 CREATE INDEX "setting_key_idx" ON "setting" ("key");
301 COMMENT ON TABLE "setting" IS 'Place to store a frontend specific setting for members as a string';
303 COMMENT ON COLUMN "setting"."key" IS 'Name of the setting, preceded by a frontend specific prefix';
306 CREATE TABLE "setting_map" (
307 PRIMARY KEY ("member_id", "key", "subkey"),
308 "member_id" INT4 REFERENCES "member" ("id") ON DELETE CASCADE ON UPDATE CASCADE,
309 "key" TEXT NOT NULL,
310 "subkey" TEXT NOT NULL,
311 "value" TEXT NOT NULL );
312 CREATE INDEX "setting_map_key_idx" ON "setting_map" ("key");
314 COMMENT ON TABLE "setting_map" IS 'Place to store a frontend specific setting for members as a map of key value pairs';
316 COMMENT ON COLUMN "setting_map"."key" IS 'Name of the setting, preceded by a frontend specific prefix';
317 COMMENT ON COLUMN "setting_map"."subkey" IS 'Key of a map entry';
318 COMMENT ON COLUMN "setting_map"."value" IS 'Value of a map entry';
321 CREATE TABLE "member_relation_setting" (
322 PRIMARY KEY ("member_id", "key", "other_member_id"),
323 "member_id" INT4 REFERENCES "member" ("id") ON DELETE CASCADE ON UPDATE CASCADE,
324 "key" TEXT NOT NULL,
325 "other_member_id" INT4 REFERENCES "member" ("id") ON DELETE CASCADE ON UPDATE CASCADE,
326 "value" TEXT NOT NULL );
328 COMMENT ON TABLE "member_relation_setting" IS 'Place to store a frontend specific setting related to relations between members as a string';
331 CREATE TYPE "member_image_type" AS ENUM ('photo', 'avatar');
333 COMMENT ON TYPE "member_image_type" IS 'Types of images for a member';
336 CREATE TABLE "member_image" (
337 PRIMARY KEY ("member_id", "image_type", "scaled"),
338 "member_id" INT4 REFERENCES "member" ("id") ON DELETE CASCADE ON UPDATE CASCADE,
339 "image_type" "member_image_type",
340 "scaled" BOOLEAN,
341 "content_type" TEXT,
342 "data" BYTEA NOT NULL );
344 COMMENT ON TABLE "member_image" IS 'Images of members';
346 COMMENT ON COLUMN "member_image"."scaled" IS 'FALSE for original image, TRUE for scaled version of the image';
349 CREATE TABLE "member_count" (
350 "calculated" TIMESTAMPTZ NOT NULL DEFAULT NOW(),
351 "total_count" INT4 NOT NULL );
353 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';
355 COMMENT ON COLUMN "member_count"."calculated" IS 'timestamp indicating when the total member count and area member counts were calculated';
356 COMMENT ON COLUMN "member_count"."total_count" IS 'Total count of active(!) members';
359 CREATE TABLE "contact" (
360 PRIMARY KEY ("member_id", "other_member_id"),
361 "member_id" INT4 REFERENCES "member" ("id") ON DELETE CASCADE ON UPDATE CASCADE,
362 "other_member_id" INT4 REFERENCES "member" ("id") ON DELETE CASCADE ON UPDATE CASCADE,
363 "public" BOOLEAN NOT NULL DEFAULT FALSE,
364 CONSTRAINT "cant_save_yourself_as_contact"
365 CHECK ("member_id" != "other_member_id") );
366 CREATE INDEX "contact_other_member_id_idx" ON "contact" ("other_member_id");
368 COMMENT ON TABLE "contact" IS 'Contact lists';
370 COMMENT ON COLUMN "contact"."member_id" IS 'Member having the contact list';
371 COMMENT ON COLUMN "contact"."other_member_id" IS 'Member referenced in the contact list';
372 COMMENT ON COLUMN "contact"."public" IS 'TRUE = display contact publically';
375 CREATE TABLE "ignored_member" (
376 PRIMARY KEY ("member_id", "other_member_id"),
377 "member_id" INT4 REFERENCES "member" ("id") ON DELETE CASCADE ON UPDATE CASCADE,
378 "other_member_id" INT4 REFERENCES "member" ("id") ON DELETE CASCADE ON UPDATE CASCADE );
379 CREATE INDEX "ignored_member_other_member_id_idx" ON "ignored_member" ("other_member_id");
381 COMMENT ON TABLE "ignored_member" IS 'Possibility to filter other members';
383 COMMENT ON COLUMN "ignored_member"."member_id" IS 'Member ignoring someone';
384 COMMENT ON COLUMN "ignored_member"."other_member_id" IS 'Member being ignored';
387 CREATE TABLE "session" (
388 "ident" TEXT PRIMARY KEY,
389 "additional_secret" TEXT,
390 "expiry" TIMESTAMPTZ NOT NULL DEFAULT now() + '24 hours',
391 "member_id" INT8 REFERENCES "member" ("id") ON DELETE SET NULL,
392 "lang" TEXT );
393 CREATE INDEX "session_expiry_idx" ON "session" ("expiry");
395 COMMENT ON TABLE "session" IS 'Sessions, i.e. for a web-frontend or API layer';
397 COMMENT ON COLUMN "session"."ident" IS 'Secret session identifier (i.e. random string)';
398 COMMENT ON COLUMN "session"."additional_secret" IS 'Additional field to store a secret, which can be used against CSRF attacks';
399 COMMENT ON COLUMN "session"."member_id" IS 'Reference to member, who is logged in';
400 COMMENT ON COLUMN "session"."lang" IS 'Language code of the selected language';
403 CREATE TABLE "policy" (
404 "id" SERIAL4 PRIMARY KEY,
405 "index" INT4 NOT NULL,
406 "active" BOOLEAN NOT NULL DEFAULT TRUE,
407 "name" TEXT NOT NULL UNIQUE,
408 "description" TEXT NOT NULL DEFAULT '',
409 "polling" BOOLEAN NOT NULL DEFAULT FALSE,
410 "admission_time" INTERVAL,
411 "discussion_time" INTERVAL,
412 "verification_time" INTERVAL,
413 "voting_time" INTERVAL,
414 "issue_quorum_num" INT4 NOT NULL,
415 "issue_quorum_den" INT4 NOT NULL,
416 "initiative_quorum_num" INT4 NOT NULL,
417 "initiative_quorum_den" INT4 NOT NULL,
418 "direct_majority_num" INT4 NOT NULL DEFAULT 1,
419 "direct_majority_den" INT4 NOT NULL DEFAULT 2,
420 "direct_majority_strict" BOOLEAN NOT NULL DEFAULT TRUE,
421 "direct_majority_positive" INT4 NOT NULL DEFAULT 0,
422 "direct_majority_non_negative" INT4 NOT NULL DEFAULT 0,
423 "indirect_majority_num" INT4 NOT NULL DEFAULT 1,
424 "indirect_majority_den" INT4 NOT NULL DEFAULT 2,
425 "indirect_majority_strict" BOOLEAN NOT NULL DEFAULT TRUE,
426 "indirect_majority_positive" INT4 NOT NULL DEFAULT 0,
427 "indirect_majority_non_negative" INT4 NOT NULL DEFAULT 0,
428 "no_reverse_beat_path" BOOLEAN NOT NULL DEFAULT TRUE,
429 "no_multistage_majority" BOOLEAN NOT NULL DEFAULT FALSE,
430 CONSTRAINT "timing" CHECK (
431 ( "polling" = FALSE AND
432 "admission_time" NOTNULL AND "discussion_time" NOTNULL AND
433 "verification_time" NOTNULL AND "voting_time" NOTNULL ) OR
434 ( "polling" = TRUE AND
435 "admission_time" ISNULL AND "discussion_time" NOTNULL AND
436 "verification_time" NOTNULL AND "voting_time" NOTNULL ) OR
437 ( "polling" = TRUE AND
438 "admission_time" ISNULL AND "discussion_time" ISNULL AND
439 "verification_time" ISNULL AND "voting_time" ISNULL ) ) );
440 CREATE INDEX "policy_active_idx" ON "policy" ("active");
442 COMMENT ON TABLE "policy" IS 'Policies for a particular proceeding type (timelimits, quorum)';
444 COMMENT ON COLUMN "policy"."index" IS 'Determines the order in listings';
445 COMMENT ON COLUMN "policy"."active" IS 'TRUE = policy can be used for new issues';
446 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)';
447 COMMENT ON COLUMN "policy"."admission_time" IS 'Maximum duration of issue state ''admission''; Maximum time an issue stays open without being "accepted"';
448 COMMENT ON COLUMN "policy"."discussion_time" IS 'Duration of issue state ''discussion''; Regular time until an issue is "half_frozen" after being "accepted"';
449 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"';
450 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'')';
451 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''';
452 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''';
453 COMMENT ON COLUMN "policy"."initiative_quorum_num" IS 'Numerator of satisfied supporter quorum to be reached by an initiative to be "admitted" for voting';
454 COMMENT ON COLUMN "policy"."initiative_quorum_den" IS 'Denominator of satisfied supporter quorum to be reached by an initiative to be "admitted" for voting';
455 COMMENT ON COLUMN "policy"."direct_majority_num" IS 'Numerator of fraction of neccessary direct majority for initiatives to be attainable as winner';
456 COMMENT ON COLUMN "policy"."direct_majority_den" IS 'Denominator of fraction of neccessary direct majority for initaitives to be attainable as winner';
457 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.';
458 COMMENT ON COLUMN "policy"."direct_majority_positive" IS 'Absolute number of "positive_votes" neccessary for an initiative to be attainable as winner';
459 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';
460 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';
461 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';
462 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.';
463 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';
464 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';
465 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.';
466 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").';
469 CREATE TABLE "unit" (
470 "id" SERIAL4 PRIMARY KEY,
471 "parent_id" INT4 REFERENCES "unit" ("id") ON DELETE CASCADE ON UPDATE CASCADE,
472 "active" BOOLEAN NOT NULL DEFAULT TRUE,
473 "name" TEXT NOT NULL,
474 "description" TEXT NOT NULL DEFAULT '',
475 "member_count" INT4,
476 "text_search_data" TSVECTOR );
477 CREATE INDEX "unit_root_idx" ON "unit" ("id") WHERE "parent_id" ISNULL;
478 CREATE INDEX "unit_parent_id_idx" ON "unit" ("parent_id");
479 CREATE INDEX "unit_active_idx" ON "unit" ("active");
480 CREATE INDEX "unit_text_search_data_idx" ON "unit" USING gin ("text_search_data");
481 CREATE TRIGGER "update_text_search_data"
482 BEFORE INSERT OR UPDATE ON "unit"
483 FOR EACH ROW EXECUTE PROCEDURE
484 tsvector_update_trigger('text_search_data', 'pg_catalog.simple',
485 "name", "description" );
487 COMMENT ON TABLE "unit" IS 'Organizational units organized as trees; Delegations are not inherited through these trees.';
489 COMMENT ON COLUMN "unit"."parent_id" IS 'Parent id of tree node; Multiple roots allowed';
490 COMMENT ON COLUMN "unit"."active" IS 'TRUE means new issues can be created in areas of this unit';
491 COMMENT ON COLUMN "unit"."member_count" IS 'Count of members as determined by column "voting_right" in table "privilege"';
494 CREATE TABLE "unit_setting" (
495 PRIMARY KEY ("member_id", "key", "unit_id"),
496 "member_id" INT4 REFERENCES "member" ("id") ON DELETE CASCADE ON UPDATE CASCADE,
497 "key" TEXT NOT NULL,
498 "unit_id" INT4 REFERENCES "unit" ("id") ON DELETE CASCADE ON UPDATE CASCADE,
499 "value" TEXT NOT NULL );
501 COMMENT ON TABLE "unit_setting" IS 'Place for frontend to store unit specific settings of members as strings';
504 CREATE TABLE "area" (
505 "id" SERIAL4 PRIMARY KEY,
506 "unit_id" INT4 NOT NULL REFERENCES "unit" ("id") ON DELETE CASCADE ON UPDATE CASCADE,
507 "active" BOOLEAN NOT NULL DEFAULT TRUE,
508 "name" TEXT NOT NULL,
509 "description" TEXT NOT NULL DEFAULT '',
510 "direct_member_count" INT4,
511 "member_weight" INT4,
512 "text_search_data" TSVECTOR );
513 CREATE INDEX "area_unit_id_idx" ON "area" ("unit_id");
514 CREATE INDEX "area_active_idx" ON "area" ("active");
515 CREATE INDEX "area_text_search_data_idx" ON "area" USING gin ("text_search_data");
516 CREATE TRIGGER "update_text_search_data"
517 BEFORE INSERT OR UPDATE ON "area"
518 FOR EACH ROW EXECUTE PROCEDURE
519 tsvector_update_trigger('text_search_data', 'pg_catalog.simple',
520 "name", "description" );
522 COMMENT ON TABLE "area" IS 'Subject areas';
524 COMMENT ON COLUMN "area"."active" IS 'TRUE means new issues can be created in this area';
525 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"';
526 COMMENT ON COLUMN "area"."member_weight" IS 'Same as "direct_member_count" but respecting delegations';
529 CREATE TABLE "area_setting" (
530 PRIMARY KEY ("member_id", "key", "area_id"),
531 "member_id" INT4 REFERENCES "member" ("id") ON DELETE CASCADE ON UPDATE CASCADE,
532 "key" TEXT NOT NULL,
533 "area_id" INT4 REFERENCES "area" ("id") ON DELETE CASCADE ON UPDATE CASCADE,
534 "value" TEXT NOT NULL );
536 COMMENT ON TABLE "area_setting" IS 'Place for frontend to store area specific settings of members as strings';
539 CREATE TABLE "allowed_policy" (
540 PRIMARY KEY ("area_id", "policy_id"),
541 "area_id" INT4 REFERENCES "area" ("id") ON DELETE CASCADE ON UPDATE CASCADE,
542 "policy_id" INT4 NOT NULL REFERENCES "policy" ("id") ON DELETE CASCADE ON UPDATE CASCADE,
543 "default_policy" BOOLEAN NOT NULL DEFAULT FALSE );
544 CREATE UNIQUE INDEX "allowed_policy_one_default_per_area_idx" ON "allowed_policy" ("area_id") WHERE "default_policy";
546 COMMENT ON TABLE "allowed_policy" IS 'Selects which policies can be used in each area';
548 COMMENT ON COLUMN "allowed_policy"."default_policy" IS 'One policy per area can be set as default.';
551 CREATE TYPE "snapshot_event" AS ENUM ('periodic', 'end_of_admission', 'half_freeze', 'full_freeze');
553 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';
556 CREATE TYPE "issue_state" AS ENUM (
557 'admission', 'discussion', 'verification', 'voting',
558 'canceled_revoked_before_accepted',
559 'canceled_issue_not_accepted',
560 'canceled_after_revocation_during_discussion',
561 'canceled_after_revocation_during_verification',
562 'calculation',
563 'canceled_no_initiative_admitted',
564 'finished_without_winner', 'finished_with_winner');
566 COMMENT ON TYPE "issue_state" IS 'State of issues';
569 CREATE TABLE "issue" (
570 "id" SERIAL4 PRIMARY KEY,
571 "area_id" INT4 NOT NULL REFERENCES "area" ("id") ON DELETE CASCADE ON UPDATE CASCADE,
572 "policy_id" INT4 NOT NULL REFERENCES "policy" ("id") ON DELETE RESTRICT ON UPDATE CASCADE,
573 "state" "issue_state" NOT NULL DEFAULT 'admission',
574 "created" TIMESTAMPTZ NOT NULL DEFAULT now(),
575 "accepted" TIMESTAMPTZ,
576 "half_frozen" TIMESTAMPTZ,
577 "fully_frozen" TIMESTAMPTZ,
578 "closed" TIMESTAMPTZ,
579 "ranks_available" BOOLEAN NOT NULL DEFAULT FALSE,
580 "cleaned" TIMESTAMPTZ,
581 "admission_time" INTERVAL NOT NULL,
582 "discussion_time" INTERVAL NOT NULL,
583 "verification_time" INTERVAL NOT NULL,
584 "voting_time" INTERVAL NOT NULL,
585 "snapshot" TIMESTAMPTZ,
586 "latest_snapshot_event" "snapshot_event",
587 "population" INT4,
588 "voter_count" INT4,
589 "status_quo_schulze_rank" INT4,
590 CONSTRAINT "valid_state" CHECK ((
591 ("accepted" ISNULL AND "half_frozen" ISNULL AND "fully_frozen" ISNULL AND "closed" ISNULL AND "ranks_available" = FALSE) OR
592 ("accepted" ISNULL AND "half_frozen" ISNULL AND "fully_frozen" ISNULL AND "closed" NOTNULL AND "ranks_available" = FALSE) OR
593 ("accepted" NOTNULL AND "half_frozen" ISNULL AND "fully_frozen" ISNULL AND "closed" ISNULL AND "ranks_available" = FALSE) OR
594 ("accepted" NOTNULL AND "half_frozen" ISNULL AND "fully_frozen" ISNULL AND "closed" NOTNULL AND "ranks_available" = FALSE) OR
595 ("accepted" NOTNULL AND "half_frozen" NOTNULL AND "fully_frozen" ISNULL AND "closed" ISNULL AND "ranks_available" = FALSE) OR
596 ("accepted" NOTNULL AND "half_frozen" NOTNULL AND "fully_frozen" ISNULL AND "closed" NOTNULL AND "ranks_available" = FALSE) OR
597 ("accepted" NOTNULL AND "half_frozen" NOTNULL AND "fully_frozen" NOTNULL AND "closed" ISNULL AND "ranks_available" = FALSE) OR
598 ("accepted" NOTNULL AND "half_frozen" NOTNULL AND "fully_frozen" NOTNULL AND "closed" NOTNULL AND "ranks_available" = FALSE) OR
599 ("accepted" NOTNULL AND "half_frozen" NOTNULL AND "fully_frozen" NOTNULL AND "closed" NOTNULL AND "ranks_available" = TRUE)) AND (
600 ("state" = 'admission' AND "closed" ISNULL AND "accepted" ISNULL) OR
601 ("state" = 'discussion' AND "closed" ISNULL AND "accepted" NOTNULL AND "half_frozen" ISNULL) OR
602 ("state" = 'verification' AND "closed" ISNULL AND "half_frozen" NOTNULL AND "fully_frozen" ISNULL) OR
603 ("state" = 'voting' AND "closed" ISNULL AND "fully_frozen" NOTNULL) OR
604 ("state" = 'canceled_revoked_before_accepted' AND "closed" NOTNULL AND "accepted" ISNULL) OR
605 ("state" = 'canceled_issue_not_accepted' AND "closed" NOTNULL AND "accepted" ISNULL) OR
606 ("state" = 'canceled_after_revocation_during_discussion' AND "closed" NOTNULL AND "half_frozen" ISNULL) OR
607 ("state" = 'canceled_after_revocation_during_verification' AND "closed" NOTNULL AND "fully_frozen" ISNULL) OR
608 ("state" = 'calculation' AND "closed" NOTNULL AND "fully_frozen" NOTNULL AND "ranks_available" = FALSE) OR
609 ("state" = 'canceled_no_initiative_admitted' AND "closed" NOTNULL AND "fully_frozen" NOTNULL AND "ranks_available" = TRUE) OR
610 ("state" = 'finished_without_winner' AND "closed" NOTNULL AND "fully_frozen" NOTNULL AND "ranks_available" = TRUE) OR
611 ("state" = 'finished_with_winner' AND "closed" NOTNULL AND "fully_frozen" NOTNULL AND "ranks_available" = TRUE)
612 )),
613 CONSTRAINT "state_change_order" CHECK (
614 "created" <= "accepted" AND
615 "accepted" <= "half_frozen" AND
616 "half_frozen" <= "fully_frozen" AND
617 "fully_frozen" <= "closed" ),
618 CONSTRAINT "only_closed_issues_may_be_cleaned" CHECK (
619 "cleaned" ISNULL OR "closed" NOTNULL ),
620 CONSTRAINT "last_snapshot_on_full_freeze"
621 CHECK ("snapshot" = "fully_frozen"), -- NOTE: snapshot can be set, while frozen is NULL yet
622 CONSTRAINT "freeze_requires_snapshot"
623 CHECK ("fully_frozen" ISNULL OR "snapshot" NOTNULL),
624 CONSTRAINT "set_both_or_none_of_snapshot_and_latest_snapshot_event"
625 CHECK ("snapshot" NOTNULL = "latest_snapshot_event" NOTNULL) );
626 CREATE INDEX "issue_area_id_idx" ON "issue" ("area_id");
627 CREATE INDEX "issue_policy_id_idx" ON "issue" ("policy_id");
628 CREATE INDEX "issue_created_idx" ON "issue" ("created");
629 CREATE INDEX "issue_accepted_idx" ON "issue" ("accepted");
630 CREATE INDEX "issue_half_frozen_idx" ON "issue" ("half_frozen");
631 CREATE INDEX "issue_fully_frozen_idx" ON "issue" ("fully_frozen");
632 CREATE INDEX "issue_closed_idx" ON "issue" ("closed");
633 CREATE INDEX "issue_created_idx_open" ON "issue" ("created") WHERE "closed" ISNULL;
634 CREATE INDEX "issue_closed_idx_canceled" ON "issue" ("closed") WHERE "fully_frozen" ISNULL;
636 COMMENT ON TABLE "issue" IS 'Groups of initiatives';
638 COMMENT ON COLUMN "issue"."accepted" IS 'Point in time, when one initiative of issue reached the "issue_quorum"';
639 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.';
640 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.';
641 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.';
642 COMMENT ON COLUMN "issue"."ranks_available" IS 'TRUE = ranks have been calculated';
643 COMMENT ON COLUMN "issue"."cleaned" IS 'Point in time, when discussion data and votes had been deleted';
644 COMMENT ON COLUMN "issue"."admission_time" IS 'Copied from "policy" table at creation of issue';
645 COMMENT ON COLUMN "issue"."discussion_time" IS 'Copied from "policy" table at creation of issue';
646 COMMENT ON COLUMN "issue"."verification_time" IS 'Copied from "policy" table at creation of issue';
647 COMMENT ON COLUMN "issue"."voting_time" IS 'Copied from "policy" table at creation of issue';
648 COMMENT ON COLUMN "issue"."snapshot" IS 'Point in time, when snapshot tables have been updated and "population" and *_count values were precalculated';
649 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';
650 COMMENT ON COLUMN "issue"."population" IS 'Sum of "weight" column in table "direct_population_snapshot"';
651 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';
652 COMMENT ON COLUMN "issue"."status_quo_schulze_rank" IS 'Schulze rank of status quo, as calculated by "calculate_ranks" function';
655 CREATE TABLE "issue_setting" (
656 PRIMARY KEY ("member_id", "key", "issue_id"),
657 "member_id" INT4 REFERENCES "member" ("id") ON DELETE CASCADE ON UPDATE CASCADE,
658 "key" TEXT NOT NULL,
659 "issue_id" INT4 REFERENCES "issue" ("id") ON DELETE CASCADE ON UPDATE CASCADE,
660 "value" TEXT NOT NULL );
662 COMMENT ON TABLE "issue_setting" IS 'Place for frontend to store issue specific settings of members as strings';
665 CREATE TABLE "initiative" (
666 UNIQUE ("issue_id", "id"), -- index needed for foreign-key on table "vote"
667 "issue_id" INT4 NOT NULL REFERENCES "issue" ("id") ON DELETE CASCADE ON UPDATE CASCADE,
668 "id" SERIAL4 PRIMARY KEY,
669 "name" TEXT NOT NULL,
670 "polling" BOOLEAN NOT NULL DEFAULT FALSE,
671 "discussion_url" TEXT,
672 "created" TIMESTAMPTZ NOT NULL DEFAULT now(),
673 "revoked" TIMESTAMPTZ,
674 "revoked_by_member_id" INT4 REFERENCES "member" ("id") ON DELETE RESTRICT ON UPDATE CASCADE,
675 "suggested_initiative_id" INT4 REFERENCES "initiative" ("id") ON DELETE CASCADE ON UPDATE CASCADE,
676 "admitted" BOOLEAN,
677 "supporter_count" INT4,
678 "informed_supporter_count" INT4,
679 "satisfied_supporter_count" INT4,
680 "satisfied_informed_supporter_count" INT4,
681 "positive_votes" INT4,
682 "negative_votes" INT4,
683 "direct_majority" BOOLEAN,
684 "indirect_majority" BOOLEAN,
685 "schulze_rank" INT4,
686 "better_than_status_quo" BOOLEAN,
687 "worse_than_status_quo" BOOLEAN,
688 "reverse_beat_path" BOOLEAN,
689 "multistage_majority" BOOLEAN,
690 "eligible" BOOLEAN,
691 "winner" BOOLEAN,
692 "rank" INT4,
693 "text_search_data" TSVECTOR,
694 CONSTRAINT "all_or_none_of_revoked_and_revoked_by_member_id_must_be_null"
695 CHECK ("revoked" NOTNULL = "revoked_by_member_id" NOTNULL),
696 CONSTRAINT "non_revoked_initiatives_cant_suggest_other"
697 CHECK ("revoked" NOTNULL OR "suggested_initiative_id" ISNULL),
698 CONSTRAINT "revoked_initiatives_cant_be_admitted"
699 CHECK ("revoked" ISNULL OR "admitted" ISNULL),
700 CONSTRAINT "non_admitted_initiatives_cant_contain_voting_results" CHECK (
701 ( "admitted" NOTNULL AND "admitted" = TRUE ) OR
702 ( "positive_votes" ISNULL AND "negative_votes" ISNULL AND
703 "direct_majority" ISNULL AND "indirect_majority" ISNULL AND
704 "schulze_rank" ISNULL AND
705 "better_than_status_quo" ISNULL AND "worse_than_status_quo" ISNULL AND
706 "reverse_beat_path" ISNULL AND "multistage_majority" ISNULL AND
707 "eligible" ISNULL AND "winner" ISNULL AND "rank" ISNULL ) ),
708 CONSTRAINT "better_excludes_worse" CHECK (NOT ("better_than_status_quo" AND "worse_than_status_quo")),
709 CONSTRAINT "minimum_requirement_to_be_eligible" CHECK (
710 "eligible" = FALSE OR
711 ("direct_majority" AND "indirect_majority" AND "better_than_status_quo") ),
712 CONSTRAINT "winner_must_be_eligible" CHECK ("winner"=FALSE OR "eligible"=TRUE),
713 CONSTRAINT "winner_must_have_first_rank" CHECK ("winner"=FALSE OR "rank"=1),
714 CONSTRAINT "eligible_at_first_rank_is_winner" CHECK ("eligible"=FALSE OR "rank"!=1 OR "winner"=TRUE),
715 CONSTRAINT "unique_rank_per_issue" UNIQUE ("issue_id", "rank") );
716 CREATE INDEX "initiative_created_idx" ON "initiative" ("created");
717 CREATE INDEX "initiative_revoked_idx" ON "initiative" ("revoked");
718 CREATE INDEX "initiative_text_search_data_idx" ON "initiative" USING gin ("text_search_data");
719 CREATE TRIGGER "update_text_search_data"
720 BEFORE INSERT OR UPDATE ON "initiative"
721 FOR EACH ROW EXECUTE PROCEDURE
722 tsvector_update_trigger('text_search_data', 'pg_catalog.simple',
723 "name", "discussion_url");
725 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.';
727 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';
728 COMMENT ON COLUMN "initiative"."discussion_url" IS 'URL pointing to a discussion platform for this initiative';
729 COMMENT ON COLUMN "initiative"."revoked" IS 'Point in time, when one initiator decided to revoke the initiative';
730 COMMENT ON COLUMN "initiative"."revoked_by_member_id" IS 'Member, who decided to revoke the initiative';
731 COMMENT ON COLUMN "initiative"."admitted" IS 'TRUE, if initiative reaches the "initiative_quorum" when freezing the issue';
732 COMMENT ON COLUMN "initiative"."supporter_count" IS 'Calculated from table "direct_supporter_snapshot"';
733 COMMENT ON COLUMN "initiative"."informed_supporter_count" IS 'Calculated from table "direct_supporter_snapshot"';
734 COMMENT ON COLUMN "initiative"."satisfied_supporter_count" IS 'Calculated from table "direct_supporter_snapshot"';
735 COMMENT ON COLUMN "initiative"."satisfied_informed_supporter_count" IS 'Calculated from table "direct_supporter_snapshot"';
736 COMMENT ON COLUMN "initiative"."positive_votes" IS 'Calculated from table "direct_voter"';
737 COMMENT ON COLUMN "initiative"."negative_votes" IS 'Calculated from table "direct_voter"';
738 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"';
739 COMMENT ON COLUMN "initiative"."indirect_majority" IS 'Same as "direct_majority", but also considering indirect beat paths';
740 COMMENT ON COLUMN "initiative"."schulze_rank" IS 'Schulze-Ranking without tie-breaking';
741 COMMENT ON COLUMN "initiative"."better_than_status_quo" IS 'TRUE, if initiative has a schulze-ranking better than the status quo (without tie-breaking)';
742 COMMENT ON COLUMN "initiative"."worse_than_status_quo" IS 'TRUE, if initiative has a schulze-ranking worse than the status quo (without tie-breaking)';
743 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';
744 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';
745 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"';
746 COMMENT ON COLUMN "initiative"."winner" IS 'Winner is the "eligible" initiative with best "schulze_rank" and in case of ties with lowest "id"';
747 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';
750 CREATE TABLE "battle" (
751 "issue_id" INT4 NOT NULL,
752 "winning_initiative_id" INT4,
753 FOREIGN KEY ("issue_id", "winning_initiative_id") REFERENCES "initiative" ("issue_id", "id") ON DELETE CASCADE ON UPDATE CASCADE,
754 "losing_initiative_id" INT4,
755 FOREIGN KEY ("issue_id", "losing_initiative_id") REFERENCES "initiative" ("issue_id", "id") ON DELETE CASCADE ON UPDATE CASCADE,
756 "count" INT4 NOT NULL,
757 CONSTRAINT "initiative_ids_not_equal" CHECK (
758 "winning_initiative_id" != "losing_initiative_id" OR
759 ( ("winning_initiative_id" NOTNULL AND "losing_initiative_id" ISNULL) OR
760 ("winning_initiative_id" ISNULL AND "losing_initiative_id" NOTNULL) ) ) );
761 CREATE UNIQUE INDEX "battle_winning_losing_idx" ON "battle" ("issue_id", "winning_initiative_id", "losing_initiative_id");
762 CREATE UNIQUE INDEX "battle_winning_null_idx" ON "battle" ("issue_id", "winning_initiative_id") WHERE "losing_initiative_id" ISNULL;
763 CREATE UNIQUE INDEX "battle_null_losing_idx" ON "battle" ("issue_id", "losing_initiative_id") WHERE "winning_initiative_id" ISNULL;
765 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';
768 CREATE TABLE "ignored_initiative" (
769 PRIMARY KEY ("initiative_id", "member_id"),
770 "initiative_id" INT4 REFERENCES "initiative" ("id") ON DELETE CASCADE ON UPDATE CASCADE,
771 "member_id" INT4 REFERENCES "member" ("id") ON DELETE CASCADE ON UPDATE CASCADE );
772 CREATE INDEX "ignored_initiative_member_id_idx" ON "ignored_initiative" ("member_id");
774 COMMENT ON TABLE "ignored_initiative" IS 'Possibility to filter initiatives';
777 CREATE TABLE "initiative_setting" (
778 PRIMARY KEY ("member_id", "key", "initiative_id"),
779 "member_id" INT4 REFERENCES "member" ("id") ON DELETE CASCADE ON UPDATE CASCADE,
780 "key" TEXT NOT NULL,
781 "initiative_id" INT4 REFERENCES "initiative" ("id") ON DELETE CASCADE ON UPDATE CASCADE,
782 "value" TEXT NOT NULL );
784 COMMENT ON TABLE "initiative_setting" IS 'Place for frontend to store initiative specific settings of members as strings';
787 CREATE TABLE "draft" (
788 UNIQUE ("initiative_id", "id"), -- index needed for foreign-key on table "supporter"
789 "initiative_id" INT4 NOT NULL REFERENCES "initiative" ("id") ON DELETE CASCADE ON UPDATE CASCADE,
790 "id" SERIAL8 PRIMARY KEY,
791 "created" TIMESTAMPTZ NOT NULL DEFAULT now(),
792 "author_id" INT4 NOT NULL REFERENCES "member" ("id") ON DELETE RESTRICT ON UPDATE CASCADE,
793 "formatting_engine" TEXT,
794 "content" TEXT NOT NULL,
795 "text_search_data" TSVECTOR );
796 CREATE INDEX "draft_created_idx" ON "draft" ("created");
797 CREATE INDEX "draft_author_id_created_idx" ON "draft" ("author_id", "created");
798 CREATE INDEX "draft_text_search_data_idx" ON "draft" USING gin ("text_search_data");
799 CREATE TRIGGER "update_text_search_data"
800 BEFORE INSERT OR UPDATE ON "draft"
801 FOR EACH ROW EXECUTE PROCEDURE
802 tsvector_update_trigger('text_search_data', 'pg_catalog.simple', "content");
804 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.';
806 COMMENT ON COLUMN "draft"."formatting_engine" IS 'Allows different formatting engines (i.e. wiki formats) to be used';
807 COMMENT ON COLUMN "draft"."content" IS 'Text of the draft in a format depending on the field "formatting_engine"';
810 CREATE TABLE "rendered_draft" (
811 PRIMARY KEY ("draft_id", "format"),
812 "draft_id" INT8 REFERENCES "draft" ("id") ON DELETE CASCADE ON UPDATE CASCADE,
813 "format" TEXT,
814 "content" TEXT NOT NULL );
816 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)';
819 CREATE TABLE "suggestion" (
820 UNIQUE ("initiative_id", "id"), -- index needed for foreign-key on table "opinion"
821 "initiative_id" INT4 NOT NULL REFERENCES "initiative" ("id") ON DELETE CASCADE ON UPDATE CASCADE,
822 "id" SERIAL8 PRIMARY KEY,
823 "draft_id" INT8 NOT NULL,
824 FOREIGN KEY ("initiative_id", "draft_id") REFERENCES "draft" ("initiative_id", "id") ON DELETE NO ACTION ON UPDATE CASCADE,
825 "created" TIMESTAMPTZ NOT NULL DEFAULT now(),
826 "author_id" INT4 NOT NULL REFERENCES "member" ("id") ON DELETE RESTRICT ON UPDATE CASCADE,
827 "name" TEXT NOT NULL,
828 "formatting_engine" TEXT,
829 "content" TEXT NOT NULL DEFAULT '',
830 "text_search_data" TSVECTOR,
831 "minus2_unfulfilled_count" INT4,
832 "minus2_fulfilled_count" INT4,
833 "minus1_unfulfilled_count" INT4,
834 "minus1_fulfilled_count" INT4,
835 "plus1_unfulfilled_count" INT4,
836 "plus1_fulfilled_count" INT4,
837 "plus2_unfulfilled_count" INT4,
838 "plus2_fulfilled_count" INT4 );
839 CREATE INDEX "suggestion_created_idx" ON "suggestion" ("created");
840 CREATE INDEX "suggestion_author_id_created_idx" ON "suggestion" ("author_id", "created");
841 CREATE INDEX "suggestion_text_search_data_idx" ON "suggestion" USING gin ("text_search_data");
842 CREATE TRIGGER "update_text_search_data"
843 BEFORE INSERT OR UPDATE ON "suggestion"
844 FOR EACH ROW EXECUTE PROCEDURE
845 tsvector_update_trigger('text_search_data', 'pg_catalog.simple',
846 "name", "content");
848 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';
850 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")';
851 COMMENT ON COLUMN "suggestion"."minus2_unfulfilled_count" IS 'Calculated from table "direct_supporter_snapshot", not requiring informed supporters';
852 COMMENT ON COLUMN "suggestion"."minus2_fulfilled_count" IS 'Calculated from table "direct_supporter_snapshot", not requiring informed supporters';
853 COMMENT ON COLUMN "suggestion"."minus1_unfulfilled_count" IS 'Calculated from table "direct_supporter_snapshot", not requiring informed supporters';
854 COMMENT ON COLUMN "suggestion"."minus1_fulfilled_count" IS 'Calculated from table "direct_supporter_snapshot", not requiring informed supporters';
855 COMMENT ON COLUMN "suggestion"."plus1_unfulfilled_count" IS 'Calculated from table "direct_supporter_snapshot", not requiring informed supporters';
856 COMMENT ON COLUMN "suggestion"."plus1_fulfilled_count" IS 'Calculated from table "direct_supporter_snapshot", not requiring informed supporters';
857 COMMENT ON COLUMN "suggestion"."plus2_unfulfilled_count" IS 'Calculated from table "direct_supporter_snapshot", not requiring informed supporters';
858 COMMENT ON COLUMN "suggestion"."plus2_fulfilled_count" IS 'Calculated from table "direct_supporter_snapshot", not requiring informed supporters';
861 CREATE TABLE "rendered_suggestion" (
862 PRIMARY KEY ("suggestion_id", "format"),
863 "suggestion_id" INT8 REFERENCES "suggestion" ("id") ON DELETE CASCADE ON UPDATE CASCADE,
864 "format" TEXT,
865 "content" TEXT NOT NULL );
867 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)';
870 CREATE TABLE "suggestion_setting" (
871 PRIMARY KEY ("member_id", "key", "suggestion_id"),
872 "member_id" INT4 REFERENCES "member" ("id") ON DELETE CASCADE ON UPDATE CASCADE,
873 "key" TEXT NOT NULL,
874 "suggestion_id" INT8 REFERENCES "suggestion" ("id") ON DELETE CASCADE ON UPDATE CASCADE,
875 "value" TEXT NOT NULL );
877 COMMENT ON TABLE "suggestion_setting" IS 'Place for frontend to store suggestion specific settings of members as strings';
880 CREATE TABLE "privilege" (
881 PRIMARY KEY ("unit_id", "member_id"),
882 "unit_id" INT4 REFERENCES "unit" ("id") ON DELETE CASCADE ON UPDATE CASCADE,
883 "member_id" INT4 REFERENCES "member" ("id") ON DELETE CASCADE ON UPDATE CASCADE,
884 "admin_manager" BOOLEAN NOT NULL DEFAULT FALSE,
885 "unit_manager" BOOLEAN NOT NULL DEFAULT FALSE,
886 "area_manager" BOOLEAN NOT NULL DEFAULT FALSE,
887 "member_manager" BOOLEAN NOT NULL DEFAULT FALSE,
888 "initiative_right" BOOLEAN NOT NULL DEFAULT TRUE,
889 "voting_right" BOOLEAN NOT NULL DEFAULT TRUE,
890 "polling_right" BOOLEAN NOT NULL DEFAULT FALSE );
892 COMMENT ON TABLE "privilege" IS 'Members rights related to each unit';
894 COMMENT ON COLUMN "privilege"."admin_manager" IS 'Grant/revoke any privileges to/from other members';
895 COMMENT ON COLUMN "privilege"."unit_manager" IS 'Create and disable sub units';
896 COMMENT ON COLUMN "privilege"."area_manager" IS 'Create and disable areas and set area parameters';
897 COMMENT ON COLUMN "privilege"."member_manager" IS 'Adding/removing members from the unit, granting or revoking "initiative_right" and "voting_right"';
898 COMMENT ON COLUMN "privilege"."initiative_right" IS 'Right to create an initiative';
899 COMMENT ON COLUMN "privilege"."voting_right" IS 'Right to support initiatives, create and rate suggestions, and to vote';
900 COMMENT ON COLUMN "privilege"."polling_right" IS 'Right to create polls (see "policy"."polling" and "initiative"."polling")';
903 CREATE TABLE "membership" (
904 PRIMARY KEY ("area_id", "member_id"),
905 "area_id" INT4 REFERENCES "area" ("id") ON DELETE CASCADE ON UPDATE CASCADE,
906 "member_id" INT4 REFERENCES "member" ("id") ON DELETE CASCADE ON UPDATE CASCADE );
907 CREATE INDEX "membership_member_id_idx" ON "membership" ("member_id");
909 COMMENT ON TABLE "membership" IS 'Interest of members in topic areas';
912 CREATE TABLE "interest" (
913 PRIMARY KEY ("issue_id", "member_id"),
914 "issue_id" INT4 REFERENCES "issue" ("id") ON DELETE CASCADE ON UPDATE CASCADE,
915 "member_id" INT4 REFERENCES "member" ("id") ON DELETE CASCADE ON UPDATE CASCADE );
916 CREATE INDEX "interest_member_id_idx" ON "interest" ("member_id");
918 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.';
921 CREATE TABLE "initiator" (
922 PRIMARY KEY ("initiative_id", "member_id"),
923 "initiative_id" INT4 REFERENCES "initiative" ("id") ON DELETE CASCADE ON UPDATE CASCADE,
924 "member_id" INT4 REFERENCES "member" ("id") ON DELETE CASCADE ON UPDATE CASCADE,
925 "accepted" BOOLEAN );
926 CREATE INDEX "initiator_member_id_idx" ON "initiator" ("member_id");
928 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.';
930 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.';
933 CREATE TABLE "supporter" (
934 "issue_id" INT4 NOT NULL,
935 PRIMARY KEY ("initiative_id", "member_id"),
936 "initiative_id" INT4,
937 "member_id" INT4,
938 "draft_id" INT8 NOT NULL,
939 FOREIGN KEY ("issue_id", "member_id") REFERENCES "interest" ("issue_id", "member_id") ON DELETE CASCADE ON UPDATE CASCADE,
940 FOREIGN KEY ("initiative_id", "draft_id") REFERENCES "draft" ("initiative_id", "id") ON DELETE NO ACTION ON UPDATE CASCADE );
941 CREATE INDEX "supporter_member_id_idx" ON "supporter" ("member_id");
943 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.';
945 COMMENT ON COLUMN "supporter"."issue_id" IS 'WARNING: No index: For selections use column "initiative_id" and join via table "initiative" where neccessary';
946 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")';
949 CREATE TABLE "opinion" (
950 "initiative_id" INT4 NOT NULL,
951 PRIMARY KEY ("suggestion_id", "member_id"),
952 "suggestion_id" INT8,
953 "member_id" INT4,
954 "degree" INT2 NOT NULL CHECK ("degree" >= -2 AND "degree" <= 2 AND "degree" != 0),
955 "fulfilled" BOOLEAN NOT NULL DEFAULT FALSE,
956 FOREIGN KEY ("initiative_id", "suggestion_id") REFERENCES "suggestion" ("initiative_id", "id") ON DELETE CASCADE ON UPDATE CASCADE,
957 FOREIGN KEY ("initiative_id", "member_id") REFERENCES "supporter" ("initiative_id", "member_id") ON DELETE CASCADE ON UPDATE CASCADE );
958 CREATE INDEX "opinion_member_id_initiative_id_idx" ON "opinion" ("member_id", "initiative_id");
960 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.';
962 COMMENT ON COLUMN "opinion"."degree" IS '2 = fulfillment required for support; 1 = fulfillment desired; -1 = fulfillment unwanted; -2 = fulfillment cancels support';
965 CREATE TYPE "delegation_scope" AS ENUM ('unit', 'area', 'issue');
967 COMMENT ON TYPE "delegation_scope" IS 'Scope for delegations: ''unit'', ''area'', or ''issue'' (order is relevant)';
970 CREATE TABLE "delegation" (
971 "id" SERIAL8 PRIMARY KEY,
972 "truster_id" INT4 NOT NULL REFERENCES "member" ("id") ON DELETE CASCADE ON UPDATE CASCADE,
973 "trustee_id" INT4 REFERENCES "member" ("id") ON DELETE CASCADE ON UPDATE CASCADE,
974 "scope" "delegation_scope" NOT NULL,
975 "unit_id" INT4 REFERENCES "unit" ("id") ON DELETE CASCADE ON UPDATE CASCADE,
976 "area_id" INT4 REFERENCES "area" ("id") ON DELETE CASCADE ON UPDATE CASCADE,
977 "issue_id" INT4 REFERENCES "issue" ("id") ON DELETE CASCADE ON UPDATE CASCADE,
978 CONSTRAINT "cant_delegate_to_yourself" CHECK ("truster_id" != "trustee_id"),
979 CONSTRAINT "no_unit_delegation_to_null"
980 CHECK ("trustee_id" NOTNULL OR "scope" != 'unit'),
981 CONSTRAINT "area_id_and_issue_id_set_according_to_scope" CHECK (
982 ("scope" = 'unit' AND "unit_id" NOTNULL AND "area_id" ISNULL AND "issue_id" ISNULL ) OR
983 ("scope" = 'area' AND "unit_id" ISNULL AND "area_id" NOTNULL AND "issue_id" ISNULL ) OR
984 ("scope" = 'issue' AND "unit_id" ISNULL AND "area_id" ISNULL AND "issue_id" NOTNULL) ),
985 UNIQUE ("unit_id", "truster_id"),
986 UNIQUE ("area_id", "truster_id"),
987 UNIQUE ("issue_id", "truster_id") );
988 CREATE INDEX "delegation_truster_id_idx" ON "delegation" ("truster_id");
989 CREATE INDEX "delegation_trustee_id_idx" ON "delegation" ("trustee_id");
991 COMMENT ON TABLE "delegation" IS 'Delegation of vote-weight to other members';
993 COMMENT ON COLUMN "delegation"."unit_id" IS 'Reference to unit, if delegation is unit-wide, otherwise NULL';
994 COMMENT ON COLUMN "delegation"."area_id" IS 'Reference to area, if delegation is area-wide, otherwise NULL';
995 COMMENT ON COLUMN "delegation"."issue_id" IS 'Reference to issue, if delegation is issue-wide, otherwise NULL';
998 CREATE TABLE "direct_population_snapshot" (
999 PRIMARY KEY ("issue_id", "event", "member_id"),
1000 "issue_id" INT4 REFERENCES "issue" ("id") ON DELETE CASCADE ON UPDATE CASCADE,
1001 "event" "snapshot_event",
1002 "member_id" INT4 REFERENCES "member" ("id") ON DELETE RESTRICT ON UPDATE RESTRICT,
1003 "weight" INT4 );
1004 CREATE INDEX "direct_population_snapshot_member_id_idx" ON "direct_population_snapshot" ("member_id");
1006 COMMENT ON TABLE "direct_population_snapshot" IS 'Snapshot of active members having either a "membership" in the "area" or an "interest" in the "issue"';
1008 COMMENT ON COLUMN "direct_population_snapshot"."event" IS 'Reason for snapshot, see "snapshot_event" type for details';
1009 COMMENT ON COLUMN "direct_population_snapshot"."weight" IS 'Weight of member (1 or higher) according to "delegating_population_snapshot"';
1012 CREATE TABLE "delegating_population_snapshot" (
1013 PRIMARY KEY ("issue_id", "event", "member_id"),
1014 "issue_id" INT4 REFERENCES "issue" ("id") ON DELETE CASCADE ON UPDATE CASCADE,
1015 "event" "snapshot_event",
1016 "member_id" INT4 REFERENCES "member" ("id") ON DELETE RESTRICT ON UPDATE RESTRICT,
1017 "weight" INT4,
1018 "scope" "delegation_scope" NOT NULL,
1019 "delegate_member_ids" INT4[] NOT NULL );
1020 CREATE INDEX "delegating_population_snapshot_member_id_idx" ON "delegating_population_snapshot" ("member_id");
1022 COMMENT ON TABLE "direct_population_snapshot" IS 'Delegations increasing the weight of entries in the "direct_population_snapshot" table';
1024 COMMENT ON COLUMN "delegating_population_snapshot"."event" IS 'Reason for snapshot, see "snapshot_event" type for details';
1025 COMMENT ON COLUMN "delegating_population_snapshot"."member_id" IS 'Delegating member';
1026 COMMENT ON COLUMN "delegating_population_snapshot"."weight" IS 'Intermediate weight';
1027 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"';
1030 CREATE TABLE "direct_interest_snapshot" (
1031 PRIMARY KEY ("issue_id", "event", "member_id"),
1032 "issue_id" INT4 REFERENCES "issue" ("id") ON DELETE CASCADE ON UPDATE CASCADE,
1033 "event" "snapshot_event",
1034 "member_id" INT4 REFERENCES "member" ("id") ON DELETE RESTRICT ON UPDATE RESTRICT,
1035 "weight" INT4 );
1036 CREATE INDEX "direct_interest_snapshot_member_id_idx" ON "direct_interest_snapshot" ("member_id");
1038 COMMENT ON TABLE "direct_interest_snapshot" IS 'Snapshot of active members having an "interest" in the "issue"';
1040 COMMENT ON COLUMN "direct_interest_snapshot"."event" IS 'Reason for snapshot, see "snapshot_event" type for details';
1041 COMMENT ON COLUMN "direct_interest_snapshot"."weight" IS 'Weight of member (1 or higher) according to "delegating_interest_snapshot"';
1044 CREATE TABLE "delegating_interest_snapshot" (
1045 PRIMARY KEY ("issue_id", "event", "member_id"),
1046 "issue_id" INT4 REFERENCES "issue" ("id") ON DELETE CASCADE ON UPDATE CASCADE,
1047 "event" "snapshot_event",
1048 "member_id" INT4 REFERENCES "member" ("id") ON DELETE RESTRICT ON UPDATE RESTRICT,
1049 "weight" INT4,
1050 "scope" "delegation_scope" NOT NULL,
1051 "delegate_member_ids" INT4[] NOT NULL );
1052 CREATE INDEX "delegating_interest_snapshot_member_id_idx" ON "delegating_interest_snapshot" ("member_id");
1054 COMMENT ON TABLE "delegating_interest_snapshot" IS 'Delegations increasing the weight of entries in the "direct_interest_snapshot" table';
1056 COMMENT ON COLUMN "delegating_interest_snapshot"."event" IS 'Reason for snapshot, see "snapshot_event" type for details';
1057 COMMENT ON COLUMN "delegating_interest_snapshot"."member_id" IS 'Delegating member';
1058 COMMENT ON COLUMN "delegating_interest_snapshot"."weight" IS 'Intermediate weight';
1059 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"';
1062 CREATE TABLE "direct_supporter_snapshot" (
1063 "issue_id" INT4 NOT NULL,
1064 PRIMARY KEY ("initiative_id", "event", "member_id"),
1065 "initiative_id" INT4,
1066 "event" "snapshot_event",
1067 "member_id" INT4 REFERENCES "member" ("id") ON DELETE RESTRICT ON UPDATE RESTRICT,
1068 "draft_id" INT8 NOT NULL,
1069 "informed" BOOLEAN NOT NULL,
1070 "satisfied" BOOLEAN NOT NULL,
1071 FOREIGN KEY ("issue_id", "initiative_id") REFERENCES "initiative" ("issue_id", "id") ON DELETE CASCADE ON UPDATE CASCADE,
1072 FOREIGN KEY ("initiative_id", "draft_id") REFERENCES "draft" ("initiative_id", "id") ON DELETE NO ACTION ON UPDATE CASCADE,
1073 FOREIGN KEY ("issue_id", "event", "member_id") REFERENCES "direct_interest_snapshot" ("issue_id", "event", "member_id") ON DELETE CASCADE ON UPDATE CASCADE );
1074 CREATE INDEX "direct_supporter_snapshot_member_id_idx" ON "direct_supporter_snapshot" ("member_id");
1076 COMMENT ON TABLE "direct_supporter_snapshot" IS 'Snapshot of supporters of initiatives (weight is stored in "direct_interest_snapshot")';
1078 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';
1079 COMMENT ON COLUMN "direct_supporter_snapshot"."event" IS 'Reason for snapshot, see "snapshot_event" type for details';
1080 COMMENT ON COLUMN "direct_supporter_snapshot"."informed" IS 'Supporter has seen the latest draft of the initiative';
1081 COMMENT ON COLUMN "direct_supporter_snapshot"."satisfied" IS 'Supporter has no "critical_opinion"s';
1084 CREATE TABLE "non_voter" (
1085 PRIMARY KEY ("issue_id", "member_id"),
1086 "issue_id" INT4 REFERENCES "issue" ("id") ON DELETE CASCADE ON UPDATE CASCADE,
1087 "member_id" INT4 REFERENCES "member" ("id") ON DELETE CASCADE ON UPDATE CASCADE );
1088 CREATE INDEX "non_voter_member_id_idx" ON "non_voter" ("member_id");
1090 COMMENT ON TABLE "non_voter" IS 'Members who decided to not vote directly on an issue';
1093 CREATE TABLE "direct_voter" (
1094 PRIMARY KEY ("issue_id", "member_id"),
1095 "issue_id" INT4 REFERENCES "issue" ("id") ON DELETE CASCADE ON UPDATE CASCADE,
1096 "member_id" INT4 REFERENCES "member" ("id") ON DELETE RESTRICT ON UPDATE RESTRICT,
1097 "weight" INT4 );
1098 CREATE INDEX "direct_voter_member_id_idx" ON "direct_voter" ("member_id");
1100 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.';
1102 COMMENT ON COLUMN "direct_voter"."weight" IS 'Weight of member (1 or higher) according to "delegating_voter" table';
1105 CREATE TABLE "delegating_voter" (
1106 PRIMARY KEY ("issue_id", "member_id"),
1107 "issue_id" INT4 REFERENCES "issue" ("id") ON DELETE CASCADE ON UPDATE CASCADE,
1108 "member_id" INT4 REFERENCES "member" ("id") ON DELETE RESTRICT ON UPDATE RESTRICT,
1109 "weight" INT4,
1110 "scope" "delegation_scope" NOT NULL,
1111 "delegate_member_ids" INT4[] NOT NULL );
1112 CREATE INDEX "delegating_voter_member_id_idx" ON "delegating_voter" ("member_id");
1114 COMMENT ON TABLE "delegating_voter" IS 'Delegations increasing the weight of entries in the "direct_voter" table';
1116 COMMENT ON COLUMN "delegating_voter"."member_id" IS 'Delegating member';
1117 COMMENT ON COLUMN "delegating_voter"."weight" IS 'Intermediate weight';
1118 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"';
1121 CREATE TABLE "vote" (
1122 "issue_id" INT4 NOT NULL,
1123 PRIMARY KEY ("initiative_id", "member_id"),
1124 "initiative_id" INT4,
1125 "member_id" INT4,
1126 "grade" INT4,
1127 FOREIGN KEY ("issue_id", "initiative_id") REFERENCES "initiative" ("issue_id", "id") ON DELETE CASCADE ON UPDATE CASCADE,
1128 FOREIGN KEY ("issue_id", "member_id") REFERENCES "direct_voter" ("issue_id", "member_id") ON DELETE CASCADE ON UPDATE CASCADE );
1129 CREATE INDEX "vote_member_id_idx" ON "vote" ("member_id");
1131 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.';
1133 COMMENT ON COLUMN "vote"."issue_id" IS 'WARNING: No index: For selections use column "initiative_id" and join via table "initiative" where neccessary';
1134 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.';
1137 CREATE TABLE "voting_comment" (
1138 PRIMARY KEY ("issue_id", "member_id"),
1139 "issue_id" INT4 REFERENCES "issue" ("id") ON DELETE CASCADE ON UPDATE CASCADE,
1140 "member_id" INT4 REFERENCES "member" ("id") ON DELETE CASCADE ON UPDATE CASCADE,
1141 "changed" TIMESTAMPTZ,
1142 "formatting_engine" TEXT,
1143 "content" TEXT NOT NULL,
1144 "text_search_data" TSVECTOR );
1145 CREATE INDEX "voting_comment_member_id_idx" ON "voting_comment" ("member_id");
1146 CREATE INDEX "voting_comment_text_search_data_idx" ON "voting_comment" USING gin ("text_search_data");
1147 CREATE TRIGGER "update_text_search_data"
1148 BEFORE INSERT OR UPDATE ON "voting_comment"
1149 FOR EACH ROW EXECUTE PROCEDURE
1150 tsvector_update_trigger('text_search_data', 'pg_catalog.simple', "content");
1152 COMMENT ON TABLE "voting_comment" IS 'Storage for comments of voters to be published after voting has finished.';
1154 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.';
1157 CREATE TABLE "rendered_voting_comment" (
1158 PRIMARY KEY ("issue_id", "member_id", "format"),
1159 FOREIGN KEY ("issue_id", "member_id")
1160 REFERENCES "voting_comment" ("issue_id", "member_id")
1161 ON DELETE CASCADE ON UPDATE CASCADE,
1162 "issue_id" INT4,
1163 "member_id" INT4,
1164 "format" TEXT,
1165 "content" TEXT NOT NULL );
1167 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)';
1170 CREATE TYPE "event_type" AS ENUM (
1171 'issue_state_changed',
1172 'initiative_created_in_new_issue',
1173 'initiative_created_in_existing_issue',
1174 'initiative_revoked',
1175 'new_draft_created',
1176 'suggestion_created');
1178 COMMENT ON TYPE "event_type" IS 'Type used for column "event" of table "event"';
1181 CREATE TABLE "event" (
1182 "id" SERIAL8 PRIMARY KEY,
1183 "occurrence" TIMESTAMPTZ NOT NULL DEFAULT now(),
1184 "event" "event_type" NOT NULL,
1185 "member_id" INT4 REFERENCES "member" ("id") ON DELETE RESTRICT ON UPDATE CASCADE,
1186 "issue_id" INT4 REFERENCES "issue" ("id") ON DELETE CASCADE ON UPDATE CASCADE,
1187 "state" "issue_state" CHECK ("state" != 'calculation'),
1188 "initiative_id" INT4,
1189 "draft_id" INT8,
1190 "suggestion_id" INT8,
1191 FOREIGN KEY ("issue_id", "initiative_id")
1192 REFERENCES "initiative" ("issue_id", "id")
1193 ON DELETE CASCADE ON UPDATE CASCADE,
1194 FOREIGN KEY ("initiative_id", "draft_id")
1195 REFERENCES "draft" ("initiative_id", "id")
1196 ON DELETE CASCADE ON UPDATE CASCADE,
1197 FOREIGN KEY ("initiative_id", "suggestion_id")
1198 REFERENCES "suggestion" ("initiative_id", "id")
1199 ON DELETE CASCADE ON UPDATE CASCADE,
1200 CONSTRAINT "null_constraints_for_issue_state_changed" CHECK (
1201 "event" != 'issue_state_changed' OR (
1202 "member_id" ISNULL AND
1203 "issue_id" NOTNULL AND
1204 "state" NOTNULL AND
1205 "initiative_id" ISNULL AND
1206 "draft_id" ISNULL AND
1207 "suggestion_id" ISNULL )),
1208 CONSTRAINT "null_constraints_for_initiative_creation_or_revocation_or_new_draft" CHECK (
1209 "event" NOT IN (
1210 'initiative_created_in_new_issue',
1211 'initiative_created_in_existing_issue',
1212 'initiative_revoked',
1213 'new_draft_created'
1214 ) OR (
1215 "member_id" NOTNULL AND
1216 "issue_id" NOTNULL AND
1217 "state" NOTNULL AND
1218 "initiative_id" NOTNULL AND
1219 "draft_id" NOTNULL AND
1220 "suggestion_id" ISNULL )),
1221 CONSTRAINT "null_constraints_for_suggestion_creation" CHECK (
1222 "event" != 'suggestion_created' OR (
1223 "member_id" NOTNULL AND
1224 "issue_id" NOTNULL AND
1225 "state" NOTNULL AND
1226 "initiative_id" NOTNULL AND
1227 "draft_id" ISNULL AND
1228 "suggestion_id" NOTNULL )) );
1229 CREATE INDEX "event_occurrence_idx" ON "event" ("occurrence");
1231 COMMENT ON TABLE "event" IS 'Event table, automatically filled by triggers';
1233 COMMENT ON COLUMN "event"."occurrence" IS 'Point in time, when event occurred';
1234 COMMENT ON COLUMN "event"."event" IS 'Type of event (see TYPE "event_type")';
1235 COMMENT ON COLUMN "event"."member_id" IS 'Member who caused the event, if applicable';
1236 COMMENT ON COLUMN "event"."state" IS 'If issue_id is set: state of affected issue; If state changed: new state';
1239 CREATE TABLE "notification_sent" (
1240 "event_id" INT8 NOT NULL );
1241 CREATE UNIQUE INDEX "notification_sent_singleton_idx" ON "notification_sent" ((1));
1243 COMMENT ON TABLE "notification_sent" IS 'This table stores one row with the last event_id, for which notifications have been sent out';
1244 COMMENT ON INDEX "notification_sent_singleton_idx" IS 'This index ensures that "notification_sent" only contains one row maximum.';
1248 ----------------------------------------------
1249 -- Writing of history entries and event log --
1250 ----------------------------------------------
1253 CREATE FUNCTION "write_member_history_trigger"()
1254 RETURNS TRIGGER
1255 LANGUAGE 'plpgsql' VOLATILE AS $$
1256 BEGIN
1257 IF
1258 ( NEW."active" != OLD."active" OR
1259 NEW."name" != OLD."name" ) AND
1260 OLD."activated" NOTNULL
1261 THEN
1262 INSERT INTO "member_history"
1263 ("member_id", "active", "name")
1264 VALUES (NEW."id", OLD."active", OLD."name");
1265 END IF;
1266 RETURN NULL;
1267 END;
1268 $$;
1270 CREATE TRIGGER "write_member_history"
1271 AFTER UPDATE ON "member" FOR EACH ROW EXECUTE PROCEDURE
1272 "write_member_history_trigger"();
1274 COMMENT ON FUNCTION "write_member_history_trigger"() IS 'Implementation of trigger "write_member_history" on table "member"';
1275 COMMENT ON TRIGGER "write_member_history" ON "member" IS 'When changing certain fields of a member, create a history entry in "member_history" table';
1278 CREATE FUNCTION "write_event_issue_state_changed_trigger"()
1279 RETURNS TRIGGER
1280 LANGUAGE 'plpgsql' VOLATILE AS $$
1281 BEGIN
1282 IF NEW."state" != OLD."state" AND NEW."state" != 'calculation' THEN
1283 INSERT INTO "event" ("event", "issue_id", "state")
1284 VALUES ('issue_state_changed', NEW."id", NEW."state");
1285 END IF;
1286 RETURN NULL;
1287 END;
1288 $$;
1290 CREATE TRIGGER "write_event_issue_state_changed"
1291 AFTER UPDATE ON "issue" FOR EACH ROW EXECUTE PROCEDURE
1292 "write_event_issue_state_changed_trigger"();
1294 COMMENT ON FUNCTION "write_event_issue_state_changed_trigger"() IS 'Implementation of trigger "write_event_issue_state_changed" on table "issue"';
1295 COMMENT ON TRIGGER "write_event_issue_state_changed" ON "issue" IS 'Create entry in "event" table on "state" change';
1298 CREATE FUNCTION "write_event_initiative_or_draft_created_trigger"()
1299 RETURNS TRIGGER
1300 LANGUAGE 'plpgsql' VOLATILE AS $$
1301 DECLARE
1302 "initiative_row" "initiative"%ROWTYPE;
1303 "issue_row" "issue"%ROWTYPE;
1304 "event_v" "event_type";
1305 BEGIN
1306 SELECT * INTO "initiative_row" FROM "initiative"
1307 WHERE "id" = NEW."initiative_id";
1308 SELECT * INTO "issue_row" FROM "issue"
1309 WHERE "id" = "initiative_row"."issue_id";
1310 IF EXISTS (
1311 SELECT NULL FROM "draft"
1312 WHERE "initiative_id" = NEW."initiative_id"
1313 AND "id" != NEW."id"
1314 ) THEN
1315 "event_v" := 'new_draft_created';
1316 ELSE
1317 IF EXISTS (
1318 SELECT NULL FROM "initiative"
1319 WHERE "issue_id" = "initiative_row"."issue_id"
1320 AND "id" != "initiative_row"."id"
1321 ) THEN
1322 "event_v" := 'initiative_created_in_existing_issue';
1323 ELSE
1324 "event_v" := 'initiative_created_in_new_issue';
1325 END IF;
1326 END IF;
1327 INSERT INTO "event" (
1328 "event", "member_id",
1329 "issue_id", "state", "initiative_id", "draft_id"
1330 ) VALUES (
1331 "event_v",
1332 NEW."author_id",
1333 "initiative_row"."issue_id",
1334 "issue_row"."state",
1335 "initiative_row"."id",
1336 NEW."id" );
1337 RETURN NULL;
1338 END;
1339 $$;
1341 CREATE TRIGGER "write_event_initiative_or_draft_created"
1342 AFTER INSERT ON "draft" FOR EACH ROW EXECUTE PROCEDURE
1343 "write_event_initiative_or_draft_created_trigger"();
1345 COMMENT ON FUNCTION "write_event_initiative_or_draft_created_trigger"() IS 'Implementation of trigger "write_event_initiative_or_draft_created" on table "issue"';
1346 COMMENT ON TRIGGER "write_event_initiative_or_draft_created" ON "draft" IS 'Create entry in "event" table on draft creation';
1349 CREATE FUNCTION "write_event_initiative_revoked_trigger"()
1350 RETURNS TRIGGER
1351 LANGUAGE 'plpgsql' VOLATILE AS $$
1352 DECLARE
1353 "issue_row" "issue"%ROWTYPE;
1354 "draft_id_v" "draft"."id"%TYPE;
1355 BEGIN
1356 IF OLD."revoked" ISNULL AND NEW."revoked" NOTNULL THEN
1357 SELECT * INTO "issue_row" FROM "issue"
1358 WHERE "id" = NEW."issue_id";
1359 SELECT "id" INTO "draft_id_v" FROM "current_draft"
1360 WHERE "initiative_id" = NEW."id";
1361 INSERT INTO "event" (
1362 "event", "member_id", "issue_id", "state", "initiative_id", "draft_id"
1363 ) VALUES (
1364 'initiative_revoked',
1365 NEW."revoked_by_member_id",
1366 NEW."issue_id",
1367 "issue_row"."state",
1368 NEW."id",
1369 "draft_id_v");
1370 END IF;
1371 RETURN NULL;
1372 END;
1373 $$;
1375 CREATE TRIGGER "write_event_initiative_revoked"
1376 AFTER UPDATE ON "initiative" FOR EACH ROW EXECUTE PROCEDURE
1377 "write_event_initiative_revoked_trigger"();
1379 COMMENT ON FUNCTION "write_event_initiative_revoked_trigger"() IS 'Implementation of trigger "write_event_initiative_revoked" on table "issue"';
1380 COMMENT ON TRIGGER "write_event_initiative_revoked" ON "initiative" IS 'Create entry in "event" table, when an initiative is revoked';
1383 CREATE FUNCTION "write_event_suggestion_created_trigger"()
1384 RETURNS TRIGGER
1385 LANGUAGE 'plpgsql' VOLATILE AS $$
1386 DECLARE
1387 "initiative_row" "initiative"%ROWTYPE;
1388 "issue_row" "issue"%ROWTYPE;
1389 BEGIN
1390 SELECT * INTO "initiative_row" FROM "initiative"
1391 WHERE "id" = NEW."initiative_id";
1392 SELECT * INTO "issue_row" FROM "issue"
1393 WHERE "id" = "initiative_row"."issue_id";
1394 INSERT INTO "event" (
1395 "event", "member_id",
1396 "issue_id", "state", "initiative_id", "suggestion_id"
1397 ) VALUES (
1398 'suggestion_created',
1399 NEW."author_id",
1400 "initiative_row"."issue_id",
1401 "issue_row"."state",
1402 "initiative_row"."id",
1403 NEW."id" );
1404 RETURN NULL;
1405 END;
1406 $$;
1408 CREATE TRIGGER "write_event_suggestion_created"
1409 AFTER INSERT ON "suggestion" FOR EACH ROW EXECUTE PROCEDURE
1410 "write_event_suggestion_created_trigger"();
1412 COMMENT ON FUNCTION "write_event_suggestion_created_trigger"() IS 'Implementation of trigger "write_event_suggestion_created" on table "issue"';
1413 COMMENT ON TRIGGER "write_event_suggestion_created" ON "suggestion" IS 'Create entry in "event" table on suggestion creation';
1417 ----------------------------
1418 -- Additional constraints --
1419 ----------------------------
1422 CREATE FUNCTION "issue_requires_first_initiative_trigger"()
1423 RETURNS TRIGGER
1424 LANGUAGE 'plpgsql' VOLATILE AS $$
1425 BEGIN
1426 IF NOT EXISTS (
1427 SELECT NULL FROM "initiative" WHERE "issue_id" = NEW."id"
1428 ) THEN
1429 --RAISE 'Cannot create issue without an initial initiative.' USING
1430 -- ERRCODE = 'integrity_constraint_violation',
1431 -- HINT = 'Create issue, initiative, and draft within the same transaction.';
1432 RAISE EXCEPTION 'Cannot create issue without an initial initiative.';
1433 END IF;
1434 RETURN NULL;
1435 END;
1436 $$;
1438 CREATE CONSTRAINT TRIGGER "issue_requires_first_initiative"
1439 AFTER INSERT OR UPDATE ON "issue" DEFERRABLE INITIALLY DEFERRED
1440 FOR EACH ROW EXECUTE PROCEDURE
1441 "issue_requires_first_initiative_trigger"();
1443 COMMENT ON FUNCTION "issue_requires_first_initiative_trigger"() IS 'Implementation of trigger "issue_requires_first_initiative" on table "issue"';
1444 COMMENT ON TRIGGER "issue_requires_first_initiative" ON "issue" IS 'Ensure that new issues have at least one initiative';
1447 CREATE FUNCTION "last_initiative_deletes_issue_trigger"()
1448 RETURNS TRIGGER
1449 LANGUAGE 'plpgsql' VOLATILE AS $$
1450 DECLARE
1451 "reference_lost" BOOLEAN;
1452 BEGIN
1453 IF TG_OP = 'DELETE' THEN
1454 "reference_lost" := TRUE;
1455 ELSE
1456 "reference_lost" := NEW."issue_id" != OLD."issue_id";
1457 END IF;
1458 IF
1459 "reference_lost" AND NOT EXISTS (
1460 SELECT NULL FROM "initiative" WHERE "issue_id" = OLD."issue_id"
1462 THEN
1463 DELETE FROM "issue" WHERE "id" = OLD."issue_id";
1464 END IF;
1465 RETURN NULL;
1466 END;
1467 $$;
1469 CREATE CONSTRAINT TRIGGER "last_initiative_deletes_issue"
1470 AFTER UPDATE OR DELETE ON "initiative" DEFERRABLE INITIALLY DEFERRED
1471 FOR EACH ROW EXECUTE PROCEDURE
1472 "last_initiative_deletes_issue_trigger"();
1474 COMMENT ON FUNCTION "last_initiative_deletes_issue_trigger"() IS 'Implementation of trigger "last_initiative_deletes_issue" on table "initiative"';
1475 COMMENT ON TRIGGER "last_initiative_deletes_issue" ON "initiative" IS 'Removing the last initiative of an issue deletes the issue';
1478 CREATE FUNCTION "initiative_requires_first_draft_trigger"()
1479 RETURNS TRIGGER
1480 LANGUAGE 'plpgsql' VOLATILE AS $$
1481 BEGIN
1482 IF NOT EXISTS (
1483 SELECT NULL FROM "draft" WHERE "initiative_id" = NEW."id"
1484 ) THEN
1485 --RAISE 'Cannot create initiative without an initial draft.' USING
1486 -- ERRCODE = 'integrity_constraint_violation',
1487 -- HINT = 'Create issue, initiative and draft within the same transaction.';
1488 RAISE EXCEPTION 'Cannot create initiative without an initial draft.';
1489 END IF;
1490 RETURN NULL;
1491 END;
1492 $$;
1494 CREATE CONSTRAINT TRIGGER "initiative_requires_first_draft"
1495 AFTER INSERT OR UPDATE ON "initiative" DEFERRABLE INITIALLY DEFERRED
1496 FOR EACH ROW EXECUTE PROCEDURE
1497 "initiative_requires_first_draft_trigger"();
1499 COMMENT ON FUNCTION "initiative_requires_first_draft_trigger"() IS 'Implementation of trigger "initiative_requires_first_draft" on table "initiative"';
1500 COMMENT ON TRIGGER "initiative_requires_first_draft" ON "initiative" IS 'Ensure that new initiatives have at least one draft';
1503 CREATE FUNCTION "last_draft_deletes_initiative_trigger"()
1504 RETURNS TRIGGER
1505 LANGUAGE 'plpgsql' VOLATILE AS $$
1506 DECLARE
1507 "reference_lost" BOOLEAN;
1508 BEGIN
1509 IF TG_OP = 'DELETE' THEN
1510 "reference_lost" := TRUE;
1511 ELSE
1512 "reference_lost" := NEW."initiative_id" != OLD."initiative_id";
1513 END IF;
1514 IF
1515 "reference_lost" AND NOT EXISTS (
1516 SELECT NULL FROM "draft" WHERE "initiative_id" = OLD."initiative_id"
1518 THEN
1519 DELETE FROM "initiative" WHERE "id" = OLD."initiative_id";
1520 END IF;
1521 RETURN NULL;
1522 END;
1523 $$;
1525 CREATE CONSTRAINT TRIGGER "last_draft_deletes_initiative"
1526 AFTER UPDATE OR DELETE ON "draft" DEFERRABLE INITIALLY DEFERRED
1527 FOR EACH ROW EXECUTE PROCEDURE
1528 "last_draft_deletes_initiative_trigger"();
1530 COMMENT ON FUNCTION "last_draft_deletes_initiative_trigger"() IS 'Implementation of trigger "last_draft_deletes_initiative" on table "draft"';
1531 COMMENT ON TRIGGER "last_draft_deletes_initiative" ON "draft" IS 'Removing the last draft of an initiative deletes the initiative';
1534 CREATE FUNCTION "suggestion_requires_first_opinion_trigger"()
1535 RETURNS TRIGGER
1536 LANGUAGE 'plpgsql' VOLATILE AS $$
1537 BEGIN
1538 IF NOT EXISTS (
1539 SELECT NULL FROM "opinion" WHERE "suggestion_id" = NEW."id"
1540 ) THEN
1541 RAISE EXCEPTION 'Cannot create a suggestion without an opinion.';
1542 END IF;
1543 RETURN NULL;
1544 END;
1545 $$;
1547 CREATE CONSTRAINT TRIGGER "suggestion_requires_first_opinion"
1548 AFTER INSERT OR UPDATE ON "suggestion" DEFERRABLE INITIALLY DEFERRED
1549 FOR EACH ROW EXECUTE PROCEDURE
1550 "suggestion_requires_first_opinion_trigger"();
1552 COMMENT ON FUNCTION "suggestion_requires_first_opinion_trigger"() IS 'Implementation of trigger "suggestion_requires_first_opinion" on table "suggestion"';
1553 COMMENT ON TRIGGER "suggestion_requires_first_opinion" ON "suggestion" IS 'Ensure that new suggestions have at least one opinion';
1556 CREATE FUNCTION "last_opinion_deletes_suggestion_trigger"()
1557 RETURNS TRIGGER
1558 LANGUAGE 'plpgsql' VOLATILE AS $$
1559 DECLARE
1560 "reference_lost" BOOLEAN;
1561 BEGIN
1562 IF TG_OP = 'DELETE' THEN
1563 "reference_lost" := TRUE;
1564 ELSE
1565 "reference_lost" := NEW."suggestion_id" != OLD."suggestion_id";
1566 END IF;
1567 IF
1568 "reference_lost" AND NOT EXISTS (
1569 SELECT NULL FROM "opinion" WHERE "suggestion_id" = OLD."suggestion_id"
1571 THEN
1572 DELETE FROM "suggestion" WHERE "id" = OLD."suggestion_id";
1573 END IF;
1574 RETURN NULL;
1575 END;
1576 $$;
1578 CREATE CONSTRAINT TRIGGER "last_opinion_deletes_suggestion"
1579 AFTER UPDATE OR DELETE ON "opinion" DEFERRABLE INITIALLY DEFERRED
1580 FOR EACH ROW EXECUTE PROCEDURE
1581 "last_opinion_deletes_suggestion_trigger"();
1583 COMMENT ON FUNCTION "last_opinion_deletes_suggestion_trigger"() IS 'Implementation of trigger "last_opinion_deletes_suggestion" on table "opinion"';
1584 COMMENT ON TRIGGER "last_opinion_deletes_suggestion" ON "opinion" IS 'Removing the last opinion of a suggestion deletes the suggestion';
1588 ---------------------------------------------------------------
1589 -- Ensure that votes are not modified when issues are frozen --
1590 ---------------------------------------------------------------
1592 -- NOTE: Frontends should ensure this anyway, but in case of programming
1593 -- errors the following triggers ensure data integrity.
1596 CREATE FUNCTION "forbid_changes_on_closed_issue_trigger"()
1597 RETURNS TRIGGER
1598 LANGUAGE 'plpgsql' VOLATILE AS $$
1599 DECLARE
1600 "issue_id_v" "issue"."id"%TYPE;
1601 "issue_row" "issue"%ROWTYPE;
1602 BEGIN
1603 IF TG_OP = 'DELETE' THEN
1604 "issue_id_v" := OLD."issue_id";
1605 ELSE
1606 "issue_id_v" := NEW."issue_id";
1607 END IF;
1608 SELECT INTO "issue_row" * FROM "issue"
1609 WHERE "id" = "issue_id_v" FOR SHARE;
1610 IF "issue_row"."closed" NOTNULL THEN
1611 RAISE EXCEPTION 'Tried to modify data belonging to a closed issue.';
1612 END IF;
1613 RETURN NULL;
1614 END;
1615 $$;
1617 CREATE TRIGGER "forbid_changes_on_closed_issue"
1618 AFTER INSERT OR UPDATE OR DELETE ON "direct_voter"
1619 FOR EACH ROW EXECUTE PROCEDURE
1620 "forbid_changes_on_closed_issue_trigger"();
1622 CREATE TRIGGER "forbid_changes_on_closed_issue"
1623 AFTER INSERT OR UPDATE OR DELETE ON "delegating_voter"
1624 FOR EACH ROW EXECUTE PROCEDURE
1625 "forbid_changes_on_closed_issue_trigger"();
1627 CREATE TRIGGER "forbid_changes_on_closed_issue"
1628 AFTER INSERT OR UPDATE OR DELETE ON "vote"
1629 FOR EACH ROW EXECUTE PROCEDURE
1630 "forbid_changes_on_closed_issue_trigger"();
1632 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"';
1633 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';
1634 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';
1635 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';
1639 --------------------------------------------------------------------
1640 -- Auto-retrieval of fields only needed for referential integrity --
1641 --------------------------------------------------------------------
1644 CREATE FUNCTION "autofill_issue_id_trigger"()
1645 RETURNS TRIGGER
1646 LANGUAGE 'plpgsql' VOLATILE AS $$
1647 BEGIN
1648 IF NEW."issue_id" ISNULL THEN
1649 SELECT "issue_id" INTO NEW."issue_id"
1650 FROM "initiative" WHERE "id" = NEW."initiative_id";
1651 END IF;
1652 RETURN NEW;
1653 END;
1654 $$;
1656 CREATE TRIGGER "autofill_issue_id" BEFORE INSERT ON "supporter"
1657 FOR EACH ROW EXECUTE PROCEDURE "autofill_issue_id_trigger"();
1659 CREATE TRIGGER "autofill_issue_id" BEFORE INSERT ON "vote"
1660 FOR EACH ROW EXECUTE PROCEDURE "autofill_issue_id_trigger"();
1662 COMMENT ON FUNCTION "autofill_issue_id_trigger"() IS 'Implementation of triggers "autofill_issue_id" on tables "supporter" and "vote"';
1663 COMMENT ON TRIGGER "autofill_issue_id" ON "supporter" IS 'Set "issue_id" field automatically, if NULL';
1664 COMMENT ON TRIGGER "autofill_issue_id" ON "vote" IS 'Set "issue_id" field automatically, if NULL';
1667 CREATE FUNCTION "autofill_initiative_id_trigger"()
1668 RETURNS TRIGGER
1669 LANGUAGE 'plpgsql' VOLATILE AS $$
1670 BEGIN
1671 IF NEW."initiative_id" ISNULL THEN
1672 SELECT "initiative_id" INTO NEW."initiative_id"
1673 FROM "suggestion" WHERE "id" = NEW."suggestion_id";
1674 END IF;
1675 RETURN NEW;
1676 END;
1677 $$;
1679 CREATE TRIGGER "autofill_initiative_id" BEFORE INSERT ON "opinion"
1680 FOR EACH ROW EXECUTE PROCEDURE "autofill_initiative_id_trigger"();
1682 COMMENT ON FUNCTION "autofill_initiative_id_trigger"() IS 'Implementation of trigger "autofill_initiative_id" on table "opinion"';
1683 COMMENT ON TRIGGER "autofill_initiative_id" ON "opinion" IS 'Set "initiative_id" field automatically, if NULL';
1687 -----------------------------------------------------
1688 -- Automatic calculation of certain default values --
1689 -----------------------------------------------------
1692 CREATE FUNCTION "copy_timings_trigger"()
1693 RETURNS TRIGGER
1694 LANGUAGE 'plpgsql' VOLATILE AS $$
1695 DECLARE
1696 "policy_row" "policy"%ROWTYPE;
1697 BEGIN
1698 SELECT * INTO "policy_row" FROM "policy"
1699 WHERE "id" = NEW."policy_id";
1700 IF NEW."admission_time" ISNULL THEN
1701 NEW."admission_time" := "policy_row"."admission_time";
1702 END IF;
1703 IF NEW."discussion_time" ISNULL THEN
1704 NEW."discussion_time" := "policy_row"."discussion_time";
1705 END IF;
1706 IF NEW."verification_time" ISNULL THEN
1707 NEW."verification_time" := "policy_row"."verification_time";
1708 END IF;
1709 IF NEW."voting_time" ISNULL THEN
1710 NEW."voting_time" := "policy_row"."voting_time";
1711 END IF;
1712 RETURN NEW;
1713 END;
1714 $$;
1716 CREATE TRIGGER "copy_timings" BEFORE INSERT OR UPDATE ON "issue"
1717 FOR EACH ROW EXECUTE PROCEDURE "copy_timings_trigger"();
1719 COMMENT ON FUNCTION "copy_timings_trigger"() IS 'Implementation of trigger "copy_timings" on table "issue"';
1720 COMMENT ON TRIGGER "copy_timings" ON "issue" IS 'If timing fields are NULL, copy values from policy.';
1723 CREATE FUNCTION "default_for_draft_id_trigger"()
1724 RETURNS TRIGGER
1725 LANGUAGE 'plpgsql' VOLATILE AS $$
1726 BEGIN
1727 IF NEW."draft_id" ISNULL THEN
1728 SELECT "id" INTO NEW."draft_id" FROM "current_draft"
1729 WHERE "initiative_id" = NEW."initiative_id";
1730 END IF;
1731 RETURN NEW;
1732 END;
1733 $$;
1735 CREATE TRIGGER "default_for_draft_id" BEFORE INSERT OR UPDATE ON "suggestion"
1736 FOR EACH ROW EXECUTE PROCEDURE "default_for_draft_id_trigger"();
1737 CREATE TRIGGER "default_for_draft_id" BEFORE INSERT OR UPDATE ON "supporter"
1738 FOR EACH ROW EXECUTE PROCEDURE "default_for_draft_id_trigger"();
1740 COMMENT ON FUNCTION "default_for_draft_id_trigger"() IS 'Implementation of trigger "default_for_draft" on tables "supporter" and "suggestion"';
1741 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';
1742 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';
1746 ----------------------------------------
1747 -- Automatic creation of dependencies --
1748 ----------------------------------------
1751 CREATE FUNCTION "autocreate_interest_trigger"()
1752 RETURNS TRIGGER
1753 LANGUAGE 'plpgsql' VOLATILE AS $$
1754 BEGIN
1755 IF NOT EXISTS (
1756 SELECT NULL FROM "initiative" JOIN "interest"
1757 ON "initiative"."issue_id" = "interest"."issue_id"
1758 WHERE "initiative"."id" = NEW."initiative_id"
1759 AND "interest"."member_id" = NEW."member_id"
1760 ) THEN
1761 BEGIN
1762 INSERT INTO "interest" ("issue_id", "member_id")
1763 SELECT "issue_id", NEW."member_id"
1764 FROM "initiative" WHERE "id" = NEW."initiative_id";
1765 EXCEPTION WHEN unique_violation THEN END;
1766 END IF;
1767 RETURN NEW;
1768 END;
1769 $$;
1771 CREATE TRIGGER "autocreate_interest" BEFORE INSERT ON "supporter"
1772 FOR EACH ROW EXECUTE PROCEDURE "autocreate_interest_trigger"();
1774 COMMENT ON FUNCTION "autocreate_interest_trigger"() IS 'Implementation of trigger "autocreate_interest" on table "supporter"';
1775 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';
1778 CREATE FUNCTION "autocreate_supporter_trigger"()
1779 RETURNS TRIGGER
1780 LANGUAGE 'plpgsql' VOLATILE AS $$
1781 BEGIN
1782 IF NOT EXISTS (
1783 SELECT NULL FROM "suggestion" JOIN "supporter"
1784 ON "suggestion"."initiative_id" = "supporter"."initiative_id"
1785 WHERE "suggestion"."id" = NEW."suggestion_id"
1786 AND "supporter"."member_id" = NEW."member_id"
1787 ) THEN
1788 BEGIN
1789 INSERT INTO "supporter" ("initiative_id", "member_id")
1790 SELECT "initiative_id", NEW."member_id"
1791 FROM "suggestion" WHERE "id" = NEW."suggestion_id";
1792 EXCEPTION WHEN unique_violation THEN END;
1793 END IF;
1794 RETURN NEW;
1795 END;
1796 $$;
1798 CREATE TRIGGER "autocreate_supporter" BEFORE INSERT ON "opinion"
1799 FOR EACH ROW EXECUTE PROCEDURE "autocreate_supporter_trigger"();
1801 COMMENT ON FUNCTION "autocreate_supporter_trigger"() IS 'Implementation of trigger "autocreate_supporter" on table "opinion"';
1802 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.';
1806 ------------------------------------------
1807 -- Views and helper functions for views --
1808 ------------------------------------------
1811 CREATE VIEW "unit_delegation" AS
1812 SELECT
1813 "unit"."id" AS "unit_id",
1814 "delegation"."id",
1815 "delegation"."truster_id",
1816 "delegation"."trustee_id",
1817 "delegation"."scope"
1818 FROM "unit"
1819 JOIN "delegation"
1820 ON "delegation"."unit_id" = "unit"."id"
1821 JOIN "member"
1822 ON "delegation"."truster_id" = "member"."id"
1823 JOIN "privilege"
1824 ON "delegation"."unit_id" = "privilege"."unit_id"
1825 AND "delegation"."truster_id" = "privilege"."member_id"
1826 WHERE "member"."active" AND "privilege"."voting_right";
1828 COMMENT ON VIEW "unit_delegation" IS 'Unit delegations where trusters are active and have voting right';
1831 CREATE VIEW "area_delegation" AS
1832 SELECT DISTINCT ON ("area"."id", "delegation"."truster_id")
1833 "area"."id" AS "area_id",
1834 "delegation"."id",
1835 "delegation"."truster_id",
1836 "delegation"."trustee_id",
1837 "delegation"."scope"
1838 FROM "area"
1839 JOIN "delegation"
1840 ON "delegation"."unit_id" = "area"."unit_id"
1841 OR "delegation"."area_id" = "area"."id"
1842 JOIN "member"
1843 ON "delegation"."truster_id" = "member"."id"
1844 JOIN "privilege"
1845 ON "area"."unit_id" = "privilege"."unit_id"
1846 AND "delegation"."truster_id" = "privilege"."member_id"
1847 WHERE "member"."active" AND "privilege"."voting_right"
1848 ORDER BY
1849 "area"."id",
1850 "delegation"."truster_id",
1851 "delegation"."scope" DESC;
1853 COMMENT ON VIEW "area_delegation" IS 'Area delegations where trusters are active and have voting right';
1856 CREATE VIEW "issue_delegation" AS
1857 SELECT DISTINCT ON ("issue"."id", "delegation"."truster_id")
1858 "issue"."id" AS "issue_id",
1859 "delegation"."id",
1860 "delegation"."truster_id",
1861 "delegation"."trustee_id",
1862 "delegation"."scope"
1863 FROM "issue"
1864 JOIN "area"
1865 ON "area"."id" = "issue"."area_id"
1866 JOIN "delegation"
1867 ON "delegation"."unit_id" = "area"."unit_id"
1868 OR "delegation"."area_id" = "area"."id"
1869 OR "delegation"."issue_id" = "issue"."id"
1870 JOIN "member"
1871 ON "delegation"."truster_id" = "member"."id"
1872 JOIN "privilege"
1873 ON "area"."unit_id" = "privilege"."unit_id"
1874 AND "delegation"."truster_id" = "privilege"."member_id"
1875 WHERE "member"."active" AND "privilege"."voting_right"
1876 ORDER BY
1877 "issue"."id",
1878 "delegation"."truster_id",
1879 "delegation"."scope" DESC;
1881 COMMENT ON VIEW "issue_delegation" IS 'Issue delegations where trusters are active and have voting right';
1884 CREATE FUNCTION "membership_weight_with_skipping"
1885 ( "area_id_p" "area"."id"%TYPE,
1886 "member_id_p" "member"."id"%TYPE,
1887 "skip_member_ids_p" INT4[] ) -- "member"."id"%TYPE[]
1888 RETURNS INT4
1889 LANGUAGE 'plpgsql' STABLE AS $$
1890 DECLARE
1891 "sum_v" INT4;
1892 "delegation_row" "area_delegation"%ROWTYPE;
1893 BEGIN
1894 "sum_v" := 1;
1895 FOR "delegation_row" IN
1896 SELECT "area_delegation".*
1897 FROM "area_delegation" LEFT JOIN "membership"
1898 ON "membership"."area_id" = "area_id_p"
1899 AND "membership"."member_id" = "area_delegation"."truster_id"
1900 WHERE "area_delegation"."area_id" = "area_id_p"
1901 AND "area_delegation"."trustee_id" = "member_id_p"
1902 AND "membership"."member_id" ISNULL
1903 LOOP
1904 IF NOT
1905 "skip_member_ids_p" @> ARRAY["delegation_row"."truster_id"]
1906 THEN
1907 "sum_v" := "sum_v" + "membership_weight_with_skipping"(
1908 "area_id_p",
1909 "delegation_row"."truster_id",
1910 "skip_member_ids_p" || "delegation_row"."truster_id"
1911 );
1912 END IF;
1913 END LOOP;
1914 RETURN "sum_v";
1915 END;
1916 $$;
1918 COMMENT ON FUNCTION "membership_weight_with_skipping"
1919 ( "area"."id"%TYPE,
1920 "member"."id"%TYPE,
1921 INT4[] )
1922 IS 'Helper function for "membership_weight" function';
1925 CREATE FUNCTION "membership_weight"
1926 ( "area_id_p" "area"."id"%TYPE,
1927 "member_id_p" "member"."id"%TYPE ) -- "member"."id"%TYPE[]
1928 RETURNS INT4
1929 LANGUAGE 'plpgsql' STABLE AS $$
1930 BEGIN
1931 RETURN "membership_weight_with_skipping"(
1932 "area_id_p",
1933 "member_id_p",
1934 ARRAY["member_id_p"]
1935 );
1936 END;
1937 $$;
1939 COMMENT ON FUNCTION "membership_weight"
1940 ( "area"."id"%TYPE,
1941 "member"."id"%TYPE )
1942 IS 'Calculates the potential voting weight of a member in a given area';
1945 CREATE VIEW "member_count_view" AS
1946 SELECT count(1) AS "total_count" FROM "member" WHERE "active";
1948 COMMENT ON VIEW "member_count_view" IS 'View used to update "member_count" table';
1951 CREATE VIEW "unit_member_count" AS
1952 SELECT
1953 "unit"."id" AS "unit_id",
1954 count("member"."id") AS "member_count"
1955 FROM "unit"
1956 LEFT JOIN "privilege"
1957 ON "privilege"."unit_id" = "unit"."id"
1958 AND "privilege"."voting_right"
1959 LEFT JOIN "member"
1960 ON "member"."id" = "privilege"."member_id"
1961 AND "member"."active"
1962 GROUP BY "unit"."id";
1964 COMMENT ON VIEW "unit_member_count" IS 'View used to update "member_count" column of "unit" table';
1967 CREATE VIEW "area_member_count" AS
1968 SELECT
1969 "area"."id" AS "area_id",
1970 count("member"."id") AS "direct_member_count",
1971 coalesce(
1972 sum(
1973 CASE WHEN "member"."id" NOTNULL THEN
1974 "membership_weight"("area"."id", "member"."id")
1975 ELSE 0 END
1977 ) AS "member_weight"
1978 FROM "area"
1979 LEFT JOIN "membership"
1980 ON "area"."id" = "membership"."area_id"
1981 LEFT JOIN "privilege"
1982 ON "privilege"."unit_id" = "area"."unit_id"
1983 AND "privilege"."member_id" = "membership"."member_id"
1984 AND "privilege"."voting_right"
1985 LEFT JOIN "member"
1986 ON "member"."id" = "privilege"."member_id" -- NOTE: no membership here!
1987 AND "member"."active"
1988 GROUP BY "area"."id";
1990 COMMENT ON VIEW "area_member_count" IS 'View used to update "direct_member_count" and "member_weight" columns of table "area"';
1993 CREATE VIEW "opening_draft" AS
1994 SELECT "draft".* FROM (
1995 SELECT
1996 "initiative"."id" AS "initiative_id",
1997 min("draft"."id") AS "draft_id"
1998 FROM "initiative" JOIN "draft"
1999 ON "initiative"."id" = "draft"."initiative_id"
2000 GROUP BY "initiative"."id"
2001 ) AS "subquery"
2002 JOIN "draft" ON "subquery"."draft_id" = "draft"."id";
2004 COMMENT ON VIEW "opening_draft" IS 'First drafts of all initiatives';
2007 CREATE VIEW "current_draft" AS
2008 SELECT "draft".* FROM (
2009 SELECT
2010 "initiative"."id" AS "initiative_id",
2011 max("draft"."id") AS "draft_id"
2012 FROM "initiative" JOIN "draft"
2013 ON "initiative"."id" = "draft"."initiative_id"
2014 GROUP BY "initiative"."id"
2015 ) AS "subquery"
2016 JOIN "draft" ON "subquery"."draft_id" = "draft"."id";
2018 COMMENT ON VIEW "current_draft" IS 'All latest drafts for each initiative';
2021 CREATE VIEW "critical_opinion" AS
2022 SELECT * FROM "opinion"
2023 WHERE ("degree" = 2 AND "fulfilled" = FALSE)
2024 OR ("degree" = -2 AND "fulfilled" = TRUE);
2026 COMMENT ON VIEW "critical_opinion" IS 'Opinions currently causing dissatisfaction';
2029 CREATE VIEW "battle_participant" AS
2030 SELECT "initiative"."id", "initiative"."issue_id"
2031 FROM "issue" JOIN "initiative"
2032 ON "issue"."id" = "initiative"."issue_id"
2033 WHERE "initiative"."admitted"
2034 UNION ALL
2035 SELECT NULL, "id" AS "issue_id"
2036 FROM "issue";
2038 COMMENT ON VIEW "battle_participant" IS 'Helper view for "battle_view" containing admitted initiatives plus virtual "status-quo" initiative denoted by NULL reference';
2041 CREATE VIEW "battle_view" AS
2042 SELECT
2043 "issue"."id" AS "issue_id",
2044 "winning_initiative"."id" AS "winning_initiative_id",
2045 "losing_initiative"."id" AS "losing_initiative_id",
2046 sum(
2047 CASE WHEN
2048 coalesce("better_vote"."grade", 0) >
2049 coalesce("worse_vote"."grade", 0)
2050 THEN "direct_voter"."weight" ELSE 0 END
2051 ) AS "count"
2052 FROM "issue"
2053 LEFT JOIN "direct_voter"
2054 ON "issue"."id" = "direct_voter"."issue_id"
2055 JOIN "battle_participant" AS "winning_initiative"
2056 ON "issue"."id" = "winning_initiative"."issue_id"
2057 JOIN "battle_participant" AS "losing_initiative"
2058 ON "issue"."id" = "losing_initiative"."issue_id"
2059 LEFT JOIN "vote" AS "better_vote"
2060 ON "direct_voter"."member_id" = "better_vote"."member_id"
2061 AND "winning_initiative"."id" = "better_vote"."initiative_id"
2062 LEFT JOIN "vote" AS "worse_vote"
2063 ON "direct_voter"."member_id" = "worse_vote"."member_id"
2064 AND "losing_initiative"."id" = "worse_vote"."initiative_id"
2065 WHERE "issue"."closed" NOTNULL
2066 AND "issue"."cleaned" ISNULL
2067 AND (
2068 "winning_initiative"."id" != "losing_initiative"."id" OR
2069 ( ("winning_initiative"."id" NOTNULL AND "losing_initiative"."id" ISNULL) OR
2070 ("winning_initiative"."id" ISNULL AND "losing_initiative"."id" NOTNULL) ) )
2071 GROUP BY
2072 "issue"."id",
2073 "winning_initiative"."id",
2074 "losing_initiative"."id";
2076 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';
2079 CREATE VIEW "expired_session" AS
2080 SELECT * FROM "session" WHERE now() > "expiry";
2082 CREATE RULE "delete" AS ON DELETE TO "expired_session" DO INSTEAD
2083 DELETE FROM "session" WHERE "ident" = OLD."ident";
2085 COMMENT ON VIEW "expired_session" IS 'View containing all expired sessions where DELETE is possible';
2086 COMMENT ON RULE "delete" ON "expired_session" IS 'Rule allowing DELETE on rows in "expired_session" view, i.e. DELETE FROM "expired_session"';
2089 CREATE VIEW "open_issue" AS
2090 SELECT * FROM "issue" WHERE "closed" ISNULL;
2092 COMMENT ON VIEW "open_issue" IS 'All open issues';
2095 CREATE VIEW "issue_with_ranks_missing" AS
2096 SELECT * FROM "issue"
2097 WHERE "fully_frozen" NOTNULL
2098 AND "closed" NOTNULL
2099 AND "ranks_available" = FALSE;
2101 COMMENT ON VIEW "issue_with_ranks_missing" IS 'Issues where voting was finished, but no ranks have been calculated yet';
2104 CREATE VIEW "member_contingent" AS
2105 SELECT
2106 "member"."id" AS "member_id",
2107 "contingent"."time_frame",
2108 CASE WHEN "contingent"."text_entry_limit" NOTNULL THEN
2110 SELECT count(1) FROM "draft"
2111 WHERE "draft"."author_id" = "member"."id"
2112 AND "draft"."created" > now() - "contingent"."time_frame"
2113 ) + (
2114 SELECT count(1) FROM "suggestion"
2115 WHERE "suggestion"."author_id" = "member"."id"
2116 AND "suggestion"."created" > now() - "contingent"."time_frame"
2118 ELSE NULL END AS "text_entry_count",
2119 "contingent"."text_entry_limit",
2120 CASE WHEN "contingent"."initiative_limit" NOTNULL THEN (
2121 SELECT count(1) FROM "opening_draft"
2122 WHERE "opening_draft"."author_id" = "member"."id"
2123 AND "opening_draft"."created" > now() - "contingent"."time_frame"
2124 ) ELSE NULL END AS "initiative_count",
2125 "contingent"."initiative_limit"
2126 FROM "member" CROSS JOIN "contingent";
2128 COMMENT ON VIEW "member_contingent" IS 'Actual counts of text entries and initiatives are calculated per member for each limit in the "contingent" table.';
2130 COMMENT ON COLUMN "member_contingent"."text_entry_count" IS 'Only calculated when "text_entry_limit" is not null in the same row';
2131 COMMENT ON COLUMN "member_contingent"."initiative_count" IS 'Only calculated when "initiative_limit" is not null in the same row';
2134 CREATE VIEW "member_contingent_left" AS
2135 SELECT
2136 "member_id",
2137 max("text_entry_limit" - "text_entry_count") AS "text_entries_left",
2138 max("initiative_limit" - "initiative_count") AS "initiatives_left"
2139 FROM "member_contingent" GROUP BY "member_id";
2141 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.';
2144 CREATE VIEW "event_seen_by_member" AS
2145 SELECT
2146 "member"."id" AS "seen_by_member_id",
2147 CASE WHEN "event"."state" IN (
2148 'voting',
2149 'finished_without_winner',
2150 'finished_with_winner'
2151 ) THEN
2152 'voting'::"notify_level"
2153 ELSE
2154 CASE WHEN "event"."state" IN (
2155 'verification',
2156 'canceled_after_revocation_during_verification',
2157 'canceled_no_initiative_admitted'
2158 ) THEN
2159 'verification'::"notify_level"
2160 ELSE
2161 CASE WHEN "event"."state" IN (
2162 'discussion',
2163 'canceled_after_revocation_during_discussion'
2164 ) THEN
2165 'discussion'::"notify_level"
2166 ELSE
2167 'all'::"notify_level"
2168 END
2169 END
2170 END AS "notify_level",
2171 "event".*
2172 FROM "member" CROSS JOIN "event"
2173 LEFT JOIN "issue"
2174 ON "event"."issue_id" = "issue"."id"
2175 LEFT JOIN "membership"
2176 ON "member"."id" = "membership"."member_id"
2177 AND "issue"."area_id" = "membership"."area_id"
2178 LEFT JOIN "interest"
2179 ON "member"."id" = "interest"."member_id"
2180 AND "event"."issue_id" = "interest"."issue_id"
2181 LEFT JOIN "supporter"
2182 ON "member"."id" = "supporter"."member_id"
2183 AND "event"."initiative_id" = "supporter"."initiative_id"
2184 LEFT JOIN "ignored_member"
2185 ON "member"."id" = "ignored_member"."member_id"
2186 AND "event"."member_id" = "ignored_member"."other_member_id"
2187 LEFT JOIN "ignored_initiative"
2188 ON "member"."id" = "ignored_initiative"."member_id"
2189 AND "event"."initiative_id" = "ignored_initiative"."initiative_id"
2190 WHERE (
2191 "supporter"."member_id" NOTNULL OR
2192 "interest"."member_id" NOTNULL OR
2193 ( "membership"."member_id" NOTNULL AND
2194 "event"."event" IN (
2195 'issue_state_changed',
2196 'initiative_created_in_new_issue',
2197 'initiative_created_in_existing_issue',
2198 'initiative_revoked' ) ) )
2199 AND "ignored_member"."member_id" ISNULL
2200 AND "ignored_initiative"."member_id" ISNULL;
2202 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"';
2205 CREATE VIEW "selected_event_seen_by_member" AS
2206 SELECT
2207 "member"."id" AS "seen_by_member_id",
2208 CASE WHEN "event"."state" IN (
2209 'voting',
2210 'finished_without_winner',
2211 'finished_with_winner'
2212 ) THEN
2213 'voting'::"notify_level"
2214 ELSE
2215 CASE WHEN "event"."state" IN (
2216 'verification',
2217 'canceled_after_revocation_during_verification',
2218 'canceled_no_initiative_admitted'
2219 ) THEN
2220 'verification'::"notify_level"
2221 ELSE
2222 CASE WHEN "event"."state" IN (
2223 'discussion',
2224 'canceled_after_revocation_during_discussion'
2225 ) THEN
2226 'discussion'::"notify_level"
2227 ELSE
2228 'all'::"notify_level"
2229 END
2230 END
2231 END AS "notify_level",
2232 "event".*
2233 FROM "member" CROSS JOIN "event"
2234 LEFT JOIN "issue"
2235 ON "event"."issue_id" = "issue"."id"
2236 LEFT JOIN "membership"
2237 ON "member"."id" = "membership"."member_id"
2238 AND "issue"."area_id" = "membership"."area_id"
2239 LEFT JOIN "interest"
2240 ON "member"."id" = "interest"."member_id"
2241 AND "event"."issue_id" = "interest"."issue_id"
2242 LEFT JOIN "supporter"
2243 ON "member"."id" = "supporter"."member_id"
2244 AND "event"."initiative_id" = "supporter"."initiative_id"
2245 LEFT JOIN "ignored_member"
2246 ON "member"."id" = "ignored_member"."member_id"
2247 AND "event"."member_id" = "ignored_member"."other_member_id"
2248 LEFT JOIN "ignored_initiative"
2249 ON "member"."id" = "ignored_initiative"."member_id"
2250 AND "event"."initiative_id" = "ignored_initiative"."initiative_id"
2251 WHERE (
2252 ( "member"."notify_level" >= 'all' ) OR
2253 ( "member"."notify_level" >= 'voting' AND
2254 "event"."state" IN (
2255 'voting',
2256 'finished_without_winner',
2257 'finished_with_winner' ) ) OR
2258 ( "member"."notify_level" >= 'verification' AND
2259 "event"."state" IN (
2260 'verification',
2261 'canceled_after_revocation_during_verification',
2262 'canceled_no_initiative_admitted' ) ) OR
2263 ( "member"."notify_level" >= 'discussion' AND
2264 "event"."state" IN (
2265 'discussion',
2266 'canceled_after_revocation_during_discussion' ) ) )
2267 AND (
2268 "supporter"."member_id" NOTNULL OR
2269 "interest"."member_id" NOTNULL OR
2270 ( "membership"."member_id" NOTNULL AND
2271 "event"."event" IN (
2272 'issue_state_changed',
2273 'initiative_created_in_new_issue',
2274 'initiative_created_in_existing_issue',
2275 'initiative_revoked' ) ) )
2276 AND "ignored_member"."member_id" ISNULL
2277 AND "ignored_initiative"."member_id" ISNULL;
2279 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"';
2282 CREATE TYPE "timeline_event" AS ENUM (
2283 'issue_created',
2284 'issue_canceled',
2285 'issue_accepted',
2286 'issue_half_frozen',
2287 'issue_finished_without_voting',
2288 'issue_voting_started',
2289 'issue_finished_after_voting',
2290 'initiative_created',
2291 'initiative_revoked',
2292 'draft_created',
2293 'suggestion_created');
2295 COMMENT ON TYPE "timeline_event" IS 'Types of event in timeline tables (DEPRECATED)';
2298 CREATE VIEW "timeline_issue" AS
2299 SELECT
2300 "created" AS "occurrence",
2301 'issue_created'::"timeline_event" AS "event",
2302 "id" AS "issue_id"
2303 FROM "issue"
2304 UNION ALL
2305 SELECT
2306 "closed" AS "occurrence",
2307 'issue_canceled'::"timeline_event" AS "event",
2308 "id" AS "issue_id"
2309 FROM "issue" WHERE "closed" NOTNULL AND "fully_frozen" ISNULL
2310 UNION ALL
2311 SELECT
2312 "accepted" AS "occurrence",
2313 'issue_accepted'::"timeline_event" AS "event",
2314 "id" AS "issue_id"
2315 FROM "issue" WHERE "accepted" NOTNULL
2316 UNION ALL
2317 SELECT
2318 "half_frozen" AS "occurrence",
2319 'issue_half_frozen'::"timeline_event" AS "event",
2320 "id" AS "issue_id"
2321 FROM "issue" WHERE "half_frozen" NOTNULL
2322 UNION ALL
2323 SELECT
2324 "fully_frozen" AS "occurrence",
2325 'issue_voting_started'::"timeline_event" AS "event",
2326 "id" AS "issue_id"
2327 FROM "issue"
2328 WHERE "fully_frozen" NOTNULL
2329 AND ("closed" ISNULL OR "closed" != "fully_frozen")
2330 UNION ALL
2331 SELECT
2332 "closed" AS "occurrence",
2333 CASE WHEN "fully_frozen" = "closed" THEN
2334 'issue_finished_without_voting'::"timeline_event"
2335 ELSE
2336 'issue_finished_after_voting'::"timeline_event"
2337 END AS "event",
2338 "id" AS "issue_id"
2339 FROM "issue" WHERE "closed" NOTNULL AND "fully_frozen" NOTNULL;
2341 COMMENT ON VIEW "timeline_issue" IS 'Helper view for "timeline" view (DEPRECATED)';
2344 CREATE VIEW "timeline_initiative" AS
2345 SELECT
2346 "created" AS "occurrence",
2347 'initiative_created'::"timeline_event" AS "event",
2348 "id" AS "initiative_id"
2349 FROM "initiative"
2350 UNION ALL
2351 SELECT
2352 "revoked" AS "occurrence",
2353 'initiative_revoked'::"timeline_event" AS "event",
2354 "id" AS "initiative_id"
2355 FROM "initiative" WHERE "revoked" NOTNULL;
2357 COMMENT ON VIEW "timeline_initiative" IS 'Helper view for "timeline" view (DEPRECATED)';
2360 CREATE VIEW "timeline_draft" AS
2361 SELECT
2362 "created" AS "occurrence",
2363 'draft_created'::"timeline_event" AS "event",
2364 "id" AS "draft_id"
2365 FROM "draft";
2367 COMMENT ON VIEW "timeline_draft" IS 'Helper view for "timeline" view (DEPRECATED)';
2370 CREATE VIEW "timeline_suggestion" AS
2371 SELECT
2372 "created" AS "occurrence",
2373 'suggestion_created'::"timeline_event" AS "event",
2374 "id" AS "suggestion_id"
2375 FROM "suggestion";
2377 COMMENT ON VIEW "timeline_suggestion" IS 'Helper view for "timeline" view (DEPRECATED)';
2380 CREATE VIEW "timeline" AS
2381 SELECT
2382 "occurrence",
2383 "event",
2384 "issue_id",
2385 NULL AS "initiative_id",
2386 NULL::INT8 AS "draft_id", -- TODO: Why do we need a type-cast here? Is this due to 32 bit architecture?
2387 NULL::INT8 AS "suggestion_id"
2388 FROM "timeline_issue"
2389 UNION ALL
2390 SELECT
2391 "occurrence",
2392 "event",
2393 NULL AS "issue_id",
2394 "initiative_id",
2395 NULL AS "draft_id",
2396 NULL AS "suggestion_id"
2397 FROM "timeline_initiative"
2398 UNION ALL
2399 SELECT
2400 "occurrence",
2401 "event",
2402 NULL AS "issue_id",
2403 NULL AS "initiative_id",
2404 "draft_id",
2405 NULL AS "suggestion_id"
2406 FROM "timeline_draft"
2407 UNION ALL
2408 SELECT
2409 "occurrence",
2410 "event",
2411 NULL AS "issue_id",
2412 NULL AS "initiative_id",
2413 NULL AS "draft_id",
2414 "suggestion_id"
2415 FROM "timeline_suggestion";
2417 COMMENT ON VIEW "timeline" IS 'Aggregation of different events in the system (DEPRECATED)';
2421 ------------------------------------------------------
2422 -- Row set returning function for delegation chains --
2423 ------------------------------------------------------
2426 CREATE TYPE "delegation_chain_loop_tag" AS ENUM
2427 ('first', 'intermediate', 'last', 'repetition');
2429 COMMENT ON TYPE "delegation_chain_loop_tag" IS 'Type for loop tags in "delegation_chain_row" type';
2432 CREATE TYPE "delegation_chain_row" AS (
2433 "index" INT4,
2434 "member_id" INT4,
2435 "member_valid" BOOLEAN,
2436 "participation" BOOLEAN,
2437 "overridden" BOOLEAN,
2438 "scope_in" "delegation_scope",
2439 "scope_out" "delegation_scope",
2440 "disabled_out" BOOLEAN,
2441 "loop" "delegation_chain_loop_tag" );
2443 COMMENT ON TYPE "delegation_chain_row" IS 'Type of rows returned by "delegation_chain" function';
2445 COMMENT ON COLUMN "delegation_chain_row"."index" IS 'Index starting with 0 and counting up';
2446 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';
2447 COMMENT ON COLUMN "delegation_chain_row"."overridden" IS 'True, if an entry with lower index has "participation" set to true';
2448 COMMENT ON COLUMN "delegation_chain_row"."scope_in" IS 'Scope of used incoming delegation';
2449 COMMENT ON COLUMN "delegation_chain_row"."scope_out" IS 'Scope of used outgoing delegation';
2450 COMMENT ON COLUMN "delegation_chain_row"."disabled_out" IS 'Outgoing delegation is explicitly disabled by a delegation with trustee_id set to NULL';
2451 COMMENT ON COLUMN "delegation_chain_row"."loop" IS 'Not null, if member is part of a loop, see "delegation_chain_loop_tag" type';
2454 CREATE FUNCTION "delegation_chain_for_closed_issue"
2455 ( "member_id_p" "member"."id"%TYPE,
2456 "issue_id_p" "issue"."id"%TYPE )
2457 RETURNS SETOF "delegation_chain_row"
2458 LANGUAGE 'plpgsql' STABLE AS $$
2459 DECLARE
2460 "output_row" "delegation_chain_row";
2461 "direct_voter_row" "direct_voter"%ROWTYPE;
2462 "delegating_voter_row" "delegating_voter"%ROWTYPE;
2463 BEGIN
2464 "output_row"."index" := 0;
2465 "output_row"."member_id" := "member_id_p";
2466 "output_row"."member_valid" := TRUE;
2467 "output_row"."participation" := FALSE;
2468 "output_row"."overridden" := FALSE;
2469 "output_row"."disabled_out" := FALSE;
2470 LOOP
2471 SELECT INTO "direct_voter_row" * FROM "direct_voter"
2472 WHERE "issue_id" = "issue_id_p"
2473 AND "member_id" = "output_row"."member_id";
2474 IF "direct_voter_row"."member_id" NOTNULL THEN
2475 "output_row"."participation" := TRUE;
2476 "output_row"."scope_out" := NULL;
2477 "output_row"."disabled_out" := NULL;
2478 RETURN NEXT "output_row";
2479 RETURN;
2480 END IF;
2481 SELECT INTO "delegating_voter_row" * FROM "delegating_voter"
2482 WHERE "issue_id" = "issue_id_p"
2483 AND "member_id" = "output_row"."member_id";
2484 IF "delegating_voter_row"."member_id" ISNULL THEN
2485 RETURN;
2486 END IF;
2487 "output_row"."scope_out" := "delegating_voter_row"."scope";
2488 RETURN NEXT "output_row";
2489 "output_row"."member_id" := "delegating_voter_row"."delegate_member_ids"[1];
2490 "output_row"."scope_in" := "output_row"."scope_out";
2491 END LOOP;
2492 END;
2493 $$;
2495 COMMENT ON FUNCTION "delegation_chain_for_closed_issue"
2496 ( "member"."id"%TYPE,
2497 "member"."id"%TYPE )
2498 IS 'Helper function for "delegation_chain" function, handling the special case of closed issues after voting';
2501 CREATE FUNCTION "delegation_chain"
2502 ( "member_id_p" "member"."id"%TYPE,
2503 "unit_id_p" "unit"."id"%TYPE,
2504 "area_id_p" "area"."id"%TYPE,
2505 "issue_id_p" "issue"."id"%TYPE,
2506 "simulate_trustee_id_p" "member"."id"%TYPE DEFAULT NULL,
2507 "simulate_default_p" BOOLEAN DEFAULT FALSE )
2508 RETURNS SETOF "delegation_chain_row"
2509 LANGUAGE 'plpgsql' STABLE AS $$
2510 DECLARE
2511 "scope_v" "delegation_scope";
2512 "unit_id_v" "unit"."id"%TYPE;
2513 "area_id_v" "area"."id"%TYPE;
2514 "issue_row" "issue"%ROWTYPE;
2515 "visited_member_ids" INT4[]; -- "member"."id"%TYPE[]
2516 "loop_member_id_v" "member"."id"%TYPE;
2517 "output_row" "delegation_chain_row";
2518 "output_rows" "delegation_chain_row"[];
2519 "simulate_v" BOOLEAN;
2520 "simulate_here_v" BOOLEAN;
2521 "delegation_row" "delegation"%ROWTYPE;
2522 "row_count" INT4;
2523 "i" INT4;
2524 "loop_v" BOOLEAN;
2525 BEGIN
2526 IF "simulate_trustee_id_p" NOTNULL AND "simulate_default_p" THEN
2527 RAISE EXCEPTION 'Both "simulate_trustee_id_p" is set, and "simulate_default_p" is true';
2528 END IF;
2529 IF "simulate_trustee_id_p" NOTNULL OR "simulate_default_p" THEN
2530 "simulate_v" := TRUE;
2531 ELSE
2532 "simulate_v" := FALSE;
2533 END IF;
2534 IF
2535 "unit_id_p" NOTNULL AND
2536 "area_id_p" ISNULL AND
2537 "issue_id_p" ISNULL
2538 THEN
2539 "scope_v" := 'unit';
2540 "unit_id_v" := "unit_id_p";
2541 ELSIF
2542 "unit_id_p" ISNULL AND
2543 "area_id_p" NOTNULL AND
2544 "issue_id_p" ISNULL
2545 THEN
2546 "scope_v" := 'area';
2547 "area_id_v" := "area_id_p";
2548 SELECT "unit_id" INTO "unit_id_v"
2549 FROM "area" WHERE "id" = "area_id_v";
2550 ELSIF
2551 "unit_id_p" ISNULL AND
2552 "area_id_p" ISNULL AND
2553 "issue_id_p" NOTNULL
2554 THEN
2555 SELECT INTO "issue_row" * FROM "issue" WHERE "id" = "issue_id_p";
2556 IF "issue_row"."id" ISNULL THEN
2557 RETURN;
2558 END IF;
2559 IF "issue_row"."closed" NOTNULL THEN
2560 IF "simulate_v" THEN
2561 RAISE EXCEPTION 'Tried to simulate delegation chain for closed issue.';
2562 END IF;
2563 FOR "output_row" IN
2564 SELECT * FROM
2565 "delegation_chain_for_closed_issue"("member_id_p", "issue_id_p")
2566 LOOP
2567 RETURN NEXT "output_row";
2568 END LOOP;
2569 RETURN;
2570 END IF;
2571 "scope_v" := 'issue';
2572 SELECT "area_id" INTO "area_id_v"
2573 FROM "issue" WHERE "id" = "issue_id_p";
2574 SELECT "unit_id" INTO "unit_id_v"
2575 FROM "area" WHERE "id" = "area_id_v";
2576 ELSE
2577 RAISE EXCEPTION 'Exactly one of unit_id_p, area_id_p, or issue_id_p must be NOTNULL.';
2578 END IF;
2579 "visited_member_ids" := '{}';
2580 "loop_member_id_v" := NULL;
2581 "output_rows" := '{}';
2582 "output_row"."index" := 0;
2583 "output_row"."member_id" := "member_id_p";
2584 "output_row"."member_valid" := TRUE;
2585 "output_row"."participation" := FALSE;
2586 "output_row"."overridden" := FALSE;
2587 "output_row"."disabled_out" := FALSE;
2588 "output_row"."scope_out" := NULL;
2589 LOOP
2590 IF "visited_member_ids" @> ARRAY["output_row"."member_id"] THEN
2591 "loop_member_id_v" := "output_row"."member_id";
2592 ELSE
2593 "visited_member_ids" :=
2594 "visited_member_ids" || "output_row"."member_id";
2595 END IF;
2596 IF "output_row"."participation" ISNULL THEN
2597 "output_row"."overridden" := NULL;
2598 ELSIF "output_row"."participation" THEN
2599 "output_row"."overridden" := TRUE;
2600 END IF;
2601 "output_row"."scope_in" := "output_row"."scope_out";
2602 "output_row"."member_valid" := EXISTS (
2603 SELECT NULL FROM "member" JOIN "privilege"
2604 ON "privilege"."member_id" = "member"."id"
2605 AND "privilege"."unit_id" = "unit_id_v"
2606 WHERE "id" = "output_row"."member_id"
2607 AND "member"."active" AND "privilege"."voting_right"
2608 );
2609 "simulate_here_v" := (
2610 "simulate_v" AND
2611 "output_row"."member_id" = "member_id_p"
2612 );
2613 "delegation_row" := ROW(NULL);
2614 IF "output_row"."member_valid" OR "simulate_here_v" THEN
2615 IF "scope_v" = 'unit' THEN
2616 IF NOT "simulate_here_v" THEN
2617 SELECT * INTO "delegation_row" FROM "delegation"
2618 WHERE "truster_id" = "output_row"."member_id"
2619 AND "unit_id" = "unit_id_v";
2620 END IF;
2621 ELSIF "scope_v" = 'area' THEN
2622 "output_row"."participation" := EXISTS (
2623 SELECT NULL FROM "membership"
2624 WHERE "area_id" = "area_id_p"
2625 AND "member_id" = "output_row"."member_id"
2626 );
2627 IF "simulate_here_v" THEN
2628 IF "simulate_trustee_id_p" ISNULL THEN
2629 SELECT * INTO "delegation_row" FROM "delegation"
2630 WHERE "truster_id" = "output_row"."member_id"
2631 AND "unit_id" = "unit_id_v";
2632 END IF;
2633 ELSE
2634 SELECT * INTO "delegation_row" FROM "delegation"
2635 WHERE "truster_id" = "output_row"."member_id"
2636 AND (
2637 "unit_id" = "unit_id_v" OR
2638 "area_id" = "area_id_v"
2640 ORDER BY "scope" DESC;
2641 END IF;
2642 ELSIF "scope_v" = 'issue' THEN
2643 IF "issue_row"."fully_frozen" ISNULL THEN
2644 "output_row"."participation" := EXISTS (
2645 SELECT NULL FROM "interest"
2646 WHERE "issue_id" = "issue_id_p"
2647 AND "member_id" = "output_row"."member_id"
2648 );
2649 ELSE
2650 IF "output_row"."member_id" = "member_id_p" THEN
2651 "output_row"."participation" := EXISTS (
2652 SELECT NULL FROM "direct_voter"
2653 WHERE "issue_id" = "issue_id_p"
2654 AND "member_id" = "output_row"."member_id"
2655 );
2656 ELSE
2657 "output_row"."participation" := NULL;
2658 END IF;
2659 END IF;
2660 IF "simulate_here_v" THEN
2661 IF "simulate_trustee_id_p" ISNULL THEN
2662 SELECT * INTO "delegation_row" FROM "delegation"
2663 WHERE "truster_id" = "output_row"."member_id"
2664 AND (
2665 "unit_id" = "unit_id_v" OR
2666 "area_id" = "area_id_v"
2668 ORDER BY "scope" DESC;
2669 END IF;
2670 ELSE
2671 SELECT * INTO "delegation_row" FROM "delegation"
2672 WHERE "truster_id" = "output_row"."member_id"
2673 AND (
2674 "unit_id" = "unit_id_v" OR
2675 "area_id" = "area_id_v" OR
2676 "issue_id" = "issue_id_p"
2678 ORDER BY "scope" DESC;
2679 END IF;
2680 END IF;
2681 ELSE
2682 "output_row"."participation" := FALSE;
2683 END IF;
2684 IF "simulate_here_v" AND "simulate_trustee_id_p" NOTNULL THEN
2685 "output_row"."scope_out" := "scope_v";
2686 "output_rows" := "output_rows" || "output_row";
2687 "output_row"."member_id" := "simulate_trustee_id_p";
2688 ELSIF "delegation_row"."trustee_id" NOTNULL THEN
2689 "output_row"."scope_out" := "delegation_row"."scope";
2690 "output_rows" := "output_rows" || "output_row";
2691 "output_row"."member_id" := "delegation_row"."trustee_id";
2692 ELSIF "delegation_row"."scope" NOTNULL THEN
2693 "output_row"."scope_out" := "delegation_row"."scope";
2694 "output_row"."disabled_out" := TRUE;
2695 "output_rows" := "output_rows" || "output_row";
2696 EXIT;
2697 ELSE
2698 "output_row"."scope_out" := NULL;
2699 "output_rows" := "output_rows" || "output_row";
2700 EXIT;
2701 END IF;
2702 EXIT WHEN "loop_member_id_v" NOTNULL;
2703 "output_row"."index" := "output_row"."index" + 1;
2704 END LOOP;
2705 "row_count" := array_upper("output_rows", 1);
2706 "i" := 1;
2707 "loop_v" := FALSE;
2708 LOOP
2709 "output_row" := "output_rows"["i"];
2710 EXIT WHEN "output_row" ISNULL; -- NOTE: ISNULL and NOT ... NOTNULL produce different results!
2711 IF "loop_v" THEN
2712 IF "i" + 1 = "row_count" THEN
2713 "output_row"."loop" := 'last';
2714 ELSIF "i" = "row_count" THEN
2715 "output_row"."loop" := 'repetition';
2716 ELSE
2717 "output_row"."loop" := 'intermediate';
2718 END IF;
2719 ELSIF "output_row"."member_id" = "loop_member_id_v" THEN
2720 "output_row"."loop" := 'first';
2721 "loop_v" := TRUE;
2722 END IF;
2723 IF "scope_v" = 'unit' THEN
2724 "output_row"."participation" := NULL;
2725 END IF;
2726 RETURN NEXT "output_row";
2727 "i" := "i" + 1;
2728 END LOOP;
2729 RETURN;
2730 END;
2731 $$;
2733 COMMENT ON FUNCTION "delegation_chain"
2734 ( "member"."id"%TYPE,
2735 "unit"."id"%TYPE,
2736 "area"."id"%TYPE,
2737 "issue"."id"%TYPE,
2738 "member"."id"%TYPE,
2739 BOOLEAN )
2740 IS 'Shows a delegation chain for unit, area, or issue; See "delegation_chain_row" type for more information';
2744 ---------------------------------------------------------
2745 -- Single row returning function for delegation chains --
2746 ---------------------------------------------------------
2749 CREATE TYPE "delegation_info_loop_type" AS ENUM
2750 ('own', 'first', 'first_ellipsis', 'other', 'other_ellipsis');
2752 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''';
2755 CREATE TYPE "delegation_info_type" AS (
2756 "own_participation" BOOLEAN,
2757 "own_delegation_scope" "delegation_scope",
2758 "first_trustee_id" INT4,
2759 "first_trustee_participation" BOOLEAN,
2760 "first_trustee_ellipsis" BOOLEAN,
2761 "other_trustee_id" INT4,
2762 "other_trustee_participation" BOOLEAN,
2763 "other_trustee_ellipsis" BOOLEAN,
2764 "delegation_loop" "delegation_info_loop_type",
2765 "participating_member_id" INT4 );
2767 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';
2769 COMMENT ON COLUMN "delegation_info_type"."own_participation" IS 'Member is directly participating';
2770 COMMENT ON COLUMN "delegation_info_type"."own_delegation_scope" IS 'Delegation scope of member';
2771 COMMENT ON COLUMN "delegation_info_type"."first_trustee_id" IS 'Direct trustee of member';
2772 COMMENT ON COLUMN "delegation_info_type"."first_trustee_participation" IS 'Direct trustee of member is participating';
2773 COMMENT ON COLUMN "delegation_info_type"."first_trustee_ellipsis" IS 'Ellipsis in delegation chain after "first_trustee"';
2774 COMMENT ON COLUMN "delegation_info_type"."other_trustee_id" IS 'Another relevant trustee (due to participation)';
2775 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)';
2776 COMMENT ON COLUMN "delegation_info_type"."other_trustee_ellipsis" IS 'Ellipsis in delegation chain after "other_trustee"';
2777 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';
2778 COMMENT ON COLUMN "delegation_info_type"."participating_member_id" IS 'First participating member in delegation chain';
2781 CREATE FUNCTION "delegation_info"
2782 ( "member_id_p" "member"."id"%TYPE,
2783 "unit_id_p" "unit"."id"%TYPE,
2784 "area_id_p" "area"."id"%TYPE,
2785 "issue_id_p" "issue"."id"%TYPE,
2786 "simulate_trustee_id_p" "member"."id"%TYPE DEFAULT NULL,
2787 "simulate_default_p" BOOLEAN DEFAULT FALSE )
2788 RETURNS "delegation_info_type"
2789 LANGUAGE 'plpgsql' STABLE AS $$
2790 DECLARE
2791 "current_row" "delegation_chain_row";
2792 "result" "delegation_info_type";
2793 BEGIN
2794 "result"."own_participation" := FALSE;
2795 FOR "current_row" IN
2796 SELECT * FROM "delegation_chain"(
2797 "member_id_p",
2798 "unit_id_p", "area_id_p", "issue_id_p",
2799 "simulate_trustee_id_p", "simulate_default_p")
2800 LOOP
2801 IF
2802 "result"."participating_member_id" ISNULL AND
2803 "current_row"."participation"
2804 THEN
2805 "result"."participating_member_id" := "current_row"."member_id";
2806 END IF;
2807 IF "current_row"."member_id" = "member_id_p" THEN
2808 "result"."own_participation" := "current_row"."participation";
2809 "result"."own_delegation_scope" := "current_row"."scope_out";
2810 IF "current_row"."loop" = 'first' THEN
2811 "result"."delegation_loop" := 'own';
2812 END IF;
2813 ELSIF
2814 "current_row"."member_valid" AND
2815 ( "current_row"."loop" ISNULL OR
2816 "current_row"."loop" != 'repetition' )
2817 THEN
2818 IF "result"."first_trustee_id" ISNULL THEN
2819 "result"."first_trustee_id" := "current_row"."member_id";
2820 "result"."first_trustee_participation" := "current_row"."participation";
2821 "result"."first_trustee_ellipsis" := FALSE;
2822 IF "current_row"."loop" = 'first' THEN
2823 "result"."delegation_loop" := 'first';
2824 END IF;
2825 ELSIF "result"."other_trustee_id" ISNULL THEN
2826 IF "current_row"."participation" AND NOT "current_row"."overridden" THEN
2827 "result"."other_trustee_id" := "current_row"."member_id";
2828 "result"."other_trustee_participation" := TRUE;
2829 "result"."other_trustee_ellipsis" := FALSE;
2830 IF "current_row"."loop" = 'first' THEN
2831 "result"."delegation_loop" := 'other';
2832 END IF;
2833 ELSE
2834 "result"."first_trustee_ellipsis" := TRUE;
2835 IF "current_row"."loop" = 'first' THEN
2836 "result"."delegation_loop" := 'first_ellipsis';
2837 END IF;
2838 END IF;
2839 ELSE
2840 "result"."other_trustee_ellipsis" := TRUE;
2841 IF "current_row"."loop" = 'first' THEN
2842 "result"."delegation_loop" := 'other_ellipsis';
2843 END IF;
2844 END IF;
2845 END IF;
2846 END LOOP;
2847 RETURN "result";
2848 END;
2849 $$;
2851 COMMENT ON FUNCTION "delegation_info"
2852 ( "member"."id"%TYPE,
2853 "unit"."id"%TYPE,
2854 "area"."id"%TYPE,
2855 "issue"."id"%TYPE,
2856 "member"."id"%TYPE,
2857 BOOLEAN )
2858 IS 'Notable information about a delegation chain for unit, area, or issue; See "delegation_info_type" for more information';
2862 ------------------------------
2863 -- Comparison by vote count --
2864 ------------------------------
2866 CREATE FUNCTION "vote_ratio"
2867 ( "positive_votes_p" "initiative"."positive_votes"%TYPE,
2868 "negative_votes_p" "initiative"."negative_votes"%TYPE )
2869 RETURNS FLOAT8
2870 LANGUAGE 'plpgsql' STABLE AS $$
2871 BEGIN
2872 IF "positive_votes_p" > 0 AND "negative_votes_p" > 0 THEN
2873 RETURN
2874 "positive_votes_p"::FLOAT8 /
2875 ("positive_votes_p" + "negative_votes_p")::FLOAT8;
2876 ELSIF "positive_votes_p" > 0 THEN
2877 RETURN "positive_votes_p";
2878 ELSIF "negative_votes_p" > 0 THEN
2879 RETURN 1 - "negative_votes_p";
2880 ELSE
2881 RETURN 0.5;
2882 END IF;
2883 END;
2884 $$;
2886 COMMENT ON FUNCTION "vote_ratio"
2887 ( "initiative"."positive_votes"%TYPE,
2888 "initiative"."negative_votes"%TYPE )
2889 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.';
2893 ------------------------------------------------
2894 -- Locking for snapshots and voting procedure --
2895 ------------------------------------------------
2898 CREATE FUNCTION "share_row_lock_issue_trigger"()
2899 RETURNS TRIGGER
2900 LANGUAGE 'plpgsql' VOLATILE AS $$
2901 BEGIN
2902 IF TG_OP = 'UPDATE' OR TG_OP = 'DELETE' THEN
2903 PERFORM NULL FROM "issue" WHERE "id" = OLD."issue_id" FOR SHARE;
2904 END IF;
2905 IF TG_OP = 'INSERT' OR TG_OP = 'UPDATE' THEN
2906 PERFORM NULL FROM "issue" WHERE "id" = NEW."issue_id" FOR SHARE;
2907 RETURN NEW;
2908 ELSE
2909 RETURN OLD;
2910 END IF;
2911 END;
2912 $$;
2914 COMMENT ON FUNCTION "share_row_lock_issue_trigger"() IS 'Implementation of triggers "share_row_lock_issue" on multiple tables';
2917 CREATE FUNCTION "share_row_lock_issue_via_initiative_trigger"()
2918 RETURNS TRIGGER
2919 LANGUAGE 'plpgsql' VOLATILE AS $$
2920 BEGIN
2921 IF TG_OP = 'UPDATE' OR TG_OP = 'DELETE' THEN
2922 PERFORM NULL FROM "issue"
2923 JOIN "initiative" ON "issue"."id" = "initiative"."issue_id"
2924 WHERE "initiative"."id" = OLD."initiative_id"
2925 FOR SHARE OF "issue";
2926 END IF;
2927 IF TG_OP = 'INSERT' OR TG_OP = 'UPDATE' THEN
2928 PERFORM NULL FROM "issue"
2929 JOIN "initiative" ON "issue"."id" = "initiative"."issue_id"
2930 WHERE "initiative"."id" = NEW."initiative_id"
2931 FOR SHARE OF "issue";
2932 RETURN NEW;
2933 ELSE
2934 RETURN OLD;
2935 END IF;
2936 END;
2937 $$;
2939 COMMENT ON FUNCTION "share_row_lock_issue_trigger"() IS 'Implementation of trigger "share_row_lock_issue_via_initiative" on table "opinion"';
2942 CREATE TRIGGER "share_row_lock_issue"
2943 BEFORE INSERT OR UPDATE OR DELETE ON "initiative"
2944 FOR EACH ROW EXECUTE PROCEDURE
2945 "share_row_lock_issue_trigger"();
2947 CREATE TRIGGER "share_row_lock_issue"
2948 BEFORE INSERT OR UPDATE OR DELETE ON "interest"
2949 FOR EACH ROW EXECUTE PROCEDURE
2950 "share_row_lock_issue_trigger"();
2952 CREATE TRIGGER "share_row_lock_issue"
2953 BEFORE INSERT OR UPDATE OR DELETE ON "supporter"
2954 FOR EACH ROW EXECUTE PROCEDURE
2955 "share_row_lock_issue_trigger"();
2957 CREATE TRIGGER "share_row_lock_issue_via_initiative"
2958 BEFORE INSERT OR UPDATE OR DELETE ON "opinion"
2959 FOR EACH ROW EXECUTE PROCEDURE
2960 "share_row_lock_issue_via_initiative_trigger"();
2962 CREATE TRIGGER "share_row_lock_issue"
2963 BEFORE INSERT OR UPDATE OR DELETE ON "direct_voter"
2964 FOR EACH ROW EXECUTE PROCEDURE
2965 "share_row_lock_issue_trigger"();
2967 CREATE TRIGGER "share_row_lock_issue"
2968 BEFORE INSERT OR UPDATE OR DELETE ON "delegating_voter"
2969 FOR EACH ROW EXECUTE PROCEDURE
2970 "share_row_lock_issue_trigger"();
2972 CREATE TRIGGER "share_row_lock_issue"
2973 BEFORE INSERT OR UPDATE OR DELETE ON "vote"
2974 FOR EACH ROW EXECUTE PROCEDURE
2975 "share_row_lock_issue_trigger"();
2977 COMMENT ON TRIGGER "share_row_lock_issue" ON "initiative" IS 'See "lock_issue" function';
2978 COMMENT ON TRIGGER "share_row_lock_issue" ON "interest" IS 'See "lock_issue" function';
2979 COMMENT ON TRIGGER "share_row_lock_issue" ON "supporter" IS 'See "lock_issue" function';
2980 COMMENT ON TRIGGER "share_row_lock_issue_via_initiative" ON "opinion" IS 'See "lock_issue" function';
2981 COMMENT ON TRIGGER "share_row_lock_issue" ON "direct_voter" IS 'See "lock_issue" function';
2982 COMMENT ON TRIGGER "share_row_lock_issue" ON "delegating_voter" IS 'See "lock_issue" function';
2983 COMMENT ON TRIGGER "share_row_lock_issue" ON "vote" IS 'See "lock_issue" function';
2986 CREATE FUNCTION "lock_issue"
2987 ( "issue_id_p" "issue"."id"%TYPE )
2988 RETURNS VOID
2989 LANGUAGE 'plpgsql' VOLATILE AS $$
2990 BEGIN
2991 LOCK TABLE "member" IN SHARE MODE;
2992 LOCK TABLE "privilege" IN SHARE MODE;
2993 LOCK TABLE "membership" IN SHARE MODE;
2994 LOCK TABLE "policy" IN SHARE MODE;
2995 PERFORM NULL FROM "issue" WHERE "id" = "issue_id_p" FOR UPDATE;
2996 -- NOTE: The row-level exclusive lock in combination with the
2997 -- share_row_lock_issue(_via_initiative)_trigger functions (which
2998 -- acquire a row-level share lock on the issue) ensure that no data
2999 -- is changed, which could affect calculation of snapshots or
3000 -- counting of votes. Table "delegation" must be table-level-locked,
3001 -- as it also contains issue- and global-scope delegations.
3002 LOCK TABLE "delegation" IN SHARE MODE;
3003 LOCK TABLE "direct_population_snapshot" IN EXCLUSIVE MODE;
3004 LOCK TABLE "delegating_population_snapshot" IN EXCLUSIVE MODE;
3005 LOCK TABLE "direct_interest_snapshot" IN EXCLUSIVE MODE;
3006 LOCK TABLE "delegating_interest_snapshot" IN EXCLUSIVE MODE;
3007 LOCK TABLE "direct_supporter_snapshot" IN EXCLUSIVE MODE;
3008 RETURN;
3009 END;
3010 $$;
3012 COMMENT ON FUNCTION "lock_issue"
3013 ( "issue"."id"%TYPE )
3014 IS 'Locks the issue and all other data which is used for calculating snapshots or counting votes.';
3018 ------------------------------------------------------------------------
3019 -- Regular tasks, except calculcation of snapshots and voting results --
3020 ------------------------------------------------------------------------
3022 CREATE FUNCTION "check_activity"()
3023 RETURNS VOID
3024 LANGUAGE 'plpgsql' VOLATILE AS $$
3025 DECLARE
3026 "system_setting_row" "system_setting"%ROWTYPE;
3027 BEGIN
3028 SELECT * INTO "system_setting_row" FROM "system_setting";
3029 LOCK TABLE "member" IN SHARE ROW EXCLUSIVE MODE;
3030 IF "system_setting_row"."member_ttl" NOTNULL THEN
3031 UPDATE "member" SET "active" = FALSE
3032 WHERE "active" = TRUE
3033 AND "last_activity" < (now() - "system_setting_row"."member_ttl")::DATE;
3034 END IF;
3035 RETURN;
3036 END;
3037 $$;
3039 COMMENT ON FUNCTION "check_activity"() IS 'Deactivates members when "last_activity" is older than "system_setting"."member_ttl".';
3042 CREATE FUNCTION "calculate_member_counts"()
3043 RETURNS VOID
3044 LANGUAGE 'plpgsql' VOLATILE AS $$
3045 BEGIN
3046 LOCK TABLE "member" IN SHARE MODE;
3047 LOCK TABLE "member_count" IN EXCLUSIVE MODE;
3048 LOCK TABLE "unit" IN EXCLUSIVE MODE;
3049 LOCK TABLE "area" IN EXCLUSIVE MODE;
3050 LOCK TABLE "privilege" IN SHARE MODE;
3051 LOCK TABLE "membership" IN SHARE MODE;
3052 DELETE FROM "member_count";
3053 INSERT INTO "member_count" ("total_count")
3054 SELECT "total_count" FROM "member_count_view";
3055 UPDATE "unit" SET "member_count" = "view"."member_count"
3056 FROM "unit_member_count" AS "view"
3057 WHERE "view"."unit_id" = "unit"."id";
3058 UPDATE "area" SET
3059 "direct_member_count" = "view"."direct_member_count",
3060 "member_weight" = "view"."member_weight"
3061 FROM "area_member_count" AS "view"
3062 WHERE "view"."area_id" = "area"."id";
3063 RETURN;
3064 END;
3065 $$;
3067 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"';
3071 ------------------------------
3072 -- Calculation of snapshots --
3073 ------------------------------
3075 CREATE FUNCTION "weight_of_added_delegations_for_population_snapshot"
3076 ( "issue_id_p" "issue"."id"%TYPE,
3077 "member_id_p" "member"."id"%TYPE,
3078 "delegate_member_ids_p" "delegating_population_snapshot"."delegate_member_ids"%TYPE )
3079 RETURNS "direct_population_snapshot"."weight"%TYPE
3080 LANGUAGE 'plpgsql' VOLATILE AS $$
3081 DECLARE
3082 "issue_delegation_row" "issue_delegation"%ROWTYPE;
3083 "delegate_member_ids_v" "delegating_population_snapshot"."delegate_member_ids"%TYPE;
3084 "weight_v" INT4;
3085 "sub_weight_v" INT4;
3086 BEGIN
3087 "weight_v" := 0;
3088 FOR "issue_delegation_row" IN
3089 SELECT * FROM "issue_delegation"
3090 WHERE "trustee_id" = "member_id_p"
3091 AND "issue_id" = "issue_id_p"
3092 LOOP
3093 IF NOT EXISTS (
3094 SELECT NULL FROM "direct_population_snapshot"
3095 WHERE "issue_id" = "issue_id_p"
3096 AND "event" = 'periodic'
3097 AND "member_id" = "issue_delegation_row"."truster_id"
3098 ) AND NOT EXISTS (
3099 SELECT NULL FROM "delegating_population_snapshot"
3100 WHERE "issue_id" = "issue_id_p"
3101 AND "event" = 'periodic'
3102 AND "member_id" = "issue_delegation_row"."truster_id"
3103 ) THEN
3104 "delegate_member_ids_v" :=
3105 "member_id_p" || "delegate_member_ids_p";
3106 INSERT INTO "delegating_population_snapshot" (
3107 "issue_id",
3108 "event",
3109 "member_id",
3110 "scope",
3111 "delegate_member_ids"
3112 ) VALUES (
3113 "issue_id_p",
3114 'periodic',
3115 "issue_delegation_row"."truster_id",
3116 "issue_delegation_row"."scope",
3117 "delegate_member_ids_v"
3118 );
3119 "sub_weight_v" := 1 +
3120 "weight_of_added_delegations_for_population_snapshot"(
3121 "issue_id_p",
3122 "issue_delegation_row"."truster_id",
3123 "delegate_member_ids_v"
3124 );
3125 UPDATE "delegating_population_snapshot"
3126 SET "weight" = "sub_weight_v"
3127 WHERE "issue_id" = "issue_id_p"
3128 AND "event" = 'periodic'
3129 AND "member_id" = "issue_delegation_row"."truster_id";
3130 "weight_v" := "weight_v" + "sub_weight_v";
3131 END IF;
3132 END LOOP;
3133 RETURN "weight_v";
3134 END;
3135 $$;
3137 COMMENT ON FUNCTION "weight_of_added_delegations_for_population_snapshot"
3138 ( "issue"."id"%TYPE,
3139 "member"."id"%TYPE,
3140 "delegating_population_snapshot"."delegate_member_ids"%TYPE )
3141 IS 'Helper function for "create_population_snapshot" function';
3144 CREATE FUNCTION "create_population_snapshot"
3145 ( "issue_id_p" "issue"."id"%TYPE )
3146 RETURNS VOID
3147 LANGUAGE 'plpgsql' VOLATILE AS $$
3148 DECLARE
3149 "member_id_v" "member"."id"%TYPE;
3150 BEGIN
3151 DELETE FROM "direct_population_snapshot"
3152 WHERE "issue_id" = "issue_id_p"
3153 AND "event" = 'periodic';
3154 DELETE FROM "delegating_population_snapshot"
3155 WHERE "issue_id" = "issue_id_p"
3156 AND "event" = 'periodic';
3157 INSERT INTO "direct_population_snapshot"
3158 ("issue_id", "event", "member_id")
3159 SELECT
3160 "issue_id_p" AS "issue_id",
3161 'periodic'::"snapshot_event" AS "event",
3162 "member"."id" AS "member_id"
3163 FROM "issue"
3164 JOIN "area" ON "issue"."area_id" = "area"."id"
3165 JOIN "membership" ON "area"."id" = "membership"."area_id"
3166 JOIN "member" ON "membership"."member_id" = "member"."id"
3167 JOIN "privilege"
3168 ON "privilege"."unit_id" = "area"."unit_id"
3169 AND "privilege"."member_id" = "member"."id"
3170 WHERE "issue"."id" = "issue_id_p"
3171 AND "member"."active" AND "privilege"."voting_right"
3172 UNION
3173 SELECT
3174 "issue_id_p" AS "issue_id",
3175 'periodic'::"snapshot_event" AS "event",
3176 "member"."id" AS "member_id"
3177 FROM "issue"
3178 JOIN "area" ON "issue"."area_id" = "area"."id"
3179 JOIN "interest" ON "issue"."id" = "interest"."issue_id"
3180 JOIN "member" ON "interest"."member_id" = "member"."id"
3181 JOIN "privilege"
3182 ON "privilege"."unit_id" = "area"."unit_id"
3183 AND "privilege"."member_id" = "member"."id"
3184 WHERE "issue"."id" = "issue_id_p"
3185 AND "member"."active" AND "privilege"."voting_right";
3186 FOR "member_id_v" IN
3187 SELECT "member_id" FROM "direct_population_snapshot"
3188 WHERE "issue_id" = "issue_id_p"
3189 AND "event" = 'periodic'
3190 LOOP
3191 UPDATE "direct_population_snapshot" SET
3192 "weight" = 1 +
3193 "weight_of_added_delegations_for_population_snapshot"(
3194 "issue_id_p",
3195 "member_id_v",
3196 '{}'
3198 WHERE "issue_id" = "issue_id_p"
3199 AND "event" = 'periodic'
3200 AND "member_id" = "member_id_v";
3201 END LOOP;
3202 RETURN;
3203 END;
3204 $$;
3206 COMMENT ON FUNCTION "create_population_snapshot"
3207 ( "issue"."id"%TYPE )
3208 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.';
3211 CREATE FUNCTION "weight_of_added_delegations_for_interest_snapshot"
3212 ( "issue_id_p" "issue"."id"%TYPE,
3213 "member_id_p" "member"."id"%TYPE,
3214 "delegate_member_ids_p" "delegating_interest_snapshot"."delegate_member_ids"%TYPE )
3215 RETURNS "direct_interest_snapshot"."weight"%TYPE
3216 LANGUAGE 'plpgsql' VOLATILE AS $$
3217 DECLARE
3218 "issue_delegation_row" "issue_delegation"%ROWTYPE;
3219 "delegate_member_ids_v" "delegating_interest_snapshot"."delegate_member_ids"%TYPE;
3220 "weight_v" INT4;
3221 "sub_weight_v" INT4;
3222 BEGIN
3223 "weight_v" := 0;
3224 FOR "issue_delegation_row" IN
3225 SELECT * FROM "issue_delegation"
3226 WHERE "trustee_id" = "member_id_p"
3227 AND "issue_id" = "issue_id_p"
3228 LOOP
3229 IF NOT EXISTS (
3230 SELECT NULL FROM "direct_interest_snapshot"
3231 WHERE "issue_id" = "issue_id_p"
3232 AND "event" = 'periodic'
3233 AND "member_id" = "issue_delegation_row"."truster_id"
3234 ) AND NOT EXISTS (
3235 SELECT NULL FROM "delegating_interest_snapshot"
3236 WHERE "issue_id" = "issue_id_p"
3237 AND "event" = 'periodic'
3238 AND "member_id" = "issue_delegation_row"."truster_id"
3239 ) THEN
3240 "delegate_member_ids_v" :=
3241 "member_id_p" || "delegate_member_ids_p";
3242 INSERT INTO "delegating_interest_snapshot" (
3243 "issue_id",
3244 "event",
3245 "member_id",
3246 "scope",
3247 "delegate_member_ids"
3248 ) VALUES (
3249 "issue_id_p",
3250 'periodic',
3251 "issue_delegation_row"."truster_id",
3252 "issue_delegation_row"."scope",
3253 "delegate_member_ids_v"
3254 );
3255 "sub_weight_v" := 1 +
3256 "weight_of_added_delegations_for_interest_snapshot"(
3257 "issue_id_p",
3258 "issue_delegation_row"."truster_id",
3259 "delegate_member_ids_v"
3260 );
3261 UPDATE "delegating_interest_snapshot"
3262 SET "weight" = "sub_weight_v"
3263 WHERE "issue_id" = "issue_id_p"
3264 AND "event" = 'periodic'
3265 AND "member_id" = "issue_delegation_row"."truster_id";
3266 "weight_v" := "weight_v" + "sub_weight_v";
3267 END IF;
3268 END LOOP;
3269 RETURN "weight_v";
3270 END;
3271 $$;
3273 COMMENT ON FUNCTION "weight_of_added_delegations_for_interest_snapshot"
3274 ( "issue"."id"%TYPE,
3275 "member"."id"%TYPE,
3276 "delegating_interest_snapshot"."delegate_member_ids"%TYPE )
3277 IS 'Helper function for "create_interest_snapshot" function';
3280 CREATE FUNCTION "create_interest_snapshot"
3281 ( "issue_id_p" "issue"."id"%TYPE )
3282 RETURNS VOID
3283 LANGUAGE 'plpgsql' VOLATILE AS $$
3284 DECLARE
3285 "member_id_v" "member"."id"%TYPE;
3286 BEGIN
3287 DELETE FROM "direct_interest_snapshot"
3288 WHERE "issue_id" = "issue_id_p"
3289 AND "event" = 'periodic';
3290 DELETE FROM "delegating_interest_snapshot"
3291 WHERE "issue_id" = "issue_id_p"
3292 AND "event" = 'periodic';
3293 DELETE FROM "direct_supporter_snapshot"
3294 WHERE "issue_id" = "issue_id_p"
3295 AND "event" = 'periodic';
3296 INSERT INTO "direct_interest_snapshot"
3297 ("issue_id", "event", "member_id")
3298 SELECT
3299 "issue_id_p" AS "issue_id",
3300 'periodic' AS "event",
3301 "member"."id" AS "member_id"
3302 FROM "issue"
3303 JOIN "area" ON "issue"."area_id" = "area"."id"
3304 JOIN "interest" ON "issue"."id" = "interest"."issue_id"
3305 JOIN "member" ON "interest"."member_id" = "member"."id"
3306 JOIN "privilege"
3307 ON "privilege"."unit_id" = "area"."unit_id"
3308 AND "privilege"."member_id" = "member"."id"
3309 WHERE "issue"."id" = "issue_id_p"
3310 AND "member"."active" AND "privilege"."voting_right";
3311 FOR "member_id_v" IN
3312 SELECT "member_id" FROM "direct_interest_snapshot"
3313 WHERE "issue_id" = "issue_id_p"
3314 AND "event" = 'periodic'
3315 LOOP
3316 UPDATE "direct_interest_snapshot" SET
3317 "weight" = 1 +
3318 "weight_of_added_delegations_for_interest_snapshot"(
3319 "issue_id_p",
3320 "member_id_v",
3321 '{}'
3323 WHERE "issue_id" = "issue_id_p"
3324 AND "event" = 'periodic'
3325 AND "member_id" = "member_id_v";
3326 END LOOP;
3327 INSERT INTO "direct_supporter_snapshot"
3328 ( "issue_id", "initiative_id", "event", "member_id",
3329 "draft_id", "informed", "satisfied" )
3330 SELECT
3331 "issue_id_p" AS "issue_id",
3332 "initiative"."id" AS "initiative_id",
3333 'periodic' AS "event",
3334 "supporter"."member_id" AS "member_id",
3335 "supporter"."draft_id" AS "draft_id",
3336 "supporter"."draft_id" = "current_draft"."id" AS "informed",
3337 NOT EXISTS (
3338 SELECT NULL FROM "critical_opinion"
3339 WHERE "initiative_id" = "initiative"."id"
3340 AND "member_id" = "supporter"."member_id"
3341 ) AS "satisfied"
3342 FROM "initiative"
3343 JOIN "supporter"
3344 ON "supporter"."initiative_id" = "initiative"."id"
3345 JOIN "current_draft"
3346 ON "initiative"."id" = "current_draft"."initiative_id"
3347 JOIN "direct_interest_snapshot"
3348 ON "supporter"."member_id" = "direct_interest_snapshot"."member_id"
3349 AND "initiative"."issue_id" = "direct_interest_snapshot"."issue_id"
3350 AND "event" = 'periodic'
3351 WHERE "initiative"."issue_id" = "issue_id_p";
3352 RETURN;
3353 END;
3354 $$;
3356 COMMENT ON FUNCTION "create_interest_snapshot"
3357 ( "issue"."id"%TYPE )
3358 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.';
3361 CREATE FUNCTION "create_snapshot"
3362 ( "issue_id_p" "issue"."id"%TYPE )
3363 RETURNS VOID
3364 LANGUAGE 'plpgsql' VOLATILE AS $$
3365 DECLARE
3366 "initiative_id_v" "initiative"."id"%TYPE;
3367 "suggestion_id_v" "suggestion"."id"%TYPE;
3368 BEGIN
3369 PERFORM "lock_issue"("issue_id_p");
3370 PERFORM "create_population_snapshot"("issue_id_p");
3371 PERFORM "create_interest_snapshot"("issue_id_p");
3372 UPDATE "issue" SET
3373 "snapshot" = now(),
3374 "latest_snapshot_event" = 'periodic',
3375 "population" = (
3376 SELECT coalesce(sum("weight"), 0)
3377 FROM "direct_population_snapshot"
3378 WHERE "issue_id" = "issue_id_p"
3379 AND "event" = 'periodic'
3381 WHERE "id" = "issue_id_p";
3382 FOR "initiative_id_v" IN
3383 SELECT "id" FROM "initiative" WHERE "issue_id" = "issue_id_p"
3384 LOOP
3385 UPDATE "initiative" SET
3386 "supporter_count" = (
3387 SELECT coalesce(sum("di"."weight"), 0)
3388 FROM "direct_interest_snapshot" AS "di"
3389 JOIN "direct_supporter_snapshot" AS "ds"
3390 ON "di"."member_id" = "ds"."member_id"
3391 WHERE "di"."issue_id" = "issue_id_p"
3392 AND "di"."event" = 'periodic'
3393 AND "ds"."initiative_id" = "initiative_id_v"
3394 AND "ds"."event" = 'periodic'
3395 ),
3396 "informed_supporter_count" = (
3397 SELECT coalesce(sum("di"."weight"), 0)
3398 FROM "direct_interest_snapshot" AS "di"
3399 JOIN "direct_supporter_snapshot" AS "ds"
3400 ON "di"."member_id" = "ds"."member_id"
3401 WHERE "di"."issue_id" = "issue_id_p"
3402 AND "di"."event" = 'periodic'
3403 AND "ds"."initiative_id" = "initiative_id_v"
3404 AND "ds"."event" = 'periodic'
3405 AND "ds"."informed"
3406 ),
3407 "satisfied_supporter_count" = (
3408 SELECT coalesce(sum("di"."weight"), 0)
3409 FROM "direct_interest_snapshot" AS "di"
3410 JOIN "direct_supporter_snapshot" AS "ds"
3411 ON "di"."member_id" = "ds"."member_id"
3412 WHERE "di"."issue_id" = "issue_id_p"
3413 AND "di"."event" = 'periodic'
3414 AND "ds"."initiative_id" = "initiative_id_v"
3415 AND "ds"."event" = 'periodic'
3416 AND "ds"."satisfied"
3417 ),
3418 "satisfied_informed_supporter_count" = (
3419 SELECT coalesce(sum("di"."weight"), 0)
3420 FROM "direct_interest_snapshot" AS "di"
3421 JOIN "direct_supporter_snapshot" AS "ds"
3422 ON "di"."member_id" = "ds"."member_id"
3423 WHERE "di"."issue_id" = "issue_id_p"
3424 AND "di"."event" = 'periodic'
3425 AND "ds"."initiative_id" = "initiative_id_v"
3426 AND "ds"."event" = 'periodic'
3427 AND "ds"."informed"
3428 AND "ds"."satisfied"
3430 WHERE "id" = "initiative_id_v";
3431 FOR "suggestion_id_v" IN
3432 SELECT "id" FROM "suggestion"
3433 WHERE "initiative_id" = "initiative_id_v"
3434 LOOP
3435 UPDATE "suggestion" SET
3436 "minus2_unfulfilled_count" = (
3437 SELECT coalesce(sum("snapshot"."weight"), 0)
3438 FROM "issue" CROSS JOIN "opinion"
3439 JOIN "direct_interest_snapshot" AS "snapshot"
3440 ON "snapshot"."issue_id" = "issue"."id"
3441 AND "snapshot"."event" = "issue"."latest_snapshot_event"
3442 AND "snapshot"."member_id" = "opinion"."member_id"
3443 WHERE "issue"."id" = "issue_id_p"
3444 AND "opinion"."suggestion_id" = "suggestion_id_v"
3445 AND "opinion"."degree" = -2
3446 AND "opinion"."fulfilled" = FALSE
3447 ),
3448 "minus2_fulfilled_count" = (
3449 SELECT coalesce(sum("snapshot"."weight"), 0)
3450 FROM "issue" CROSS JOIN "opinion"
3451 JOIN "direct_interest_snapshot" AS "snapshot"
3452 ON "snapshot"."issue_id" = "issue"."id"
3453 AND "snapshot"."event" = "issue"."latest_snapshot_event"
3454 AND "snapshot"."member_id" = "opinion"."member_id"
3455 WHERE "issue"."id" = "issue_id_p"
3456 AND "opinion"."suggestion_id" = "suggestion_id_v"
3457 AND "opinion"."degree" = -2
3458 AND "opinion"."fulfilled" = TRUE
3459 ),
3460 "minus1_unfulfilled_count" = (
3461 SELECT coalesce(sum("snapshot"."weight"), 0)
3462 FROM "issue" CROSS JOIN "opinion"
3463 JOIN "direct_interest_snapshot" AS "snapshot"
3464 ON "snapshot"."issue_id" = "issue"."id"
3465 AND "snapshot"."event" = "issue"."latest_snapshot_event"
3466 AND "snapshot"."member_id" = "opinion"."member_id"
3467 WHERE "issue"."id" = "issue_id_p"
3468 AND "opinion"."suggestion_id" = "suggestion_id_v"
3469 AND "opinion"."degree" = -1
3470 AND "opinion"."fulfilled" = FALSE
3471 ),
3472 "minus1_fulfilled_count" = (
3473 SELECT coalesce(sum("snapshot"."weight"), 0)
3474 FROM "issue" CROSS JOIN "opinion"
3475 JOIN "direct_interest_snapshot" AS "snapshot"
3476 ON "snapshot"."issue_id" = "issue"."id"
3477 AND "snapshot"."event" = "issue"."latest_snapshot_event"
3478 AND "snapshot"."member_id" = "opinion"."member_id"
3479 WHERE "issue"."id" = "issue_id_p"
3480 AND "opinion"."suggestion_id" = "suggestion_id_v"
3481 AND "opinion"."degree" = -1
3482 AND "opinion"."fulfilled" = TRUE
3483 ),
3484 "plus1_unfulfilled_count" = (
3485 SELECT coalesce(sum("snapshot"."weight"), 0)
3486 FROM "issue" CROSS JOIN "opinion"
3487 JOIN "direct_interest_snapshot" AS "snapshot"
3488 ON "snapshot"."issue_id" = "issue"."id"
3489 AND "snapshot"."event" = "issue"."latest_snapshot_event"
3490 AND "snapshot"."member_id" = "opinion"."member_id"
3491 WHERE "issue"."id" = "issue_id_p"
3492 AND "opinion"."suggestion_id" = "suggestion_id_v"
3493 AND "opinion"."degree" = 1
3494 AND "opinion"."fulfilled" = FALSE
3495 ),
3496 "plus1_fulfilled_count" = (
3497 SELECT coalesce(sum("snapshot"."weight"), 0)
3498 FROM "issue" CROSS JOIN "opinion"
3499 JOIN "direct_interest_snapshot" AS "snapshot"
3500 ON "snapshot"."issue_id" = "issue"."id"
3501 AND "snapshot"."event" = "issue"."latest_snapshot_event"
3502 AND "snapshot"."member_id" = "opinion"."member_id"
3503 WHERE "issue"."id" = "issue_id_p"
3504 AND "opinion"."suggestion_id" = "suggestion_id_v"
3505 AND "opinion"."degree" = 1
3506 AND "opinion"."fulfilled" = TRUE
3507 ),
3508 "plus2_unfulfilled_count" = (
3509 SELECT coalesce(sum("snapshot"."weight"), 0)
3510 FROM "issue" CROSS JOIN "opinion"
3511 JOIN "direct_interest_snapshot" AS "snapshot"
3512 ON "snapshot"."issue_id" = "issue"."id"
3513 AND "snapshot"."event" = "issue"."latest_snapshot_event"
3514 AND "snapshot"."member_id" = "opinion"."member_id"
3515 WHERE "issue"."id" = "issue_id_p"
3516 AND "opinion"."suggestion_id" = "suggestion_id_v"
3517 AND "opinion"."degree" = 2
3518 AND "opinion"."fulfilled" = FALSE
3519 ),
3520 "plus2_fulfilled_count" = (
3521 SELECT coalesce(sum("snapshot"."weight"), 0)
3522 FROM "issue" CROSS JOIN "opinion"
3523 JOIN "direct_interest_snapshot" AS "snapshot"
3524 ON "snapshot"."issue_id" = "issue"."id"
3525 AND "snapshot"."event" = "issue"."latest_snapshot_event"
3526 AND "snapshot"."member_id" = "opinion"."member_id"
3527 WHERE "issue"."id" = "issue_id_p"
3528 AND "opinion"."suggestion_id" = "suggestion_id_v"
3529 AND "opinion"."degree" = 2
3530 AND "opinion"."fulfilled" = TRUE
3532 WHERE "suggestion"."id" = "suggestion_id_v";
3533 END LOOP;
3534 END LOOP;
3535 RETURN;
3536 END;
3537 $$;
3539 COMMENT ON FUNCTION "create_snapshot"
3540 ( "issue"."id"%TYPE )
3541 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.';
3544 CREATE FUNCTION "set_snapshot_event"
3545 ( "issue_id_p" "issue"."id"%TYPE,
3546 "event_p" "snapshot_event" )
3547 RETURNS VOID
3548 LANGUAGE 'plpgsql' VOLATILE AS $$
3549 DECLARE
3550 "event_v" "issue"."latest_snapshot_event"%TYPE;
3551 BEGIN
3552 SELECT "latest_snapshot_event" INTO "event_v" FROM "issue"
3553 WHERE "id" = "issue_id_p" FOR UPDATE;
3554 UPDATE "issue" SET "latest_snapshot_event" = "event_p"
3555 WHERE "id" = "issue_id_p";
3556 UPDATE "direct_population_snapshot" SET "event" = "event_p"
3557 WHERE "issue_id" = "issue_id_p" AND "event" = "event_v";
3558 UPDATE "delegating_population_snapshot" SET "event" = "event_p"
3559 WHERE "issue_id" = "issue_id_p" AND "event" = "event_v";
3560 UPDATE "direct_interest_snapshot" SET "event" = "event_p"
3561 WHERE "issue_id" = "issue_id_p" AND "event" = "event_v";
3562 UPDATE "delegating_interest_snapshot" SET "event" = "event_p"
3563 WHERE "issue_id" = "issue_id_p" AND "event" = "event_v";
3564 UPDATE "direct_supporter_snapshot" SET "event" = "event_p"
3565 WHERE "issue_id" = "issue_id_p" AND "event" = "event_v";
3566 RETURN;
3567 END;
3568 $$;
3570 COMMENT ON FUNCTION "set_snapshot_event"
3571 ( "issue"."id"%TYPE,
3572 "snapshot_event" )
3573 IS 'Change "event" attribute of the previous ''periodic'' snapshot';
3577 ---------------------
3578 -- Freezing issues --
3579 ---------------------
3581 CREATE FUNCTION "freeze_after_snapshot"
3582 ( "issue_id_p" "issue"."id"%TYPE )
3583 RETURNS VOID
3584 LANGUAGE 'plpgsql' VOLATILE AS $$
3585 DECLARE
3586 "issue_row" "issue"%ROWTYPE;
3587 "policy_row" "policy"%ROWTYPE;
3588 "initiative_row" "initiative"%ROWTYPE;
3589 BEGIN
3590 SELECT * INTO "issue_row" FROM "issue" WHERE "id" = "issue_id_p";
3591 SELECT * INTO "policy_row"
3592 FROM "policy" WHERE "id" = "issue_row"."policy_id";
3593 PERFORM "set_snapshot_event"("issue_id_p", 'full_freeze');
3594 FOR "initiative_row" IN
3595 SELECT * FROM "initiative"
3596 WHERE "issue_id" = "issue_id_p" AND "revoked" ISNULL
3597 LOOP
3598 IF
3599 "initiative_row"."polling" OR (
3600 "initiative_row"."satisfied_supporter_count" > 0 AND
3601 "initiative_row"."satisfied_supporter_count" *
3602 "policy_row"."initiative_quorum_den" >=
3603 "issue_row"."population" * "policy_row"."initiative_quorum_num"
3605 THEN
3606 UPDATE "initiative" SET "admitted" = TRUE
3607 WHERE "id" = "initiative_row"."id";
3608 ELSE
3609 UPDATE "initiative" SET "admitted" = FALSE
3610 WHERE "id" = "initiative_row"."id";
3611 END IF;
3612 END LOOP;
3613 IF EXISTS (
3614 SELECT NULL FROM "initiative"
3615 WHERE "issue_id" = "issue_id_p" AND "admitted" = TRUE
3616 ) THEN
3617 UPDATE "issue" SET
3618 "state" = 'voting',
3619 "accepted" = coalesce("accepted", now()),
3620 "half_frozen" = coalesce("half_frozen", now()),
3621 "fully_frozen" = now()
3622 WHERE "id" = "issue_id_p";
3623 ELSE
3624 UPDATE "issue" SET
3625 "state" = 'canceled_no_initiative_admitted',
3626 "accepted" = coalesce("accepted", now()),
3627 "half_frozen" = coalesce("half_frozen", now()),
3628 "fully_frozen" = now(),
3629 "closed" = now(),
3630 "ranks_available" = TRUE
3631 WHERE "id" = "issue_id_p";
3632 -- NOTE: The following DELETE statements have effect only when
3633 -- issue state has been manipulated
3634 DELETE FROM "direct_voter" WHERE "issue_id" = "issue_id_p";
3635 DELETE FROM "delegating_voter" WHERE "issue_id" = "issue_id_p";
3636 DELETE FROM "battle" WHERE "issue_id" = "issue_id_p";
3637 END IF;
3638 RETURN;
3639 END;
3640 $$;
3642 COMMENT ON FUNCTION "freeze_after_snapshot"
3643 ( "issue"."id"%TYPE )
3644 IS 'This function freezes an issue (fully) and starts voting, but must only be called when "create_snapshot" was called in the same transaction.';
3647 CREATE FUNCTION "manual_freeze"("issue_id_p" "issue"."id"%TYPE)
3648 RETURNS VOID
3649 LANGUAGE 'plpgsql' VOLATILE AS $$
3650 DECLARE
3651 "issue_row" "issue"%ROWTYPE;
3652 BEGIN
3653 PERFORM "create_snapshot"("issue_id_p");
3654 PERFORM "freeze_after_snapshot"("issue_id_p");
3655 RETURN;
3656 END;
3657 $$;
3659 COMMENT ON FUNCTION "manual_freeze"
3660 ( "issue"."id"%TYPE )
3661 IS 'Freeze an issue manually (fully) and start voting';
3665 -----------------------
3666 -- Counting of votes --
3667 -----------------------
3670 CREATE FUNCTION "weight_of_added_vote_delegations"
3671 ( "issue_id_p" "issue"."id"%TYPE,
3672 "member_id_p" "member"."id"%TYPE,
3673 "delegate_member_ids_p" "delegating_voter"."delegate_member_ids"%TYPE )
3674 RETURNS "direct_voter"."weight"%TYPE
3675 LANGUAGE 'plpgsql' VOLATILE AS $$
3676 DECLARE
3677 "issue_delegation_row" "issue_delegation"%ROWTYPE;
3678 "delegate_member_ids_v" "delegating_voter"."delegate_member_ids"%TYPE;
3679 "weight_v" INT4;
3680 "sub_weight_v" INT4;
3681 BEGIN
3682 "weight_v" := 0;
3683 FOR "issue_delegation_row" IN
3684 SELECT * FROM "issue_delegation"
3685 WHERE "trustee_id" = "member_id_p"
3686 AND "issue_id" = "issue_id_p"
3687 LOOP
3688 IF NOT EXISTS (
3689 SELECT NULL FROM "direct_voter"
3690 WHERE "member_id" = "issue_delegation_row"."truster_id"
3691 AND "issue_id" = "issue_id_p"
3692 ) AND NOT EXISTS (
3693 SELECT NULL FROM "delegating_voter"
3694 WHERE "member_id" = "issue_delegation_row"."truster_id"
3695 AND "issue_id" = "issue_id_p"
3696 ) THEN
3697 "delegate_member_ids_v" :=
3698 "member_id_p" || "delegate_member_ids_p";
3699 INSERT INTO "delegating_voter" (
3700 "issue_id",
3701 "member_id",
3702 "scope",
3703 "delegate_member_ids"
3704 ) VALUES (
3705 "issue_id_p",
3706 "issue_delegation_row"."truster_id",
3707 "issue_delegation_row"."scope",
3708 "delegate_member_ids_v"
3709 );
3710 "sub_weight_v" := 1 +
3711 "weight_of_added_vote_delegations"(
3712 "issue_id_p",
3713 "issue_delegation_row"."truster_id",
3714 "delegate_member_ids_v"
3715 );
3716 UPDATE "delegating_voter"
3717 SET "weight" = "sub_weight_v"
3718 WHERE "issue_id" = "issue_id_p"
3719 AND "member_id" = "issue_delegation_row"."truster_id";
3720 "weight_v" := "weight_v" + "sub_weight_v";
3721 END IF;
3722 END LOOP;
3723 RETURN "weight_v";
3724 END;
3725 $$;
3727 COMMENT ON FUNCTION "weight_of_added_vote_delegations"
3728 ( "issue"."id"%TYPE,
3729 "member"."id"%TYPE,
3730 "delegating_voter"."delegate_member_ids"%TYPE )
3731 IS 'Helper function for "add_vote_delegations" function';
3734 CREATE FUNCTION "add_vote_delegations"
3735 ( "issue_id_p" "issue"."id"%TYPE )
3736 RETURNS VOID
3737 LANGUAGE 'plpgsql' VOLATILE AS $$
3738 DECLARE
3739 "member_id_v" "member"."id"%TYPE;
3740 BEGIN
3741 FOR "member_id_v" IN
3742 SELECT "member_id" FROM "direct_voter"
3743 WHERE "issue_id" = "issue_id_p"
3744 LOOP
3745 UPDATE "direct_voter" SET
3746 "weight" = "weight" + "weight_of_added_vote_delegations"(
3747 "issue_id_p",
3748 "member_id_v",
3749 '{}'
3751 WHERE "member_id" = "member_id_v"
3752 AND "issue_id" = "issue_id_p";
3753 END LOOP;
3754 RETURN;
3755 END;
3756 $$;
3758 COMMENT ON FUNCTION "add_vote_delegations"
3759 ( "issue_id_p" "issue"."id"%TYPE )
3760 IS 'Helper function for "close_voting" function';
3763 CREATE FUNCTION "close_voting"("issue_id_p" "issue"."id"%TYPE)
3764 RETURNS VOID
3765 LANGUAGE 'plpgsql' VOLATILE AS $$
3766 DECLARE
3767 "area_id_v" "area"."id"%TYPE;
3768 "unit_id_v" "unit"."id"%TYPE;
3769 "member_id_v" "member"."id"%TYPE;
3770 BEGIN
3771 PERFORM "lock_issue"("issue_id_p");
3772 SELECT "area_id" INTO "area_id_v" FROM "issue" WHERE "id" = "issue_id_p";
3773 SELECT "unit_id" INTO "unit_id_v" FROM "area" WHERE "id" = "area_id_v";
3774 -- delete delegating votes (in cases of manual reset of issue state):
3775 DELETE FROM "delegating_voter"
3776 WHERE "issue_id" = "issue_id_p";
3777 -- delete votes from non-privileged voters:
3778 DELETE FROM "direct_voter"
3779 USING (
3780 SELECT
3781 "direct_voter"."member_id"
3782 FROM "direct_voter"
3783 JOIN "member" ON "direct_voter"."member_id" = "member"."id"
3784 LEFT JOIN "privilege"
3785 ON "privilege"."unit_id" = "unit_id_v"
3786 AND "privilege"."member_id" = "direct_voter"."member_id"
3787 WHERE "direct_voter"."issue_id" = "issue_id_p" AND (
3788 "member"."active" = FALSE OR
3789 "privilege"."voting_right" ISNULL OR
3790 "privilege"."voting_right" = FALSE
3792 ) AS "subquery"
3793 WHERE "direct_voter"."issue_id" = "issue_id_p"
3794 AND "direct_voter"."member_id" = "subquery"."member_id";
3795 -- consider delegations:
3796 UPDATE "direct_voter" SET "weight" = 1
3797 WHERE "issue_id" = "issue_id_p";
3798 PERFORM "add_vote_delegations"("issue_id_p");
3799 -- set voter count and mark issue as being calculated:
3800 UPDATE "issue" SET
3801 "state" = 'calculation',
3802 "closed" = now(),
3803 "voter_count" = (
3804 SELECT coalesce(sum("weight"), 0)
3805 FROM "direct_voter" WHERE "issue_id" = "issue_id_p"
3807 WHERE "id" = "issue_id_p";
3808 -- materialize battle_view:
3809 -- NOTE: "closed" column of issue must be set at this point
3810 DELETE FROM "battle" WHERE "issue_id" = "issue_id_p";
3811 INSERT INTO "battle" (
3812 "issue_id",
3813 "winning_initiative_id", "losing_initiative_id",
3814 "count"
3815 ) SELECT
3816 "issue_id",
3817 "winning_initiative_id", "losing_initiative_id",
3818 "count"
3819 FROM "battle_view" WHERE "issue_id" = "issue_id_p";
3820 -- copy "positive_votes" and "negative_votes" from "battle" table:
3821 UPDATE "initiative" SET
3822 "positive_votes" = "battle_win"."count",
3823 "negative_votes" = "battle_lose"."count"
3824 FROM "battle" AS "battle_win", "battle" AS "battle_lose"
3825 WHERE
3826 "battle_win"."issue_id" = "issue_id_p" AND
3827 "battle_win"."winning_initiative_id" = "initiative"."id" AND
3828 "battle_win"."losing_initiative_id" ISNULL AND
3829 "battle_lose"."issue_id" = "issue_id_p" AND
3830 "battle_lose"."losing_initiative_id" = "initiative"."id" AND
3831 "battle_lose"."winning_initiative_id" ISNULL;
3832 END;
3833 $$;
3835 COMMENT ON FUNCTION "close_voting"
3836 ( "issue"."id"%TYPE )
3837 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.';
3840 CREATE FUNCTION "defeat_strength"
3841 ( "positive_votes_p" INT4, "negative_votes_p" INT4 )
3842 RETURNS INT8
3843 LANGUAGE 'plpgsql' IMMUTABLE AS $$
3844 BEGIN
3845 IF "positive_votes_p" > "negative_votes_p" THEN
3846 RETURN ("positive_votes_p"::INT8 << 31) - "negative_votes_p"::INT8;
3847 ELSIF "positive_votes_p" = "negative_votes_p" THEN
3848 RETURN 0;
3849 ELSE
3850 RETURN -1;
3851 END IF;
3852 END;
3853 $$;
3855 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';
3858 CREATE FUNCTION "calculate_ranks"("issue_id_p" "issue"."id"%TYPE)
3859 RETURNS VOID
3860 LANGUAGE 'plpgsql' VOLATILE AS $$
3861 DECLARE
3862 "issue_row" "issue"%ROWTYPE;
3863 "policy_row" "policy"%ROWTYPE;
3864 "dimension_v" INTEGER;
3865 "vote_matrix" INT4[][]; -- absolute votes
3866 "matrix" INT8[][]; -- defeat strength / best paths
3867 "i" INTEGER;
3868 "j" INTEGER;
3869 "k" INTEGER;
3870 "battle_row" "battle"%ROWTYPE;
3871 "rank_ary" INT4[];
3872 "rank_v" INT4;
3873 "done_v" INTEGER;
3874 "winners_ary" INTEGER[];
3875 "initiative_id_v" "initiative"."id"%TYPE;
3876 BEGIN
3877 SELECT * INTO "issue_row"
3878 FROM "issue" WHERE "id" = "issue_id_p"
3879 FOR UPDATE;
3880 SELECT * INTO "policy_row"
3881 FROM "policy" WHERE "id" = "issue_row"."policy_id";
3882 SELECT count(1) INTO "dimension_v"
3883 FROM "battle_participant" WHERE "issue_id" = "issue_id_p";
3884 -- Create "vote_matrix" with absolute number of votes in pairwise
3885 -- comparison:
3886 "vote_matrix" := array_fill(NULL::INT4, ARRAY["dimension_v", "dimension_v"]);
3887 "i" := 1;
3888 "j" := 2;
3889 FOR "battle_row" IN
3890 SELECT * FROM "battle" WHERE "issue_id" = "issue_id_p"
3891 ORDER BY
3892 "winning_initiative_id" NULLS LAST,
3893 "losing_initiative_id" NULLS LAST
3894 LOOP
3895 "vote_matrix"["i"]["j"] := "battle_row"."count";
3896 IF "j" = "dimension_v" THEN
3897 "i" := "i" + 1;
3898 "j" := 1;
3899 ELSE
3900 "j" := "j" + 1;
3901 IF "j" = "i" THEN
3902 "j" := "j" + 1;
3903 END IF;
3904 END IF;
3905 END LOOP;
3906 IF "i" != "dimension_v" OR "j" != "dimension_v" + 1 THEN
3907 RAISE EXCEPTION 'Wrong battle count (should not happen)';
3908 END IF;
3909 -- Store defeat strengths in "matrix" using "defeat_strength"
3910 -- function:
3911 "matrix" := array_fill(NULL::INT8, ARRAY["dimension_v", "dimension_v"]);
3912 "i" := 1;
3913 LOOP
3914 "j" := 1;
3915 LOOP
3916 IF "i" != "j" THEN
3917 "matrix"["i"]["j"] := "defeat_strength"(
3918 "vote_matrix"["i"]["j"],
3919 "vote_matrix"["j"]["i"]
3920 );
3921 END IF;
3922 EXIT WHEN "j" = "dimension_v";
3923 "j" := "j" + 1;
3924 END LOOP;
3925 EXIT WHEN "i" = "dimension_v";
3926 "i" := "i" + 1;
3927 END LOOP;
3928 -- Find best paths:
3929 "i" := 1;
3930 LOOP
3931 "j" := 1;
3932 LOOP
3933 IF "i" != "j" THEN
3934 "k" := 1;
3935 LOOP
3936 IF "i" != "k" AND "j" != "k" THEN
3937 IF "matrix"["j"]["i"] < "matrix"["i"]["k"] THEN
3938 IF "matrix"["j"]["i"] > "matrix"["j"]["k"] THEN
3939 "matrix"["j"]["k"] := "matrix"["j"]["i"];
3940 END IF;
3941 ELSE
3942 IF "matrix"["i"]["k"] > "matrix"["j"]["k"] THEN
3943 "matrix"["j"]["k"] := "matrix"["i"]["k"];
3944 END IF;
3945 END IF;
3946 END IF;
3947 EXIT WHEN "k" = "dimension_v";
3948 "k" := "k" + 1;
3949 END LOOP;
3950 END IF;
3951 EXIT WHEN "j" = "dimension_v";
3952 "j" := "j" + 1;
3953 END LOOP;
3954 EXIT WHEN "i" = "dimension_v";
3955 "i" := "i" + 1;
3956 END LOOP;
3957 -- Determine order of winners:
3958 "rank_ary" := array_fill(NULL::INT4, ARRAY["dimension_v"]);
3959 "rank_v" := 1;
3960 "done_v" := 0;
3961 LOOP
3962 "winners_ary" := '{}';
3963 "i" := 1;
3964 LOOP
3965 IF "rank_ary"["i"] ISNULL THEN
3966 "j" := 1;
3967 LOOP
3968 IF
3969 "i" != "j" AND
3970 "rank_ary"["j"] ISNULL AND
3971 "matrix"["j"]["i"] > "matrix"["i"]["j"]
3972 THEN
3973 -- someone else is better
3974 EXIT;
3975 END IF;
3976 IF "j" = "dimension_v" THEN
3977 -- noone is better
3978 "winners_ary" := "winners_ary" || "i";
3979 EXIT;
3980 END IF;
3981 "j" := "j" + 1;
3982 END LOOP;
3983 END IF;
3984 EXIT WHEN "i" = "dimension_v";
3985 "i" := "i" + 1;
3986 END LOOP;
3987 "i" := 1;
3988 LOOP
3989 "rank_ary"["winners_ary"["i"]] := "rank_v";
3990 "done_v" := "done_v" + 1;
3991 EXIT WHEN "i" = array_upper("winners_ary", 1);
3992 "i" := "i" + 1;
3993 END LOOP;
3994 EXIT WHEN "done_v" = "dimension_v";
3995 "rank_v" := "rank_v" + 1;
3996 END LOOP;
3997 -- write preliminary results:
3998 "i" := 1;
3999 FOR "initiative_id_v" IN
4000 SELECT "id" FROM "initiative"
4001 WHERE "issue_id" = "issue_id_p" AND "admitted"
4002 ORDER BY "id"
4003 LOOP
4004 UPDATE "initiative" SET
4005 "direct_majority" =
4006 CASE WHEN "policy_row"."direct_majority_strict" THEN
4007 "positive_votes" * "policy_row"."direct_majority_den" >
4008 "policy_row"."direct_majority_num" * ("positive_votes"+"negative_votes")
4009 ELSE
4010 "positive_votes" * "policy_row"."direct_majority_den" >=
4011 "policy_row"."direct_majority_num" * ("positive_votes"+"negative_votes")
4012 END
4013 AND "positive_votes" >= "policy_row"."direct_majority_positive"
4014 AND "issue_row"."voter_count"-"negative_votes" >=
4015 "policy_row"."direct_majority_non_negative",
4016 "indirect_majority" =
4017 CASE WHEN "policy_row"."indirect_majority_strict" THEN
4018 "positive_votes" * "policy_row"."indirect_majority_den" >
4019 "policy_row"."indirect_majority_num" * ("positive_votes"+"negative_votes")
4020 ELSE
4021 "positive_votes" * "policy_row"."indirect_majority_den" >=
4022 "policy_row"."indirect_majority_num" * ("positive_votes"+"negative_votes")
4023 END
4024 AND "positive_votes" >= "policy_row"."indirect_majority_positive"
4025 AND "issue_row"."voter_count"-"negative_votes" >=
4026 "policy_row"."indirect_majority_non_negative",
4027 "schulze_rank" = "rank_ary"["i"],
4028 "better_than_status_quo" = "rank_ary"["i"] < "rank_ary"["dimension_v"],
4029 "worse_than_status_quo" = "rank_ary"["i"] > "rank_ary"["dimension_v"],
4030 "multistage_majority" = "rank_ary"["i"] >= "rank_ary"["dimension_v"],
4031 "reverse_beat_path" = "matrix"["dimension_v"]["i"] >= 0,
4032 "eligible" = FALSE,
4033 "winner" = FALSE,
4034 "rank" = NULL -- NOTE: in cases of manual reset of issue state
4035 WHERE "id" = "initiative_id_v";
4036 "i" := "i" + 1;
4037 END LOOP;
4038 IF "i" != "dimension_v" THEN
4039 RAISE EXCEPTION 'Wrong winner count (should not happen)';
4040 END IF;
4041 -- take indirect majorities into account:
4042 LOOP
4043 UPDATE "initiative" SET "indirect_majority" = TRUE
4044 FROM (
4045 SELECT "new_initiative"."id" AS "initiative_id"
4046 FROM "initiative" "old_initiative"
4047 JOIN "initiative" "new_initiative"
4048 ON "new_initiative"."issue_id" = "issue_id_p"
4049 AND "new_initiative"."indirect_majority" = FALSE
4050 JOIN "battle" "battle_win"
4051 ON "battle_win"."issue_id" = "issue_id_p"
4052 AND "battle_win"."winning_initiative_id" = "new_initiative"."id"
4053 AND "battle_win"."losing_initiative_id" = "old_initiative"."id"
4054 JOIN "battle" "battle_lose"
4055 ON "battle_lose"."issue_id" = "issue_id_p"
4056 AND "battle_lose"."losing_initiative_id" = "new_initiative"."id"
4057 AND "battle_lose"."winning_initiative_id" = "old_initiative"."id"
4058 WHERE "old_initiative"."issue_id" = "issue_id_p"
4059 AND "old_initiative"."indirect_majority" = TRUE
4060 AND CASE WHEN "policy_row"."indirect_majority_strict" THEN
4061 "battle_win"."count" * "policy_row"."indirect_majority_den" >
4062 "policy_row"."indirect_majority_num" *
4063 ("battle_win"."count"+"battle_lose"."count")
4064 ELSE
4065 "battle_win"."count" * "policy_row"."indirect_majority_den" >=
4066 "policy_row"."indirect_majority_num" *
4067 ("battle_win"."count"+"battle_lose"."count")
4068 END
4069 AND "battle_win"."count" >= "policy_row"."indirect_majority_positive"
4070 AND "issue_row"."voter_count"-"battle_lose"."count" >=
4071 "policy_row"."indirect_majority_non_negative"
4072 ) AS "subquery"
4073 WHERE "id" = "subquery"."initiative_id";
4074 EXIT WHEN NOT FOUND;
4075 END LOOP;
4076 -- set "multistage_majority" for remaining matching initiatives:
4077 UPDATE "initiative" SET "multistage_majority" = TRUE
4078 FROM (
4079 SELECT "losing_initiative"."id" AS "initiative_id"
4080 FROM "initiative" "losing_initiative"
4081 JOIN "initiative" "winning_initiative"
4082 ON "winning_initiative"."issue_id" = "issue_id_p"
4083 AND "winning_initiative"."admitted"
4084 JOIN "battle" "battle_win"
4085 ON "battle_win"."issue_id" = "issue_id_p"
4086 AND "battle_win"."winning_initiative_id" = "winning_initiative"."id"
4087 AND "battle_win"."losing_initiative_id" = "losing_initiative"."id"
4088 JOIN "battle" "battle_lose"
4089 ON "battle_lose"."issue_id" = "issue_id_p"
4090 AND "battle_lose"."losing_initiative_id" = "winning_initiative"."id"
4091 AND "battle_lose"."winning_initiative_id" = "losing_initiative"."id"
4092 WHERE "losing_initiative"."issue_id" = "issue_id_p"
4093 AND "losing_initiative"."admitted"
4094 AND "winning_initiative"."schulze_rank" <
4095 "losing_initiative"."schulze_rank"
4096 AND "battle_win"."count" > "battle_lose"."count"
4097 AND (
4098 "battle_win"."count" > "winning_initiative"."positive_votes" OR
4099 "battle_lose"."count" < "losing_initiative"."negative_votes" )
4100 ) AS "subquery"
4101 WHERE "id" = "subquery"."initiative_id";
4102 -- mark eligible initiatives:
4103 UPDATE "initiative" SET "eligible" = TRUE
4104 WHERE "issue_id" = "issue_id_p"
4105 AND "initiative"."direct_majority"
4106 AND "initiative"."indirect_majority"
4107 AND "initiative"."better_than_status_quo"
4108 AND (
4109 "policy_row"."no_multistage_majority" = FALSE OR
4110 "initiative"."multistage_majority" = FALSE )
4111 AND (
4112 "policy_row"."no_reverse_beat_path" = FALSE OR
4113 "initiative"."reverse_beat_path" = FALSE );
4114 -- mark final winner:
4115 UPDATE "initiative" SET "winner" = TRUE
4116 FROM (
4117 SELECT "id" AS "initiative_id"
4118 FROM "initiative"
4119 WHERE "issue_id" = "issue_id_p" AND "eligible"
4120 ORDER BY
4121 "schulze_rank",
4122 "vote_ratio"("positive_votes", "negative_votes"),
4123 "id"
4124 LIMIT 1
4125 ) AS "subquery"
4126 WHERE "id" = "subquery"."initiative_id";
4127 -- write (final) ranks:
4128 "rank_v" := 1;
4129 FOR "initiative_id_v" IN
4130 SELECT "id"
4131 FROM "initiative"
4132 WHERE "issue_id" = "issue_id_p" AND "admitted"
4133 ORDER BY
4134 "winner" DESC,
4135 "eligible" DESC,
4136 "schulze_rank",
4137 "vote_ratio"("positive_votes", "negative_votes"),
4138 "id"
4139 LOOP
4140 UPDATE "initiative" SET "rank" = "rank_v"
4141 WHERE "id" = "initiative_id_v";
4142 "rank_v" := "rank_v" + 1;
4143 END LOOP;
4144 -- set schulze rank of status quo and mark issue as finished:
4145 UPDATE "issue" SET
4146 "status_quo_schulze_rank" = "rank_ary"["dimension_v"],
4147 "state" =
4148 CASE WHEN EXISTS (
4149 SELECT NULL FROM "initiative"
4150 WHERE "issue_id" = "issue_id_p" AND "winner"
4151 ) THEN
4152 'finished_with_winner'::"issue_state"
4153 ELSE
4154 'finished_without_winner'::"issue_state"
4155 END,
4156 "ranks_available" = TRUE
4157 WHERE "id" = "issue_id_p";
4158 RETURN;
4159 END;
4160 $$;
4162 COMMENT ON FUNCTION "calculate_ranks"
4163 ( "issue"."id"%TYPE )
4164 IS 'Determine ranking (Votes have to be counted first)';
4168 -----------------------------
4169 -- Automatic state changes --
4170 -----------------------------
4173 CREATE FUNCTION "check_issue"
4174 ( "issue_id_p" "issue"."id"%TYPE )
4175 RETURNS VOID
4176 LANGUAGE 'plpgsql' VOLATILE AS $$
4177 DECLARE
4178 "issue_row" "issue"%ROWTYPE;
4179 "policy_row" "policy"%ROWTYPE;
4180 BEGIN
4181 PERFORM "lock_issue"("issue_id_p");
4182 SELECT * INTO "issue_row" FROM "issue" WHERE "id" = "issue_id_p";
4183 -- only process open issues:
4184 IF "issue_row"."closed" ISNULL THEN
4185 SELECT * INTO "policy_row" FROM "policy"
4186 WHERE "id" = "issue_row"."policy_id";
4187 -- create a snapshot, unless issue is already fully frozen:
4188 IF "issue_row"."fully_frozen" ISNULL THEN
4189 PERFORM "create_snapshot"("issue_id_p");
4190 SELECT * INTO "issue_row" FROM "issue" WHERE "id" = "issue_id_p";
4191 END IF;
4192 -- eventually close or accept issues, which have not been accepted:
4193 IF "issue_row"."accepted" ISNULL THEN
4194 IF EXISTS (
4195 SELECT NULL FROM "initiative"
4196 WHERE "issue_id" = "issue_id_p"
4197 AND "supporter_count" > 0
4198 AND "supporter_count" * "policy_row"."issue_quorum_den"
4199 >= "issue_row"."population" * "policy_row"."issue_quorum_num"
4200 ) THEN
4201 -- accept issues, if supporter count is high enough
4202 PERFORM "set_snapshot_event"("issue_id_p", 'end_of_admission');
4203 -- NOTE: "issue_row" used later
4204 "issue_row"."state" := 'discussion';
4205 "issue_row"."accepted" := now();
4206 UPDATE "issue" SET
4207 "state" = "issue_row"."state",
4208 "accepted" = "issue_row"."accepted"
4209 WHERE "id" = "issue_row"."id";
4210 ELSIF
4211 now() >= "issue_row"."created" + "issue_row"."admission_time"
4212 THEN
4213 -- close issues, if admission time has expired
4214 PERFORM "set_snapshot_event"("issue_id_p", 'end_of_admission');
4215 UPDATE "issue" SET
4216 "state" = 'canceled_issue_not_accepted',
4217 "closed" = now()
4218 WHERE "id" = "issue_row"."id";
4219 END IF;
4220 END IF;
4221 -- eventually half freeze issues:
4222 IF
4223 -- NOTE: issue can't be closed at this point, if it has been accepted
4224 "issue_row"."accepted" NOTNULL AND
4225 "issue_row"."half_frozen" ISNULL
4226 THEN
4227 IF
4228 now() >= "issue_row"."accepted" + "issue_row"."discussion_time"
4229 THEN
4230 PERFORM "set_snapshot_event"("issue_id_p", 'half_freeze');
4231 -- NOTE: "issue_row" used later
4232 "issue_row"."state" := 'verification';
4233 "issue_row"."half_frozen" := now();
4234 UPDATE "issue" SET
4235 "state" = "issue_row"."state",
4236 "half_frozen" = "issue_row"."half_frozen"
4237 WHERE "id" = "issue_row"."id";
4238 END IF;
4239 END IF;
4240 -- close issues after some time, if all initiatives have been revoked:
4241 IF
4242 "issue_row"."closed" ISNULL AND
4243 NOT EXISTS (
4244 -- all initiatives are revoked
4245 SELECT NULL FROM "initiative"
4246 WHERE "issue_id" = "issue_id_p" AND "revoked" ISNULL
4247 ) AND (
4248 -- and issue has not been accepted yet
4249 "issue_row"."accepted" ISNULL OR
4250 NOT EXISTS (
4251 -- or no initiatives have been revoked lately
4252 SELECT NULL FROM "initiative"
4253 WHERE "issue_id" = "issue_id_p"
4254 AND now() < "revoked" + "issue_row"."verification_time"
4255 ) OR (
4256 -- or verification time has elapsed
4257 "issue_row"."half_frozen" NOTNULL AND
4258 "issue_row"."fully_frozen" ISNULL AND
4259 now() >= "issue_row"."half_frozen" + "issue_row"."verification_time"
4262 THEN
4263 -- NOTE: "issue_row" used later
4264 IF "issue_row"."accepted" ISNULL THEN
4265 "issue_row"."state" := 'canceled_revoked_before_accepted';
4266 ELSIF "issue_row"."half_frozen" ISNULL THEN
4267 "issue_row"."state" := 'canceled_after_revocation_during_discussion';
4268 ELSE
4269 "issue_row"."state" := 'canceled_after_revocation_during_verification';
4270 END IF;
4271 "issue_row"."closed" := now();
4272 UPDATE "issue" SET
4273 "state" = "issue_row"."state",
4274 "closed" = "issue_row"."closed"
4275 WHERE "id" = "issue_row"."id";
4276 END IF;
4277 -- fully freeze issue after verification time:
4278 IF
4279 "issue_row"."half_frozen" NOTNULL AND
4280 "issue_row"."fully_frozen" ISNULL AND
4281 "issue_row"."closed" ISNULL AND
4282 now() >= "issue_row"."half_frozen" + "issue_row"."verification_time"
4283 THEN
4284 PERFORM "freeze_after_snapshot"("issue_id_p");
4285 -- NOTE: "issue" might change, thus "issue_row" has to be updated below
4286 END IF;
4287 SELECT * INTO "issue_row" FROM "issue" WHERE "id" = "issue_id_p";
4288 -- close issue by calling close_voting(...) after voting time:
4289 IF
4290 "issue_row"."closed" ISNULL AND
4291 "issue_row"."fully_frozen" NOTNULL AND
4292 now() >= "issue_row"."fully_frozen" + "issue_row"."voting_time"
4293 THEN
4294 PERFORM "close_voting"("issue_id_p");
4295 -- calculate ranks will not consume much time and can be done now
4296 PERFORM "calculate_ranks"("issue_id_p");
4297 END IF;
4298 END IF;
4299 RETURN;
4300 END;
4301 $$;
4303 COMMENT ON FUNCTION "check_issue"
4304 ( "issue"."id"%TYPE )
4305 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.';
4308 CREATE FUNCTION "check_everything"()
4309 RETURNS VOID
4310 LANGUAGE 'plpgsql' VOLATILE AS $$
4311 DECLARE
4312 "issue_id_v" "issue"."id"%TYPE;
4313 BEGIN
4314 DELETE FROM "expired_session";
4315 PERFORM "check_activity"();
4316 PERFORM "calculate_member_counts"();
4317 FOR "issue_id_v" IN SELECT "id" FROM "open_issue" LOOP
4318 PERFORM "check_issue"("issue_id_v");
4319 END LOOP;
4320 FOR "issue_id_v" IN SELECT "id" FROM "issue_with_ranks_missing" LOOP
4321 PERFORM "calculate_ranks"("issue_id_v");
4322 END LOOP;
4323 RETURN;
4324 END;
4325 $$;
4327 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.';
4331 ----------------------
4332 -- Deletion of data --
4333 ----------------------
4336 CREATE FUNCTION "clean_issue"("issue_id_p" "issue"."id"%TYPE)
4337 RETURNS VOID
4338 LANGUAGE 'plpgsql' VOLATILE AS $$
4339 DECLARE
4340 "issue_row" "issue"%ROWTYPE;
4341 BEGIN
4342 SELECT * INTO "issue_row"
4343 FROM "issue" WHERE "id" = "issue_id_p"
4344 FOR UPDATE;
4345 IF "issue_row"."cleaned" ISNULL THEN
4346 UPDATE "issue" SET
4347 "state" = 'voting',
4348 "closed" = NULL,
4349 "ranks_available" = FALSE
4350 WHERE "id" = "issue_id_p";
4351 DELETE FROM "voting_comment"
4352 WHERE "issue_id" = "issue_id_p";
4353 DELETE FROM "delegating_voter"
4354 WHERE "issue_id" = "issue_id_p";
4355 DELETE FROM "direct_voter"
4356 WHERE "issue_id" = "issue_id_p";
4357 DELETE FROM "delegating_interest_snapshot"
4358 WHERE "issue_id" = "issue_id_p";
4359 DELETE FROM "direct_interest_snapshot"
4360 WHERE "issue_id" = "issue_id_p";
4361 DELETE FROM "delegating_population_snapshot"
4362 WHERE "issue_id" = "issue_id_p";
4363 DELETE FROM "direct_population_snapshot"
4364 WHERE "issue_id" = "issue_id_p";
4365 DELETE FROM "non_voter"
4366 WHERE "issue_id" = "issue_id_p";
4367 DELETE FROM "delegation"
4368 WHERE "issue_id" = "issue_id_p";
4369 DELETE FROM "supporter"
4370 WHERE "issue_id" = "issue_id_p";
4371 UPDATE "issue" SET
4372 "state" = "issue_row"."state",
4373 "closed" = "issue_row"."closed",
4374 "ranks_available" = "issue_row"."ranks_available",
4375 "cleaned" = now()
4376 WHERE "id" = "issue_id_p";
4377 END IF;
4378 RETURN;
4379 END;
4380 $$;
4382 COMMENT ON FUNCTION "clean_issue"("issue"."id"%TYPE) IS 'Delete discussion data and votes belonging to an issue';
4385 CREATE FUNCTION "delete_member"("member_id_p" "member"."id"%TYPE)
4386 RETURNS VOID
4387 LANGUAGE 'plpgsql' VOLATILE AS $$
4388 BEGIN
4389 UPDATE "member" SET
4390 "last_login" = NULL,
4391 "login" = NULL,
4392 "password" = NULL,
4393 "locked" = TRUE,
4394 "active" = FALSE,
4395 "notify_email" = NULL,
4396 "notify_email_unconfirmed" = NULL,
4397 "notify_email_secret" = NULL,
4398 "notify_email_secret_expiry" = NULL,
4399 "notify_email_lock_expiry" = NULL,
4400 "password_reset_secret" = NULL,
4401 "password_reset_secret_expiry" = NULL,
4402 "organizational_unit" = NULL,
4403 "internal_posts" = NULL,
4404 "realname" = NULL,
4405 "birthday" = NULL,
4406 "address" = NULL,
4407 "email" = NULL,
4408 "xmpp_address" = NULL,
4409 "website" = NULL,
4410 "phone" = NULL,
4411 "mobile_phone" = NULL,
4412 "profession" = NULL,
4413 "external_memberships" = NULL,
4414 "external_posts" = NULL,
4415 "statement" = NULL
4416 WHERE "id" = "member_id_p";
4417 -- "text_search_data" is updated by triggers
4418 DELETE FROM "setting" WHERE "member_id" = "member_id_p";
4419 DELETE FROM "setting_map" WHERE "member_id" = "member_id_p";
4420 DELETE FROM "member_relation_setting" WHERE "member_id" = "member_id_p";
4421 DELETE FROM "member_image" WHERE "member_id" = "member_id_p";
4422 DELETE FROM "contact" WHERE "member_id" = "member_id_p";
4423 DELETE FROM "ignored_member" WHERE "member_id" = "member_id_p";
4424 DELETE FROM "session" WHERE "member_id" = "member_id_p";
4425 DELETE FROM "area_setting" WHERE "member_id" = "member_id_p";
4426 DELETE FROM "issue_setting" WHERE "member_id" = "member_id_p";
4427 DELETE FROM "ignored_initiative" WHERE "member_id" = "member_id_p";
4428 DELETE FROM "initiative_setting" WHERE "member_id" = "member_id_p";
4429 DELETE FROM "suggestion_setting" WHERE "member_id" = "member_id_p";
4430 DELETE FROM "membership" WHERE "member_id" = "member_id_p";
4431 DELETE FROM "delegation" WHERE "truster_id" = "member_id_p";
4432 DELETE FROM "non_voter" WHERE "member_id" = "member_id_p";
4433 DELETE FROM "direct_voter" USING "issue"
4434 WHERE "direct_voter"."issue_id" = "issue"."id"
4435 AND "issue"."closed" ISNULL
4436 AND "member_id" = "member_id_p";
4437 RETURN;
4438 END;
4439 $$;
4441 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)';
4444 CREATE FUNCTION "delete_private_data"()
4445 RETURNS VOID
4446 LANGUAGE 'plpgsql' VOLATILE AS $$
4447 BEGIN
4448 DELETE FROM "member" WHERE "activated" ISNULL;
4449 UPDATE "member" SET
4450 "invite_code" = NULL,
4451 "invite_code_expiry" = NULL,
4452 "admin_comment" = NULL,
4453 "last_login" = NULL,
4454 "login" = NULL,
4455 "password" = NULL,
4456 "lang" = NULL,
4457 "notify_email" = NULL,
4458 "notify_email_unconfirmed" = NULL,
4459 "notify_email_secret" = NULL,
4460 "notify_email_secret_expiry" = NULL,
4461 "notify_email_lock_expiry" = NULL,
4462 "notify_level" = NULL,
4463 "password_reset_secret" = NULL,
4464 "password_reset_secret_expiry" = NULL,
4465 "organizational_unit" = NULL,
4466 "internal_posts" = NULL,
4467 "realname" = NULL,
4468 "birthday" = NULL,
4469 "address" = NULL,
4470 "email" = NULL,
4471 "xmpp_address" = NULL,
4472 "website" = NULL,
4473 "phone" = NULL,
4474 "mobile_phone" = NULL,
4475 "profession" = NULL,
4476 "external_memberships" = NULL,
4477 "external_posts" = NULL,
4478 "formatting_engine" = NULL,
4479 "statement" = NULL;
4480 -- "text_search_data" is updated by triggers
4481 DELETE FROM "setting";
4482 DELETE FROM "setting_map";
4483 DELETE FROM "member_relation_setting";
4484 DELETE FROM "member_image";
4485 DELETE FROM "contact";
4486 DELETE FROM "ignored_member";
4487 DELETE FROM "session";
4488 DELETE FROM "area_setting";
4489 DELETE FROM "issue_setting";
4490 DELETE FROM "ignored_initiative";
4491 DELETE FROM "initiative_setting";
4492 DELETE FROM "suggestion_setting";
4493 DELETE FROM "non_voter";
4494 DELETE FROM "direct_voter" USING "issue"
4495 WHERE "direct_voter"."issue_id" = "issue"."id"
4496 AND "issue"."closed" ISNULL;
4497 RETURN;
4498 END;
4499 $$;
4501 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.';
4505 COMMIT;

Impressum / About Us