liquid_feedback_core

view core.sql @ 34:9970f73c1140

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

Impressum / About Us