liquid_feedback_core

view core.sql @ 79:0758a2e02620

implement auto_support and delegation checks

* users can put their support in auto_support mode that supports every new draft text, this is automaticly done for the author of the draft.
* enforce that new delegations cannot be done set on inactive members.
* delete also incomming delegations on delete of a user.
author Daniel Poelzleithner <poelzi@poelzi.org>
date Thu Oct 07 19:45:12 2010 +0200 (2010-10-07)
parents f77c0f3d443c
children ca13b2614d10
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 ('1.2.8', 1, 2, 8))
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 "last_login" TIMESTAMPTZ,
60 "login" TEXT UNIQUE,
61 "password" TEXT,
62 "active" BOOLEAN NOT NULL DEFAULT TRUE,
63 "admin" BOOLEAN NOT NULL DEFAULT FALSE,
64 "notify_email" TEXT,
65 "notify_email_unconfirmed" TEXT,
66 "notify_email_secret" TEXT UNIQUE,
67 "notify_email_secret_expiry" TIMESTAMPTZ,
68 "notify_email_lock_expiry" TIMESTAMPTZ,
69 "password_reset_secret" TEXT UNIQUE,
70 "password_reset_secret_expiry" TIMESTAMPTZ,
71 "name" TEXT NOT NULL UNIQUE,
72 "identification" TEXT UNIQUE,
73 "organizational_unit" TEXT,
74 "internal_posts" TEXT,
75 "realname" TEXT,
76 "birthday" DATE,
77 "address" TEXT,
78 "email" TEXT,
79 "xmpp_address" TEXT,
80 "website" TEXT,
81 "phone" TEXT,
82 "mobile_phone" TEXT,
83 "profession" TEXT,
84 "external_memberships" TEXT,
85 "external_posts" TEXT,
86 "statement" TEXT,
87 "text_search_data" TSVECTOR );
88 CREATE INDEX "member_active_idx" ON "member" ("active");
89 CREATE INDEX "member_text_search_data_idx" ON "member" USING gin ("text_search_data");
90 CREATE TRIGGER "update_text_search_data"
91 BEFORE INSERT OR UPDATE ON "member"
92 FOR EACH ROW EXECUTE PROCEDURE
93 tsvector_update_trigger('text_search_data', 'pg_catalog.simple',
94 "name", "identification", "organizational_unit", "internal_posts",
95 "realname", "external_memberships", "external_posts", "statement" );
97 COMMENT ON TABLE "member" IS 'Users of the system, e.g. members of an organization';
99 COMMENT ON COLUMN "member"."login" IS 'Login name';
100 COMMENT ON COLUMN "member"."password" IS 'Password (preferably as crypto-hash, depending on the frontend or access layer)';
101 COMMENT ON COLUMN "member"."active" IS 'Inactive members can not login and their supports/votes are not counted by the system.';
102 COMMENT ON COLUMN "member"."admin" IS 'TRUE for admins, which can administrate other users and setup policies and areas';
103 COMMENT ON COLUMN "member"."notify_email" IS 'Email address where notifications of the system are sent to';
104 COMMENT ON COLUMN "member"."notify_email_unconfirmed" IS 'Unconfirmed email address provided by the member to be copied into "notify_email" field after verification';
105 COMMENT ON COLUMN "member"."notify_email_secret" IS 'Secret sent to the address in "notify_email_unconformed"';
106 COMMENT ON COLUMN "member"."notify_email_secret_expiry" IS 'Expiry date/time for "notify_email_secret"';
107 COMMENT ON COLUMN "member"."notify_email_lock_expiry" IS 'Date/time until no further email confirmation mails may be sent (abuse protection)';
108 COMMENT ON COLUMN "member"."name" IS 'Distinct name of the member';
109 COMMENT ON COLUMN "member"."identification" IS 'Optional identification number or code of the member';
110 COMMENT ON COLUMN "member"."organizational_unit" IS 'Branch or division of the organization the member belongs to';
111 COMMENT ON COLUMN "member"."internal_posts" IS 'Posts (offices) of the member inside the organization';
112 COMMENT ON COLUMN "member"."realname" IS 'Real name of the member, may be identical with "name"';
113 COMMENT ON COLUMN "member"."email" IS 'Published email address of the member; not used for system notifications';
114 COMMENT ON COLUMN "member"."external_memberships" IS 'Other organizations the member is involved in';
115 COMMENT ON COLUMN "member"."external_posts" IS 'Posts (offices) outside the organization';
116 COMMENT ON COLUMN "member"."statement" IS 'Freely chosen text of the member for his homepage within the system';
119 CREATE TABLE "member_history" (
120 "id" SERIAL8 PRIMARY KEY,
121 "member_id" INT4 NOT NULL REFERENCES "member" ("id") ON DELETE CASCADE ON UPDATE CASCADE,
122 "until" TIMESTAMPTZ NOT NULL DEFAULT now(),
123 "active" BOOLEAN NOT NULL,
124 "name" TEXT NOT NULL );
125 CREATE INDEX "member_history_member_id_idx" ON "member_history" ("member_id");
127 COMMENT ON TABLE "member_history" IS 'Filled by trigger; keeps information about old names and active flag of members';
129 COMMENT ON COLUMN "member_history"."id" IS 'Primary key, which can be used to sort entries correctly (and time warp resistant)';
130 COMMENT ON COLUMN "member_history"."until" IS 'Timestamp until the data was valid';
133 CREATE TABLE "invite_code" (
134 "code" TEXT PRIMARY KEY,
135 "created" TIMESTAMPTZ NOT NULL DEFAULT now(),
136 "used" TIMESTAMPTZ,
137 "member_id" INT4 UNIQUE REFERENCES "member" ("id") ON DELETE SET NULL ON UPDATE CASCADE,
138 "comment" TEXT,
139 CONSTRAINT "only_used_codes_may_refer_to_member" CHECK ("used" NOTNULL OR "member_id" ISNULL) );
141 COMMENT ON TABLE "invite_code" IS 'Invite codes can be used once to create a new member account.';
143 COMMENT ON COLUMN "invite_code"."code" IS 'Secret code';
144 COMMENT ON COLUMN "invite_code"."created" IS 'Time of creation of the secret code';
145 COMMENT ON COLUMN "invite_code"."used" IS 'NULL, if not used yet, otherwise tells when this code was used to create a member account';
146 COMMENT ON COLUMN "invite_code"."member_id" IS 'References the member whose account was created with this code';
147 COMMENT ON COLUMN "invite_code"."comment" IS 'Comment on the code, which is to be used for administrative reasons only';
150 CREATE TABLE "setting" (
151 PRIMARY KEY ("member_id", "key"),
152 "member_id" INT4 REFERENCES "member" ("id") ON DELETE CASCADE ON UPDATE CASCADE,
153 "key" TEXT NOT NULL,
154 "value" TEXT NOT NULL );
155 CREATE INDEX "setting_key_idx" ON "setting" ("key");
157 COMMENT ON TABLE "setting" IS 'Place to store a frontend specific setting for members as a string';
159 COMMENT ON COLUMN "setting"."key" IS 'Name of the setting, preceded by a frontend specific prefix';
162 CREATE TABLE "setting_map" (
163 PRIMARY KEY ("member_id", "key", "subkey"),
164 "member_id" INT4 REFERENCES "member" ("id") ON DELETE CASCADE ON UPDATE CASCADE,
165 "key" TEXT NOT NULL,
166 "subkey" TEXT NOT NULL,
167 "value" TEXT NOT NULL );
168 CREATE INDEX "setting_map_key_idx" ON "setting_map" ("key");
170 COMMENT ON TABLE "setting_map" IS 'Place to store a frontend specific setting for members as a map of key value pairs';
172 COMMENT ON COLUMN "setting_map"."key" IS 'Name of the setting, preceded by a frontend specific prefix';
173 COMMENT ON COLUMN "setting_map"."subkey" IS 'Key of a map entry';
174 COMMENT ON COLUMN "setting_map"."value" IS 'Value of a map entry';
177 CREATE TABLE "member_relation_setting" (
178 PRIMARY KEY ("member_id", "key", "other_member_id"),
179 "member_id" INT4 REFERENCES "member" ("id") ON DELETE CASCADE ON UPDATE CASCADE,
180 "key" TEXT NOT NULL,
181 "other_member_id" INT4 REFERENCES "member" ("id") ON DELETE CASCADE ON UPDATE CASCADE,
182 "value" TEXT NOT NULL );
184 COMMENT ON TABLE "member_relation_setting" IS 'Place to store a frontend specific setting related to relations between members as a string';
187 CREATE TYPE "member_image_type" AS ENUM ('photo', 'avatar');
189 COMMENT ON TYPE "member_image_type" IS 'Types of images for a member';
192 CREATE TABLE "member_image" (
193 PRIMARY KEY ("member_id", "image_type", "scaled"),
194 "member_id" INT4 REFERENCES "member" ("id") ON DELETE CASCADE ON UPDATE CASCADE,
195 "image_type" "member_image_type",
196 "scaled" BOOLEAN,
197 "content_type" TEXT,
198 "data" BYTEA NOT NULL );
200 COMMENT ON TABLE "member_image" IS 'Images of members';
202 COMMENT ON COLUMN "member_image"."scaled" IS 'FALSE for original image, TRUE for scaled version of the image';
205 CREATE TABLE "member_count" (
206 "calculated" TIMESTAMPTZ NOT NULL DEFAULT NOW(),
207 "total_count" INT4 NOT NULL );
209 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';
211 COMMENT ON COLUMN "member_count"."calculated" IS 'timestamp indicating when the total member count and area member counts were calculated';
212 COMMENT ON COLUMN "member_count"."total_count" IS 'Total count of active(!) members';
215 CREATE TABLE "contact" (
216 PRIMARY KEY ("member_id", "other_member_id"),
217 "member_id" INT4 REFERENCES "member" ("id") ON DELETE CASCADE ON UPDATE CASCADE,
218 "other_member_id" INT4 REFERENCES "member" ("id") ON DELETE CASCADE ON UPDATE CASCADE,
219 "public" BOOLEAN NOT NULL DEFAULT FALSE,
220 CONSTRAINT "cant_save_yourself_as_contact"
221 CHECK ("member_id" != "other_member_id") );
223 COMMENT ON TABLE "contact" IS 'Contact lists';
225 COMMENT ON COLUMN "contact"."member_id" IS 'Member having the contact list';
226 COMMENT ON COLUMN "contact"."other_member_id" IS 'Member referenced in the contact list';
227 COMMENT ON COLUMN "contact"."public" IS 'TRUE = display contact publically';
230 CREATE TABLE "session" (
231 "ident" TEXT PRIMARY KEY,
232 "additional_secret" TEXT,
233 "expiry" TIMESTAMPTZ NOT NULL DEFAULT now() + '24 hours',
234 "member_id" INT8 REFERENCES "member" ("id") ON DELETE SET NULL,
235 "lang" TEXT );
236 CREATE INDEX "session_expiry_idx" ON "session" ("expiry");
238 COMMENT ON TABLE "session" IS 'Sessions, i.e. for a web-frontend';
240 COMMENT ON COLUMN "session"."ident" IS 'Secret session identifier (i.e. random string)';
241 COMMENT ON COLUMN "session"."additional_secret" IS 'Additional field to store a secret, which can be used against CSRF attacks';
242 COMMENT ON COLUMN "session"."member_id" IS 'Reference to member, who is logged in';
243 COMMENT ON COLUMN "session"."lang" IS 'Language code of the selected language';
246 CREATE TABLE "policy" (
247 "id" SERIAL4 PRIMARY KEY,
248 "index" INT4 NOT NULL,
249 "active" BOOLEAN NOT NULL DEFAULT TRUE,
250 "name" TEXT NOT NULL UNIQUE,
251 "description" TEXT NOT NULL DEFAULT '',
252 "admission_time" INTERVAL NOT NULL,
253 "discussion_time" INTERVAL NOT NULL,
254 "verification_time" INTERVAL NOT NULL,
255 "voting_time" INTERVAL NOT NULL,
256 "issue_quorum_num" INT4 NOT NULL,
257 "issue_quorum_den" INT4 NOT NULL,
258 "initiative_quorum_num" INT4 NOT NULL,
259 "initiative_quorum_den" INT4 NOT NULL,
260 "majority_num" INT4 NOT NULL DEFAULT 1,
261 "majority_den" INT4 NOT NULL DEFAULT 2,
262 "majority_strict" BOOLEAN NOT NULL DEFAULT TRUE );
263 CREATE INDEX "policy_active_idx" ON "policy" ("active");
265 COMMENT ON TABLE "policy" IS 'Policies for a particular proceeding type (timelimits, quorum)';
267 COMMENT ON COLUMN "policy"."index" IS 'Determines the order in listings';
268 COMMENT ON COLUMN "policy"."active" IS 'TRUE = policy can be used for new issues';
269 COMMENT ON COLUMN "policy"."admission_time" IS 'Maximum time an issue stays open without being "accepted"';
270 COMMENT ON COLUMN "policy"."discussion_time" IS 'Regular time until an issue is "half_frozen" after being "accepted"';
271 COMMENT ON COLUMN "policy"."verification_time" IS 'Regular time until an issue is "fully_frozen" after being "half_frozen"';
272 COMMENT ON COLUMN "policy"."voting_time" IS 'Time after an issue is "fully_frozen" but not "closed"';
273 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"';
274 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"';
275 COMMENT ON COLUMN "policy"."initiative_quorum_num" IS 'Numerator of satisfied supporter quorum to be reached by an initiative to be "admitted" for voting';
276 COMMENT ON COLUMN "policy"."initiative_quorum_den" IS 'Denominator of satisfied supporter quorum to be reached by an initiative to be "admitted" for voting';
277 COMMENT ON COLUMN "policy"."majority_num" IS 'Numerator of fraction of majority to be reached during voting by an initiative to be aggreed upon';
278 COMMENT ON COLUMN "policy"."majority_den" IS 'Denominator of fraction of majority to be reached during voting by an initiative to be aggreed upon';
279 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.';
282 CREATE TABLE "area" (
283 "id" SERIAL4 PRIMARY KEY,
284 "active" BOOLEAN NOT NULL DEFAULT TRUE,
285 "name" TEXT NOT NULL,
286 "description" TEXT NOT NULL DEFAULT '',
287 "direct_member_count" INT4,
288 "member_weight" INT4,
289 "autoreject_weight" INT4,
290 "text_search_data" TSVECTOR );
291 CREATE INDEX "area_active_idx" ON "area" ("active");
292 CREATE INDEX "area_text_search_data_idx" ON "area" USING gin ("text_search_data");
293 CREATE TRIGGER "update_text_search_data"
294 BEFORE INSERT OR UPDATE ON "area"
295 FOR EACH ROW EXECUTE PROCEDURE
296 tsvector_update_trigger('text_search_data', 'pg_catalog.simple',
297 "name", "description" );
299 COMMENT ON TABLE "area" IS 'Subject areas';
301 COMMENT ON COLUMN "area"."active" IS 'TRUE means new issues can be created in this area';
302 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"';
303 COMMENT ON COLUMN "area"."member_weight" IS 'Same as "direct_member_count" but respecting delegations';
304 COMMENT ON COLUMN "area"."autoreject_weight" IS 'Sum of weight of members using the autoreject feature';
307 CREATE TABLE "area_setting" (
308 PRIMARY KEY ("member_id", "key", "area_id"),
309 "member_id" INT4 REFERENCES "member" ("id") ON DELETE CASCADE ON UPDATE CASCADE,
310 "key" TEXT NOT NULL,
311 "area_id" INT4 REFERENCES "area" ("id") ON DELETE CASCADE ON UPDATE CASCADE,
312 "value" TEXT NOT NULL );
314 COMMENT ON TABLE "area_setting" IS 'Place for frontend to store area specific settings of members as strings';
317 CREATE TABLE "allowed_policy" (
318 PRIMARY KEY ("area_id", "policy_id"),
319 "area_id" INT4 REFERENCES "area" ("id") ON DELETE CASCADE ON UPDATE CASCADE,
320 "policy_id" INT4 NOT NULL REFERENCES "policy" ("id") ON DELETE CASCADE ON UPDATE CASCADE,
321 "default_policy" BOOLEAN NOT NULL DEFAULT FALSE );
322 CREATE UNIQUE INDEX "allowed_policy_one_default_per_area_idx" ON "allowed_policy" ("area_id") WHERE "default_policy";
324 COMMENT ON TABLE "allowed_policy" IS 'Selects which policies can be used in each area';
326 COMMENT ON COLUMN "allowed_policy"."default_policy" IS 'One policy per area can be set as default.';
329 CREATE TYPE "snapshot_event" AS ENUM ('periodic', 'end_of_admission', 'half_freeze', 'full_freeze');
331 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';
334 CREATE TABLE "issue" (
335 "id" SERIAL4 PRIMARY KEY,
336 "area_id" INT4 NOT NULL REFERENCES "area" ("id") ON DELETE CASCADE ON UPDATE CASCADE,
337 "policy_id" INT4 NOT NULL REFERENCES "policy" ("id") ON DELETE RESTRICT ON UPDATE CASCADE,
338 "created" TIMESTAMPTZ NOT NULL DEFAULT now(),
339 "accepted" TIMESTAMPTZ,
340 "half_frozen" TIMESTAMPTZ,
341 "fully_frozen" TIMESTAMPTZ,
342 "closed" TIMESTAMPTZ,
343 "ranks_available" BOOLEAN NOT NULL DEFAULT FALSE,
344 "cleaned" TIMESTAMPTZ,
345 "admission_time" INTERVAL NOT NULL,
346 "discussion_time" INTERVAL NOT NULL,
347 "verification_time" INTERVAL NOT NULL,
348 "voting_time" INTERVAL NOT NULL,
349 "snapshot" TIMESTAMPTZ,
350 "latest_snapshot_event" "snapshot_event",
351 "population" INT4,
352 "vote_now" INT4,
353 "vote_later" INT4,
354 "voter_count" INT4,
355 CONSTRAINT "valid_state" CHECK (
356 ("accepted" ISNULL AND "half_frozen" ISNULL AND "fully_frozen" ISNULL AND "closed" ISNULL AND "ranks_available" = FALSE) OR
357 ("accepted" ISNULL AND "half_frozen" ISNULL AND "fully_frozen" ISNULL AND "closed" NOTNULL AND "ranks_available" = FALSE) OR
358 ("accepted" NOTNULL AND "half_frozen" ISNULL AND "fully_frozen" ISNULL AND "closed" ISNULL AND "ranks_available" = FALSE) OR
359 ("accepted" NOTNULL AND "half_frozen" ISNULL AND "fully_frozen" ISNULL AND "closed" NOTNULL AND "ranks_available" = FALSE) OR
360 ("accepted" NOTNULL AND "half_frozen" NOTNULL AND "fully_frozen" ISNULL AND "closed" ISNULL AND "ranks_available" = FALSE) OR
361 ("accepted" NOTNULL AND "half_frozen" NOTNULL AND "fully_frozen" ISNULL AND "closed" NOTNULL AND "ranks_available" = FALSE) OR
362 ("accepted" NOTNULL AND "half_frozen" NOTNULL AND "fully_frozen" NOTNULL AND "closed" ISNULL AND "ranks_available" = FALSE) OR
363 ("accepted" NOTNULL AND "half_frozen" NOTNULL AND "fully_frozen" NOTNULL AND "closed" NOTNULL AND "ranks_available" = FALSE) OR
364 ("accepted" NOTNULL AND "half_frozen" NOTNULL AND "fully_frozen" NOTNULL AND "closed" NOTNULL AND "ranks_available" = TRUE) ),
365 CONSTRAINT "state_change_order" CHECK (
366 "created" <= "accepted" AND
367 "accepted" <= "half_frozen" AND
368 "half_frozen" <= "fully_frozen" AND
369 "fully_frozen" <= "closed" ),
370 CONSTRAINT "only_closed_issues_may_be_cleaned" CHECK (
371 "cleaned" ISNULL OR "closed" NOTNULL ),
372 CONSTRAINT "last_snapshot_on_full_freeze"
373 CHECK ("snapshot" = "fully_frozen"), -- NOTE: snapshot can be set, while frozen is NULL yet
374 CONSTRAINT "freeze_requires_snapshot"
375 CHECK ("fully_frozen" ISNULL OR "snapshot" NOTNULL),
376 CONSTRAINT "set_both_or_none_of_snapshot_and_latest_snapshot_event"
377 CHECK ("snapshot" NOTNULL = "latest_snapshot_event" NOTNULL) );
378 CREATE INDEX "issue_area_id_idx" ON "issue" ("area_id");
379 CREATE INDEX "issue_policy_id_idx" ON "issue" ("policy_id");
380 CREATE INDEX "issue_created_idx" ON "issue" ("created");
381 CREATE INDEX "issue_accepted_idx" ON "issue" ("accepted");
382 CREATE INDEX "issue_half_frozen_idx" ON "issue" ("half_frozen");
383 CREATE INDEX "issue_fully_frozen_idx" ON "issue" ("fully_frozen");
384 CREATE INDEX "issue_closed_idx" ON "issue" ("closed");
385 CREATE INDEX "issue_created_idx_open" ON "issue" ("created") WHERE "closed" ISNULL;
386 CREATE INDEX "issue_closed_idx_canceled" ON "issue" ("closed") WHERE "fully_frozen" ISNULL;
388 COMMENT ON TABLE "issue" IS 'Groups of initiatives';
390 COMMENT ON COLUMN "issue"."accepted" IS 'Point in time, when one initiative of issue reached the "issue_quorum"';
391 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.';
392 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.';
393 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.';
394 COMMENT ON COLUMN "issue"."ranks_available" IS 'TRUE = ranks have been calculated';
395 COMMENT ON COLUMN "issue"."cleaned" IS 'Point in time, when discussion data and votes had been deleted';
396 COMMENT ON COLUMN "issue"."admission_time" IS 'Copied from "policy" table at creation of issue';
397 COMMENT ON COLUMN "issue"."discussion_time" IS 'Copied from "policy" table at creation of issue';
398 COMMENT ON COLUMN "issue"."verification_time" IS 'Copied from "policy" table at creation of issue';
399 COMMENT ON COLUMN "issue"."voting_time" IS 'Copied from "policy" table at creation of issue';
400 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';
401 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';
402 COMMENT ON COLUMN "issue"."population" IS 'Sum of "weight" column in table "direct_population_snapshot"';
403 COMMENT ON COLUMN "issue"."vote_now" IS 'Number of votes in favor of voting now, as calculated from table "direct_interest_snapshot"';
404 COMMENT ON COLUMN "issue"."vote_later" IS 'Number of votes against voting now, as calculated from table "direct_interest_snapshot"';
405 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';
408 CREATE TABLE "issue_setting" (
409 PRIMARY KEY ("member_id", "key", "issue_id"),
410 "member_id" INT4 REFERENCES "member" ("id") ON DELETE CASCADE ON UPDATE CASCADE,
411 "key" TEXT NOT NULL,
412 "issue_id" INT4 REFERENCES "issue" ("id") ON DELETE CASCADE ON UPDATE CASCADE,
413 "value" TEXT NOT NULL );
415 COMMENT ON TABLE "issue_setting" IS 'Place for frontend to store issue specific settings of members as strings';
418 CREATE TABLE "initiative" (
419 UNIQUE ("issue_id", "id"), -- index needed for foreign-key on table "vote"
420 "issue_id" INT4 NOT NULL REFERENCES "issue" ("id") ON DELETE CASCADE ON UPDATE CASCADE,
421 "id" SERIAL4 PRIMARY KEY,
422 "name" TEXT NOT NULL,
423 "discussion_url" TEXT,
424 "created" TIMESTAMPTZ NOT NULL DEFAULT now(),
425 "revoked" TIMESTAMPTZ,
426 "suggested_initiative_id" INT4 REFERENCES "initiative" ("id") ON DELETE CASCADE ON UPDATE CASCADE,
427 "admitted" BOOLEAN,
428 "supporter_count" INT4,
429 "informed_supporter_count" INT4,
430 "satisfied_supporter_count" INT4,
431 "satisfied_informed_supporter_count" INT4,
432 "positive_votes" INT4,
433 "negative_votes" INT4,
434 "agreed" BOOLEAN,
435 "rank" INT4,
436 "text_search_data" TSVECTOR,
437 CONSTRAINT "non_revoked_initiatives_cant_suggest_other"
438 CHECK ("revoked" NOTNULL OR "suggested_initiative_id" ISNULL),
439 CONSTRAINT "revoked_initiatives_cant_be_admitted"
440 CHECK ("revoked" ISNULL OR "admitted" ISNULL),
441 CONSTRAINT "non_admitted_initiatives_cant_contain_voting_results"
442 CHECK (("admitted" NOTNULL AND "admitted" = TRUE) OR ("positive_votes" ISNULL AND "negative_votes" ISNULL AND "agreed" ISNULL)),
443 CONSTRAINT "all_or_none_of_positive_votes_negative_votes_and_agreed_must_be_null"
444 CHECK ("positive_votes" NOTNULL = "negative_votes" NOTNULL AND "positive_votes" NOTNULL = "agreed" NOTNULL),
445 CONSTRAINT "non_agreed_initiatives_cant_get_a_rank"
446 CHECK (("agreed" NOTNULL AND "agreed" = TRUE) OR "rank" ISNULL) );
447 CREATE INDEX "initiative_created_idx" ON "initiative" ("created");
448 CREATE INDEX "initiative_revoked_idx" ON "initiative" ("revoked");
449 CREATE INDEX "initiative_text_search_data_idx" ON "initiative" USING gin ("text_search_data");
450 CREATE TRIGGER "update_text_search_data"
451 BEFORE INSERT OR UPDATE ON "initiative"
452 FOR EACH ROW EXECUTE PROCEDURE
453 tsvector_update_trigger('text_search_data', 'pg_catalog.simple',
454 "name", "discussion_url");
456 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.';
458 COMMENT ON COLUMN "initiative"."discussion_url" IS 'URL pointing to a discussion platform for this initiative';
459 COMMENT ON COLUMN "initiative"."revoked" IS 'Point in time, when one initiator decided to revoke the initiative';
460 COMMENT ON COLUMN "initiative"."admitted" IS 'TRUE, if initiative reaches the "initiative_quorum" when freezing the issue';
461 COMMENT ON COLUMN "initiative"."supporter_count" IS 'Calculated from table "direct_supporter_snapshot"';
462 COMMENT ON COLUMN "initiative"."informed_supporter_count" IS 'Calculated from table "direct_supporter_snapshot"';
463 COMMENT ON COLUMN "initiative"."satisfied_supporter_count" IS 'Calculated from table "direct_supporter_snapshot"';
464 COMMENT ON COLUMN "initiative"."satisfied_informed_supporter_count" IS 'Calculated from table "direct_supporter_snapshot"';
465 COMMENT ON COLUMN "initiative"."positive_votes" IS 'Calculated from table "direct_voter"';
466 COMMENT ON COLUMN "initiative"."negative_votes" IS 'Calculated from table "direct_voter"';
467 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"';
468 COMMENT ON COLUMN "initiative"."rank" IS 'Rank of approved initiatives (winner is 1), calculated from table "direct_voter"';
471 CREATE TABLE "battle" (
472 PRIMARY KEY ("issue_id", "winning_initiative_id", "losing_initiative_id"),
473 "issue_id" INT4,
474 "winning_initiative_id" INT4,
475 FOREIGN KEY ("issue_id", "winning_initiative_id") REFERENCES "initiative" ("issue_id", "id") ON DELETE CASCADE ON UPDATE CASCADE,
476 "losing_initiative_id" INT4,
477 FOREIGN KEY ("issue_id", "losing_initiative_id") REFERENCES "initiative" ("issue_id", "id") ON DELETE CASCADE ON UPDATE CASCADE,
478 "count" INT4 NOT NULL);
480 COMMENT ON TABLE "battle" IS 'Number of members preferring one initiative to another; Filled by "battle_view" when closing an issue';
483 CREATE TABLE "initiative_setting" (
484 PRIMARY KEY ("member_id", "key", "initiative_id"),
485 "member_id" INT4 REFERENCES "member" ("id") ON DELETE CASCADE ON UPDATE CASCADE,
486 "key" TEXT NOT NULL,
487 "initiative_id" INT4 REFERENCES "initiative" ("id") ON DELETE CASCADE ON UPDATE CASCADE,
488 "value" TEXT NOT NULL );
490 COMMENT ON TABLE "initiative_setting" IS 'Place for frontend to store initiative specific settings of members as strings';
493 CREATE TABLE "draft" (
494 UNIQUE ("initiative_id", "id"), -- index needed for foreign-key on table "supporter"
495 "initiative_id" INT4 NOT NULL REFERENCES "initiative" ("id") ON DELETE CASCADE ON UPDATE CASCADE,
496 "id" SERIAL8 PRIMARY KEY,
497 "created" TIMESTAMPTZ NOT NULL DEFAULT now(),
498 "author_id" INT4 NOT NULL REFERENCES "member" ("id") ON DELETE RESTRICT ON UPDATE CASCADE,
499 "formatting_engine" TEXT,
500 "content" TEXT NOT NULL,
501 "text_search_data" TSVECTOR );
502 CREATE INDEX "draft_created_idx" ON "draft" ("created");
503 CREATE INDEX "draft_author_id_created_idx" ON "draft" ("author_id", "created");
504 CREATE INDEX "draft_text_search_data_idx" ON "draft" USING gin ("text_search_data");
505 CREATE TRIGGER "update_text_search_data"
506 BEFORE INSERT OR UPDATE ON "draft"
507 FOR EACH ROW EXECUTE PROCEDURE
508 tsvector_update_trigger('text_search_data', 'pg_catalog.simple', "content");
510 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.';
512 COMMENT ON COLUMN "draft"."formatting_engine" IS 'Allows different formatting engines (i.e. wiki formats) to be used';
513 COMMENT ON COLUMN "draft"."content" IS 'Text of the draft in a format depending on the field "formatting_engine"';
516 CREATE TABLE "rendered_draft" (
517 PRIMARY KEY ("draft_id", "format"),
518 "draft_id" INT8 REFERENCES "draft" ("id") ON DELETE CASCADE ON UPDATE CASCADE,
519 "format" TEXT,
520 "content" TEXT NOT NULL );
522 COMMENT ON TABLE "rendered_draft" IS 'This table may be used by frontends to cache "rendered" drafts (e.g. HTML output generated from wiki text)';
525 CREATE TABLE "suggestion" (
526 UNIQUE ("initiative_id", "id"), -- index needed for foreign-key on table "opinion"
527 "initiative_id" INT4 NOT NULL REFERENCES "initiative" ("id") ON DELETE CASCADE ON UPDATE CASCADE,
528 "id" SERIAL8 PRIMARY KEY,
529 "created" TIMESTAMPTZ NOT NULL DEFAULT now(),
530 "author_id" INT4 NOT NULL REFERENCES "member" ("id") ON DELETE RESTRICT ON UPDATE CASCADE,
531 "name" TEXT NOT NULL,
532 "description" TEXT NOT NULL DEFAULT '',
533 "text_search_data" TSVECTOR,
534 "minus2_unfulfilled_count" INT4,
535 "minus2_fulfilled_count" INT4,
536 "minus1_unfulfilled_count" INT4,
537 "minus1_fulfilled_count" INT4,
538 "plus1_unfulfilled_count" INT4,
539 "plus1_fulfilled_count" INT4,
540 "plus2_unfulfilled_count" INT4,
541 "plus2_fulfilled_count" INT4 );
542 CREATE INDEX "suggestion_created_idx" ON "suggestion" ("created");
543 CREATE INDEX "suggestion_author_id_created_idx" ON "suggestion" ("author_id", "created");
544 CREATE INDEX "suggestion_text_search_data_idx" ON "suggestion" USING gin ("text_search_data");
545 CREATE TRIGGER "update_text_search_data"
546 BEFORE INSERT OR UPDATE ON "suggestion"
547 FOR EACH ROW EXECUTE PROCEDURE
548 tsvector_update_trigger('text_search_data', 'pg_catalog.simple',
549 "name", "description");
551 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';
553 COMMENT ON COLUMN "suggestion"."minus2_unfulfilled_count" IS 'Calculated from table "direct_supporter_snapshot", not requiring informed supporters';
554 COMMENT ON COLUMN "suggestion"."minus2_fulfilled_count" IS 'Calculated from table "direct_supporter_snapshot", not requiring informed supporters';
555 COMMENT ON COLUMN "suggestion"."minus1_unfulfilled_count" IS 'Calculated from table "direct_supporter_snapshot", not requiring informed supporters';
556 COMMENT ON COLUMN "suggestion"."minus1_fulfilled_count" IS 'Calculated from table "direct_supporter_snapshot", not requiring informed supporters';
557 COMMENT ON COLUMN "suggestion"."plus1_unfulfilled_count" IS 'Calculated from table "direct_supporter_snapshot", not requiring informed supporters';
558 COMMENT ON COLUMN "suggestion"."plus1_fulfilled_count" IS 'Calculated from table "direct_supporter_snapshot", not requiring informed supporters';
559 COMMENT ON COLUMN "suggestion"."plus2_unfulfilled_count" IS 'Calculated from table "direct_supporter_snapshot", not requiring informed supporters';
560 COMMENT ON COLUMN "suggestion"."plus2_fulfilled_count" IS 'Calculated from table "direct_supporter_snapshot", not requiring informed supporters';
563 CREATE TABLE "suggestion_setting" (
564 PRIMARY KEY ("member_id", "key", "suggestion_id"),
565 "member_id" INT4 REFERENCES "member" ("id") ON DELETE CASCADE ON UPDATE CASCADE,
566 "key" TEXT NOT NULL,
567 "suggestion_id" INT8 REFERENCES "suggestion" ("id") ON DELETE CASCADE ON UPDATE CASCADE,
568 "value" TEXT NOT NULL );
570 COMMENT ON TABLE "suggestion_setting" IS 'Place for frontend to store suggestion specific settings of members as strings';
573 CREATE TABLE "membership" (
574 PRIMARY KEY ("area_id", "member_id"),
575 "area_id" INT4 REFERENCES "area" ("id") ON DELETE CASCADE ON UPDATE CASCADE,
576 "member_id" INT4 REFERENCES "member" ("id") ON DELETE CASCADE ON UPDATE CASCADE,
577 "autoreject" BOOLEAN NOT NULL DEFAULT FALSE );
578 CREATE INDEX "membership_member_id_idx" ON "membership" ("member_id");
580 COMMENT ON TABLE "membership" IS 'Interest of members in topic areas';
582 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';
585 CREATE TABLE "interest" (
586 PRIMARY KEY ("issue_id", "member_id"),
587 "issue_id" INT4 REFERENCES "issue" ("id") ON DELETE CASCADE ON UPDATE CASCADE,
588 "member_id" INT4 REFERENCES "member" ("id") ON DELETE CASCADE ON UPDATE CASCADE,
589 "autoreject" BOOLEAN NOT NULL,
590 "voting_requested" BOOLEAN );
591 CREATE INDEX "interest_member_id_idx" ON "interest" ("member_id");
593 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.';
595 COMMENT ON COLUMN "interest"."autoreject" IS 'TRUE = member votes against all initiatives in case of not explicitly taking part in the voting procedure';
596 COMMENT ON COLUMN "interest"."voting_requested" IS 'TRUE = member wants to vote now, FALSE = member wants to vote later, NULL = policy rules should apply';
599 CREATE TABLE "initiator" (
600 PRIMARY KEY ("initiative_id", "member_id"),
601 "initiative_id" INT4 REFERENCES "initiative" ("id") ON DELETE CASCADE ON UPDATE CASCADE,
602 "member_id" INT4 REFERENCES "member" ("id") ON DELETE CASCADE ON UPDATE CASCADE,
603 "accepted" BOOLEAN );
604 CREATE INDEX "initiator_member_id_idx" ON "initiator" ("member_id");
606 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.';
608 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.';
611 CREATE TABLE "supporter" (
612 "issue_id" INT4 NOT NULL,
613 PRIMARY KEY ("initiative_id", "member_id"),
614 "initiative_id" INT4,
615 "member_id" INT4,
616 "draft_id" INT8 NOT NULL,
617 "auto_support" BOOLEAN NOT NULL DEFAULT 'f',
618 FOREIGN KEY ("issue_id", "member_id") REFERENCES "interest" ("issue_id", "member_id") ON DELETE CASCADE ON UPDATE CASCADE,
619 FOREIGN KEY ("initiative_id", "draft_id") REFERENCES "draft" ("initiative_id", "id") ON DELETE CASCADE ON UPDATE CASCADE );
620 CREATE INDEX "supporter_member_id_idx" ON "supporter" ("member_id");
622 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.';
624 COMMENT ON COLUMN "supporter"."draft_id" IS 'Latest seen draft, defaults to current draft of the initiative (implemented by trigger "default_for_draft_id")';
626 CREATE FUNCTION update_supporter_drafts()
627 RETURNS trigger
628 LANGUAGE 'plpgsql' AS $$
629 BEGIN
630 UPDATE supporter SET draft_id = NEW.id
631 WHERE initiative_id = NEW.initiative_id AND
632 (auto_support = 't' OR member_id = NEW.author_id);
633 RETURN new;
634 END
635 $$;
637 CREATE TRIGGER "update_draft_supporter"
638 AFTER INSERT ON "draft"
639 FOR EACH ROW EXECUTE PROCEDURE
640 update_supporter_drafts();
642 COMMENT ON FUNCTION "update_supporter_drafts"() IS 'Automaticly update the supported draft_id to the latest version when auto_support is enabled';
644 CREATE TABLE "opinion" (
645 "initiative_id" INT4 NOT NULL,
646 PRIMARY KEY ("suggestion_id", "member_id"),
647 "suggestion_id" INT8,
648 "member_id" INT4,
649 "degree" INT2 NOT NULL CHECK ("degree" >= -2 AND "degree" <= 2 AND "degree" != 0),
650 "fulfilled" BOOLEAN NOT NULL DEFAULT FALSE,
651 FOREIGN KEY ("initiative_id", "suggestion_id") REFERENCES "suggestion" ("initiative_id", "id") ON DELETE CASCADE ON UPDATE CASCADE,
652 FOREIGN KEY ("initiative_id", "member_id") REFERENCES "supporter" ("initiative_id", "member_id") ON DELETE CASCADE ON UPDATE CASCADE );
653 CREATE INDEX "opinion_member_id_initiative_id_idx" ON "opinion" ("member_id", "initiative_id");
655 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.';
657 COMMENT ON COLUMN "opinion"."degree" IS '2 = fulfillment required for support; 1 = fulfillment desired; -1 = fulfillment unwanted; -2 = fulfillment cancels support';
660 CREATE TYPE "delegation_scope" AS ENUM ('global', 'area', 'issue');
662 COMMENT ON TYPE "delegation_scope" IS 'Scope for delegations: ''global'', ''area'', or ''issue'' (order is relevant)';
665 CREATE TABLE "delegation" (
666 "id" SERIAL8 PRIMARY KEY,
667 "truster_id" INT4 NOT NULL REFERENCES "member" ("id") ON DELETE CASCADE ON UPDATE CASCADE,
668 "trustee_id" INT4 NOT NULL REFERENCES "member" ("id") ON DELETE CASCADE ON UPDATE CASCADE,
669 "scope" "delegation_scope" NOT NULL,
670 "area_id" INT4 REFERENCES "area" ("id") ON DELETE CASCADE ON UPDATE CASCADE,
671 "issue_id" INT4 REFERENCES "issue" ("id") ON DELETE CASCADE ON UPDATE CASCADE,
672 CONSTRAINT "cant_delegate_to_yourself" CHECK ("truster_id" != "trustee_id"),
673 CONSTRAINT "area_id_and_issue_id_set_according_to_scope" CHECK (
674 ("scope" = 'global' AND "area_id" ISNULL AND "issue_id" ISNULL ) OR
675 ("scope" = 'area' AND "area_id" NOTNULL AND "issue_id" ISNULL ) OR
676 ("scope" = 'issue' AND "area_id" ISNULL AND "issue_id" NOTNULL) ),
677 UNIQUE ("area_id", "truster_id"),
678 UNIQUE ("issue_id", "truster_id") );
679 CREATE UNIQUE INDEX "delegation_global_truster_id_unique_idx"
680 ON "delegation" ("truster_id") WHERE "scope" = 'global';
681 CREATE INDEX "delegation_truster_id_idx" ON "delegation" ("truster_id");
682 CREATE INDEX "delegation_trustee_id_idx" ON "delegation" ("trustee_id");
684 COMMENT ON TABLE "delegation" IS 'Delegation of vote-weight to other members';
686 COMMENT ON COLUMN "delegation"."area_id" IS 'Reference to area, if delegation is area-wide, otherwise NULL';
687 COMMENT ON COLUMN "delegation"."issue_id" IS 'Reference to issue, if delegation is issue-wide, otherwise NULL';
689 CREATE FUNCTION "check_delegation"()
690 RETURNS TRIGGER
691 LANGUAGE 'plpgsql' VOLATILE AS $$
692 BEGIN
693 IF EXISTS (
694 SELECT NULL FROM "member" WHERE
695 "id" = NEW."trustee_id" AND active = 'n'
696 ) THEN
697 RAISE EXCEPTION 'Cannot delegate to an inactive member';
698 END IF;
699 RETURN NEW;
700 END;
701 $$;
703 CREATE TRIGGER "update_delegation"
704 BEFORE INSERT OR UPDATE ON "delegation"
705 FOR EACH ROW EXECUTE PROCEDURE
706 check_delegation();
708 COMMENT ON FUNCTION "check_delegation"() IS 'Sanity checks for new delegation. Dont allow delegations to inactive members';
710 CREATE TABLE "direct_population_snapshot" (
711 PRIMARY KEY ("issue_id", "event", "member_id"),
712 "issue_id" INT4 REFERENCES "issue" ("id") ON DELETE CASCADE ON UPDATE CASCADE,
713 "event" "snapshot_event",
714 "member_id" INT4 REFERENCES "member" ("id") ON DELETE RESTRICT ON UPDATE RESTRICT,
715 "weight" INT4 );
716 CREATE INDEX "direct_population_snapshot_member_id_idx" ON "direct_population_snapshot" ("member_id");
718 COMMENT ON TABLE "direct_population_snapshot" IS 'Snapshot of active members having either a "membership" in the "area" or an "interest" in the "issue"';
720 COMMENT ON COLUMN "direct_population_snapshot"."event" IS 'Reason for snapshot, see "snapshot_event" type for details';
721 COMMENT ON COLUMN "direct_population_snapshot"."weight" IS 'Weight of member (1 or higher) according to "delegating_population_snapshot"';
724 CREATE TABLE "delegating_population_snapshot" (
725 PRIMARY KEY ("issue_id", "event", "member_id"),
726 "issue_id" INT4 REFERENCES "issue" ("id") ON DELETE CASCADE ON UPDATE CASCADE,
727 "event" "snapshot_event",
728 "member_id" INT4 REFERENCES "member" ("id") ON DELETE RESTRICT ON UPDATE RESTRICT,
729 "weight" INT4,
730 "scope" "delegation_scope" NOT NULL,
731 "delegate_member_ids" INT4[] NOT NULL );
732 CREATE INDEX "delegating_population_snapshot_member_id_idx" ON "delegating_population_snapshot" ("member_id");
734 COMMENT ON TABLE "direct_population_snapshot" IS 'Delegations increasing the weight of entries in the "direct_population_snapshot" table';
736 COMMENT ON COLUMN "delegating_population_snapshot"."event" IS 'Reason for snapshot, see "snapshot_event" type for details';
737 COMMENT ON COLUMN "delegating_population_snapshot"."member_id" IS 'Delegating member';
738 COMMENT ON COLUMN "delegating_population_snapshot"."weight" IS 'Intermediate weight';
739 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"';
742 CREATE TABLE "direct_interest_snapshot" (
743 PRIMARY KEY ("issue_id", "event", "member_id"),
744 "issue_id" INT4 REFERENCES "issue" ("id") ON DELETE CASCADE ON UPDATE CASCADE,
745 "event" "snapshot_event",
746 "member_id" INT4 REFERENCES "member" ("id") ON DELETE RESTRICT ON UPDATE RESTRICT,
747 "weight" INT4,
748 "voting_requested" BOOLEAN );
749 CREATE INDEX "direct_interest_snapshot_member_id_idx" ON "direct_interest_snapshot" ("member_id");
751 COMMENT ON TABLE "direct_interest_snapshot" IS 'Snapshot of active members having an "interest" in the "issue"';
753 COMMENT ON COLUMN "direct_interest_snapshot"."event" IS 'Reason for snapshot, see "snapshot_event" type for details';
754 COMMENT ON COLUMN "direct_interest_snapshot"."weight" IS 'Weight of member (1 or higher) according to "delegating_interest_snapshot"';
755 COMMENT ON COLUMN "direct_interest_snapshot"."voting_requested" IS 'Copied from column "voting_requested" of table "interest"';
758 CREATE TABLE "delegating_interest_snapshot" (
759 PRIMARY KEY ("issue_id", "event", "member_id"),
760 "issue_id" INT4 REFERENCES "issue" ("id") ON DELETE CASCADE ON UPDATE CASCADE,
761 "event" "snapshot_event",
762 "member_id" INT4 REFERENCES "member" ("id") ON DELETE RESTRICT ON UPDATE RESTRICT,
763 "weight" INT4,
764 "scope" "delegation_scope" NOT NULL,
765 "delegate_member_ids" INT4[] NOT NULL );
766 CREATE INDEX "delegating_interest_snapshot_member_id_idx" ON "delegating_interest_snapshot" ("member_id");
768 COMMENT ON TABLE "delegating_interest_snapshot" IS 'Delegations increasing the weight of entries in the "direct_interest_snapshot" table';
770 COMMENT ON COLUMN "delegating_interest_snapshot"."event" IS 'Reason for snapshot, see "snapshot_event" type for details';
771 COMMENT ON COLUMN "delegating_interest_snapshot"."member_id" IS 'Delegating member';
772 COMMENT ON COLUMN "delegating_interest_snapshot"."weight" IS 'Intermediate weight';
773 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"';
776 CREATE TABLE "direct_supporter_snapshot" (
777 "issue_id" INT4 NOT NULL,
778 PRIMARY KEY ("initiative_id", "event", "member_id"),
779 "initiative_id" INT4,
780 "event" "snapshot_event",
781 "member_id" INT4 REFERENCES "member" ("id") ON DELETE RESTRICT ON UPDATE RESTRICT,
782 "informed" BOOLEAN NOT NULL,
783 "satisfied" BOOLEAN NOT NULL,
784 FOREIGN KEY ("issue_id", "initiative_id") REFERENCES "initiative" ("issue_id", "id") ON DELETE CASCADE ON UPDATE CASCADE,
785 FOREIGN KEY ("issue_id", "event", "member_id") REFERENCES "direct_interest_snapshot" ("issue_id", "event", "member_id") ON DELETE CASCADE ON UPDATE CASCADE );
786 CREATE INDEX "direct_supporter_snapshot_member_id_idx" ON "direct_supporter_snapshot" ("member_id");
788 COMMENT ON TABLE "direct_supporter_snapshot" IS 'Snapshot of supporters of initiatives (weight is stored in "direct_interest_snapshot")';
790 COMMENT ON COLUMN "direct_supporter_snapshot"."event" IS 'Reason for snapshot, see "snapshot_event" type for details';
791 COMMENT ON COLUMN "direct_supporter_snapshot"."informed" IS 'Supporter has seen the latest draft of the initiative';
792 COMMENT ON COLUMN "direct_supporter_snapshot"."satisfied" IS 'Supporter has no "critical_opinion"s';
795 CREATE TABLE "direct_voter" (
796 PRIMARY KEY ("issue_id", "member_id"),
797 "issue_id" INT4 REFERENCES "issue" ("id") ON DELETE CASCADE ON UPDATE CASCADE,
798 "member_id" INT4 REFERENCES "member" ("id") ON DELETE RESTRICT ON UPDATE RESTRICT,
799 "weight" INT4,
800 "autoreject" BOOLEAN NOT NULL DEFAULT FALSE );
801 CREATE INDEX "direct_voter_member_id_idx" ON "direct_voter" ("member_id");
803 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.';
805 COMMENT ON COLUMN "direct_voter"."weight" IS 'Weight of member (1 or higher) according to "delegating_voter" table';
806 COMMENT ON COLUMN "direct_voter"."autoreject" IS 'Votes were inserted due to "autoreject" feature';
809 CREATE TABLE "delegating_voter" (
810 PRIMARY KEY ("issue_id", "member_id"),
811 "issue_id" INT4 REFERENCES "issue" ("id") ON DELETE CASCADE ON UPDATE CASCADE,
812 "member_id" INT4 REFERENCES "member" ("id") ON DELETE RESTRICT ON UPDATE RESTRICT,
813 "weight" INT4,
814 "scope" "delegation_scope" NOT NULL,
815 "delegate_member_ids" INT4[] NOT NULL );
816 CREATE INDEX "delegating_voter_member_id_idx" ON "delegating_voter" ("member_id");
818 COMMENT ON TABLE "delegating_voter" IS 'Delegations increasing the weight of entries in the "direct_voter" table';
820 COMMENT ON COLUMN "delegating_voter"."member_id" IS 'Delegating member';
821 COMMENT ON COLUMN "delegating_voter"."weight" IS 'Intermediate weight';
822 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"';
825 CREATE TABLE "vote" (
826 "issue_id" INT4 NOT NULL,
827 PRIMARY KEY ("initiative_id", "member_id"),
828 "initiative_id" INT4,
829 "member_id" INT4,
830 "grade" INT4,
831 FOREIGN KEY ("issue_id", "initiative_id") REFERENCES "initiative" ("issue_id", "id") ON DELETE CASCADE ON UPDATE CASCADE,
832 FOREIGN KEY ("issue_id", "member_id") REFERENCES "direct_voter" ("issue_id", "member_id") ON DELETE CASCADE ON UPDATE CASCADE );
833 CREATE INDEX "vote_member_id_idx" ON "vote" ("member_id");
835 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.';
837 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.';
840 CREATE TABLE "contingent" (
841 "time_frame" INTERVAL PRIMARY KEY,
842 "text_entry_limit" INT4,
843 "initiative_limit" INT4 );
845 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.';
847 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';
848 COMMENT ON COLUMN "contingent"."initiative_limit" IS 'Number of new initiatives to be opened by each member within a given time frame';
852 --------------------------------
853 -- Writing of history entries --
854 --------------------------------
856 CREATE FUNCTION "write_member_history_trigger"()
857 RETURNS TRIGGER
858 LANGUAGE 'plpgsql' VOLATILE AS $$
859 BEGIN
860 IF
861 NEW."active" != OLD."active" OR
862 NEW."name" != OLD."name"
863 THEN
864 INSERT INTO "member_history"
865 ("member_id", "active", "name")
866 VALUES (NEW."id", OLD."active", OLD."name");
867 END IF;
868 RETURN NULL;
869 END;
870 $$;
872 CREATE TRIGGER "write_member_history"
873 AFTER UPDATE ON "member" FOR EACH ROW EXECUTE PROCEDURE
874 "write_member_history_trigger"();
876 COMMENT ON FUNCTION "write_member_history_trigger"() IS 'Implementation of trigger "write_member_history" on table "member"';
877 COMMENT ON TRIGGER "write_member_history" ON "member" IS 'When changing certain fields of a member, create a history entry in "member_history" table';
881 ----------------------------
882 -- Additional constraints --
883 ----------------------------
886 CREATE FUNCTION "issue_requires_first_initiative_trigger"()
887 RETURNS TRIGGER
888 LANGUAGE 'plpgsql' VOLATILE AS $$
889 BEGIN
890 IF NOT EXISTS (
891 SELECT NULL FROM "initiative" WHERE "issue_id" = NEW."id"
892 ) THEN
893 --RAISE 'Cannot create issue without an initial initiative.' USING
894 -- ERRCODE = 'integrity_constraint_violation',
895 -- HINT = 'Create issue, initiative, and draft within the same transaction.';
896 RAISE EXCEPTION 'Cannot create issue without an initial initiative.';
897 END IF;
898 RETURN NULL;
899 END;
900 $$;
902 CREATE CONSTRAINT TRIGGER "issue_requires_first_initiative"
903 AFTER INSERT OR UPDATE ON "issue" DEFERRABLE INITIALLY DEFERRED
904 FOR EACH ROW EXECUTE PROCEDURE
905 "issue_requires_first_initiative_trigger"();
907 COMMENT ON FUNCTION "issue_requires_first_initiative_trigger"() IS 'Implementation of trigger "issue_requires_first_initiative" on table "issue"';
908 COMMENT ON TRIGGER "issue_requires_first_initiative" ON "issue" IS 'Ensure that new issues have at least one initiative';
911 CREATE FUNCTION "last_initiative_deletes_issue_trigger"()
912 RETURNS TRIGGER
913 LANGUAGE 'plpgsql' VOLATILE AS $$
914 DECLARE
915 "reference_lost" BOOLEAN;
916 BEGIN
917 IF TG_OP = 'DELETE' THEN
918 "reference_lost" := TRUE;
919 ELSE
920 "reference_lost" := NEW."issue_id" != OLD."issue_id";
921 END IF;
922 IF
923 "reference_lost" AND NOT EXISTS (
924 SELECT NULL FROM "initiative" WHERE "issue_id" = OLD."issue_id"
925 )
926 THEN
927 DELETE FROM "issue" WHERE "id" = OLD."issue_id";
928 END IF;
929 RETURN NULL;
930 END;
931 $$;
933 CREATE CONSTRAINT TRIGGER "last_initiative_deletes_issue"
934 AFTER UPDATE OR DELETE ON "initiative" DEFERRABLE INITIALLY DEFERRED
935 FOR EACH ROW EXECUTE PROCEDURE
936 "last_initiative_deletes_issue_trigger"();
938 COMMENT ON FUNCTION "last_initiative_deletes_issue_trigger"() IS 'Implementation of trigger "last_initiative_deletes_issue" on table "initiative"';
939 COMMENT ON TRIGGER "last_initiative_deletes_issue" ON "initiative" IS 'Removing the last initiative of an issue deletes the issue';
942 CREATE FUNCTION "initiative_requires_first_draft_trigger"()
943 RETURNS TRIGGER
944 LANGUAGE 'plpgsql' VOLATILE AS $$
945 BEGIN
946 IF NOT EXISTS (
947 SELECT NULL FROM "draft" WHERE "initiative_id" = NEW."id"
948 ) THEN
949 --RAISE 'Cannot create initiative without an initial draft.' USING
950 -- ERRCODE = 'integrity_constraint_violation',
951 -- HINT = 'Create issue, initiative and draft within the same transaction.';
952 RAISE EXCEPTION 'Cannot create initiative without an initial draft.';
953 END IF;
954 RETURN NULL;
955 END;
956 $$;
958 CREATE CONSTRAINT TRIGGER "initiative_requires_first_draft"
959 AFTER INSERT OR UPDATE ON "initiative" DEFERRABLE INITIALLY DEFERRED
960 FOR EACH ROW EXECUTE PROCEDURE
961 "initiative_requires_first_draft_trigger"();
963 COMMENT ON FUNCTION "initiative_requires_first_draft_trigger"() IS 'Implementation of trigger "initiative_requires_first_draft" on table "initiative"';
964 COMMENT ON TRIGGER "initiative_requires_first_draft" ON "initiative" IS 'Ensure that new initiatives have at least one draft';
967 CREATE FUNCTION "last_draft_deletes_initiative_trigger"()
968 RETURNS TRIGGER
969 LANGUAGE 'plpgsql' VOLATILE AS $$
970 DECLARE
971 "reference_lost" BOOLEAN;
972 BEGIN
973 IF TG_OP = 'DELETE' THEN
974 "reference_lost" := TRUE;
975 ELSE
976 "reference_lost" := NEW."initiative_id" != OLD."initiative_id";
977 END IF;
978 IF
979 "reference_lost" AND NOT EXISTS (
980 SELECT NULL FROM "draft" WHERE "initiative_id" = OLD."initiative_id"
981 )
982 THEN
983 DELETE FROM "initiative" WHERE "id" = OLD."initiative_id";
984 END IF;
985 RETURN NULL;
986 END;
987 $$;
989 CREATE CONSTRAINT TRIGGER "last_draft_deletes_initiative"
990 AFTER UPDATE OR DELETE ON "draft" DEFERRABLE INITIALLY DEFERRED
991 FOR EACH ROW EXECUTE PROCEDURE
992 "last_draft_deletes_initiative_trigger"();
994 COMMENT ON FUNCTION "last_draft_deletes_initiative_trigger"() IS 'Implementation of trigger "last_draft_deletes_initiative" on table "draft"';
995 COMMENT ON TRIGGER "last_draft_deletes_initiative" ON "draft" IS 'Removing the last draft of an initiative deletes the initiative';
998 CREATE FUNCTION "suggestion_requires_first_opinion_trigger"()
999 RETURNS TRIGGER
1000 LANGUAGE 'plpgsql' VOLATILE AS $$
1001 BEGIN
1002 IF NOT EXISTS (
1003 SELECT NULL FROM "opinion" WHERE "suggestion_id" = NEW."id"
1004 ) THEN
1005 RAISE EXCEPTION 'Cannot create a suggestion without an opinion.';
1006 END IF;
1007 RETURN NULL;
1008 END;
1009 $$;
1011 CREATE CONSTRAINT TRIGGER "suggestion_requires_first_opinion"
1012 AFTER INSERT OR UPDATE ON "suggestion" DEFERRABLE INITIALLY DEFERRED
1013 FOR EACH ROW EXECUTE PROCEDURE
1014 "suggestion_requires_first_opinion_trigger"();
1016 COMMENT ON FUNCTION "suggestion_requires_first_opinion_trigger"() IS 'Implementation of trigger "suggestion_requires_first_opinion" on table "suggestion"';
1017 COMMENT ON TRIGGER "suggestion_requires_first_opinion" ON "suggestion" IS 'Ensure that new suggestions have at least one opinion';
1020 CREATE FUNCTION "last_opinion_deletes_suggestion_trigger"()
1021 RETURNS TRIGGER
1022 LANGUAGE 'plpgsql' VOLATILE AS $$
1023 DECLARE
1024 "reference_lost" BOOLEAN;
1025 BEGIN
1026 IF TG_OP = 'DELETE' THEN
1027 "reference_lost" := TRUE;
1028 ELSE
1029 "reference_lost" := NEW."suggestion_id" != OLD."suggestion_id";
1030 END IF;
1031 IF
1032 "reference_lost" AND NOT EXISTS (
1033 SELECT NULL FROM "opinion" WHERE "suggestion_id" = OLD."suggestion_id"
1035 THEN
1036 DELETE FROM "suggestion" WHERE "id" = OLD."suggestion_id";
1037 END IF;
1038 RETURN NULL;
1039 END;
1040 $$;
1042 CREATE CONSTRAINT TRIGGER "last_opinion_deletes_suggestion"
1043 AFTER UPDATE OR DELETE ON "opinion" DEFERRABLE INITIALLY DEFERRED
1044 FOR EACH ROW EXECUTE PROCEDURE
1045 "last_opinion_deletes_suggestion_trigger"();
1047 COMMENT ON FUNCTION "last_opinion_deletes_suggestion_trigger"() IS 'Implementation of trigger "last_opinion_deletes_suggestion" on table "opinion"';
1048 COMMENT ON TRIGGER "last_opinion_deletes_suggestion" ON "opinion" IS 'Removing the last opinion of a suggestion deletes the suggestion';
1052 ---------------------------------------------------------------
1053 -- Ensure that votes are not modified when issues are frozen --
1054 ---------------------------------------------------------------
1056 -- NOTE: Frontends should ensure this anyway, but in case of programming
1057 -- errors the following triggers ensure data integrity.
1060 CREATE FUNCTION "forbid_changes_on_closed_issue_trigger"()
1061 RETURNS TRIGGER
1062 LANGUAGE 'plpgsql' VOLATILE AS $$
1063 DECLARE
1064 "issue_id_v" "issue"."id"%TYPE;
1065 "issue_row" "issue"%ROWTYPE;
1066 BEGIN
1067 IF TG_OP = 'DELETE' THEN
1068 "issue_id_v" := OLD."issue_id";
1069 ELSE
1070 "issue_id_v" := NEW."issue_id";
1071 END IF;
1072 SELECT INTO "issue_row" * FROM "issue"
1073 WHERE "id" = "issue_id_v" FOR SHARE;
1074 IF "issue_row"."closed" NOTNULL THEN
1075 RAISE EXCEPTION 'Tried to modify data belonging to a closed issue.';
1076 END IF;
1077 RETURN NULL;
1078 END;
1079 $$;
1081 CREATE TRIGGER "forbid_changes_on_closed_issue"
1082 AFTER INSERT OR UPDATE OR DELETE ON "direct_voter"
1083 FOR EACH ROW EXECUTE PROCEDURE
1084 "forbid_changes_on_closed_issue_trigger"();
1086 CREATE TRIGGER "forbid_changes_on_closed_issue"
1087 AFTER INSERT OR UPDATE OR DELETE ON "delegating_voter"
1088 FOR EACH ROW EXECUTE PROCEDURE
1089 "forbid_changes_on_closed_issue_trigger"();
1091 CREATE TRIGGER "forbid_changes_on_closed_issue"
1092 AFTER INSERT OR UPDATE OR DELETE ON "vote"
1093 FOR EACH ROW EXECUTE PROCEDURE
1094 "forbid_changes_on_closed_issue_trigger"();
1096 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"';
1097 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';
1098 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';
1099 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';
1103 --------------------------------------------------------------------
1104 -- Auto-retrieval of fields only needed for referential integrity --
1105 --------------------------------------------------------------------
1108 CREATE FUNCTION "autofill_issue_id_trigger"()
1109 RETURNS TRIGGER
1110 LANGUAGE 'plpgsql' VOLATILE AS $$
1111 BEGIN
1112 IF NEW."issue_id" ISNULL THEN
1113 SELECT "issue_id" INTO NEW."issue_id"
1114 FROM "initiative" WHERE "id" = NEW."initiative_id";
1115 END IF;
1116 RETURN NEW;
1117 END;
1118 $$;
1120 CREATE TRIGGER "autofill_issue_id" BEFORE INSERT ON "supporter"
1121 FOR EACH ROW EXECUTE PROCEDURE "autofill_issue_id_trigger"();
1123 CREATE TRIGGER "autofill_issue_id" BEFORE INSERT ON "vote"
1124 FOR EACH ROW EXECUTE PROCEDURE "autofill_issue_id_trigger"();
1126 COMMENT ON FUNCTION "autofill_issue_id_trigger"() IS 'Implementation of triggers "autofill_issue_id" on tables "supporter" and "vote"';
1127 COMMENT ON TRIGGER "autofill_issue_id" ON "supporter" IS 'Set "issue_id" field automatically, if NULL';
1128 COMMENT ON TRIGGER "autofill_issue_id" ON "vote" IS 'Set "issue_id" field automatically, if NULL';
1131 CREATE FUNCTION "autofill_initiative_id_trigger"()
1132 RETURNS TRIGGER
1133 LANGUAGE 'plpgsql' VOLATILE AS $$
1134 BEGIN
1135 IF NEW."initiative_id" ISNULL THEN
1136 SELECT "initiative_id" INTO NEW."initiative_id"
1137 FROM "suggestion" WHERE "id" = NEW."suggestion_id";
1138 END IF;
1139 RETURN NEW;
1140 END;
1141 $$;
1143 CREATE TRIGGER "autofill_initiative_id" BEFORE INSERT ON "opinion"
1144 FOR EACH ROW EXECUTE PROCEDURE "autofill_initiative_id_trigger"();
1146 COMMENT ON FUNCTION "autofill_initiative_id_trigger"() IS 'Implementation of trigger "autofill_initiative_id" on table "opinion"';
1147 COMMENT ON TRIGGER "autofill_initiative_id" ON "opinion" IS 'Set "initiative_id" field automatically, if NULL';
1151 -----------------------------------------------------
1152 -- Automatic calculation of certain default values --
1153 -----------------------------------------------------
1156 CREATE FUNCTION "copy_timings_trigger"()
1157 RETURNS TRIGGER
1158 LANGUAGE 'plpgsql' VOLATILE AS $$
1159 DECLARE
1160 "policy_row" "policy"%ROWTYPE;
1161 BEGIN
1162 SELECT * INTO "policy_row" FROM "policy"
1163 WHERE "id" = NEW."policy_id";
1164 IF NEW."admission_time" ISNULL THEN
1165 NEW."admission_time" := "policy_row"."admission_time";
1166 END IF;
1167 IF NEW."discussion_time" ISNULL THEN
1168 NEW."discussion_time" := "policy_row"."discussion_time";
1169 END IF;
1170 IF NEW."verification_time" ISNULL THEN
1171 NEW."verification_time" := "policy_row"."verification_time";
1172 END IF;
1173 IF NEW."voting_time" ISNULL THEN
1174 NEW."voting_time" := "policy_row"."voting_time";
1175 END IF;
1176 RETURN NEW;
1177 END;
1178 $$;
1180 CREATE TRIGGER "copy_timings" BEFORE INSERT OR UPDATE ON "issue"
1181 FOR EACH ROW EXECUTE PROCEDURE "copy_timings_trigger"();
1183 COMMENT ON FUNCTION "copy_timings_trigger"() IS 'Implementation of trigger "copy_timings" on table "issue"';
1184 COMMENT ON TRIGGER "copy_timings" ON "issue" IS 'If timing fields are NULL, copy values from policy.';
1187 CREATE FUNCTION "copy_autoreject_trigger"()
1188 RETURNS TRIGGER
1189 LANGUAGE 'plpgsql' VOLATILE AS $$
1190 BEGIN
1191 IF NEW."autoreject" ISNULL THEN
1192 SELECT "membership"."autoreject" INTO NEW."autoreject"
1193 FROM "issue" JOIN "membership"
1194 ON "issue"."area_id" = "membership"."area_id"
1195 WHERE "issue"."id" = NEW."issue_id"
1196 AND "membership"."member_id" = NEW."member_id";
1197 END IF;
1198 IF NEW."autoreject" ISNULL THEN
1199 NEW."autoreject" := FALSE;
1200 END IF;
1201 RETURN NEW;
1202 END;
1203 $$;
1205 CREATE TRIGGER "copy_autoreject" BEFORE INSERT OR UPDATE ON "interest"
1206 FOR EACH ROW EXECUTE PROCEDURE "copy_autoreject_trigger"();
1208 COMMENT ON FUNCTION "copy_autoreject_trigger"() IS 'Implementation of trigger "copy_autoreject" on table "interest"';
1209 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';
1212 CREATE FUNCTION "supporter_default_for_draft_id_trigger"()
1213 RETURNS TRIGGER
1214 LANGUAGE 'plpgsql' VOLATILE AS $$
1215 BEGIN
1216 IF NEW."draft_id" ISNULL THEN
1217 SELECT "id" INTO NEW."draft_id" FROM "current_draft"
1218 WHERE "initiative_id" = NEW."initiative_id";
1219 END IF;
1220 RETURN NEW;
1221 END;
1222 $$;
1224 CREATE TRIGGER "default_for_draft_id" BEFORE INSERT OR UPDATE ON "supporter"
1225 FOR EACH ROW EXECUTE PROCEDURE "supporter_default_for_draft_id_trigger"();
1227 COMMENT ON FUNCTION "supporter_default_for_draft_id_trigger"() IS 'Implementation of trigger "default_for_draft" on table "supporter"';
1228 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';
1232 ----------------------------------------
1233 -- Automatic creation of dependencies --
1234 ----------------------------------------
1237 CREATE FUNCTION "autocreate_interest_trigger"()
1238 RETURNS TRIGGER
1239 LANGUAGE 'plpgsql' VOLATILE AS $$
1240 BEGIN
1241 IF NOT EXISTS (
1242 SELECT NULL FROM "initiative" JOIN "interest"
1243 ON "initiative"."issue_id" = "interest"."issue_id"
1244 WHERE "initiative"."id" = NEW."initiative_id"
1245 AND "interest"."member_id" = NEW."member_id"
1246 ) THEN
1247 BEGIN
1248 INSERT INTO "interest" ("issue_id", "member_id")
1249 SELECT "issue_id", NEW."member_id"
1250 FROM "initiative" WHERE "id" = NEW."initiative_id";
1251 EXCEPTION WHEN unique_violation THEN END;
1252 END IF;
1253 RETURN NEW;
1254 END;
1255 $$;
1257 CREATE TRIGGER "autocreate_interest" BEFORE INSERT ON "supporter"
1258 FOR EACH ROW EXECUTE PROCEDURE "autocreate_interest_trigger"();
1260 COMMENT ON FUNCTION "autocreate_interest_trigger"() IS 'Implementation of trigger "autocreate_interest" on table "supporter"';
1261 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';
1264 CREATE FUNCTION "autocreate_supporter_trigger"()
1265 RETURNS TRIGGER
1266 LANGUAGE 'plpgsql' VOLATILE AS $$
1267 BEGIN
1268 IF NOT EXISTS (
1269 SELECT NULL FROM "suggestion" JOIN "supporter"
1270 ON "suggestion"."initiative_id" = "supporter"."initiative_id"
1271 WHERE "suggestion"."id" = NEW."suggestion_id"
1272 AND "supporter"."member_id" = NEW."member_id"
1273 ) THEN
1274 BEGIN
1275 INSERT INTO "supporter" ("initiative_id", "member_id")
1276 SELECT "initiative_id", NEW."member_id"
1277 FROM "suggestion" WHERE "id" = NEW."suggestion_id";
1278 EXCEPTION WHEN unique_violation THEN END;
1279 END IF;
1280 RETURN NEW;
1281 END;
1282 $$;
1284 CREATE TRIGGER "autocreate_supporter" BEFORE INSERT ON "opinion"
1285 FOR EACH ROW EXECUTE PROCEDURE "autocreate_supporter_trigger"();
1287 COMMENT ON FUNCTION "autocreate_supporter_trigger"() IS 'Implementation of trigger "autocreate_supporter" on table "opinion"';
1288 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.';
1292 ------------------------------------------
1293 -- Views and helper functions for views --
1294 ------------------------------------------
1297 CREATE VIEW "active_delegation" AS
1298 SELECT "delegation".* FROM "delegation"
1299 JOIN "member" ON "delegation"."truster_id" = "member"."id"
1300 WHERE "member"."active" = TRUE;
1302 COMMENT ON VIEW "active_delegation" IS 'Delegations where the truster_id refers to an active member';
1305 CREATE VIEW "global_delegation" AS
1306 SELECT "id", "truster_id", "trustee_id"
1307 FROM "active_delegation" WHERE "scope" = 'global';
1309 COMMENT ON VIEW "global_delegation" IS 'Global delegations from active members';
1312 CREATE VIEW "area_delegation" AS
1313 SELECT DISTINCT ON ("area"."id", "delegation"."truster_id")
1314 "area"."id" AS "area_id",
1315 "delegation"."id",
1316 "delegation"."truster_id",
1317 "delegation"."trustee_id",
1318 "delegation"."scope"
1319 FROM "area" JOIN "active_delegation" AS "delegation"
1320 ON "delegation"."scope" = 'global'
1321 OR "delegation"."area_id" = "area"."id"
1322 ORDER BY
1323 "area"."id",
1324 "delegation"."truster_id",
1325 "delegation"."scope" DESC;
1327 COMMENT ON VIEW "area_delegation" IS 'Resulting area delegations from active members';
1330 CREATE VIEW "issue_delegation" AS
1331 SELECT DISTINCT ON ("issue"."id", "delegation"."truster_id")
1332 "issue"."id" AS "issue_id",
1333 "delegation"."id",
1334 "delegation"."truster_id",
1335 "delegation"."trustee_id",
1336 "delegation"."scope"
1337 FROM "issue" JOIN "active_delegation" AS "delegation"
1338 ON "delegation"."scope" = 'global'
1339 OR "delegation"."area_id" = "issue"."area_id"
1340 OR "delegation"."issue_id" = "issue"."id"
1341 ORDER BY
1342 "issue"."id",
1343 "delegation"."truster_id",
1344 "delegation"."scope" DESC;
1346 COMMENT ON VIEW "issue_delegation" IS 'Resulting issue delegations from active members';
1349 CREATE FUNCTION "membership_weight_with_skipping"
1350 ( "area_id_p" "area"."id"%TYPE,
1351 "member_id_p" "member"."id"%TYPE,
1352 "skip_member_ids_p" INT4[] ) -- "member"."id"%TYPE[]
1353 RETURNS INT4
1354 LANGUAGE 'plpgsql' STABLE AS $$
1355 DECLARE
1356 "sum_v" INT4;
1357 "delegation_row" "area_delegation"%ROWTYPE;
1358 BEGIN
1359 "sum_v" := 1;
1360 FOR "delegation_row" IN
1361 SELECT "area_delegation".*
1362 FROM "area_delegation" LEFT JOIN "membership"
1363 ON "membership"."area_id" = "area_id_p"
1364 AND "membership"."member_id" = "area_delegation"."truster_id"
1365 WHERE "area_delegation"."area_id" = "area_id_p"
1366 AND "area_delegation"."trustee_id" = "member_id_p"
1367 AND "membership"."member_id" ISNULL
1368 LOOP
1369 IF NOT
1370 "skip_member_ids_p" @> ARRAY["delegation_row"."truster_id"]
1371 THEN
1372 "sum_v" := "sum_v" + "membership_weight_with_skipping"(
1373 "area_id_p",
1374 "delegation_row"."truster_id",
1375 "skip_member_ids_p" || "delegation_row"."truster_id"
1376 );
1377 END IF;
1378 END LOOP;
1379 RETURN "sum_v";
1380 END;
1381 $$;
1383 COMMENT ON FUNCTION "membership_weight_with_skipping"
1384 ( "area"."id"%TYPE,
1385 "member"."id"%TYPE,
1386 INT4[] )
1387 IS 'Helper function for "membership_weight" function';
1390 CREATE FUNCTION "membership_weight"
1391 ( "area_id_p" "area"."id"%TYPE,
1392 "member_id_p" "member"."id"%TYPE ) -- "member"."id"%TYPE[]
1393 RETURNS INT4
1394 LANGUAGE 'plpgsql' STABLE AS $$
1395 BEGIN
1396 RETURN "membership_weight_with_skipping"(
1397 "area_id_p",
1398 "member_id_p",
1399 ARRAY["member_id_p"]
1400 );
1401 END;
1402 $$;
1404 COMMENT ON FUNCTION "membership_weight"
1405 ( "area"."id"%TYPE,
1406 "member"."id"%TYPE )
1407 IS 'Calculates the potential voting weight of a member in a given area';
1410 CREATE VIEW "member_count_view" AS
1411 SELECT count(1) AS "total_count" FROM "member" WHERE "active";
1413 COMMENT ON VIEW "member_count_view" IS 'View used to update "member_count" table';
1416 CREATE VIEW "area_member_count" AS
1417 SELECT
1418 "area"."id" AS "area_id",
1419 count("member"."id") AS "direct_member_count",
1420 coalesce(
1421 sum(
1422 CASE WHEN "member"."id" NOTNULL THEN
1423 "membership_weight"("area"."id", "member"."id")
1424 ELSE 0 END
1426 ) AS "member_weight",
1427 coalesce(
1428 sum(
1429 CASE WHEN "member"."id" NOTNULL AND "membership"."autoreject" THEN
1430 "membership_weight"("area"."id", "member"."id")
1431 ELSE 0 END
1433 ) AS "autoreject_weight"
1434 FROM "area"
1435 LEFT JOIN "membership"
1436 ON "area"."id" = "membership"."area_id"
1437 LEFT JOIN "member"
1438 ON "membership"."member_id" = "member"."id"
1439 AND "member"."active"
1440 GROUP BY "area"."id";
1442 COMMENT ON VIEW "area_member_count" IS 'View used to update "member_count" column of table "area"';
1445 CREATE VIEW "opening_draft" AS
1446 SELECT "draft".* FROM (
1447 SELECT
1448 "initiative"."id" AS "initiative_id",
1449 min("draft"."id") AS "draft_id"
1450 FROM "initiative" JOIN "draft"
1451 ON "initiative"."id" = "draft"."initiative_id"
1452 GROUP BY "initiative"."id"
1453 ) AS "subquery"
1454 JOIN "draft" ON "subquery"."draft_id" = "draft"."id";
1456 COMMENT ON VIEW "opening_draft" IS 'First drafts of all initiatives';
1459 CREATE VIEW "current_draft" AS
1460 SELECT "draft".* FROM (
1461 SELECT
1462 "initiative"."id" AS "initiative_id",
1463 max("draft"."id") AS "draft_id"
1464 FROM "initiative" JOIN "draft"
1465 ON "initiative"."id" = "draft"."initiative_id"
1466 GROUP BY "initiative"."id"
1467 ) AS "subquery"
1468 JOIN "draft" ON "subquery"."draft_id" = "draft"."id";
1470 COMMENT ON VIEW "current_draft" IS 'All latest drafts for each initiative';
1473 CREATE VIEW "critical_opinion" AS
1474 SELECT * FROM "opinion"
1475 WHERE ("degree" = 2 AND "fulfilled" = FALSE)
1476 OR ("degree" = -2 AND "fulfilled" = TRUE);
1478 COMMENT ON VIEW "critical_opinion" IS 'Opinions currently causing dissatisfaction';
1481 CREATE VIEW "battle_view" AS
1482 SELECT
1483 "issue"."id" AS "issue_id",
1484 "winning_initiative"."id" AS "winning_initiative_id",
1485 "losing_initiative"."id" AS "losing_initiative_id",
1486 sum(
1487 CASE WHEN
1488 coalesce("better_vote"."grade", 0) >
1489 coalesce("worse_vote"."grade", 0)
1490 THEN "direct_voter"."weight" ELSE 0 END
1491 ) AS "count"
1492 FROM "issue"
1493 LEFT JOIN "direct_voter"
1494 ON "issue"."id" = "direct_voter"."issue_id"
1495 JOIN "initiative" AS "winning_initiative"
1496 ON "issue"."id" = "winning_initiative"."issue_id"
1497 AND "winning_initiative"."agreed"
1498 JOIN "initiative" AS "losing_initiative"
1499 ON "issue"."id" = "losing_initiative"."issue_id"
1500 AND "losing_initiative"."agreed"
1501 LEFT JOIN "vote" AS "better_vote"
1502 ON "direct_voter"."member_id" = "better_vote"."member_id"
1503 AND "winning_initiative"."id" = "better_vote"."initiative_id"
1504 LEFT JOIN "vote" AS "worse_vote"
1505 ON "direct_voter"."member_id" = "worse_vote"."member_id"
1506 AND "losing_initiative"."id" = "worse_vote"."initiative_id"
1507 WHERE "issue"."closed" NOTNULL
1508 AND "issue"."cleaned" ISNULL
1509 AND "winning_initiative"."id" != "losing_initiative"."id"
1510 GROUP BY
1511 "issue"."id",
1512 "winning_initiative"."id",
1513 "losing_initiative"."id";
1515 COMMENT ON VIEW "battle_view" IS 'Number of members preferring one initiative to another; Used to fill "battle" table';
1518 CREATE VIEW "expired_session" AS
1519 SELECT * FROM "session" WHERE now() > "expiry";
1521 CREATE RULE "delete" AS ON DELETE TO "expired_session" DO INSTEAD
1522 DELETE FROM "session" WHERE "ident" = OLD."ident";
1524 COMMENT ON VIEW "expired_session" IS 'View containing all expired sessions where DELETE is possible';
1525 COMMENT ON RULE "delete" ON "expired_session" IS 'Rule allowing DELETE on rows in "expired_session" view, i.e. DELETE FROM "expired_session"';
1528 CREATE VIEW "open_issue" AS
1529 SELECT * FROM "issue" WHERE "closed" ISNULL;
1531 COMMENT ON VIEW "open_issue" IS 'All open issues';
1534 CREATE VIEW "issue_with_ranks_missing" AS
1535 SELECT * FROM "issue"
1536 WHERE "fully_frozen" NOTNULL
1537 AND "closed" NOTNULL
1538 AND "ranks_available" = FALSE;
1540 COMMENT ON VIEW "issue_with_ranks_missing" IS 'Issues where voting was finished, but no ranks have been calculated yet';
1543 CREATE VIEW "member_contingent" AS
1544 SELECT
1545 "member"."id" AS "member_id",
1546 "contingent"."time_frame",
1547 CASE WHEN "contingent"."text_entry_limit" NOTNULL THEN
1549 SELECT count(1) FROM "draft"
1550 WHERE "draft"."author_id" = "member"."id"
1551 AND "draft"."created" > now() - "contingent"."time_frame"
1552 ) + (
1553 SELECT count(1) FROM "suggestion"
1554 WHERE "suggestion"."author_id" = "member"."id"
1555 AND "suggestion"."created" > now() - "contingent"."time_frame"
1557 ELSE NULL END AS "text_entry_count",
1558 "contingent"."text_entry_limit",
1559 CASE WHEN "contingent"."initiative_limit" NOTNULL THEN (
1560 SELECT count(1) FROM "opening_draft"
1561 WHERE "opening_draft"."author_id" = "member"."id"
1562 AND "opening_draft"."created" > now() - "contingent"."time_frame"
1563 ) ELSE NULL END AS "initiative_count",
1564 "contingent"."initiative_limit"
1565 FROM "member" CROSS JOIN "contingent";
1567 COMMENT ON VIEW "member_contingent" IS 'Actual counts of text entries and initiatives are calculated per member for each limit in the "contingent" table.';
1569 COMMENT ON COLUMN "member_contingent"."text_entry_count" IS 'Only calculated when "text_entry_limit" is not null in the same row';
1570 COMMENT ON COLUMN "member_contingent"."initiative_count" IS 'Only calculated when "initiative_limit" is not null in the same row';
1573 CREATE VIEW "member_contingent_left" AS
1574 SELECT
1575 "member_id",
1576 max("text_entry_limit" - "text_entry_count") AS "text_entries_left",
1577 max("initiative_limit" - "initiative_count") AS "initiatives_left"
1578 FROM "member_contingent" GROUP BY "member_id";
1580 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.';
1583 CREATE TYPE "timeline_event" AS ENUM (
1584 'issue_created',
1585 'issue_canceled',
1586 'issue_accepted',
1587 'issue_half_frozen',
1588 'issue_finished_without_voting',
1589 'issue_voting_started',
1590 'issue_finished_after_voting',
1591 'initiative_created',
1592 'initiative_revoked',
1593 'draft_created',
1594 'suggestion_created');
1596 COMMENT ON TYPE "timeline_event" IS 'Types of event in timeline tables';
1599 CREATE VIEW "timeline_issue" AS
1600 SELECT
1601 "created" AS "occurrence",
1602 'issue_created'::"timeline_event" AS "event",
1603 "id" AS "issue_id"
1604 FROM "issue"
1605 UNION ALL
1606 SELECT
1607 "closed" AS "occurrence",
1608 'issue_canceled'::"timeline_event" AS "event",
1609 "id" AS "issue_id"
1610 FROM "issue" WHERE "closed" NOTNULL AND "fully_frozen" ISNULL
1611 UNION ALL
1612 SELECT
1613 "accepted" AS "occurrence",
1614 'issue_accepted'::"timeline_event" AS "event",
1615 "id" AS "issue_id"
1616 FROM "issue" WHERE "accepted" NOTNULL
1617 UNION ALL
1618 SELECT
1619 "half_frozen" AS "occurrence",
1620 'issue_half_frozen'::"timeline_event" AS "event",
1621 "id" AS "issue_id"
1622 FROM "issue" WHERE "half_frozen" NOTNULL
1623 UNION ALL
1624 SELECT
1625 "fully_frozen" AS "occurrence",
1626 'issue_voting_started'::"timeline_event" AS "event",
1627 "id" AS "issue_id"
1628 FROM "issue"
1629 WHERE "fully_frozen" NOTNULL
1630 AND ("closed" ISNULL OR "closed" != "fully_frozen")
1631 UNION ALL
1632 SELECT
1633 "closed" AS "occurrence",
1634 CASE WHEN "fully_frozen" = "closed" THEN
1635 'issue_finished_without_voting'::"timeline_event"
1636 ELSE
1637 'issue_finished_after_voting'::"timeline_event"
1638 END AS "event",
1639 "id" AS "issue_id"
1640 FROM "issue" WHERE "closed" NOTNULL AND "fully_frozen" NOTNULL;
1642 COMMENT ON VIEW "timeline_issue" IS 'Helper view for "timeline" view';
1645 CREATE VIEW "timeline_initiative" AS
1646 SELECT
1647 "created" AS "occurrence",
1648 'initiative_created'::"timeline_event" AS "event",
1649 "id" AS "initiative_id"
1650 FROM "initiative"
1651 UNION ALL
1652 SELECT
1653 "revoked" AS "occurrence",
1654 'initiative_revoked'::"timeline_event" AS "event",
1655 "id" AS "initiative_id"
1656 FROM "initiative" WHERE "revoked" NOTNULL;
1658 COMMENT ON VIEW "timeline_initiative" IS 'Helper view for "timeline" view';
1661 CREATE VIEW "timeline_draft" AS
1662 SELECT
1663 "created" AS "occurrence",
1664 'draft_created'::"timeline_event" AS "event",
1665 "id" AS "draft_id"
1666 FROM "draft";
1668 COMMENT ON VIEW "timeline_draft" IS 'Helper view for "timeline" view';
1671 CREATE VIEW "timeline_suggestion" AS
1672 SELECT
1673 "created" AS "occurrence",
1674 'suggestion_created'::"timeline_event" AS "event",
1675 "id" AS "suggestion_id"
1676 FROM "suggestion";
1678 COMMENT ON VIEW "timeline_suggestion" IS 'Helper view for "timeline" view';
1681 CREATE VIEW "timeline" AS
1682 SELECT
1683 "occurrence",
1684 "event",
1685 "issue_id",
1686 NULL AS "initiative_id",
1687 NULL::INT8 AS "draft_id", -- TODO: Why do we need a type-cast here? Is this due to 32 bit architecture?
1688 NULL::INT8 AS "suggestion_id"
1689 FROM "timeline_issue"
1690 UNION ALL
1691 SELECT
1692 "occurrence",
1693 "event",
1694 NULL AS "issue_id",
1695 "initiative_id",
1696 NULL AS "draft_id",
1697 NULL AS "suggestion_id"
1698 FROM "timeline_initiative"
1699 UNION ALL
1700 SELECT
1701 "occurrence",
1702 "event",
1703 NULL AS "issue_id",
1704 NULL AS "initiative_id",
1705 "draft_id",
1706 NULL AS "suggestion_id"
1707 FROM "timeline_draft"
1708 UNION ALL
1709 SELECT
1710 "occurrence",
1711 "event",
1712 NULL AS "issue_id",
1713 NULL AS "initiative_id",
1714 NULL AS "draft_id",
1715 "suggestion_id"
1716 FROM "timeline_suggestion";
1718 COMMENT ON VIEW "timeline" IS 'Aggregation of different events in the system';
1722 --------------------------------------------------
1723 -- Set returning function for delegation chains --
1724 --------------------------------------------------
1727 CREATE TYPE "delegation_chain_loop_tag" AS ENUM
1728 ('first', 'intermediate', 'last', 'repetition');
1730 COMMENT ON TYPE "delegation_chain_loop_tag" IS 'Type for loop tags in "delegation_chain_row" type';
1733 CREATE TYPE "delegation_chain_row" AS (
1734 "index" INT4,
1735 "member_id" INT4,
1736 "member_active" BOOLEAN,
1737 "participation" BOOLEAN,
1738 "overridden" BOOLEAN,
1739 "scope_in" "delegation_scope",
1740 "scope_out" "delegation_scope",
1741 "loop" "delegation_chain_loop_tag" );
1743 COMMENT ON TYPE "delegation_chain_row" IS 'Type of rows returned by "delegation_chain"(...) functions';
1745 COMMENT ON COLUMN "delegation_chain_row"."index" IS 'Index starting with 0 and counting up';
1746 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';
1747 COMMENT ON COLUMN "delegation_chain_row"."overridden" IS 'True, if an entry with lower index has "participation" set to true';
1748 COMMENT ON COLUMN "delegation_chain_row"."scope_in" IS 'Scope of used incoming delegation';
1749 COMMENT ON COLUMN "delegation_chain_row"."scope_out" IS 'Scope of used outgoing delegation';
1750 COMMENT ON COLUMN "delegation_chain_row"."loop" IS 'Not null, if member is part of a loop, see "delegation_chain_loop_tag" type';
1753 CREATE FUNCTION "delegation_chain"
1754 ( "member_id_p" "member"."id"%TYPE,
1755 "area_id_p" "area"."id"%TYPE,
1756 "issue_id_p" "issue"."id"%TYPE,
1757 "simulate_trustee_id_p" "member"."id"%TYPE )
1758 RETURNS SETOF "delegation_chain_row"
1759 LANGUAGE 'plpgsql' STABLE AS $$
1760 DECLARE
1761 "issue_row" "issue"%ROWTYPE;
1762 "visited_member_ids" INT4[]; -- "member"."id"%TYPE[]
1763 "loop_member_id_v" "member"."id"%TYPE;
1764 "output_row" "delegation_chain_row";
1765 "output_rows" "delegation_chain_row"[];
1766 "delegation_row" "delegation"%ROWTYPE;
1767 "row_count" INT4;
1768 "i" INT4;
1769 "loop_v" BOOLEAN;
1770 BEGIN
1771 SELECT * INTO "issue_row" FROM "issue" WHERE "id" = "issue_id_p";
1772 "visited_member_ids" := '{}';
1773 "loop_member_id_v" := NULL;
1774 "output_rows" := '{}';
1775 "output_row"."index" := 0;
1776 "output_row"."member_id" := "member_id_p";
1777 "output_row"."member_active" := TRUE;
1778 "output_row"."participation" := FALSE;
1779 "output_row"."overridden" := FALSE;
1780 "output_row"."scope_out" := NULL;
1781 LOOP
1782 IF "visited_member_ids" @> ARRAY["output_row"."member_id"] THEN
1783 "loop_member_id_v" := "output_row"."member_id";
1784 ELSE
1785 "visited_member_ids" :=
1786 "visited_member_ids" || "output_row"."member_id";
1787 END IF;
1788 IF "output_row"."participation" THEN
1789 "output_row"."overridden" := TRUE;
1790 END IF;
1791 "output_row"."scope_in" := "output_row"."scope_out";
1792 IF EXISTS (
1793 SELECT NULL FROM "member"
1794 WHERE "id" = "output_row"."member_id" AND "active"
1795 ) THEN
1796 IF "area_id_p" ISNULL AND "issue_id_p" ISNULL THEN
1797 SELECT * INTO "delegation_row" FROM "delegation"
1798 WHERE "truster_id" = "output_row"."member_id"
1799 AND "scope" = 'global';
1800 ELSIF "area_id_p" NOTNULL AND "issue_id_p" ISNULL THEN
1801 "output_row"."participation" := EXISTS (
1802 SELECT NULL FROM "membership"
1803 WHERE "area_id" = "area_id_p"
1804 AND "member_id" = "output_row"."member_id"
1805 );
1806 SELECT * INTO "delegation_row" FROM "delegation"
1807 WHERE "truster_id" = "output_row"."member_id"
1808 AND ("scope" = 'global' OR "area_id" = "area_id_p")
1809 ORDER BY "scope" DESC;
1810 ELSIF "area_id_p" ISNULL AND "issue_id_p" NOTNULL THEN
1811 "output_row"."participation" := EXISTS (
1812 SELECT NULL FROM "interest"
1813 WHERE "issue_id" = "issue_id_p"
1814 AND "member_id" = "output_row"."member_id"
1815 );
1816 SELECT * INTO "delegation_row" FROM "delegation"
1817 WHERE "truster_id" = "output_row"."member_id"
1818 AND ("scope" = 'global' OR
1819 "area_id" = "issue_row"."area_id" OR
1820 "issue_id" = "issue_id_p"
1822 ORDER BY "scope" DESC;
1823 ELSE
1824 RAISE EXCEPTION 'Either area_id or issue_id or both must be NULL.';
1825 END IF;
1826 ELSE
1827 "output_row"."member_active" := FALSE;
1828 "output_row"."participation" := FALSE;
1829 "output_row"."scope_out" := NULL;
1830 "delegation_row" := ROW(NULL);
1831 END IF;
1832 IF
1833 "output_row"."member_id" = "member_id_p" AND
1834 "simulate_trustee_id_p" NOTNULL
1835 THEN
1836 "output_row"."scope_out" := CASE
1837 WHEN "area_id_p" ISNULL AND "issue_id_p" ISNULL THEN 'global'
1838 WHEN "area_id_p" NOTNULL AND "issue_id_p" ISNULL THEN 'area'
1839 WHEN "area_id_p" ISNULL AND "issue_id_p" NOTNULL THEN 'issue'
1840 END;
1841 "output_rows" := "output_rows" || "output_row";
1842 "output_row"."member_id" := "simulate_trustee_id_p";
1843 ELSIF "delegation_row"."trustee_id" NOTNULL THEN
1844 "output_row"."scope_out" := "delegation_row"."scope";
1845 "output_rows" := "output_rows" || "output_row";
1846 "output_row"."member_id" := "delegation_row"."trustee_id";
1847 ELSE
1848 "output_row"."scope_out" := NULL;
1849 "output_rows" := "output_rows" || "output_row";
1850 EXIT;
1851 END IF;
1852 EXIT WHEN "loop_member_id_v" NOTNULL;
1853 "output_row"."index" := "output_row"."index" + 1;
1854 END LOOP;
1855 "row_count" := array_upper("output_rows", 1);
1856 "i" := 1;
1857 "loop_v" := FALSE;
1858 LOOP
1859 "output_row" := "output_rows"["i"];
1860 EXIT WHEN "output_row"."member_id" ISNULL;
1861 IF "loop_v" THEN
1862 IF "i" + 1 = "row_count" THEN
1863 "output_row"."loop" := 'last';
1864 ELSIF "i" = "row_count" THEN
1865 "output_row"."loop" := 'repetition';
1866 ELSE
1867 "output_row"."loop" := 'intermediate';
1868 END IF;
1869 ELSIF "output_row"."member_id" = "loop_member_id_v" THEN
1870 "output_row"."loop" := 'first';
1871 "loop_v" := TRUE;
1872 END IF;
1873 IF "area_id_p" ISNULL AND "issue_id_p" ISNULL THEN
1874 "output_row"."participation" := NULL;
1875 END IF;
1876 RETURN NEXT "output_row";
1877 "i" := "i" + 1;
1878 END LOOP;
1879 RETURN;
1880 END;
1881 $$;
1883 COMMENT ON FUNCTION "delegation_chain"
1884 ( "member"."id"%TYPE,
1885 "area"."id"%TYPE,
1886 "issue"."id"%TYPE,
1887 "member"."id"%TYPE )
1888 IS 'Helper function for frontends to display delegation chains; Not part of internal voting logic';
1890 CREATE FUNCTION "delegation_chain"
1891 ( "member_id_p" "member"."id"%TYPE,
1892 "area_id_p" "area"."id"%TYPE,
1893 "issue_id_p" "issue"."id"%TYPE )
1894 RETURNS SETOF "delegation_chain_row"
1895 LANGUAGE 'plpgsql' STABLE AS $$
1896 DECLARE
1897 "result_row" "delegation_chain_row";
1898 BEGIN
1899 FOR "result_row" IN
1900 SELECT * FROM "delegation_chain"(
1901 "member_id_p", "area_id_p", "issue_id_p", NULL
1903 LOOP
1904 RETURN NEXT "result_row";
1905 END LOOP;
1906 RETURN;
1907 END;
1908 $$;
1910 COMMENT ON FUNCTION "delegation_chain"
1911 ( "member"."id"%TYPE,
1912 "area"."id"%TYPE,
1913 "issue"."id"%TYPE )
1914 IS 'Shortcut for "delegation_chain"(...) function where 4th parameter is null';
1918 ------------------------------
1919 -- Comparison by vote count --
1920 ------------------------------
1922 CREATE FUNCTION "vote_ratio"
1923 ( "positive_votes_p" "initiative"."positive_votes"%TYPE,
1924 "negative_votes_p" "initiative"."negative_votes"%TYPE )
1925 RETURNS FLOAT8
1926 LANGUAGE 'plpgsql' STABLE AS $$
1927 BEGIN
1928 IF "positive_votes_p" > 0 AND "negative_votes_p" > 0 THEN
1929 RETURN
1930 "positive_votes_p"::FLOAT8 /
1931 ("positive_votes_p" + "negative_votes_p")::FLOAT8;
1932 ELSIF "positive_votes_p" > 0 THEN
1933 RETURN "positive_votes_p";
1934 ELSIF "negative_votes_p" > 0 THEN
1935 RETURN 1 - "negative_votes_p";
1936 ELSE
1937 RETURN 0.5;
1938 END IF;
1939 END;
1940 $$;
1942 COMMENT ON FUNCTION "vote_ratio"
1943 ( "initiative"."positive_votes"%TYPE,
1944 "initiative"."negative_votes"%TYPE )
1945 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.';
1949 ------------------------------------------------
1950 -- Locking for snapshots and voting procedure --
1951 ------------------------------------------------
1954 CREATE FUNCTION "share_row_lock_issue_trigger"()
1955 RETURNS TRIGGER
1956 LANGUAGE 'plpgsql' VOLATILE AS $$
1957 BEGIN
1958 IF TG_OP = 'UPDATE' OR TG_OP = 'DELETE' THEN
1959 PERFORM NULL FROM "issue" WHERE "id" = OLD."issue_id" FOR SHARE;
1960 END IF;
1961 IF TG_OP = 'INSERT' OR TG_OP = 'UPDATE' THEN
1962 PERFORM NULL FROM "issue" WHERE "id" = NEW."issue_id" FOR SHARE;
1963 RETURN NEW;
1964 ELSE
1965 RETURN OLD;
1966 END IF;
1967 END;
1968 $$;
1970 COMMENT ON FUNCTION "share_row_lock_issue_trigger"() IS 'Implementation of triggers "share_row_lock_issue" on multiple tables';
1973 CREATE FUNCTION "share_row_lock_issue_via_initiative_trigger"()
1974 RETURNS TRIGGER
1975 LANGUAGE 'plpgsql' VOLATILE AS $$
1976 BEGIN
1977 IF TG_OP = 'UPDATE' OR TG_OP = 'DELETE' THEN
1978 PERFORM NULL FROM "issue"
1979 JOIN "initiative" ON "issue"."id" = "initiative"."issue_id"
1980 WHERE "initiative"."id" = OLD."initiative_id"
1981 FOR SHARE OF "issue";
1982 END IF;
1983 IF TG_OP = 'INSERT' OR TG_OP = 'UPDATE' THEN
1984 PERFORM NULL FROM "issue"
1985 JOIN "initiative" ON "issue"."id" = "initiative"."issue_id"
1986 WHERE "initiative"."id" = NEW."initiative_id"
1987 FOR SHARE OF "issue";
1988 RETURN NEW;
1989 ELSE
1990 RETURN OLD;
1991 END IF;
1992 END;
1993 $$;
1995 COMMENT ON FUNCTION "share_row_lock_issue_trigger"() IS 'Implementation of trigger "share_row_lock_issue_via_initiative" on table "opinion"';
1998 CREATE TRIGGER "share_row_lock_issue"
1999 BEFORE INSERT OR UPDATE OR DELETE ON "initiative"
2000 FOR EACH ROW EXECUTE PROCEDURE
2001 "share_row_lock_issue_trigger"();
2003 CREATE TRIGGER "share_row_lock_issue"
2004 BEFORE INSERT OR UPDATE OR DELETE ON "interest"
2005 FOR EACH ROW EXECUTE PROCEDURE
2006 "share_row_lock_issue_trigger"();
2008 CREATE TRIGGER "share_row_lock_issue"
2009 BEFORE INSERT OR UPDATE OR DELETE ON "supporter"
2010 FOR EACH ROW EXECUTE PROCEDURE
2011 "share_row_lock_issue_trigger"();
2013 CREATE TRIGGER "share_row_lock_issue_via_initiative"
2014 BEFORE INSERT OR UPDATE OR DELETE ON "opinion"
2015 FOR EACH ROW EXECUTE PROCEDURE
2016 "share_row_lock_issue_via_initiative_trigger"();
2018 CREATE TRIGGER "share_row_lock_issue"
2019 BEFORE INSERT OR UPDATE OR DELETE ON "direct_voter"
2020 FOR EACH ROW EXECUTE PROCEDURE
2021 "share_row_lock_issue_trigger"();
2023 CREATE TRIGGER "share_row_lock_issue"
2024 BEFORE INSERT OR UPDATE OR DELETE ON "delegating_voter"
2025 FOR EACH ROW EXECUTE PROCEDURE
2026 "share_row_lock_issue_trigger"();
2028 CREATE TRIGGER "share_row_lock_issue"
2029 BEFORE INSERT OR UPDATE OR DELETE ON "vote"
2030 FOR EACH ROW EXECUTE PROCEDURE
2031 "share_row_lock_issue_trigger"();
2033 COMMENT ON TRIGGER "share_row_lock_issue" ON "initiative" IS 'See "lock_issue" function';
2034 COMMENT ON TRIGGER "share_row_lock_issue" ON "interest" IS 'See "lock_issue" function';
2035 COMMENT ON TRIGGER "share_row_lock_issue" ON "supporter" IS 'See "lock_issue" function';
2036 COMMENT ON TRIGGER "share_row_lock_issue_via_initiative" ON "opinion" IS 'See "lock_issue" function';
2037 COMMENT ON TRIGGER "share_row_lock_issue" ON "direct_voter" IS 'See "lock_issue" function';
2038 COMMENT ON TRIGGER "share_row_lock_issue" ON "delegating_voter" IS 'See "lock_issue" function';
2039 COMMENT ON TRIGGER "share_row_lock_issue" ON "vote" IS 'See "lock_issue" function';
2042 CREATE FUNCTION "lock_issue"
2043 ( "issue_id_p" "issue"."id"%TYPE )
2044 RETURNS VOID
2045 LANGUAGE 'plpgsql' VOLATILE AS $$
2046 BEGIN
2047 LOCK TABLE "member" IN SHARE MODE;
2048 LOCK TABLE "membership" IN SHARE MODE;
2049 LOCK TABLE "policy" IN SHARE MODE;
2050 PERFORM NULL FROM "issue" WHERE "id" = "issue_id_p" FOR UPDATE;
2051 -- NOTE: The row-level exclusive lock in combination with the
2052 -- share_row_lock_issue(_via_initiative)_trigger functions (which
2053 -- acquire a row-level share lock on the issue) ensure that no data
2054 -- is changed, which could affect calculation of snapshots or
2055 -- counting of votes. Table "delegation" must be table-level-locked,
2056 -- as it also contains issue- and global-scope delegations.
2057 LOCK TABLE "delegation" IN SHARE MODE;
2058 LOCK TABLE "direct_population_snapshot" IN EXCLUSIVE MODE;
2059 LOCK TABLE "delegating_population_snapshot" IN EXCLUSIVE MODE;
2060 LOCK TABLE "direct_interest_snapshot" IN EXCLUSIVE MODE;
2061 LOCK TABLE "delegating_interest_snapshot" IN EXCLUSIVE MODE;
2062 LOCK TABLE "direct_supporter_snapshot" IN EXCLUSIVE MODE;
2063 RETURN;
2064 END;
2065 $$;
2067 COMMENT ON FUNCTION "lock_issue"
2068 ( "issue"."id"%TYPE )
2069 IS 'Locks the issue and all other data which is used for calculating snapshots or counting votes.';
2073 -------------------------------
2074 -- Materialize member counts --
2075 -------------------------------
2077 CREATE FUNCTION "calculate_member_counts"()
2078 RETURNS VOID
2079 LANGUAGE 'plpgsql' VOLATILE AS $$
2080 BEGIN
2081 LOCK TABLE "member" IN SHARE MODE;
2082 LOCK TABLE "member_count" IN EXCLUSIVE MODE;
2083 LOCK TABLE "area" IN EXCLUSIVE MODE;
2084 LOCK TABLE "membership" IN SHARE MODE;
2085 DELETE FROM "member_count";
2086 INSERT INTO "member_count" ("total_count")
2087 SELECT "total_count" FROM "member_count_view";
2088 UPDATE "area" SET
2089 "direct_member_count" = "view"."direct_member_count",
2090 "member_weight" = "view"."member_weight",
2091 "autoreject_weight" = "view"."autoreject_weight"
2092 FROM "area_member_count" AS "view"
2093 WHERE "view"."area_id" = "area"."id";
2094 RETURN;
2095 END;
2096 $$;
2098 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"';
2102 ------------------------------
2103 -- Calculation of snapshots --
2104 ------------------------------
2106 CREATE FUNCTION "weight_of_added_delegations_for_population_snapshot"
2107 ( "issue_id_p" "issue"."id"%TYPE,
2108 "member_id_p" "member"."id"%TYPE,
2109 "delegate_member_ids_p" "delegating_population_snapshot"."delegate_member_ids"%TYPE )
2110 RETURNS "direct_population_snapshot"."weight"%TYPE
2111 LANGUAGE 'plpgsql' VOLATILE AS $$
2112 DECLARE
2113 "issue_delegation_row" "issue_delegation"%ROWTYPE;
2114 "delegate_member_ids_v" "delegating_population_snapshot"."delegate_member_ids"%TYPE;
2115 "weight_v" INT4;
2116 "sub_weight_v" INT4;
2117 BEGIN
2118 "weight_v" := 0;
2119 FOR "issue_delegation_row" IN
2120 SELECT * FROM "issue_delegation"
2121 WHERE "trustee_id" = "member_id_p"
2122 AND "issue_id" = "issue_id_p"
2123 LOOP
2124 IF NOT EXISTS (
2125 SELECT NULL FROM "direct_population_snapshot"
2126 WHERE "issue_id" = "issue_id_p"
2127 AND "event" = 'periodic'
2128 AND "member_id" = "issue_delegation_row"."truster_id"
2129 ) AND NOT EXISTS (
2130 SELECT NULL FROM "delegating_population_snapshot"
2131 WHERE "issue_id" = "issue_id_p"
2132 AND "event" = 'periodic'
2133 AND "member_id" = "issue_delegation_row"."truster_id"
2134 ) THEN
2135 "delegate_member_ids_v" :=
2136 "member_id_p" || "delegate_member_ids_p";
2137 INSERT INTO "delegating_population_snapshot" (
2138 "issue_id",
2139 "event",
2140 "member_id",
2141 "scope",
2142 "delegate_member_ids"
2143 ) VALUES (
2144 "issue_id_p",
2145 'periodic',
2146 "issue_delegation_row"."truster_id",
2147 "issue_delegation_row"."scope",
2148 "delegate_member_ids_v"
2149 );
2150 "sub_weight_v" := 1 +
2151 "weight_of_added_delegations_for_population_snapshot"(
2152 "issue_id_p",
2153 "issue_delegation_row"."truster_id",
2154 "delegate_member_ids_v"
2155 );
2156 UPDATE "delegating_population_snapshot"
2157 SET "weight" = "sub_weight_v"
2158 WHERE "issue_id" = "issue_id_p"
2159 AND "event" = 'periodic'
2160 AND "member_id" = "issue_delegation_row"."truster_id";
2161 "weight_v" := "weight_v" + "sub_weight_v";
2162 END IF;
2163 END LOOP;
2164 RETURN "weight_v";
2165 END;
2166 $$;
2168 COMMENT ON FUNCTION "weight_of_added_delegations_for_population_snapshot"
2169 ( "issue"."id"%TYPE,
2170 "member"."id"%TYPE,
2171 "delegating_population_snapshot"."delegate_member_ids"%TYPE )
2172 IS 'Helper function for "create_population_snapshot" function';
2175 CREATE FUNCTION "create_population_snapshot"
2176 ( "issue_id_p" "issue"."id"%TYPE )
2177 RETURNS VOID
2178 LANGUAGE 'plpgsql' VOLATILE AS $$
2179 DECLARE
2180 "member_id_v" "member"."id"%TYPE;
2181 BEGIN
2182 DELETE FROM "direct_population_snapshot"
2183 WHERE "issue_id" = "issue_id_p"
2184 AND "event" = 'periodic';
2185 DELETE FROM "delegating_population_snapshot"
2186 WHERE "issue_id" = "issue_id_p"
2187 AND "event" = 'periodic';
2188 INSERT INTO "direct_population_snapshot"
2189 ("issue_id", "event", "member_id")
2190 SELECT
2191 "issue_id_p" AS "issue_id",
2192 'periodic'::"snapshot_event" AS "event",
2193 "member"."id" AS "member_id"
2194 FROM "issue"
2195 JOIN "area" ON "issue"."area_id" = "area"."id"
2196 JOIN "membership" ON "area"."id" = "membership"."area_id"
2197 JOIN "member" ON "membership"."member_id" = "member"."id"
2198 WHERE "issue"."id" = "issue_id_p"
2199 AND "member"."active"
2200 UNION
2201 SELECT
2202 "issue_id_p" AS "issue_id",
2203 'periodic'::"snapshot_event" AS "event",
2204 "member"."id" AS "member_id"
2205 FROM "interest" JOIN "member"
2206 ON "interest"."member_id" = "member"."id"
2207 WHERE "interest"."issue_id" = "issue_id_p"
2208 AND "member"."active";
2209 FOR "member_id_v" IN
2210 SELECT "member_id" FROM "direct_population_snapshot"
2211 WHERE "issue_id" = "issue_id_p"
2212 AND "event" = 'periodic'
2213 LOOP
2214 UPDATE "direct_population_snapshot" SET
2215 "weight" = 1 +
2216 "weight_of_added_delegations_for_population_snapshot"(
2217 "issue_id_p",
2218 "member_id_v",
2219 '{}'
2221 WHERE "issue_id" = "issue_id_p"
2222 AND "event" = 'periodic'
2223 AND "member_id" = "member_id_v";
2224 END LOOP;
2225 RETURN;
2226 END;
2227 $$;
2229 COMMENT ON FUNCTION "create_population_snapshot"
2230 ( "issue"."id"%TYPE )
2231 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.';
2234 CREATE FUNCTION "weight_of_added_delegations_for_interest_snapshot"
2235 ( "issue_id_p" "issue"."id"%TYPE,
2236 "member_id_p" "member"."id"%TYPE,
2237 "delegate_member_ids_p" "delegating_interest_snapshot"."delegate_member_ids"%TYPE )
2238 RETURNS "direct_interest_snapshot"."weight"%TYPE
2239 LANGUAGE 'plpgsql' VOLATILE AS $$
2240 DECLARE
2241 "issue_delegation_row" "issue_delegation"%ROWTYPE;
2242 "delegate_member_ids_v" "delegating_interest_snapshot"."delegate_member_ids"%TYPE;
2243 "weight_v" INT4;
2244 "sub_weight_v" INT4;
2245 BEGIN
2246 "weight_v" := 0;
2247 FOR "issue_delegation_row" IN
2248 SELECT * FROM "issue_delegation"
2249 WHERE "trustee_id" = "member_id_p"
2250 AND "issue_id" = "issue_id_p"
2251 LOOP
2252 IF NOT EXISTS (
2253 SELECT NULL FROM "direct_interest_snapshot"
2254 WHERE "issue_id" = "issue_id_p"
2255 AND "event" = 'periodic'
2256 AND "member_id" = "issue_delegation_row"."truster_id"
2257 ) AND NOT EXISTS (
2258 SELECT NULL FROM "delegating_interest_snapshot"
2259 WHERE "issue_id" = "issue_id_p"
2260 AND "event" = 'periodic'
2261 AND "member_id" = "issue_delegation_row"."truster_id"
2262 ) THEN
2263 "delegate_member_ids_v" :=
2264 "member_id_p" || "delegate_member_ids_p";
2265 INSERT INTO "delegating_interest_snapshot" (
2266 "issue_id",
2267 "event",
2268 "member_id",
2269 "scope",
2270 "delegate_member_ids"
2271 ) VALUES (
2272 "issue_id_p",
2273 'periodic',
2274 "issue_delegation_row"."truster_id",
2275 "issue_delegation_row"."scope",
2276 "delegate_member_ids_v"
2277 );
2278 "sub_weight_v" := 1 +
2279 "weight_of_added_delegations_for_interest_snapshot"(
2280 "issue_id_p",
2281 "issue_delegation_row"."truster_id",
2282 "delegate_member_ids_v"
2283 );
2284 UPDATE "delegating_interest_snapshot"
2285 SET "weight" = "sub_weight_v"
2286 WHERE "issue_id" = "issue_id_p"
2287 AND "event" = 'periodic'
2288 AND "member_id" = "issue_delegation_row"."truster_id";
2289 "weight_v" := "weight_v" + "sub_weight_v";
2290 END IF;
2291 END LOOP;
2292 RETURN "weight_v";
2293 END;
2294 $$;
2296 COMMENT ON FUNCTION "weight_of_added_delegations_for_interest_snapshot"
2297 ( "issue"."id"%TYPE,
2298 "member"."id"%TYPE,
2299 "delegating_interest_snapshot"."delegate_member_ids"%TYPE )
2300 IS 'Helper function for "create_interest_snapshot" function';
2303 CREATE FUNCTION "create_interest_snapshot"
2304 ( "issue_id_p" "issue"."id"%TYPE )
2305 RETURNS VOID
2306 LANGUAGE 'plpgsql' VOLATILE AS $$
2307 DECLARE
2308 "member_id_v" "member"."id"%TYPE;
2309 BEGIN
2310 DELETE FROM "direct_interest_snapshot"
2311 WHERE "issue_id" = "issue_id_p"
2312 AND "event" = 'periodic';
2313 DELETE FROM "delegating_interest_snapshot"
2314 WHERE "issue_id" = "issue_id_p"
2315 AND "event" = 'periodic';
2316 DELETE FROM "direct_supporter_snapshot"
2317 WHERE "issue_id" = "issue_id_p"
2318 AND "event" = 'periodic';
2319 INSERT INTO "direct_interest_snapshot"
2320 ("issue_id", "event", "member_id", "voting_requested")
2321 SELECT
2322 "issue_id_p" AS "issue_id",
2323 'periodic' AS "event",
2324 "member"."id" AS "member_id",
2325 "interest"."voting_requested"
2326 FROM "interest" JOIN "member"
2327 ON "interest"."member_id" = "member"."id"
2328 WHERE "interest"."issue_id" = "issue_id_p"
2329 AND "member"."active";
2330 FOR "member_id_v" IN
2331 SELECT "member_id" FROM "direct_interest_snapshot"
2332 WHERE "issue_id" = "issue_id_p"
2333 AND "event" = 'periodic'
2334 LOOP
2335 UPDATE "direct_interest_snapshot" SET
2336 "weight" = 1 +
2337 "weight_of_added_delegations_for_interest_snapshot"(
2338 "issue_id_p",
2339 "member_id_v",
2340 '{}'
2342 WHERE "issue_id" = "issue_id_p"
2343 AND "event" = 'periodic'
2344 AND "member_id" = "member_id_v";
2345 END LOOP;
2346 INSERT INTO "direct_supporter_snapshot"
2347 ( "issue_id", "initiative_id", "event", "member_id",
2348 "informed", "satisfied" )
2349 SELECT
2350 "issue_id_p" AS "issue_id",
2351 "initiative"."id" AS "initiative_id",
2352 'periodic' AS "event",
2353 "member"."id" AS "member_id",
2354 "supporter"."draft_id" = "current_draft"."id" AS "informed",
2355 NOT EXISTS (
2356 SELECT NULL FROM "critical_opinion"
2357 WHERE "initiative_id" = "initiative"."id"
2358 AND "member_id" = "member"."id"
2359 ) AS "satisfied"
2360 FROM "supporter"
2361 JOIN "member"
2362 ON "supporter"."member_id" = "member"."id"
2363 JOIN "initiative"
2364 ON "supporter"."initiative_id" = "initiative"."id"
2365 JOIN "current_draft"
2366 ON "initiative"."id" = "current_draft"."initiative_id"
2367 JOIN "direct_interest_snapshot"
2368 ON "member"."id" = "direct_interest_snapshot"."member_id"
2369 AND "initiative"."issue_id" = "direct_interest_snapshot"."issue_id"
2370 AND "event" = 'periodic'
2371 WHERE "member"."active"
2372 AND "initiative"."issue_id" = "issue_id_p";
2373 RETURN;
2374 END;
2375 $$;
2377 COMMENT ON FUNCTION "create_interest_snapshot"
2378 ( "issue"."id"%TYPE )
2379 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.';
2382 CREATE FUNCTION "create_snapshot"
2383 ( "issue_id_p" "issue"."id"%TYPE )
2384 RETURNS VOID
2385 LANGUAGE 'plpgsql' VOLATILE AS $$
2386 DECLARE
2387 "initiative_id_v" "initiative"."id"%TYPE;
2388 "suggestion_id_v" "suggestion"."id"%TYPE;
2389 BEGIN
2390 PERFORM "lock_issue"("issue_id_p");
2391 PERFORM "create_population_snapshot"("issue_id_p");
2392 PERFORM "create_interest_snapshot"("issue_id_p");
2393 UPDATE "issue" SET
2394 "snapshot" = now(),
2395 "latest_snapshot_event" = 'periodic',
2396 "population" = (
2397 SELECT coalesce(sum("weight"), 0)
2398 FROM "direct_population_snapshot"
2399 WHERE "issue_id" = "issue_id_p"
2400 AND "event" = 'periodic'
2401 ),
2402 "vote_now" = (
2403 SELECT coalesce(sum("weight"), 0)
2404 FROM "direct_interest_snapshot"
2405 WHERE "issue_id" = "issue_id_p"
2406 AND "event" = 'periodic'
2407 AND "voting_requested" = TRUE
2408 ),
2409 "vote_later" = (
2410 SELECT coalesce(sum("weight"), 0)
2411 FROM "direct_interest_snapshot"
2412 WHERE "issue_id" = "issue_id_p"
2413 AND "event" = 'periodic'
2414 AND "voting_requested" = FALSE
2416 WHERE "id" = "issue_id_p";
2417 FOR "initiative_id_v" IN
2418 SELECT "id" FROM "initiative" WHERE "issue_id" = "issue_id_p"
2419 LOOP
2420 UPDATE "initiative" SET
2421 "supporter_count" = (
2422 SELECT coalesce(sum("di"."weight"), 0)
2423 FROM "direct_interest_snapshot" AS "di"
2424 JOIN "direct_supporter_snapshot" AS "ds"
2425 ON "di"."member_id" = "ds"."member_id"
2426 WHERE "di"."issue_id" = "issue_id_p"
2427 AND "di"."event" = 'periodic'
2428 AND "ds"."initiative_id" = "initiative_id_v"
2429 AND "ds"."event" = 'periodic'
2430 ),
2431 "informed_supporter_count" = (
2432 SELECT coalesce(sum("di"."weight"), 0)
2433 FROM "direct_interest_snapshot" AS "di"
2434 JOIN "direct_supporter_snapshot" AS "ds"
2435 ON "di"."member_id" = "ds"."member_id"
2436 WHERE "di"."issue_id" = "issue_id_p"
2437 AND "di"."event" = 'periodic'
2438 AND "ds"."initiative_id" = "initiative_id_v"
2439 AND "ds"."event" = 'periodic'
2440 AND "ds"."informed"
2441 ),
2442 "satisfied_supporter_count" = (
2443 SELECT coalesce(sum("di"."weight"), 0)
2444 FROM "direct_interest_snapshot" AS "di"
2445 JOIN "direct_supporter_snapshot" AS "ds"
2446 ON "di"."member_id" = "ds"."member_id"
2447 WHERE "di"."issue_id" = "issue_id_p"
2448 AND "di"."event" = 'periodic'
2449 AND "ds"."initiative_id" = "initiative_id_v"
2450 AND "ds"."event" = 'periodic'
2451 AND "ds"."satisfied"
2452 ),
2453 "satisfied_informed_supporter_count" = (
2454 SELECT coalesce(sum("di"."weight"), 0)
2455 FROM "direct_interest_snapshot" AS "di"
2456 JOIN "direct_supporter_snapshot" AS "ds"
2457 ON "di"."member_id" = "ds"."member_id"
2458 WHERE "di"."issue_id" = "issue_id_p"
2459 AND "di"."event" = 'periodic'
2460 AND "ds"."initiative_id" = "initiative_id_v"
2461 AND "ds"."event" = 'periodic'
2462 AND "ds"."informed"
2463 AND "ds"."satisfied"
2465 WHERE "id" = "initiative_id_v";
2466 FOR "suggestion_id_v" IN
2467 SELECT "id" FROM "suggestion"
2468 WHERE "initiative_id" = "initiative_id_v"
2469 LOOP
2470 UPDATE "suggestion" SET
2471 "minus2_unfulfilled_count" = (
2472 SELECT coalesce(sum("snapshot"."weight"), 0)
2473 FROM "issue" CROSS JOIN "opinion"
2474 JOIN "direct_interest_snapshot" AS "snapshot"
2475 ON "snapshot"."issue_id" = "issue"."id"
2476 AND "snapshot"."event" = "issue"."latest_snapshot_event"
2477 AND "snapshot"."member_id" = "opinion"."member_id"
2478 WHERE "issue"."id" = "issue_id_p"
2479 AND "opinion"."suggestion_id" = "suggestion_id_v"
2480 AND "opinion"."degree" = -2
2481 AND "opinion"."fulfilled" = FALSE
2482 ),
2483 "minus2_fulfilled_count" = (
2484 SELECT coalesce(sum("snapshot"."weight"), 0)
2485 FROM "issue" CROSS JOIN "opinion"
2486 JOIN "direct_interest_snapshot" AS "snapshot"
2487 ON "snapshot"."issue_id" = "issue"."id"
2488 AND "snapshot"."event" = "issue"."latest_snapshot_event"
2489 AND "snapshot"."member_id" = "opinion"."member_id"
2490 WHERE "issue"."id" = "issue_id_p"
2491 AND "opinion"."suggestion_id" = "suggestion_id_v"
2492 AND "opinion"."degree" = -2
2493 AND "opinion"."fulfilled" = TRUE
2494 ),
2495 "minus1_unfulfilled_count" = (
2496 SELECT coalesce(sum("snapshot"."weight"), 0)
2497 FROM "issue" CROSS JOIN "opinion"
2498 JOIN "direct_interest_snapshot" AS "snapshot"
2499 ON "snapshot"."issue_id" = "issue"."id"
2500 AND "snapshot"."event" = "issue"."latest_snapshot_event"
2501 AND "snapshot"."member_id" = "opinion"."member_id"
2502 WHERE "issue"."id" = "issue_id_p"
2503 AND "opinion"."suggestion_id" = "suggestion_id_v"
2504 AND "opinion"."degree" = -1
2505 AND "opinion"."fulfilled" = FALSE
2506 ),
2507 "minus1_fulfilled_count" = (
2508 SELECT coalesce(sum("snapshot"."weight"), 0)
2509 FROM "issue" CROSS JOIN "opinion"
2510 JOIN "direct_interest_snapshot" AS "snapshot"
2511 ON "snapshot"."issue_id" = "issue"."id"
2512 AND "snapshot"."event" = "issue"."latest_snapshot_event"
2513 AND "snapshot"."member_id" = "opinion"."member_id"
2514 WHERE "issue"."id" = "issue_id_p"
2515 AND "opinion"."suggestion_id" = "suggestion_id_v"
2516 AND "opinion"."degree" = -1
2517 AND "opinion"."fulfilled" = TRUE
2518 ),
2519 "plus1_unfulfilled_count" = (
2520 SELECT coalesce(sum("snapshot"."weight"), 0)
2521 FROM "issue" CROSS JOIN "opinion"
2522 JOIN "direct_interest_snapshot" AS "snapshot"
2523 ON "snapshot"."issue_id" = "issue"."id"
2524 AND "snapshot"."event" = "issue"."latest_snapshot_event"
2525 AND "snapshot"."member_id" = "opinion"."member_id"
2526 WHERE "issue"."id" = "issue_id_p"
2527 AND "opinion"."suggestion_id" = "suggestion_id_v"
2528 AND "opinion"."degree" = 1
2529 AND "opinion"."fulfilled" = FALSE
2530 ),
2531 "plus1_fulfilled_count" = (
2532 SELECT coalesce(sum("snapshot"."weight"), 0)
2533 FROM "issue" CROSS JOIN "opinion"
2534 JOIN "direct_interest_snapshot" AS "snapshot"
2535 ON "snapshot"."issue_id" = "issue"."id"
2536 AND "snapshot"."event" = "issue"."latest_snapshot_event"
2537 AND "snapshot"."member_id" = "opinion"."member_id"
2538 WHERE "issue"."id" = "issue_id_p"
2539 AND "opinion"."suggestion_id" = "suggestion_id_v"
2540 AND "opinion"."degree" = 1
2541 AND "opinion"."fulfilled" = TRUE
2542 ),
2543 "plus2_unfulfilled_count" = (
2544 SELECT coalesce(sum("snapshot"."weight"), 0)
2545 FROM "issue" CROSS JOIN "opinion"
2546 JOIN "direct_interest_snapshot" AS "snapshot"
2547 ON "snapshot"."issue_id" = "issue"."id"
2548 AND "snapshot"."event" = "issue"."latest_snapshot_event"
2549 AND "snapshot"."member_id" = "opinion"."member_id"
2550 WHERE "issue"."id" = "issue_id_p"
2551 AND "opinion"."suggestion_id" = "suggestion_id_v"
2552 AND "opinion"."degree" = 2
2553 AND "opinion"."fulfilled" = FALSE
2554 ),
2555 "plus2_fulfilled_count" = (
2556 SELECT coalesce(sum("snapshot"."weight"), 0)
2557 FROM "issue" CROSS JOIN "opinion"
2558 JOIN "direct_interest_snapshot" AS "snapshot"
2559 ON "snapshot"."issue_id" = "issue"."id"
2560 AND "snapshot"."event" = "issue"."latest_snapshot_event"
2561 AND "snapshot"."member_id" = "opinion"."member_id"
2562 WHERE "issue"."id" = "issue_id_p"
2563 AND "opinion"."suggestion_id" = "suggestion_id_v"
2564 AND "opinion"."degree" = 2
2565 AND "opinion"."fulfilled" = TRUE
2567 WHERE "suggestion"."id" = "suggestion_id_v";
2568 END LOOP;
2569 END LOOP;
2570 RETURN;
2571 END;
2572 $$;
2574 COMMENT ON FUNCTION "create_snapshot"
2575 ( "issue"."id"%TYPE )
2576 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.';
2579 CREATE FUNCTION "set_snapshot_event"
2580 ( "issue_id_p" "issue"."id"%TYPE,
2581 "event_p" "snapshot_event" )
2582 RETURNS VOID
2583 LANGUAGE 'plpgsql' VOLATILE AS $$
2584 DECLARE
2585 "event_v" "issue"."latest_snapshot_event"%TYPE;
2586 BEGIN
2587 SELECT "latest_snapshot_event" INTO "event_v" FROM "issue"
2588 WHERE "id" = "issue_id_p" FOR UPDATE;
2589 UPDATE "issue" SET "latest_snapshot_event" = "event_p"
2590 WHERE "id" = "issue_id_p";
2591 UPDATE "direct_population_snapshot" SET "event" = "event_p"
2592 WHERE "issue_id" = "issue_id_p" AND "event" = "event_v";
2593 UPDATE "delegating_population_snapshot" SET "event" = "event_p"
2594 WHERE "issue_id" = "issue_id_p" AND "event" = "event_v";
2595 UPDATE "direct_interest_snapshot" SET "event" = "event_p"
2596 WHERE "issue_id" = "issue_id_p" AND "event" = "event_v";
2597 UPDATE "delegating_interest_snapshot" SET "event" = "event_p"
2598 WHERE "issue_id" = "issue_id_p" AND "event" = "event_v";
2599 UPDATE "direct_supporter_snapshot" SET "event" = "event_p"
2600 WHERE "issue_id" = "issue_id_p" AND "event" = "event_v";
2601 RETURN;
2602 END;
2603 $$;
2605 COMMENT ON FUNCTION "set_snapshot_event"
2606 ( "issue"."id"%TYPE,
2607 "snapshot_event" )
2608 IS 'Change "event" attribute of the previous ''periodic'' snapshot';
2612 ---------------------
2613 -- Freezing issues --
2614 ---------------------
2616 CREATE FUNCTION "freeze_after_snapshot"
2617 ( "issue_id_p" "issue"."id"%TYPE )
2618 RETURNS VOID
2619 LANGUAGE 'plpgsql' VOLATILE AS $$
2620 DECLARE
2621 "issue_row" "issue"%ROWTYPE;
2622 "policy_row" "policy"%ROWTYPE;
2623 "initiative_row" "initiative"%ROWTYPE;
2624 BEGIN
2625 SELECT * INTO "issue_row" FROM "issue" WHERE "id" = "issue_id_p";
2626 SELECT * INTO "policy_row"
2627 FROM "policy" WHERE "id" = "issue_row"."policy_id";
2628 PERFORM "set_snapshot_event"("issue_id_p", 'full_freeze');
2629 UPDATE "issue" SET
2630 "accepted" = coalesce("accepted", now()),
2631 "half_frozen" = coalesce("half_frozen", now()),
2632 "fully_frozen" = now()
2633 WHERE "id" = "issue_id_p";
2634 FOR "initiative_row" IN
2635 SELECT * FROM "initiative"
2636 WHERE "issue_id" = "issue_id_p" AND "revoked" ISNULL
2637 LOOP
2638 IF
2639 "initiative_row"."satisfied_supporter_count" > 0 AND
2640 "initiative_row"."satisfied_supporter_count" *
2641 "policy_row"."initiative_quorum_den" >=
2642 "issue_row"."population" * "policy_row"."initiative_quorum_num"
2643 THEN
2644 UPDATE "initiative" SET "admitted" = TRUE
2645 WHERE "id" = "initiative_row"."id";
2646 ELSE
2647 UPDATE "initiative" SET "admitted" = FALSE
2648 WHERE "id" = "initiative_row"."id";
2649 END IF;
2650 END LOOP;
2651 IF NOT EXISTS (
2652 SELECT NULL FROM "initiative"
2653 WHERE "issue_id" = "issue_id_p" AND "admitted" = TRUE
2654 ) THEN
2655 PERFORM "close_voting"("issue_id_p");
2656 END IF;
2657 RETURN;
2658 END;
2659 $$;
2661 COMMENT ON FUNCTION "freeze_after_snapshot"
2662 ( "issue"."id"%TYPE )
2663 IS 'This function freezes an issue (fully) and starts voting, but must only be called when "create_snapshot" was called in the same transaction.';
2666 CREATE FUNCTION "manual_freeze"("issue_id_p" "issue"."id"%TYPE)
2667 RETURNS VOID
2668 LANGUAGE 'plpgsql' VOLATILE AS $$
2669 DECLARE
2670 "issue_row" "issue"%ROWTYPE;
2671 BEGIN
2672 PERFORM "create_snapshot"("issue_id_p");
2673 PERFORM "freeze_after_snapshot"("issue_id_p");
2674 RETURN;
2675 END;
2676 $$;
2678 COMMENT ON FUNCTION "manual_freeze"
2679 ( "issue"."id"%TYPE )
2680 IS 'Freeze an issue manually (fully) and start voting';
2684 -----------------------
2685 -- Counting of votes --
2686 -----------------------
2689 CREATE FUNCTION "weight_of_added_vote_delegations"
2690 ( "issue_id_p" "issue"."id"%TYPE,
2691 "member_id_p" "member"."id"%TYPE,
2692 "delegate_member_ids_p" "delegating_voter"."delegate_member_ids"%TYPE )
2693 RETURNS "direct_voter"."weight"%TYPE
2694 LANGUAGE 'plpgsql' VOLATILE AS $$
2695 DECLARE
2696 "issue_delegation_row" "issue_delegation"%ROWTYPE;
2697 "delegate_member_ids_v" "delegating_voter"."delegate_member_ids"%TYPE;
2698 "weight_v" INT4;
2699 "sub_weight_v" INT4;
2700 BEGIN
2701 "weight_v" := 0;
2702 FOR "issue_delegation_row" IN
2703 SELECT * FROM "issue_delegation"
2704 WHERE "trustee_id" = "member_id_p"
2705 AND "issue_id" = "issue_id_p"
2706 LOOP
2707 IF NOT EXISTS (
2708 SELECT NULL FROM "direct_voter"
2709 WHERE "member_id" = "issue_delegation_row"."truster_id"
2710 AND "issue_id" = "issue_id_p"
2711 ) AND NOT EXISTS (
2712 SELECT NULL FROM "delegating_voter"
2713 WHERE "member_id" = "issue_delegation_row"."truster_id"
2714 AND "issue_id" = "issue_id_p"
2715 ) THEN
2716 "delegate_member_ids_v" :=
2717 "member_id_p" || "delegate_member_ids_p";
2718 INSERT INTO "delegating_voter" (
2719 "issue_id",
2720 "member_id",
2721 "scope",
2722 "delegate_member_ids"
2723 ) VALUES (
2724 "issue_id_p",
2725 "issue_delegation_row"."truster_id",
2726 "issue_delegation_row"."scope",
2727 "delegate_member_ids_v"
2728 );
2729 "sub_weight_v" := 1 +
2730 "weight_of_added_vote_delegations"(
2731 "issue_id_p",
2732 "issue_delegation_row"."truster_id",
2733 "delegate_member_ids_v"
2734 );
2735 UPDATE "delegating_voter"
2736 SET "weight" = "sub_weight_v"
2737 WHERE "issue_id" = "issue_id_p"
2738 AND "member_id" = "issue_delegation_row"."truster_id";
2739 "weight_v" := "weight_v" + "sub_weight_v";
2740 END IF;
2741 END LOOP;
2742 RETURN "weight_v";
2743 END;
2744 $$;
2746 COMMENT ON FUNCTION "weight_of_added_vote_delegations"
2747 ( "issue"."id"%TYPE,
2748 "member"."id"%TYPE,
2749 "delegating_voter"."delegate_member_ids"%TYPE )
2750 IS 'Helper function for "add_vote_delegations" function';
2753 CREATE FUNCTION "add_vote_delegations"
2754 ( "issue_id_p" "issue"."id"%TYPE )
2755 RETURNS VOID
2756 LANGUAGE 'plpgsql' VOLATILE AS $$
2757 DECLARE
2758 "member_id_v" "member"."id"%TYPE;
2759 BEGIN
2760 FOR "member_id_v" IN
2761 SELECT "member_id" FROM "direct_voter"
2762 WHERE "issue_id" = "issue_id_p"
2763 LOOP
2764 UPDATE "direct_voter" SET
2765 "weight" = "weight" + "weight_of_added_vote_delegations"(
2766 "issue_id_p",
2767 "member_id_v",
2768 '{}'
2770 WHERE "member_id" = "member_id_v"
2771 AND "issue_id" = "issue_id_p";
2772 END LOOP;
2773 RETURN;
2774 END;
2775 $$;
2777 COMMENT ON FUNCTION "add_vote_delegations"
2778 ( "issue_id_p" "issue"."id"%TYPE )
2779 IS 'Helper function for "close_voting" function';
2782 CREATE FUNCTION "close_voting"("issue_id_p" "issue"."id"%TYPE)
2783 RETURNS VOID
2784 LANGUAGE 'plpgsql' VOLATILE AS $$
2785 DECLARE
2786 "issue_row" "issue"%ROWTYPE;
2787 "member_id_v" "member"."id"%TYPE;
2788 BEGIN
2789 PERFORM "lock_issue"("issue_id_p");
2790 SELECT * INTO "issue_row" FROM "issue" WHERE "id" = "issue_id_p";
2791 DELETE FROM "delegating_voter"
2792 WHERE "issue_id" = "issue_id_p";
2793 DELETE FROM "direct_voter"
2794 WHERE "issue_id" = "issue_id_p"
2795 AND "autoreject" = TRUE;
2796 DELETE FROM "direct_voter" USING "member"
2797 WHERE "direct_voter"."member_id" = "member"."id"
2798 AND "direct_voter"."issue_id" = "issue_id_p"
2799 AND "member"."active" = FALSE;
2800 UPDATE "direct_voter" SET "weight" = 1
2801 WHERE "issue_id" = "issue_id_p";
2802 PERFORM "add_vote_delegations"("issue_id_p");
2803 FOR "member_id_v" IN
2804 SELECT "interest"."member_id"
2805 FROM "interest"
2806 LEFT JOIN "direct_voter"
2807 ON "interest"."member_id" = "direct_voter"."member_id"
2808 AND "interest"."issue_id" = "direct_voter"."issue_id"
2809 LEFT JOIN "delegating_voter"
2810 ON "interest"."member_id" = "delegating_voter"."member_id"
2811 AND "interest"."issue_id" = "delegating_voter"."issue_id"
2812 WHERE "interest"."issue_id" = "issue_id_p"
2813 AND "interest"."autoreject" = TRUE
2814 AND "direct_voter"."member_id" ISNULL
2815 AND "delegating_voter"."member_id" ISNULL
2816 UNION SELECT "membership"."member_id"
2817 FROM "membership"
2818 LEFT JOIN "interest"
2819 ON "membership"."member_id" = "interest"."member_id"
2820 AND "interest"."issue_id" = "issue_id_p"
2821 LEFT JOIN "direct_voter"
2822 ON "membership"."member_id" = "direct_voter"."member_id"
2823 AND "direct_voter"."issue_id" = "issue_id_p"
2824 LEFT JOIN "delegating_voter"
2825 ON "membership"."member_id" = "delegating_voter"."member_id"
2826 AND "delegating_voter"."issue_id" = "issue_id_p"
2827 WHERE "membership"."area_id" = "issue_row"."area_id"
2828 AND "membership"."autoreject" = TRUE
2829 AND "interest"."autoreject" ISNULL
2830 AND "direct_voter"."member_id" ISNULL
2831 AND "delegating_voter"."member_id" ISNULL
2832 LOOP
2833 INSERT INTO "direct_voter"
2834 ("member_id", "issue_id", "weight", "autoreject") VALUES
2835 ("member_id_v", "issue_id_p", 1, TRUE);
2836 INSERT INTO "vote" (
2837 "member_id",
2838 "issue_id",
2839 "initiative_id",
2840 "grade"
2841 ) SELECT
2842 "member_id_v" AS "member_id",
2843 "issue_id_p" AS "issue_id",
2844 "id" AS "initiative_id",
2845 -1 AS "grade"
2846 FROM "initiative" WHERE "issue_id" = "issue_id_p";
2847 END LOOP;
2848 PERFORM "add_vote_delegations"("issue_id_p");
2849 UPDATE "issue" SET
2850 "closed" = now(),
2851 "voter_count" = (
2852 SELECT coalesce(sum("weight"), 0)
2853 FROM "direct_voter" WHERE "issue_id" = "issue_id_p"
2855 WHERE "id" = "issue_id_p";
2856 UPDATE "initiative" SET
2857 "positive_votes" = "vote_counts"."positive_votes",
2858 "negative_votes" = "vote_counts"."negative_votes",
2859 "agreed" = CASE WHEN "majority_strict" THEN
2860 "vote_counts"."positive_votes" * "majority_den" >
2861 "majority_num" *
2862 ("vote_counts"."positive_votes"+"vote_counts"."negative_votes")
2863 ELSE
2864 "vote_counts"."positive_votes" * "majority_den" >=
2865 "majority_num" *
2866 ("vote_counts"."positive_votes"+"vote_counts"."negative_votes")
2867 END
2868 FROM
2869 ( SELECT
2870 "initiative"."id" AS "initiative_id",
2871 coalesce(
2872 sum(
2873 CASE WHEN "grade" > 0 THEN "direct_voter"."weight" ELSE 0 END
2874 ),
2876 ) AS "positive_votes",
2877 coalesce(
2878 sum(
2879 CASE WHEN "grade" < 0 THEN "direct_voter"."weight" ELSE 0 END
2880 ),
2882 ) AS "negative_votes"
2883 FROM "initiative"
2884 JOIN "issue" ON "initiative"."issue_id" = "issue"."id"
2885 JOIN "policy" ON "issue"."policy_id" = "policy"."id"
2886 LEFT JOIN "direct_voter"
2887 ON "direct_voter"."issue_id" = "initiative"."issue_id"
2888 LEFT JOIN "vote"
2889 ON "vote"."initiative_id" = "initiative"."id"
2890 AND "vote"."member_id" = "direct_voter"."member_id"
2891 WHERE "initiative"."issue_id" = "issue_id_p"
2892 AND "initiative"."admitted" -- NOTE: NULL case is handled too
2893 GROUP BY "initiative"."id"
2894 ) AS "vote_counts",
2895 "issue",
2896 "policy"
2897 WHERE "vote_counts"."initiative_id" = "initiative"."id"
2898 AND "issue"."id" = "initiative"."issue_id"
2899 AND "policy"."id" = "issue"."policy_id";
2900 -- NOTE: "closed" column of issue must be set at this point
2901 DELETE FROM "battle" WHERE "issue_id" = "issue_id_p";
2902 INSERT INTO "battle" (
2903 "issue_id",
2904 "winning_initiative_id", "losing_initiative_id",
2905 "count"
2906 ) SELECT
2907 "issue_id",
2908 "winning_initiative_id", "losing_initiative_id",
2909 "count"
2910 FROM "battle_view" WHERE "issue_id" = "issue_id_p";
2911 END;
2912 $$;
2914 COMMENT ON FUNCTION "close_voting"
2915 ( "issue"."id"%TYPE )
2916 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.';
2919 CREATE FUNCTION "defeat_strength"
2920 ( "positive_votes_p" INT4, "negative_votes_p" INT4 )
2921 RETURNS INT8
2922 LANGUAGE 'plpgsql' IMMUTABLE AS $$
2923 BEGIN
2924 IF "positive_votes_p" > "negative_votes_p" THEN
2925 RETURN ("positive_votes_p"::INT8 << 31) - "negative_votes_p"::INT8;
2926 ELSIF "positive_votes_p" = "negative_votes_p" THEN
2927 RETURN 0;
2928 ELSE
2929 RETURN -1;
2930 END IF;
2931 END;
2932 $$;
2934 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';
2937 CREATE FUNCTION "array_init_string"("dim_p" INTEGER)
2938 RETURNS TEXT
2939 LANGUAGE 'plpgsql' IMMUTABLE AS $$
2940 DECLARE
2941 "i" INTEGER;
2942 "ary_text_v" TEXT;
2943 BEGIN
2944 IF "dim_p" >= 1 THEN
2945 "ary_text_v" := '{NULL';
2946 "i" := "dim_p";
2947 LOOP
2948 "i" := "i" - 1;
2949 EXIT WHEN "i" = 0;
2950 "ary_text_v" := "ary_text_v" || ',NULL';
2951 END LOOP;
2952 "ary_text_v" := "ary_text_v" || '}';
2953 RETURN "ary_text_v";
2954 ELSE
2955 RAISE EXCEPTION 'Dimension needs to be at least 1.';
2956 END IF;
2957 END;
2958 $$;
2960 COMMENT ON FUNCTION "array_init_string"(INTEGER) IS 'Needed for PostgreSQL < 8.4, due to missing "array_fill" function';
2963 CREATE FUNCTION "square_matrix_init_string"("dim_p" INTEGER)
2964 RETURNS TEXT
2965 LANGUAGE 'plpgsql' IMMUTABLE AS $$
2966 DECLARE
2967 "i" INTEGER;
2968 "row_text_v" TEXT;
2969 "ary_text_v" TEXT;
2970 BEGIN
2971 IF "dim_p" >= 1 THEN
2972 "row_text_v" := '{NULL';
2973 "i" := "dim_p";
2974 LOOP
2975 "i" := "i" - 1;
2976 EXIT WHEN "i" = 0;
2977 "row_text_v" := "row_text_v" || ',NULL';
2978 END LOOP;
2979 "row_text_v" := "row_text_v" || '}';
2980 "ary_text_v" := '{' || "row_text_v";
2981 "i" := "dim_p";
2982 LOOP
2983 "i" := "i" - 1;
2984 EXIT WHEN "i" = 0;
2985 "ary_text_v" := "ary_text_v" || ',' || "row_text_v";
2986 END LOOP;
2987 "ary_text_v" := "ary_text_v" || '}';
2988 RETURN "ary_text_v";
2989 ELSE
2990 RAISE EXCEPTION 'Dimension needs to be at least 1.';
2991 END IF;
2992 END;
2993 $$;
2995 COMMENT ON FUNCTION "square_matrix_init_string"(INTEGER) IS 'Needed for PostgreSQL < 8.4, due to missing "array_fill" function';
2998 CREATE FUNCTION "calculate_ranks"("issue_id_p" "issue"."id"%TYPE)
2999 RETURNS VOID
3000 LANGUAGE 'plpgsql' VOLATILE AS $$
3001 DECLARE
3002 "dimension_v" INTEGER;
3003 "vote_matrix" INT4[][]; -- absolute votes
3004 "matrix" INT8[][]; -- defeat strength / best paths
3005 "i" INTEGER;
3006 "j" INTEGER;
3007 "k" INTEGER;
3008 "battle_row" "battle"%ROWTYPE;
3009 "rank_ary" INT4[];
3010 "rank_v" INT4;
3011 "done_v" INTEGER;
3012 "winners_ary" INTEGER[];
3013 "initiative_id_v" "initiative"."id"%TYPE;
3014 BEGIN
3015 PERFORM NULL FROM "issue" WHERE "id" = "issue_id_p" FOR UPDATE;
3016 SELECT count(1) INTO "dimension_v" FROM "initiative"
3017 WHERE "issue_id" = "issue_id_p" AND "agreed";
3018 IF "dimension_v" = 1 THEN
3019 UPDATE "initiative" SET "rank" = 1
3020 WHERE "issue_id" = "issue_id_p" AND "agreed";
3021 ELSIF "dimension_v" > 1 THEN
3022 -- Create "vote_matrix" with absolute number of votes in pairwise
3023 -- comparison:
3024 "vote_matrix" := "square_matrix_init_string"("dimension_v"); -- TODO: replace by "array_fill" function (PostgreSQL 8.4)
3025 "i" := 1;
3026 "j" := 2;
3027 FOR "battle_row" IN
3028 SELECT * FROM "battle" WHERE "issue_id" = "issue_id_p"
3029 ORDER BY "winning_initiative_id", "losing_initiative_id"
3030 LOOP
3031 "vote_matrix"["i"]["j"] := "battle_row"."count";
3032 IF "j" = "dimension_v" THEN
3033 "i" := "i" + 1;
3034 "j" := 1;
3035 ELSE
3036 "j" := "j" + 1;
3037 IF "j" = "i" THEN
3038 "j" := "j" + 1;
3039 END IF;
3040 END IF;
3041 END LOOP;
3042 IF "i" != "dimension_v" OR "j" != "dimension_v" + 1 THEN
3043 RAISE EXCEPTION 'Wrong battle count (should not happen)';
3044 END IF;
3045 -- Store defeat strengths in "matrix" using "defeat_strength"
3046 -- function:
3047 "matrix" := "square_matrix_init_string"("dimension_v"); -- TODO: replace by "array_fill" function (PostgreSQL 8.4)
3048 "i" := 1;
3049 LOOP
3050 "j" := 1;
3051 LOOP
3052 IF "i" != "j" THEN
3053 "matrix"["i"]["j"] := "defeat_strength"(
3054 "vote_matrix"["i"]["j"],
3055 "vote_matrix"["j"]["i"]
3056 );
3057 END IF;
3058 EXIT WHEN "j" = "dimension_v";
3059 "j" := "j" + 1;
3060 END LOOP;
3061 EXIT WHEN "i" = "dimension_v";
3062 "i" := "i" + 1;
3063 END LOOP;
3064 -- Find best paths:
3065 "i" := 1;
3066 LOOP
3067 "j" := 1;
3068 LOOP
3069 IF "i" != "j" THEN
3070 "k" := 1;
3071 LOOP
3072 IF "i" != "k" AND "j" != "k" THEN
3073 IF "matrix"["j"]["i"] < "matrix"["i"]["k"] THEN
3074 IF "matrix"["j"]["i"] > "matrix"["j"]["k"] THEN
3075 "matrix"["j"]["k"] := "matrix"["j"]["i"];
3076 END IF;
3077 ELSE
3078 IF "matrix"["i"]["k"] > "matrix"["j"]["k"] THEN
3079 "matrix"["j"]["k"] := "matrix"["i"]["k"];
3080 END IF;
3081 END IF;
3082 END IF;
3083 EXIT WHEN "k" = "dimension_v";
3084 "k" := "k" + 1;
3085 END LOOP;
3086 END IF;
3087 EXIT WHEN "j" = "dimension_v";
3088 "j" := "j" + 1;
3089 END LOOP;
3090 EXIT WHEN "i" = "dimension_v";
3091 "i" := "i" + 1;
3092 END LOOP;
3093 -- Determine order of winners:
3094 "rank_ary" := "array_init_string"("dimension_v"); -- TODO: replace by "array_fill" function (PostgreSQL 8.4)
3095 "rank_v" := 1;
3096 "done_v" := 0;
3097 LOOP
3098 "winners_ary" := '{}';
3099 "i" := 1;
3100 LOOP
3101 IF "rank_ary"["i"] ISNULL THEN
3102 "j" := 1;
3103 LOOP
3104 IF
3105 "i" != "j" AND
3106 "rank_ary"["j"] ISNULL AND
3107 "matrix"["j"]["i"] > "matrix"["i"]["j"]
3108 THEN
3109 -- someone else is better
3110 EXIT;
3111 END IF;
3112 IF "j" = "dimension_v" THEN
3113 -- noone is better
3114 "winners_ary" := "winners_ary" || "i";
3115 EXIT;
3116 END IF;
3117 "j" := "j" + 1;
3118 END LOOP;
3119 END IF;
3120 EXIT WHEN "i" = "dimension_v";
3121 "i" := "i" + 1;
3122 END LOOP;
3123 "i" := 1;
3124 LOOP
3125 "rank_ary"["winners_ary"["i"]] := "rank_v";
3126 "done_v" := "done_v" + 1;
3127 EXIT WHEN "i" = array_upper("winners_ary", 1);
3128 "i" := "i" + 1;
3129 END LOOP;
3130 EXIT WHEN "done_v" = "dimension_v";
3131 "rank_v" := "rank_v" + 1;
3132 END LOOP;
3133 -- write preliminary ranks:
3134 "i" := 1;
3135 FOR "initiative_id_v" IN
3136 SELECT "id" FROM "initiative"
3137 WHERE "issue_id" = "issue_id_p" AND "agreed"
3138 ORDER BY "id"
3139 LOOP
3140 UPDATE "initiative" SET "rank" = "rank_ary"["i"]
3141 WHERE "id" = "initiative_id_v";
3142 "i" := "i" + 1;
3143 END LOOP;
3144 IF "i" != "dimension_v" + 1 THEN
3145 RAISE EXCEPTION 'Wrong winner count (should not happen)';
3146 END IF;
3147 -- straighten ranks (start counting with 1, no equal ranks):
3148 "rank_v" := 1;
3149 FOR "initiative_id_v" IN
3150 SELECT "id" FROM "initiative"
3151 WHERE "issue_id" = "issue_id_p" AND "rank" NOTNULL
3152 ORDER BY
3153 "rank",
3154 "vote_ratio"("positive_votes", "negative_votes") DESC,
3155 "id"
3156 LOOP
3157 UPDATE "initiative" SET "rank" = "rank_v"
3158 WHERE "id" = "initiative_id_v";
3159 "rank_v" := "rank_v" + 1;
3160 END LOOP;
3161 END IF;
3162 -- mark issue as finished
3163 UPDATE "issue" SET "ranks_available" = TRUE
3164 WHERE "id" = "issue_id_p";
3165 RETURN;
3166 END;
3167 $$;
3169 COMMENT ON FUNCTION "calculate_ranks"
3170 ( "issue"."id"%TYPE )
3171 IS 'Determine ranking (Votes have to be counted first)';
3175 -----------------------------
3176 -- Automatic state changes --
3177 -----------------------------
3180 CREATE FUNCTION "check_issue"
3181 ( "issue_id_p" "issue"."id"%TYPE )
3182 RETURNS VOID
3183 LANGUAGE 'plpgsql' VOLATILE AS $$
3184 DECLARE
3185 "issue_row" "issue"%ROWTYPE;
3186 "policy_row" "policy"%ROWTYPE;
3187 "voting_requested_v" BOOLEAN;
3188 BEGIN
3189 PERFORM "lock_issue"("issue_id_p");
3190 SELECT * INTO "issue_row" FROM "issue" WHERE "id" = "issue_id_p";
3191 -- only process open issues:
3192 IF "issue_row"."closed" ISNULL THEN
3193 SELECT * INTO "policy_row" FROM "policy"
3194 WHERE "id" = "issue_row"."policy_id";
3195 -- create a snapshot, unless issue is already fully frozen:
3196 IF "issue_row"."fully_frozen" ISNULL THEN
3197 PERFORM "create_snapshot"("issue_id_p");
3198 SELECT * INTO "issue_row" FROM "issue" WHERE "id" = "issue_id_p";
3199 END IF;
3200 -- eventually close or accept issues, which have not been accepted:
3201 IF "issue_row"."accepted" ISNULL THEN
3202 IF EXISTS (
3203 SELECT NULL FROM "initiative"
3204 WHERE "issue_id" = "issue_id_p"
3205 AND "supporter_count" > 0
3206 AND "supporter_count" * "policy_row"."issue_quorum_den"
3207 >= "issue_row"."population" * "policy_row"."issue_quorum_num"
3208 ) THEN
3209 -- accept issues, if supporter count is high enough
3210 PERFORM "set_snapshot_event"("issue_id_p", 'end_of_admission');
3211 "issue_row"."accepted" = now(); -- NOTE: "issue_row" used later
3212 UPDATE "issue" SET "accepted" = "issue_row"."accepted"
3213 WHERE "id" = "issue_row"."id";
3214 ELSIF
3215 now() >= "issue_row"."created" + "issue_row"."admission_time"
3216 THEN
3217 -- close issues, if admission time has expired
3218 PERFORM "set_snapshot_event"("issue_id_p", 'end_of_admission');
3219 UPDATE "issue" SET "closed" = now()
3220 WHERE "id" = "issue_row"."id";
3221 END IF;
3222 END IF;
3223 -- eventually half freeze issues:
3224 IF
3225 -- NOTE: issue can't be closed at this point, if it has been accepted
3226 "issue_row"."accepted" NOTNULL AND
3227 "issue_row"."half_frozen" ISNULL
3228 THEN
3229 SELECT
3230 CASE
3231 WHEN "vote_now" * 2 > "issue_row"."population" THEN
3232 TRUE
3233 WHEN "vote_later" * 2 > "issue_row"."population" THEN
3234 FALSE
3235 ELSE NULL
3236 END
3237 INTO "voting_requested_v"
3238 FROM "issue" WHERE "id" = "issue_id_p";
3239 IF
3240 "voting_requested_v" OR (
3241 "voting_requested_v" ISNULL AND
3242 now() >= "issue_row"."accepted" + "issue_row"."discussion_time"
3244 THEN
3245 PERFORM "set_snapshot_event"("issue_id_p", 'half_freeze');
3246 "issue_row"."half_frozen" = now(); -- NOTE: "issue_row" used later
3247 UPDATE "issue" SET "half_frozen" = "issue_row"."half_frozen"
3248 WHERE "id" = "issue_row"."id";
3249 END IF;
3250 END IF;
3251 -- close issues after some time, if all initiatives have been revoked:
3252 IF
3253 "issue_row"."closed" ISNULL AND
3254 NOT EXISTS (
3255 -- all initiatives are revoked
3256 SELECT NULL FROM "initiative"
3257 WHERE "issue_id" = "issue_id_p" AND "revoked" ISNULL
3258 ) AND (
3259 NOT EXISTS (
3260 -- and no initiatives have been revoked lately
3261 SELECT NULL FROM "initiative"
3262 WHERE "issue_id" = "issue_id_p"
3263 AND now() < "revoked" + "issue_row"."verification_time"
3264 ) OR (
3265 -- or verification time has elapsed
3266 "issue_row"."half_frozen" NOTNULL AND
3267 "issue_row"."fully_frozen" ISNULL AND
3268 now() >= "issue_row"."half_frozen" + "issue_row"."verification_time"
3271 THEN
3272 "issue_row"."closed" = now(); -- NOTE: "issue_row" used later
3273 UPDATE "issue" SET "closed" = "issue_row"."closed"
3274 WHERE "id" = "issue_row"."id";
3275 END IF;
3276 -- fully freeze issue after verification time:
3277 IF
3278 "issue_row"."half_frozen" NOTNULL AND
3279 "issue_row"."fully_frozen" ISNULL AND
3280 "issue_row"."closed" ISNULL AND
3281 now() >= "issue_row"."half_frozen" + "issue_row"."verification_time"
3282 THEN
3283 PERFORM "freeze_after_snapshot"("issue_id_p");
3284 -- NOTE: "issue" might change, thus "issue_row" has to be updated below
3285 END IF;
3286 SELECT * INTO "issue_row" FROM "issue" WHERE "id" = "issue_id_p";
3287 -- close issue by calling close_voting(...) after voting time:
3288 IF
3289 "issue_row"."closed" ISNULL AND
3290 "issue_row"."fully_frozen" NOTNULL AND
3291 now() >= "issue_row"."fully_frozen" + "issue_row"."voting_time"
3292 THEN
3293 PERFORM "close_voting"("issue_id_p");
3294 END IF;
3295 END IF;
3296 RETURN;
3297 END;
3298 $$;
3300 COMMENT ON FUNCTION "check_issue"
3301 ( "issue"."id"%TYPE )
3302 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.';
3305 CREATE FUNCTION "check_everything"()
3306 RETURNS VOID
3307 LANGUAGE 'plpgsql' VOLATILE AS $$
3308 DECLARE
3309 "issue_id_v" "issue"."id"%TYPE;
3310 BEGIN
3311 DELETE FROM "expired_session";
3312 PERFORM "calculate_member_counts"();
3313 FOR "issue_id_v" IN SELECT "id" FROM "open_issue" LOOP
3314 PERFORM "check_issue"("issue_id_v");
3315 END LOOP;
3316 FOR "issue_id_v" IN SELECT "id" FROM "issue_with_ranks_missing" LOOP
3317 PERFORM "calculate_ranks"("issue_id_v");
3318 END LOOP;
3319 RETURN;
3320 END;
3321 $$;
3323 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.';
3327 ----------------------
3328 -- Deletion of data --
3329 ----------------------
3332 CREATE FUNCTION "clean_issue"("issue_id_p" "issue"."id"%TYPE)
3333 RETURNS VOID
3334 LANGUAGE 'plpgsql' VOLATILE AS $$
3335 DECLARE
3336 "issue_row" "issue"%ROWTYPE;
3337 BEGIN
3338 SELECT * INTO "issue_row"
3339 FROM "issue" WHERE "id" = "issue_id_p"
3340 FOR UPDATE;
3341 IF "issue_row"."cleaned" ISNULL THEN
3342 UPDATE "issue" SET
3343 "closed" = NULL,
3344 "ranks_available" = FALSE
3345 WHERE "id" = "issue_id_p";
3346 DELETE FROM "delegating_voter"
3347 WHERE "issue_id" = "issue_id_p";
3348 DELETE FROM "direct_voter"
3349 WHERE "issue_id" = "issue_id_p";
3350 DELETE FROM "delegating_interest_snapshot"
3351 WHERE "issue_id" = "issue_id_p";
3352 DELETE FROM "direct_interest_snapshot"
3353 WHERE "issue_id" = "issue_id_p";
3354 DELETE FROM "delegating_population_snapshot"
3355 WHERE "issue_id" = "issue_id_p";
3356 DELETE FROM "direct_population_snapshot"
3357 WHERE "issue_id" = "issue_id_p";
3358 DELETE FROM "delegation"
3359 WHERE "issue_id" = "issue_id_p";
3360 DELETE FROM "supporter"
3361 WHERE "issue_id" = "issue_id_p";
3362 UPDATE "issue" SET
3363 "closed" = "issue_row"."closed",
3364 "ranks_available" = "issue_row"."ranks_available",
3365 "cleaned" = now()
3366 WHERE "id" = "issue_id_p";
3367 END IF;
3368 RETURN;
3369 END;
3370 $$;
3372 COMMENT ON FUNCTION "clean_issue"("issue"."id"%TYPE) IS 'Delete discussion data and votes belonging to an issue';
3375 CREATE FUNCTION "delete_member"("member_id_p" "member"."id"%TYPE)
3376 RETURNS VOID
3377 LANGUAGE 'plpgsql' VOLATILE AS $$
3378 BEGIN
3379 UPDATE "member" SET
3380 "last_login" = NULL,
3381 "login" = NULL,
3382 "password" = NULL,
3383 "active" = FALSE,
3384 "notify_email" = NULL,
3385 "notify_email_unconfirmed" = NULL,
3386 "notify_email_secret" = NULL,
3387 "notify_email_secret_expiry" = NULL,
3388 "notify_email_lock_expiry" = NULL,
3389 "password_reset_secret" = NULL,
3390 "password_reset_secret_expiry" = NULL,
3391 "organizational_unit" = NULL,
3392 "internal_posts" = NULL,
3393 "realname" = NULL,
3394 "birthday" = NULL,
3395 "address" = NULL,
3396 "email" = NULL,
3397 "xmpp_address" = NULL,
3398 "website" = NULL,
3399 "phone" = NULL,
3400 "mobile_phone" = NULL,
3401 "profession" = NULL,
3402 "external_memberships" = NULL,
3403 "external_posts" = NULL,
3404 "statement" = NULL
3405 WHERE "id" = "member_id_p";
3406 -- "text_search_data" is updated by triggers
3407 DELETE FROM "setting" WHERE "member_id" = "member_id_p";
3408 DELETE FROM "setting_map" WHERE "member_id" = "member_id_p";
3409 DELETE FROM "member_relation_setting" WHERE "member_id" = "member_id_p";
3410 DELETE FROM "member_image" WHERE "member_id" = "member_id_p";
3411 DELETE FROM "contact" WHERE "member_id" = "member_id_p";
3412 DELETE FROM "area_setting" WHERE "member_id" = "member_id_p";
3413 DELETE FROM "issue_setting" WHERE "member_id" = "member_id_p";
3414 DELETE FROM "initiative_setting" WHERE "member_id" = "member_id_p";
3415 DELETE FROM "suggestion_setting" WHERE "member_id" = "member_id_p";
3416 DELETE FROM "membership" WHERE "member_id" = "member_id_p";
3417 DELETE FROM "delegation" WHERE "truster_id" = "member_id_p";
3418 DELETE FROM "delegation" WHERE "trustee_id" = "member_id_p";
3419 DELETE FROM "direct_voter" USING "issue"
3420 WHERE "direct_voter"."issue_id" = "issue"."id"
3421 AND "issue"."closed" ISNULL
3422 AND "member_id" = "member_id_p";
3423 RETURN;
3424 END;
3425 $$;
3427 COMMENT ON FUNCTION "delete_member"("member_id_p" "member"."id"%TYPE) IS 'Deactivate member and clear certain settings and data of this member (data protection)';
3430 CREATE FUNCTION "delete_private_data"()
3431 RETURNS VOID
3432 LANGUAGE 'plpgsql' VOLATILE AS $$
3433 BEGIN
3434 UPDATE "member" SET
3435 "last_login" = NULL,
3436 "login" = NULL,
3437 "password" = NULL,
3438 "notify_email" = NULL,
3439 "notify_email_unconfirmed" = NULL,
3440 "notify_email_secret" = NULL,
3441 "notify_email_secret_expiry" = NULL,
3442 "notify_email_lock_expiry" = NULL,
3443 "password_reset_secret" = NULL,
3444 "password_reset_secret_expiry" = NULL,
3445 "organizational_unit" = NULL,
3446 "internal_posts" = NULL,
3447 "realname" = NULL,
3448 "birthday" = NULL,
3449 "address" = NULL,
3450 "email" = NULL,
3451 "xmpp_address" = NULL,
3452 "website" = NULL,
3453 "phone" = NULL,
3454 "mobile_phone" = NULL,
3455 "profession" = NULL,
3456 "external_memberships" = NULL,
3457 "external_posts" = NULL,
3458 "statement" = NULL;
3459 -- "text_search_data" is updated by triggers
3460 DELETE FROM "invite_code";
3461 DELETE FROM "setting";
3462 DELETE FROM "setting_map";
3463 DELETE FROM "member_relation_setting";
3464 DELETE FROM "member_image";
3465 DELETE FROM "contact";
3466 DELETE FROM "session";
3467 DELETE FROM "area_setting";
3468 DELETE FROM "issue_setting";
3469 DELETE FROM "initiative_setting";
3470 DELETE FROM "suggestion_setting";
3471 DELETE FROM "direct_voter" USING "issue"
3472 WHERE "direct_voter"."issue_id" = "issue"."id"
3473 AND "issue"."closed" ISNULL;
3474 RETURN;
3475 END;
3476 $$;
3478 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.';
3482 COMMIT;

Impressum / About Us