liquid_feedback_core

view core.sql @ 109:6df4faaa7a79

Added tag v1.3.1 for changeset ea4928ccc8eb
author jbe
date Sat Feb 05 20:04:00 2011 +0100 (2011-02-05)
parents 4d121276bf04
children 575559c319e9
line source
2 -- Execute the following command manually for PostgreSQL prior version 9.0:
3 -- CREATE LANGUAGE plpgsql;
5 -- NOTE: In PostgreSQL every UNIQUE constraint implies creation of an index
7 BEGIN;
9 CREATE VIEW "liquid_feedback_version" AS
10 SELECT * FROM (VALUES ('1.3.1', 1, 3, 1))
11 AS "subquery"("string", "major", "minor", "revision");
15 ----------------------
16 -- Full text search --
17 ----------------------
20 CREATE FUNCTION "text_search_query"("query_text_p" TEXT)
21 RETURNS TSQUERY
22 LANGUAGE 'plpgsql' IMMUTABLE AS $$
23 BEGIN
24 RETURN plainto_tsquery('pg_catalog.simple', "query_text_p");
25 END;
26 $$;
28 COMMENT ON FUNCTION "text_search_query"(TEXT) IS 'Usage: WHERE "text_search_data" @@ "text_search_query"(''<user query>'')';
31 CREATE FUNCTION "highlight"
32 ( "body_p" TEXT,
33 "query_text_p" TEXT )
34 RETURNS TEXT
35 LANGUAGE 'plpgsql' IMMUTABLE AS $$
36 BEGIN
37 RETURN ts_headline(
38 'pg_catalog.simple',
39 replace(replace("body_p", e'\\', e'\\\\'), '*', e'\\*'),
40 "text_search_query"("query_text_p"),
41 'StartSel=* StopSel=* HighlightAll=TRUE' );
42 END;
43 $$;
45 COMMENT ON FUNCTION "highlight"
46 ( "body_p" TEXT,
47 "query_text_p" TEXT )
48 IS 'For a given a user query this function encapsulates all matches with asterisks. Asterisks and backslashes being already present are preceeded with one extra backslash.';
52 -------------------------
53 -- Tables and indicies --
54 -------------------------
57 CREATE TABLE "system_setting" (
58 "member_ttl" INTERVAL );
59 CREATE UNIQUE INDEX "system_setting_singleton_idx" ON "system_setting" ((1));
61 COMMENT ON TABLE "system_setting" IS 'This table contains only one row with different settings in each column.';
62 COMMENT ON INDEX "system_setting_singleton_idx" IS 'This index ensures that "system_setting" only contains one row maximum.';
64 COMMENT ON COLUMN "system_setting"."member_ttl" IS 'Time after members get their "active" flag set to FALSE, if they do not login anymore.';
67 CREATE TABLE "member" (
68 "id" SERIAL4 PRIMARY KEY,
69 "created" TIMESTAMPTZ NOT NULL DEFAULT now(),
70 "last_login" TIMESTAMPTZ,
71 "last_login_public" DATE,
72 "login" TEXT UNIQUE,
73 "password" TEXT,
74 "locked" BOOLEAN NOT NULL DEFAULT FALSE,
75 "active" BOOLEAN NOT NULL DEFAULT TRUE,
76 "admin" BOOLEAN NOT NULL DEFAULT FALSE,
77 "notify_email" TEXT,
78 "notify_email_unconfirmed" TEXT,
79 "notify_email_secret" TEXT UNIQUE,
80 "notify_email_secret_expiry" TIMESTAMPTZ,
81 "notify_email_lock_expiry" TIMESTAMPTZ,
82 "password_reset_secret" TEXT UNIQUE,
83 "password_reset_secret_expiry" TIMESTAMPTZ,
84 "name" TEXT NOT NULL UNIQUE,
85 "identification" TEXT UNIQUE,
86 "organizational_unit" TEXT,
87 "internal_posts" TEXT,
88 "realname" TEXT,
89 "birthday" DATE,
90 "address" TEXT,
91 "email" TEXT,
92 "xmpp_address" TEXT,
93 "website" TEXT,
94 "phone" TEXT,
95 "mobile_phone" TEXT,
96 "profession" TEXT,
97 "external_memberships" TEXT,
98 "external_posts" TEXT,
99 "statement" TEXT,
100 "text_search_data" TSVECTOR );
101 CREATE INDEX "member_active_idx" ON "member" ("active");
102 CREATE INDEX "member_text_search_data_idx" ON "member" USING gin ("text_search_data");
103 CREATE TRIGGER "update_text_search_data"
104 BEFORE INSERT OR UPDATE ON "member"
105 FOR EACH ROW EXECUTE PROCEDURE
106 tsvector_update_trigger('text_search_data', 'pg_catalog.simple',
107 "name", "identification", "organizational_unit", "internal_posts",
108 "realname", "external_memberships", "external_posts", "statement" );
110 COMMENT ON TABLE "member" IS 'Users of the system, e.g. members of an organization';
112 COMMENT ON COLUMN "member"."last_login" IS 'Timestamp of last login';
113 COMMENT ON COLUMN "member"."last_login_public" IS 'Date of last login (time stripped for privacy reasons, updated only after day change)';
114 COMMENT ON COLUMN "member"."login" IS 'Login name';
115 COMMENT ON COLUMN "member"."password" IS 'Password (preferably as crypto-hash, depending on the frontend or access layer)';
116 COMMENT ON COLUMN "member"."locked" IS 'Locked members can not log in.';
117 COMMENT ON COLUMN "member"."active" IS 'Memberships, support and votes are taken into account when corresponding members are marked as active. When the user does not log in for an extended period of time, this flag may be set to FALSE. If the user is not locked, he/she may reset the active flag by logging in.';
118 COMMENT ON COLUMN "member"."admin" IS 'TRUE for admins, which can administrate other users and setup policies and areas';
119 COMMENT ON COLUMN "member"."notify_email" IS 'Email address where notifications of the system are sent to';
120 COMMENT ON COLUMN "member"."notify_email_unconfirmed" IS 'Unconfirmed email address provided by the member to be copied into "notify_email" field after verification';
121 COMMENT ON COLUMN "member"."notify_email_secret" IS 'Secret sent to the address in "notify_email_unconformed"';
122 COMMENT ON COLUMN "member"."notify_email_secret_expiry" IS 'Expiry date/time for "notify_email_secret"';
123 COMMENT ON COLUMN "member"."notify_email_lock_expiry" IS 'Date/time until no further email confirmation mails may be sent (abuse protection)';
124 COMMENT ON COLUMN "member"."name" IS 'Distinct name of the member';
125 COMMENT ON COLUMN "member"."identification" IS 'Optional identification number or code of the member';
126 COMMENT ON COLUMN "member"."organizational_unit" IS 'Branch or division of the organization the member belongs to';
127 COMMENT ON COLUMN "member"."internal_posts" IS 'Posts (offices) of the member inside the organization';
128 COMMENT ON COLUMN "member"."realname" IS 'Real name of the member, may be identical with "name"';
129 COMMENT ON COLUMN "member"."email" IS 'Published email address of the member; not used for system notifications';
130 COMMENT ON COLUMN "member"."external_memberships" IS 'Other organizations the member is involved in';
131 COMMENT ON COLUMN "member"."external_posts" IS 'Posts (offices) outside the organization';
132 COMMENT ON COLUMN "member"."statement" IS 'Freely chosen text of the member for his homepage within the system';
135 CREATE TABLE "member_history" (
136 "id" SERIAL8 PRIMARY KEY,
137 "member_id" INT4 NOT NULL REFERENCES "member" ("id") ON DELETE CASCADE ON UPDATE CASCADE,
138 "until" TIMESTAMPTZ NOT NULL DEFAULT now(),
139 "active" BOOLEAN NOT NULL,
140 "name" TEXT NOT NULL );
141 CREATE INDEX "member_history_member_id_idx" ON "member_history" ("member_id");
143 COMMENT ON TABLE "member_history" IS 'Filled by trigger; keeps information about old names and active flag of members';
145 COMMENT ON COLUMN "member_history"."id" IS 'Primary key, which can be used to sort entries correctly (and time warp resistant)';
146 COMMENT ON COLUMN "member_history"."until" IS 'Timestamp until the data was valid';
149 CREATE TABLE "invite_code" (
150 "code" TEXT PRIMARY KEY,
151 "created" TIMESTAMPTZ NOT NULL DEFAULT now(),
152 "used" TIMESTAMPTZ,
153 "member_id" INT4 UNIQUE REFERENCES "member" ("id") ON DELETE SET NULL ON UPDATE CASCADE,
154 "comment" TEXT,
155 CONSTRAINT "only_used_codes_may_refer_to_member" CHECK ("used" NOTNULL OR "member_id" ISNULL) );
157 COMMENT ON TABLE "invite_code" IS 'Invite codes can be used once to create a new member account.';
159 COMMENT ON COLUMN "invite_code"."code" IS 'Secret code';
160 COMMENT ON COLUMN "invite_code"."created" IS 'Time of creation of the secret code';
161 COMMENT ON COLUMN "invite_code"."used" IS 'NULL, if not used yet, otherwise tells when this code was used to create a member account';
162 COMMENT ON COLUMN "invite_code"."member_id" IS 'References the member whose account was created with this code';
163 COMMENT ON COLUMN "invite_code"."comment" IS 'Comment on the code, which is to be used for administrative reasons only';
166 CREATE TABLE "setting" (
167 PRIMARY KEY ("member_id", "key"),
168 "member_id" INT4 REFERENCES "member" ("id") ON DELETE CASCADE ON UPDATE CASCADE,
169 "key" TEXT NOT NULL,
170 "value" TEXT NOT NULL );
171 CREATE INDEX "setting_key_idx" ON "setting" ("key");
173 COMMENT ON TABLE "setting" IS 'Place to store a frontend specific setting for members as a string';
175 COMMENT ON COLUMN "setting"."key" IS 'Name of the setting, preceded by a frontend specific prefix';
178 CREATE TABLE "setting_map" (
179 PRIMARY KEY ("member_id", "key", "subkey"),
180 "member_id" INT4 REFERENCES "member" ("id") ON DELETE CASCADE ON UPDATE CASCADE,
181 "key" TEXT NOT NULL,
182 "subkey" TEXT NOT NULL,
183 "value" TEXT NOT NULL );
184 CREATE INDEX "setting_map_key_idx" ON "setting_map" ("key");
186 COMMENT ON TABLE "setting_map" IS 'Place to store a frontend specific setting for members as a map of key value pairs';
188 COMMENT ON COLUMN "setting_map"."key" IS 'Name of the setting, preceded by a frontend specific prefix';
189 COMMENT ON COLUMN "setting_map"."subkey" IS 'Key of a map entry';
190 COMMENT ON COLUMN "setting_map"."value" IS 'Value of a map entry';
193 CREATE TABLE "member_relation_setting" (
194 PRIMARY KEY ("member_id", "key", "other_member_id"),
195 "member_id" INT4 REFERENCES "member" ("id") ON DELETE CASCADE ON UPDATE CASCADE,
196 "key" TEXT NOT NULL,
197 "other_member_id" INT4 REFERENCES "member" ("id") ON DELETE CASCADE ON UPDATE CASCADE,
198 "value" TEXT NOT NULL );
200 COMMENT ON TABLE "member_relation_setting" IS 'Place to store a frontend specific setting related to relations between members as a string';
203 CREATE TYPE "member_image_type" AS ENUM ('photo', 'avatar');
205 COMMENT ON TYPE "member_image_type" IS 'Types of images for a member';
208 CREATE TABLE "member_image" (
209 PRIMARY KEY ("member_id", "image_type", "scaled"),
210 "member_id" INT4 REFERENCES "member" ("id") ON DELETE CASCADE ON UPDATE CASCADE,
211 "image_type" "member_image_type",
212 "scaled" BOOLEAN,
213 "content_type" TEXT,
214 "data" BYTEA NOT NULL );
216 COMMENT ON TABLE "member_image" IS 'Images of members';
218 COMMENT ON COLUMN "member_image"."scaled" IS 'FALSE for original image, TRUE for scaled version of the image';
221 CREATE TABLE "member_count" (
222 "calculated" TIMESTAMPTZ NOT NULL DEFAULT NOW(),
223 "total_count" INT4 NOT NULL );
225 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';
227 COMMENT ON COLUMN "member_count"."calculated" IS 'timestamp indicating when the total member count and area member counts were calculated';
228 COMMENT ON COLUMN "member_count"."total_count" IS 'Total count of active(!) members';
231 CREATE TABLE "contact" (
232 PRIMARY KEY ("member_id", "other_member_id"),
233 "member_id" INT4 REFERENCES "member" ("id") ON DELETE CASCADE ON UPDATE CASCADE,
234 "other_member_id" INT4 REFERENCES "member" ("id") ON DELETE CASCADE ON UPDATE CASCADE,
235 "public" BOOLEAN NOT NULL DEFAULT FALSE,
236 CONSTRAINT "cant_save_yourself_as_contact"
237 CHECK ("member_id" != "other_member_id") );
239 COMMENT ON TABLE "contact" IS 'Contact lists';
241 COMMENT ON COLUMN "contact"."member_id" IS 'Member having the contact list';
242 COMMENT ON COLUMN "contact"."other_member_id" IS 'Member referenced in the contact list';
243 COMMENT ON COLUMN "contact"."public" IS 'TRUE = display contact publically';
246 CREATE TABLE "session" (
247 "ident" TEXT PRIMARY KEY,
248 "additional_secret" TEXT,
249 "expiry" TIMESTAMPTZ NOT NULL DEFAULT now() + '24 hours',
250 "member_id" INT8 REFERENCES "member" ("id") ON DELETE SET NULL,
251 "lang" TEXT );
252 CREATE INDEX "session_expiry_idx" ON "session" ("expiry");
254 COMMENT ON TABLE "session" IS 'Sessions, i.e. for a web-frontend';
256 COMMENT ON COLUMN "session"."ident" IS 'Secret session identifier (i.e. random string)';
257 COMMENT ON COLUMN "session"."additional_secret" IS 'Additional field to store a secret, which can be used against CSRF attacks';
258 COMMENT ON COLUMN "session"."member_id" IS 'Reference to member, who is logged in';
259 COMMENT ON COLUMN "session"."lang" IS 'Language code of the selected language';
262 CREATE TABLE "policy" (
263 "id" SERIAL4 PRIMARY KEY,
264 "index" INT4 NOT NULL,
265 "active" BOOLEAN NOT NULL DEFAULT TRUE,
266 "name" TEXT NOT NULL UNIQUE,
267 "description" TEXT NOT NULL DEFAULT '',
268 "admission_time" INTERVAL NOT NULL,
269 "discussion_time" INTERVAL NOT NULL,
270 "verification_time" INTERVAL NOT NULL,
271 "voting_time" INTERVAL NOT NULL,
272 "issue_quorum_num" INT4 NOT NULL,
273 "issue_quorum_den" INT4 NOT NULL,
274 "initiative_quorum_num" INT4 NOT NULL,
275 "initiative_quorum_den" INT4 NOT NULL,
276 "majority_num" INT4 NOT NULL DEFAULT 1,
277 "majority_den" INT4 NOT NULL DEFAULT 2,
278 "majority_strict" BOOLEAN NOT NULL DEFAULT TRUE );
279 CREATE INDEX "policy_active_idx" ON "policy" ("active");
281 COMMENT ON TABLE "policy" IS 'Policies for a particular proceeding type (timelimits, quorum)';
283 COMMENT ON COLUMN "policy"."index" IS 'Determines the order in listings';
284 COMMENT ON COLUMN "policy"."active" IS 'TRUE = policy can be used for new issues';
285 COMMENT ON COLUMN "policy"."admission_time" IS 'Maximum time an issue stays open without being "accepted"';
286 COMMENT ON COLUMN "policy"."discussion_time" IS 'Regular time until an issue is "half_frozen" after being "accepted"';
287 COMMENT ON COLUMN "policy"."verification_time" IS 'Regular time until an issue is "fully_frozen" after being "half_frozen"';
288 COMMENT ON COLUMN "policy"."voting_time" IS 'Time after an issue is "fully_frozen" but not "closed"';
289 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"';
290 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"';
291 COMMENT ON COLUMN "policy"."initiative_quorum_num" IS 'Numerator of satisfied supporter quorum to be reached by an initiative to be "admitted" for voting';
292 COMMENT ON COLUMN "policy"."initiative_quorum_den" IS 'Denominator of satisfied supporter quorum to be reached by an initiative to be "admitted" for voting';
293 COMMENT ON COLUMN "policy"."majority_num" IS 'Numerator of fraction of majority to be reached during voting by an initiative to be aggreed upon';
294 COMMENT ON COLUMN "policy"."majority_den" IS 'Denominator of fraction of majority to be reached during voting by an initiative to be aggreed upon';
295 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.';
298 CREATE TABLE "area" (
299 "id" SERIAL4 PRIMARY KEY,
300 "active" BOOLEAN NOT NULL DEFAULT TRUE,
301 "name" TEXT NOT NULL,
302 "description" TEXT NOT NULL DEFAULT '',
303 "direct_member_count" INT4,
304 "member_weight" INT4,
305 "autoreject_weight" INT4,
306 "text_search_data" TSVECTOR );
307 CREATE INDEX "area_active_idx" ON "area" ("active");
308 CREATE INDEX "area_text_search_data_idx" ON "area" USING gin ("text_search_data");
309 CREATE TRIGGER "update_text_search_data"
310 BEFORE INSERT OR UPDATE ON "area"
311 FOR EACH ROW EXECUTE PROCEDURE
312 tsvector_update_trigger('text_search_data', 'pg_catalog.simple',
313 "name", "description" );
315 COMMENT ON TABLE "area" IS 'Subject areas';
317 COMMENT ON COLUMN "area"."active" IS 'TRUE means new issues can be created in this area';
318 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"';
319 COMMENT ON COLUMN "area"."member_weight" IS 'Same as "direct_member_count" but respecting delegations';
320 COMMENT ON COLUMN "area"."autoreject_weight" IS 'Sum of weight of members using the autoreject feature';
323 CREATE TABLE "area_setting" (
324 PRIMARY KEY ("member_id", "key", "area_id"),
325 "member_id" INT4 REFERENCES "member" ("id") ON DELETE CASCADE ON UPDATE CASCADE,
326 "key" TEXT NOT NULL,
327 "area_id" INT4 REFERENCES "area" ("id") ON DELETE CASCADE ON UPDATE CASCADE,
328 "value" TEXT NOT NULL );
330 COMMENT ON TABLE "area_setting" IS 'Place for frontend to store area specific settings of members as strings';
333 CREATE TABLE "allowed_policy" (
334 PRIMARY KEY ("area_id", "policy_id"),
335 "area_id" INT4 REFERENCES "area" ("id") ON DELETE CASCADE ON UPDATE CASCADE,
336 "policy_id" INT4 NOT NULL REFERENCES "policy" ("id") ON DELETE CASCADE ON UPDATE CASCADE,
337 "default_policy" BOOLEAN NOT NULL DEFAULT FALSE );
338 CREATE UNIQUE INDEX "allowed_policy_one_default_per_area_idx" ON "allowed_policy" ("area_id") WHERE "default_policy";
340 COMMENT ON TABLE "allowed_policy" IS 'Selects which policies can be used in each area';
342 COMMENT ON COLUMN "allowed_policy"."default_policy" IS 'One policy per area can be set as default.';
345 CREATE TYPE "snapshot_event" AS ENUM ('periodic', 'end_of_admission', 'half_freeze', 'full_freeze');
347 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';
350 CREATE TABLE "issue" (
351 "id" SERIAL4 PRIMARY KEY,
352 "area_id" INT4 NOT NULL REFERENCES "area" ("id") ON DELETE CASCADE ON UPDATE CASCADE,
353 "policy_id" INT4 NOT NULL REFERENCES "policy" ("id") ON DELETE RESTRICT ON UPDATE CASCADE,
354 "created" TIMESTAMPTZ NOT NULL DEFAULT now(),
355 "accepted" TIMESTAMPTZ,
356 "half_frozen" TIMESTAMPTZ,
357 "fully_frozen" TIMESTAMPTZ,
358 "closed" TIMESTAMPTZ,
359 "ranks_available" BOOLEAN NOT NULL DEFAULT FALSE,
360 "cleaned" TIMESTAMPTZ,
361 "admission_time" INTERVAL NOT NULL,
362 "discussion_time" INTERVAL NOT NULL,
363 "verification_time" INTERVAL NOT NULL,
364 "voting_time" INTERVAL NOT NULL,
365 "snapshot" TIMESTAMPTZ,
366 "latest_snapshot_event" "snapshot_event",
367 "population" INT4,
368 "vote_now" INT4,
369 "vote_later" INT4,
370 "voter_count" INT4,
371 CONSTRAINT "valid_state" CHECK (
372 ("accepted" ISNULL AND "half_frozen" ISNULL AND "fully_frozen" ISNULL AND "closed" ISNULL AND "ranks_available" = FALSE) OR
373 ("accepted" ISNULL AND "half_frozen" ISNULL AND "fully_frozen" ISNULL AND "closed" NOTNULL AND "ranks_available" = FALSE) OR
374 ("accepted" NOTNULL AND "half_frozen" ISNULL AND "fully_frozen" ISNULL AND "closed" ISNULL AND "ranks_available" = FALSE) OR
375 ("accepted" NOTNULL AND "half_frozen" ISNULL AND "fully_frozen" ISNULL AND "closed" NOTNULL AND "ranks_available" = FALSE) OR
376 ("accepted" NOTNULL AND "half_frozen" NOTNULL AND "fully_frozen" ISNULL AND "closed" ISNULL AND "ranks_available" = FALSE) OR
377 ("accepted" NOTNULL AND "half_frozen" NOTNULL AND "fully_frozen" ISNULL AND "closed" NOTNULL AND "ranks_available" = FALSE) OR
378 ("accepted" NOTNULL AND "half_frozen" NOTNULL AND "fully_frozen" NOTNULL AND "closed" ISNULL AND "ranks_available" = FALSE) OR
379 ("accepted" NOTNULL AND "half_frozen" NOTNULL AND "fully_frozen" NOTNULL AND "closed" NOTNULL AND "ranks_available" = FALSE) OR
380 ("accepted" NOTNULL AND "half_frozen" NOTNULL AND "fully_frozen" NOTNULL AND "closed" NOTNULL AND "ranks_available" = TRUE) ),
381 CONSTRAINT "state_change_order" CHECK (
382 "created" <= "accepted" AND
383 "accepted" <= "half_frozen" AND
384 "half_frozen" <= "fully_frozen" AND
385 "fully_frozen" <= "closed" ),
386 CONSTRAINT "only_closed_issues_may_be_cleaned" CHECK (
387 "cleaned" ISNULL OR "closed" NOTNULL ),
388 CONSTRAINT "last_snapshot_on_full_freeze"
389 CHECK ("snapshot" = "fully_frozen"), -- NOTE: snapshot can be set, while frozen is NULL yet
390 CONSTRAINT "freeze_requires_snapshot"
391 CHECK ("fully_frozen" ISNULL OR "snapshot" NOTNULL),
392 CONSTRAINT "set_both_or_none_of_snapshot_and_latest_snapshot_event"
393 CHECK ("snapshot" NOTNULL = "latest_snapshot_event" NOTNULL) );
394 CREATE INDEX "issue_area_id_idx" ON "issue" ("area_id");
395 CREATE INDEX "issue_policy_id_idx" ON "issue" ("policy_id");
396 CREATE INDEX "issue_created_idx" ON "issue" ("created");
397 CREATE INDEX "issue_accepted_idx" ON "issue" ("accepted");
398 CREATE INDEX "issue_half_frozen_idx" ON "issue" ("half_frozen");
399 CREATE INDEX "issue_fully_frozen_idx" ON "issue" ("fully_frozen");
400 CREATE INDEX "issue_closed_idx" ON "issue" ("closed");
401 CREATE INDEX "issue_created_idx_open" ON "issue" ("created") WHERE "closed" ISNULL;
402 CREATE INDEX "issue_closed_idx_canceled" ON "issue" ("closed") WHERE "fully_frozen" ISNULL;
404 COMMENT ON TABLE "issue" IS 'Groups of initiatives';
406 COMMENT ON COLUMN "issue"."accepted" IS 'Point in time, when one initiative of issue reached the "issue_quorum"';
407 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.';
408 COMMENT ON COLUMN "issue"."fully_frozen" IS 'Point in time, when "verification_time" has elapsed and voting has started; Frontends must ensure that for fully_frozen issues additionally to the restrictions for half_frozen issues a) initiatives are not created, b) no interest is created or removed, c) no supporters are added or removed, d) no opinions are created, changed or deleted.';
409 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.';
410 COMMENT ON COLUMN "issue"."ranks_available" IS 'TRUE = ranks have been calculated';
411 COMMENT ON COLUMN "issue"."cleaned" IS 'Point in time, when discussion data and votes had been deleted';
412 COMMENT ON COLUMN "issue"."admission_time" IS 'Copied from "policy" table at creation of issue';
413 COMMENT ON COLUMN "issue"."discussion_time" IS 'Copied from "policy" table at creation of issue';
414 COMMENT ON COLUMN "issue"."verification_time" IS 'Copied from "policy" table at creation of issue';
415 COMMENT ON COLUMN "issue"."voting_time" IS 'Copied from "policy" table at creation of issue';
416 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';
417 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';
418 COMMENT ON COLUMN "issue"."population" IS 'Sum of "weight" column in table "direct_population_snapshot"';
419 COMMENT ON COLUMN "issue"."vote_now" IS 'Number of votes in favor of voting now, as calculated from table "direct_interest_snapshot"';
420 COMMENT ON COLUMN "issue"."vote_later" IS 'Number of votes against voting now, as calculated from table "direct_interest_snapshot"';
421 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';
424 CREATE TABLE "issue_setting" (
425 PRIMARY KEY ("member_id", "key", "issue_id"),
426 "member_id" INT4 REFERENCES "member" ("id") ON DELETE CASCADE ON UPDATE CASCADE,
427 "key" TEXT NOT NULL,
428 "issue_id" INT4 REFERENCES "issue" ("id") ON DELETE CASCADE ON UPDATE CASCADE,
429 "value" TEXT NOT NULL );
431 COMMENT ON TABLE "issue_setting" IS 'Place for frontend to store issue specific settings of members as strings';
434 CREATE TABLE "initiative" (
435 UNIQUE ("issue_id", "id"), -- index needed for foreign-key on table "vote"
436 "issue_id" INT4 NOT NULL REFERENCES "issue" ("id") ON DELETE CASCADE ON UPDATE CASCADE,
437 "id" SERIAL4 PRIMARY KEY,
438 "name" TEXT NOT NULL,
439 "discussion_url" TEXT,
440 "created" TIMESTAMPTZ NOT NULL DEFAULT now(),
441 "revoked" TIMESTAMPTZ,
442 "suggested_initiative_id" INT4 REFERENCES "initiative" ("id") ON DELETE CASCADE ON UPDATE CASCADE,
443 "admitted" BOOLEAN,
444 "supporter_count" INT4,
445 "informed_supporter_count" INT4,
446 "satisfied_supporter_count" INT4,
447 "satisfied_informed_supporter_count" INT4,
448 "positive_votes" INT4,
449 "negative_votes" INT4,
450 "agreed" BOOLEAN,
451 "rank" INT4,
452 "text_search_data" TSVECTOR,
453 CONSTRAINT "non_revoked_initiatives_cant_suggest_other"
454 CHECK ("revoked" NOTNULL OR "suggested_initiative_id" ISNULL),
455 CONSTRAINT "revoked_initiatives_cant_be_admitted"
456 CHECK ("revoked" ISNULL OR "admitted" ISNULL),
457 CONSTRAINT "non_admitted_initiatives_cant_contain_voting_results"
458 CHECK (("admitted" NOTNULL AND "admitted" = TRUE) OR ("positive_votes" ISNULL AND "negative_votes" ISNULL AND "agreed" ISNULL)),
459 CONSTRAINT "all_or_none_of_positive_votes_negative_votes_and_agreed_must_be_null"
460 CHECK ("positive_votes" NOTNULL = "negative_votes" NOTNULL AND "positive_votes" NOTNULL = "agreed" NOTNULL),
461 CONSTRAINT "non_agreed_initiatives_cant_get_a_rank"
462 CHECK (("agreed" NOTNULL AND "agreed" = TRUE) OR "rank" ISNULL) );
463 CREATE INDEX "initiative_created_idx" ON "initiative" ("created");
464 CREATE INDEX "initiative_revoked_idx" ON "initiative" ("revoked");
465 CREATE INDEX "initiative_text_search_data_idx" ON "initiative" USING gin ("text_search_data");
466 CREATE TRIGGER "update_text_search_data"
467 BEFORE INSERT OR UPDATE ON "initiative"
468 FOR EACH ROW EXECUTE PROCEDURE
469 tsvector_update_trigger('text_search_data', 'pg_catalog.simple',
470 "name", "discussion_url");
472 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.';
474 COMMENT ON COLUMN "initiative"."discussion_url" IS 'URL pointing to a discussion platform for this initiative';
475 COMMENT ON COLUMN "initiative"."revoked" IS 'Point in time, when one initiator decided to revoke the initiative';
476 COMMENT ON COLUMN "initiative"."admitted" IS 'TRUE, if initiative reaches the "initiative_quorum" when freezing the issue';
477 COMMENT ON COLUMN "initiative"."supporter_count" IS 'Calculated from table "direct_supporter_snapshot"';
478 COMMENT ON COLUMN "initiative"."informed_supporter_count" IS 'Calculated from table "direct_supporter_snapshot"';
479 COMMENT ON COLUMN "initiative"."satisfied_supporter_count" IS 'Calculated from table "direct_supporter_snapshot"';
480 COMMENT ON COLUMN "initiative"."satisfied_informed_supporter_count" IS 'Calculated from table "direct_supporter_snapshot"';
481 COMMENT ON COLUMN "initiative"."positive_votes" IS 'Calculated from table "direct_voter"';
482 COMMENT ON COLUMN "initiative"."negative_votes" IS 'Calculated from table "direct_voter"';
483 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"';
484 COMMENT ON COLUMN "initiative"."rank" IS 'Rank of approved initiatives (winner is 1), calculated from table "direct_voter"';
487 CREATE TABLE "battle" (
488 PRIMARY KEY ("issue_id", "winning_initiative_id", "losing_initiative_id"),
489 "issue_id" INT4,
490 "winning_initiative_id" INT4,
491 FOREIGN KEY ("issue_id", "winning_initiative_id") REFERENCES "initiative" ("issue_id", "id") ON DELETE CASCADE ON UPDATE CASCADE,
492 "losing_initiative_id" INT4,
493 FOREIGN KEY ("issue_id", "losing_initiative_id") REFERENCES "initiative" ("issue_id", "id") ON DELETE CASCADE ON UPDATE CASCADE,
494 "count" INT4 NOT NULL);
496 COMMENT ON TABLE "battle" IS 'Number of members preferring one initiative to another; Filled by "battle_view" when closing an issue';
499 CREATE TABLE "initiative_setting" (
500 PRIMARY KEY ("member_id", "key", "initiative_id"),
501 "member_id" INT4 REFERENCES "member" ("id") ON DELETE CASCADE ON UPDATE CASCADE,
502 "key" TEXT NOT NULL,
503 "initiative_id" INT4 REFERENCES "initiative" ("id") ON DELETE CASCADE ON UPDATE CASCADE,
504 "value" TEXT NOT NULL );
506 COMMENT ON TABLE "initiative_setting" IS 'Place for frontend to store initiative specific settings of members as strings';
509 CREATE TABLE "draft" (
510 UNIQUE ("initiative_id", "id"), -- index needed for foreign-key on table "supporter"
511 "initiative_id" INT4 NOT NULL REFERENCES "initiative" ("id") ON DELETE CASCADE ON UPDATE CASCADE,
512 "id" SERIAL8 PRIMARY KEY,
513 "created" TIMESTAMPTZ NOT NULL DEFAULT now(),
514 "author_id" INT4 NOT NULL REFERENCES "member" ("id") ON DELETE RESTRICT ON UPDATE CASCADE,
515 "formatting_engine" TEXT,
516 "content" TEXT NOT NULL,
517 "text_search_data" TSVECTOR );
518 CREATE INDEX "draft_created_idx" ON "draft" ("created");
519 CREATE INDEX "draft_author_id_created_idx" ON "draft" ("author_id", "created");
520 CREATE INDEX "draft_text_search_data_idx" ON "draft" USING gin ("text_search_data");
521 CREATE TRIGGER "update_text_search_data"
522 BEFORE INSERT OR UPDATE ON "draft"
523 FOR EACH ROW EXECUTE PROCEDURE
524 tsvector_update_trigger('text_search_data', 'pg_catalog.simple', "content");
526 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.';
528 COMMENT ON COLUMN "draft"."formatting_engine" IS 'Allows different formatting engines (i.e. wiki formats) to be used';
529 COMMENT ON COLUMN "draft"."content" IS 'Text of the draft in a format depending on the field "formatting_engine"';
532 CREATE TABLE "rendered_draft" (
533 PRIMARY KEY ("draft_id", "format"),
534 "draft_id" INT8 REFERENCES "draft" ("id") ON DELETE CASCADE ON UPDATE CASCADE,
535 "format" TEXT,
536 "content" TEXT NOT NULL );
538 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)';
541 CREATE TABLE "suggestion" (
542 UNIQUE ("initiative_id", "id"), -- index needed for foreign-key on table "opinion"
543 "initiative_id" INT4 NOT NULL REFERENCES "initiative" ("id") ON DELETE CASCADE ON UPDATE CASCADE,
544 "id" SERIAL8 PRIMARY KEY,
545 "created" TIMESTAMPTZ NOT NULL DEFAULT now(),
546 "author_id" INT4 NOT NULL REFERENCES "member" ("id") ON DELETE RESTRICT ON UPDATE CASCADE,
547 "name" TEXT NOT NULL,
548 "description" TEXT NOT NULL DEFAULT '',
549 "text_search_data" TSVECTOR,
550 "minus2_unfulfilled_count" INT4,
551 "minus2_fulfilled_count" INT4,
552 "minus1_unfulfilled_count" INT4,
553 "minus1_fulfilled_count" INT4,
554 "plus1_unfulfilled_count" INT4,
555 "plus1_fulfilled_count" INT4,
556 "plus2_unfulfilled_count" INT4,
557 "plus2_fulfilled_count" INT4 );
558 CREATE INDEX "suggestion_created_idx" ON "suggestion" ("created");
559 CREATE INDEX "suggestion_author_id_created_idx" ON "suggestion" ("author_id", "created");
560 CREATE INDEX "suggestion_text_search_data_idx" ON "suggestion" USING gin ("text_search_data");
561 CREATE TRIGGER "update_text_search_data"
562 BEFORE INSERT OR UPDATE ON "suggestion"
563 FOR EACH ROW EXECUTE PROCEDURE
564 tsvector_update_trigger('text_search_data', 'pg_catalog.simple',
565 "name", "description");
567 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';
569 COMMENT ON COLUMN "suggestion"."minus2_unfulfilled_count" IS 'Calculated from table "direct_supporter_snapshot", not requiring informed supporters';
570 COMMENT ON COLUMN "suggestion"."minus2_fulfilled_count" IS 'Calculated from table "direct_supporter_snapshot", not requiring informed supporters';
571 COMMENT ON COLUMN "suggestion"."minus1_unfulfilled_count" IS 'Calculated from table "direct_supporter_snapshot", not requiring informed supporters';
572 COMMENT ON COLUMN "suggestion"."minus1_fulfilled_count" IS 'Calculated from table "direct_supporter_snapshot", not requiring informed supporters';
573 COMMENT ON COLUMN "suggestion"."plus1_unfulfilled_count" IS 'Calculated from table "direct_supporter_snapshot", not requiring informed supporters';
574 COMMENT ON COLUMN "suggestion"."plus1_fulfilled_count" IS 'Calculated from table "direct_supporter_snapshot", not requiring informed supporters';
575 COMMENT ON COLUMN "suggestion"."plus2_unfulfilled_count" IS 'Calculated from table "direct_supporter_snapshot", not requiring informed supporters';
576 COMMENT ON COLUMN "suggestion"."plus2_fulfilled_count" IS 'Calculated from table "direct_supporter_snapshot", not requiring informed supporters';
579 CREATE TABLE "suggestion_setting" (
580 PRIMARY KEY ("member_id", "key", "suggestion_id"),
581 "member_id" INT4 REFERENCES "member" ("id") ON DELETE CASCADE ON UPDATE CASCADE,
582 "key" TEXT NOT NULL,
583 "suggestion_id" INT8 REFERENCES "suggestion" ("id") ON DELETE CASCADE ON UPDATE CASCADE,
584 "value" TEXT NOT NULL );
586 COMMENT ON TABLE "suggestion_setting" IS 'Place for frontend to store suggestion specific settings of members as strings';
589 CREATE TABLE "membership" (
590 PRIMARY KEY ("area_id", "member_id"),
591 "area_id" INT4 REFERENCES "area" ("id") ON DELETE CASCADE ON UPDATE CASCADE,
592 "member_id" INT4 REFERENCES "member" ("id") ON DELETE CASCADE ON UPDATE CASCADE,
593 "autoreject" BOOLEAN NOT NULL DEFAULT FALSE );
594 CREATE INDEX "membership_member_id_idx" ON "membership" ("member_id");
596 COMMENT ON TABLE "membership" IS 'Interest of members in topic areas';
598 COMMENT ON COLUMN "membership"."autoreject" IS 'TRUE = member votes against all initiatives, if he is neither direct_ or delegating_voter; Entries in the "interest" table can override this setting.';
601 CREATE TABLE "interest" (
602 PRIMARY KEY ("issue_id", "member_id"),
603 "issue_id" INT4 REFERENCES "issue" ("id") ON DELETE CASCADE ON UPDATE CASCADE,
604 "member_id" INT4 REFERENCES "member" ("id") ON DELETE CASCADE ON UPDATE CASCADE,
605 "autoreject" BOOLEAN,
606 "voting_requested" BOOLEAN );
607 CREATE INDEX "interest_member_id_idx" ON "interest" ("member_id");
609 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.';
611 COMMENT ON COLUMN "interest"."autoreject" IS 'TRUE = member votes against all initiatives in case of not explicitly taking part in the voting procedure';
612 COMMENT ON COLUMN "interest"."voting_requested" IS 'TRUE = member wants to vote now, FALSE = member wants to vote later, NULL = policy rules should apply';
615 CREATE TABLE "ignored_issue" (
616 PRIMARY KEY ("issue_id", "member_id"),
617 "issue_id" INT4 REFERENCES "issue" ("id") ON DELETE CASCADE ON UPDATE CASCADE,
618 "member_id" INT4 REFERENCES "member" ("id") ON DELETE CASCADE ON UPDATE CASCADE,
619 "new" BOOLEAN NOT NULL DEFAULT FALSE,
620 "accepted" BOOLEAN NOT NULL DEFAULT FALSE,
621 "half_frozen" BOOLEAN NOT NULL DEFAULT FALSE,
622 "fully_frozen" BOOLEAN NOT NULL DEFAULT FALSE );
623 CREATE INDEX "ignored_issue_member_id_idx" ON "ignored_issue" ("member_id");
625 COMMENT ON TABLE "ignored_issue" IS 'Table to store member specific options to ignore issues in selected states';
627 COMMENT ON COLUMN "ignored_issue"."new" IS 'Apply when issue is neither closed nor accepted';
628 COMMENT ON COLUMN "ignored_issue"."accepted" IS 'Apply when issue is accepted but not (half_)frozen or closed';
629 COMMENT ON COLUMN "ignored_issue"."half_frozen" IS 'Apply when issue is half_frozen but not fully_frozen or closed';
630 COMMENT ON COLUMN "ignored_issue"."fully_frozen" IS 'Apply when issue is fully_frozen (in voting) and not closed';
633 CREATE TABLE "initiator" (
634 PRIMARY KEY ("initiative_id", "member_id"),
635 "initiative_id" INT4 REFERENCES "initiative" ("id") ON DELETE CASCADE ON UPDATE CASCADE,
636 "member_id" INT4 REFERENCES "member" ("id") ON DELETE CASCADE ON UPDATE CASCADE,
637 "accepted" BOOLEAN );
638 CREATE INDEX "initiator_member_id_idx" ON "initiator" ("member_id");
640 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.';
642 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.';
645 CREATE TABLE "supporter" (
646 "issue_id" INT4 NOT NULL,
647 PRIMARY KEY ("initiative_id", "member_id"),
648 "initiative_id" INT4,
649 "member_id" INT4,
650 "draft_id" INT8 NOT NULL,
651 FOREIGN KEY ("issue_id", "member_id") REFERENCES "interest" ("issue_id", "member_id") ON DELETE CASCADE ON UPDATE CASCADE,
652 FOREIGN KEY ("initiative_id", "draft_id") REFERENCES "draft" ("initiative_id", "id") ON DELETE CASCADE ON UPDATE CASCADE );
653 CREATE INDEX "supporter_member_id_idx" ON "supporter" ("member_id");
655 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.';
657 COMMENT ON COLUMN "supporter"."draft_id" IS 'Latest seen draft, defaults to current draft of the initiative (implemented by trigger "default_for_draft_id")';
660 CREATE TABLE "opinion" (
661 "initiative_id" INT4 NOT NULL,
662 PRIMARY KEY ("suggestion_id", "member_id"),
663 "suggestion_id" INT8,
664 "member_id" INT4,
665 "degree" INT2 NOT NULL CHECK ("degree" >= -2 AND "degree" <= 2 AND "degree" != 0),
666 "fulfilled" BOOLEAN NOT NULL DEFAULT FALSE,
667 FOREIGN KEY ("initiative_id", "suggestion_id") REFERENCES "suggestion" ("initiative_id", "id") ON DELETE CASCADE ON UPDATE CASCADE,
668 FOREIGN KEY ("initiative_id", "member_id") REFERENCES "supporter" ("initiative_id", "member_id") ON DELETE CASCADE ON UPDATE CASCADE );
669 CREATE INDEX "opinion_member_id_initiative_id_idx" ON "opinion" ("member_id", "initiative_id");
671 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.';
673 COMMENT ON COLUMN "opinion"."degree" IS '2 = fulfillment required for support; 1 = fulfillment desired; -1 = fulfillment unwanted; -2 = fulfillment cancels support';
676 CREATE TYPE "delegation_scope" AS ENUM ('global', 'area', 'issue');
678 COMMENT ON TYPE "delegation_scope" IS 'Scope for delegations: ''global'', ''area'', or ''issue'' (order is relevant)';
681 CREATE TABLE "delegation" (
682 "id" SERIAL8 PRIMARY KEY,
683 "truster_id" INT4 NOT NULL REFERENCES "member" ("id") ON DELETE CASCADE ON UPDATE CASCADE,
684 "trustee_id" INT4 REFERENCES "member" ("id") ON DELETE CASCADE ON UPDATE CASCADE,
685 "scope" "delegation_scope" NOT NULL,
686 "area_id" INT4 REFERENCES "area" ("id") ON DELETE CASCADE ON UPDATE CASCADE,
687 "issue_id" INT4 REFERENCES "issue" ("id") ON DELETE CASCADE ON UPDATE CASCADE,
688 CONSTRAINT "cant_delegate_to_yourself" CHECK ("truster_id" != "trustee_id"),
689 CONSTRAINT "no_global_delegation_to_null"
690 CHECK ("trustee_id" NOTNULL OR "scope" != 'global'),
691 CONSTRAINT "area_id_and_issue_id_set_according_to_scope" CHECK (
692 ("scope" = 'global' AND "area_id" ISNULL AND "issue_id" ISNULL ) OR
693 ("scope" = 'area' AND "area_id" NOTNULL AND "issue_id" ISNULL ) OR
694 ("scope" = 'issue' AND "area_id" ISNULL AND "issue_id" NOTNULL) ),
695 UNIQUE ("area_id", "truster_id"),
696 UNIQUE ("issue_id", "truster_id") );
697 CREATE UNIQUE INDEX "delegation_global_truster_id_unique_idx"
698 ON "delegation" ("truster_id") WHERE "scope" = 'global';
699 CREATE INDEX "delegation_truster_id_idx" ON "delegation" ("truster_id");
700 CREATE INDEX "delegation_trustee_id_idx" ON "delegation" ("trustee_id");
702 COMMENT ON TABLE "delegation" IS 'Delegation of vote-weight to other members';
704 COMMENT ON COLUMN "delegation"."area_id" IS 'Reference to area, if delegation is area-wide, otherwise NULL';
705 COMMENT ON COLUMN "delegation"."issue_id" IS 'Reference to issue, if delegation is issue-wide, otherwise NULL';
708 CREATE TABLE "direct_population_snapshot" (
709 PRIMARY KEY ("issue_id", "event", "member_id"),
710 "issue_id" INT4 REFERENCES "issue" ("id") ON DELETE CASCADE ON UPDATE CASCADE,
711 "event" "snapshot_event",
712 "member_id" INT4 REFERENCES "member" ("id") ON DELETE RESTRICT ON UPDATE RESTRICT,
713 "weight" INT4 );
714 CREATE INDEX "direct_population_snapshot_member_id_idx" ON "direct_population_snapshot" ("member_id");
716 COMMENT ON TABLE "direct_population_snapshot" IS 'Snapshot of active members having either a "membership" in the "area" or an "interest" in the "issue"';
718 COMMENT ON COLUMN "direct_population_snapshot"."event" IS 'Reason for snapshot, see "snapshot_event" type for details';
719 COMMENT ON COLUMN "direct_population_snapshot"."weight" IS 'Weight of member (1 or higher) according to "delegating_population_snapshot"';
722 CREATE TABLE "delegating_population_snapshot" (
723 PRIMARY KEY ("issue_id", "event", "member_id"),
724 "issue_id" INT4 REFERENCES "issue" ("id") ON DELETE CASCADE ON UPDATE CASCADE,
725 "event" "snapshot_event",
726 "member_id" INT4 REFERENCES "member" ("id") ON DELETE RESTRICT ON UPDATE RESTRICT,
727 "weight" INT4,
728 "scope" "delegation_scope" NOT NULL,
729 "delegate_member_ids" INT4[] NOT NULL );
730 CREATE INDEX "delegating_population_snapshot_member_id_idx" ON "delegating_population_snapshot" ("member_id");
732 COMMENT ON TABLE "direct_population_snapshot" IS 'Delegations increasing the weight of entries in the "direct_population_snapshot" table';
734 COMMENT ON COLUMN "delegating_population_snapshot"."event" IS 'Reason for snapshot, see "snapshot_event" type for details';
735 COMMENT ON COLUMN "delegating_population_snapshot"."member_id" IS 'Delegating member';
736 COMMENT ON COLUMN "delegating_population_snapshot"."weight" IS 'Intermediate weight';
737 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"';
740 CREATE TABLE "direct_interest_snapshot" (
741 PRIMARY KEY ("issue_id", "event", "member_id"),
742 "issue_id" INT4 REFERENCES "issue" ("id") ON DELETE CASCADE ON UPDATE CASCADE,
743 "event" "snapshot_event",
744 "member_id" INT4 REFERENCES "member" ("id") ON DELETE RESTRICT ON UPDATE RESTRICT,
745 "weight" INT4,
746 "voting_requested" BOOLEAN );
747 CREATE INDEX "direct_interest_snapshot_member_id_idx" ON "direct_interest_snapshot" ("member_id");
749 COMMENT ON TABLE "direct_interest_snapshot" IS 'Snapshot of active members having an "interest" in the "issue"';
751 COMMENT ON COLUMN "direct_interest_snapshot"."event" IS 'Reason for snapshot, see "snapshot_event" type for details';
752 COMMENT ON COLUMN "direct_interest_snapshot"."weight" IS 'Weight of member (1 or higher) according to "delegating_interest_snapshot"';
753 COMMENT ON COLUMN "direct_interest_snapshot"."voting_requested" IS 'Copied from column "voting_requested" of table "interest"';
756 CREATE TABLE "delegating_interest_snapshot" (
757 PRIMARY KEY ("issue_id", "event", "member_id"),
758 "issue_id" INT4 REFERENCES "issue" ("id") ON DELETE CASCADE ON UPDATE CASCADE,
759 "event" "snapshot_event",
760 "member_id" INT4 REFERENCES "member" ("id") ON DELETE RESTRICT ON UPDATE RESTRICT,
761 "weight" INT4,
762 "scope" "delegation_scope" NOT NULL,
763 "delegate_member_ids" INT4[] NOT NULL );
764 CREATE INDEX "delegating_interest_snapshot_member_id_idx" ON "delegating_interest_snapshot" ("member_id");
766 COMMENT ON TABLE "delegating_interest_snapshot" IS 'Delegations increasing the weight of entries in the "direct_interest_snapshot" table';
768 COMMENT ON COLUMN "delegating_interest_snapshot"."event" IS 'Reason for snapshot, see "snapshot_event" type for details';
769 COMMENT ON COLUMN "delegating_interest_snapshot"."member_id" IS 'Delegating member';
770 COMMENT ON COLUMN "delegating_interest_snapshot"."weight" IS 'Intermediate weight';
771 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"';
774 CREATE TABLE "direct_supporter_snapshot" (
775 "issue_id" INT4 NOT NULL,
776 PRIMARY KEY ("initiative_id", "event", "member_id"),
777 "initiative_id" INT4,
778 "event" "snapshot_event",
779 "member_id" INT4 REFERENCES "member" ("id") ON DELETE RESTRICT ON UPDATE RESTRICT,
780 "informed" BOOLEAN NOT NULL,
781 "satisfied" BOOLEAN NOT NULL,
782 FOREIGN KEY ("issue_id", "initiative_id") REFERENCES "initiative" ("issue_id", "id") ON DELETE CASCADE ON UPDATE CASCADE,
783 FOREIGN KEY ("issue_id", "event", "member_id") REFERENCES "direct_interest_snapshot" ("issue_id", "event", "member_id") ON DELETE CASCADE ON UPDATE CASCADE );
784 CREATE INDEX "direct_supporter_snapshot_member_id_idx" ON "direct_supporter_snapshot" ("member_id");
786 COMMENT ON TABLE "direct_supporter_snapshot" IS 'Snapshot of supporters of initiatives (weight is stored in "direct_interest_snapshot")';
788 COMMENT ON COLUMN "direct_supporter_snapshot"."event" IS 'Reason for snapshot, see "snapshot_event" type for details';
789 COMMENT ON COLUMN "direct_supporter_snapshot"."informed" IS 'Supporter has seen the latest draft of the initiative';
790 COMMENT ON COLUMN "direct_supporter_snapshot"."satisfied" IS 'Supporter has no "critical_opinion"s';
793 CREATE TABLE "direct_voter" (
794 PRIMARY KEY ("issue_id", "member_id"),
795 "issue_id" INT4 REFERENCES "issue" ("id") ON DELETE CASCADE ON UPDATE CASCADE,
796 "member_id" INT4 REFERENCES "member" ("id") ON DELETE RESTRICT ON UPDATE RESTRICT,
797 "weight" INT4,
798 "autoreject" BOOLEAN NOT NULL DEFAULT FALSE );
799 CREATE INDEX "direct_voter_member_id_idx" ON "direct_voter" ("member_id");
801 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.';
803 COMMENT ON COLUMN "direct_voter"."weight" IS 'Weight of member (1 or higher) according to "delegating_voter" table';
804 COMMENT ON COLUMN "direct_voter"."autoreject" IS 'Votes were inserted due to "autoreject" feature';
807 CREATE TABLE "delegating_voter" (
808 PRIMARY KEY ("issue_id", "member_id"),
809 "issue_id" INT4 REFERENCES "issue" ("id") ON DELETE CASCADE ON UPDATE CASCADE,
810 "member_id" INT4 REFERENCES "member" ("id") ON DELETE RESTRICT ON UPDATE RESTRICT,
811 "weight" INT4,
812 "scope" "delegation_scope" NOT NULL,
813 "delegate_member_ids" INT4[] NOT NULL );
814 CREATE INDEX "delegating_voter_member_id_idx" ON "delegating_voter" ("member_id");
816 COMMENT ON TABLE "delegating_voter" IS 'Delegations increasing the weight of entries in the "direct_voter" table';
818 COMMENT ON COLUMN "delegating_voter"."member_id" IS 'Delegating member';
819 COMMENT ON COLUMN "delegating_voter"."weight" IS 'Intermediate weight';
820 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"';
823 CREATE TABLE "vote" (
824 "issue_id" INT4 NOT NULL,
825 PRIMARY KEY ("initiative_id", "member_id"),
826 "initiative_id" INT4,
827 "member_id" INT4,
828 "grade" INT4,
829 FOREIGN KEY ("issue_id", "initiative_id") REFERENCES "initiative" ("issue_id", "id") ON DELETE CASCADE ON UPDATE CASCADE,
830 FOREIGN KEY ("issue_id", "member_id") REFERENCES "direct_voter" ("issue_id", "member_id") ON DELETE CASCADE ON UPDATE CASCADE );
831 CREATE INDEX "vote_member_id_idx" ON "vote" ("member_id");
833 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.';
835 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.';
838 CREATE TABLE "contingent" (
839 "time_frame" INTERVAL PRIMARY KEY,
840 "text_entry_limit" INT4,
841 "initiative_limit" INT4 );
843 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.';
845 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';
846 COMMENT ON COLUMN "contingent"."initiative_limit" IS 'Number of new initiatives to be opened by each member within a given time frame';
850 --------------------------------
851 -- Writing of history entries --
852 --------------------------------
854 CREATE FUNCTION "write_member_history_trigger"()
855 RETURNS TRIGGER
856 LANGUAGE 'plpgsql' VOLATILE AS $$
857 BEGIN
858 IF
859 NEW."active" != OLD."active" OR
860 NEW."name" != OLD."name"
861 THEN
862 INSERT INTO "member_history"
863 ("member_id", "active", "name")
864 VALUES (NEW."id", OLD."active", OLD."name");
865 END IF;
866 RETURN NULL;
867 END;
868 $$;
870 CREATE TRIGGER "write_member_history"
871 AFTER UPDATE ON "member" FOR EACH ROW EXECUTE PROCEDURE
872 "write_member_history_trigger"();
874 COMMENT ON FUNCTION "write_member_history_trigger"() IS 'Implementation of trigger "write_member_history" on table "member"';
875 COMMENT ON TRIGGER "write_member_history" ON "member" IS 'When changing certain fields of a member, create a history entry in "member_history" table';
879 ----------------------------
880 -- Additional constraints --
881 ----------------------------
884 CREATE FUNCTION "issue_requires_first_initiative_trigger"()
885 RETURNS TRIGGER
886 LANGUAGE 'plpgsql' VOLATILE AS $$
887 BEGIN
888 IF NOT EXISTS (
889 SELECT NULL FROM "initiative" WHERE "issue_id" = NEW."id"
890 ) THEN
891 --RAISE 'Cannot create issue without an initial initiative.' USING
892 -- ERRCODE = 'integrity_constraint_violation',
893 -- HINT = 'Create issue, initiative, and draft within the same transaction.';
894 RAISE EXCEPTION 'Cannot create issue without an initial initiative.';
895 END IF;
896 RETURN NULL;
897 END;
898 $$;
900 CREATE CONSTRAINT TRIGGER "issue_requires_first_initiative"
901 AFTER INSERT OR UPDATE ON "issue" DEFERRABLE INITIALLY DEFERRED
902 FOR EACH ROW EXECUTE PROCEDURE
903 "issue_requires_first_initiative_trigger"();
905 COMMENT ON FUNCTION "issue_requires_first_initiative_trigger"() IS 'Implementation of trigger "issue_requires_first_initiative" on table "issue"';
906 COMMENT ON TRIGGER "issue_requires_first_initiative" ON "issue" IS 'Ensure that new issues have at least one initiative';
909 CREATE FUNCTION "last_initiative_deletes_issue_trigger"()
910 RETURNS TRIGGER
911 LANGUAGE 'plpgsql' VOLATILE AS $$
912 DECLARE
913 "reference_lost" BOOLEAN;
914 BEGIN
915 IF TG_OP = 'DELETE' THEN
916 "reference_lost" := TRUE;
917 ELSE
918 "reference_lost" := NEW."issue_id" != OLD."issue_id";
919 END IF;
920 IF
921 "reference_lost" AND NOT EXISTS (
922 SELECT NULL FROM "initiative" WHERE "issue_id" = OLD."issue_id"
923 )
924 THEN
925 DELETE FROM "issue" WHERE "id" = OLD."issue_id";
926 END IF;
927 RETURN NULL;
928 END;
929 $$;
931 CREATE CONSTRAINT TRIGGER "last_initiative_deletes_issue"
932 AFTER UPDATE OR DELETE ON "initiative" DEFERRABLE INITIALLY DEFERRED
933 FOR EACH ROW EXECUTE PROCEDURE
934 "last_initiative_deletes_issue_trigger"();
936 COMMENT ON FUNCTION "last_initiative_deletes_issue_trigger"() IS 'Implementation of trigger "last_initiative_deletes_issue" on table "initiative"';
937 COMMENT ON TRIGGER "last_initiative_deletes_issue" ON "initiative" IS 'Removing the last initiative of an issue deletes the issue';
940 CREATE FUNCTION "initiative_requires_first_draft_trigger"()
941 RETURNS TRIGGER
942 LANGUAGE 'plpgsql' VOLATILE AS $$
943 BEGIN
944 IF NOT EXISTS (
945 SELECT NULL FROM "draft" WHERE "initiative_id" = NEW."id"
946 ) THEN
947 --RAISE 'Cannot create initiative without an initial draft.' USING
948 -- ERRCODE = 'integrity_constraint_violation',
949 -- HINT = 'Create issue, initiative and draft within the same transaction.';
950 RAISE EXCEPTION 'Cannot create initiative without an initial draft.';
951 END IF;
952 RETURN NULL;
953 END;
954 $$;
956 CREATE CONSTRAINT TRIGGER "initiative_requires_first_draft"
957 AFTER INSERT OR UPDATE ON "initiative" DEFERRABLE INITIALLY DEFERRED
958 FOR EACH ROW EXECUTE PROCEDURE
959 "initiative_requires_first_draft_trigger"();
961 COMMENT ON FUNCTION "initiative_requires_first_draft_trigger"() IS 'Implementation of trigger "initiative_requires_first_draft" on table "initiative"';
962 COMMENT ON TRIGGER "initiative_requires_first_draft" ON "initiative" IS 'Ensure that new initiatives have at least one draft';
965 CREATE FUNCTION "last_draft_deletes_initiative_trigger"()
966 RETURNS TRIGGER
967 LANGUAGE 'plpgsql' VOLATILE AS $$
968 DECLARE
969 "reference_lost" BOOLEAN;
970 BEGIN
971 IF TG_OP = 'DELETE' THEN
972 "reference_lost" := TRUE;
973 ELSE
974 "reference_lost" := NEW."initiative_id" != OLD."initiative_id";
975 END IF;
976 IF
977 "reference_lost" AND NOT EXISTS (
978 SELECT NULL FROM "draft" WHERE "initiative_id" = OLD."initiative_id"
979 )
980 THEN
981 DELETE FROM "initiative" WHERE "id" = OLD."initiative_id";
982 END IF;
983 RETURN NULL;
984 END;
985 $$;
987 CREATE CONSTRAINT TRIGGER "last_draft_deletes_initiative"
988 AFTER UPDATE OR DELETE ON "draft" DEFERRABLE INITIALLY DEFERRED
989 FOR EACH ROW EXECUTE PROCEDURE
990 "last_draft_deletes_initiative_trigger"();
992 COMMENT ON FUNCTION "last_draft_deletes_initiative_trigger"() IS 'Implementation of trigger "last_draft_deletes_initiative" on table "draft"';
993 COMMENT ON TRIGGER "last_draft_deletes_initiative" ON "draft" IS 'Removing the last draft of an initiative deletes the initiative';
996 CREATE FUNCTION "suggestion_requires_first_opinion_trigger"()
997 RETURNS TRIGGER
998 LANGUAGE 'plpgsql' VOLATILE AS $$
999 BEGIN
1000 IF NOT EXISTS (
1001 SELECT NULL FROM "opinion" WHERE "suggestion_id" = NEW."id"
1002 ) THEN
1003 RAISE EXCEPTION 'Cannot create a suggestion without an opinion.';
1004 END IF;
1005 RETURN NULL;
1006 END;
1007 $$;
1009 CREATE CONSTRAINT TRIGGER "suggestion_requires_first_opinion"
1010 AFTER INSERT OR UPDATE ON "suggestion" DEFERRABLE INITIALLY DEFERRED
1011 FOR EACH ROW EXECUTE PROCEDURE
1012 "suggestion_requires_first_opinion_trigger"();
1014 COMMENT ON FUNCTION "suggestion_requires_first_opinion_trigger"() IS 'Implementation of trigger "suggestion_requires_first_opinion" on table "suggestion"';
1015 COMMENT ON TRIGGER "suggestion_requires_first_opinion" ON "suggestion" IS 'Ensure that new suggestions have at least one opinion';
1018 CREATE FUNCTION "last_opinion_deletes_suggestion_trigger"()
1019 RETURNS TRIGGER
1020 LANGUAGE 'plpgsql' VOLATILE AS $$
1021 DECLARE
1022 "reference_lost" BOOLEAN;
1023 BEGIN
1024 IF TG_OP = 'DELETE' THEN
1025 "reference_lost" := TRUE;
1026 ELSE
1027 "reference_lost" := NEW."suggestion_id" != OLD."suggestion_id";
1028 END IF;
1029 IF
1030 "reference_lost" AND NOT EXISTS (
1031 SELECT NULL FROM "opinion" WHERE "suggestion_id" = OLD."suggestion_id"
1033 THEN
1034 DELETE FROM "suggestion" WHERE "id" = OLD."suggestion_id";
1035 END IF;
1036 RETURN NULL;
1037 END;
1038 $$;
1040 CREATE CONSTRAINT TRIGGER "last_opinion_deletes_suggestion"
1041 AFTER UPDATE OR DELETE ON "opinion" DEFERRABLE INITIALLY DEFERRED
1042 FOR EACH ROW EXECUTE PROCEDURE
1043 "last_opinion_deletes_suggestion_trigger"();
1045 COMMENT ON FUNCTION "last_opinion_deletes_suggestion_trigger"() IS 'Implementation of trigger "last_opinion_deletes_suggestion" on table "opinion"';
1046 COMMENT ON TRIGGER "last_opinion_deletes_suggestion" ON "opinion" IS 'Removing the last opinion of a suggestion deletes the suggestion';
1050 ---------------------------------------------------------------
1051 -- Ensure that votes are not modified when issues are frozen --
1052 ---------------------------------------------------------------
1054 -- NOTE: Frontends should ensure this anyway, but in case of programming
1055 -- errors the following triggers ensure data integrity.
1058 CREATE FUNCTION "forbid_changes_on_closed_issue_trigger"()
1059 RETURNS TRIGGER
1060 LANGUAGE 'plpgsql' VOLATILE AS $$
1061 DECLARE
1062 "issue_id_v" "issue"."id"%TYPE;
1063 "issue_row" "issue"%ROWTYPE;
1064 BEGIN
1065 IF TG_OP = 'DELETE' THEN
1066 "issue_id_v" := OLD."issue_id";
1067 ELSE
1068 "issue_id_v" := NEW."issue_id";
1069 END IF;
1070 SELECT INTO "issue_row" * FROM "issue"
1071 WHERE "id" = "issue_id_v" FOR SHARE;
1072 IF "issue_row"."closed" NOTNULL THEN
1073 RAISE EXCEPTION 'Tried to modify data belonging to a closed issue.';
1074 END IF;
1075 RETURN NULL;
1076 END;
1077 $$;
1079 CREATE TRIGGER "forbid_changes_on_closed_issue"
1080 AFTER INSERT OR UPDATE OR DELETE ON "direct_voter"
1081 FOR EACH ROW EXECUTE PROCEDURE
1082 "forbid_changes_on_closed_issue_trigger"();
1084 CREATE TRIGGER "forbid_changes_on_closed_issue"
1085 AFTER INSERT OR UPDATE OR DELETE ON "delegating_voter"
1086 FOR EACH ROW EXECUTE PROCEDURE
1087 "forbid_changes_on_closed_issue_trigger"();
1089 CREATE TRIGGER "forbid_changes_on_closed_issue"
1090 AFTER INSERT OR UPDATE OR DELETE ON "vote"
1091 FOR EACH ROW EXECUTE PROCEDURE
1092 "forbid_changes_on_closed_issue_trigger"();
1094 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"';
1095 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';
1096 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';
1097 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';
1101 --------------------------------------------------------------------
1102 -- Auto-retrieval of fields only needed for referential integrity --
1103 --------------------------------------------------------------------
1106 CREATE FUNCTION "autofill_issue_id_trigger"()
1107 RETURNS TRIGGER
1108 LANGUAGE 'plpgsql' VOLATILE AS $$
1109 BEGIN
1110 IF NEW."issue_id" ISNULL THEN
1111 SELECT "issue_id" INTO NEW."issue_id"
1112 FROM "initiative" WHERE "id" = NEW."initiative_id";
1113 END IF;
1114 RETURN NEW;
1115 END;
1116 $$;
1118 CREATE TRIGGER "autofill_issue_id" BEFORE INSERT ON "supporter"
1119 FOR EACH ROW EXECUTE PROCEDURE "autofill_issue_id_trigger"();
1121 CREATE TRIGGER "autofill_issue_id" BEFORE INSERT ON "vote"
1122 FOR EACH ROW EXECUTE PROCEDURE "autofill_issue_id_trigger"();
1124 COMMENT ON FUNCTION "autofill_issue_id_trigger"() IS 'Implementation of triggers "autofill_issue_id" on tables "supporter" and "vote"';
1125 COMMENT ON TRIGGER "autofill_issue_id" ON "supporter" IS 'Set "issue_id" field automatically, if NULL';
1126 COMMENT ON TRIGGER "autofill_issue_id" ON "vote" IS 'Set "issue_id" field automatically, if NULL';
1129 CREATE FUNCTION "autofill_initiative_id_trigger"()
1130 RETURNS TRIGGER
1131 LANGUAGE 'plpgsql' VOLATILE AS $$
1132 BEGIN
1133 IF NEW."initiative_id" ISNULL THEN
1134 SELECT "initiative_id" INTO NEW."initiative_id"
1135 FROM "suggestion" WHERE "id" = NEW."suggestion_id";
1136 END IF;
1137 RETURN NEW;
1138 END;
1139 $$;
1141 CREATE TRIGGER "autofill_initiative_id" BEFORE INSERT ON "opinion"
1142 FOR EACH ROW EXECUTE PROCEDURE "autofill_initiative_id_trigger"();
1144 COMMENT ON FUNCTION "autofill_initiative_id_trigger"() IS 'Implementation of trigger "autofill_initiative_id" on table "opinion"';
1145 COMMENT ON TRIGGER "autofill_initiative_id" ON "opinion" IS 'Set "initiative_id" field automatically, if NULL';
1149 -----------------------------------------------------
1150 -- Automatic calculation of certain default values --
1151 -----------------------------------------------------
1154 CREATE FUNCTION "copy_timings_trigger"()
1155 RETURNS TRIGGER
1156 LANGUAGE 'plpgsql' VOLATILE AS $$
1157 DECLARE
1158 "policy_row" "policy"%ROWTYPE;
1159 BEGIN
1160 SELECT * INTO "policy_row" FROM "policy"
1161 WHERE "id" = NEW."policy_id";
1162 IF NEW."admission_time" ISNULL THEN
1163 NEW."admission_time" := "policy_row"."admission_time";
1164 END IF;
1165 IF NEW."discussion_time" ISNULL THEN
1166 NEW."discussion_time" := "policy_row"."discussion_time";
1167 END IF;
1168 IF NEW."verification_time" ISNULL THEN
1169 NEW."verification_time" := "policy_row"."verification_time";
1170 END IF;
1171 IF NEW."voting_time" ISNULL THEN
1172 NEW."voting_time" := "policy_row"."voting_time";
1173 END IF;
1174 RETURN NEW;
1175 END;
1176 $$;
1178 CREATE TRIGGER "copy_timings" BEFORE INSERT OR UPDATE ON "issue"
1179 FOR EACH ROW EXECUTE PROCEDURE "copy_timings_trigger"();
1181 COMMENT ON FUNCTION "copy_timings_trigger"() IS 'Implementation of trigger "copy_timings" on table "issue"';
1182 COMMENT ON TRIGGER "copy_timings" ON "issue" IS 'If timing fields are NULL, copy values from policy.';
1185 CREATE FUNCTION "supporter_default_for_draft_id_trigger"()
1186 RETURNS TRIGGER
1187 LANGUAGE 'plpgsql' VOLATILE AS $$
1188 BEGIN
1189 IF NEW."draft_id" ISNULL THEN
1190 SELECT "id" INTO NEW."draft_id" FROM "current_draft"
1191 WHERE "initiative_id" = NEW."initiative_id";
1192 END IF;
1193 RETURN NEW;
1194 END;
1195 $$;
1197 CREATE TRIGGER "default_for_draft_id" BEFORE INSERT OR UPDATE ON "supporter"
1198 FOR EACH ROW EXECUTE PROCEDURE "supporter_default_for_draft_id_trigger"();
1200 COMMENT ON FUNCTION "supporter_default_for_draft_id_trigger"() IS 'Implementation of trigger "default_for_draft" on table "supporter"';
1201 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';
1205 ----------------------------------------
1206 -- Automatic creation of dependencies --
1207 ----------------------------------------
1210 CREATE FUNCTION "autocreate_interest_trigger"()
1211 RETURNS TRIGGER
1212 LANGUAGE 'plpgsql' VOLATILE AS $$
1213 BEGIN
1214 IF NOT EXISTS (
1215 SELECT NULL FROM "initiative" JOIN "interest"
1216 ON "initiative"."issue_id" = "interest"."issue_id"
1217 WHERE "initiative"."id" = NEW."initiative_id"
1218 AND "interest"."member_id" = NEW."member_id"
1219 ) THEN
1220 BEGIN
1221 INSERT INTO "interest" ("issue_id", "member_id")
1222 SELECT "issue_id", NEW."member_id"
1223 FROM "initiative" WHERE "id" = NEW."initiative_id";
1224 EXCEPTION WHEN unique_violation THEN END;
1225 END IF;
1226 RETURN NEW;
1227 END;
1228 $$;
1230 CREATE TRIGGER "autocreate_interest" BEFORE INSERT ON "supporter"
1231 FOR EACH ROW EXECUTE PROCEDURE "autocreate_interest_trigger"();
1233 COMMENT ON FUNCTION "autocreate_interest_trigger"() IS 'Implementation of trigger "autocreate_interest" on table "supporter"';
1234 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';
1237 CREATE FUNCTION "autocreate_supporter_trigger"()
1238 RETURNS TRIGGER
1239 LANGUAGE 'plpgsql' VOLATILE AS $$
1240 BEGIN
1241 IF NOT EXISTS (
1242 SELECT NULL FROM "suggestion" JOIN "supporter"
1243 ON "suggestion"."initiative_id" = "supporter"."initiative_id"
1244 WHERE "suggestion"."id" = NEW."suggestion_id"
1245 AND "supporter"."member_id" = NEW."member_id"
1246 ) THEN
1247 BEGIN
1248 INSERT INTO "supporter" ("initiative_id", "member_id")
1249 SELECT "initiative_id", NEW."member_id"
1250 FROM "suggestion" WHERE "id" = NEW."suggestion_id";
1251 EXCEPTION WHEN unique_violation THEN END;
1252 END IF;
1253 RETURN NEW;
1254 END;
1255 $$;
1257 CREATE TRIGGER "autocreate_supporter" BEFORE INSERT ON "opinion"
1258 FOR EACH ROW EXECUTE PROCEDURE "autocreate_supporter_trigger"();
1260 COMMENT ON FUNCTION "autocreate_supporter_trigger"() IS 'Implementation of trigger "autocreate_supporter" on table "opinion"';
1261 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.';
1265 ------------------------------------------
1266 -- Views and helper functions for views --
1267 ------------------------------------------
1270 CREATE VIEW "active_delegation" AS
1271 SELECT "delegation".* FROM "delegation"
1272 JOIN "member" ON "delegation"."truster_id" = "member"."id"
1273 WHERE "member"."active" = TRUE;
1275 COMMENT ON VIEW "active_delegation" IS 'Helper view for views "global_delegation", "area_delegation" and "issue_delegation": Contains delegations where the truster_id refers to an active member and includes those delegations where trustee_id is NULL';
1278 CREATE VIEW "global_delegation" AS
1279 SELECT "id", "truster_id", "trustee_id"
1280 FROM "active_delegation" WHERE "scope" = 'global';
1282 COMMENT ON VIEW "global_delegation" IS 'Global delegations from active members';
1285 CREATE VIEW "area_delegation" AS
1286 SELECT DISTINCT ON ("area"."id", "delegation"."truster_id")
1287 "area"."id" AS "area_id",
1288 "delegation"."id",
1289 "delegation"."truster_id",
1290 "delegation"."trustee_id",
1291 "delegation"."scope"
1292 FROM "area" JOIN "active_delegation" AS "delegation"
1293 ON "delegation"."scope" = 'global'
1294 OR "delegation"."area_id" = "area"."id"
1295 ORDER BY
1296 "area"."id",
1297 "delegation"."truster_id",
1298 "delegation"."scope" DESC;
1300 COMMENT ON VIEW "area_delegation" IS 'Resulting area delegations from active members; can include rows with trustee_id set to NULL';
1303 CREATE VIEW "issue_delegation" AS
1304 SELECT DISTINCT ON ("issue"."id", "delegation"."truster_id")
1305 "issue"."id" AS "issue_id",
1306 "delegation"."id",
1307 "delegation"."truster_id",
1308 "delegation"."trustee_id",
1309 "delegation"."scope"
1310 FROM "issue" JOIN "active_delegation" AS "delegation"
1311 ON "delegation"."scope" = 'global'
1312 OR "delegation"."area_id" = "issue"."area_id"
1313 OR "delegation"."issue_id" = "issue"."id"
1314 ORDER BY
1315 "issue"."id",
1316 "delegation"."truster_id",
1317 "delegation"."scope" DESC;
1319 COMMENT ON VIEW "issue_delegation" IS 'Resulting issue delegations from active members; can include rows with trustee_id set to NULL';
1322 CREATE FUNCTION "membership_weight_with_skipping"
1323 ( "area_id_p" "area"."id"%TYPE,
1324 "member_id_p" "member"."id"%TYPE,
1325 "skip_member_ids_p" INT4[] ) -- "member"."id"%TYPE[]
1326 RETURNS INT4
1327 LANGUAGE 'plpgsql' STABLE AS $$
1328 DECLARE
1329 "sum_v" INT4;
1330 "delegation_row" "area_delegation"%ROWTYPE;
1331 BEGIN
1332 "sum_v" := 1;
1333 FOR "delegation_row" IN
1334 SELECT "area_delegation".*
1335 FROM "area_delegation" LEFT JOIN "membership"
1336 ON "membership"."area_id" = "area_id_p"
1337 AND "membership"."member_id" = "area_delegation"."truster_id"
1338 WHERE "area_delegation"."area_id" = "area_id_p"
1339 AND "area_delegation"."trustee_id" = "member_id_p"
1340 AND "membership"."member_id" ISNULL
1341 LOOP
1342 IF NOT
1343 "skip_member_ids_p" @> ARRAY["delegation_row"."truster_id"]
1344 THEN
1345 "sum_v" := "sum_v" + "membership_weight_with_skipping"(
1346 "area_id_p",
1347 "delegation_row"."truster_id",
1348 "skip_member_ids_p" || "delegation_row"."truster_id"
1349 );
1350 END IF;
1351 END LOOP;
1352 RETURN "sum_v";
1353 END;
1354 $$;
1356 COMMENT ON FUNCTION "membership_weight_with_skipping"
1357 ( "area"."id"%TYPE,
1358 "member"."id"%TYPE,
1359 INT4[] )
1360 IS 'Helper function for "membership_weight" function';
1363 CREATE FUNCTION "membership_weight"
1364 ( "area_id_p" "area"."id"%TYPE,
1365 "member_id_p" "member"."id"%TYPE ) -- "member"."id"%TYPE[]
1366 RETURNS INT4
1367 LANGUAGE 'plpgsql' STABLE AS $$
1368 BEGIN
1369 RETURN "membership_weight_with_skipping"(
1370 "area_id_p",
1371 "member_id_p",
1372 ARRAY["member_id_p"]
1373 );
1374 END;
1375 $$;
1377 COMMENT ON FUNCTION "membership_weight"
1378 ( "area"."id"%TYPE,
1379 "member"."id"%TYPE )
1380 IS 'Calculates the potential voting weight of a member in a given area';
1383 CREATE VIEW "member_count_view" AS
1384 SELECT count(1) AS "total_count" FROM "member" WHERE "active";
1386 COMMENT ON VIEW "member_count_view" IS 'View used to update "member_count" table';
1389 CREATE VIEW "area_member_count" AS
1390 SELECT
1391 "area"."id" AS "area_id",
1392 count("member"."id") AS "direct_member_count",
1393 coalesce(
1394 sum(
1395 CASE WHEN "member"."id" NOTNULL THEN
1396 "membership_weight"("area"."id", "member"."id")
1397 ELSE 0 END
1399 ) AS "member_weight",
1400 coalesce(
1401 sum(
1402 CASE WHEN "member"."id" NOTNULL AND "membership"."autoreject" THEN
1403 "membership_weight"("area"."id", "member"."id")
1404 ELSE 0 END
1406 ) AS "autoreject_weight"
1407 FROM "area"
1408 LEFT JOIN "membership"
1409 ON "area"."id" = "membership"."area_id"
1410 LEFT JOIN "member"
1411 ON "membership"."member_id" = "member"."id"
1412 AND "member"."active"
1413 GROUP BY "area"."id";
1415 COMMENT ON VIEW "area_member_count" IS 'View used to update "member_count" column of table "area"';
1418 CREATE VIEW "opening_draft" AS
1419 SELECT "draft".* FROM (
1420 SELECT
1421 "initiative"."id" AS "initiative_id",
1422 min("draft"."id") AS "draft_id"
1423 FROM "initiative" JOIN "draft"
1424 ON "initiative"."id" = "draft"."initiative_id"
1425 GROUP BY "initiative"."id"
1426 ) AS "subquery"
1427 JOIN "draft" ON "subquery"."draft_id" = "draft"."id";
1429 COMMENT ON VIEW "opening_draft" IS 'First drafts of all initiatives';
1432 CREATE VIEW "current_draft" AS
1433 SELECT "draft".* FROM (
1434 SELECT
1435 "initiative"."id" AS "initiative_id",
1436 max("draft"."id") AS "draft_id"
1437 FROM "initiative" JOIN "draft"
1438 ON "initiative"."id" = "draft"."initiative_id"
1439 GROUP BY "initiative"."id"
1440 ) AS "subquery"
1441 JOIN "draft" ON "subquery"."draft_id" = "draft"."id";
1443 COMMENT ON VIEW "current_draft" IS 'All latest drafts for each initiative';
1446 CREATE VIEW "critical_opinion" AS
1447 SELECT * FROM "opinion"
1448 WHERE ("degree" = 2 AND "fulfilled" = FALSE)
1449 OR ("degree" = -2 AND "fulfilled" = TRUE);
1451 COMMENT ON VIEW "critical_opinion" IS 'Opinions currently causing dissatisfaction';
1454 CREATE VIEW "battle_view" AS
1455 SELECT
1456 "issue"."id" AS "issue_id",
1457 "winning_initiative"."id" AS "winning_initiative_id",
1458 "losing_initiative"."id" AS "losing_initiative_id",
1459 sum(
1460 CASE WHEN
1461 coalesce("better_vote"."grade", 0) >
1462 coalesce("worse_vote"."grade", 0)
1463 THEN "direct_voter"."weight" ELSE 0 END
1464 ) AS "count"
1465 FROM "issue"
1466 LEFT JOIN "direct_voter"
1467 ON "issue"."id" = "direct_voter"."issue_id"
1468 JOIN "initiative" AS "winning_initiative"
1469 ON "issue"."id" = "winning_initiative"."issue_id"
1470 AND "winning_initiative"."agreed"
1471 JOIN "initiative" AS "losing_initiative"
1472 ON "issue"."id" = "losing_initiative"."issue_id"
1473 AND "losing_initiative"."agreed"
1474 LEFT JOIN "vote" AS "better_vote"
1475 ON "direct_voter"."member_id" = "better_vote"."member_id"
1476 AND "winning_initiative"."id" = "better_vote"."initiative_id"
1477 LEFT JOIN "vote" AS "worse_vote"
1478 ON "direct_voter"."member_id" = "worse_vote"."member_id"
1479 AND "losing_initiative"."id" = "worse_vote"."initiative_id"
1480 WHERE "issue"."closed" NOTNULL
1481 AND "issue"."cleaned" ISNULL
1482 AND "winning_initiative"."id" != "losing_initiative"."id"
1483 GROUP BY
1484 "issue"."id",
1485 "winning_initiative"."id",
1486 "losing_initiative"."id";
1488 COMMENT ON VIEW "battle_view" IS 'Number of members preferring one initiative to another; Used to fill "battle" table';
1491 CREATE VIEW "expired_session" AS
1492 SELECT * FROM "session" WHERE now() > "expiry";
1494 CREATE RULE "delete" AS ON DELETE TO "expired_session" DO INSTEAD
1495 DELETE FROM "session" WHERE "ident" = OLD."ident";
1497 COMMENT ON VIEW "expired_session" IS 'View containing all expired sessions where DELETE is possible';
1498 COMMENT ON RULE "delete" ON "expired_session" IS 'Rule allowing DELETE on rows in "expired_session" view, i.e. DELETE FROM "expired_session"';
1501 CREATE VIEW "open_issue" AS
1502 SELECT * FROM "issue" WHERE "closed" ISNULL;
1504 COMMENT ON VIEW "open_issue" IS 'All open issues';
1507 CREATE VIEW "issue_with_ranks_missing" AS
1508 SELECT * FROM "issue"
1509 WHERE "fully_frozen" NOTNULL
1510 AND "closed" NOTNULL
1511 AND "ranks_available" = FALSE;
1513 COMMENT ON VIEW "issue_with_ranks_missing" IS 'Issues where voting was finished, but no ranks have been calculated yet';
1516 CREATE VIEW "member_contingent" AS
1517 SELECT
1518 "member"."id" AS "member_id",
1519 "contingent"."time_frame",
1520 CASE WHEN "contingent"."text_entry_limit" NOTNULL THEN
1522 SELECT count(1) FROM "draft"
1523 WHERE "draft"."author_id" = "member"."id"
1524 AND "draft"."created" > now() - "contingent"."time_frame"
1525 ) + (
1526 SELECT count(1) FROM "suggestion"
1527 WHERE "suggestion"."author_id" = "member"."id"
1528 AND "suggestion"."created" > now() - "contingent"."time_frame"
1530 ELSE NULL END AS "text_entry_count",
1531 "contingent"."text_entry_limit",
1532 CASE WHEN "contingent"."initiative_limit" NOTNULL THEN (
1533 SELECT count(1) FROM "opening_draft"
1534 WHERE "opening_draft"."author_id" = "member"."id"
1535 AND "opening_draft"."created" > now() - "contingent"."time_frame"
1536 ) ELSE NULL END AS "initiative_count",
1537 "contingent"."initiative_limit"
1538 FROM "member" CROSS JOIN "contingent";
1540 COMMENT ON VIEW "member_contingent" IS 'Actual counts of text entries and initiatives are calculated per member for each limit in the "contingent" table.';
1542 COMMENT ON COLUMN "member_contingent"."text_entry_count" IS 'Only calculated when "text_entry_limit" is not null in the same row';
1543 COMMENT ON COLUMN "member_contingent"."initiative_count" IS 'Only calculated when "initiative_limit" is not null in the same row';
1546 CREATE VIEW "member_contingent_left" AS
1547 SELECT
1548 "member_id",
1549 max("text_entry_limit" - "text_entry_count") AS "text_entries_left",
1550 max("initiative_limit" - "initiative_count") AS "initiatives_left"
1551 FROM "member_contingent" GROUP BY "member_id";
1553 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.';
1556 CREATE TYPE "timeline_event" AS ENUM (
1557 'issue_created',
1558 'issue_canceled',
1559 'issue_accepted',
1560 'issue_half_frozen',
1561 'issue_finished_without_voting',
1562 'issue_voting_started',
1563 'issue_finished_after_voting',
1564 'initiative_created',
1565 'initiative_revoked',
1566 'draft_created',
1567 'suggestion_created');
1569 COMMENT ON TYPE "timeline_event" IS 'Types of event in timeline tables';
1572 CREATE VIEW "timeline_issue" AS
1573 SELECT
1574 "created" AS "occurrence",
1575 'issue_created'::"timeline_event" AS "event",
1576 "id" AS "issue_id"
1577 FROM "issue"
1578 UNION ALL
1579 SELECT
1580 "closed" AS "occurrence",
1581 'issue_canceled'::"timeline_event" AS "event",
1582 "id" AS "issue_id"
1583 FROM "issue" WHERE "closed" NOTNULL AND "fully_frozen" ISNULL
1584 UNION ALL
1585 SELECT
1586 "accepted" AS "occurrence",
1587 'issue_accepted'::"timeline_event" AS "event",
1588 "id" AS "issue_id"
1589 FROM "issue" WHERE "accepted" NOTNULL
1590 UNION ALL
1591 SELECT
1592 "half_frozen" AS "occurrence",
1593 'issue_half_frozen'::"timeline_event" AS "event",
1594 "id" AS "issue_id"
1595 FROM "issue" WHERE "half_frozen" NOTNULL
1596 UNION ALL
1597 SELECT
1598 "fully_frozen" AS "occurrence",
1599 'issue_voting_started'::"timeline_event" AS "event",
1600 "id" AS "issue_id"
1601 FROM "issue"
1602 WHERE "fully_frozen" NOTNULL
1603 AND ("closed" ISNULL OR "closed" != "fully_frozen")
1604 UNION ALL
1605 SELECT
1606 "closed" AS "occurrence",
1607 CASE WHEN "fully_frozen" = "closed" THEN
1608 'issue_finished_without_voting'::"timeline_event"
1609 ELSE
1610 'issue_finished_after_voting'::"timeline_event"
1611 END AS "event",
1612 "id" AS "issue_id"
1613 FROM "issue" WHERE "closed" NOTNULL AND "fully_frozen" NOTNULL;
1615 COMMENT ON VIEW "timeline_issue" IS 'Helper view for "timeline" view';
1618 CREATE VIEW "timeline_initiative" AS
1619 SELECT
1620 "created" AS "occurrence",
1621 'initiative_created'::"timeline_event" AS "event",
1622 "id" AS "initiative_id"
1623 FROM "initiative"
1624 UNION ALL
1625 SELECT
1626 "revoked" AS "occurrence",
1627 'initiative_revoked'::"timeline_event" AS "event",
1628 "id" AS "initiative_id"
1629 FROM "initiative" WHERE "revoked" NOTNULL;
1631 COMMENT ON VIEW "timeline_initiative" IS 'Helper view for "timeline" view';
1634 CREATE VIEW "timeline_draft" AS
1635 SELECT
1636 "created" AS "occurrence",
1637 'draft_created'::"timeline_event" AS "event",
1638 "id" AS "draft_id"
1639 FROM "draft";
1641 COMMENT ON VIEW "timeline_draft" IS 'Helper view for "timeline" view';
1644 CREATE VIEW "timeline_suggestion" AS
1645 SELECT
1646 "created" AS "occurrence",
1647 'suggestion_created'::"timeline_event" AS "event",
1648 "id" AS "suggestion_id"
1649 FROM "suggestion";
1651 COMMENT ON VIEW "timeline_suggestion" IS 'Helper view for "timeline" view';
1654 CREATE VIEW "timeline" AS
1655 SELECT
1656 "occurrence",
1657 "event",
1658 "issue_id",
1659 NULL AS "initiative_id",
1660 NULL::INT8 AS "draft_id", -- TODO: Why do we need a type-cast here? Is this due to 32 bit architecture?
1661 NULL::INT8 AS "suggestion_id"
1662 FROM "timeline_issue"
1663 UNION ALL
1664 SELECT
1665 "occurrence",
1666 "event",
1667 NULL AS "issue_id",
1668 "initiative_id",
1669 NULL AS "draft_id",
1670 NULL AS "suggestion_id"
1671 FROM "timeline_initiative"
1672 UNION ALL
1673 SELECT
1674 "occurrence",
1675 "event",
1676 NULL AS "issue_id",
1677 NULL AS "initiative_id",
1678 "draft_id",
1679 NULL AS "suggestion_id"
1680 FROM "timeline_draft"
1681 UNION ALL
1682 SELECT
1683 "occurrence",
1684 "event",
1685 NULL AS "issue_id",
1686 NULL AS "initiative_id",
1687 NULL AS "draft_id",
1688 "suggestion_id"
1689 FROM "timeline_suggestion";
1691 COMMENT ON VIEW "timeline" IS 'Aggregation of different events in the system';
1695 --------------------------------------------------
1696 -- Set returning function for delegation chains --
1697 --------------------------------------------------
1700 CREATE TYPE "delegation_chain_loop_tag" AS ENUM
1701 ('first', 'intermediate', 'last', 'repetition');
1703 COMMENT ON TYPE "delegation_chain_loop_tag" IS 'Type for loop tags in "delegation_chain_row" type';
1706 CREATE TYPE "delegation_chain_row" AS (
1707 "index" INT4,
1708 "member_id" INT4,
1709 "member_active" BOOLEAN,
1710 "participation" BOOLEAN,
1711 "overridden" BOOLEAN,
1712 "scope_in" "delegation_scope",
1713 "scope_out" "delegation_scope",
1714 "disabled_out" BOOLEAN,
1715 "loop" "delegation_chain_loop_tag" );
1717 COMMENT ON TYPE "delegation_chain_row" IS 'Type of rows returned by "delegation_chain"(...) functions';
1719 COMMENT ON COLUMN "delegation_chain_row"."index" IS 'Index starting with 0 and counting up';
1720 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';
1721 COMMENT ON COLUMN "delegation_chain_row"."overridden" IS 'True, if an entry with lower index has "participation" set to true';
1722 COMMENT ON COLUMN "delegation_chain_row"."scope_in" IS 'Scope of used incoming delegation';
1723 COMMENT ON COLUMN "delegation_chain_row"."scope_out" IS 'Scope of used outgoing delegation';
1724 COMMENT ON COLUMN "delegation_chain_row"."disabled_out" IS 'Outgoing delegation is explicitly disabled by a delegation with trustee_id set to NULL';
1725 COMMENT ON COLUMN "delegation_chain_row"."loop" IS 'Not null, if member is part of a loop, see "delegation_chain_loop_tag" type';
1728 CREATE FUNCTION "delegation_chain"
1729 ( "member_id_p" "member"."id"%TYPE,
1730 "area_id_p" "area"."id"%TYPE,
1731 "issue_id_p" "issue"."id"%TYPE,
1732 "simulate_trustee_id_p" "member"."id"%TYPE )
1733 RETURNS SETOF "delegation_chain_row"
1734 LANGUAGE 'plpgsql' STABLE AS $$
1735 DECLARE
1736 "issue_row" "issue"%ROWTYPE;
1737 "visited_member_ids" INT4[]; -- "member"."id"%TYPE[]
1738 "loop_member_id_v" "member"."id"%TYPE;
1739 "output_row" "delegation_chain_row";
1740 "output_rows" "delegation_chain_row"[];
1741 "delegation_row" "delegation"%ROWTYPE;
1742 "row_count" INT4;
1743 "i" INT4;
1744 "loop_v" BOOLEAN;
1745 BEGIN
1746 SELECT * INTO "issue_row" FROM "issue" WHERE "id" = "issue_id_p";
1747 "visited_member_ids" := '{}';
1748 "loop_member_id_v" := NULL;
1749 "output_rows" := '{}';
1750 "output_row"."index" := 0;
1751 "output_row"."member_id" := "member_id_p";
1752 "output_row"."member_active" := TRUE;
1753 "output_row"."participation" := FALSE;
1754 "output_row"."overridden" := FALSE;
1755 "output_row"."disabled_out" := FALSE;
1756 "output_row"."scope_out" := NULL;
1757 LOOP
1758 IF "visited_member_ids" @> ARRAY["output_row"."member_id"] THEN
1759 "loop_member_id_v" := "output_row"."member_id";
1760 ELSE
1761 "visited_member_ids" :=
1762 "visited_member_ids" || "output_row"."member_id";
1763 END IF;
1764 IF "output_row"."participation" THEN
1765 "output_row"."overridden" := TRUE;
1766 END IF;
1767 "output_row"."scope_in" := "output_row"."scope_out";
1768 IF EXISTS (
1769 SELECT NULL FROM "member"
1770 WHERE "id" = "output_row"."member_id" AND "active"
1771 ) THEN
1772 IF "area_id_p" ISNULL AND "issue_id_p" ISNULL THEN
1773 SELECT * INTO "delegation_row" FROM "delegation"
1774 WHERE "truster_id" = "output_row"."member_id"
1775 AND "scope" = 'global';
1776 ELSIF "area_id_p" NOTNULL AND "issue_id_p" ISNULL THEN
1777 "output_row"."participation" := EXISTS (
1778 SELECT NULL FROM "membership"
1779 WHERE "area_id" = "area_id_p"
1780 AND "member_id" = "output_row"."member_id"
1781 );
1782 SELECT * INTO "delegation_row" FROM "delegation"
1783 WHERE "truster_id" = "output_row"."member_id"
1784 AND ("scope" = 'global' OR "area_id" = "area_id_p")
1785 ORDER BY "scope" DESC;
1786 ELSIF "area_id_p" ISNULL AND "issue_id_p" NOTNULL THEN
1787 "output_row"."participation" := EXISTS (
1788 SELECT NULL FROM "interest"
1789 WHERE "issue_id" = "issue_id_p"
1790 AND "member_id" = "output_row"."member_id"
1791 );
1792 SELECT * INTO "delegation_row" FROM "delegation"
1793 WHERE "truster_id" = "output_row"."member_id"
1794 AND ("scope" = 'global' OR
1795 "area_id" = "issue_row"."area_id" OR
1796 "issue_id" = "issue_id_p"
1798 ORDER BY "scope" DESC;
1799 ELSE
1800 RAISE EXCEPTION 'Either area_id or issue_id or both must be NULL.';
1801 END IF;
1802 ELSE
1803 "output_row"."member_active" := FALSE;
1804 "output_row"."participation" := FALSE;
1805 "output_row"."scope_out" := NULL;
1806 "delegation_row" := ROW(NULL);
1807 END IF;
1808 IF
1809 "output_row"."member_id" = "member_id_p" AND
1810 "simulate_trustee_id_p" NOTNULL
1811 THEN
1812 "output_row"."scope_out" := CASE
1813 WHEN "area_id_p" ISNULL AND "issue_id_p" ISNULL THEN 'global'
1814 WHEN "area_id_p" NOTNULL AND "issue_id_p" ISNULL THEN 'area'
1815 WHEN "area_id_p" ISNULL AND "issue_id_p" NOTNULL THEN 'issue'
1816 END;
1817 "output_rows" := "output_rows" || "output_row";
1818 "output_row"."member_id" := "simulate_trustee_id_p";
1819 ELSIF "delegation_row"."trustee_id" NOTNULL THEN
1820 "output_row"."scope_out" := "delegation_row"."scope";
1821 "output_rows" := "output_rows" || "output_row";
1822 "output_row"."member_id" := "delegation_row"."trustee_id";
1823 ELSIF "delegation_row"."scope" NOTNULL THEN
1824 "output_row"."scope_out" := "delegation_row"."scope";
1825 "output_row"."disabled_out" := TRUE;
1826 "output_rows" := "output_rows" || "output_row";
1827 EXIT;
1828 ELSE
1829 "output_row"."scope_out" := NULL;
1830 "output_rows" := "output_rows" || "output_row";
1831 EXIT;
1832 END IF;
1833 EXIT WHEN "loop_member_id_v" NOTNULL;
1834 "output_row"."index" := "output_row"."index" + 1;
1835 END LOOP;
1836 "row_count" := array_upper("output_rows", 1);
1837 "i" := 1;
1838 "loop_v" := FALSE;
1839 LOOP
1840 "output_row" := "output_rows"["i"];
1841 EXIT WHEN "output_row" ISNULL;
1842 IF "loop_v" THEN
1843 IF "i" + 1 = "row_count" THEN
1844 "output_row"."loop" := 'last';
1845 ELSIF "i" = "row_count" THEN
1846 "output_row"."loop" := 'repetition';
1847 ELSE
1848 "output_row"."loop" := 'intermediate';
1849 END IF;
1850 ELSIF "output_row"."member_id" = "loop_member_id_v" THEN
1851 "output_row"."loop" := 'first';
1852 "loop_v" := TRUE;
1853 END IF;
1854 IF "area_id_p" ISNULL AND "issue_id_p" ISNULL THEN
1855 "output_row"."participation" := NULL;
1856 END IF;
1857 RETURN NEXT "output_row";
1858 "i" := "i" + 1;
1859 END LOOP;
1860 RETURN;
1861 END;
1862 $$;
1864 COMMENT ON FUNCTION "delegation_chain"
1865 ( "member"."id"%TYPE,
1866 "area"."id"%TYPE,
1867 "issue"."id"%TYPE,
1868 "member"."id"%TYPE )
1869 IS 'Helper function for frontends to display delegation chains; Not part of internal voting logic';
1871 CREATE FUNCTION "delegation_chain"
1872 ( "member_id_p" "member"."id"%TYPE,
1873 "area_id_p" "area"."id"%TYPE,
1874 "issue_id_p" "issue"."id"%TYPE )
1875 RETURNS SETOF "delegation_chain_row"
1876 LANGUAGE 'plpgsql' STABLE AS $$
1877 DECLARE
1878 "result_row" "delegation_chain_row";
1879 BEGIN
1880 FOR "result_row" IN
1881 SELECT * FROM "delegation_chain"(
1882 "member_id_p", "area_id_p", "issue_id_p", NULL
1884 LOOP
1885 RETURN NEXT "result_row";
1886 END LOOP;
1887 RETURN;
1888 END;
1889 $$;
1891 COMMENT ON FUNCTION "delegation_chain"
1892 ( "member"."id"%TYPE,
1893 "area"."id"%TYPE,
1894 "issue"."id"%TYPE )
1895 IS 'Shortcut for "delegation_chain"(...) function where 4th parameter is null';
1899 ------------------------------
1900 -- Comparison by vote count --
1901 ------------------------------
1903 CREATE FUNCTION "vote_ratio"
1904 ( "positive_votes_p" "initiative"."positive_votes"%TYPE,
1905 "negative_votes_p" "initiative"."negative_votes"%TYPE )
1906 RETURNS FLOAT8
1907 LANGUAGE 'plpgsql' STABLE AS $$
1908 BEGIN
1909 IF "positive_votes_p" > 0 AND "negative_votes_p" > 0 THEN
1910 RETURN
1911 "positive_votes_p"::FLOAT8 /
1912 ("positive_votes_p" + "negative_votes_p")::FLOAT8;
1913 ELSIF "positive_votes_p" > 0 THEN
1914 RETURN "positive_votes_p";
1915 ELSIF "negative_votes_p" > 0 THEN
1916 RETURN 1 - "negative_votes_p";
1917 ELSE
1918 RETURN 0.5;
1919 END IF;
1920 END;
1921 $$;
1923 COMMENT ON FUNCTION "vote_ratio"
1924 ( "initiative"."positive_votes"%TYPE,
1925 "initiative"."negative_votes"%TYPE )
1926 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.';
1930 ------------------------------------------------
1931 -- Locking for snapshots and voting procedure --
1932 ------------------------------------------------
1935 CREATE FUNCTION "share_row_lock_issue_trigger"()
1936 RETURNS TRIGGER
1937 LANGUAGE 'plpgsql' VOLATILE AS $$
1938 BEGIN
1939 IF TG_OP = 'UPDATE' OR TG_OP = 'DELETE' THEN
1940 PERFORM NULL FROM "issue" WHERE "id" = OLD."issue_id" FOR SHARE;
1941 END IF;
1942 IF TG_OP = 'INSERT' OR TG_OP = 'UPDATE' THEN
1943 PERFORM NULL FROM "issue" WHERE "id" = NEW."issue_id" FOR SHARE;
1944 RETURN NEW;
1945 ELSE
1946 RETURN OLD;
1947 END IF;
1948 END;
1949 $$;
1951 COMMENT ON FUNCTION "share_row_lock_issue_trigger"() IS 'Implementation of triggers "share_row_lock_issue" on multiple tables';
1954 CREATE FUNCTION "share_row_lock_issue_via_initiative_trigger"()
1955 RETURNS TRIGGER
1956 LANGUAGE 'plpgsql' VOLATILE AS $$
1957 BEGIN
1958 IF TG_OP = 'UPDATE' OR TG_OP = 'DELETE' THEN
1959 PERFORM NULL FROM "issue"
1960 JOIN "initiative" ON "issue"."id" = "initiative"."issue_id"
1961 WHERE "initiative"."id" = OLD."initiative_id"
1962 FOR SHARE OF "issue";
1963 END IF;
1964 IF TG_OP = 'INSERT' OR TG_OP = 'UPDATE' THEN
1965 PERFORM NULL FROM "issue"
1966 JOIN "initiative" ON "issue"."id" = "initiative"."issue_id"
1967 WHERE "initiative"."id" = NEW."initiative_id"
1968 FOR SHARE OF "issue";
1969 RETURN NEW;
1970 ELSE
1971 RETURN OLD;
1972 END IF;
1973 END;
1974 $$;
1976 COMMENT ON FUNCTION "share_row_lock_issue_trigger"() IS 'Implementation of trigger "share_row_lock_issue_via_initiative" on table "opinion"';
1979 CREATE TRIGGER "share_row_lock_issue"
1980 BEFORE INSERT OR UPDATE OR DELETE ON "initiative"
1981 FOR EACH ROW EXECUTE PROCEDURE
1982 "share_row_lock_issue_trigger"();
1984 CREATE TRIGGER "share_row_lock_issue"
1985 BEFORE INSERT OR UPDATE OR DELETE ON "interest"
1986 FOR EACH ROW EXECUTE PROCEDURE
1987 "share_row_lock_issue_trigger"();
1989 CREATE TRIGGER "share_row_lock_issue"
1990 BEFORE INSERT OR UPDATE OR DELETE ON "supporter"
1991 FOR EACH ROW EXECUTE PROCEDURE
1992 "share_row_lock_issue_trigger"();
1994 CREATE TRIGGER "share_row_lock_issue_via_initiative"
1995 BEFORE INSERT OR UPDATE OR DELETE ON "opinion"
1996 FOR EACH ROW EXECUTE PROCEDURE
1997 "share_row_lock_issue_via_initiative_trigger"();
1999 CREATE TRIGGER "share_row_lock_issue"
2000 BEFORE INSERT OR UPDATE OR DELETE ON "direct_voter"
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 "delegating_voter"
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 "vote"
2011 FOR EACH ROW EXECUTE PROCEDURE
2012 "share_row_lock_issue_trigger"();
2014 COMMENT ON TRIGGER "share_row_lock_issue" ON "initiative" IS 'See "lock_issue" function';
2015 COMMENT ON TRIGGER "share_row_lock_issue" ON "interest" IS 'See "lock_issue" function';
2016 COMMENT ON TRIGGER "share_row_lock_issue" ON "supporter" IS 'See "lock_issue" function';
2017 COMMENT ON TRIGGER "share_row_lock_issue_via_initiative" ON "opinion" IS 'See "lock_issue" function';
2018 COMMENT ON TRIGGER "share_row_lock_issue" ON "direct_voter" IS 'See "lock_issue" function';
2019 COMMENT ON TRIGGER "share_row_lock_issue" ON "delegating_voter" IS 'See "lock_issue" function';
2020 COMMENT ON TRIGGER "share_row_lock_issue" ON "vote" IS 'See "lock_issue" function';
2023 CREATE FUNCTION "lock_issue"
2024 ( "issue_id_p" "issue"."id"%TYPE )
2025 RETURNS VOID
2026 LANGUAGE 'plpgsql' VOLATILE AS $$
2027 BEGIN
2028 LOCK TABLE "member" IN SHARE MODE;
2029 LOCK TABLE "membership" IN SHARE MODE;
2030 LOCK TABLE "policy" IN SHARE MODE;
2031 PERFORM NULL FROM "issue" WHERE "id" = "issue_id_p" FOR UPDATE;
2032 -- NOTE: The row-level exclusive lock in combination with the
2033 -- share_row_lock_issue(_via_initiative)_trigger functions (which
2034 -- acquire a row-level share lock on the issue) ensure that no data
2035 -- is changed, which could affect calculation of snapshots or
2036 -- counting of votes. Table "delegation" must be table-level-locked,
2037 -- as it also contains issue- and global-scope delegations.
2038 LOCK TABLE "delegation" IN SHARE MODE;
2039 LOCK TABLE "direct_population_snapshot" IN EXCLUSIVE MODE;
2040 LOCK TABLE "delegating_population_snapshot" IN EXCLUSIVE MODE;
2041 LOCK TABLE "direct_interest_snapshot" IN EXCLUSIVE MODE;
2042 LOCK TABLE "delegating_interest_snapshot" IN EXCLUSIVE MODE;
2043 LOCK TABLE "direct_supporter_snapshot" IN EXCLUSIVE MODE;
2044 RETURN;
2045 END;
2046 $$;
2048 COMMENT ON FUNCTION "lock_issue"
2049 ( "issue"."id"%TYPE )
2050 IS 'Locks the issue and all other data which is used for calculating snapshots or counting votes.';
2054 ------------------------------------------------------------------------
2055 -- Regular tasks, except calculcation of snapshots and voting results --
2056 ------------------------------------------------------------------------
2058 CREATE FUNCTION "check_last_login"()
2059 RETURNS VOID
2060 LANGUAGE 'plpgsql' VOLATILE AS $$
2061 DECLARE
2062 "system_setting_row" "system_setting"%ROWTYPE;
2063 BEGIN
2064 SELECT * INTO "system_setting_row" FROM "system_setting";
2065 LOCK TABLE "member" IN SHARE ROW EXCLUSIVE MODE;
2066 UPDATE "member" SET "last_login_public" = "last_login"::date
2067 FROM (
2068 SELECT DISTINCT "member"."id"
2069 FROM "member" LEFT JOIN "member_history"
2070 ON "member"."id" = "member_history"."member_id"
2071 WHERE "member"."last_login"::date < 'today' OR (
2072 "member_history"."until"::date >= 'today' AND
2073 "member_history"."active" = FALSE AND "member"."active" = TRUE
2075 ) AS "subquery"
2076 WHERE "member"."id" = "subquery"."id";
2077 IF "system_setting_row"."member_ttl" NOTNULL THEN
2078 UPDATE "member" SET "active" = FALSE
2079 WHERE "active" = TRUE
2080 AND "last_login"::date < 'today'
2081 AND "last_login_public" <
2082 (now() - "system_setting_row"."member_ttl")::date;
2083 END IF;
2084 RETURN;
2085 END;
2086 $$;
2088 COMMENT ON FUNCTION "check_last_login"() IS 'Updates "last_login_public" field, which contains the date but not the time of the last login, and deactivates members who do not login for the time specified in "system_setting"."member_ttl". For privacy reasons this function does not update "last_login_public", if the last login of a member has been today (except when member was reactivated today).';
2091 CREATE FUNCTION "calculate_member_counts"()
2092 RETURNS VOID
2093 LANGUAGE 'plpgsql' VOLATILE AS $$
2094 BEGIN
2095 LOCK TABLE "member" IN SHARE MODE;
2096 LOCK TABLE "member_count" IN EXCLUSIVE MODE;
2097 LOCK TABLE "area" IN EXCLUSIVE MODE;
2098 LOCK TABLE "membership" IN SHARE MODE;
2099 DELETE FROM "member_count";
2100 INSERT INTO "member_count" ("total_count")
2101 SELECT "total_count" FROM "member_count_view";
2102 UPDATE "area" SET
2103 "direct_member_count" = "view"."direct_member_count",
2104 "member_weight" = "view"."member_weight",
2105 "autoreject_weight" = "view"."autoreject_weight"
2106 FROM "area_member_count" AS "view"
2107 WHERE "view"."area_id" = "area"."id";
2108 RETURN;
2109 END;
2110 $$;
2112 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"';
2116 ------------------------------
2117 -- Calculation of snapshots --
2118 ------------------------------
2120 CREATE FUNCTION "weight_of_added_delegations_for_population_snapshot"
2121 ( "issue_id_p" "issue"."id"%TYPE,
2122 "member_id_p" "member"."id"%TYPE,
2123 "delegate_member_ids_p" "delegating_population_snapshot"."delegate_member_ids"%TYPE )
2124 RETURNS "direct_population_snapshot"."weight"%TYPE
2125 LANGUAGE 'plpgsql' VOLATILE AS $$
2126 DECLARE
2127 "issue_delegation_row" "issue_delegation"%ROWTYPE;
2128 "delegate_member_ids_v" "delegating_population_snapshot"."delegate_member_ids"%TYPE;
2129 "weight_v" INT4;
2130 "sub_weight_v" INT4;
2131 BEGIN
2132 "weight_v" := 0;
2133 FOR "issue_delegation_row" IN
2134 SELECT * FROM "issue_delegation"
2135 WHERE "trustee_id" = "member_id_p"
2136 AND "issue_id" = "issue_id_p"
2137 LOOP
2138 IF NOT EXISTS (
2139 SELECT NULL FROM "direct_population_snapshot"
2140 WHERE "issue_id" = "issue_id_p"
2141 AND "event" = 'periodic'
2142 AND "member_id" = "issue_delegation_row"."truster_id"
2143 ) AND NOT EXISTS (
2144 SELECT NULL FROM "delegating_population_snapshot"
2145 WHERE "issue_id" = "issue_id_p"
2146 AND "event" = 'periodic'
2147 AND "member_id" = "issue_delegation_row"."truster_id"
2148 ) THEN
2149 "delegate_member_ids_v" :=
2150 "member_id_p" || "delegate_member_ids_p";
2151 INSERT INTO "delegating_population_snapshot" (
2152 "issue_id",
2153 "event",
2154 "member_id",
2155 "scope",
2156 "delegate_member_ids"
2157 ) VALUES (
2158 "issue_id_p",
2159 'periodic',
2160 "issue_delegation_row"."truster_id",
2161 "issue_delegation_row"."scope",
2162 "delegate_member_ids_v"
2163 );
2164 "sub_weight_v" := 1 +
2165 "weight_of_added_delegations_for_population_snapshot"(
2166 "issue_id_p",
2167 "issue_delegation_row"."truster_id",
2168 "delegate_member_ids_v"
2169 );
2170 UPDATE "delegating_population_snapshot"
2171 SET "weight" = "sub_weight_v"
2172 WHERE "issue_id" = "issue_id_p"
2173 AND "event" = 'periodic'
2174 AND "member_id" = "issue_delegation_row"."truster_id";
2175 "weight_v" := "weight_v" + "sub_weight_v";
2176 END IF;
2177 END LOOP;
2178 RETURN "weight_v";
2179 END;
2180 $$;
2182 COMMENT ON FUNCTION "weight_of_added_delegations_for_population_snapshot"
2183 ( "issue"."id"%TYPE,
2184 "member"."id"%TYPE,
2185 "delegating_population_snapshot"."delegate_member_ids"%TYPE )
2186 IS 'Helper function for "create_population_snapshot" function';
2189 CREATE FUNCTION "create_population_snapshot"
2190 ( "issue_id_p" "issue"."id"%TYPE )
2191 RETURNS VOID
2192 LANGUAGE 'plpgsql' VOLATILE AS $$
2193 DECLARE
2194 "member_id_v" "member"."id"%TYPE;
2195 BEGIN
2196 DELETE FROM "direct_population_snapshot"
2197 WHERE "issue_id" = "issue_id_p"
2198 AND "event" = 'periodic';
2199 DELETE FROM "delegating_population_snapshot"
2200 WHERE "issue_id" = "issue_id_p"
2201 AND "event" = 'periodic';
2202 INSERT INTO "direct_population_snapshot"
2203 ("issue_id", "event", "member_id")
2204 SELECT
2205 "issue_id_p" AS "issue_id",
2206 'periodic'::"snapshot_event" AS "event",
2207 "member"."id" AS "member_id"
2208 FROM "issue"
2209 JOIN "area" ON "issue"."area_id" = "area"."id"
2210 JOIN "membership" ON "area"."id" = "membership"."area_id"
2211 JOIN "member" ON "membership"."member_id" = "member"."id"
2212 WHERE "issue"."id" = "issue_id_p"
2213 AND "member"."active"
2214 UNION
2215 SELECT
2216 "issue_id_p" AS "issue_id",
2217 'periodic'::"snapshot_event" AS "event",
2218 "member"."id" AS "member_id"
2219 FROM "interest" JOIN "member"
2220 ON "interest"."member_id" = "member"."id"
2221 WHERE "interest"."issue_id" = "issue_id_p"
2222 AND "member"."active";
2223 FOR "member_id_v" IN
2224 SELECT "member_id" FROM "direct_population_snapshot"
2225 WHERE "issue_id" = "issue_id_p"
2226 AND "event" = 'periodic'
2227 LOOP
2228 UPDATE "direct_population_snapshot" SET
2229 "weight" = 1 +
2230 "weight_of_added_delegations_for_population_snapshot"(
2231 "issue_id_p",
2232 "member_id_v",
2233 '{}'
2235 WHERE "issue_id" = "issue_id_p"
2236 AND "event" = 'periodic'
2237 AND "member_id" = "member_id_v";
2238 END LOOP;
2239 RETURN;
2240 END;
2241 $$;
2243 COMMENT ON FUNCTION "create_population_snapshot"
2244 ( "issue"."id"%TYPE )
2245 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.';
2248 CREATE FUNCTION "weight_of_added_delegations_for_interest_snapshot"
2249 ( "issue_id_p" "issue"."id"%TYPE,
2250 "member_id_p" "member"."id"%TYPE,
2251 "delegate_member_ids_p" "delegating_interest_snapshot"."delegate_member_ids"%TYPE )
2252 RETURNS "direct_interest_snapshot"."weight"%TYPE
2253 LANGUAGE 'plpgsql' VOLATILE AS $$
2254 DECLARE
2255 "issue_delegation_row" "issue_delegation"%ROWTYPE;
2256 "delegate_member_ids_v" "delegating_interest_snapshot"."delegate_member_ids"%TYPE;
2257 "weight_v" INT4;
2258 "sub_weight_v" INT4;
2259 BEGIN
2260 "weight_v" := 0;
2261 FOR "issue_delegation_row" IN
2262 SELECT * FROM "issue_delegation"
2263 WHERE "trustee_id" = "member_id_p"
2264 AND "issue_id" = "issue_id_p"
2265 LOOP
2266 IF NOT EXISTS (
2267 SELECT NULL FROM "direct_interest_snapshot"
2268 WHERE "issue_id" = "issue_id_p"
2269 AND "event" = 'periodic'
2270 AND "member_id" = "issue_delegation_row"."truster_id"
2271 ) AND NOT EXISTS (
2272 SELECT NULL FROM "delegating_interest_snapshot"
2273 WHERE "issue_id" = "issue_id_p"
2274 AND "event" = 'periodic'
2275 AND "member_id" = "issue_delegation_row"."truster_id"
2276 ) THEN
2277 "delegate_member_ids_v" :=
2278 "member_id_p" || "delegate_member_ids_p";
2279 INSERT INTO "delegating_interest_snapshot" (
2280 "issue_id",
2281 "event",
2282 "member_id",
2283 "scope",
2284 "delegate_member_ids"
2285 ) VALUES (
2286 "issue_id_p",
2287 'periodic',
2288 "issue_delegation_row"."truster_id",
2289 "issue_delegation_row"."scope",
2290 "delegate_member_ids_v"
2291 );
2292 "sub_weight_v" := 1 +
2293 "weight_of_added_delegations_for_interest_snapshot"(
2294 "issue_id_p",
2295 "issue_delegation_row"."truster_id",
2296 "delegate_member_ids_v"
2297 );
2298 UPDATE "delegating_interest_snapshot"
2299 SET "weight" = "sub_weight_v"
2300 WHERE "issue_id" = "issue_id_p"
2301 AND "event" = 'periodic'
2302 AND "member_id" = "issue_delegation_row"."truster_id";
2303 "weight_v" := "weight_v" + "sub_weight_v";
2304 END IF;
2305 END LOOP;
2306 RETURN "weight_v";
2307 END;
2308 $$;
2310 COMMENT ON FUNCTION "weight_of_added_delegations_for_interest_snapshot"
2311 ( "issue"."id"%TYPE,
2312 "member"."id"%TYPE,
2313 "delegating_interest_snapshot"."delegate_member_ids"%TYPE )
2314 IS 'Helper function for "create_interest_snapshot" function';
2317 CREATE FUNCTION "create_interest_snapshot"
2318 ( "issue_id_p" "issue"."id"%TYPE )
2319 RETURNS VOID
2320 LANGUAGE 'plpgsql' VOLATILE AS $$
2321 DECLARE
2322 "member_id_v" "member"."id"%TYPE;
2323 BEGIN
2324 DELETE FROM "direct_interest_snapshot"
2325 WHERE "issue_id" = "issue_id_p"
2326 AND "event" = 'periodic';
2327 DELETE FROM "delegating_interest_snapshot"
2328 WHERE "issue_id" = "issue_id_p"
2329 AND "event" = 'periodic';
2330 DELETE FROM "direct_supporter_snapshot"
2331 WHERE "issue_id" = "issue_id_p"
2332 AND "event" = 'periodic';
2333 INSERT INTO "direct_interest_snapshot"
2334 ("issue_id", "event", "member_id", "voting_requested")
2335 SELECT
2336 "issue_id_p" AS "issue_id",
2337 'periodic' AS "event",
2338 "member"."id" AS "member_id",
2339 "interest"."voting_requested"
2340 FROM "interest" JOIN "member"
2341 ON "interest"."member_id" = "member"."id"
2342 WHERE "interest"."issue_id" = "issue_id_p"
2343 AND "member"."active";
2344 FOR "member_id_v" IN
2345 SELECT "member_id" FROM "direct_interest_snapshot"
2346 WHERE "issue_id" = "issue_id_p"
2347 AND "event" = 'periodic'
2348 LOOP
2349 UPDATE "direct_interest_snapshot" SET
2350 "weight" = 1 +
2351 "weight_of_added_delegations_for_interest_snapshot"(
2352 "issue_id_p",
2353 "member_id_v",
2354 '{}'
2356 WHERE "issue_id" = "issue_id_p"
2357 AND "event" = 'periodic'
2358 AND "member_id" = "member_id_v";
2359 END LOOP;
2360 INSERT INTO "direct_supporter_snapshot"
2361 ( "issue_id", "initiative_id", "event", "member_id",
2362 "informed", "satisfied" )
2363 SELECT
2364 "issue_id_p" AS "issue_id",
2365 "initiative"."id" AS "initiative_id",
2366 'periodic' AS "event",
2367 "supporter"."member_id" AS "member_id",
2368 "supporter"."draft_id" = "current_draft"."id" AS "informed",
2369 NOT EXISTS (
2370 SELECT NULL FROM "critical_opinion"
2371 WHERE "initiative_id" = "initiative"."id"
2372 AND "member_id" = "supporter"."member_id"
2373 ) AS "satisfied"
2374 FROM "initiative"
2375 JOIN "supporter"
2376 ON "supporter"."initiative_id" = "initiative"."id"
2377 JOIN "current_draft"
2378 ON "initiative"."id" = "current_draft"."initiative_id"
2379 JOIN "direct_interest_snapshot"
2380 ON "supporter"."member_id" = "direct_interest_snapshot"."member_id"
2381 AND "initiative"."issue_id" = "direct_interest_snapshot"."issue_id"
2382 AND "event" = 'periodic'
2383 WHERE "initiative"."issue_id" = "issue_id_p";
2384 RETURN;
2385 END;
2386 $$;
2388 COMMENT ON FUNCTION "create_interest_snapshot"
2389 ( "issue"."id"%TYPE )
2390 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.';
2393 CREATE FUNCTION "create_snapshot"
2394 ( "issue_id_p" "issue"."id"%TYPE )
2395 RETURNS VOID
2396 LANGUAGE 'plpgsql' VOLATILE AS $$
2397 DECLARE
2398 "initiative_id_v" "initiative"."id"%TYPE;
2399 "suggestion_id_v" "suggestion"."id"%TYPE;
2400 BEGIN
2401 PERFORM "lock_issue"("issue_id_p");
2402 PERFORM "create_population_snapshot"("issue_id_p");
2403 PERFORM "create_interest_snapshot"("issue_id_p");
2404 UPDATE "issue" SET
2405 "snapshot" = now(),
2406 "latest_snapshot_event" = 'periodic',
2407 "population" = (
2408 SELECT coalesce(sum("weight"), 0)
2409 FROM "direct_population_snapshot"
2410 WHERE "issue_id" = "issue_id_p"
2411 AND "event" = 'periodic'
2412 ),
2413 "vote_now" = (
2414 SELECT coalesce(sum("weight"), 0)
2415 FROM "direct_interest_snapshot"
2416 WHERE "issue_id" = "issue_id_p"
2417 AND "event" = 'periodic'
2418 AND "voting_requested" = TRUE
2419 ),
2420 "vote_later" = (
2421 SELECT coalesce(sum("weight"), 0)
2422 FROM "direct_interest_snapshot"
2423 WHERE "issue_id" = "issue_id_p"
2424 AND "event" = 'periodic'
2425 AND "voting_requested" = FALSE
2427 WHERE "id" = "issue_id_p";
2428 FOR "initiative_id_v" IN
2429 SELECT "id" FROM "initiative" WHERE "issue_id" = "issue_id_p"
2430 LOOP
2431 UPDATE "initiative" SET
2432 "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 ),
2442 "informed_supporter_count" = (
2443 SELECT coalesce(sum("di"."weight"), 0)
2444 FROM "direct_interest_snapshot" AS "di"
2445 JOIN "direct_supporter_snapshot" AS "ds"
2446 ON "di"."member_id" = "ds"."member_id"
2447 WHERE "di"."issue_id" = "issue_id_p"
2448 AND "di"."event" = 'periodic'
2449 AND "ds"."initiative_id" = "initiative_id_v"
2450 AND "ds"."event" = 'periodic'
2451 AND "ds"."informed"
2452 ),
2453 "satisfied_supporter_count" = (
2454 SELECT coalesce(sum("di"."weight"), 0)
2455 FROM "direct_interest_snapshot" AS "di"
2456 JOIN "direct_supporter_snapshot" AS "ds"
2457 ON "di"."member_id" = "ds"."member_id"
2458 WHERE "di"."issue_id" = "issue_id_p"
2459 AND "di"."event" = 'periodic'
2460 AND "ds"."initiative_id" = "initiative_id_v"
2461 AND "ds"."event" = 'periodic'
2462 AND "ds"."satisfied"
2463 ),
2464 "satisfied_informed_supporter_count" = (
2465 SELECT coalesce(sum("di"."weight"), 0)
2466 FROM "direct_interest_snapshot" AS "di"
2467 JOIN "direct_supporter_snapshot" AS "ds"
2468 ON "di"."member_id" = "ds"."member_id"
2469 WHERE "di"."issue_id" = "issue_id_p"
2470 AND "di"."event" = 'periodic'
2471 AND "ds"."initiative_id" = "initiative_id_v"
2472 AND "ds"."event" = 'periodic'
2473 AND "ds"."informed"
2474 AND "ds"."satisfied"
2476 WHERE "id" = "initiative_id_v";
2477 FOR "suggestion_id_v" IN
2478 SELECT "id" FROM "suggestion"
2479 WHERE "initiative_id" = "initiative_id_v"
2480 LOOP
2481 UPDATE "suggestion" SET
2482 "minus2_unfulfilled_count" = (
2483 SELECT coalesce(sum("snapshot"."weight"), 0)
2484 FROM "issue" CROSS JOIN "opinion"
2485 JOIN "direct_interest_snapshot" AS "snapshot"
2486 ON "snapshot"."issue_id" = "issue"."id"
2487 AND "snapshot"."event" = "issue"."latest_snapshot_event"
2488 AND "snapshot"."member_id" = "opinion"."member_id"
2489 WHERE "issue"."id" = "issue_id_p"
2490 AND "opinion"."suggestion_id" = "suggestion_id_v"
2491 AND "opinion"."degree" = -2
2492 AND "opinion"."fulfilled" = FALSE
2493 ),
2494 "minus2_fulfilled_count" = (
2495 SELECT coalesce(sum("snapshot"."weight"), 0)
2496 FROM "issue" CROSS JOIN "opinion"
2497 JOIN "direct_interest_snapshot" AS "snapshot"
2498 ON "snapshot"."issue_id" = "issue"."id"
2499 AND "snapshot"."event" = "issue"."latest_snapshot_event"
2500 AND "snapshot"."member_id" = "opinion"."member_id"
2501 WHERE "issue"."id" = "issue_id_p"
2502 AND "opinion"."suggestion_id" = "suggestion_id_v"
2503 AND "opinion"."degree" = -2
2504 AND "opinion"."fulfilled" = TRUE
2505 ),
2506 "minus1_unfulfilled_count" = (
2507 SELECT coalesce(sum("snapshot"."weight"), 0)
2508 FROM "issue" CROSS JOIN "opinion"
2509 JOIN "direct_interest_snapshot" AS "snapshot"
2510 ON "snapshot"."issue_id" = "issue"."id"
2511 AND "snapshot"."event" = "issue"."latest_snapshot_event"
2512 AND "snapshot"."member_id" = "opinion"."member_id"
2513 WHERE "issue"."id" = "issue_id_p"
2514 AND "opinion"."suggestion_id" = "suggestion_id_v"
2515 AND "opinion"."degree" = -1
2516 AND "opinion"."fulfilled" = FALSE
2517 ),
2518 "minus1_fulfilled_count" = (
2519 SELECT coalesce(sum("snapshot"."weight"), 0)
2520 FROM "issue" CROSS JOIN "opinion"
2521 JOIN "direct_interest_snapshot" AS "snapshot"
2522 ON "snapshot"."issue_id" = "issue"."id"
2523 AND "snapshot"."event" = "issue"."latest_snapshot_event"
2524 AND "snapshot"."member_id" = "opinion"."member_id"
2525 WHERE "issue"."id" = "issue_id_p"
2526 AND "opinion"."suggestion_id" = "suggestion_id_v"
2527 AND "opinion"."degree" = -1
2528 AND "opinion"."fulfilled" = TRUE
2529 ),
2530 "plus1_unfulfilled_count" = (
2531 SELECT coalesce(sum("snapshot"."weight"), 0)
2532 FROM "issue" CROSS JOIN "opinion"
2533 JOIN "direct_interest_snapshot" AS "snapshot"
2534 ON "snapshot"."issue_id" = "issue"."id"
2535 AND "snapshot"."event" = "issue"."latest_snapshot_event"
2536 AND "snapshot"."member_id" = "opinion"."member_id"
2537 WHERE "issue"."id" = "issue_id_p"
2538 AND "opinion"."suggestion_id" = "suggestion_id_v"
2539 AND "opinion"."degree" = 1
2540 AND "opinion"."fulfilled" = FALSE
2541 ),
2542 "plus1_fulfilled_count" = (
2543 SELECT coalesce(sum("snapshot"."weight"), 0)
2544 FROM "issue" CROSS JOIN "opinion"
2545 JOIN "direct_interest_snapshot" AS "snapshot"
2546 ON "snapshot"."issue_id" = "issue"."id"
2547 AND "snapshot"."event" = "issue"."latest_snapshot_event"
2548 AND "snapshot"."member_id" = "opinion"."member_id"
2549 WHERE "issue"."id" = "issue_id_p"
2550 AND "opinion"."suggestion_id" = "suggestion_id_v"
2551 AND "opinion"."degree" = 1
2552 AND "opinion"."fulfilled" = TRUE
2553 ),
2554 "plus2_unfulfilled_count" = (
2555 SELECT coalesce(sum("snapshot"."weight"), 0)
2556 FROM "issue" CROSS JOIN "opinion"
2557 JOIN "direct_interest_snapshot" AS "snapshot"
2558 ON "snapshot"."issue_id" = "issue"."id"
2559 AND "snapshot"."event" = "issue"."latest_snapshot_event"
2560 AND "snapshot"."member_id" = "opinion"."member_id"
2561 WHERE "issue"."id" = "issue_id_p"
2562 AND "opinion"."suggestion_id" = "suggestion_id_v"
2563 AND "opinion"."degree" = 2
2564 AND "opinion"."fulfilled" = FALSE
2565 ),
2566 "plus2_fulfilled_count" = (
2567 SELECT coalesce(sum("snapshot"."weight"), 0)
2568 FROM "issue" CROSS JOIN "opinion"
2569 JOIN "direct_interest_snapshot" AS "snapshot"
2570 ON "snapshot"."issue_id" = "issue"."id"
2571 AND "snapshot"."event" = "issue"."latest_snapshot_event"
2572 AND "snapshot"."member_id" = "opinion"."member_id"
2573 WHERE "issue"."id" = "issue_id_p"
2574 AND "opinion"."suggestion_id" = "suggestion_id_v"
2575 AND "opinion"."degree" = 2
2576 AND "opinion"."fulfilled" = TRUE
2578 WHERE "suggestion"."id" = "suggestion_id_v";
2579 END LOOP;
2580 END LOOP;
2581 RETURN;
2582 END;
2583 $$;
2585 COMMENT ON FUNCTION "create_snapshot"
2586 ( "issue"."id"%TYPE )
2587 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.';
2590 CREATE FUNCTION "set_snapshot_event"
2591 ( "issue_id_p" "issue"."id"%TYPE,
2592 "event_p" "snapshot_event" )
2593 RETURNS VOID
2594 LANGUAGE 'plpgsql' VOLATILE AS $$
2595 DECLARE
2596 "event_v" "issue"."latest_snapshot_event"%TYPE;
2597 BEGIN
2598 SELECT "latest_snapshot_event" INTO "event_v" FROM "issue"
2599 WHERE "id" = "issue_id_p" FOR UPDATE;
2600 UPDATE "issue" SET "latest_snapshot_event" = "event_p"
2601 WHERE "id" = "issue_id_p";
2602 UPDATE "direct_population_snapshot" SET "event" = "event_p"
2603 WHERE "issue_id" = "issue_id_p" AND "event" = "event_v";
2604 UPDATE "delegating_population_snapshot" SET "event" = "event_p"
2605 WHERE "issue_id" = "issue_id_p" AND "event" = "event_v";
2606 UPDATE "direct_interest_snapshot" SET "event" = "event_p"
2607 WHERE "issue_id" = "issue_id_p" AND "event" = "event_v";
2608 UPDATE "delegating_interest_snapshot" SET "event" = "event_p"
2609 WHERE "issue_id" = "issue_id_p" AND "event" = "event_v";
2610 UPDATE "direct_supporter_snapshot" SET "event" = "event_p"
2611 WHERE "issue_id" = "issue_id_p" AND "event" = "event_v";
2612 RETURN;
2613 END;
2614 $$;
2616 COMMENT ON FUNCTION "set_snapshot_event"
2617 ( "issue"."id"%TYPE,
2618 "snapshot_event" )
2619 IS 'Change "event" attribute of the previous ''periodic'' snapshot';
2623 ---------------------
2624 -- Freezing issues --
2625 ---------------------
2627 CREATE FUNCTION "freeze_after_snapshot"
2628 ( "issue_id_p" "issue"."id"%TYPE )
2629 RETURNS VOID
2630 LANGUAGE 'plpgsql' VOLATILE AS $$
2631 DECLARE
2632 "issue_row" "issue"%ROWTYPE;
2633 "policy_row" "policy"%ROWTYPE;
2634 "initiative_row" "initiative"%ROWTYPE;
2635 BEGIN
2636 SELECT * INTO "issue_row" FROM "issue" WHERE "id" = "issue_id_p";
2637 SELECT * INTO "policy_row"
2638 FROM "policy" WHERE "id" = "issue_row"."policy_id";
2639 PERFORM "set_snapshot_event"("issue_id_p", 'full_freeze');
2640 UPDATE "issue" SET
2641 "accepted" = coalesce("accepted", now()),
2642 "half_frozen" = coalesce("half_frozen", now()),
2643 "fully_frozen" = now()
2644 WHERE "id" = "issue_id_p";
2645 FOR "initiative_row" IN
2646 SELECT * FROM "initiative"
2647 WHERE "issue_id" = "issue_id_p" AND "revoked" ISNULL
2648 LOOP
2649 IF
2650 "initiative_row"."satisfied_supporter_count" > 0 AND
2651 "initiative_row"."satisfied_supporter_count" *
2652 "policy_row"."initiative_quorum_den" >=
2653 "issue_row"."population" * "policy_row"."initiative_quorum_num"
2654 THEN
2655 UPDATE "initiative" SET "admitted" = TRUE
2656 WHERE "id" = "initiative_row"."id";
2657 ELSE
2658 UPDATE "initiative" SET "admitted" = FALSE
2659 WHERE "id" = "initiative_row"."id";
2660 END IF;
2661 END LOOP;
2662 IF NOT EXISTS (
2663 SELECT NULL FROM "initiative"
2664 WHERE "issue_id" = "issue_id_p" AND "admitted" = TRUE
2665 ) THEN
2666 PERFORM "close_voting"("issue_id_p");
2667 END IF;
2668 RETURN;
2669 END;
2670 $$;
2672 COMMENT ON FUNCTION "freeze_after_snapshot"
2673 ( "issue"."id"%TYPE )
2674 IS 'This function freezes an issue (fully) and starts voting, but must only be called when "create_snapshot" was called in the same transaction.';
2677 CREATE FUNCTION "manual_freeze"("issue_id_p" "issue"."id"%TYPE)
2678 RETURNS VOID
2679 LANGUAGE 'plpgsql' VOLATILE AS $$
2680 DECLARE
2681 "issue_row" "issue"%ROWTYPE;
2682 BEGIN
2683 PERFORM "create_snapshot"("issue_id_p");
2684 PERFORM "freeze_after_snapshot"("issue_id_p");
2685 RETURN;
2686 END;
2687 $$;
2689 COMMENT ON FUNCTION "manual_freeze"
2690 ( "issue"."id"%TYPE )
2691 IS 'Freeze an issue manually (fully) and start voting';
2695 -----------------------
2696 -- Counting of votes --
2697 -----------------------
2700 CREATE FUNCTION "weight_of_added_vote_delegations"
2701 ( "issue_id_p" "issue"."id"%TYPE,
2702 "member_id_p" "member"."id"%TYPE,
2703 "delegate_member_ids_p" "delegating_voter"."delegate_member_ids"%TYPE )
2704 RETURNS "direct_voter"."weight"%TYPE
2705 LANGUAGE 'plpgsql' VOLATILE AS $$
2706 DECLARE
2707 "issue_delegation_row" "issue_delegation"%ROWTYPE;
2708 "delegate_member_ids_v" "delegating_voter"."delegate_member_ids"%TYPE;
2709 "weight_v" INT4;
2710 "sub_weight_v" INT4;
2711 BEGIN
2712 "weight_v" := 0;
2713 FOR "issue_delegation_row" IN
2714 SELECT * FROM "issue_delegation"
2715 WHERE "trustee_id" = "member_id_p"
2716 AND "issue_id" = "issue_id_p"
2717 LOOP
2718 IF NOT EXISTS (
2719 SELECT NULL FROM "direct_voter"
2720 WHERE "member_id" = "issue_delegation_row"."truster_id"
2721 AND "issue_id" = "issue_id_p"
2722 ) AND NOT EXISTS (
2723 SELECT NULL FROM "delegating_voter"
2724 WHERE "member_id" = "issue_delegation_row"."truster_id"
2725 AND "issue_id" = "issue_id_p"
2726 ) THEN
2727 "delegate_member_ids_v" :=
2728 "member_id_p" || "delegate_member_ids_p";
2729 INSERT INTO "delegating_voter" (
2730 "issue_id",
2731 "member_id",
2732 "scope",
2733 "delegate_member_ids"
2734 ) VALUES (
2735 "issue_id_p",
2736 "issue_delegation_row"."truster_id",
2737 "issue_delegation_row"."scope",
2738 "delegate_member_ids_v"
2739 );
2740 "sub_weight_v" := 1 +
2741 "weight_of_added_vote_delegations"(
2742 "issue_id_p",
2743 "issue_delegation_row"."truster_id",
2744 "delegate_member_ids_v"
2745 );
2746 UPDATE "delegating_voter"
2747 SET "weight" = "sub_weight_v"
2748 WHERE "issue_id" = "issue_id_p"
2749 AND "member_id" = "issue_delegation_row"."truster_id";
2750 "weight_v" := "weight_v" + "sub_weight_v";
2751 END IF;
2752 END LOOP;
2753 RETURN "weight_v";
2754 END;
2755 $$;
2757 COMMENT ON FUNCTION "weight_of_added_vote_delegations"
2758 ( "issue"."id"%TYPE,
2759 "member"."id"%TYPE,
2760 "delegating_voter"."delegate_member_ids"%TYPE )
2761 IS 'Helper function for "add_vote_delegations" function';
2764 CREATE FUNCTION "add_vote_delegations"
2765 ( "issue_id_p" "issue"."id"%TYPE )
2766 RETURNS VOID
2767 LANGUAGE 'plpgsql' VOLATILE AS $$
2768 DECLARE
2769 "member_id_v" "member"."id"%TYPE;
2770 BEGIN
2771 FOR "member_id_v" IN
2772 SELECT "member_id" FROM "direct_voter"
2773 WHERE "issue_id" = "issue_id_p"
2774 LOOP
2775 UPDATE "direct_voter" SET
2776 "weight" = "weight" + "weight_of_added_vote_delegations"(
2777 "issue_id_p",
2778 "member_id_v",
2779 '{}'
2781 WHERE "member_id" = "member_id_v"
2782 AND "issue_id" = "issue_id_p";
2783 END LOOP;
2784 RETURN;
2785 END;
2786 $$;
2788 COMMENT ON FUNCTION "add_vote_delegations"
2789 ( "issue_id_p" "issue"."id"%TYPE )
2790 IS 'Helper function for "close_voting" function';
2793 CREATE FUNCTION "close_voting"("issue_id_p" "issue"."id"%TYPE)
2794 RETURNS VOID
2795 LANGUAGE 'plpgsql' VOLATILE AS $$
2796 DECLARE
2797 "issue_row" "issue"%ROWTYPE;
2798 "member_id_v" "member"."id"%TYPE;
2799 BEGIN
2800 PERFORM "lock_issue"("issue_id_p");
2801 SELECT * INTO "issue_row" FROM "issue" WHERE "id" = "issue_id_p";
2802 DELETE FROM "delegating_voter"
2803 WHERE "issue_id" = "issue_id_p";
2804 DELETE FROM "direct_voter"
2805 WHERE "issue_id" = "issue_id_p"
2806 AND "autoreject" = TRUE;
2807 DELETE FROM "direct_voter" USING "member"
2808 WHERE "direct_voter"."member_id" = "member"."id"
2809 AND "direct_voter"."issue_id" = "issue_id_p"
2810 AND "member"."active" = FALSE;
2811 UPDATE "direct_voter" SET "weight" = 1
2812 WHERE "issue_id" = "issue_id_p";
2813 PERFORM "add_vote_delegations"("issue_id_p");
2814 FOR "member_id_v" IN
2815 SELECT "interest"."member_id"
2816 FROM "interest"
2817 JOIN "member"
2818 ON "interest"."member_id" = "member"."id"
2819 LEFT JOIN "direct_voter"
2820 ON "interest"."member_id" = "direct_voter"."member_id"
2821 AND "interest"."issue_id" = "direct_voter"."issue_id"
2822 LEFT JOIN "delegating_voter"
2823 ON "interest"."member_id" = "delegating_voter"."member_id"
2824 AND "interest"."issue_id" = "delegating_voter"."issue_id"
2825 WHERE "interest"."issue_id" = "issue_id_p"
2826 AND "interest"."autoreject" = TRUE
2827 AND "member"."active"
2828 AND "direct_voter"."member_id" ISNULL
2829 AND "delegating_voter"."member_id" ISNULL
2830 UNION SELECT "membership"."member_id"
2831 FROM "membership"
2832 JOIN "member"
2833 ON "membership"."member_id" = "member"."id"
2834 LEFT JOIN "interest"
2835 ON "membership"."member_id" = "interest"."member_id"
2836 AND "interest"."issue_id" = "issue_id_p"
2837 LEFT JOIN "direct_voter"
2838 ON "membership"."member_id" = "direct_voter"."member_id"
2839 AND "direct_voter"."issue_id" = "issue_id_p"
2840 LEFT JOIN "delegating_voter"
2841 ON "membership"."member_id" = "delegating_voter"."member_id"
2842 AND "delegating_voter"."issue_id" = "issue_id_p"
2843 WHERE "membership"."area_id" = "issue_row"."area_id"
2844 AND "membership"."autoreject" = TRUE
2845 AND "member"."active"
2846 AND "interest"."autoreject" ISNULL
2847 AND "direct_voter"."member_id" ISNULL
2848 AND "delegating_voter"."member_id" ISNULL
2849 LOOP
2850 INSERT INTO "direct_voter"
2851 ("member_id", "issue_id", "weight", "autoreject") VALUES
2852 ("member_id_v", "issue_id_p", 1, TRUE);
2853 INSERT INTO "vote" (
2854 "member_id",
2855 "issue_id",
2856 "initiative_id",
2857 "grade"
2858 ) SELECT
2859 "member_id_v" AS "member_id",
2860 "issue_id_p" AS "issue_id",
2861 "id" AS "initiative_id",
2862 -1 AS "grade"
2863 FROM "initiative" WHERE "issue_id" = "issue_id_p";
2864 END LOOP;
2865 PERFORM "add_vote_delegations"("issue_id_p");
2866 UPDATE "issue" SET
2867 "closed" = now(),
2868 "voter_count" = (
2869 SELECT coalesce(sum("weight"), 0)
2870 FROM "direct_voter" WHERE "issue_id" = "issue_id_p"
2872 WHERE "id" = "issue_id_p";
2873 UPDATE "initiative" SET
2874 "positive_votes" = "vote_counts"."positive_votes",
2875 "negative_votes" = "vote_counts"."negative_votes",
2876 "agreed" = CASE WHEN "majority_strict" THEN
2877 "vote_counts"."positive_votes" * "majority_den" >
2878 "majority_num" *
2879 ("vote_counts"."positive_votes"+"vote_counts"."negative_votes")
2880 ELSE
2881 "vote_counts"."positive_votes" * "majority_den" >=
2882 "majority_num" *
2883 ("vote_counts"."positive_votes"+"vote_counts"."negative_votes")
2884 END
2885 FROM
2886 ( SELECT
2887 "initiative"."id" AS "initiative_id",
2888 coalesce(
2889 sum(
2890 CASE WHEN "grade" > 0 THEN "direct_voter"."weight" ELSE 0 END
2891 ),
2893 ) AS "positive_votes",
2894 coalesce(
2895 sum(
2896 CASE WHEN "grade" < 0 THEN "direct_voter"."weight" ELSE 0 END
2897 ),
2899 ) AS "negative_votes"
2900 FROM "initiative"
2901 JOIN "issue" ON "initiative"."issue_id" = "issue"."id"
2902 JOIN "policy" ON "issue"."policy_id" = "policy"."id"
2903 LEFT JOIN "direct_voter"
2904 ON "direct_voter"."issue_id" = "initiative"."issue_id"
2905 LEFT JOIN "vote"
2906 ON "vote"."initiative_id" = "initiative"."id"
2907 AND "vote"."member_id" = "direct_voter"."member_id"
2908 WHERE "initiative"."issue_id" = "issue_id_p"
2909 AND "initiative"."admitted" -- NOTE: NULL case is handled too
2910 GROUP BY "initiative"."id"
2911 ) AS "vote_counts",
2912 "issue",
2913 "policy"
2914 WHERE "vote_counts"."initiative_id" = "initiative"."id"
2915 AND "issue"."id" = "initiative"."issue_id"
2916 AND "policy"."id" = "issue"."policy_id";
2917 -- NOTE: "closed" column of issue must be set at this point
2918 DELETE FROM "battle" WHERE "issue_id" = "issue_id_p";
2919 INSERT INTO "battle" (
2920 "issue_id",
2921 "winning_initiative_id", "losing_initiative_id",
2922 "count"
2923 ) SELECT
2924 "issue_id",
2925 "winning_initiative_id", "losing_initiative_id",
2926 "count"
2927 FROM "battle_view" WHERE "issue_id" = "issue_id_p";
2928 END;
2929 $$;
2931 COMMENT ON FUNCTION "close_voting"
2932 ( "issue"."id"%TYPE )
2933 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.';
2936 CREATE FUNCTION "defeat_strength"
2937 ( "positive_votes_p" INT4, "negative_votes_p" INT4 )
2938 RETURNS INT8
2939 LANGUAGE 'plpgsql' IMMUTABLE AS $$
2940 BEGIN
2941 IF "positive_votes_p" > "negative_votes_p" THEN
2942 RETURN ("positive_votes_p"::INT8 << 31) - "negative_votes_p"::INT8;
2943 ELSIF "positive_votes_p" = "negative_votes_p" THEN
2944 RETURN 0;
2945 ELSE
2946 RETURN -1;
2947 END IF;
2948 END;
2949 $$;
2951 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';
2954 CREATE FUNCTION "array_init_string"("dim_p" INTEGER)
2955 RETURNS TEXT
2956 LANGUAGE 'plpgsql' IMMUTABLE AS $$
2957 DECLARE
2958 "i" INTEGER;
2959 "ary_text_v" TEXT;
2960 BEGIN
2961 IF "dim_p" >= 1 THEN
2962 "ary_text_v" := '{NULL';
2963 "i" := "dim_p";
2964 LOOP
2965 "i" := "i" - 1;
2966 EXIT WHEN "i" = 0;
2967 "ary_text_v" := "ary_text_v" || ',NULL';
2968 END LOOP;
2969 "ary_text_v" := "ary_text_v" || '}';
2970 RETURN "ary_text_v";
2971 ELSE
2972 RAISE EXCEPTION 'Dimension needs to be at least 1.';
2973 END IF;
2974 END;
2975 $$;
2977 COMMENT ON FUNCTION "array_init_string"(INTEGER) IS 'Needed for PostgreSQL < 8.4, due to missing "array_fill" function';
2980 CREATE FUNCTION "square_matrix_init_string"("dim_p" INTEGER)
2981 RETURNS TEXT
2982 LANGUAGE 'plpgsql' IMMUTABLE AS $$
2983 DECLARE
2984 "i" INTEGER;
2985 "row_text_v" TEXT;
2986 "ary_text_v" TEXT;
2987 BEGIN
2988 IF "dim_p" >= 1 THEN
2989 "row_text_v" := '{NULL';
2990 "i" := "dim_p";
2991 LOOP
2992 "i" := "i" - 1;
2993 EXIT WHEN "i" = 0;
2994 "row_text_v" := "row_text_v" || ',NULL';
2995 END LOOP;
2996 "row_text_v" := "row_text_v" || '}';
2997 "ary_text_v" := '{' || "row_text_v";
2998 "i" := "dim_p";
2999 LOOP
3000 "i" := "i" - 1;
3001 EXIT WHEN "i" = 0;
3002 "ary_text_v" := "ary_text_v" || ',' || "row_text_v";
3003 END LOOP;
3004 "ary_text_v" := "ary_text_v" || '}';
3005 RETURN "ary_text_v";
3006 ELSE
3007 RAISE EXCEPTION 'Dimension needs to be at least 1.';
3008 END IF;
3009 END;
3010 $$;
3012 COMMENT ON FUNCTION "square_matrix_init_string"(INTEGER) IS 'Needed for PostgreSQL < 8.4, due to missing "array_fill" function';
3015 CREATE FUNCTION "calculate_ranks"("issue_id_p" "issue"."id"%TYPE)
3016 RETURNS VOID
3017 LANGUAGE 'plpgsql' VOLATILE AS $$
3018 DECLARE
3019 "dimension_v" INTEGER;
3020 "vote_matrix" INT4[][]; -- absolute votes
3021 "matrix" INT8[][]; -- defeat strength / best paths
3022 "i" INTEGER;
3023 "j" INTEGER;
3024 "k" INTEGER;
3025 "battle_row" "battle"%ROWTYPE;
3026 "rank_ary" INT4[];
3027 "rank_v" INT4;
3028 "done_v" INTEGER;
3029 "winners_ary" INTEGER[];
3030 "initiative_id_v" "initiative"."id"%TYPE;
3031 BEGIN
3032 PERFORM NULL FROM "issue" WHERE "id" = "issue_id_p" FOR UPDATE;
3033 SELECT count(1) INTO "dimension_v" FROM "initiative"
3034 WHERE "issue_id" = "issue_id_p" AND "agreed";
3035 IF "dimension_v" = 1 THEN
3036 UPDATE "initiative" SET "rank" = 1
3037 WHERE "issue_id" = "issue_id_p" AND "agreed";
3038 ELSIF "dimension_v" > 1 THEN
3039 -- Create "vote_matrix" with absolute number of votes in pairwise
3040 -- comparison:
3041 "vote_matrix" := "square_matrix_init_string"("dimension_v"); -- TODO: replace by "array_fill" function (PostgreSQL 8.4)
3042 "i" := 1;
3043 "j" := 2;
3044 FOR "battle_row" IN
3045 SELECT * FROM "battle" WHERE "issue_id" = "issue_id_p"
3046 ORDER BY "winning_initiative_id", "losing_initiative_id"
3047 LOOP
3048 "vote_matrix"["i"]["j"] := "battle_row"."count";
3049 IF "j" = "dimension_v" THEN
3050 "i" := "i" + 1;
3051 "j" := 1;
3052 ELSE
3053 "j" := "j" + 1;
3054 IF "j" = "i" THEN
3055 "j" := "j" + 1;
3056 END IF;
3057 END IF;
3058 END LOOP;
3059 IF "i" != "dimension_v" OR "j" != "dimension_v" + 1 THEN
3060 RAISE EXCEPTION 'Wrong battle count (should not happen)';
3061 END IF;
3062 -- Store defeat strengths in "matrix" using "defeat_strength"
3063 -- function:
3064 "matrix" := "square_matrix_init_string"("dimension_v"); -- TODO: replace by "array_fill" function (PostgreSQL 8.4)
3065 "i" := 1;
3066 LOOP
3067 "j" := 1;
3068 LOOP
3069 IF "i" != "j" THEN
3070 "matrix"["i"]["j"] := "defeat_strength"(
3071 "vote_matrix"["i"]["j"],
3072 "vote_matrix"["j"]["i"]
3073 );
3074 END IF;
3075 EXIT WHEN "j" = "dimension_v";
3076 "j" := "j" + 1;
3077 END LOOP;
3078 EXIT WHEN "i" = "dimension_v";
3079 "i" := "i" + 1;
3080 END LOOP;
3081 -- Find best paths:
3082 "i" := 1;
3083 LOOP
3084 "j" := 1;
3085 LOOP
3086 IF "i" != "j" THEN
3087 "k" := 1;
3088 LOOP
3089 IF "i" != "k" AND "j" != "k" THEN
3090 IF "matrix"["j"]["i"] < "matrix"["i"]["k"] THEN
3091 IF "matrix"["j"]["i"] > "matrix"["j"]["k"] THEN
3092 "matrix"["j"]["k"] := "matrix"["j"]["i"];
3093 END IF;
3094 ELSE
3095 IF "matrix"["i"]["k"] > "matrix"["j"]["k"] THEN
3096 "matrix"["j"]["k"] := "matrix"["i"]["k"];
3097 END IF;
3098 END IF;
3099 END IF;
3100 EXIT WHEN "k" = "dimension_v";
3101 "k" := "k" + 1;
3102 END LOOP;
3103 END IF;
3104 EXIT WHEN "j" = "dimension_v";
3105 "j" := "j" + 1;
3106 END LOOP;
3107 EXIT WHEN "i" = "dimension_v";
3108 "i" := "i" + 1;
3109 END LOOP;
3110 -- Determine order of winners:
3111 "rank_ary" := "array_init_string"("dimension_v"); -- TODO: replace by "array_fill" function (PostgreSQL 8.4)
3112 "rank_v" := 1;
3113 "done_v" := 0;
3114 LOOP
3115 "winners_ary" := '{}';
3116 "i" := 1;
3117 LOOP
3118 IF "rank_ary"["i"] ISNULL THEN
3119 "j" := 1;
3120 LOOP
3121 IF
3122 "i" != "j" AND
3123 "rank_ary"["j"] ISNULL AND
3124 "matrix"["j"]["i"] > "matrix"["i"]["j"]
3125 THEN
3126 -- someone else is better
3127 EXIT;
3128 END IF;
3129 IF "j" = "dimension_v" THEN
3130 -- noone is better
3131 "winners_ary" := "winners_ary" || "i";
3132 EXIT;
3133 END IF;
3134 "j" := "j" + 1;
3135 END LOOP;
3136 END IF;
3137 EXIT WHEN "i" = "dimension_v";
3138 "i" := "i" + 1;
3139 END LOOP;
3140 "i" := 1;
3141 LOOP
3142 "rank_ary"["winners_ary"["i"]] := "rank_v";
3143 "done_v" := "done_v" + 1;
3144 EXIT WHEN "i" = array_upper("winners_ary", 1);
3145 "i" := "i" + 1;
3146 END LOOP;
3147 EXIT WHEN "done_v" = "dimension_v";
3148 "rank_v" := "rank_v" + 1;
3149 END LOOP;
3150 -- write preliminary ranks:
3151 "i" := 1;
3152 FOR "initiative_id_v" IN
3153 SELECT "id" FROM "initiative"
3154 WHERE "issue_id" = "issue_id_p" AND "agreed"
3155 ORDER BY "id"
3156 LOOP
3157 UPDATE "initiative" SET "rank" = "rank_ary"["i"]
3158 WHERE "id" = "initiative_id_v";
3159 "i" := "i" + 1;
3160 END LOOP;
3161 IF "i" != "dimension_v" + 1 THEN
3162 RAISE EXCEPTION 'Wrong winner count (should not happen)';
3163 END IF;
3164 -- straighten ranks (start counting with 1, no equal ranks):
3165 "rank_v" := 1;
3166 FOR "initiative_id_v" IN
3167 SELECT "id" FROM "initiative"
3168 WHERE "issue_id" = "issue_id_p" AND "rank" NOTNULL
3169 ORDER BY
3170 "rank",
3171 "vote_ratio"("positive_votes", "negative_votes") DESC,
3172 "id"
3173 LOOP
3174 UPDATE "initiative" SET "rank" = "rank_v"
3175 WHERE "id" = "initiative_id_v";
3176 "rank_v" := "rank_v" + 1;
3177 END LOOP;
3178 END IF;
3179 -- mark issue as finished
3180 UPDATE "issue" SET "ranks_available" = TRUE
3181 WHERE "id" = "issue_id_p";
3182 RETURN;
3183 END;
3184 $$;
3186 COMMENT ON FUNCTION "calculate_ranks"
3187 ( "issue"."id"%TYPE )
3188 IS 'Determine ranking (Votes have to be counted first)';
3192 -----------------------------
3193 -- Automatic state changes --
3194 -----------------------------
3197 CREATE FUNCTION "check_issue"
3198 ( "issue_id_p" "issue"."id"%TYPE )
3199 RETURNS VOID
3200 LANGUAGE 'plpgsql' VOLATILE AS $$
3201 DECLARE
3202 "issue_row" "issue"%ROWTYPE;
3203 "policy_row" "policy"%ROWTYPE;
3204 "voting_requested_v" BOOLEAN;
3205 BEGIN
3206 PERFORM "lock_issue"("issue_id_p");
3207 SELECT * INTO "issue_row" FROM "issue" WHERE "id" = "issue_id_p";
3208 -- only process open issues:
3209 IF "issue_row"."closed" ISNULL THEN
3210 SELECT * INTO "policy_row" FROM "policy"
3211 WHERE "id" = "issue_row"."policy_id";
3212 -- create a snapshot, unless issue is already fully frozen:
3213 IF "issue_row"."fully_frozen" ISNULL THEN
3214 PERFORM "create_snapshot"("issue_id_p");
3215 SELECT * INTO "issue_row" FROM "issue" WHERE "id" = "issue_id_p";
3216 END IF;
3217 -- eventually close or accept issues, which have not been accepted:
3218 IF "issue_row"."accepted" ISNULL THEN
3219 IF EXISTS (
3220 SELECT NULL FROM "initiative"
3221 WHERE "issue_id" = "issue_id_p"
3222 AND "supporter_count" > 0
3223 AND "supporter_count" * "policy_row"."issue_quorum_den"
3224 >= "issue_row"."population" * "policy_row"."issue_quorum_num"
3225 ) THEN
3226 -- accept issues, if supporter count is high enough
3227 PERFORM "set_snapshot_event"("issue_id_p", 'end_of_admission');
3228 "issue_row"."accepted" = now(); -- NOTE: "issue_row" used later
3229 UPDATE "issue" SET "accepted" = "issue_row"."accepted"
3230 WHERE "id" = "issue_row"."id";
3231 ELSIF
3232 now() >= "issue_row"."created" + "issue_row"."admission_time"
3233 THEN
3234 -- close issues, if admission time has expired
3235 PERFORM "set_snapshot_event"("issue_id_p", 'end_of_admission');
3236 UPDATE "issue" SET "closed" = now()
3237 WHERE "id" = "issue_row"."id";
3238 END IF;
3239 END IF;
3240 -- eventually half freeze issues:
3241 IF
3242 -- NOTE: issue can't be closed at this point, if it has been accepted
3243 "issue_row"."accepted" NOTNULL AND
3244 "issue_row"."half_frozen" ISNULL
3245 THEN
3246 SELECT
3247 CASE
3248 WHEN "vote_now" * 2 > "issue_row"."population" THEN
3249 TRUE
3250 WHEN "vote_later" * 2 > "issue_row"."population" THEN
3251 FALSE
3252 ELSE NULL
3253 END
3254 INTO "voting_requested_v"
3255 FROM "issue" WHERE "id" = "issue_id_p";
3256 IF
3257 "voting_requested_v" OR (
3258 "voting_requested_v" ISNULL AND
3259 now() >= "issue_row"."accepted" + "issue_row"."discussion_time"
3261 THEN
3262 PERFORM "set_snapshot_event"("issue_id_p", 'half_freeze');
3263 "issue_row"."half_frozen" = now(); -- NOTE: "issue_row" used later
3264 UPDATE "issue" SET "half_frozen" = "issue_row"."half_frozen"
3265 WHERE "id" = "issue_row"."id";
3266 END IF;
3267 END IF;
3268 -- close issues after some time, if all initiatives have been revoked:
3269 IF
3270 "issue_row"."closed" ISNULL AND
3271 NOT EXISTS (
3272 -- all initiatives are revoked
3273 SELECT NULL FROM "initiative"
3274 WHERE "issue_id" = "issue_id_p" AND "revoked" ISNULL
3275 ) AND (
3276 NOT EXISTS (
3277 -- and no initiatives have been revoked lately
3278 SELECT NULL FROM "initiative"
3279 WHERE "issue_id" = "issue_id_p"
3280 AND now() < "revoked" + "issue_row"."verification_time"
3281 ) OR (
3282 -- or verification time has elapsed
3283 "issue_row"."half_frozen" NOTNULL AND
3284 "issue_row"."fully_frozen" ISNULL AND
3285 now() >= "issue_row"."half_frozen" + "issue_row"."verification_time"
3288 THEN
3289 "issue_row"."closed" = now(); -- NOTE: "issue_row" used later
3290 UPDATE "issue" SET "closed" = "issue_row"."closed"
3291 WHERE "id" = "issue_row"."id";
3292 END IF;
3293 -- fully freeze issue after verification time:
3294 IF
3295 "issue_row"."half_frozen" NOTNULL AND
3296 "issue_row"."fully_frozen" ISNULL AND
3297 "issue_row"."closed" ISNULL AND
3298 now() >= "issue_row"."half_frozen" + "issue_row"."verification_time"
3299 THEN
3300 PERFORM "freeze_after_snapshot"("issue_id_p");
3301 -- NOTE: "issue" might change, thus "issue_row" has to be updated below
3302 END IF;
3303 SELECT * INTO "issue_row" FROM "issue" WHERE "id" = "issue_id_p";
3304 -- close issue by calling close_voting(...) after voting time:
3305 IF
3306 "issue_row"."closed" ISNULL AND
3307 "issue_row"."fully_frozen" NOTNULL AND
3308 now() >= "issue_row"."fully_frozen" + "issue_row"."voting_time"
3309 THEN
3310 PERFORM "close_voting"("issue_id_p");
3311 END IF;
3312 END IF;
3313 RETURN;
3314 END;
3315 $$;
3317 COMMENT ON FUNCTION "check_issue"
3318 ( "issue"."id"%TYPE )
3319 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.';
3322 CREATE FUNCTION "check_everything"()
3323 RETURNS VOID
3324 LANGUAGE 'plpgsql' VOLATILE AS $$
3325 DECLARE
3326 "issue_id_v" "issue"."id"%TYPE;
3327 BEGIN
3328 DELETE FROM "expired_session";
3329 PERFORM "check_last_login"();
3330 PERFORM "calculate_member_counts"();
3331 FOR "issue_id_v" IN SELECT "id" FROM "open_issue" LOOP
3332 PERFORM "check_issue"("issue_id_v");
3333 END LOOP;
3334 FOR "issue_id_v" IN SELECT "id" FROM "issue_with_ranks_missing" LOOP
3335 PERFORM "calculate_ranks"("issue_id_v");
3336 END LOOP;
3337 RETURN;
3338 END;
3339 $$;
3341 COMMENT ON FUNCTION "check_everything"() IS 'Amongst other regular tasks this function performs "check_issue" for every open issue, and if possible, automatically calculates ranks. Use this function only for development and debugging purposes, as long transactions with exclusive locking may result. In productive environments you should call the lf_update program instead.';
3345 ----------------------
3346 -- Deletion of data --
3347 ----------------------
3350 CREATE FUNCTION "clean_issue"("issue_id_p" "issue"."id"%TYPE)
3351 RETURNS VOID
3352 LANGUAGE 'plpgsql' VOLATILE AS $$
3353 DECLARE
3354 "issue_row" "issue"%ROWTYPE;
3355 BEGIN
3356 SELECT * INTO "issue_row"
3357 FROM "issue" WHERE "id" = "issue_id_p"
3358 FOR UPDATE;
3359 IF "issue_row"."cleaned" ISNULL THEN
3360 UPDATE "issue" SET
3361 "closed" = NULL,
3362 "ranks_available" = FALSE
3363 WHERE "id" = "issue_id_p";
3364 DELETE FROM "delegating_voter"
3365 WHERE "issue_id" = "issue_id_p";
3366 DELETE FROM "direct_voter"
3367 WHERE "issue_id" = "issue_id_p";
3368 DELETE FROM "delegating_interest_snapshot"
3369 WHERE "issue_id" = "issue_id_p";
3370 DELETE FROM "direct_interest_snapshot"
3371 WHERE "issue_id" = "issue_id_p";
3372 DELETE FROM "delegating_population_snapshot"
3373 WHERE "issue_id" = "issue_id_p";
3374 DELETE FROM "direct_population_snapshot"
3375 WHERE "issue_id" = "issue_id_p";
3376 DELETE FROM "ignored_issue"
3377 WHERE "issue_id" = "issue_id_p";
3378 DELETE FROM "delegation"
3379 WHERE "issue_id" = "issue_id_p";
3380 DELETE FROM "supporter"
3381 WHERE "issue_id" = "issue_id_p";
3382 UPDATE "issue" SET
3383 "closed" = "issue_row"."closed",
3384 "ranks_available" = "issue_row"."ranks_available",
3385 "cleaned" = now()
3386 WHERE "id" = "issue_id_p";
3387 END IF;
3388 RETURN;
3389 END;
3390 $$;
3392 COMMENT ON FUNCTION "clean_issue"("issue"."id"%TYPE) IS 'Delete discussion data and votes belonging to an issue';
3395 CREATE FUNCTION "delete_member"("member_id_p" "member"."id"%TYPE)
3396 RETURNS VOID
3397 LANGUAGE 'plpgsql' VOLATILE AS $$
3398 BEGIN
3399 UPDATE "member" SET
3400 "last_login" = NULL,
3401 "last_login_public" = NULL,
3402 "login" = NULL,
3403 "password" = NULL,
3404 "locked" = TRUE,
3405 "active" = FALSE,
3406 "notify_email" = NULL,
3407 "notify_email_unconfirmed" = NULL,
3408 "notify_email_secret" = NULL,
3409 "notify_email_secret_expiry" = NULL,
3410 "notify_email_lock_expiry" = NULL,
3411 "password_reset_secret" = NULL,
3412 "password_reset_secret_expiry" = NULL,
3413 "organizational_unit" = NULL,
3414 "internal_posts" = NULL,
3415 "realname" = NULL,
3416 "birthday" = NULL,
3417 "address" = NULL,
3418 "email" = NULL,
3419 "xmpp_address" = NULL,
3420 "website" = NULL,
3421 "phone" = NULL,
3422 "mobile_phone" = NULL,
3423 "profession" = NULL,
3424 "external_memberships" = NULL,
3425 "external_posts" = NULL,
3426 "statement" = NULL
3427 WHERE "id" = "member_id_p";
3428 -- "text_search_data" is updated by triggers
3429 DELETE FROM "setting" WHERE "member_id" = "member_id_p";
3430 DELETE FROM "setting_map" WHERE "member_id" = "member_id_p";
3431 DELETE FROM "member_relation_setting" WHERE "member_id" = "member_id_p";
3432 DELETE FROM "member_image" WHERE "member_id" = "member_id_p";
3433 DELETE FROM "contact" WHERE "member_id" = "member_id_p";
3434 DELETE FROM "area_setting" WHERE "member_id" = "member_id_p";
3435 DELETE FROM "issue_setting" WHERE "member_id" = "member_id_p";
3436 DELETE FROM "initiative_setting" WHERE "member_id" = "member_id_p";
3437 DELETE FROM "suggestion_setting" WHERE "member_id" = "member_id_p";
3438 DELETE FROM "membership" WHERE "member_id" = "member_id_p";
3439 DELETE FROM "ignored_issue" WHERE "member_id" = "member_id_p";
3440 DELETE FROM "delegation" WHERE "truster_id" = "member_id_p";
3441 DELETE FROM "direct_voter" USING "issue"
3442 WHERE "direct_voter"."issue_id" = "issue"."id"
3443 AND "issue"."closed" ISNULL
3444 AND "member_id" = "member_id_p";
3445 RETURN;
3446 END;
3447 $$;
3449 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)';
3452 CREATE FUNCTION "delete_private_data"()
3453 RETURNS VOID
3454 LANGUAGE 'plpgsql' VOLATILE AS $$
3455 BEGIN
3456 UPDATE "member" SET
3457 "last_login" = NULL,
3458 "login" = NULL,
3459 "password" = NULL,
3460 "notify_email" = NULL,
3461 "notify_email_unconfirmed" = NULL,
3462 "notify_email_secret" = NULL,
3463 "notify_email_secret_expiry" = NULL,
3464 "notify_email_lock_expiry" = NULL,
3465 "password_reset_secret" = NULL,
3466 "password_reset_secret_expiry" = NULL,
3467 "organizational_unit" = NULL,
3468 "internal_posts" = NULL,
3469 "realname" = NULL,
3470 "birthday" = NULL,
3471 "address" = NULL,
3472 "email" = NULL,
3473 "xmpp_address" = NULL,
3474 "website" = NULL,
3475 "phone" = NULL,
3476 "mobile_phone" = NULL,
3477 "profession" = NULL,
3478 "external_memberships" = NULL,
3479 "external_posts" = NULL,
3480 "statement" = NULL;
3481 -- "text_search_data" is updated by triggers
3482 DELETE FROM "invite_code";
3483 DELETE FROM "setting";
3484 DELETE FROM "setting_map";
3485 DELETE FROM "member_relation_setting";
3486 DELETE FROM "member_image";
3487 DELETE FROM "contact";
3488 DELETE FROM "session";
3489 DELETE FROM "area_setting";
3490 DELETE FROM "issue_setting";
3491 DELETE FROM "initiative_setting";
3492 DELETE FROM "suggestion_setting";
3493 DELETE FROM "ignored_issue";
3494 DELETE FROM "direct_voter" USING "issue"
3495 WHERE "direct_voter"."issue_id" = "issue"."id"
3496 AND "issue"."closed" ISNULL;
3497 RETURN;
3498 END;
3499 $$;
3501 COMMENT ON FUNCTION "delete_private_data"() IS 'Used by lf_export script. DO NOT USE on productive database, but only on a copy! This function deletes all data which should not be publicly available, and can be used to create a database dump for publication.';
3505 COMMIT;

Impressum / About Us