liquid_feedback_core

view core.sql @ 82:7744034552a3

don't cause nan values in demo policies
author Daniel Poelzleithner <poelzi@poelzi.org>
date Sat Oct 09 21:56:27 2010 +0200 (2010-10-09)
parents dfa8e6a1f1e7
children bb04e4d1c68c
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_issue_id_idx" ON "initiative" ("issue_id");
450 CREATE INDEX "initiative_text_search_data_idx" ON "initiative" USING gin ("text_search_data");
451 CREATE TRIGGER "update_text_search_data"
452 BEFORE INSERT OR UPDATE ON "initiative"
453 FOR EACH ROW EXECUTE PROCEDURE
454 tsvector_update_trigger('text_search_data', 'pg_catalog.simple',
455 "name", "discussion_url");
457 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.';
459 COMMENT ON COLUMN "initiative"."discussion_url" IS 'URL pointing to a discussion platform for this initiative';
460 COMMENT ON COLUMN "initiative"."revoked" IS 'Point in time, when one initiator decided to revoke the initiative';
461 COMMENT ON COLUMN "initiative"."admitted" IS 'TRUE, if initiative reaches the "initiative_quorum" when freezing the issue';
462 COMMENT ON COLUMN "initiative"."supporter_count" IS 'Calculated from table "direct_supporter_snapshot"';
463 COMMENT ON COLUMN "initiative"."informed_supporter_count" IS 'Calculated from table "direct_supporter_snapshot"';
464 COMMENT ON COLUMN "initiative"."satisfied_supporter_count" IS 'Calculated from table "direct_supporter_snapshot"';
465 COMMENT ON COLUMN "initiative"."satisfied_informed_supporter_count" IS 'Calculated from table "direct_supporter_snapshot"';
466 COMMENT ON COLUMN "initiative"."positive_votes" IS 'Calculated from table "direct_voter"';
467 COMMENT ON COLUMN "initiative"."negative_votes" IS 'Calculated from table "direct_voter"';
468 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"';
469 COMMENT ON COLUMN "initiative"."rank" IS 'Rank of approved initiatives (winner is 1), calculated from table "direct_voter"';
472 CREATE TABLE "battle" (
473 PRIMARY KEY ("issue_id", "winning_initiative_id", "losing_initiative_id"),
474 "issue_id" INT4,
475 "winning_initiative_id" INT4,
476 FOREIGN KEY ("issue_id", "winning_initiative_id") REFERENCES "initiative" ("issue_id", "id") ON DELETE CASCADE ON UPDATE CASCADE,
477 "losing_initiative_id" INT4,
478 FOREIGN KEY ("issue_id", "losing_initiative_id") REFERENCES "initiative" ("issue_id", "id") ON DELETE CASCADE ON UPDATE CASCADE,
479 "count" INT4 NOT NULL);
481 COMMENT ON TABLE "battle" IS 'Number of members preferring one initiative to another; Filled by "battle_view" when closing an issue';
484 CREATE TABLE "initiative_setting" (
485 PRIMARY KEY ("member_id", "key", "initiative_id"),
486 "member_id" INT4 REFERENCES "member" ("id") ON DELETE CASCADE ON UPDATE CASCADE,
487 "key" TEXT NOT NULL,
488 "initiative_id" INT4 REFERENCES "initiative" ("id") ON DELETE CASCADE ON UPDATE CASCADE,
489 "value" TEXT NOT NULL );
491 COMMENT ON TABLE "initiative_setting" IS 'Place for frontend to store initiative specific settings of members as strings';
494 CREATE TABLE "draft" (
495 UNIQUE ("initiative_id", "id"), -- index needed for foreign-key on table "supporter"
496 "initiative_id" INT4 NOT NULL REFERENCES "initiative" ("id") ON DELETE CASCADE ON UPDATE CASCADE,
497 "id" SERIAL8 PRIMARY KEY,
498 "created" TIMESTAMPTZ NOT NULL DEFAULT now(),
499 "author_id" INT4 NOT NULL REFERENCES "member" ("id") ON DELETE RESTRICT ON UPDATE CASCADE,
500 "formatting_engine" TEXT,
501 "content" TEXT NOT NULL,
502 "text_search_data" TSVECTOR );
503 CREATE INDEX "draft_created_idx" ON "draft" ("created");
504 CREATE INDEX "draft_author_id_created_idx" ON "draft" ("author_id", "created");
505 CREATE INDEX "draft_text_search_data_idx" ON "draft" USING gin ("text_search_data");
506 CREATE TRIGGER "update_text_search_data"
507 BEFORE INSERT OR UPDATE ON "draft"
508 FOR EACH ROW EXECUTE PROCEDURE
509 tsvector_update_trigger('text_search_data', 'pg_catalog.simple', "content");
511 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.';
513 COMMENT ON COLUMN "draft"."formatting_engine" IS 'Allows different formatting engines (i.e. wiki formats) to be used';
514 COMMENT ON COLUMN "draft"."content" IS 'Text of the draft in a format depending on the field "formatting_engine"';
517 CREATE TABLE "rendered_draft" (
518 PRIMARY KEY ("draft_id", "format"),
519 "draft_id" INT8 REFERENCES "draft" ("id") ON DELETE CASCADE ON UPDATE CASCADE,
520 "format" TEXT,
521 "content" TEXT NOT NULL );
523 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)';
526 CREATE TABLE "suggestion" (
527 UNIQUE ("initiative_id", "id"), -- index needed for foreign-key on table "opinion"
528 "initiative_id" INT4 NOT NULL REFERENCES "initiative" ("id") ON DELETE CASCADE ON UPDATE CASCADE,
529 "id" SERIAL8 PRIMARY KEY,
530 "created" TIMESTAMPTZ NOT NULL DEFAULT now(),
531 "author_id" INT4 NOT NULL REFERENCES "member" ("id") ON DELETE RESTRICT ON UPDATE CASCADE,
532 "name" TEXT NOT NULL,
533 "description" TEXT NOT NULL DEFAULT '',
534 "text_search_data" TSVECTOR,
535 "minus2_unfulfilled_count" INT4,
536 "minus2_fulfilled_count" INT4,
537 "minus1_unfulfilled_count" INT4,
538 "minus1_fulfilled_count" INT4,
539 "plus1_unfulfilled_count" INT4,
540 "plus1_fulfilled_count" INT4,
541 "plus2_unfulfilled_count" INT4,
542 "plus2_fulfilled_count" INT4 );
543 CREATE INDEX "suggestion_created_idx" ON "suggestion" ("created");
544 CREATE INDEX "suggestion_author_id_created_idx" ON "suggestion" ("author_id", "created");
545 CREATE INDEX "suggestion_text_search_data_idx" ON "suggestion" USING gin ("text_search_data");
546 CREATE TRIGGER "update_text_search_data"
547 BEFORE INSERT OR UPDATE ON "suggestion"
548 FOR EACH ROW EXECUTE PROCEDURE
549 tsvector_update_trigger('text_search_data', 'pg_catalog.simple',
550 "name", "description");
552 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';
554 COMMENT ON COLUMN "suggestion"."minus2_unfulfilled_count" IS 'Calculated from table "direct_supporter_snapshot", not requiring informed supporters';
555 COMMENT ON COLUMN "suggestion"."minus2_fulfilled_count" IS 'Calculated from table "direct_supporter_snapshot", not requiring informed supporters';
556 COMMENT ON COLUMN "suggestion"."minus1_unfulfilled_count" IS 'Calculated from table "direct_supporter_snapshot", not requiring informed supporters';
557 COMMENT ON COLUMN "suggestion"."minus1_fulfilled_count" IS 'Calculated from table "direct_supporter_snapshot", not requiring informed supporters';
558 COMMENT ON COLUMN "suggestion"."plus1_unfulfilled_count" IS 'Calculated from table "direct_supporter_snapshot", not requiring informed supporters';
559 COMMENT ON COLUMN "suggestion"."plus1_fulfilled_count" IS 'Calculated from table "direct_supporter_snapshot", not requiring informed supporters';
560 COMMENT ON COLUMN "suggestion"."plus2_unfulfilled_count" IS 'Calculated from table "direct_supporter_snapshot", not requiring informed supporters';
561 COMMENT ON COLUMN "suggestion"."plus2_fulfilled_count" IS 'Calculated from table "direct_supporter_snapshot", not requiring informed supporters';
564 CREATE TABLE "suggestion_setting" (
565 PRIMARY KEY ("member_id", "key", "suggestion_id"),
566 "member_id" INT4 REFERENCES "member" ("id") ON DELETE CASCADE ON UPDATE CASCADE,
567 "key" TEXT NOT NULL,
568 "suggestion_id" INT8 REFERENCES "suggestion" ("id") ON DELETE CASCADE ON UPDATE CASCADE,
569 "value" TEXT NOT NULL );
571 COMMENT ON TABLE "suggestion_setting" IS 'Place for frontend to store suggestion specific settings of members as strings';
574 CREATE TABLE "membership" (
575 PRIMARY KEY ("area_id", "member_id"),
576 "area_id" INT4 REFERENCES "area" ("id") ON DELETE CASCADE ON UPDATE CASCADE,
577 "member_id" INT4 REFERENCES "member" ("id") ON DELETE CASCADE ON UPDATE CASCADE,
578 "autoreject" BOOLEAN NOT NULL DEFAULT FALSE );
579 CREATE INDEX "membership_member_id_idx" ON "membership" ("member_id");
581 COMMENT ON TABLE "membership" IS 'Interest of members in topic areas';
583 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';
586 CREATE TABLE "interest" (
587 PRIMARY KEY ("issue_id", "member_id"),
588 "issue_id" INT4 REFERENCES "issue" ("id") ON DELETE CASCADE ON UPDATE CASCADE,
589 "member_id" INT4 REFERENCES "member" ("id") ON DELETE CASCADE ON UPDATE CASCADE,
590 "autoreject" BOOLEAN NOT NULL,
591 "voting_requested" BOOLEAN );
592 CREATE INDEX "interest_member_id_idx" ON "interest" ("member_id");
594 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.';
596 COMMENT ON COLUMN "interest"."autoreject" IS 'TRUE = member votes against all initiatives in case of not explicitly taking part in the voting procedure';
597 COMMENT ON COLUMN "interest"."voting_requested" IS 'TRUE = member wants to vote now, FALSE = member wants to vote later, NULL = policy rules should apply';
600 CREATE TABLE "initiator" (
601 PRIMARY KEY ("initiative_id", "member_id"),
602 "initiative_id" INT4 REFERENCES "initiative" ("id") ON DELETE CASCADE ON UPDATE CASCADE,
603 "member_id" INT4 REFERENCES "member" ("id") ON DELETE CASCADE ON UPDATE CASCADE,
604 "accepted" BOOLEAN );
605 CREATE INDEX "initiator_member_id_idx" ON "initiator" ("member_id");
607 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.';
609 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.';
612 CREATE TABLE "supporter" (
613 "issue_id" INT4 NOT NULL,
614 PRIMARY KEY ("initiative_id", "member_id"),
615 "initiative_id" INT4,
616 "member_id" INT4,
617 "draft_id" INT8 NOT NULL,
618 "auto_support" BOOLEAN NOT NULL DEFAULT 'f',
619 FOREIGN KEY ("issue_id", "member_id") REFERENCES "interest" ("issue_id", "member_id") ON DELETE CASCADE ON UPDATE CASCADE,
620 FOREIGN KEY ("initiative_id", "draft_id") REFERENCES "draft" ("initiative_id", "id") ON DELETE CASCADE ON UPDATE CASCADE );
621 CREATE INDEX "supporter_member_id_idx" ON "supporter" ("member_id");
623 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.';
625 COMMENT ON COLUMN "supporter"."draft_id" IS 'Latest seen draft, defaults to current draft of the initiative (implemented by trigger "default_for_draft_id")';
627 CREATE FUNCTION update_supporter_drafts()
628 RETURNS trigger
629 LANGUAGE 'plpgsql' VOLATILE AS $$
630 BEGIN
631 UPDATE supporter SET draft_id = NEW.id
632 WHERE initiative_id = NEW.initiative_id AND
633 (auto_support = 't' OR member_id = NEW.author_id);
634 RETURN new;
635 END
636 $$;
638 CREATE TRIGGER "update_draft_supporter"
639 AFTER INSERT ON "draft"
640 FOR EACH ROW EXECUTE PROCEDURE
641 update_supporter_drafts();
643 COMMENT ON FUNCTION "update_supporter_drafts"() IS 'Automaticly update the supported draft_id to the latest version when auto_support is enabled';
645 CREATE TABLE "opinion" (
646 "initiative_id" INT4 NOT NULL,
647 PRIMARY KEY ("suggestion_id", "member_id"),
648 "suggestion_id" INT8,
649 "member_id" INT4,
650 "degree" INT2 NOT NULL CHECK ("degree" >= -2 AND "degree" <= 2 AND "degree" != 0),
651 "fulfilled" BOOLEAN NOT NULL DEFAULT FALSE,
652 FOREIGN KEY ("initiative_id", "suggestion_id") REFERENCES "suggestion" ("initiative_id", "id") ON DELETE CASCADE ON UPDATE CASCADE,
653 FOREIGN KEY ("initiative_id", "member_id") REFERENCES "supporter" ("initiative_id", "member_id") ON DELETE CASCADE ON UPDATE CASCADE );
654 CREATE INDEX "opinion_member_id_initiative_id_idx" ON "opinion" ("member_id", "initiative_id");
656 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.';
658 COMMENT ON COLUMN "opinion"."degree" IS '2 = fulfillment required for support; 1 = fulfillment desired; -1 = fulfillment unwanted; -2 = fulfillment cancels support';
661 CREATE TYPE "delegation_scope" AS ENUM ('global', 'area', 'issue');
663 COMMENT ON TYPE "delegation_scope" IS 'Scope for delegations: ''global'', ''area'', or ''issue'' (order is relevant)';
666 CREATE TABLE "delegation" (
667 "id" SERIAL8 PRIMARY KEY,
668 "truster_id" INT4 NOT NULL REFERENCES "member" ("id") ON DELETE CASCADE ON UPDATE CASCADE,
669 "trustee_id" INT4 NOT NULL REFERENCES "member" ("id") ON DELETE CASCADE ON UPDATE CASCADE,
670 "scope" "delegation_scope" NOT NULL,
671 "area_id" INT4 REFERENCES "area" ("id") ON DELETE CASCADE ON UPDATE CASCADE,
672 "issue_id" INT4 REFERENCES "issue" ("id") ON DELETE CASCADE ON UPDATE CASCADE,
673 CONSTRAINT "cant_delegate_to_yourself" CHECK ("truster_id" != "trustee_id"),
674 CONSTRAINT "area_id_and_issue_id_set_according_to_scope" CHECK (
675 ("scope" = 'global' AND "area_id" ISNULL AND "issue_id" ISNULL ) OR
676 ("scope" = 'area' AND "area_id" NOTNULL AND "issue_id" ISNULL ) OR
677 ("scope" = 'issue' AND "area_id" ISNULL AND "issue_id" NOTNULL) ),
678 UNIQUE ("area_id", "truster_id"),
679 UNIQUE ("issue_id", "truster_id") );
680 CREATE UNIQUE INDEX "delegation_global_truster_id_unique_idx"
681 ON "delegation" ("truster_id") WHERE "scope" = 'global';
682 CREATE INDEX "delegation_truster_id_idx" ON "delegation" ("truster_id");
683 CREATE INDEX "delegation_trustee_id_idx" ON "delegation" ("trustee_id");
685 COMMENT ON TABLE "delegation" IS 'Delegation of vote-weight to other members';
687 COMMENT ON COLUMN "delegation"."area_id" IS 'Reference to area, if delegation is area-wide, otherwise NULL';
688 COMMENT ON COLUMN "delegation"."issue_id" IS 'Reference to issue, if delegation is issue-wide, otherwise NULL';
690 CREATE FUNCTION "check_delegation"()
691 RETURNS TRIGGER
692 LANGUAGE 'plpgsql' VOLATILE AS $$
693 BEGIN
694 IF EXISTS (
695 SELECT NULL FROM "member" WHERE
696 "id" = NEW."trustee_id" AND active = 'n'
697 ) THEN
698 RAISE EXCEPTION 'Cannot delegate to an inactive member';
699 END IF;
700 RETURN NEW;
701 END;
702 $$;
704 CREATE TRIGGER "update_delegation"
705 BEFORE INSERT OR UPDATE ON "delegation"
706 FOR EACH ROW EXECUTE PROCEDURE
707 check_delegation();
709 COMMENT ON FUNCTION "check_delegation"() IS 'Sanity checks for new delegation. Dont allow delegations to inactive members';
711 CREATE TABLE "direct_population_snapshot" (
712 PRIMARY KEY ("issue_id", "event", "member_id"),
713 "issue_id" INT4 REFERENCES "issue" ("id") ON DELETE CASCADE ON UPDATE CASCADE,
714 "event" "snapshot_event",
715 "member_id" INT4 REFERENCES "member" ("id") ON DELETE RESTRICT ON UPDATE RESTRICT,
716 "weight" INT4 );
717 CREATE INDEX "direct_population_snapshot_member_id_idx" ON "direct_population_snapshot" ("member_id");
719 COMMENT ON TABLE "direct_population_snapshot" IS 'Snapshot of active members having either a "membership" in the "area" or an "interest" in the "issue"';
721 COMMENT ON COLUMN "direct_population_snapshot"."event" IS 'Reason for snapshot, see "snapshot_event" type for details';
722 COMMENT ON COLUMN "direct_population_snapshot"."weight" IS 'Weight of member (1 or higher) according to "delegating_population_snapshot"';
725 CREATE TABLE "delegating_population_snapshot" (
726 PRIMARY KEY ("issue_id", "event", "member_id"),
727 "issue_id" INT4 REFERENCES "issue" ("id") ON DELETE CASCADE ON UPDATE CASCADE,
728 "event" "snapshot_event",
729 "member_id" INT4 REFERENCES "member" ("id") ON DELETE RESTRICT ON UPDATE RESTRICT,
730 "weight" INT4,
731 "scope" "delegation_scope" NOT NULL,
732 "delegate_member_ids" INT4[] NOT NULL );
733 CREATE INDEX "delegating_population_snapshot_member_id_idx" ON "delegating_population_snapshot" ("member_id");
735 COMMENT ON TABLE "direct_population_snapshot" IS 'Delegations increasing the weight of entries in the "direct_population_snapshot" table';
737 COMMENT ON COLUMN "delegating_population_snapshot"."event" IS 'Reason for snapshot, see "snapshot_event" type for details';
738 COMMENT ON COLUMN "delegating_population_snapshot"."member_id" IS 'Delegating member';
739 COMMENT ON COLUMN "delegating_population_snapshot"."weight" IS 'Intermediate weight';
740 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"';
743 CREATE TABLE "direct_interest_snapshot" (
744 PRIMARY KEY ("issue_id", "event", "member_id"),
745 "issue_id" INT4 REFERENCES "issue" ("id") ON DELETE CASCADE ON UPDATE CASCADE,
746 "event" "snapshot_event",
747 "member_id" INT4 REFERENCES "member" ("id") ON DELETE RESTRICT ON UPDATE RESTRICT,
748 "weight" INT4,
749 "voting_requested" BOOLEAN );
750 CREATE INDEX "direct_interest_snapshot_member_id_idx" ON "direct_interest_snapshot" ("member_id");
752 COMMENT ON TABLE "direct_interest_snapshot" IS 'Snapshot of active members having an "interest" in the "issue"';
754 COMMENT ON COLUMN "direct_interest_snapshot"."event" IS 'Reason for snapshot, see "snapshot_event" type for details';
755 COMMENT ON COLUMN "direct_interest_snapshot"."weight" IS 'Weight of member (1 or higher) according to "delegating_interest_snapshot"';
756 COMMENT ON COLUMN "direct_interest_snapshot"."voting_requested" IS 'Copied from column "voting_requested" of table "interest"';
759 CREATE TABLE "delegating_interest_snapshot" (
760 PRIMARY KEY ("issue_id", "event", "member_id"),
761 "issue_id" INT4 REFERENCES "issue" ("id") ON DELETE CASCADE ON UPDATE CASCADE,
762 "event" "snapshot_event",
763 "member_id" INT4 REFERENCES "member" ("id") ON DELETE RESTRICT ON UPDATE RESTRICT,
764 "weight" INT4,
765 "scope" "delegation_scope" NOT NULL,
766 "delegate_member_ids" INT4[] NOT NULL );
767 CREATE INDEX "delegating_interest_snapshot_member_id_idx" ON "delegating_interest_snapshot" ("member_id");
769 COMMENT ON TABLE "delegating_interest_snapshot" IS 'Delegations increasing the weight of entries in the "direct_interest_snapshot" table';
771 COMMENT ON COLUMN "delegating_interest_snapshot"."event" IS 'Reason for snapshot, see "snapshot_event" type for details';
772 COMMENT ON COLUMN "delegating_interest_snapshot"."member_id" IS 'Delegating member';
773 COMMENT ON COLUMN "delegating_interest_snapshot"."weight" IS 'Intermediate weight';
774 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"';
777 CREATE TABLE "direct_supporter_snapshot" (
778 "issue_id" INT4 NOT NULL,
779 PRIMARY KEY ("initiative_id", "event", "member_id"),
780 "initiative_id" INT4,
781 "event" "snapshot_event",
782 "member_id" INT4 REFERENCES "member" ("id") ON DELETE RESTRICT ON UPDATE RESTRICT,
783 "informed" BOOLEAN NOT NULL,
784 "satisfied" BOOLEAN NOT NULL,
785 FOREIGN KEY ("issue_id", "initiative_id") REFERENCES "initiative" ("issue_id", "id") ON DELETE CASCADE ON UPDATE CASCADE,
786 FOREIGN KEY ("issue_id", "event", "member_id") REFERENCES "direct_interest_snapshot" ("issue_id", "event", "member_id") ON DELETE CASCADE ON UPDATE CASCADE );
787 CREATE INDEX "direct_supporter_snapshot_member_id_idx" ON "direct_supporter_snapshot" ("member_id");
789 COMMENT ON TABLE "direct_supporter_snapshot" IS 'Snapshot of supporters of initiatives (weight is stored in "direct_interest_snapshot")';
791 COMMENT ON COLUMN "direct_supporter_snapshot"."event" IS 'Reason for snapshot, see "snapshot_event" type for details';
792 COMMENT ON COLUMN "direct_supporter_snapshot"."informed" IS 'Supporter has seen the latest draft of the initiative';
793 COMMENT ON COLUMN "direct_supporter_snapshot"."satisfied" IS 'Supporter has no "critical_opinion"s';
796 CREATE TABLE "direct_voter" (
797 PRIMARY KEY ("issue_id", "member_id"),
798 "issue_id" INT4 REFERENCES "issue" ("id") ON DELETE CASCADE ON UPDATE CASCADE,
799 "member_id" INT4 REFERENCES "member" ("id") ON DELETE RESTRICT ON UPDATE RESTRICT,
800 "weight" INT4,
801 "autoreject" BOOLEAN NOT NULL DEFAULT FALSE );
802 CREATE INDEX "direct_voter_member_id_idx" ON "direct_voter" ("member_id");
804 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.';
806 COMMENT ON COLUMN "direct_voter"."weight" IS 'Weight of member (1 or higher) according to "delegating_voter" table';
807 COMMENT ON COLUMN "direct_voter"."autoreject" IS 'Votes were inserted due to "autoreject" feature';
810 CREATE TABLE "delegating_voter" (
811 PRIMARY KEY ("issue_id", "member_id"),
812 "issue_id" INT4 REFERENCES "issue" ("id") ON DELETE CASCADE ON UPDATE CASCADE,
813 "member_id" INT4 REFERENCES "member" ("id") ON DELETE RESTRICT ON UPDATE RESTRICT,
814 "weight" INT4,
815 "scope" "delegation_scope" NOT NULL,
816 "delegate_member_ids" INT4[] NOT NULL );
817 CREATE INDEX "delegating_voter_member_id_idx" ON "delegating_voter" ("member_id");
819 COMMENT ON TABLE "delegating_voter" IS 'Delegations increasing the weight of entries in the "direct_voter" table';
821 COMMENT ON COLUMN "delegating_voter"."member_id" IS 'Delegating member';
822 COMMENT ON COLUMN "delegating_voter"."weight" IS 'Intermediate weight';
823 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"';
826 CREATE TABLE "vote" (
827 "issue_id" INT4 NOT NULL,
828 PRIMARY KEY ("initiative_id", "member_id"),
829 "initiative_id" INT4,
830 "member_id" INT4,
831 "grade" INT4,
832 FOREIGN KEY ("issue_id", "initiative_id") REFERENCES "initiative" ("issue_id", "id") ON DELETE CASCADE ON UPDATE CASCADE,
833 FOREIGN KEY ("issue_id", "member_id") REFERENCES "direct_voter" ("issue_id", "member_id") ON DELETE CASCADE ON UPDATE CASCADE );
834 CREATE INDEX "vote_member_id_idx" ON "vote" ("member_id");
836 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.';
838 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.';
841 CREATE TABLE "contingent" (
842 "time_frame" INTERVAL PRIMARY KEY,
843 "text_entry_limit" INT4,
844 "initiative_limit" INT4 );
846 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.';
848 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';
849 COMMENT ON COLUMN "contingent"."initiative_limit" IS 'Number of new initiatives to be opened by each member within a given time frame';
853 --------------------------------
854 -- Writing of history entries --
855 --------------------------------
857 CREATE FUNCTION "write_member_history_trigger"()
858 RETURNS TRIGGER
859 LANGUAGE 'plpgsql' VOLATILE AS $$
860 BEGIN
861 IF
862 NEW."active" != OLD."active" OR
863 NEW."name" != OLD."name"
864 THEN
865 INSERT INTO "member_history"
866 ("member_id", "active", "name")
867 VALUES (NEW."id", OLD."active", OLD."name");
868 END IF;
869 RETURN NULL;
870 END;
871 $$;
873 CREATE TRIGGER "write_member_history"
874 AFTER UPDATE ON "member" FOR EACH ROW EXECUTE PROCEDURE
875 "write_member_history_trigger"();
877 COMMENT ON FUNCTION "write_member_history_trigger"() IS 'Implementation of trigger "write_member_history" on table "member"';
878 COMMENT ON TRIGGER "write_member_history" ON "member" IS 'When changing certain fields of a member, create a history entry in "member_history" table';
882 ----------------------------
883 -- Additional constraints --
884 ----------------------------
887 CREATE FUNCTION "issue_requires_first_initiative_trigger"()
888 RETURNS TRIGGER
889 LANGUAGE 'plpgsql' VOLATILE AS $$
890 BEGIN
891 IF NOT EXISTS (
892 SELECT NULL FROM "initiative" WHERE "issue_id" = NEW."id"
893 ) THEN
894 --RAISE 'Cannot create issue without an initial initiative.' USING
895 -- ERRCODE = 'integrity_constraint_violation',
896 -- HINT = 'Create issue, initiative, and draft within the same transaction.';
897 RAISE EXCEPTION 'Cannot create issue without an initial initiative.';
898 END IF;
899 RETURN NULL;
900 END;
901 $$;
903 CREATE CONSTRAINT TRIGGER "issue_requires_first_initiative"
904 AFTER INSERT OR UPDATE ON "issue" DEFERRABLE INITIALLY DEFERRED
905 FOR EACH ROW EXECUTE PROCEDURE
906 "issue_requires_first_initiative_trigger"();
908 COMMENT ON FUNCTION "issue_requires_first_initiative_trigger"() IS 'Implementation of trigger "issue_requires_first_initiative" on table "issue"';
909 COMMENT ON TRIGGER "issue_requires_first_initiative" ON "issue" IS 'Ensure that new issues have at least one initiative';
912 CREATE FUNCTION "last_initiative_deletes_issue_trigger"()
913 RETURNS TRIGGER
914 LANGUAGE 'plpgsql' VOLATILE AS $$
915 DECLARE
916 "reference_lost" BOOLEAN;
917 BEGIN
918 IF TG_OP = 'DELETE' THEN
919 "reference_lost" := TRUE;
920 ELSE
921 "reference_lost" := NEW."issue_id" != OLD."issue_id";
922 END IF;
923 IF
924 "reference_lost" AND NOT EXISTS (
925 SELECT NULL FROM "initiative" WHERE "issue_id" = OLD."issue_id"
926 )
927 THEN
928 DELETE FROM "issue" WHERE "id" = OLD."issue_id";
929 END IF;
930 RETURN NULL;
931 END;
932 $$;
934 CREATE CONSTRAINT TRIGGER "last_initiative_deletes_issue"
935 AFTER UPDATE OR DELETE ON "initiative" DEFERRABLE INITIALLY DEFERRED
936 FOR EACH ROW EXECUTE PROCEDURE
937 "last_initiative_deletes_issue_trigger"();
939 COMMENT ON FUNCTION "last_initiative_deletes_issue_trigger"() IS 'Implementation of trigger "last_initiative_deletes_issue" on table "initiative"';
940 COMMENT ON TRIGGER "last_initiative_deletes_issue" ON "initiative" IS 'Removing the last initiative of an issue deletes the issue';
943 CREATE FUNCTION "initiative_requires_first_draft_trigger"()
944 RETURNS TRIGGER
945 LANGUAGE 'plpgsql' VOLATILE AS $$
946 BEGIN
947 IF NOT EXISTS (
948 SELECT NULL FROM "draft" WHERE "initiative_id" = NEW."id"
949 ) THEN
950 --RAISE 'Cannot create initiative without an initial draft.' USING
951 -- ERRCODE = 'integrity_constraint_violation',
952 -- HINT = 'Create issue, initiative and draft within the same transaction.';
953 RAISE EXCEPTION 'Cannot create initiative without an initial draft.';
954 END IF;
955 RETURN NULL;
956 END;
957 $$;
959 CREATE CONSTRAINT TRIGGER "initiative_requires_first_draft"
960 AFTER INSERT OR UPDATE ON "initiative" DEFERRABLE INITIALLY DEFERRED
961 FOR EACH ROW EXECUTE PROCEDURE
962 "initiative_requires_first_draft_trigger"();
964 COMMENT ON FUNCTION "initiative_requires_first_draft_trigger"() IS 'Implementation of trigger "initiative_requires_first_draft" on table "initiative"';
965 COMMENT ON TRIGGER "initiative_requires_first_draft" ON "initiative" IS 'Ensure that new initiatives have at least one draft';
968 CREATE FUNCTION "last_draft_deletes_initiative_trigger"()
969 RETURNS TRIGGER
970 LANGUAGE 'plpgsql' VOLATILE AS $$
971 DECLARE
972 "reference_lost" BOOLEAN;
973 BEGIN
974 IF TG_OP = 'DELETE' THEN
975 "reference_lost" := TRUE;
976 ELSE
977 "reference_lost" := NEW."initiative_id" != OLD."initiative_id";
978 END IF;
979 IF
980 "reference_lost" AND NOT EXISTS (
981 SELECT NULL FROM "draft" WHERE "initiative_id" = OLD."initiative_id"
982 )
983 THEN
984 DELETE FROM "initiative" WHERE "id" = OLD."initiative_id";
985 END IF;
986 RETURN NULL;
987 END;
988 $$;
990 CREATE CONSTRAINT TRIGGER "last_draft_deletes_initiative"
991 AFTER UPDATE OR DELETE ON "draft" DEFERRABLE INITIALLY DEFERRED
992 FOR EACH ROW EXECUTE PROCEDURE
993 "last_draft_deletes_initiative_trigger"();
995 COMMENT ON FUNCTION "last_draft_deletes_initiative_trigger"() IS 'Implementation of trigger "last_draft_deletes_initiative" on table "draft"';
996 COMMENT ON TRIGGER "last_draft_deletes_initiative" ON "draft" IS 'Removing the last draft of an initiative deletes the initiative';
999 CREATE FUNCTION "suggestion_requires_first_opinion_trigger"()
1000 RETURNS TRIGGER
1001 LANGUAGE 'plpgsql' VOLATILE AS $$
1002 BEGIN
1003 IF NOT EXISTS (
1004 SELECT NULL FROM "opinion" WHERE "suggestion_id" = NEW."id"
1005 ) THEN
1006 RAISE EXCEPTION 'Cannot create a suggestion without an opinion.';
1007 END IF;
1008 RETURN NULL;
1009 END;
1010 $$;
1012 CREATE CONSTRAINT TRIGGER "suggestion_requires_first_opinion"
1013 AFTER INSERT OR UPDATE ON "suggestion" DEFERRABLE INITIALLY DEFERRED
1014 FOR EACH ROW EXECUTE PROCEDURE
1015 "suggestion_requires_first_opinion_trigger"();
1017 COMMENT ON FUNCTION "suggestion_requires_first_opinion_trigger"() IS 'Implementation of trigger "suggestion_requires_first_opinion" on table "suggestion"';
1018 COMMENT ON TRIGGER "suggestion_requires_first_opinion" ON "suggestion" IS 'Ensure that new suggestions have at least one opinion';
1021 CREATE FUNCTION "last_opinion_deletes_suggestion_trigger"()
1022 RETURNS TRIGGER
1023 LANGUAGE 'plpgsql' VOLATILE AS $$
1024 DECLARE
1025 "reference_lost" BOOLEAN;
1026 BEGIN
1027 IF TG_OP = 'DELETE' THEN
1028 "reference_lost" := TRUE;
1029 ELSE
1030 "reference_lost" := NEW."suggestion_id" != OLD."suggestion_id";
1031 END IF;
1032 IF
1033 "reference_lost" AND NOT EXISTS (
1034 SELECT NULL FROM "opinion" WHERE "suggestion_id" = OLD."suggestion_id"
1036 THEN
1037 DELETE FROM "suggestion" WHERE "id" = OLD."suggestion_id";
1038 END IF;
1039 RETURN NULL;
1040 END;
1041 $$;
1043 CREATE CONSTRAINT TRIGGER "last_opinion_deletes_suggestion"
1044 AFTER UPDATE OR DELETE ON "opinion" DEFERRABLE INITIALLY DEFERRED
1045 FOR EACH ROW EXECUTE PROCEDURE
1046 "last_opinion_deletes_suggestion_trigger"();
1048 COMMENT ON FUNCTION "last_opinion_deletes_suggestion_trigger"() IS 'Implementation of trigger "last_opinion_deletes_suggestion" on table "opinion"';
1049 COMMENT ON TRIGGER "last_opinion_deletes_suggestion" ON "opinion" IS 'Removing the last opinion of a suggestion deletes the suggestion';
1053 ---------------------------------------------------------------
1054 -- Ensure that votes are not modified when issues are frozen --
1055 ---------------------------------------------------------------
1057 -- NOTE: Frontends should ensure this anyway, but in case of programming
1058 -- errors the following triggers ensure data integrity.
1061 CREATE FUNCTION "forbid_changes_on_closed_issue_trigger"()
1062 RETURNS TRIGGER
1063 LANGUAGE 'plpgsql' VOLATILE AS $$
1064 DECLARE
1065 "issue_id_v" "issue"."id"%TYPE;
1066 "issue_row" "issue"%ROWTYPE;
1067 BEGIN
1068 IF TG_OP = 'DELETE' THEN
1069 "issue_id_v" := OLD."issue_id";
1070 ELSE
1071 "issue_id_v" := NEW."issue_id";
1072 END IF;
1073 SELECT INTO "issue_row" * FROM "issue"
1074 WHERE "id" = "issue_id_v" FOR SHARE;
1075 IF "issue_row"."closed" NOTNULL THEN
1076 RAISE EXCEPTION 'Tried to modify data belonging to a closed issue.';
1077 END IF;
1078 RETURN NULL;
1079 END;
1080 $$;
1082 CREATE TRIGGER "forbid_changes_on_closed_issue"
1083 AFTER INSERT OR UPDATE OR DELETE ON "direct_voter"
1084 FOR EACH ROW EXECUTE PROCEDURE
1085 "forbid_changes_on_closed_issue_trigger"();
1087 CREATE TRIGGER "forbid_changes_on_closed_issue"
1088 AFTER INSERT OR UPDATE OR DELETE ON "delegating_voter"
1089 FOR EACH ROW EXECUTE PROCEDURE
1090 "forbid_changes_on_closed_issue_trigger"();
1092 CREATE TRIGGER "forbid_changes_on_closed_issue"
1093 AFTER INSERT OR UPDATE OR DELETE ON "vote"
1094 FOR EACH ROW EXECUTE PROCEDURE
1095 "forbid_changes_on_closed_issue_trigger"();
1097 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"';
1098 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';
1099 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';
1100 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';
1104 --------------------------------------------------------------------
1105 -- Auto-retrieval of fields only needed for referential integrity --
1106 --------------------------------------------------------------------
1109 CREATE FUNCTION "autofill_issue_id_trigger"()
1110 RETURNS TRIGGER
1111 LANGUAGE 'plpgsql' VOLATILE AS $$
1112 BEGIN
1113 IF NEW."issue_id" ISNULL THEN
1114 SELECT "issue_id" INTO NEW."issue_id"
1115 FROM "initiative" WHERE "id" = NEW."initiative_id";
1116 END IF;
1117 RETURN NEW;
1118 END;
1119 $$;
1121 CREATE TRIGGER "autofill_issue_id" BEFORE INSERT ON "supporter"
1122 FOR EACH ROW EXECUTE PROCEDURE "autofill_issue_id_trigger"();
1124 CREATE TRIGGER "autofill_issue_id" BEFORE INSERT ON "vote"
1125 FOR EACH ROW EXECUTE PROCEDURE "autofill_issue_id_trigger"();
1127 COMMENT ON FUNCTION "autofill_issue_id_trigger"() IS 'Implementation of triggers "autofill_issue_id" on tables "supporter" and "vote"';
1128 COMMENT ON TRIGGER "autofill_issue_id" ON "supporter" IS 'Set "issue_id" field automatically, if NULL';
1129 COMMENT ON TRIGGER "autofill_issue_id" ON "vote" IS 'Set "issue_id" field automatically, if NULL';
1132 CREATE FUNCTION "autofill_initiative_id_trigger"()
1133 RETURNS TRIGGER
1134 LANGUAGE 'plpgsql' VOLATILE AS $$
1135 BEGIN
1136 IF NEW."initiative_id" ISNULL THEN
1137 SELECT "initiative_id" INTO NEW."initiative_id"
1138 FROM "suggestion" WHERE "id" = NEW."suggestion_id";
1139 END IF;
1140 RETURN NEW;
1141 END;
1142 $$;
1144 CREATE TRIGGER "autofill_initiative_id" BEFORE INSERT ON "opinion"
1145 FOR EACH ROW EXECUTE PROCEDURE "autofill_initiative_id_trigger"();
1147 COMMENT ON FUNCTION "autofill_initiative_id_trigger"() IS 'Implementation of trigger "autofill_initiative_id" on table "opinion"';
1148 COMMENT ON TRIGGER "autofill_initiative_id" ON "opinion" IS 'Set "initiative_id" field automatically, if NULL';
1152 -----------------------------------------------------
1153 -- Automatic calculation of certain default values --
1154 -----------------------------------------------------
1157 CREATE FUNCTION "copy_timings_trigger"()
1158 RETURNS TRIGGER
1159 LANGUAGE 'plpgsql' VOLATILE AS $$
1160 DECLARE
1161 "policy_row" "policy"%ROWTYPE;
1162 BEGIN
1163 SELECT * INTO "policy_row" FROM "policy"
1164 WHERE "id" = NEW."policy_id";
1165 IF NEW."admission_time" ISNULL THEN
1166 NEW."admission_time" := "policy_row"."admission_time";
1167 END IF;
1168 IF NEW."discussion_time" ISNULL THEN
1169 NEW."discussion_time" := "policy_row"."discussion_time";
1170 END IF;
1171 IF NEW."verification_time" ISNULL THEN
1172 NEW."verification_time" := "policy_row"."verification_time";
1173 END IF;
1174 IF NEW."voting_time" ISNULL THEN
1175 NEW."voting_time" := "policy_row"."voting_time";
1176 END IF;
1177 RETURN NEW;
1178 END;
1179 $$;
1181 CREATE TRIGGER "copy_timings" BEFORE INSERT OR UPDATE ON "issue"
1182 FOR EACH ROW EXECUTE PROCEDURE "copy_timings_trigger"();
1184 COMMENT ON FUNCTION "copy_timings_trigger"() IS 'Implementation of trigger "copy_timings" on table "issue"';
1185 COMMENT ON TRIGGER "copy_timings" ON "issue" IS 'If timing fields are NULL, copy values from policy.';
1188 CREATE FUNCTION "copy_autoreject_trigger"()
1189 RETURNS TRIGGER
1190 LANGUAGE 'plpgsql' VOLATILE AS $$
1191 BEGIN
1192 IF NEW."autoreject" ISNULL THEN
1193 SELECT "membership"."autoreject" INTO NEW."autoreject"
1194 FROM "issue" JOIN "membership"
1195 ON "issue"."area_id" = "membership"."area_id"
1196 WHERE "issue"."id" = NEW."issue_id"
1197 AND "membership"."member_id" = NEW."member_id";
1198 END IF;
1199 IF NEW."autoreject" ISNULL THEN
1200 NEW."autoreject" := FALSE;
1201 END IF;
1202 RETURN NEW;
1203 END;
1204 $$;
1206 CREATE TRIGGER "copy_autoreject" BEFORE INSERT OR UPDATE ON "interest"
1207 FOR EACH ROW EXECUTE PROCEDURE "copy_autoreject_trigger"();
1209 COMMENT ON FUNCTION "copy_autoreject_trigger"() IS 'Implementation of trigger "copy_autoreject" on table "interest"';
1210 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';
1213 CREATE FUNCTION "supporter_default_for_draft_id_trigger"()
1214 RETURNS TRIGGER
1215 LANGUAGE 'plpgsql' VOLATILE AS $$
1216 BEGIN
1217 IF NEW."draft_id" ISNULL THEN
1218 SELECT "id" INTO NEW."draft_id" FROM "current_draft"
1219 WHERE "initiative_id" = NEW."initiative_id";
1220 END IF;
1221 RETURN NEW;
1222 END;
1223 $$;
1225 CREATE TRIGGER "default_for_draft_id" BEFORE INSERT OR UPDATE ON "supporter"
1226 FOR EACH ROW EXECUTE PROCEDURE "supporter_default_for_draft_id_trigger"();
1228 COMMENT ON FUNCTION "supporter_default_for_draft_id_trigger"() IS 'Implementation of trigger "default_for_draft" on table "supporter"';
1229 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';
1233 ----------------------------------------
1234 -- Automatic creation of dependencies --
1235 ----------------------------------------
1238 CREATE FUNCTION "autocreate_interest_trigger"()
1239 RETURNS TRIGGER
1240 LANGUAGE 'plpgsql' VOLATILE AS $$
1241 BEGIN
1242 IF NOT EXISTS (
1243 SELECT NULL FROM "initiative" JOIN "interest"
1244 ON "initiative"."issue_id" = "interest"."issue_id"
1245 WHERE "initiative"."id" = NEW."initiative_id"
1246 AND "interest"."member_id" = NEW."member_id"
1247 ) THEN
1248 BEGIN
1249 INSERT INTO "interest" ("issue_id", "member_id")
1250 SELECT "issue_id", NEW."member_id"
1251 FROM "initiative" WHERE "id" = NEW."initiative_id";
1252 EXCEPTION WHEN unique_violation THEN END;
1253 END IF;
1254 RETURN NEW;
1255 END;
1256 $$;
1258 CREATE TRIGGER "autocreate_interest" BEFORE INSERT ON "supporter"
1259 FOR EACH ROW EXECUTE PROCEDURE "autocreate_interest_trigger"();
1261 COMMENT ON FUNCTION "autocreate_interest_trigger"() IS 'Implementation of trigger "autocreate_interest" on table "supporter"';
1262 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';
1265 CREATE FUNCTION "autocreate_supporter_trigger"()
1266 RETURNS TRIGGER
1267 LANGUAGE 'plpgsql' VOLATILE AS $$
1268 BEGIN
1269 IF NOT EXISTS (
1270 SELECT NULL FROM "suggestion" JOIN "supporter"
1271 ON "suggestion"."initiative_id" = "supporter"."initiative_id"
1272 WHERE "suggestion"."id" = NEW."suggestion_id"
1273 AND "supporter"."member_id" = NEW."member_id"
1274 ) THEN
1275 BEGIN
1276 INSERT INTO "supporter" ("initiative_id", "member_id")
1277 SELECT "initiative_id", NEW."member_id"
1278 FROM "suggestion" WHERE "id" = NEW."suggestion_id";
1279 EXCEPTION WHEN unique_violation THEN END;
1280 END IF;
1281 RETURN NEW;
1282 END;
1283 $$;
1285 CREATE TRIGGER "autocreate_supporter" BEFORE INSERT ON "opinion"
1286 FOR EACH ROW EXECUTE PROCEDURE "autocreate_supporter_trigger"();
1288 COMMENT ON FUNCTION "autocreate_supporter_trigger"() IS 'Implementation of trigger "autocreate_supporter" on table "opinion"';
1289 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.';
1293 ------------------------------------------
1294 -- Views and helper functions for views --
1295 ------------------------------------------
1298 CREATE VIEW "active_delegation" AS
1299 SELECT "delegation".* FROM "delegation"
1300 JOIN "member" ON "delegation"."truster_id" = "member"."id"
1301 WHERE "member"."active" = TRUE;
1303 COMMENT ON VIEW "active_delegation" IS 'Delegations where the truster_id refers to an active member';
1306 CREATE VIEW "global_delegation" AS
1307 SELECT "id", "truster_id", "trustee_id"
1308 FROM "active_delegation" WHERE "scope" = 'global';
1310 COMMENT ON VIEW "global_delegation" IS 'Global delegations from active members';
1313 CREATE VIEW "area_delegation" AS
1314 SELECT DISTINCT ON ("area"."id", "delegation"."truster_id")
1315 "area"."id" AS "area_id",
1316 "delegation"."id",
1317 "delegation"."truster_id",
1318 "delegation"."trustee_id",
1319 "delegation"."scope"
1320 FROM "area" JOIN "active_delegation" AS "delegation"
1321 ON "delegation"."scope" = 'global'
1322 OR "delegation"."area_id" = "area"."id"
1323 ORDER BY
1324 "area"."id",
1325 "delegation"."truster_id",
1326 "delegation"."scope" DESC;
1328 COMMENT ON VIEW "area_delegation" IS 'Resulting area delegations from active members';
1331 CREATE VIEW "issue_delegation" AS
1332 SELECT DISTINCT ON ("issue"."id", "delegation"."truster_id")
1333 "issue"."id" AS "issue_id",
1334 "delegation"."id",
1335 "delegation"."truster_id",
1336 "delegation"."trustee_id",
1337 "delegation"."scope"
1338 FROM "issue" JOIN "active_delegation" AS "delegation"
1339 ON "delegation"."scope" = 'global'
1340 OR "delegation"."area_id" = "issue"."area_id"
1341 OR "delegation"."issue_id" = "issue"."id"
1342 ORDER BY
1343 "issue"."id",
1344 "delegation"."truster_id",
1345 "delegation"."scope" DESC;
1347 COMMENT ON VIEW "issue_delegation" IS 'Resulting issue delegations from active members';
1350 CREATE FUNCTION "membership_weight_with_skipping"
1351 ( "area_id_p" "area"."id"%TYPE,
1352 "member_id_p" "member"."id"%TYPE,
1353 "skip_member_ids_p" INT4[] ) -- "member"."id"%TYPE[]
1354 RETURNS INT4
1355 LANGUAGE 'plpgsql' STABLE AS $$
1356 DECLARE
1357 "sum_v" INT4;
1358 "delegation_row" "area_delegation"%ROWTYPE;
1359 BEGIN
1360 "sum_v" := 1;
1361 FOR "delegation_row" IN
1362 SELECT "area_delegation".*
1363 FROM "area_delegation" LEFT JOIN "membership"
1364 ON "membership"."area_id" = "area_id_p"
1365 AND "membership"."member_id" = "area_delegation"."truster_id"
1366 WHERE "area_delegation"."area_id" = "area_id_p"
1367 AND "area_delegation"."trustee_id" = "member_id_p"
1368 AND "membership"."member_id" ISNULL
1369 LOOP
1370 IF NOT
1371 "skip_member_ids_p" @> ARRAY["delegation_row"."truster_id"]
1372 THEN
1373 "sum_v" := "sum_v" + "membership_weight_with_skipping"(
1374 "area_id_p",
1375 "delegation_row"."truster_id",
1376 "skip_member_ids_p" || "delegation_row"."truster_id"
1377 );
1378 END IF;
1379 END LOOP;
1380 RETURN "sum_v";
1381 END;
1382 $$;
1384 COMMENT ON FUNCTION "membership_weight_with_skipping"
1385 ( "area"."id"%TYPE,
1386 "member"."id"%TYPE,
1387 INT4[] )
1388 IS 'Helper function for "membership_weight" function';
1391 CREATE FUNCTION "membership_weight"
1392 ( "area_id_p" "area"."id"%TYPE,
1393 "member_id_p" "member"."id"%TYPE ) -- "member"."id"%TYPE[]
1394 RETURNS INT4
1395 LANGUAGE 'plpgsql' STABLE AS $$
1396 BEGIN
1397 RETURN "membership_weight_with_skipping"(
1398 "area_id_p",
1399 "member_id_p",
1400 ARRAY["member_id_p"]
1401 );
1402 END;
1403 $$;
1405 COMMENT ON FUNCTION "membership_weight"
1406 ( "area"."id"%TYPE,
1407 "member"."id"%TYPE )
1408 IS 'Calculates the potential voting weight of a member in a given area';
1411 CREATE VIEW "member_count_view" AS
1412 SELECT count(1) AS "total_count" FROM "member" WHERE "active";
1414 COMMENT ON VIEW "member_count_view" IS 'View used to update "member_count" table';
1417 CREATE VIEW "area_member_count" AS
1418 SELECT
1419 "area"."id" AS "area_id",
1420 count("member"."id") AS "direct_member_count",
1421 coalesce(
1422 sum(
1423 CASE WHEN "member"."id" NOTNULL THEN
1424 "membership_weight"("area"."id", "member"."id")
1425 ELSE 0 END
1427 ) AS "member_weight",
1428 coalesce(
1429 sum(
1430 CASE WHEN "member"."id" NOTNULL AND "membership"."autoreject" THEN
1431 "membership_weight"("area"."id", "member"."id")
1432 ELSE 0 END
1434 ) AS "autoreject_weight"
1435 FROM "area"
1436 LEFT JOIN "membership"
1437 ON "area"."id" = "membership"."area_id"
1438 LEFT JOIN "member"
1439 ON "membership"."member_id" = "member"."id"
1440 AND "member"."active"
1441 GROUP BY "area"."id";
1443 COMMENT ON VIEW "area_member_count" IS 'View used to update "member_count" column of table "area"';
1446 CREATE VIEW "opening_draft" AS
1447 SELECT "draft".* FROM (
1448 SELECT
1449 "initiative"."id" AS "initiative_id",
1450 min("draft"."id") AS "draft_id"
1451 FROM "initiative" JOIN "draft"
1452 ON "initiative"."id" = "draft"."initiative_id"
1453 GROUP BY "initiative"."id"
1454 ) AS "subquery"
1455 JOIN "draft" ON "subquery"."draft_id" = "draft"."id";
1457 COMMENT ON VIEW "opening_draft" IS 'First drafts of all initiatives';
1460 CREATE VIEW "current_draft" AS
1461 SELECT "draft".* FROM (
1462 SELECT
1463 "initiative"."id" AS "initiative_id",
1464 max("draft"."id") AS "draft_id"
1465 FROM "initiative" JOIN "draft"
1466 ON "initiative"."id" = "draft"."initiative_id"
1467 GROUP BY "initiative"."id"
1468 ) AS "subquery"
1469 JOIN "draft" ON "subquery"."draft_id" = "draft"."id";
1471 COMMENT ON VIEW "current_draft" IS 'All latest drafts for each initiative';
1474 CREATE VIEW "critical_opinion" AS
1475 SELECT * FROM "opinion"
1476 WHERE ("degree" = 2 AND "fulfilled" = FALSE)
1477 OR ("degree" = -2 AND "fulfilled" = TRUE);
1479 COMMENT ON VIEW "critical_opinion" IS 'Opinions currently causing dissatisfaction';
1482 CREATE VIEW "battle_view" AS
1483 SELECT
1484 "issue"."id" AS "issue_id",
1485 "winning_initiative"."id" AS "winning_initiative_id",
1486 "losing_initiative"."id" AS "losing_initiative_id",
1487 sum(
1488 CASE WHEN
1489 coalesce("better_vote"."grade", 0) >
1490 coalesce("worse_vote"."grade", 0)
1491 THEN "direct_voter"."weight" ELSE 0 END
1492 ) AS "count"
1493 FROM "issue"
1494 LEFT JOIN "direct_voter"
1495 ON "issue"."id" = "direct_voter"."issue_id"
1496 JOIN "initiative" AS "winning_initiative"
1497 ON "issue"."id" = "winning_initiative"."issue_id"
1498 AND "winning_initiative"."agreed"
1499 JOIN "initiative" AS "losing_initiative"
1500 ON "issue"."id" = "losing_initiative"."issue_id"
1501 AND "losing_initiative"."agreed"
1502 LEFT JOIN "vote" AS "better_vote"
1503 ON "direct_voter"."member_id" = "better_vote"."member_id"
1504 AND "winning_initiative"."id" = "better_vote"."initiative_id"
1505 LEFT JOIN "vote" AS "worse_vote"
1506 ON "direct_voter"."member_id" = "worse_vote"."member_id"
1507 AND "losing_initiative"."id" = "worse_vote"."initiative_id"
1508 WHERE "issue"."closed" NOTNULL
1509 AND "issue"."cleaned" ISNULL
1510 AND "winning_initiative"."id" != "losing_initiative"."id"
1511 GROUP BY
1512 "issue"."id",
1513 "winning_initiative"."id",
1514 "losing_initiative"."id";
1516 COMMENT ON VIEW "battle_view" IS 'Number of members preferring one initiative to another; Used to fill "battle" table';
1519 CREATE VIEW "expired_session" AS
1520 SELECT * FROM "session" WHERE now() > "expiry";
1522 CREATE RULE "delete" AS ON DELETE TO "expired_session" DO INSTEAD
1523 DELETE FROM "session" WHERE "ident" = OLD."ident";
1525 COMMENT ON VIEW "expired_session" IS 'View containing all expired sessions where DELETE is possible';
1526 COMMENT ON RULE "delete" ON "expired_session" IS 'Rule allowing DELETE on rows in "expired_session" view, i.e. DELETE FROM "expired_session"';
1529 CREATE VIEW "open_issue" AS
1530 SELECT * FROM "issue" WHERE "closed" ISNULL;
1532 COMMENT ON VIEW "open_issue" IS 'All open issues';
1535 CREATE VIEW "issue_with_ranks_missing" AS
1536 SELECT * FROM "issue"
1537 WHERE "fully_frozen" NOTNULL
1538 AND "closed" NOTNULL
1539 AND "ranks_available" = FALSE;
1541 COMMENT ON VIEW "issue_with_ranks_missing" IS 'Issues where voting was finished, but no ranks have been calculated yet';
1544 CREATE VIEW "member_contingent" AS
1545 SELECT
1546 "member"."id" AS "member_id",
1547 "contingent"."time_frame",
1548 CASE WHEN "contingent"."text_entry_limit" NOTNULL THEN
1550 SELECT count(1) FROM "draft"
1551 WHERE "draft"."author_id" = "member"."id"
1552 AND "draft"."created" > now() - "contingent"."time_frame"
1553 ) + (
1554 SELECT count(1) FROM "suggestion"
1555 WHERE "suggestion"."author_id" = "member"."id"
1556 AND "suggestion"."created" > now() - "contingent"."time_frame"
1558 ELSE NULL END AS "text_entry_count",
1559 "contingent"."text_entry_limit",
1560 CASE WHEN "contingent"."initiative_limit" NOTNULL THEN (
1561 SELECT count(1) FROM "opening_draft"
1562 WHERE "opening_draft"."author_id" = "member"."id"
1563 AND "opening_draft"."created" > now() - "contingent"."time_frame"
1564 ) ELSE NULL END AS "initiative_count",
1565 "contingent"."initiative_limit"
1566 FROM "member" CROSS JOIN "contingent";
1568 COMMENT ON VIEW "member_contingent" IS 'Actual counts of text entries and initiatives are calculated per member for each limit in the "contingent" table.';
1570 COMMENT ON COLUMN "member_contingent"."text_entry_count" IS 'Only calculated when "text_entry_limit" is not null in the same row';
1571 COMMENT ON COLUMN "member_contingent"."initiative_count" IS 'Only calculated when "initiative_limit" is not null in the same row';
1574 CREATE VIEW "member_contingent_left" AS
1575 SELECT
1576 "member_id",
1577 max("text_entry_limit" - "text_entry_count") AS "text_entries_left",
1578 max("initiative_limit" - "initiative_count") AS "initiatives_left"
1579 FROM "member_contingent" GROUP BY "member_id";
1581 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.';
1584 CREATE TYPE "timeline_event" AS ENUM (
1585 'issue_created',
1586 'issue_canceled',
1587 'issue_accepted',
1588 'issue_half_frozen',
1589 'issue_finished_without_voting',
1590 'issue_voting_started',
1591 'issue_finished_after_voting',
1592 'initiative_created',
1593 'initiative_revoked',
1594 'draft_created',
1595 'suggestion_created');
1597 COMMENT ON TYPE "timeline_event" IS 'Types of event in timeline tables';
1600 CREATE VIEW "timeline_issue" AS
1601 SELECT
1602 "created" AS "occurrence",
1603 'issue_created'::"timeline_event" AS "event",
1604 "id" AS "issue_id"
1605 FROM "issue"
1606 UNION ALL
1607 SELECT
1608 "closed" AS "occurrence",
1609 'issue_canceled'::"timeline_event" AS "event",
1610 "id" AS "issue_id"
1611 FROM "issue" WHERE "closed" NOTNULL AND "fully_frozen" ISNULL
1612 UNION ALL
1613 SELECT
1614 "accepted" AS "occurrence",
1615 'issue_accepted'::"timeline_event" AS "event",
1616 "id" AS "issue_id"
1617 FROM "issue" WHERE "accepted" NOTNULL
1618 UNION ALL
1619 SELECT
1620 "half_frozen" AS "occurrence",
1621 'issue_half_frozen'::"timeline_event" AS "event",
1622 "id" AS "issue_id"
1623 FROM "issue" WHERE "half_frozen" NOTNULL
1624 UNION ALL
1625 SELECT
1626 "fully_frozen" AS "occurrence",
1627 'issue_voting_started'::"timeline_event" AS "event",
1628 "id" AS "issue_id"
1629 FROM "issue"
1630 WHERE "fully_frozen" NOTNULL
1631 AND ("closed" ISNULL OR "closed" != "fully_frozen")
1632 UNION ALL
1633 SELECT
1634 "closed" AS "occurrence",
1635 CASE WHEN "fully_frozen" = "closed" THEN
1636 'issue_finished_without_voting'::"timeline_event"
1637 ELSE
1638 'issue_finished_after_voting'::"timeline_event"
1639 END AS "event",
1640 "id" AS "issue_id"
1641 FROM "issue" WHERE "closed" NOTNULL AND "fully_frozen" NOTNULL;
1643 COMMENT ON VIEW "timeline_issue" IS 'Helper view for "timeline" view';
1646 CREATE VIEW "timeline_initiative" AS
1647 SELECT
1648 "created" AS "occurrence",
1649 'initiative_created'::"timeline_event" AS "event",
1650 "id" AS "initiative_id"
1651 FROM "initiative"
1652 UNION ALL
1653 SELECT
1654 "revoked" AS "occurrence",
1655 'initiative_revoked'::"timeline_event" AS "event",
1656 "id" AS "initiative_id"
1657 FROM "initiative" WHERE "revoked" NOTNULL;
1659 COMMENT ON VIEW "timeline_initiative" IS 'Helper view for "timeline" view';
1662 CREATE VIEW "timeline_draft" AS
1663 SELECT
1664 "created" AS "occurrence",
1665 'draft_created'::"timeline_event" AS "event",
1666 "id" AS "draft_id"
1667 FROM "draft";
1669 COMMENT ON VIEW "timeline_draft" IS 'Helper view for "timeline" view';
1672 CREATE VIEW "timeline_suggestion" AS
1673 SELECT
1674 "created" AS "occurrence",
1675 'suggestion_created'::"timeline_event" AS "event",
1676 "id" AS "suggestion_id"
1677 FROM "suggestion";
1679 COMMENT ON VIEW "timeline_suggestion" IS 'Helper view for "timeline" view';
1682 CREATE VIEW "timeline" AS
1683 SELECT
1684 "occurrence",
1685 "event",
1686 "issue_id",
1687 NULL AS "initiative_id",
1688 NULL::INT8 AS "draft_id", -- TODO: Why do we need a type-cast here? Is this due to 32 bit architecture?
1689 NULL::INT8 AS "suggestion_id"
1690 FROM "timeline_issue"
1691 UNION ALL
1692 SELECT
1693 "occurrence",
1694 "event",
1695 NULL AS "issue_id",
1696 "initiative_id",
1697 NULL AS "draft_id",
1698 NULL AS "suggestion_id"
1699 FROM "timeline_initiative"
1700 UNION ALL
1701 SELECT
1702 "occurrence",
1703 "event",
1704 NULL AS "issue_id",
1705 NULL AS "initiative_id",
1706 "draft_id",
1707 NULL AS "suggestion_id"
1708 FROM "timeline_draft"
1709 UNION ALL
1710 SELECT
1711 "occurrence",
1712 "event",
1713 NULL AS "issue_id",
1714 NULL AS "initiative_id",
1715 NULL AS "draft_id",
1716 "suggestion_id"
1717 FROM "timeline_suggestion";
1719 COMMENT ON VIEW "timeline" IS 'Aggregation of different events in the system';
1723 --------------------------------------------------
1724 -- Set returning function for delegation chains --
1725 --------------------------------------------------
1728 CREATE TYPE "delegation_chain_loop_tag" AS ENUM
1729 ('first', 'intermediate', 'last', 'repetition');
1731 COMMENT ON TYPE "delegation_chain_loop_tag" IS 'Type for loop tags in "delegation_chain_row" type';
1734 CREATE TYPE "delegation_chain_row" AS (
1735 "index" INT4,
1736 "member_id" INT4,
1737 "member_active" BOOLEAN,
1738 "participation" BOOLEAN,
1739 "overridden" BOOLEAN,
1740 "scope_in" "delegation_scope",
1741 "scope_out" "delegation_scope",
1742 "loop" "delegation_chain_loop_tag" );
1744 COMMENT ON TYPE "delegation_chain_row" IS 'Type of rows returned by "delegation_chain"(...) functions';
1746 COMMENT ON COLUMN "delegation_chain_row"."index" IS 'Index starting with 0 and counting up';
1747 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';
1748 COMMENT ON COLUMN "delegation_chain_row"."overridden" IS 'True, if an entry with lower index has "participation" set to true';
1749 COMMENT ON COLUMN "delegation_chain_row"."scope_in" IS 'Scope of used incoming delegation';
1750 COMMENT ON COLUMN "delegation_chain_row"."scope_out" IS 'Scope of used outgoing delegation';
1751 COMMENT ON COLUMN "delegation_chain_row"."loop" IS 'Not null, if member is part of a loop, see "delegation_chain_loop_tag" type';
1754 CREATE FUNCTION "delegation_chain"
1755 ( "member_id_p" "member"."id"%TYPE,
1756 "area_id_p" "area"."id"%TYPE,
1757 "issue_id_p" "issue"."id"%TYPE,
1758 "simulate_trustee_id_p" "member"."id"%TYPE )
1759 RETURNS SETOF "delegation_chain_row"
1760 LANGUAGE 'plpgsql' STABLE AS $$
1761 DECLARE
1762 "issue_row" "issue"%ROWTYPE;
1763 "visited_member_ids" INT4[]; -- "member"."id"%TYPE[]
1764 "loop_member_id_v" "member"."id"%TYPE;
1765 "output_row" "delegation_chain_row";
1766 "output_rows" "delegation_chain_row"[];
1767 "delegation_row" "delegation"%ROWTYPE;
1768 "row_count" INT4;
1769 "i" INT4;
1770 "loop_v" BOOLEAN;
1771 BEGIN
1772 SELECT * INTO "issue_row" FROM "issue" WHERE "id" = "issue_id_p";
1773 "visited_member_ids" := '{}';
1774 "loop_member_id_v" := NULL;
1775 "output_rows" := '{}';
1776 "output_row"."index" := 0;
1777 "output_row"."member_id" := "member_id_p";
1778 "output_row"."member_active" := TRUE;
1779 "output_row"."participation" := FALSE;
1780 "output_row"."overridden" := FALSE;
1781 "output_row"."scope_out" := NULL;
1782 LOOP
1783 IF "visited_member_ids" @> ARRAY["output_row"."member_id"] THEN
1784 "loop_member_id_v" := "output_row"."member_id";
1785 ELSE
1786 "visited_member_ids" :=
1787 "visited_member_ids" || "output_row"."member_id";
1788 END IF;
1789 IF "output_row"."participation" THEN
1790 "output_row"."overridden" := TRUE;
1791 END IF;
1792 "output_row"."scope_in" := "output_row"."scope_out";
1793 IF EXISTS (
1794 SELECT NULL FROM "member"
1795 WHERE "id" = "output_row"."member_id" AND "active"
1796 ) THEN
1797 IF "area_id_p" ISNULL AND "issue_id_p" ISNULL THEN
1798 SELECT * INTO "delegation_row" FROM "delegation"
1799 WHERE "truster_id" = "output_row"."member_id"
1800 AND "scope" = 'global';
1801 ELSIF "area_id_p" NOTNULL AND "issue_id_p" ISNULL THEN
1802 "output_row"."participation" := EXISTS (
1803 SELECT NULL FROM "membership"
1804 WHERE "area_id" = "area_id_p"
1805 AND "member_id" = "output_row"."member_id"
1806 );
1807 SELECT * INTO "delegation_row" FROM "delegation"
1808 WHERE "truster_id" = "output_row"."member_id"
1809 AND ("scope" = 'global' OR "area_id" = "area_id_p")
1810 ORDER BY "scope" DESC;
1811 ELSIF "area_id_p" ISNULL AND "issue_id_p" NOTNULL THEN
1812 "output_row"."participation" := EXISTS (
1813 SELECT NULL FROM "interest"
1814 WHERE "issue_id" = "issue_id_p"
1815 AND "member_id" = "output_row"."member_id"
1816 );
1817 SELECT * INTO "delegation_row" FROM "delegation"
1818 WHERE "truster_id" = "output_row"."member_id"
1819 AND ("scope" = 'global' OR
1820 "area_id" = "issue_row"."area_id" OR
1821 "issue_id" = "issue_id_p"
1823 ORDER BY "scope" DESC;
1824 ELSE
1825 RAISE EXCEPTION 'Either area_id or issue_id or both must be NULL.';
1826 END IF;
1827 ELSE
1828 "output_row"."member_active" := FALSE;
1829 "output_row"."participation" := FALSE;
1830 "output_row"."scope_out" := NULL;
1831 "delegation_row" := ROW(NULL);
1832 END IF;
1833 IF
1834 "output_row"."member_id" = "member_id_p" AND
1835 "simulate_trustee_id_p" NOTNULL
1836 THEN
1837 "output_row"."scope_out" := CASE
1838 WHEN "area_id_p" ISNULL AND "issue_id_p" ISNULL THEN 'global'
1839 WHEN "area_id_p" NOTNULL AND "issue_id_p" ISNULL THEN 'area'
1840 WHEN "area_id_p" ISNULL AND "issue_id_p" NOTNULL THEN 'issue'
1841 END;
1842 "output_rows" := "output_rows" || "output_row";
1843 "output_row"."member_id" := "simulate_trustee_id_p";
1844 ELSIF "delegation_row"."trustee_id" NOTNULL THEN
1845 "output_row"."scope_out" := "delegation_row"."scope";
1846 "output_rows" := "output_rows" || "output_row";
1847 "output_row"."member_id" := "delegation_row"."trustee_id";
1848 ELSE
1849 "output_row"."scope_out" := NULL;
1850 "output_rows" := "output_rows" || "output_row";
1851 EXIT;
1852 END IF;
1853 EXIT WHEN "loop_member_id_v" NOTNULL;
1854 "output_row"."index" := "output_row"."index" + 1;
1855 END LOOP;
1856 "row_count" := array_upper("output_rows", 1);
1857 "i" := 1;
1858 "loop_v" := FALSE;
1859 LOOP
1860 "output_row" := "output_rows"["i"];
1861 EXIT WHEN "output_row"."member_id" ISNULL;
1862 IF "loop_v" THEN
1863 IF "i" + 1 = "row_count" THEN
1864 "output_row"."loop" := 'last';
1865 ELSIF "i" = "row_count" THEN
1866 "output_row"."loop" := 'repetition';
1867 ELSE
1868 "output_row"."loop" := 'intermediate';
1869 END IF;
1870 ELSIF "output_row"."member_id" = "loop_member_id_v" THEN
1871 "output_row"."loop" := 'first';
1872 "loop_v" := TRUE;
1873 END IF;
1874 IF "area_id_p" ISNULL AND "issue_id_p" ISNULL THEN
1875 "output_row"."participation" := NULL;
1876 END IF;
1877 RETURN NEXT "output_row";
1878 "i" := "i" + 1;
1879 END LOOP;
1880 RETURN;
1881 END;
1882 $$;
1884 COMMENT ON FUNCTION "delegation_chain"
1885 ( "member"."id"%TYPE,
1886 "area"."id"%TYPE,
1887 "issue"."id"%TYPE,
1888 "member"."id"%TYPE )
1889 IS 'Helper function for frontends to display delegation chains; Not part of internal voting logic';
1891 CREATE FUNCTION "delegation_chain"
1892 ( "member_id_p" "member"."id"%TYPE,
1893 "area_id_p" "area"."id"%TYPE,
1894 "issue_id_p" "issue"."id"%TYPE )
1895 RETURNS SETOF "delegation_chain_row"
1896 LANGUAGE 'plpgsql' STABLE AS $$
1897 DECLARE
1898 "result_row" "delegation_chain_row";
1899 BEGIN
1900 FOR "result_row" IN
1901 SELECT * FROM "delegation_chain"(
1902 "member_id_p", "area_id_p", "issue_id_p", NULL
1904 LOOP
1905 RETURN NEXT "result_row";
1906 END LOOP;
1907 RETURN;
1908 END;
1909 $$;
1911 COMMENT ON FUNCTION "delegation_chain"
1912 ( "member"."id"%TYPE,
1913 "area"."id"%TYPE,
1914 "issue"."id"%TYPE )
1915 IS 'Shortcut for "delegation_chain"(...) function where 4th parameter is null';
1919 ------------------------------
1920 -- Comparison by vote count --
1921 ------------------------------
1923 CREATE FUNCTION "vote_ratio"
1924 ( "positive_votes_p" "initiative"."positive_votes"%TYPE,
1925 "negative_votes_p" "initiative"."negative_votes"%TYPE )
1926 RETURNS FLOAT8
1927 LANGUAGE 'plpgsql' STABLE AS $$
1928 BEGIN
1929 IF "positive_votes_p" > 0 AND "negative_votes_p" > 0 THEN
1930 RETURN
1931 "positive_votes_p"::FLOAT8 /
1932 ("positive_votes_p" + "negative_votes_p")::FLOAT8;
1933 ELSIF "positive_votes_p" > 0 THEN
1934 RETURN "positive_votes_p";
1935 ELSIF "negative_votes_p" > 0 THEN
1936 RETURN 1 - "negative_votes_p";
1937 ELSE
1938 RETURN 0.5;
1939 END IF;
1940 END;
1941 $$;
1943 COMMENT ON FUNCTION "vote_ratio"
1944 ( "initiative"."positive_votes"%TYPE,
1945 "initiative"."negative_votes"%TYPE )
1946 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.';
1950 ------------------------------------------------
1951 -- Locking for snapshots and voting procedure --
1952 ------------------------------------------------
1955 CREATE FUNCTION "share_row_lock_issue_trigger"()
1956 RETURNS TRIGGER
1957 LANGUAGE 'plpgsql' VOLATILE AS $$
1958 BEGIN
1959 IF TG_OP = 'UPDATE' OR TG_OP = 'DELETE' THEN
1960 PERFORM NULL FROM "issue" WHERE "id" = OLD."issue_id" FOR SHARE;
1961 END IF;
1962 IF TG_OP = 'INSERT' OR TG_OP = 'UPDATE' THEN
1963 PERFORM NULL FROM "issue" WHERE "id" = NEW."issue_id" FOR SHARE;
1964 RETURN NEW;
1965 ELSE
1966 RETURN OLD;
1967 END IF;
1968 END;
1969 $$;
1971 COMMENT ON FUNCTION "share_row_lock_issue_trigger"() IS 'Implementation of triggers "share_row_lock_issue" on multiple tables';
1974 CREATE FUNCTION "share_row_lock_issue_via_initiative_trigger"()
1975 RETURNS TRIGGER
1976 LANGUAGE 'plpgsql' VOLATILE AS $$
1977 BEGIN
1978 IF TG_OP = 'UPDATE' OR TG_OP = 'DELETE' THEN
1979 PERFORM NULL FROM "issue"
1980 JOIN "initiative" ON "issue"."id" = "initiative"."issue_id"
1981 WHERE "initiative"."id" = OLD."initiative_id"
1982 FOR SHARE OF "issue";
1983 END IF;
1984 IF TG_OP = 'INSERT' OR TG_OP = 'UPDATE' THEN
1985 PERFORM NULL FROM "issue"
1986 JOIN "initiative" ON "issue"."id" = "initiative"."issue_id"
1987 WHERE "initiative"."id" = NEW."initiative_id"
1988 FOR SHARE OF "issue";
1989 RETURN NEW;
1990 ELSE
1991 RETURN OLD;
1992 END IF;
1993 END;
1994 $$;
1996 COMMENT ON FUNCTION "share_row_lock_issue_trigger"() IS 'Implementation of trigger "share_row_lock_issue_via_initiative" on table "opinion"';
1999 CREATE TRIGGER "share_row_lock_issue"
2000 BEFORE INSERT OR UPDATE OR DELETE ON "initiative"
2001 FOR EACH ROW EXECUTE PROCEDURE
2002 "share_row_lock_issue_trigger"();
2004 CREATE TRIGGER "share_row_lock_issue"
2005 BEFORE INSERT OR UPDATE OR DELETE ON "interest"
2006 FOR EACH ROW EXECUTE PROCEDURE
2007 "share_row_lock_issue_trigger"();
2009 CREATE TRIGGER "share_row_lock_issue"
2010 BEFORE INSERT OR UPDATE OR DELETE ON "supporter"
2011 FOR EACH ROW EXECUTE PROCEDURE
2012 "share_row_lock_issue_trigger"();
2014 CREATE TRIGGER "share_row_lock_issue_via_initiative"
2015 BEFORE INSERT OR UPDATE OR DELETE ON "opinion"
2016 FOR EACH ROW EXECUTE PROCEDURE
2017 "share_row_lock_issue_via_initiative_trigger"();
2019 CREATE TRIGGER "share_row_lock_issue"
2020 BEFORE INSERT OR UPDATE OR DELETE ON "direct_voter"
2021 FOR EACH ROW EXECUTE PROCEDURE
2022 "share_row_lock_issue_trigger"();
2024 CREATE TRIGGER "share_row_lock_issue"
2025 BEFORE INSERT OR UPDATE OR DELETE ON "delegating_voter"
2026 FOR EACH ROW EXECUTE PROCEDURE
2027 "share_row_lock_issue_trigger"();
2029 CREATE TRIGGER "share_row_lock_issue"
2030 BEFORE INSERT OR UPDATE OR DELETE ON "vote"
2031 FOR EACH ROW EXECUTE PROCEDURE
2032 "share_row_lock_issue_trigger"();
2034 COMMENT ON TRIGGER "share_row_lock_issue" ON "initiative" IS 'See "lock_issue" function';
2035 COMMENT ON TRIGGER "share_row_lock_issue" ON "interest" IS 'See "lock_issue" function';
2036 COMMENT ON TRIGGER "share_row_lock_issue" ON "supporter" IS 'See "lock_issue" function';
2037 COMMENT ON TRIGGER "share_row_lock_issue_via_initiative" ON "opinion" IS 'See "lock_issue" function';
2038 COMMENT ON TRIGGER "share_row_lock_issue" ON "direct_voter" IS 'See "lock_issue" function';
2039 COMMENT ON TRIGGER "share_row_lock_issue" ON "delegating_voter" IS 'See "lock_issue" function';
2040 COMMENT ON TRIGGER "share_row_lock_issue" ON "vote" IS 'See "lock_issue" function';
2043 CREATE FUNCTION "lock_issue"
2044 ( "issue_id_p" "issue"."id"%TYPE )
2045 RETURNS VOID
2046 LANGUAGE 'plpgsql' VOLATILE AS $$
2047 BEGIN
2048 LOCK TABLE "member" IN SHARE MODE;
2049 LOCK TABLE "membership" IN SHARE MODE;
2050 LOCK TABLE "policy" IN SHARE MODE;
2051 PERFORM NULL FROM "issue" WHERE "id" = "issue_id_p" FOR UPDATE;
2052 -- NOTE: The row-level exclusive lock in combination with the
2053 -- share_row_lock_issue(_via_initiative)_trigger functions (which
2054 -- acquire a row-level share lock on the issue) ensure that no data
2055 -- is changed, which could affect calculation of snapshots or
2056 -- counting of votes. Table "delegation" must be table-level-locked,
2057 -- as it also contains issue- and global-scope delegations.
2058 LOCK TABLE "delegation" IN SHARE MODE;
2059 LOCK TABLE "direct_population_snapshot" IN EXCLUSIVE MODE;
2060 LOCK TABLE "delegating_population_snapshot" IN EXCLUSIVE MODE;
2061 LOCK TABLE "direct_interest_snapshot" IN EXCLUSIVE MODE;
2062 LOCK TABLE "delegating_interest_snapshot" IN EXCLUSIVE MODE;
2063 LOCK TABLE "direct_supporter_snapshot" IN EXCLUSIVE MODE;
2064 RETURN;
2065 END;
2066 $$;
2068 COMMENT ON FUNCTION "lock_issue"
2069 ( "issue"."id"%TYPE )
2070 IS 'Locks the issue and all other data which is used for calculating snapshots or counting votes.';
2074 -------------------------------
2075 -- Materialize member counts --
2076 -------------------------------
2078 CREATE FUNCTION "calculate_member_counts"()
2079 RETURNS VOID
2080 LANGUAGE 'plpgsql' VOLATILE AS $$
2081 BEGIN
2082 LOCK TABLE "member" IN SHARE MODE;
2083 LOCK TABLE "member_count" IN EXCLUSIVE MODE;
2084 LOCK TABLE "area" IN EXCLUSIVE MODE;
2085 LOCK TABLE "membership" IN SHARE MODE;
2086 DELETE FROM "member_count";
2087 INSERT INTO "member_count" ("total_count")
2088 SELECT "total_count" FROM "member_count_view";
2089 UPDATE "area" SET
2090 "direct_member_count" = "view"."direct_member_count",
2091 "member_weight" = "view"."member_weight",
2092 "autoreject_weight" = "view"."autoreject_weight"
2093 FROM "area_member_count" AS "view"
2094 WHERE "view"."area_id" = "area"."id";
2095 RETURN;
2096 END;
2097 $$;
2099 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"';
2103 ------------------------------
2104 -- Calculation of snapshots --
2105 ------------------------------
2107 CREATE FUNCTION "weight_of_added_delegations_for_population_snapshot"
2108 ( "issue_id_p" "issue"."id"%TYPE,
2109 "member_id_p" "member"."id"%TYPE,
2110 "delegate_member_ids_p" "delegating_population_snapshot"."delegate_member_ids"%TYPE )
2111 RETURNS "direct_population_snapshot"."weight"%TYPE
2112 LANGUAGE 'plpgsql' VOLATILE AS $$
2113 DECLARE
2114 "issue_delegation_row" "issue_delegation"%ROWTYPE;
2115 "delegate_member_ids_v" "delegating_population_snapshot"."delegate_member_ids"%TYPE;
2116 "weight_v" INT4;
2117 "sub_weight_v" INT4;
2118 BEGIN
2119 "weight_v" := 0;
2120 FOR "issue_delegation_row" IN
2121 SELECT * FROM "issue_delegation"
2122 WHERE "trustee_id" = "member_id_p"
2123 AND "issue_id" = "issue_id_p"
2124 LOOP
2125 IF NOT EXISTS (
2126 SELECT NULL FROM "direct_population_snapshot"
2127 WHERE "issue_id" = "issue_id_p"
2128 AND "event" = 'periodic'
2129 AND "member_id" = "issue_delegation_row"."truster_id"
2130 ) AND NOT EXISTS (
2131 SELECT NULL FROM "delegating_population_snapshot"
2132 WHERE "issue_id" = "issue_id_p"
2133 AND "event" = 'periodic'
2134 AND "member_id" = "issue_delegation_row"."truster_id"
2135 ) THEN
2136 "delegate_member_ids_v" :=
2137 "member_id_p" || "delegate_member_ids_p";
2138 INSERT INTO "delegating_population_snapshot" (
2139 "issue_id",
2140 "event",
2141 "member_id",
2142 "scope",
2143 "delegate_member_ids"
2144 ) VALUES (
2145 "issue_id_p",
2146 'periodic',
2147 "issue_delegation_row"."truster_id",
2148 "issue_delegation_row"."scope",
2149 "delegate_member_ids_v"
2150 );
2151 "sub_weight_v" := 1 +
2152 "weight_of_added_delegations_for_population_snapshot"(
2153 "issue_id_p",
2154 "issue_delegation_row"."truster_id",
2155 "delegate_member_ids_v"
2156 );
2157 UPDATE "delegating_population_snapshot"
2158 SET "weight" = "sub_weight_v"
2159 WHERE "issue_id" = "issue_id_p"
2160 AND "event" = 'periodic'
2161 AND "member_id" = "issue_delegation_row"."truster_id";
2162 "weight_v" := "weight_v" + "sub_weight_v";
2163 END IF;
2164 END LOOP;
2165 RETURN "weight_v";
2166 END;
2167 $$;
2169 COMMENT ON FUNCTION "weight_of_added_delegations_for_population_snapshot"
2170 ( "issue"."id"%TYPE,
2171 "member"."id"%TYPE,
2172 "delegating_population_snapshot"."delegate_member_ids"%TYPE )
2173 IS 'Helper function for "create_population_snapshot" function';
2176 CREATE FUNCTION "create_population_snapshot"
2177 ( "issue_id_p" "issue"."id"%TYPE )
2178 RETURNS VOID
2179 LANGUAGE 'plpgsql' VOLATILE AS $$
2180 DECLARE
2181 "member_id_v" "member"."id"%TYPE;
2182 BEGIN
2183 DELETE FROM "direct_population_snapshot"
2184 WHERE "issue_id" = "issue_id_p"
2185 AND "event" = 'periodic';
2186 DELETE FROM "delegating_population_snapshot"
2187 WHERE "issue_id" = "issue_id_p"
2188 AND "event" = 'periodic';
2189 INSERT INTO "direct_population_snapshot"
2190 ("issue_id", "event", "member_id")
2191 SELECT
2192 "issue_id_p" AS "issue_id",
2193 'periodic'::"snapshot_event" AS "event",
2194 "member"."id" AS "member_id"
2195 FROM "issue"
2196 JOIN "area" ON "issue"."area_id" = "area"."id"
2197 JOIN "membership" ON "area"."id" = "membership"."area_id"
2198 JOIN "member" ON "membership"."member_id" = "member"."id"
2199 WHERE "issue"."id" = "issue_id_p"
2200 AND "member"."active"
2201 UNION
2202 SELECT
2203 "issue_id_p" AS "issue_id",
2204 'periodic'::"snapshot_event" AS "event",
2205 "member"."id" AS "member_id"
2206 FROM "interest" JOIN "member"
2207 ON "interest"."member_id" = "member"."id"
2208 WHERE "interest"."issue_id" = "issue_id_p"
2209 AND "member"."active";
2210 FOR "member_id_v" IN
2211 SELECT "member_id" FROM "direct_population_snapshot"
2212 WHERE "issue_id" = "issue_id_p"
2213 AND "event" = 'periodic'
2214 LOOP
2215 UPDATE "direct_population_snapshot" SET
2216 "weight" = 1 +
2217 "weight_of_added_delegations_for_population_snapshot"(
2218 "issue_id_p",
2219 "member_id_v",
2220 '{}'
2222 WHERE "issue_id" = "issue_id_p"
2223 AND "event" = 'periodic'
2224 AND "member_id" = "member_id_v";
2225 END LOOP;
2226 RETURN;
2227 END;
2228 $$;
2230 COMMENT ON FUNCTION "create_population_snapshot"
2231 ( "issue"."id"%TYPE )
2232 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.';
2235 CREATE FUNCTION "weight_of_added_delegations_for_interest_snapshot"
2236 ( "issue_id_p" "issue"."id"%TYPE,
2237 "member_id_p" "member"."id"%TYPE,
2238 "delegate_member_ids_p" "delegating_interest_snapshot"."delegate_member_ids"%TYPE )
2239 RETURNS "direct_interest_snapshot"."weight"%TYPE
2240 LANGUAGE 'plpgsql' VOLATILE AS $$
2241 DECLARE
2242 "issue_delegation_row" "issue_delegation"%ROWTYPE;
2243 "delegate_member_ids_v" "delegating_interest_snapshot"."delegate_member_ids"%TYPE;
2244 "weight_v" INT4;
2245 "sub_weight_v" INT4;
2246 BEGIN
2247 "weight_v" := 0;
2248 FOR "issue_delegation_row" IN
2249 SELECT * FROM "issue_delegation"
2250 WHERE "trustee_id" = "member_id_p"
2251 AND "issue_id" = "issue_id_p"
2252 LOOP
2253 IF NOT EXISTS (
2254 SELECT NULL FROM "direct_interest_snapshot"
2255 WHERE "issue_id" = "issue_id_p"
2256 AND "event" = 'periodic'
2257 AND "member_id" = "issue_delegation_row"."truster_id"
2258 ) AND NOT EXISTS (
2259 SELECT NULL FROM "delegating_interest_snapshot"
2260 WHERE "issue_id" = "issue_id_p"
2261 AND "event" = 'periodic'
2262 AND "member_id" = "issue_delegation_row"."truster_id"
2263 ) THEN
2264 "delegate_member_ids_v" :=
2265 "member_id_p" || "delegate_member_ids_p";
2266 INSERT INTO "delegating_interest_snapshot" (
2267 "issue_id",
2268 "event",
2269 "member_id",
2270 "scope",
2271 "delegate_member_ids"
2272 ) VALUES (
2273 "issue_id_p",
2274 'periodic',
2275 "issue_delegation_row"."truster_id",
2276 "issue_delegation_row"."scope",
2277 "delegate_member_ids_v"
2278 );
2279 "sub_weight_v" := 1 +
2280 "weight_of_added_delegations_for_interest_snapshot"(
2281 "issue_id_p",
2282 "issue_delegation_row"."truster_id",
2283 "delegate_member_ids_v"
2284 );
2285 UPDATE "delegating_interest_snapshot"
2286 SET "weight" = "sub_weight_v"
2287 WHERE "issue_id" = "issue_id_p"
2288 AND "event" = 'periodic'
2289 AND "member_id" = "issue_delegation_row"."truster_id";
2290 "weight_v" := "weight_v" + "sub_weight_v";
2291 END IF;
2292 END LOOP;
2293 RETURN "weight_v";
2294 END;
2295 $$;
2297 COMMENT ON FUNCTION "weight_of_added_delegations_for_interest_snapshot"
2298 ( "issue"."id"%TYPE,
2299 "member"."id"%TYPE,
2300 "delegating_interest_snapshot"."delegate_member_ids"%TYPE )
2301 IS 'Helper function for "create_interest_snapshot" function';
2304 CREATE FUNCTION "create_interest_snapshot"
2305 ( "issue_id_p" "issue"."id"%TYPE )
2306 RETURNS VOID
2307 LANGUAGE 'plpgsql' VOLATILE AS $$
2308 DECLARE
2309 "member_id_v" "member"."id"%TYPE;
2310 BEGIN
2311 DELETE FROM "direct_interest_snapshot"
2312 WHERE "issue_id" = "issue_id_p"
2313 AND "event" = 'periodic';
2314 DELETE FROM "delegating_interest_snapshot"
2315 WHERE "issue_id" = "issue_id_p"
2316 AND "event" = 'periodic';
2317 DELETE FROM "direct_supporter_snapshot"
2318 WHERE "issue_id" = "issue_id_p"
2319 AND "event" = 'periodic';
2320 INSERT INTO "direct_interest_snapshot"
2321 ("issue_id", "event", "member_id", "voting_requested")
2322 SELECT
2323 "issue_id_p" AS "issue_id",
2324 'periodic' AS "event",
2325 "member"."id" AS "member_id",
2326 "interest"."voting_requested"
2327 FROM "interest" JOIN "member"
2328 ON "interest"."member_id" = "member"."id"
2329 WHERE "interest"."issue_id" = "issue_id_p"
2330 AND "member"."active";
2331 FOR "member_id_v" IN
2332 SELECT "member_id" FROM "direct_interest_snapshot"
2333 WHERE "issue_id" = "issue_id_p"
2334 AND "event" = 'periodic'
2335 LOOP
2336 UPDATE "direct_interest_snapshot" SET
2337 "weight" = 1 +
2338 "weight_of_added_delegations_for_interest_snapshot"(
2339 "issue_id_p",
2340 "member_id_v",
2341 '{}'
2343 WHERE "issue_id" = "issue_id_p"
2344 AND "event" = 'periodic'
2345 AND "member_id" = "member_id_v";
2346 END LOOP;
2347 INSERT INTO "direct_supporter_snapshot"
2348 ( "issue_id", "initiative_id", "event", "member_id",
2349 "informed", "satisfied" )
2350 SELECT
2351 "issue_id_p" AS "issue_id",
2352 "initiative"."id" AS "initiative_id",
2353 'periodic' AS "event",
2354 "member"."id" AS "member_id",
2355 "supporter"."draft_id" = "current_draft"."id" AS "informed",
2356 NOT EXISTS (
2357 SELECT NULL FROM "critical_opinion"
2358 WHERE "initiative_id" = "initiative"."id"
2359 AND "member_id" = "member"."id"
2360 ) AS "satisfied"
2361 FROM "supporter"
2362 JOIN "member"
2363 ON "supporter"."member_id" = "member"."id"
2364 JOIN "initiative"
2365 ON "supporter"."initiative_id" = "initiative"."id"
2366 JOIN "current_draft"
2367 ON "initiative"."id" = "current_draft"."initiative_id"
2368 JOIN "direct_interest_snapshot"
2369 ON "member"."id" = "direct_interest_snapshot"."member_id"
2370 AND "initiative"."issue_id" = "direct_interest_snapshot"."issue_id"
2371 AND "event" = 'periodic'
2372 WHERE "member"."active"
2373 AND "initiative"."issue_id" = "issue_id_p";
2374 RETURN;
2375 END;
2376 $$;
2378 COMMENT ON FUNCTION "create_interest_snapshot"
2379 ( "issue"."id"%TYPE )
2380 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.';
2383 CREATE FUNCTION "create_snapshot"
2384 ( "issue_id_p" "issue"."id"%TYPE )
2385 RETURNS VOID
2386 LANGUAGE 'plpgsql' VOLATILE AS $$
2387 DECLARE
2388 "initiative_id_v" "initiative"."id"%TYPE;
2389 "suggestion_id_v" "suggestion"."id"%TYPE;
2390 BEGIN
2391 PERFORM "lock_issue"("issue_id_p");
2392 PERFORM "create_population_snapshot"("issue_id_p");
2393 PERFORM "create_interest_snapshot"("issue_id_p");
2394 UPDATE "issue" SET
2395 "snapshot" = now(),
2396 "latest_snapshot_event" = 'periodic',
2397 "population" = (
2398 SELECT coalesce(sum("weight"), 0)
2399 FROM "direct_population_snapshot"
2400 WHERE "issue_id" = "issue_id_p"
2401 AND "event" = 'periodic'
2402 ),
2403 "vote_now" = (
2404 SELECT coalesce(sum("weight"), 0)
2405 FROM "direct_interest_snapshot"
2406 WHERE "issue_id" = "issue_id_p"
2407 AND "event" = 'periodic'
2408 AND "voting_requested" = TRUE
2409 ),
2410 "vote_later" = (
2411 SELECT coalesce(sum("weight"), 0)
2412 FROM "direct_interest_snapshot"
2413 WHERE "issue_id" = "issue_id_p"
2414 AND "event" = 'periodic'
2415 AND "voting_requested" = FALSE
2417 WHERE "id" = "issue_id_p";
2418 FOR "initiative_id_v" IN
2419 SELECT "id" FROM "initiative" WHERE "issue_id" = "issue_id_p"
2420 LOOP
2421 UPDATE "initiative" SET
2422 "supporter_count" = (
2423 SELECT coalesce(sum("di"."weight"), 0)
2424 FROM "direct_interest_snapshot" AS "di"
2425 JOIN "direct_supporter_snapshot" AS "ds"
2426 ON "di"."member_id" = "ds"."member_id"
2427 WHERE "di"."issue_id" = "issue_id_p"
2428 AND "di"."event" = 'periodic'
2429 AND "ds"."initiative_id" = "initiative_id_v"
2430 AND "ds"."event" = 'periodic'
2431 ),
2432 "informed_supporter_count" = (
2433 SELECT coalesce(sum("di"."weight"), 0)
2434 FROM "direct_interest_snapshot" AS "di"
2435 JOIN "direct_supporter_snapshot" AS "ds"
2436 ON "di"."member_id" = "ds"."member_id"
2437 WHERE "di"."issue_id" = "issue_id_p"
2438 AND "di"."event" = 'periodic'
2439 AND "ds"."initiative_id" = "initiative_id_v"
2440 AND "ds"."event" = 'periodic'
2441 AND "ds"."informed"
2442 ),
2443 "satisfied_supporter_count" = (
2444 SELECT coalesce(sum("di"."weight"), 0)
2445 FROM "direct_interest_snapshot" AS "di"
2446 JOIN "direct_supporter_snapshot" AS "ds"
2447 ON "di"."member_id" = "ds"."member_id"
2448 WHERE "di"."issue_id" = "issue_id_p"
2449 AND "di"."event" = 'periodic'
2450 AND "ds"."initiative_id" = "initiative_id_v"
2451 AND "ds"."event" = 'periodic'
2452 AND "ds"."satisfied"
2453 ),
2454 "satisfied_informed_supporter_count" = (
2455 SELECT coalesce(sum("di"."weight"), 0)
2456 FROM "direct_interest_snapshot" AS "di"
2457 JOIN "direct_supporter_snapshot" AS "ds"
2458 ON "di"."member_id" = "ds"."member_id"
2459 WHERE "di"."issue_id" = "issue_id_p"
2460 AND "di"."event" = 'periodic'
2461 AND "ds"."initiative_id" = "initiative_id_v"
2462 AND "ds"."event" = 'periodic'
2463 AND "ds"."informed"
2464 AND "ds"."satisfied"
2466 WHERE "id" = "initiative_id_v";
2467 FOR "suggestion_id_v" IN
2468 SELECT "id" FROM "suggestion"
2469 WHERE "initiative_id" = "initiative_id_v"
2470 LOOP
2471 UPDATE "suggestion" SET
2472 "minus2_unfulfilled_count" = (
2473 SELECT coalesce(sum("snapshot"."weight"), 0)
2474 FROM "issue" CROSS JOIN "opinion"
2475 JOIN "direct_interest_snapshot" AS "snapshot"
2476 ON "snapshot"."issue_id" = "issue"."id"
2477 AND "snapshot"."event" = "issue"."latest_snapshot_event"
2478 AND "snapshot"."member_id" = "opinion"."member_id"
2479 WHERE "issue"."id" = "issue_id_p"
2480 AND "opinion"."suggestion_id" = "suggestion_id_v"
2481 AND "opinion"."degree" = -2
2482 AND "opinion"."fulfilled" = FALSE
2483 ),
2484 "minus2_fulfilled_count" = (
2485 SELECT coalesce(sum("snapshot"."weight"), 0)
2486 FROM "issue" CROSS JOIN "opinion"
2487 JOIN "direct_interest_snapshot" AS "snapshot"
2488 ON "snapshot"."issue_id" = "issue"."id"
2489 AND "snapshot"."event" = "issue"."latest_snapshot_event"
2490 AND "snapshot"."member_id" = "opinion"."member_id"
2491 WHERE "issue"."id" = "issue_id_p"
2492 AND "opinion"."suggestion_id" = "suggestion_id_v"
2493 AND "opinion"."degree" = -2
2494 AND "opinion"."fulfilled" = TRUE
2495 ),
2496 "minus1_unfulfilled_count" = (
2497 SELECT coalesce(sum("snapshot"."weight"), 0)
2498 FROM "issue" CROSS JOIN "opinion"
2499 JOIN "direct_interest_snapshot" AS "snapshot"
2500 ON "snapshot"."issue_id" = "issue"."id"
2501 AND "snapshot"."event" = "issue"."latest_snapshot_event"
2502 AND "snapshot"."member_id" = "opinion"."member_id"
2503 WHERE "issue"."id" = "issue_id_p"
2504 AND "opinion"."suggestion_id" = "suggestion_id_v"
2505 AND "opinion"."degree" = -1
2506 AND "opinion"."fulfilled" = FALSE
2507 ),
2508 "minus1_fulfilled_count" = (
2509 SELECT coalesce(sum("snapshot"."weight"), 0)
2510 FROM "issue" CROSS JOIN "opinion"
2511 JOIN "direct_interest_snapshot" AS "snapshot"
2512 ON "snapshot"."issue_id" = "issue"."id"
2513 AND "snapshot"."event" = "issue"."latest_snapshot_event"
2514 AND "snapshot"."member_id" = "opinion"."member_id"
2515 WHERE "issue"."id" = "issue_id_p"
2516 AND "opinion"."suggestion_id" = "suggestion_id_v"
2517 AND "opinion"."degree" = -1
2518 AND "opinion"."fulfilled" = TRUE
2519 ),
2520 "plus1_unfulfilled_count" = (
2521 SELECT coalesce(sum("snapshot"."weight"), 0)
2522 FROM "issue" CROSS JOIN "opinion"
2523 JOIN "direct_interest_snapshot" AS "snapshot"
2524 ON "snapshot"."issue_id" = "issue"."id"
2525 AND "snapshot"."event" = "issue"."latest_snapshot_event"
2526 AND "snapshot"."member_id" = "opinion"."member_id"
2527 WHERE "issue"."id" = "issue_id_p"
2528 AND "opinion"."suggestion_id" = "suggestion_id_v"
2529 AND "opinion"."degree" = 1
2530 AND "opinion"."fulfilled" = FALSE
2531 ),
2532 "plus1_fulfilled_count" = (
2533 SELECT coalesce(sum("snapshot"."weight"), 0)
2534 FROM "issue" CROSS JOIN "opinion"
2535 JOIN "direct_interest_snapshot" AS "snapshot"
2536 ON "snapshot"."issue_id" = "issue"."id"
2537 AND "snapshot"."event" = "issue"."latest_snapshot_event"
2538 AND "snapshot"."member_id" = "opinion"."member_id"
2539 WHERE "issue"."id" = "issue_id_p"
2540 AND "opinion"."suggestion_id" = "suggestion_id_v"
2541 AND "opinion"."degree" = 1
2542 AND "opinion"."fulfilled" = TRUE
2543 ),
2544 "plus2_unfulfilled_count" = (
2545 SELECT coalesce(sum("snapshot"."weight"), 0)
2546 FROM "issue" CROSS JOIN "opinion"
2547 JOIN "direct_interest_snapshot" AS "snapshot"
2548 ON "snapshot"."issue_id" = "issue"."id"
2549 AND "snapshot"."event" = "issue"."latest_snapshot_event"
2550 AND "snapshot"."member_id" = "opinion"."member_id"
2551 WHERE "issue"."id" = "issue_id_p"
2552 AND "opinion"."suggestion_id" = "suggestion_id_v"
2553 AND "opinion"."degree" = 2
2554 AND "opinion"."fulfilled" = FALSE
2555 ),
2556 "plus2_fulfilled_count" = (
2557 SELECT coalesce(sum("snapshot"."weight"), 0)
2558 FROM "issue" CROSS JOIN "opinion"
2559 JOIN "direct_interest_snapshot" AS "snapshot"
2560 ON "snapshot"."issue_id" = "issue"."id"
2561 AND "snapshot"."event" = "issue"."latest_snapshot_event"
2562 AND "snapshot"."member_id" = "opinion"."member_id"
2563 WHERE "issue"."id" = "issue_id_p"
2564 AND "opinion"."suggestion_id" = "suggestion_id_v"
2565 AND "opinion"."degree" = 2
2566 AND "opinion"."fulfilled" = TRUE
2568 WHERE "suggestion"."id" = "suggestion_id_v";
2569 END LOOP;
2570 END LOOP;
2571 RETURN;
2572 END;
2573 $$;
2575 COMMENT ON FUNCTION "create_snapshot"
2576 ( "issue"."id"%TYPE )
2577 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.';
2580 CREATE FUNCTION "set_snapshot_event"
2581 ( "issue_id_p" "issue"."id"%TYPE,
2582 "event_p" "snapshot_event" )
2583 RETURNS VOID
2584 LANGUAGE 'plpgsql' VOLATILE AS $$
2585 DECLARE
2586 "event_v" "issue"."latest_snapshot_event"%TYPE;
2587 BEGIN
2588 SELECT "latest_snapshot_event" INTO "event_v" FROM "issue"
2589 WHERE "id" = "issue_id_p" FOR UPDATE;
2590 UPDATE "issue" SET "latest_snapshot_event" = "event_p"
2591 WHERE "id" = "issue_id_p";
2592 UPDATE "direct_population_snapshot" SET "event" = "event_p"
2593 WHERE "issue_id" = "issue_id_p" AND "event" = "event_v";
2594 UPDATE "delegating_population_snapshot" SET "event" = "event_p"
2595 WHERE "issue_id" = "issue_id_p" AND "event" = "event_v";
2596 UPDATE "direct_interest_snapshot" SET "event" = "event_p"
2597 WHERE "issue_id" = "issue_id_p" AND "event" = "event_v";
2598 UPDATE "delegating_interest_snapshot" SET "event" = "event_p"
2599 WHERE "issue_id" = "issue_id_p" AND "event" = "event_v";
2600 UPDATE "direct_supporter_snapshot" SET "event" = "event_p"
2601 WHERE "issue_id" = "issue_id_p" AND "event" = "event_v";
2602 RETURN;
2603 END;
2604 $$;
2606 COMMENT ON FUNCTION "set_snapshot_event"
2607 ( "issue"."id"%TYPE,
2608 "snapshot_event" )
2609 IS 'Change "event" attribute of the previous ''periodic'' snapshot';
2613 ---------------------
2614 -- Freezing issues --
2615 ---------------------
2617 CREATE FUNCTION "freeze_after_snapshot"
2618 ( "issue_id_p" "issue"."id"%TYPE )
2619 RETURNS VOID
2620 LANGUAGE 'plpgsql' VOLATILE AS $$
2621 DECLARE
2622 "issue_row" "issue"%ROWTYPE;
2623 "policy_row" "policy"%ROWTYPE;
2624 "initiative_row" "initiative"%ROWTYPE;
2625 BEGIN
2626 SELECT * INTO "issue_row" FROM "issue" WHERE "id" = "issue_id_p";
2627 SELECT * INTO "policy_row"
2628 FROM "policy" WHERE "id" = "issue_row"."policy_id";
2629 PERFORM "set_snapshot_event"("issue_id_p", 'full_freeze');
2630 UPDATE "issue" SET
2631 "accepted" = coalesce("accepted", now()),
2632 "half_frozen" = coalesce("half_frozen", now()),
2633 "fully_frozen" = now()
2634 WHERE "id" = "issue_id_p";
2635 FOR "initiative_row" IN
2636 SELECT * FROM "initiative"
2637 WHERE "issue_id" = "issue_id_p" AND "revoked" ISNULL
2638 LOOP
2639 IF
2640 "initiative_row"."satisfied_supporter_count" > 0 AND
2641 "initiative_row"."satisfied_supporter_count" *
2642 "policy_row"."initiative_quorum_den" >=
2643 "issue_row"."population" * "policy_row"."initiative_quorum_num"
2644 THEN
2645 UPDATE "initiative" SET "admitted" = TRUE
2646 WHERE "id" = "initiative_row"."id";
2647 ELSE
2648 UPDATE "initiative" SET "admitted" = FALSE
2649 WHERE "id" = "initiative_row"."id";
2650 END IF;
2651 END LOOP;
2652 IF NOT EXISTS (
2653 SELECT NULL FROM "initiative"
2654 WHERE "issue_id" = "issue_id_p" AND "admitted" = TRUE
2655 ) THEN
2656 PERFORM "close_voting"("issue_id_p");
2657 END IF;
2658 RETURN;
2659 END;
2660 $$;
2662 COMMENT ON FUNCTION "freeze_after_snapshot"
2663 ( "issue"."id"%TYPE )
2664 IS 'This function freezes an issue (fully) and starts voting, but must only be called when "create_snapshot" was called in the same transaction.';
2667 CREATE FUNCTION "manual_freeze"("issue_id_p" "issue"."id"%TYPE)
2668 RETURNS VOID
2669 LANGUAGE 'plpgsql' VOLATILE AS $$
2670 DECLARE
2671 "issue_row" "issue"%ROWTYPE;
2672 BEGIN
2673 PERFORM "create_snapshot"("issue_id_p");
2674 PERFORM "freeze_after_snapshot"("issue_id_p");
2675 RETURN;
2676 END;
2677 $$;
2679 COMMENT ON FUNCTION "manual_freeze"
2680 ( "issue"."id"%TYPE )
2681 IS 'Freeze an issue manually (fully) and start voting';
2685 -----------------------
2686 -- Counting of votes --
2687 -----------------------
2690 CREATE FUNCTION "weight_of_added_vote_delegations"
2691 ( "issue_id_p" "issue"."id"%TYPE,
2692 "member_id_p" "member"."id"%TYPE,
2693 "delegate_member_ids_p" "delegating_voter"."delegate_member_ids"%TYPE )
2694 RETURNS "direct_voter"."weight"%TYPE
2695 LANGUAGE 'plpgsql' VOLATILE AS $$
2696 DECLARE
2697 "issue_delegation_row" "issue_delegation"%ROWTYPE;
2698 "delegate_member_ids_v" "delegating_voter"."delegate_member_ids"%TYPE;
2699 "weight_v" INT4;
2700 "sub_weight_v" INT4;
2701 BEGIN
2702 "weight_v" := 0;
2703 FOR "issue_delegation_row" IN
2704 SELECT * FROM "issue_delegation"
2705 WHERE "trustee_id" = "member_id_p"
2706 AND "issue_id" = "issue_id_p"
2707 LOOP
2708 IF NOT EXISTS (
2709 SELECT NULL FROM "direct_voter"
2710 WHERE "member_id" = "issue_delegation_row"."truster_id"
2711 AND "issue_id" = "issue_id_p"
2712 ) AND NOT EXISTS (
2713 SELECT NULL FROM "delegating_voter"
2714 WHERE "member_id" = "issue_delegation_row"."truster_id"
2715 AND "issue_id" = "issue_id_p"
2716 ) THEN
2717 "delegate_member_ids_v" :=
2718 "member_id_p" || "delegate_member_ids_p";
2719 INSERT INTO "delegating_voter" (
2720 "issue_id",
2721 "member_id",
2722 "scope",
2723 "delegate_member_ids"
2724 ) VALUES (
2725 "issue_id_p",
2726 "issue_delegation_row"."truster_id",
2727 "issue_delegation_row"."scope",
2728 "delegate_member_ids_v"
2729 );
2730 "sub_weight_v" := 1 +
2731 "weight_of_added_vote_delegations"(
2732 "issue_id_p",
2733 "issue_delegation_row"."truster_id",
2734 "delegate_member_ids_v"
2735 );
2736 UPDATE "delegating_voter"
2737 SET "weight" = "sub_weight_v"
2738 WHERE "issue_id" = "issue_id_p"
2739 AND "member_id" = "issue_delegation_row"."truster_id";
2740 "weight_v" := "weight_v" + "sub_weight_v";
2741 END IF;
2742 END LOOP;
2743 RETURN "weight_v";
2744 END;
2745 $$;
2747 COMMENT ON FUNCTION "weight_of_added_vote_delegations"
2748 ( "issue"."id"%TYPE,
2749 "member"."id"%TYPE,
2750 "delegating_voter"."delegate_member_ids"%TYPE )
2751 IS 'Helper function for "add_vote_delegations" function';
2754 CREATE FUNCTION "add_vote_delegations"
2755 ( "issue_id_p" "issue"."id"%TYPE )
2756 RETURNS VOID
2757 LANGUAGE 'plpgsql' VOLATILE AS $$
2758 DECLARE
2759 "member_id_v" "member"."id"%TYPE;
2760 BEGIN
2761 FOR "member_id_v" IN
2762 SELECT "member_id" FROM "direct_voter"
2763 WHERE "issue_id" = "issue_id_p"
2764 LOOP
2765 UPDATE "direct_voter" SET
2766 "weight" = "weight" + "weight_of_added_vote_delegations"(
2767 "issue_id_p",
2768 "member_id_v",
2769 '{}'
2771 WHERE "member_id" = "member_id_v"
2772 AND "issue_id" = "issue_id_p";
2773 END LOOP;
2774 RETURN;
2775 END;
2776 $$;
2778 COMMENT ON FUNCTION "add_vote_delegations"
2779 ( "issue_id_p" "issue"."id"%TYPE )
2780 IS 'Helper function for "close_voting" function';
2783 CREATE FUNCTION "close_voting"("issue_id_p" "issue"."id"%TYPE)
2784 RETURNS VOID
2785 LANGUAGE 'plpgsql' VOLATILE AS $$
2786 DECLARE
2787 "issue_row" "issue"%ROWTYPE;
2788 "member_id_v" "member"."id"%TYPE;
2789 BEGIN
2790 PERFORM "lock_issue"("issue_id_p");
2791 SELECT * INTO "issue_row" FROM "issue" WHERE "id" = "issue_id_p";
2792 DELETE FROM "delegating_voter"
2793 WHERE "issue_id" = "issue_id_p";
2794 DELETE FROM "direct_voter"
2795 WHERE "issue_id" = "issue_id_p"
2796 AND "autoreject" = TRUE;
2797 DELETE FROM "direct_voter" USING "member"
2798 WHERE "direct_voter"."member_id" = "member"."id"
2799 AND "direct_voter"."issue_id" = "issue_id_p"
2800 AND "member"."active" = FALSE;
2801 UPDATE "direct_voter" SET "weight" = 1
2802 WHERE "issue_id" = "issue_id_p";
2803 PERFORM "add_vote_delegations"("issue_id_p");
2804 FOR "member_id_v" IN
2805 SELECT "interest"."member_id"
2806 FROM "interest"
2807 LEFT JOIN "direct_voter"
2808 ON "interest"."member_id" = "direct_voter"."member_id"
2809 AND "interest"."issue_id" = "direct_voter"."issue_id"
2810 LEFT JOIN "delegating_voter"
2811 ON "interest"."member_id" = "delegating_voter"."member_id"
2812 AND "interest"."issue_id" = "delegating_voter"."issue_id"
2813 WHERE "interest"."issue_id" = "issue_id_p"
2814 AND "interest"."autoreject" = TRUE
2815 AND "direct_voter"."member_id" ISNULL
2816 AND "delegating_voter"."member_id" ISNULL
2817 UNION SELECT "membership"."member_id"
2818 FROM "membership"
2819 LEFT JOIN "interest"
2820 ON "membership"."member_id" = "interest"."member_id"
2821 AND "interest"."issue_id" = "issue_id_p"
2822 LEFT JOIN "direct_voter"
2823 ON "membership"."member_id" = "direct_voter"."member_id"
2824 AND "direct_voter"."issue_id" = "issue_id_p"
2825 LEFT JOIN "delegating_voter"
2826 ON "membership"."member_id" = "delegating_voter"."member_id"
2827 AND "delegating_voter"."issue_id" = "issue_id_p"
2828 WHERE "membership"."area_id" = "issue_row"."area_id"
2829 AND "membership"."autoreject" = TRUE
2830 AND "interest"."autoreject" ISNULL
2831 AND "direct_voter"."member_id" ISNULL
2832 AND "delegating_voter"."member_id" ISNULL
2833 LOOP
2834 INSERT INTO "direct_voter"
2835 ("member_id", "issue_id", "weight", "autoreject") VALUES
2836 ("member_id_v", "issue_id_p", 1, TRUE);
2837 INSERT INTO "vote" (
2838 "member_id",
2839 "issue_id",
2840 "initiative_id",
2841 "grade"
2842 ) SELECT
2843 "member_id_v" AS "member_id",
2844 "issue_id_p" AS "issue_id",
2845 "id" AS "initiative_id",
2846 -1 AS "grade"
2847 FROM "initiative" WHERE "issue_id" = "issue_id_p";
2848 END LOOP;
2849 PERFORM "add_vote_delegations"("issue_id_p");
2850 UPDATE "issue" SET
2851 "closed" = now(),
2852 "voter_count" = (
2853 SELECT coalesce(sum("weight"), 0)
2854 FROM "direct_voter" WHERE "issue_id" = "issue_id_p"
2856 WHERE "id" = "issue_id_p";
2857 UPDATE "initiative" SET
2858 "positive_votes" = "vote_counts"."positive_votes",
2859 "negative_votes" = "vote_counts"."negative_votes",
2860 "agreed" = CASE WHEN "majority_strict" THEN
2861 "vote_counts"."positive_votes" * "majority_den" >
2862 "majority_num" *
2863 ("vote_counts"."positive_votes"+"vote_counts"."negative_votes")
2864 ELSE
2865 "vote_counts"."positive_votes" * "majority_den" >=
2866 "majority_num" *
2867 ("vote_counts"."positive_votes"+"vote_counts"."negative_votes")
2868 END
2869 FROM
2870 ( SELECT
2871 "initiative"."id" AS "initiative_id",
2872 coalesce(
2873 sum(
2874 CASE WHEN "grade" > 0 THEN "direct_voter"."weight" ELSE 0 END
2875 ),
2877 ) AS "positive_votes",
2878 coalesce(
2879 sum(
2880 CASE WHEN "grade" < 0 THEN "direct_voter"."weight" ELSE 0 END
2881 ),
2883 ) AS "negative_votes"
2884 FROM "initiative"
2885 JOIN "issue" ON "initiative"."issue_id" = "issue"."id"
2886 JOIN "policy" ON "issue"."policy_id" = "policy"."id"
2887 LEFT JOIN "direct_voter"
2888 ON "direct_voter"."issue_id" = "initiative"."issue_id"
2889 LEFT JOIN "vote"
2890 ON "vote"."initiative_id" = "initiative"."id"
2891 AND "vote"."member_id" = "direct_voter"."member_id"
2892 WHERE "initiative"."issue_id" = "issue_id_p"
2893 AND "initiative"."admitted" -- NOTE: NULL case is handled too
2894 GROUP BY "initiative"."id"
2895 ) AS "vote_counts",
2896 "issue",
2897 "policy"
2898 WHERE "vote_counts"."initiative_id" = "initiative"."id"
2899 AND "issue"."id" = "initiative"."issue_id"
2900 AND "policy"."id" = "issue"."policy_id";
2901 -- NOTE: "closed" column of issue must be set at this point
2902 DELETE FROM "battle" WHERE "issue_id" = "issue_id_p";
2903 INSERT INTO "battle" (
2904 "issue_id",
2905 "winning_initiative_id", "losing_initiative_id",
2906 "count"
2907 ) SELECT
2908 "issue_id",
2909 "winning_initiative_id", "losing_initiative_id",
2910 "count"
2911 FROM "battle_view" WHERE "issue_id" = "issue_id_p";
2912 END;
2913 $$;
2915 COMMENT ON FUNCTION "close_voting"
2916 ( "issue"."id"%TYPE )
2917 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.';
2920 CREATE FUNCTION "defeat_strength"
2921 ( "positive_votes_p" INT4, "negative_votes_p" INT4 )
2922 RETURNS INT8
2923 LANGUAGE 'plpgsql' IMMUTABLE AS $$
2924 BEGIN
2925 IF "positive_votes_p" > "negative_votes_p" THEN
2926 RETURN ("positive_votes_p"::INT8 << 31) - "negative_votes_p"::INT8;
2927 ELSIF "positive_votes_p" = "negative_votes_p" THEN
2928 RETURN 0;
2929 ELSE
2930 RETURN -1;
2931 END IF;
2932 END;
2933 $$;
2935 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';
2938 CREATE FUNCTION "array_init_string"("dim_p" INTEGER)
2939 RETURNS TEXT
2940 LANGUAGE 'plpgsql' IMMUTABLE AS $$
2941 DECLARE
2942 "i" INTEGER;
2943 "ary_text_v" TEXT;
2944 BEGIN
2945 IF "dim_p" >= 1 THEN
2946 "ary_text_v" := '{NULL';
2947 "i" := "dim_p";
2948 LOOP
2949 "i" := "i" - 1;
2950 EXIT WHEN "i" = 0;
2951 "ary_text_v" := "ary_text_v" || ',NULL';
2952 END LOOP;
2953 "ary_text_v" := "ary_text_v" || '}';
2954 RETURN "ary_text_v";
2955 ELSE
2956 RAISE EXCEPTION 'Dimension needs to be at least 1.';
2957 END IF;
2958 END;
2959 $$;
2961 COMMENT ON FUNCTION "array_init_string"(INTEGER) IS 'Needed for PostgreSQL < 8.4, due to missing "array_fill" function';
2964 CREATE FUNCTION "square_matrix_init_string"("dim_p" INTEGER)
2965 RETURNS TEXT
2966 LANGUAGE 'plpgsql' IMMUTABLE AS $$
2967 DECLARE
2968 "i" INTEGER;
2969 "row_text_v" TEXT;
2970 "ary_text_v" TEXT;
2971 BEGIN
2972 IF "dim_p" >= 1 THEN
2973 "row_text_v" := '{NULL';
2974 "i" := "dim_p";
2975 LOOP
2976 "i" := "i" - 1;
2977 EXIT WHEN "i" = 0;
2978 "row_text_v" := "row_text_v" || ',NULL';
2979 END LOOP;
2980 "row_text_v" := "row_text_v" || '}';
2981 "ary_text_v" := '{' || "row_text_v";
2982 "i" := "dim_p";
2983 LOOP
2984 "i" := "i" - 1;
2985 EXIT WHEN "i" = 0;
2986 "ary_text_v" := "ary_text_v" || ',' || "row_text_v";
2987 END LOOP;
2988 "ary_text_v" := "ary_text_v" || '}';
2989 RETURN "ary_text_v";
2990 ELSE
2991 RAISE EXCEPTION 'Dimension needs to be at least 1.';
2992 END IF;
2993 END;
2994 $$;
2996 COMMENT ON FUNCTION "square_matrix_init_string"(INTEGER) IS 'Needed for PostgreSQL < 8.4, due to missing "array_fill" function';
2999 CREATE FUNCTION "calculate_ranks"("issue_id_p" "issue"."id"%TYPE)
3000 RETURNS VOID
3001 LANGUAGE 'plpgsql' VOLATILE AS $$
3002 DECLARE
3003 "dimension_v" INTEGER;
3004 "vote_matrix" INT4[][]; -- absolute votes
3005 "matrix" INT8[][]; -- defeat strength / best paths
3006 "i" INTEGER;
3007 "j" INTEGER;
3008 "k" INTEGER;
3009 "battle_row" "battle"%ROWTYPE;
3010 "rank_ary" INT4[];
3011 "rank_v" INT4;
3012 "done_v" INTEGER;
3013 "winners_ary" INTEGER[];
3014 "initiative_id_v" "initiative"."id"%TYPE;
3015 BEGIN
3016 PERFORM NULL FROM "issue" WHERE "id" = "issue_id_p" FOR UPDATE;
3017 SELECT count(1) INTO "dimension_v" FROM "initiative"
3018 WHERE "issue_id" = "issue_id_p" AND "agreed";
3019 IF "dimension_v" = 1 THEN
3020 UPDATE "initiative" SET "rank" = 1
3021 WHERE "issue_id" = "issue_id_p" AND "agreed";
3022 ELSIF "dimension_v" > 1 THEN
3023 -- Create "vote_matrix" with absolute number of votes in pairwise
3024 -- comparison:
3025 "vote_matrix" := "square_matrix_init_string"("dimension_v"); -- TODO: replace by "array_fill" function (PostgreSQL 8.4)
3026 "i" := 1;
3027 "j" := 2;
3028 FOR "battle_row" IN
3029 SELECT * FROM "battle" WHERE "issue_id" = "issue_id_p"
3030 ORDER BY "winning_initiative_id", "losing_initiative_id"
3031 LOOP
3032 "vote_matrix"["i"]["j"] := "battle_row"."count";
3033 IF "j" = "dimension_v" THEN
3034 "i" := "i" + 1;
3035 "j" := 1;
3036 ELSE
3037 "j" := "j" + 1;
3038 IF "j" = "i" THEN
3039 "j" := "j" + 1;
3040 END IF;
3041 END IF;
3042 END LOOP;
3043 IF "i" != "dimension_v" OR "j" != "dimension_v" + 1 THEN
3044 RAISE EXCEPTION 'Wrong battle count (should not happen)';
3045 END IF;
3046 -- Store defeat strengths in "matrix" using "defeat_strength"
3047 -- function:
3048 "matrix" := "square_matrix_init_string"("dimension_v"); -- TODO: replace by "array_fill" function (PostgreSQL 8.4)
3049 "i" := 1;
3050 LOOP
3051 "j" := 1;
3052 LOOP
3053 IF "i" != "j" THEN
3054 "matrix"["i"]["j"] := "defeat_strength"(
3055 "vote_matrix"["i"]["j"],
3056 "vote_matrix"["j"]["i"]
3057 );
3058 END IF;
3059 EXIT WHEN "j" = "dimension_v";
3060 "j" := "j" + 1;
3061 END LOOP;
3062 EXIT WHEN "i" = "dimension_v";
3063 "i" := "i" + 1;
3064 END LOOP;
3065 -- Find best paths:
3066 "i" := 1;
3067 LOOP
3068 "j" := 1;
3069 LOOP
3070 IF "i" != "j" THEN
3071 "k" := 1;
3072 LOOP
3073 IF "i" != "k" AND "j" != "k" THEN
3074 IF "matrix"["j"]["i"] < "matrix"["i"]["k"] THEN
3075 IF "matrix"["j"]["i"] > "matrix"["j"]["k"] THEN
3076 "matrix"["j"]["k"] := "matrix"["j"]["i"];
3077 END IF;
3078 ELSE
3079 IF "matrix"["i"]["k"] > "matrix"["j"]["k"] THEN
3080 "matrix"["j"]["k"] := "matrix"["i"]["k"];
3081 END IF;
3082 END IF;
3083 END IF;
3084 EXIT WHEN "k" = "dimension_v";
3085 "k" := "k" + 1;
3086 END LOOP;
3087 END IF;
3088 EXIT WHEN "j" = "dimension_v";
3089 "j" := "j" + 1;
3090 END LOOP;
3091 EXIT WHEN "i" = "dimension_v";
3092 "i" := "i" + 1;
3093 END LOOP;
3094 -- Determine order of winners:
3095 "rank_ary" := "array_init_string"("dimension_v"); -- TODO: replace by "array_fill" function (PostgreSQL 8.4)
3096 "rank_v" := 1;
3097 "done_v" := 0;
3098 LOOP
3099 "winners_ary" := '{}';
3100 "i" := 1;
3101 LOOP
3102 IF "rank_ary"["i"] ISNULL THEN
3103 "j" := 1;
3104 LOOP
3105 IF
3106 "i" != "j" AND
3107 "rank_ary"["j"] ISNULL AND
3108 "matrix"["j"]["i"] > "matrix"["i"]["j"]
3109 THEN
3110 -- someone else is better
3111 EXIT;
3112 END IF;
3113 IF "j" = "dimension_v" THEN
3114 -- noone is better
3115 "winners_ary" := "winners_ary" || "i";
3116 EXIT;
3117 END IF;
3118 "j" := "j" + 1;
3119 END LOOP;
3120 END IF;
3121 EXIT WHEN "i" = "dimension_v";
3122 "i" := "i" + 1;
3123 END LOOP;
3124 "i" := 1;
3125 LOOP
3126 "rank_ary"["winners_ary"["i"]] := "rank_v";
3127 "done_v" := "done_v" + 1;
3128 EXIT WHEN "i" = array_upper("winners_ary", 1);
3129 "i" := "i" + 1;
3130 END LOOP;
3131 EXIT WHEN "done_v" = "dimension_v";
3132 "rank_v" := "rank_v" + 1;
3133 END LOOP;
3134 -- write preliminary ranks:
3135 "i" := 1;
3136 FOR "initiative_id_v" IN
3137 SELECT "id" FROM "initiative"
3138 WHERE "issue_id" = "issue_id_p" AND "agreed"
3139 ORDER BY "id"
3140 LOOP
3141 UPDATE "initiative" SET "rank" = "rank_ary"["i"]
3142 WHERE "id" = "initiative_id_v";
3143 "i" := "i" + 1;
3144 END LOOP;
3145 IF "i" != "dimension_v" + 1 THEN
3146 RAISE EXCEPTION 'Wrong winner count (should not happen)';
3147 END IF;
3148 -- straighten ranks (start counting with 1, no equal ranks):
3149 "rank_v" := 1;
3150 FOR "initiative_id_v" IN
3151 SELECT "id" FROM "initiative"
3152 WHERE "issue_id" = "issue_id_p" AND "rank" NOTNULL
3153 ORDER BY
3154 "rank",
3155 "vote_ratio"("positive_votes", "negative_votes") DESC,
3156 "id"
3157 LOOP
3158 UPDATE "initiative" SET "rank" = "rank_v"
3159 WHERE "id" = "initiative_id_v";
3160 "rank_v" := "rank_v" + 1;
3161 END LOOP;
3162 END IF;
3163 -- mark issue as finished
3164 UPDATE "issue" SET "ranks_available" = TRUE
3165 WHERE "id" = "issue_id_p";
3166 RETURN;
3167 END;
3168 $$;
3170 COMMENT ON FUNCTION "calculate_ranks"
3171 ( "issue"."id"%TYPE )
3172 IS 'Determine ranking (Votes have to be counted first)';
3176 -----------------------------
3177 -- Automatic state changes --
3178 -----------------------------
3181 CREATE FUNCTION "check_issue"
3182 ( "issue_id_p" "issue"."id"%TYPE )
3183 RETURNS VOID
3184 LANGUAGE 'plpgsql' VOLATILE AS $$
3185 DECLARE
3186 "issue_row" "issue"%ROWTYPE;
3187 "policy_row" "policy"%ROWTYPE;
3188 "voting_requested_v" BOOLEAN;
3189 BEGIN
3190 PERFORM "lock_issue"("issue_id_p");
3191 SELECT * INTO "issue_row" FROM "issue" WHERE "id" = "issue_id_p";
3192 -- only process open issues:
3193 IF "issue_row"."closed" ISNULL THEN
3194 SELECT * INTO "policy_row" FROM "policy"
3195 WHERE "id" = "issue_row"."policy_id";
3196 -- create a snapshot, unless issue is already fully frozen:
3197 IF "issue_row"."fully_frozen" ISNULL THEN
3198 PERFORM "create_snapshot"("issue_id_p");
3199 SELECT * INTO "issue_row" FROM "issue" WHERE "id" = "issue_id_p";
3200 END IF;
3201 -- eventually close or accept issues, which have not been accepted:
3202 IF "issue_row"."accepted" ISNULL THEN
3203 IF EXISTS (
3204 SELECT NULL FROM "initiative"
3205 WHERE "issue_id" = "issue_id_p"
3206 AND "supporter_count" > 0
3207 AND "supporter_count" * "policy_row"."issue_quorum_den"
3208 >= "issue_row"."population" * "policy_row"."issue_quorum_num"
3209 ) THEN
3210 -- accept issues, if supporter count is high enough
3211 PERFORM "set_snapshot_event"("issue_id_p", 'end_of_admission');
3212 "issue_row"."accepted" = now(); -- NOTE: "issue_row" used later
3213 UPDATE "issue" SET "accepted" = "issue_row"."accepted"
3214 WHERE "id" = "issue_row"."id";
3215 ELSIF
3216 now() >= "issue_row"."created" + "issue_row"."admission_time"
3217 THEN
3218 -- close issues, if admission time has expired
3219 PERFORM "set_snapshot_event"("issue_id_p", 'end_of_admission');
3220 UPDATE "issue" SET "closed" = now()
3221 WHERE "id" = "issue_row"."id";
3222 END IF;
3223 END IF;
3224 -- eventually half freeze issues:
3225 IF
3226 -- NOTE: issue can't be closed at this point, if it has been accepted
3227 "issue_row"."accepted" NOTNULL AND
3228 "issue_row"."half_frozen" ISNULL
3229 THEN
3230 SELECT
3231 CASE
3232 WHEN "vote_now" * 2 > "issue_row"."population" THEN
3233 TRUE
3234 WHEN "vote_later" * 2 > "issue_row"."population" THEN
3235 FALSE
3236 ELSE NULL
3237 END
3238 INTO "voting_requested_v"
3239 FROM "issue" WHERE "id" = "issue_id_p";
3240 IF
3241 "voting_requested_v" OR (
3242 "voting_requested_v" ISNULL AND
3243 now() >= "issue_row"."accepted" + "issue_row"."discussion_time"
3245 THEN
3246 PERFORM "set_snapshot_event"("issue_id_p", 'half_freeze');
3247 "issue_row"."half_frozen" = now(); -- NOTE: "issue_row" used later
3248 UPDATE "issue" SET "half_frozen" = "issue_row"."half_frozen"
3249 WHERE "id" = "issue_row"."id";
3250 END IF;
3251 END IF;
3252 -- close issues after some time, if all initiatives have been revoked:
3253 IF
3254 "issue_row"."closed" ISNULL AND
3255 NOT EXISTS (
3256 -- all initiatives are revoked
3257 SELECT NULL FROM "initiative"
3258 WHERE "issue_id" = "issue_id_p" AND "revoked" ISNULL
3259 ) AND (
3260 NOT EXISTS (
3261 -- and no initiatives have been revoked lately
3262 SELECT NULL FROM "initiative"
3263 WHERE "issue_id" = "issue_id_p"
3264 AND now() < "revoked" + "issue_row"."verification_time"
3265 ) OR (
3266 -- or verification time has elapsed
3267 "issue_row"."half_frozen" NOTNULL AND
3268 "issue_row"."fully_frozen" ISNULL AND
3269 now() >= "issue_row"."half_frozen" + "issue_row"."verification_time"
3272 THEN
3273 "issue_row"."closed" = now(); -- NOTE: "issue_row" used later
3274 UPDATE "issue" SET "closed" = "issue_row"."closed"
3275 WHERE "id" = "issue_row"."id";
3276 END IF;
3277 -- fully freeze issue after verification time:
3278 IF
3279 "issue_row"."half_frozen" NOTNULL AND
3280 "issue_row"."fully_frozen" ISNULL AND
3281 "issue_row"."closed" ISNULL AND
3282 now() >= "issue_row"."half_frozen" + "issue_row"."verification_time"
3283 THEN
3284 PERFORM "freeze_after_snapshot"("issue_id_p");
3285 -- NOTE: "issue" might change, thus "issue_row" has to be updated below
3286 END IF;
3287 SELECT * INTO "issue_row" FROM "issue" WHERE "id" = "issue_id_p";
3288 -- close issue by calling close_voting(...) after voting time:
3289 IF
3290 "issue_row"."closed" ISNULL AND
3291 "issue_row"."fully_frozen" NOTNULL AND
3292 now() >= "issue_row"."fully_frozen" + "issue_row"."voting_time"
3293 THEN
3294 PERFORM "close_voting"("issue_id_p");
3295 END IF;
3296 END IF;
3297 RETURN;
3298 END;
3299 $$;
3301 COMMENT ON FUNCTION "check_issue"
3302 ( "issue"."id"%TYPE )
3303 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.';
3306 CREATE FUNCTION "check_everything"()
3307 RETURNS VOID
3308 LANGUAGE 'plpgsql' VOLATILE AS $$
3309 DECLARE
3310 "issue_id_v" "issue"."id"%TYPE;
3311 BEGIN
3312 DELETE FROM "expired_session";
3313 PERFORM "calculate_member_counts"();
3314 FOR "issue_id_v" IN SELECT "id" FROM "open_issue" LOOP
3315 PERFORM "check_issue"("issue_id_v");
3316 END LOOP;
3317 FOR "issue_id_v" IN SELECT "id" FROM "issue_with_ranks_missing" LOOP
3318 PERFORM "calculate_ranks"("issue_id_v");
3319 END LOOP;
3320 RETURN;
3321 END;
3322 $$;
3324 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.';
3328 ----------------------
3329 -- Deletion of data --
3330 ----------------------
3333 CREATE FUNCTION "clean_issue"("issue_id_p" "issue"."id"%TYPE)
3334 RETURNS VOID
3335 LANGUAGE 'plpgsql' VOLATILE AS $$
3336 DECLARE
3337 "issue_row" "issue"%ROWTYPE;
3338 BEGIN
3339 SELECT * INTO "issue_row"
3340 FROM "issue" WHERE "id" = "issue_id_p"
3341 FOR UPDATE;
3342 IF "issue_row"."cleaned" ISNULL THEN
3343 UPDATE "issue" SET
3344 "closed" = NULL,
3345 "ranks_available" = FALSE
3346 WHERE "id" = "issue_id_p";
3347 DELETE FROM "delegating_voter"
3348 WHERE "issue_id" = "issue_id_p";
3349 DELETE FROM "direct_voter"
3350 WHERE "issue_id" = "issue_id_p";
3351 DELETE FROM "delegating_interest_snapshot"
3352 WHERE "issue_id" = "issue_id_p";
3353 DELETE FROM "direct_interest_snapshot"
3354 WHERE "issue_id" = "issue_id_p";
3355 DELETE FROM "delegating_population_snapshot"
3356 WHERE "issue_id" = "issue_id_p";
3357 DELETE FROM "direct_population_snapshot"
3358 WHERE "issue_id" = "issue_id_p";
3359 DELETE FROM "delegation"
3360 WHERE "issue_id" = "issue_id_p";
3361 DELETE FROM "supporter"
3362 WHERE "issue_id" = "issue_id_p";
3363 UPDATE "issue" SET
3364 "closed" = "issue_row"."closed",
3365 "ranks_available" = "issue_row"."ranks_available",
3366 "cleaned" = now()
3367 WHERE "id" = "issue_id_p";
3368 END IF;
3369 RETURN;
3370 END;
3371 $$;
3373 COMMENT ON FUNCTION "clean_issue"("issue"."id"%TYPE) IS 'Delete discussion data and votes belonging to an issue';
3376 CREATE FUNCTION "delete_member"("member_id_p" "member"."id"%TYPE)
3377 RETURNS VOID
3378 LANGUAGE 'plpgsql' VOLATILE AS $$
3379 BEGIN
3380 UPDATE "member" SET
3381 "last_login" = NULL,
3382 "login" = NULL,
3383 "password" = NULL,
3384 "active" = FALSE,
3385 "notify_email" = NULL,
3386 "notify_email_unconfirmed" = NULL,
3387 "notify_email_secret" = NULL,
3388 "notify_email_secret_expiry" = NULL,
3389 "notify_email_lock_expiry" = NULL,
3390 "password_reset_secret" = NULL,
3391 "password_reset_secret_expiry" = NULL,
3392 "organizational_unit" = NULL,
3393 "internal_posts" = NULL,
3394 "realname" = NULL,
3395 "birthday" = NULL,
3396 "address" = NULL,
3397 "email" = NULL,
3398 "xmpp_address" = NULL,
3399 "website" = NULL,
3400 "phone" = NULL,
3401 "mobile_phone" = NULL,
3402 "profession" = NULL,
3403 "external_memberships" = NULL,
3404 "external_posts" = NULL,
3405 "statement" = NULL
3406 WHERE "id" = "member_id_p";
3407 -- "text_search_data" is updated by triggers
3408 DELETE FROM "setting" WHERE "member_id" = "member_id_p";
3409 DELETE FROM "setting_map" WHERE "member_id" = "member_id_p";
3410 DELETE FROM "member_relation_setting" WHERE "member_id" = "member_id_p";
3411 DELETE FROM "member_image" WHERE "member_id" = "member_id_p";
3412 DELETE FROM "contact" WHERE "member_id" = "member_id_p";
3413 DELETE FROM "area_setting" WHERE "member_id" = "member_id_p";
3414 DELETE FROM "issue_setting" WHERE "member_id" = "member_id_p";
3415 DELETE FROM "initiative_setting" WHERE "member_id" = "member_id_p";
3416 DELETE FROM "suggestion_setting" WHERE "member_id" = "member_id_p";
3417 DELETE FROM "membership" WHERE "member_id" = "member_id_p";
3418 DELETE FROM "delegation" WHERE "truster_id" = "member_id_p";
3419 DELETE FROM "delegation" WHERE "trustee_id" = "member_id_p";
3420 DELETE FROM "direct_voter" USING "issue"
3421 WHERE "direct_voter"."issue_id" = "issue"."id"
3422 AND "issue"."closed" ISNULL
3423 AND "member_id" = "member_id_p";
3424 RETURN;
3425 END;
3426 $$;
3428 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)';
3431 CREATE FUNCTION "delete_private_data"()
3432 RETURNS VOID
3433 LANGUAGE 'plpgsql' VOLATILE AS $$
3434 BEGIN
3435 UPDATE "member" SET
3436 "last_login" = NULL,
3437 "login" = NULL,
3438 "password" = NULL,
3439 "notify_email" = NULL,
3440 "notify_email_unconfirmed" = NULL,
3441 "notify_email_secret" = NULL,
3442 "notify_email_secret_expiry" = NULL,
3443 "notify_email_lock_expiry" = NULL,
3444 "password_reset_secret" = NULL,
3445 "password_reset_secret_expiry" = NULL,
3446 "organizational_unit" = NULL,
3447 "internal_posts" = NULL,
3448 "realname" = NULL,
3449 "birthday" = NULL,
3450 "address" = NULL,
3451 "email" = NULL,
3452 "xmpp_address" = NULL,
3453 "website" = NULL,
3454 "phone" = NULL,
3455 "mobile_phone" = NULL,
3456 "profession" = NULL,
3457 "external_memberships" = NULL,
3458 "external_posts" = NULL,
3459 "statement" = NULL;
3460 -- "text_search_data" is updated by triggers
3461 DELETE FROM "invite_code";
3462 DELETE FROM "setting";
3463 DELETE FROM "setting_map";
3464 DELETE FROM "member_relation_setting";
3465 DELETE FROM "member_image";
3466 DELETE FROM "contact";
3467 DELETE FROM "session";
3468 DELETE FROM "area_setting";
3469 DELETE FROM "issue_setting";
3470 DELETE FROM "initiative_setting";
3471 DELETE FROM "suggestion_setting";
3472 DELETE FROM "direct_voter" USING "issue"
3473 WHERE "direct_voter"."issue_id" = "issue"."id"
3474 AND "issue"."closed" ISNULL;
3475 RETURN;
3476 END;
3477 $$;
3479 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.';
3483 COMMIT;

Impressum / About Us