liquid_feedback_core

view core.sql @ 602:9570aeabf4fc

Added update script to version 4.2.0
author jbe
date Fri Feb 07 10:52:37 2020 +0100 (2020-02-07)
parents aa0620c9c4df
children 617ac1725557
line source
2 -- NOTE: In PostgreSQL every UNIQUE constraint implies creation of an index
4 BEGIN;
6 CREATE EXTENSION IF NOT EXISTS btree_gist;
7 CREATE EXTENSION IF NOT EXISTS latlon;
8 CREATE EXTENSION IF NOT EXISTS conflux;
10 CREATE VIEW "liquid_feedback_version" AS
11 SELECT * FROM (VALUES ('4.2.0', 4, 2, 0))
12 AS "subquery"("string", "major", "minor", "revision");
16 -------------------------
17 -- Tables and indicies --
18 -------------------------
21 CREATE TABLE "temporary_transaction_data" (
22 PRIMARY KEY ("txid", "key"),
23 "txid" INT8 DEFAULT txid_current(),
24 "key" TEXT,
25 "value" TEXT NOT NULL );
27 COMMENT ON TABLE "temporary_transaction_data" IS 'Table to store temporary transaction data; shall be emptied before a transaction is committed';
29 COMMENT ON COLUMN "temporary_transaction_data"."txid" IS 'Value returned by function txid_current(); should be added to WHERE clause, when doing SELECT on this table, but ignored when doing DELETE on this table';
32 CREATE TABLE "system_setting" (
33 "member_ttl" INTERVAL );
34 CREATE UNIQUE INDEX "system_setting_singleton_idx" ON "system_setting" ((1));
36 COMMENT ON TABLE "system_setting" IS 'This table contains only one row with different settings in each column.';
37 COMMENT ON INDEX "system_setting_singleton_idx" IS 'This index ensures that "system_setting" only contains one row maximum.';
39 COMMENT ON COLUMN "system_setting"."member_ttl" IS 'Time after members get their "active" flag set to FALSE, if they do not show any activity.';
42 CREATE TABLE "contingent" (
43 PRIMARY KEY ("polling", "time_frame"),
44 "polling" BOOLEAN,
45 "time_frame" INTERVAL,
46 "text_entry_limit" INT4,
47 "initiative_limit" INT4 );
49 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.';
51 COMMENT ON COLUMN "contingent"."polling" IS 'Determines if settings are for creating initiatives and new drafts of initiatives with "polling" flag set';
52 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';
53 COMMENT ON COLUMN "contingent"."initiative_limit" IS 'Number of new initiatives to be opened by each member within a given time frame';
56 CREATE TABLE "file" (
57 "id" SERIAL8 PRIMARY KEY,
58 UNIQUE ("content_type", "hash"),
59 "content_type" TEXT NOT NULL,
60 "hash" TEXT NOT NULL,
61 "data" BYTEA NOT NULL,
62 "preview_content_type" TEXT,
63 "preview_data" BYTEA );
65 COMMENT ON TABLE "file" IS 'Table holding file contents for draft attachments';
67 COMMENT ON COLUMN "file"."content_type" IS 'Content type of "data"';
68 COMMENT ON COLUMN "file"."hash" IS 'Hash of "data" to avoid storing duplicates where content-type and data is identical';
69 COMMENT ON COLUMN "file"."data" IS 'Binary content';
70 COMMENT ON COLUMN "file"."preview_content_type" IS 'Content type of "preview_data"';
71 COMMENT ON COLUMN "file"."preview_data" IS 'Preview (e.g. preview image)';
74 CREATE TABLE "member" (
75 "id" SERIAL4 PRIMARY KEY,
76 "created" TIMESTAMPTZ NOT NULL DEFAULT now(),
77 "deleted" TIMESTAMPTZ,
78 "invite_code" TEXT UNIQUE,
79 "invite_code_expiry" TIMESTAMPTZ,
80 "admin_comment" TEXT,
81 "activated" TIMESTAMPTZ,
82 "last_activity" DATE,
83 "last_login" TIMESTAMPTZ,
84 "last_delegation_check" TIMESTAMPTZ,
85 "login" TEXT UNIQUE,
86 "password" TEXT,
87 "authority" TEXT,
88 "authority_uid" TEXT,
89 "authority_login" TEXT,
90 "locked" BOOLEAN NOT NULL DEFAULT FALSE,
91 "active" BOOLEAN NOT NULL DEFAULT FALSE,
92 "admin" BOOLEAN NOT NULL DEFAULT FALSE,
93 "lang" TEXT,
94 "notify_email" TEXT,
95 "notify_email_unconfirmed" TEXT,
96 "notify_email_secret" TEXT UNIQUE,
97 "notify_email_secret_expiry" TIMESTAMPTZ,
98 "notify_email_lock_expiry" TIMESTAMPTZ,
99 "unsubscribe_secret" TEXT,
100 "disable_notifications" BOOLEAN NOT NULL DEFAULT FALSE,
101 "notification_counter" INT4 NOT NULL DEFAULT 1,
102 "notification_sample_size" INT4 NOT NULL DEFAULT 3,
103 "notification_dow" INT4 CHECK ("notification_dow" BETWEEN 0 AND 6),
104 "notification_hour" INT4 DEFAULT floor(random() * 24) CHECK ("notification_hour" BETWEEN 0 AND 23),
105 "notification_sent" TIMESTAMP,
106 "login_recovery_expiry" TIMESTAMPTZ,
107 "password_reset_secret" TEXT UNIQUE,
108 "password_reset_secret_expiry" TIMESTAMPTZ,
109 "name" TEXT UNIQUE, -- full text search
110 "identification" TEXT UNIQUE, -- full text search
111 "authentication" TEXT,
112 "role" BOOLEAN NOT NULL DEFAULT FALSE,
113 "location" JSONB,
114 CONSTRAINT "deleted_requires_locked"
115 CHECK ("deleted" ISNULL OR "locked" = TRUE),
116 CONSTRAINT "active_requires_activated_and_last_activity"
117 CHECK ("active" = FALSE OR ("activated" NOTNULL AND "last_activity" NOTNULL)),
118 CONSTRAINT "authority_requires_uid_and_vice_versa"
119 CHECK (("authority" NOTNULL) = ("authority_uid" NOTNULL)),
120 CONSTRAINT "authority_uid_unique_per_authority"
121 UNIQUE ("authority", "authority_uid"),
122 CONSTRAINT "authority_login_requires_authority"
123 CHECK ("authority" NOTNULL OR "authority_login" ISNULL),
124 CONSTRAINT "notification_dow_requires_notification_hour"
125 CHECK ("notification_dow" ISNULL OR "notification_hour" NOTNULL),
126 CONSTRAINT "name_not_null_if_activated"
127 CHECK ("activated" ISNULL OR "name" NOTNULL) );
128 CREATE INDEX "member_authority_login_idx" ON "member" ("authority_login");
129 CREATE INDEX "member_active_idx" ON "member" ("active");
130 CREATE INDEX "member_location_idx" ON "member" USING gist ((GeoJSON_to_ecluster("location")));
132 COMMENT ON TABLE "member" IS 'Users of the system, e.g. members of an organization';
134 COMMENT ON COLUMN "member"."created" IS 'Creation of member record and/or invite code';
135 COMMENT ON COLUMN "member"."invite_code" IS 'Optional invite code, to allow a member to initialize his/her account the first time';
136 COMMENT ON COLUMN "member"."invite_code_expiry" IS 'Expiry data/time for "invite_code"';
137 COMMENT ON COLUMN "member"."admin_comment" IS 'Hidden comment for administrative purposes';
138 COMMENT ON COLUMN "member"."activated" IS 'Timestamp of first activation of account (i.e. usage of "invite_code"); required to be set for "active" members';
139 COMMENT ON COLUMN "member"."last_activity" IS 'Date of last activity of member; required to be set for "active" members';
140 COMMENT ON COLUMN "member"."last_login" IS 'Timestamp of last login';
141 COMMENT ON COLUMN "member"."last_delegation_check" IS 'Timestamp of last delegation check (i.e. confirmation of all unit and area delegations)';
142 COMMENT ON COLUMN "member"."login" IS 'Login name';
143 COMMENT ON COLUMN "member"."password" IS 'Password (preferably as crypto-hash, depending on the frontend or access layer)';
144 COMMENT ON COLUMN "member"."authority" IS 'NULL if LiquidFeedback Core is authoritative for the member account; otherwise a string that indicates the source/authority of the external account (e.g. ''LDAP'' for an LDAP account)';
145 COMMENT ON COLUMN "member"."authority_uid" IS 'Unique identifier (unique per "authority") that allows to identify an external account (e.g. even if the login name changes)';
146 COMMENT ON COLUMN "member"."authority_login" IS 'Login name for external accounts (field is not unique!)';
147 COMMENT ON COLUMN "member"."deleted" IS 'Timestamp of deletion (set by "delete_member" function)';
148 COMMENT ON COLUMN "member"."locked" IS 'Locked members can not log in.';
149 COMMENT ON COLUMN "member"."active" IS 'Memberships, support and votes are taken into account when corresponding members are marked as active. Automatically set to FALSE, if "last_activity" is older than "system_setting"."member_ttl".';
150 COMMENT ON COLUMN "member"."admin" IS 'TRUE for admins, which can administrate other users and setup policies and areas';
151 COMMENT ON COLUMN "member"."lang" IS 'Language code of the preferred language of the member';
152 COMMENT ON COLUMN "member"."notify_email" IS 'Email address where notifications of the system are sent to';
153 COMMENT ON COLUMN "member"."notify_email_unconfirmed" IS 'Unconfirmed email address provided by the member to be copied into "notify_email" field after verification';
154 COMMENT ON COLUMN "member"."notify_email_secret" IS 'Secret sent to the address in "notify_email_unconformed"';
155 COMMENT ON COLUMN "member"."notify_email_secret_expiry" IS 'Expiry date/time for "notify_email_secret"';
156 COMMENT ON COLUMN "member"."notify_email_lock_expiry" IS 'Date/time until no further email confirmation mails may be sent (abuse protection)';
157 COMMENT ON COLUMN "member"."unsubscribe_secret" IS 'Secret string to be used for a List-Unsubscribe mail header';
158 COMMENT ON COLUMN "member"."disable_notifications" IS 'TRUE if member does not want to receive notifications';
159 COMMENT ON COLUMN "member"."notification_counter" IS 'Sequential number of next scheduled notification message (used as a seed for pseudo-random initiative selection algorithm)';
160 COMMENT ON COLUMN "member"."notification_sample_size" IS 'Number of featured initiatives per issue in scheduled notification messages';
161 COMMENT ON COLUMN "member"."notification_dow" IS 'Day of week for scheduled notifications (NULL to receive a daily digest)';
162 COMMENT ON COLUMN "member"."notification_hour" IS 'Time of day when scheduled notifications are sent out';
163 COMMENT ON COLUMN "member"."notification_sent" IS 'Timestamp of last scheduled notification mail that has been sent out';
164 COMMENT ON COLUMN "member"."login_recovery_expiry" IS 'Date/time after which another login recovery attempt is allowed';
165 COMMENT ON COLUMN "member"."password_reset_secret" IS 'Secret string sent via e-mail for password recovery';
166 COMMENT ON COLUMN "member"."password_reset_secret_expiry" IS 'Date/time until the password recovery secret is valid, and date/time after which another password recovery attempt is allowed';
167 COMMENT ON COLUMN "member"."name" IS 'Distinct name of the member, may be NULL if account has not been activated yet';
168 COMMENT ON COLUMN "member"."identification" IS 'Optional identification number or code of the member';
169 COMMENT ON COLUMN "member"."authentication" IS 'Information about how this member was authenticated';
170 COMMENT ON COLUMN "member"."location" IS 'Geographic location on earth as GeoJSON object';
173 CREATE TABLE "member_history" ( -- TODO: redundancy with new "event" table
174 "id" SERIAL8 PRIMARY KEY,
175 "member_id" INT4 NOT NULL REFERENCES "member" ("id") ON DELETE CASCADE ON UPDATE CASCADE,
176 "until" TIMESTAMPTZ NOT NULL DEFAULT now(),
177 "active" BOOLEAN NOT NULL,
178 "name" TEXT NOT NULL );
179 CREATE INDEX "member_history_member_id_idx" ON "member_history" ("member_id");
181 COMMENT ON TABLE "member_history" IS 'Filled by trigger; keeps information about old names and active flag of members';
183 COMMENT ON COLUMN "member_history"."id" IS 'Primary key, which can be used to sort entries correctly (and time warp resistant)';
184 COMMENT ON COLUMN "member_history"."until" IS 'Timestamp until the data was valid';
187 CREATE TABLE "agent" (
188 PRIMARY KEY ("controlled_id", "controller_id"),
189 "controlled_id" INT4 REFERENCES "member" ("id") ON DELETE CASCADE ON UPDATE CASCADE,
190 "controller_id" INT4 REFERENCES "member" ("id") ON DELETE CASCADE ON UPDATE CASCADE,
191 "accepted" BOOLEAN,
192 CONSTRAINT "controlled_id_and_controller_id_differ" CHECK (
193 "controlled_id" != "controller_id" ) );
194 CREATE INDEX "agent_controller_id_idx" ON "agent" ("controller_id");
196 COMMENT ON TABLE "agent" IS 'Privileges for role accounts';
198 COMMENT ON COLUMN "agent"."accepted" IS 'If "accepted" is NULL, then the member was invited to be an agent, but has not reacted yet. If it is TRUE, the member has accepted the invitation, if it is FALSE, the member has rejected the invitation.';
201 CREATE TABLE "verification" (
202 "id" SERIAL8 PRIMARY KEY,
203 "requested" TIMESTAMPTZ,
204 "request_origin" JSONB,
205 "request_data" JSONB,
206 "requesting_member_id" INT4 REFERENCES "member" ("id") ON DELETE RESTRICT ON UPDATE CASCADE,
207 "verifying_member_id" INT4 REFERENCES "member" ("id") ON DELETE RESTRICT ON UPDATE CASCADE,
208 "verified_member_id" INT4 REFERENCES "member" ("id") ON DELETE RESTRICT ON UPDATE CASCADE,
209 "verified" TIMESTAMPTZ,
210 "verification_data" JSONB,
211 "denied" TIMESTAMPTZ,
212 "comment" TEXT,
213 CONSTRAINT "verified_and_denied_conflict" CHECK (
214 "verified" ISNULL OR "denied" ISNULL ) );
215 CREATE INDEX "verification_requested_idx" ON "verification" ("requested");
216 CREATE INDEX "verification_open_request_idx" ON "verification" ("requested") WHERE "verified" ISNULL AND "denied" ISNULL;
217 CREATE INDEX "verification_requesting_member_id_idx" ON "verification" ("requesting_member_id");
218 CREATE INDEX "verification_verified_member_id_idx" ON "verification" ("verified_member_id");
219 CREATE INDEX "verification_verified_idx" ON "verification" ("verified");
220 CREATE INDEX "verification_denied_idx" ON "verification" ("denied");
222 COMMENT ON TABLE "verification" IS 'Request to verify a participant';
224 COMMENT ON COLUMN "verification"."requested" IS 'Timestamp when request for verification has been submitted';
225 COMMENT ON COLUMN "verification"."request_origin" IS 'JSON data containing information about the origin of the request (e.g. IP address or hostname)';
226 COMMENT ON COLUMN "verification"."request_data" IS 'JSON data containing information about the entity to be verified (e.g. real name, address, etc.)';
227 COMMENT ON COLUMN "verification"."requesting_member_id" IS 'Member who requested verification';
228 COMMENT ON COLUMN "verification"."verifying_member_id" IS 'Member who processed the verification request (i.e. who accepted or denied the request)';
229 COMMENT ON COLUMN "verification"."verified_member_id" IS 'Member entry containing verified information (not necessarily equal to "requesting_member_id" but may be merged with requesting member later)';
230 COMMENT ON COLUMN "verification"."verified" IS 'Timestamp when request for verification has been accepted by authority';
231 COMMENT ON COLUMN "verification"."verification_data" IS 'JSON data containing additional verified data or information about the authority or operator who accepted or denied the request, but all public information shall be copied to "member"."identification", "member"."verification" and/or "member"."name" if applicable for setup';
232 COMMENT ON COLUMN "verification"."denied" IS 'Timestamp when request for verification has been denied by authority';
233 COMMENT ON COLUMN "verification"."comment" IS 'Administrative comment';
236 -- TODO: merge tables "verification" and "role_verification"
238 CREATE TABLE "role_verification" (
239 "id" SERIAL8 PRIMARY KEY,
240 "requested" TIMESTAMPTZ,
241 "request_origin" JSONB,
242 "request_data" JSONB,
243 "requesting_member_id" INT4 REFERENCES "member" ("id") ON DELETE RESTRICT ON UPDATE CASCADE,
244 "requesting_real_member_id" INT4 REFERENCES "member" ("id") ON DELETE RESTRICT ON UPDATE CASCADE,
245 "verifying_member_id" INT4 REFERENCES "member" ("id") ON DELETE RESTRICT ON UPDATE CASCADE,
246 "verified_member_id" INT4 REFERENCES "member" ("id") ON DELETE RESTRICT ON UPDATE CASCADE,
247 "verified" TIMESTAMPTZ,
248 "verification_data" JSONB,
249 "denied" TIMESTAMPTZ,
250 "comment" TEXT,
251 CONSTRAINT "verified_and_denied_conflict" CHECK (
252 "verified" ISNULL OR "denied" ISNULL ) );
253 CREATE INDEX "role_verification_requested_idx" ON "role_verification" ("requested");
254 CREATE INDEX "role_verification_open_request_idx" ON "role_verification" ("requested") WHERE "verified" ISNULL AND "denied" ISNULL;
255 CREATE INDEX "role_verification_requesting_member_id_idx" ON "role_verification" ("requesting_member_id");
256 CREATE INDEX "role_verification_verified_member_id_idx" ON "role_verification" ("verified_member_id");
257 CREATE INDEX "role_verification_verified_idx" ON "role_verification" ("verified");
258 CREATE INDEX "role_verification_denied_idx" ON "role_verification" ("denied");
260 COMMENT ON TABLE "role_verification" IS 'Request to verify a role account (see table "verification" for documentation of columns not documented for this table)';
262 COMMENT ON COLUMN "role_verification"."requesting_member_id" IS 'Member role account to verify';
263 COMMENT ON COLUMN "role_verification"."requesting_real_member_id" IS 'Member account of real person who requested verification';
266 CREATE TABLE "member_settings" (
267 "member_id" INT4 PRIMARY KEY REFERENCES "member" ("id") ON DELETE CASCADE ON UPDATE CASCADE,
268 "settings" JSONB NOT NULL CHECK (jsonb_typeof("settings") = 'object') );
270 COMMENT ON TABLE "member_settings" IS 'Stores a JSON document for each member containing optional (additional) settings for the respective member';
273 CREATE TABLE "member_useterms" (
274 "id" SERIAL8 PRIMARY KEY,
275 "member_id" INT4 NOT NULL REFERENCES "member" ("id") ON DELETE CASCADE ON UPDATE CASCADE,
276 "accepted" TIMESTAMPTZ NOT NULL DEFAULT now(),
277 "contract_identifier" TEXT NOT NULL );
278 CREATE INDEX "member_useterms_member_id_contract_identifier" ON "member_useterms" ("member_id", "contract_identifier");
280 COMMENT ON TABLE "member_useterms" IS 'Keeps record of accepted terms of use; may contain multiple rows per member';
282 COMMENT ON COLUMN "member_useterms"."accepted" IS 'Point in time when user accepted the terms of use';
283 COMMENT ON COLUMN "member_useterms"."contract_identifier" IS 'String identifier to denote the accepted terms of use, including their version or revision';
286 CREATE TABLE "member_profile" (
287 "member_id" INT4 PRIMARY KEY REFERENCES "member" ("id") ON DELETE CASCADE ON UPDATE CASCADE,
288 "formatting_engine" TEXT,
289 "statement" TEXT, -- full text search
290 "profile" JSONB NOT NULL DEFAULT '{}' CHECK (jsonb_typeof("profile") = 'object'),
291 "profile_text_data" TEXT ); -- full text search
293 COMMENT ON COLUMN "member_profile"."formatting_engine" IS 'Allows different formatting engines (i.e. wiki formats) to be used for "member_profile"."statement"';
294 COMMENT ON COLUMN "member_profile"."statement" IS 'Freely chosen text of the member for his/her profile';
295 COMMENT ON COLUMN "member_profile"."profile" IS 'Additional profile data as JSON document';
296 COMMENT ON COLUMN "member_profile"."profile_text_data" IS 'Text data from "profile" field for full text search';
299 CREATE TABLE "rendered_member_statement" (
300 PRIMARY KEY ("member_id", "format"),
301 "member_id" INT4 REFERENCES "member" ("id") ON DELETE CASCADE ON UPDATE CASCADE,
302 "format" TEXT,
303 "content" TEXT NOT NULL );
305 COMMENT ON TABLE "rendered_member_statement" IS 'This table may be used by frontends to cache "rendered" member statements (e.g. HTML output generated from wiki text)';
308 CREATE TYPE "member_image_type" AS ENUM ('photo', 'avatar');
310 COMMENT ON TYPE "member_image_type" IS 'Types of images for a member';
313 CREATE TABLE "member_image" (
314 PRIMARY KEY ("member_id", "image_type", "scaled"),
315 "member_id" INT4 REFERENCES "member" ("id") ON DELETE CASCADE ON UPDATE CASCADE,
316 "image_type" "member_image_type",
317 "scaled" BOOLEAN,
318 "content_type" TEXT, -- TODO: NOT NULL?
319 "data" BYTEA NOT NULL );
321 COMMENT ON TABLE "member_image" IS 'Images of members';
323 COMMENT ON COLUMN "member_image"."scaled" IS 'FALSE for original image, TRUE for scaled version of the image';
326 CREATE TABLE "member_count" (
327 "calculated" TIMESTAMPTZ NOT NULL DEFAULT now(),
328 "total_count" INT4 NOT NULL );
330 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';
332 COMMENT ON COLUMN "member_count"."calculated" IS 'timestamp indicating when the total member count and area member counts were calculated';
333 COMMENT ON COLUMN "member_count"."total_count" IS 'Total count of active(!) members';
336 CREATE TABLE "contact" (
337 PRIMARY KEY ("member_id", "other_member_id"),
338 "member_id" INT4 REFERENCES "member" ("id") ON DELETE CASCADE ON UPDATE CASCADE,
339 "other_member_id" INT4 REFERENCES "member" ("id") ON DELETE CASCADE ON UPDATE CASCADE,
340 "public" BOOLEAN NOT NULL DEFAULT FALSE,
341 "following" BOOLEAN NOT NULL DEFAULT TRUE,
342 CONSTRAINT "cant_save_yourself_as_contact"
343 CHECK ("member_id" != "other_member_id") );
344 CREATE INDEX "contact_other_member_id_idx" ON "contact" ("other_member_id");
346 COMMENT ON TABLE "contact" IS 'Contact lists';
348 COMMENT ON COLUMN "contact"."member_id" IS 'Member having the contact list';
349 COMMENT ON COLUMN "contact"."other_member_id" IS 'Member referenced in the contact list';
350 COMMENT ON COLUMN "contact"."public" IS 'TRUE = display contact publically';
351 COMMENT ON COLUMN "contact"."following" IS 'TRUE = actions of contact are shown in personal timeline';
354 CREATE TABLE "ignored_member" (
355 PRIMARY KEY ("member_id", "other_member_id"),
356 "member_id" INT4 REFERENCES "member" ("id") ON DELETE CASCADE ON UPDATE CASCADE,
357 "other_member_id" INT4 REFERENCES "member" ("id") ON DELETE CASCADE ON UPDATE CASCADE );
358 CREATE INDEX "ignored_member_other_member_id_idx" ON "ignored_member" ("other_member_id");
360 COMMENT ON TABLE "ignored_member" IS 'Possibility to filter other members';
362 COMMENT ON COLUMN "ignored_member"."member_id" IS 'Member ignoring someone';
363 COMMENT ON COLUMN "ignored_member"."other_member_id" IS 'Member being ignored';
366 CREATE TABLE "session" (
367 UNIQUE ("member_id", "id"), -- index needed for foreign-key on table "token"
368 "id" SERIAL8 PRIMARY KEY,
369 "ident" TEXT NOT NULL UNIQUE,
370 "additional_secret" TEXT,
371 "logout_token" TEXT,
372 "expiry" TIMESTAMPTZ NOT NULL DEFAULT now() + '24 hours',
373 "member_id" INT4 REFERENCES "member" ("id") ON DELETE SET NULL,
374 "real_member_id" INT4 REFERENCES "member" ("id") ON DELETE RESTRICT ON UPDATE CASCADE,
375 "authority" TEXT,
376 "authority_uid" TEXT,
377 "authority_login" TEXT,
378 "needs_delegation_check" BOOLEAN NOT NULL DEFAULT FALSE,
379 "lang" TEXT );
380 CREATE INDEX "session_expiry_idx" ON "session" ("expiry");
382 COMMENT ON TABLE "session" IS 'Sessions, i.e. for a web-frontend or API layer';
384 COMMENT ON COLUMN "session"."ident" IS 'Secret session identifier (i.e. random string)';
385 COMMENT ON COLUMN "session"."additional_secret" IS 'Additional field to store a secret, which can be used against CSRF attacks';
386 COMMENT ON COLUMN "session"."logout_token" IS 'Optional token to authorize logout through external component';
387 COMMENT ON COLUMN "session"."member_id" IS 'Reference to member, who is logged in, or role account in use';
388 COMMENT ON COLUMN "session"."real_member_id" IS 'Reference to member, who is really logged in (real person rather than role account)';
389 COMMENT ON COLUMN "session"."authority" IS 'Temporary store for "member"."authority" during member account creation';
390 COMMENT ON COLUMN "session"."authority_uid" IS 'Temporary store for "member"."authority_uid" during member account creation';
391 COMMENT ON COLUMN "session"."authority_login" IS 'Temporary store for "member"."authority_login" during member account creation';
392 COMMENT ON COLUMN "session"."needs_delegation_check" IS 'Set to TRUE, if member must perform a delegation check to proceed with login; see column "last_delegation_check" in "member" table';
393 COMMENT ON COLUMN "session"."lang" IS 'Language code of the selected language';
396 CREATE TYPE "authflow" AS ENUM ('code', 'token');
398 COMMENT ON TYPE "authflow" IS 'OAuth 2.0 flows: ''code'' = Authorization Code flow, ''token'' = Implicit flow';
401 CREATE TABLE "system_application" (
402 "id" SERIAL4 PRIMARY KEY,
403 "name" TEXT NOT NULL,
404 "base_url" TEXT,
405 "manifest_url" TEXT,
406 "client_id" TEXT NOT NULL UNIQUE,
407 "default_redirect_uri" TEXT NOT NULL,
408 "cert_common_name" TEXT,
409 "client_cred_scope" TEXT,
410 "flow" "authflow",
411 "automatic_scope" TEXT,
412 "permitted_scope" TEXT,
413 "forbidden_scope" TEXT );
415 COMMENT ON TABLE "system_application" IS 'OAuth 2.0 clients that are registered by the system administrator';
417 COMMENT ON COLUMN "system_application"."name" IS 'Human readable name of application';
418 COMMENT ON COLUMN "system_application"."base_url" IS 'Base URL for users';
419 COMMENT ON COLUMN "system_application"."manifest_url" IS 'URL referring to a manifest that can be used for application (type/version) discovery';
420 COMMENT ON COLUMN "system_application"."client_id" IS 'OAuth 2.0 "client_id"';
421 COMMENT ON COLUMN "system_application"."cert_common_name" IS 'Value for CN field of TLS client certificate';
422 COMMENT ON COLUMN "system_application"."client_cred_scope" IS 'Space-separated list of scopes; If set, Client Credentials Grant is allowed; value determines scope';
423 COMMENT ON COLUMN "system_application"."flow" IS 'If set to ''code'' or ''token'', then Authorization Code or Implicit flow is allowed respectively';
424 COMMENT ON COLUMN "system_application"."automatic_scope" IS 'Space-separated list of scopes; Automatically granted scope for Authorization Code or Implicit flow';
425 COMMENT ON COLUMN "system_application"."permitted_scope" IS 'Space-separated list of scopes; If set, scope that members may grant to the application is limited to the given value';
426 COMMENT ON COLUMN "system_application"."forbidden_scope" IS 'Space-separated list of scopes that may not be granted to the application by a member';
429 CREATE TABLE "system_application_redirect_uri" (
430 PRIMARY KEY ("system_application_id", "redirect_uri"),
431 "system_application_id" INT4 REFERENCES "system_application" ("id") ON DELETE CASCADE ON UPDATE CASCADE,
432 "redirect_uri" TEXT );
434 COMMENT ON TABLE "system_application_redirect_uri" IS 'Additional OAuth 2.0 redirection endpoints, which may be selected through the "redirect_uri" GET parameter';
437 CREATE TABLE "dynamic_application_scope" (
438 PRIMARY KEY ("redirect_uri", "flow", "scope"),
439 "redirect_uri" TEXT,
440 "flow" TEXT,
441 "scope" TEXT,
442 "expiry" TIMESTAMPTZ NOT NULL DEFAULT now() + '24 hours' );
443 CREATE INDEX "dynamic_application_scope_redirect_uri_scope_idx" ON "dynamic_application_scope" ("redirect_uri", "flow", "scope");
444 CREATE INDEX "dynamic_application_scope_expiry_idx" ON "dynamic_application_scope" ("expiry");
446 COMMENT ON TABLE "dynamic_application_scope" IS 'Dynamic OAuth 2.0 client registration data';
448 COMMENT ON COLUMN "dynamic_application_scope"."redirect_uri" IS 'Redirection endpoint for which the registration has been done';
449 COMMENT ON COLUMN "dynamic_application_scope"."flow" IS 'OAuth 2.0 flow for which the registration has been done (see also "system_application"."flow")';
450 COMMENT ON COLUMN "dynamic_application_scope"."scope" IS 'Single scope without space characters (use multiple rows for more scopes)';
451 COMMENT ON COLUMN "dynamic_application_scope"."expiry" IS 'Expiry unless renewed';
454 CREATE TABLE "member_application" (
455 "id" SERIAL4 PRIMARY KEY,
456 UNIQUE ("system_application_id", "member_id"),
457 UNIQUE ("domain", "member_id"),
458 "member_id" INT4 NOT NULL REFERENCES "member" ("id") ON DELETE CASCADE ON UPDATE CASCADE,
459 "system_application_id" INT4 REFERENCES "system_application" ("id") ON DELETE CASCADE ON UPDATE CASCADE,
460 "domain" TEXT,
461 "session_id" INT8,
462 FOREIGN KEY ("member_id", "session_id") REFERENCES "session" ("member_id", "id") ON DELETE CASCADE ON UPDATE CASCADE,
463 "scope" TEXT NOT NULL,
464 CONSTRAINT "system_application_or_domain_but_not_both" CHECK (
465 ("system_application_id" NOTNULL AND "domain" ISNULL) OR
466 ("system_application_id" ISNULL AND "domain" NOTNULL) ) );
467 CREATE INDEX "member_application_member_id_idx" ON "member_application" ("member_id");
469 COMMENT ON TABLE "member_application" IS 'Application authorized by a member';
471 COMMENT ON COLUMN "member_application"."system_application_id" IS 'If set, then application is a system application';
472 COMMENT ON COLUMN "member_application"."domain" IS 'If set, then application is a dynamically registered OAuth 2.0 client; value is set to client''s domain';
473 COMMENT ON COLUMN "member_application"."session_id" IS 'If set, registration ends with session';
474 COMMENT ON COLUMN "member_application"."scope" IS 'Granted scope as space-separated list of strings';
477 CREATE TYPE "token_type" AS ENUM ('authorization', 'refresh', 'access');
479 COMMENT ON TYPE "token_type" IS 'Types for entries in "token" table';
482 CREATE TABLE "token" (
483 "id" SERIAL8 PRIMARY KEY,
484 "token" TEXT NOT NULL UNIQUE,
485 "token_type" "token_type" NOT NULL,
486 "authorization_token_id" INT8 REFERENCES "token" ("id") ON DELETE CASCADE ON UPDATE CASCADE,
487 "member_id" INT4 NOT NULL REFERENCES "member" ("id") ON DELETE CASCADE ON UPDATE CASCADE,
488 "system_application_id" INT4 REFERENCES "system_application" ("id") ON DELETE CASCADE ON UPDATE CASCADE,
489 "domain" TEXT,
490 FOREIGN KEY ("member_id", "domain") REFERENCES "member_application" ("member_id", "domain") ON DELETE CASCADE ON UPDATE CASCADE,
491 "session_id" INT8,
492 FOREIGN KEY ("member_id", "session_id") REFERENCES "session" ("member_id", "id") ON DELETE RESTRICT ON UPDATE CASCADE, -- NOTE: deletion through "detach_token_from_session" trigger on table "session"
493 "redirect_uri" TEXT,
494 "redirect_uri_explicit" BOOLEAN,
495 "created" TIMESTAMPTZ NOT NULL DEFAULT now(),
496 "expiry" TIMESTAMPTZ DEFAULT now() + '1 hour',
497 "used" BOOLEAN NOT NULL DEFAULT FALSE,
498 "scope" TEXT NOT NULL,
499 CONSTRAINT "access_token_needs_expiry"
500 CHECK ("token_type" != 'access'::"token_type" OR "expiry" NOTNULL),
501 CONSTRAINT "authorization_token_needs_redirect_uri"
502 CHECK ("token_type" != 'authorization'::"token_type" OR ("redirect_uri" NOTNULL AND "redirect_uri_explicit" NOTNULL) ) );
503 CREATE INDEX "token_member_id_idx" ON "token" ("member_id");
504 CREATE INDEX "token_authorization_token_id_idx" ON "token" ("authorization_token_id");
505 CREATE INDEX "token_expiry_idx" ON "token" ("expiry");
507 COMMENT ON TABLE "token" IS 'Issued OAuth 2.0 authorization codes and access/refresh tokens';
509 COMMENT ON COLUMN "token"."token" IS 'String secret (the actual token)';
510 COMMENT ON COLUMN "token"."authorization_token_id" IS 'Reference to authorization token if tokens were originally created by Authorization Code flow (allows deletion if code is used twice)';
511 COMMENT ON COLUMN "token"."system_application_id" IS 'If set, then application is a system application';
512 COMMENT ON COLUMN "token"."domain" IS 'If set, then application is a dynamically registered OAuth 2.0 client; value is set to client''s domain';
513 COMMENT ON COLUMN "token"."session_id" IS 'If set, then token is tied to a session; Deletion of session sets value to NULL (via trigger) and removes all scopes without suffix ''_detached''';
514 COMMENT ON COLUMN "token"."redirect_uri" IS 'Authorization codes must be bound to a specific redirect URI';
515 COMMENT ON COLUMN "token"."redirect_uri_explicit" IS 'True if ''redirect_uri'' parameter was explicitly specified during authorization request of the Authorization Code flow (since RFC 6749 requires it to be included in the access token request in this case)';
516 COMMENT ON COLUMN "token"."expiry" IS 'Point in time when code or token expired; In case of "used" authorization codes, authorization code must not be deleted as long as tokens exist which refer to the authorization code';
517 COMMENT ON COLUMN "token"."used" IS 'Can be set to TRUE for authorization codes that have been used (enables deletion of authorization codes that were used twice)';
518 COMMENT ON COLUMN "token"."scope" IS 'Scope as space-separated list of strings (detached scopes are marked with ''_detached'' suffix)';
521 CREATE TABLE "token_scope" (
522 PRIMARY KEY ("token_id", "index"),
523 "token_id" INT8 REFERENCES "token" ("id") ON DELETE CASCADE ON UPDATE CASCADE,
524 "index" INT4,
525 "scope" TEXT NOT NULL );
527 COMMENT ON TABLE "token_scope" IS 'Additional scopes for an authorization code if ''scope1'', ''scope2'', etc. parameters were used during Authorization Code flow to request several access and refresh tokens at once';
530 CREATE TYPE "defeat_strength" AS ENUM ('simple', 'tuple');
532 COMMENT ON TYPE "defeat_strength" IS 'How pairwise defeats are measured for the Schulze method: ''simple'' = only the number of winning votes, ''tuple'' = primarily the number of winning votes, secondarily the number of losing votes';
535 CREATE TYPE "tie_breaking" AS ENUM ('simple', 'variant1', 'variant2');
537 COMMENT ON TYPE "tie_breaking" IS 'Tie-breaker for the Schulze method: ''simple'' = only initiative ids are used, ''variant1'' = use initiative ids in variant 1 for tie breaking of the links (TBRL) and sequentially forbid shared links, ''variant2'' = use initiative ids in variant 2 for tie breaking of the links (TBRL) and sequentially forbid shared links';
540 CREATE TABLE "policy" (
541 "id" SERIAL4 PRIMARY KEY,
542 "index" INT4 NOT NULL,
543 "active" BOOLEAN NOT NULL DEFAULT TRUE,
544 "name" TEXT NOT NULL UNIQUE,
545 "description" TEXT NOT NULL DEFAULT '',
546 "polling" BOOLEAN NOT NULL DEFAULT FALSE,
547 "min_admission_time" INTERVAL,
548 "max_admission_time" INTERVAL,
549 "discussion_time" INTERVAL,
550 "verification_time" INTERVAL,
551 "voting_time" INTERVAL,
552 "issue_quorum" INT4 CHECK ("issue_quorum" >= 1),
553 "issue_quorum_num" INT4,
554 "issue_quorum_den" INT4,
555 "initiative_quorum" INT4 NOT NULL CHECK ("initiative_quorum" >= 1),
556 "initiative_quorum_num" INT4 NOT NULL,
557 "initiative_quorum_den" INT4 NOT NULL,
558 "defeat_strength" "defeat_strength" NOT NULL DEFAULT 'tuple',
559 "tie_breaking" "tie_breaking" NOT NULL DEFAULT 'variant1',
560 "direct_majority_num" INT4 NOT NULL DEFAULT 1,
561 "direct_majority_den" INT4 NOT NULL DEFAULT 2,
562 "direct_majority_strict" BOOLEAN NOT NULL DEFAULT TRUE,
563 "direct_majority_positive" INT4 NOT NULL DEFAULT 0,
564 "direct_majority_non_negative" INT4 NOT NULL DEFAULT 0,
565 "indirect_majority_num" INT4 NOT NULL DEFAULT 1,
566 "indirect_majority_den" INT4 NOT NULL DEFAULT 2,
567 "indirect_majority_strict" BOOLEAN NOT NULL DEFAULT TRUE,
568 "indirect_majority_positive" INT4 NOT NULL DEFAULT 0,
569 "indirect_majority_non_negative" INT4 NOT NULL DEFAULT 0,
570 "no_reverse_beat_path" BOOLEAN NOT NULL DEFAULT FALSE,
571 "no_multistage_majority" BOOLEAN NOT NULL DEFAULT FALSE,
572 CONSTRAINT "issue_quorum_if_and_only_if_not_polling" CHECK (
573 "polling" = ("issue_quorum" ISNULL) AND
574 "polling" = ("issue_quorum_num" ISNULL) AND
575 "polling" = ("issue_quorum_den" ISNULL) ),
576 CONSTRAINT "min_admission_time_smaller_than_max_admission_time" CHECK (
577 "min_admission_time" < "max_admission_time" ),
578 CONSTRAINT "timing_null_or_not_null_constraints" CHECK (
579 ( "polling" = FALSE AND
580 "min_admission_time" NOTNULL AND "max_admission_time" NOTNULL AND
581 "discussion_time" NOTNULL AND
582 "verification_time" NOTNULL AND
583 "voting_time" NOTNULL ) OR
584 ( "polling" = TRUE AND
585 "min_admission_time" ISNULL AND "max_admission_time" ISNULL AND
586 "discussion_time" NOTNULL AND
587 "verification_time" NOTNULL AND
588 "voting_time" NOTNULL ) OR
589 ( "polling" = TRUE AND
590 "min_admission_time" ISNULL AND "max_admission_time" ISNULL AND
591 "discussion_time" ISNULL AND
592 "verification_time" ISNULL AND
593 "voting_time" ISNULL ) ),
594 CONSTRAINT "no_reverse_beat_path_requires_tuple_defeat_strength" CHECK (
595 "defeat_strength" = 'tuple'::"defeat_strength" OR
596 "no_reverse_beat_path" = FALSE ) );
597 CREATE INDEX "policy_active_idx" ON "policy" ("active");
599 COMMENT ON TABLE "policy" IS 'Policies for a particular proceeding type (timelimits, quorum)';
601 COMMENT ON COLUMN "policy"."index" IS 'Determines the order in listings';
602 COMMENT ON COLUMN "policy"."active" IS 'TRUE = policy can be used for new issues';
603 COMMENT ON COLUMN "policy"."polling" IS 'TRUE = special policy for non-user-generated issues without issue quorum, where certain initiatives (those having the "polling" flag set) do not need to pass the initiative quorum; "min_admission_time" and "max_admission_time" MUST be set to NULL, the other timings may be set to NULL altogether, allowing individual timing for those issues';
604 COMMENT ON COLUMN "policy"."min_admission_time" IS 'Minimum duration of issue state ''admission''; Minimum time an issue stays open; Note: should be considerably smaller than "max_admission_time"';
605 COMMENT ON COLUMN "policy"."max_admission_time" IS 'Maximum duration of issue state ''admission''; Maximum time an issue stays open without being "accepted"';
606 COMMENT ON COLUMN "policy"."discussion_time" IS 'Duration of issue state ''discussion''; Regular time until an issue is "half_frozen" after being "accepted"';
607 COMMENT ON COLUMN "policy"."verification_time" IS 'Duration of issue state ''verification''; Regular time until an issue is "fully_frozen" (e.g. entering issue state ''voting'') after being "half_frozen"';
608 COMMENT ON COLUMN "policy"."voting_time" IS 'Duration of issue state ''voting''; Time after an issue is "fully_frozen" but not "closed" (duration of issue state ''voting'')';
609 COMMENT ON COLUMN "policy"."issue_quorum" IS 'Absolute number of supporters needed by an initiative to be "accepted", i.e. pass from ''admission'' to ''discussion'' state';
610 COMMENT ON COLUMN "policy"."issue_quorum_num" IS 'Numerator of supporter quorum to be reached by an initiative to be "accepted", i.e. pass from ''admission'' to ''discussion'' state (Note: further requirements apply, see quorum columns of "area" table)';
611 COMMENT ON COLUMN "policy"."issue_quorum_den" IS 'Denominator of supporter quorum to be reached by an initiative to be "accepted", i.e. pass from ''admission'' to ''discussion'' state (Note: further requirements apply, see quorum columns of "area" table)';
612 COMMENT ON COLUMN "policy"."initiative_quorum" IS 'Absolute number of satisfied supporters to be reached by an initiative to be "admitted" for voting';
613 COMMENT ON COLUMN "policy"."initiative_quorum_num" IS 'Numerator of satisfied supporter quorum to be reached by an initiative to be "admitted" for voting';
614 COMMENT ON COLUMN "policy"."initiative_quorum_den" IS 'Denominator of satisfied supporter quorum to be reached by an initiative to be "admitted" for voting';
615 COMMENT ON COLUMN "policy"."defeat_strength" IS 'How pairwise defeats are measured for the Schulze method; see type "defeat_strength"; ''tuple'' is the recommended setting';
616 COMMENT ON COLUMN "policy"."tie_breaking" IS 'Tie-breaker for the Schulze method; see type "tie_breaking"; ''variant1'' or ''variant2'' are recommended';
617 COMMENT ON COLUMN "policy"."direct_majority_num" IS 'Numerator of fraction of neccessary direct majority for initiatives to be attainable as winner';
618 COMMENT ON COLUMN "policy"."direct_majority_den" IS 'Denominator of fraction of neccessary direct majority for initaitives to be attainable as winner';
619 COMMENT ON COLUMN "policy"."direct_majority_strict" IS 'If TRUE, then the direct majority must be strictly greater than "direct_majority_num"/"direct_majority_den", otherwise it may also be equal.';
620 COMMENT ON COLUMN "policy"."direct_majority_positive" IS 'Absolute number of "positive_votes" neccessary for an initiative to be attainable as winner';
621 COMMENT ON COLUMN "policy"."direct_majority_non_negative" IS 'Absolute number of sum of "positive_votes" and abstentions neccessary for an initiative to be attainable as winner';
622 COMMENT ON COLUMN "policy"."indirect_majority_num" IS 'Numerator of fraction of neccessary indirect majority (through beat path) for initiatives to be attainable as winner';
623 COMMENT ON COLUMN "policy"."indirect_majority_den" IS 'Denominator of fraction of neccessary indirect majority (through beat path) for initiatives to be attainable as winner';
624 COMMENT ON COLUMN "policy"."indirect_majority_strict" IS 'If TRUE, then the indirect majority must be strictly greater than "indirect_majority_num"/"indirect_majority_den", otherwise it may also be equal.';
625 COMMENT ON COLUMN "policy"."indirect_majority_positive" IS 'Absolute number of votes in favor of the winner neccessary in a beat path to the status quo for an initaitive to be attainable as winner';
626 COMMENT ON COLUMN "policy"."indirect_majority_non_negative" IS 'Absolute number of sum of votes in favor and abstentions in a beat path to the status quo for an initiative to be attainable as winner';
627 COMMENT ON COLUMN "policy"."no_reverse_beat_path" IS 'EXPERIMENTAL FEATURE: Causes initiatives with "reverse_beat_path" flag to not be "eligible", thus disallowing them to be winner. See comment on column "initiative"."reverse_beat_path". This option ensures both that a winning initiative is never tied in a (weak) condorcet paradox with the status quo and a winning initiative always beats the status quo directly with a simple majority.';
628 COMMENT ON COLUMN "policy"."no_multistage_majority" IS 'EXPERIMENTAL FEATURE: Causes initiatives with "multistage_majority" flag to not be "eligible", thus disallowing them to be winner. See comment on column "initiative"."multistage_majority". This disqualifies initiatives which could cause an instable result. An instable result in this meaning is a result such that repeating the ballot with same preferences but with the winner of the first ballot as status quo would lead to a different winner in the second ballot. If there are no direct majorities required for the winner, or if in direct comparison only simple majorities are required and "no_reverse_beat_path" is true, then results are always stable and this flag does not have any effect on the winner (but still affects the "eligible" flag of an "initiative").';
631 CREATE TABLE "unit" (
632 "id" SERIAL4 PRIMARY KEY,
633 "parent_id" INT4 REFERENCES "unit" ("id") ON DELETE CASCADE ON UPDATE CASCADE,
634 "active" BOOLEAN NOT NULL DEFAULT TRUE,
635 "name" TEXT NOT NULL, -- full text search
636 "description" TEXT NOT NULL DEFAULT '', -- full text search
637 "external_reference" TEXT,
638 "member_count" INT4,
639 "location" JSONB );
640 CREATE INDEX "unit_root_idx" ON "unit" ("id") WHERE "parent_id" ISNULL;
641 CREATE INDEX "unit_parent_id_idx" ON "unit" ("parent_id");
642 CREATE INDEX "unit_active_idx" ON "unit" ("active");
643 CREATE INDEX "unit_location_idx" ON "unit" USING gist ((GeoJSON_to_ecluster("location")));
645 COMMENT ON TABLE "unit" IS 'Organizational units organized as trees; Delegations are not inherited through these trees.';
647 COMMENT ON COLUMN "unit"."parent_id" IS 'Parent id of tree node; Multiple roots allowed';
648 COMMENT ON COLUMN "unit"."active" IS 'TRUE means new issues can be created in areas of this unit';
649 COMMENT ON COLUMN "unit"."external_reference" IS 'Opaque data field to store an external reference';
650 COMMENT ON COLUMN "unit"."member_count" IS 'Count of members as determined by column "voting_right" in table "privilege" (only active members counted)';
651 COMMENT ON COLUMN "unit"."location" IS 'Geographic location on earth as GeoJSON object indicating valid coordinates for initiatives of issues with this policy';
654 CREATE TABLE "subscription" (
655 PRIMARY KEY ("member_id", "unit_id"),
656 "member_id" INT4 REFERENCES "member" ("id") ON DELETE CASCADE ON UPDATE CASCADE,
657 "unit_id" INT4 REFERENCES "unit" ("id") ON DELETE CASCADE ON UPDATE CASCADE );
658 CREATE INDEX "subscription_unit_id_idx" ON "subscription" ("unit_id");
660 COMMENT ON TABLE "subscription" IS 'An entry in this table denotes that the member wishes to receive notifications regardless of his/her privileges in the given unit';
663 CREATE TABLE "area" (
664 UNIQUE ("unit_id", "id"), -- index needed for foreign-key on table "event"
665 "id" SERIAL4 PRIMARY KEY,
666 "unit_id" INT4 NOT NULL REFERENCES "unit" ("id") ON DELETE CASCADE ON UPDATE CASCADE,
667 "active" BOOLEAN NOT NULL DEFAULT TRUE,
668 "name" TEXT NOT NULL, -- full text search
669 "description" TEXT NOT NULL DEFAULT '', -- full text search
670 "quorum_standard" NUMERIC NOT NULL DEFAULT 2 CHECK ("quorum_standard" >= 0),
671 "quorum_issues" NUMERIC NOT NULL DEFAULT 1 CHECK ("quorum_issues" > 0),
672 "quorum_time" INTERVAL NOT NULL DEFAULT '1 day' CHECK ("quorum_time" > '0'::INTERVAL),
673 "quorum_exponent" NUMERIC NOT NULL DEFAULT 0.5 CHECK ("quorum_exponent" BETWEEN 0 AND 1),
674 "quorum_factor" NUMERIC NOT NULL DEFAULT 2 CHECK ("quorum_factor" >= 1),
675 "quorum_den" INT4 CHECK ("quorum_den" > 0),
676 "issue_quorum" INT4,
677 "external_reference" TEXT,
678 "location" JSONB );
679 CREATE INDEX "area_active_idx" ON "area" ("active");
680 CREATE INDEX "area_location_idx" ON "area" USING gist ((GeoJSON_to_ecluster("location")));
682 COMMENT ON TABLE "area" IS 'Subject areas';
684 COMMENT ON COLUMN "area"."active" IS 'TRUE means new issues can be created in this area';
685 COMMENT ON COLUMN "area"."quorum_standard" IS 'Parameter for dynamic issue quorum: default quorum';
686 COMMENT ON COLUMN "area"."quorum_issues" IS 'Parameter for dynamic issue quorum: number of open issues for default quorum';
687 COMMENT ON COLUMN "area"."quorum_time" IS 'Parameter for dynamic issue quorum: discussion, verification, and voting time of open issues to result in the given default quorum (open issues with shorter time will increase quorum and open issues with longer time will reduce quorum if "quorum_exponent" is greater than zero)';
688 COMMENT ON COLUMN "area"."quorum_exponent" IS 'Parameter for dynamic issue quorum: set to zero to ignore duration of open issues, set to one to fully take duration of open issues into account; defaults to 0.5';
689 COMMENT ON COLUMN "area"."quorum_factor" IS 'Parameter for dynamic issue quorum: factor to increase dynamic quorum when a number of "quorum_issues" issues with "quorum_time" duration of discussion, verification, and voting phase are added to the number of open admitted issues';
690 COMMENT ON COLUMN "area"."quorum_den" IS 'Parameter for dynamic issue quorum: when set, dynamic quorum is multiplied with "issue"."population" and divided by "quorum_den" (and then rounded up)';
691 COMMENT ON COLUMN "area"."issue_quorum" IS 'Additional dynamic issue quorum based on the number of open accepted issues; automatically calculated by function "issue_admission"';
692 COMMENT ON COLUMN "area"."external_reference" IS 'Opaque data field to store an external reference';
693 COMMENT ON COLUMN "area"."location" IS 'Geographic location on earth as GeoJSON object indicating valid coordinates for initiatives of issues with this policy';
696 CREATE TABLE "ignored_area" (
697 PRIMARY KEY ("member_id", "area_id"),
698 "member_id" INT4 REFERENCES "member" ("id") ON DELETE CASCADE ON UPDATE CASCADE,
699 "area_id" INT4 REFERENCES "area" ("id") ON DELETE CASCADE ON UPDATE CASCADE );
700 CREATE INDEX "ignored_area_area_id_idx" ON "ignored_area" ("area_id");
702 COMMENT ON TABLE "ignored_area" IS 'An entry in this table denotes that the member does not wish to receive notifications for the given subject area unless he/she declared interested in a particular issue';
705 CREATE TABLE "allowed_policy" (
706 PRIMARY KEY ("area_id", "policy_id"),
707 "area_id" INT4 REFERENCES "area" ("id") ON DELETE CASCADE ON UPDATE CASCADE,
708 "policy_id" INT4 NOT NULL REFERENCES "policy" ("id") ON DELETE CASCADE ON UPDATE CASCADE,
709 "default_policy" BOOLEAN NOT NULL DEFAULT FALSE );
710 CREATE UNIQUE INDEX "allowed_policy_one_default_per_area_idx" ON "allowed_policy" ("area_id") WHERE "default_policy";
712 COMMENT ON TABLE "allowed_policy" IS 'Selects which policies can be used in each area';
714 COMMENT ON COLUMN "allowed_policy"."default_policy" IS 'One policy per area can be set as default.';
717 CREATE TABLE "snapshot" (
718 UNIQUE ("issue_id", "id"), -- index needed for foreign-key on table "issue"
719 "id" SERIAL8 PRIMARY KEY,
720 "calculated" TIMESTAMPTZ NOT NULL DEFAULT now(),
721 "population" INT4,
722 "area_id" INT4 NOT NULL REFERENCES "area" ("id") ON DELETE CASCADE ON UPDATE CASCADE,
723 "issue_id" INT4 ); -- NOTE: following (cyclic) reference is added later through ALTER command: REFERENCES "issue" ("id") ON DELETE CASCADE ON UPDATE CASCADE
725 COMMENT ON TABLE "snapshot" IS 'Point in time when a snapshot of one or more issues (see table "snapshot_issue") and their supporter situation is taken';
728 CREATE TABLE "snapshot_population" (
729 PRIMARY KEY ("snapshot_id", "member_id"),
730 "snapshot_id" INT8 REFERENCES "snapshot" ("id") ON DELETE CASCADE ON UPDATE CASCADE,
731 "member_id" INT4 REFERENCES "member" ("id") ON DELETE RESTRICT ON UPDATE CASCADE );
733 COMMENT ON TABLE "snapshot_population" IS 'Members with voting right relevant for a snapshot';
736 CREATE TYPE "issue_state" AS ENUM (
737 'admission', 'discussion', 'verification', 'voting',
738 'canceled_by_admin',
739 'canceled_revoked_before_accepted',
740 'canceled_issue_not_accepted',
741 'canceled_after_revocation_during_discussion',
742 'canceled_after_revocation_during_verification',
743 'canceled_no_initiative_admitted',
744 'finished_without_winner', 'finished_with_winner');
746 COMMENT ON TYPE "issue_state" IS 'State of issues';
749 CREATE TABLE "issue" (
750 UNIQUE ("area_id", "id"), -- index needed for foreign-key on table "event"
751 UNIQUE ("policy_id", "id"), -- index needed for foreign-key on table "event"
752 "id" SERIAL4 PRIMARY KEY,
753 "area_id" INT4 NOT NULL REFERENCES "area" ("id") ON DELETE CASCADE ON UPDATE CASCADE,
754 "policy_id" INT4 NOT NULL REFERENCES "policy" ("id") ON DELETE RESTRICT ON UPDATE CASCADE,
755 "admin_notice" TEXT,
756 "external_reference" TEXT,
757 "state" "issue_state" NOT NULL DEFAULT 'admission',
758 "phase_finished" TIMESTAMPTZ,
759 "created" TIMESTAMPTZ NOT NULL DEFAULT now(),
760 "accepted" TIMESTAMPTZ,
761 "half_frozen" TIMESTAMPTZ,
762 "fully_frozen" TIMESTAMPTZ,
763 "closed" TIMESTAMPTZ,
764 "cleaned" TIMESTAMPTZ,
765 "min_admission_time" INTERVAL,
766 "max_admission_time" INTERVAL,
767 "discussion_time" INTERVAL NOT NULL,
768 "verification_time" INTERVAL NOT NULL,
769 "voting_time" INTERVAL NOT NULL,
770 "calculated" TIMESTAMPTZ, -- NOTE: copy of "calculated" column of latest snapshot, but no referential integrity to avoid overhead
771 "latest_snapshot_id" INT8 REFERENCES "snapshot" ("id") ON DELETE RESTRICT ON UPDATE CASCADE,
772 "admission_snapshot_id" INT8 REFERENCES "snapshot" ("id") ON DELETE SET NULL ON UPDATE CASCADE,
773 "half_freeze_snapshot_id" INT8,
774 FOREIGN KEY ("id", "half_freeze_snapshot_id")
775 REFERENCES "snapshot" ("issue_id", "id") ON DELETE RESTRICT ON UPDATE CASCADE,
776 "full_freeze_snapshot_id" INT8,
777 FOREIGN KEY ("id", "full_freeze_snapshot_id")
778 REFERENCES "snapshot" ("issue_id", "id") ON DELETE RESTRICT ON UPDATE CASCADE,
779 "issue_quorum" INT4,
780 "initiative_quorum" INT4,
781 "population" INT4,
782 "voter_count" INT4,
783 "status_quo_schulze_rank" INT4,
784 CONSTRAINT "admission_time_not_null_unless_instantly_accepted" CHECK (
785 ("min_admission_time" NOTNULL) = ("max_admission_time" NOTNULL) AND
786 ("min_admission_time" NOTNULL OR ("accepted" NOTNULL AND "accepted" = "created")) ),
787 CONSTRAINT "valid_state" CHECK (
788 (
789 ("accepted" ISNULL AND "half_frozen" ISNULL AND "fully_frozen" ISNULL ) OR
790 ("accepted" NOTNULL AND "half_frozen" ISNULL AND "fully_frozen" ISNULL ) OR
791 ("accepted" NOTNULL AND "half_frozen" NOTNULL AND "fully_frozen" ISNULL ) OR
792 ("accepted" NOTNULL AND "half_frozen" NOTNULL AND "fully_frozen" NOTNULL)
793 ) AND (
794 ("state" = 'admission' AND "closed" ISNULL AND "accepted" ISNULL) OR
795 ("state" = 'discussion' AND "closed" ISNULL AND "accepted" NOTNULL AND "half_frozen" ISNULL) OR
796 ("state" = 'verification' AND "closed" ISNULL AND "half_frozen" NOTNULL AND "fully_frozen" ISNULL) OR
797 ("state" = 'voting' AND "closed" ISNULL AND "fully_frozen" NOTNULL) OR
798 ("state" = 'canceled_by_admin' AND "closed" NOTNULL) OR
799 ("state" = 'canceled_revoked_before_accepted' AND "closed" NOTNULL AND "accepted" ISNULL) OR
800 ("state" = 'canceled_issue_not_accepted' AND "closed" NOTNULL AND "accepted" ISNULL) OR
801 ("state" = 'canceled_after_revocation_during_discussion' AND "closed" NOTNULL AND "half_frozen" ISNULL) OR
802 ("state" = 'canceled_after_revocation_during_verification' AND "closed" NOTNULL AND "fully_frozen" ISNULL) OR
803 ("state" = 'canceled_no_initiative_admitted' AND "closed" NOTNULL AND "fully_frozen" NOTNULL AND "closed" = "fully_frozen") OR
804 ("state" = 'finished_without_winner' AND "closed" NOTNULL AND "fully_frozen" NOTNULL AND "closed" != "fully_frozen") OR
805 ("state" = 'finished_with_winner' AND "closed" NOTNULL AND "fully_frozen" NOTNULL AND "closed" != "fully_frozen")
806 )),
807 CONSTRAINT "phase_finished_only_when_not_closed" CHECK (
808 "phase_finished" ISNULL OR "closed" ISNULL ),
809 CONSTRAINT "state_change_order" CHECK (
810 "created" <= "accepted" AND
811 "accepted" <= "half_frozen" AND
812 "half_frozen" <= "fully_frozen" AND
813 "fully_frozen" <= "closed" ),
814 CONSTRAINT "only_closed_issues_may_be_cleaned" CHECK (
815 "cleaned" ISNULL OR "closed" NOTNULL ),
816 CONSTRAINT "snapshot_required" CHECK (
817 --("accepted" ISNULL OR "admission_snapshot_id" NOTNULL) AND
818 ("half_frozen" ISNULL OR "half_freeze_snapshot_id" NOTNULL) AND
819 ("fully_frozen" ISNULL OR "full_freeze_snapshot_id" NOTNULL) ) );
820 CREATE INDEX "issue_state_idx" ON "issue" ("state");
821 CREATE INDEX "issue_created_idx" ON "issue" ("created");
822 CREATE INDEX "issue_closed_idx" ON "issue" ("closed");
823 CREATE INDEX "issue_open_created_idx" ON "issue" ("created") WHERE "closed" ISNULL;
824 CREATE INDEX "issue_latest_snapshot_id_idx" ON "issue" ("latest_snapshot_id");
825 CREATE INDEX "issue_admission_snapshot_id_idx" ON "issue" ("admission_snapshot_id");
826 CREATE INDEX "issue_half_freeze_snapshot_id_idx" ON "issue" ("half_freeze_snapshot_id");
827 CREATE INDEX "issue_full_freeze_snapshot_id_idx" ON "issue" ("full_freeze_snapshot_id");
829 COMMENT ON TABLE "issue" IS 'Groups of initiatives';
831 COMMENT ON COLUMN "issue"."admin_notice" IS 'Public notice by admin to explain manual interventions, or to announce corrections';
832 COMMENT ON COLUMN "issue"."external_reference" IS 'Opaque data field to store an external reference';
833 COMMENT ON COLUMN "issue"."phase_finished" IS 'Set to a value NOTNULL, if the current phase has finished, but calculations are pending; No changes in this issue shall be made by the frontend or API when this value is set';
834 COMMENT ON COLUMN "issue"."accepted" IS 'Point in time, when the issue was accepted for further discussion (see columns "issue_quorum_num" and "issue_quorum_den" of table "policy" and quorum columns of table "area")';
835 COMMENT ON COLUMN "issue"."half_frozen" IS 'Point in time, when "discussion_time" has elapsed; Frontends must ensure that for half_frozen issues a) initiatives are not revoked, b) no new drafts are created, c) no initiators are added or removed.';
836 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.';
837 COMMENT ON COLUMN "issue"."closed" IS 'Point in time, when "max_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.';
838 COMMENT ON COLUMN "issue"."cleaned" IS 'Point in time, when discussion data and votes had been deleted';
839 COMMENT ON COLUMN "issue"."min_admission_time" IS 'Copied from "policy" table at creation of issue';
840 COMMENT ON COLUMN "issue"."max_admission_time" IS 'Copied from "policy" table at creation of issue';
841 COMMENT ON COLUMN "issue"."discussion_time" IS 'Copied from "policy" table at creation of issue';
842 COMMENT ON COLUMN "issue"."verification_time" IS 'Copied from "policy" table at creation of issue';
843 COMMENT ON COLUMN "issue"."voting_time" IS 'Copied from "policy" table at creation of issue';
844 COMMENT ON COLUMN "issue"."calculated" IS 'Point in time, when most recent snapshot and "population" and *_count values were calculated (NOTE: value is equal to "snapshot"."calculated" of snapshot with "id"="issue"."latest_snapshot_id")';
845 COMMENT ON COLUMN "issue"."latest_snapshot_id" IS 'Snapshot id of most recent snapshot';
846 COMMENT ON COLUMN "issue"."admission_snapshot_id" IS 'Snapshot id when issue as accepted or canceled in admission phase';
847 COMMENT ON COLUMN "issue"."half_freeze_snapshot_id" IS 'Snapshot id at end of discussion phase';
848 COMMENT ON COLUMN "issue"."full_freeze_snapshot_id" IS 'Snapshot id at end of verification phase';
849 COMMENT ON COLUMN "issue"."issue_quorum" IS 'Calculated number of supporters needed by an initiative of the issue to be "accepted", i.e. pass from ''admission'' to ''discussion'' state';
850 COMMENT ON COLUMN "issue"."initiative_quorum" IS 'Calculated number of satisfied supporters to be reached by an initiative to be "admitted" for voting';
851 COMMENT ON COLUMN "issue"."population" IS 'Count of members in "snapshot_population" table with "snapshot_id" equal to "issue"."latest_snapshot_id"';
852 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';
853 COMMENT ON COLUMN "issue"."status_quo_schulze_rank" IS 'Schulze rank of status quo, as calculated by "calculate_ranks" function';
856 ALTER TABLE "snapshot" ADD FOREIGN KEY ("issue_id") REFERENCES "issue" ("id") ON DELETE CASCADE ON UPDATE CASCADE;
859 CREATE TABLE "issue_order_in_admission_state" (
860 "id" INT8 PRIMARY KEY, -- NOTE: no referential integrity due to performans/locking issues; REFERENCES "issue" ("id") ON DELETE CASCADE ON UPDATE CASCADE,
861 "order_in_area" INT4,
862 "order_in_unit" INT4 );
864 COMMENT ON TABLE "issue_order_in_admission_state" IS 'Ordering information for issues that are not stored in the "issue" table to avoid locking of multiple issues at once; Filled/updated by "lf_update_issue_order"';
866 COMMENT ON COLUMN "issue_order_in_admission_state"."id" IS 'References "issue" ("id") but has no referential integrity trigger associated, due to performance/locking issues';
867 COMMENT ON COLUMN "issue_order_in_admission_state"."order_in_area" IS 'Order of issues in admission state within a single area; NULL values sort last';
868 COMMENT ON COLUMN "issue_order_in_admission_state"."order_in_unit" IS 'Order of issues in admission state within all areas of a unit; NULL values sort last';
871 CREATE TABLE "initiative" (
872 UNIQUE ("issue_id", "id"), -- index needed for foreign-key on table "vote"
873 "issue_id" INT4 NOT NULL REFERENCES "issue" ("id") ON DELETE CASCADE ON UPDATE CASCADE,
874 "id" SERIAL4 PRIMARY KEY,
875 "name" TEXT NOT NULL, -- full text index
876 "polling" BOOLEAN NOT NULL DEFAULT FALSE,
877 "created" TIMESTAMPTZ NOT NULL DEFAULT now(),
878 "revoked" TIMESTAMPTZ,
879 "revoked_by_member_id" INT4 REFERENCES "member" ("id") ON DELETE RESTRICT ON UPDATE CASCADE,
880 "suggested_initiative_id" INT4 REFERENCES "initiative" ("id") ON DELETE SET NULL ON UPDATE CASCADE,
881 "location" JSONB,
882 "content" TEXT, -- full text search
883 "external_reference" TEXT,
884 "admitted" BOOLEAN,
885 "supporter_count" INT4,
886 "informed_supporter_count" INT4,
887 "satisfied_supporter_count" INT4,
888 "satisfied_informed_supporter_count" INT4,
889 "harmonic_weight" NUMERIC(12, 3),
890 "final_suggestion_order_calculated" BOOLEAN NOT NULL DEFAULT FALSE,
891 "first_preference_votes" INT4,
892 "positive_votes" INT4,
893 "negative_votes" INT4,
894 "direct_majority" BOOLEAN,
895 "indirect_majority" BOOLEAN,
896 "schulze_rank" INT4,
897 "better_than_status_quo" BOOLEAN,
898 "worse_than_status_quo" BOOLEAN,
899 "reverse_beat_path" BOOLEAN,
900 "multistage_majority" BOOLEAN,
901 "eligible" BOOLEAN,
902 "winner" BOOLEAN,
903 "rank" INT4,
904 CONSTRAINT "all_or_none_of_revoked_and_revoked_by_member_id_must_be_null"
905 CHECK (("revoked" NOTNULL) = ("revoked_by_member_id" NOTNULL)),
906 CONSTRAINT "non_revoked_initiatives_cant_suggest_other"
907 CHECK ("revoked" NOTNULL OR "suggested_initiative_id" ISNULL),
908 CONSTRAINT "revoked_initiatives_cant_be_admitted"
909 CHECK ("revoked" ISNULL OR "admitted" ISNULL),
910 CONSTRAINT "non_admitted_initiatives_cant_contain_voting_results" CHECK (
911 ( "admitted" NOTNULL AND "admitted" = TRUE ) OR
912 ( "first_preference_votes" ISNULL AND
913 "positive_votes" ISNULL AND "negative_votes" ISNULL AND
914 "direct_majority" ISNULL AND "indirect_majority" ISNULL AND
915 "schulze_rank" ISNULL AND
916 "better_than_status_quo" ISNULL AND "worse_than_status_quo" ISNULL AND
917 "reverse_beat_path" ISNULL AND "multistage_majority" ISNULL AND
918 "eligible" ISNULL AND "winner" ISNULL AND "rank" ISNULL ) ),
919 CONSTRAINT "better_excludes_worse" CHECK (NOT ("better_than_status_quo" AND "worse_than_status_quo")),
920 CONSTRAINT "minimum_requirement_to_be_eligible" CHECK (
921 "eligible" = FALSE OR
922 ("direct_majority" AND "indirect_majority" AND "better_than_status_quo") ),
923 CONSTRAINT "winner_must_be_eligible" CHECK ("winner"=FALSE OR "eligible"=TRUE),
924 CONSTRAINT "winner_must_have_first_rank" CHECK ("winner"=FALSE OR "rank"=1),
925 CONSTRAINT "eligible_at_first_rank_is_winner" CHECK ("eligible"=FALSE OR "rank"!=1 OR "winner"=TRUE),
926 CONSTRAINT "unique_rank_per_issue" UNIQUE ("issue_id", "rank") );
927 CREATE INDEX "initiative_created_idx" ON "initiative" ("created");
928 CREATE INDEX "initiative_location_idx" ON "initiative" USING gist ((GeoJSON_to_ecluster("location")));
930 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.';
932 COMMENT ON COLUMN "initiative"."polling" IS 'Initiative does not need to pass the initiative quorum (see "policy"."polling")';
933 COMMENT ON COLUMN "initiative"."revoked" IS 'Point in time, when one initiator decided to revoke the initiative';
934 COMMENT ON COLUMN "initiative"."revoked_by_member_id" IS 'Member, who decided to revoke the initiative';
935 COMMENT ON COLUMN "initiative"."location" IS 'Geographic location of initiative as GeoJSON object (automatically copied from most recent draft)';
936 COMMENT ON COLUMN "initiative"."content" IS 'Initiative text (automatically copied from most recent draft)';
937 COMMENT ON COLUMN "initiative"."external_reference" IS 'Opaque data field to store an external reference';
938 COMMENT ON COLUMN "initiative"."admitted" IS 'TRUE, if initiative reaches the "initiative_quorum" when freezing the issue';
939 COMMENT ON COLUMN "initiative"."supporter_count" IS 'Calculated from table "direct_supporter_snapshot"';
940 COMMENT ON COLUMN "initiative"."informed_supporter_count" IS 'Calculated from table "direct_supporter_snapshot"';
941 COMMENT ON COLUMN "initiative"."satisfied_supporter_count" IS 'Calculated from table "direct_supporter_snapshot"';
942 COMMENT ON COLUMN "initiative"."satisfied_informed_supporter_count" IS 'Calculated from table "direct_supporter_snapshot"';
943 COMMENT ON COLUMN "initiative"."harmonic_weight" IS 'Indicates the relevancy of the initiative, calculated from the potential supporters weighted with the harmonic series to avoid a large number of clones affecting other initiative''s sorting positions too much; shall be used as secondary sorting key after "admitted" as primary sorting key';
944 COMMENT ON COLUMN "initiative"."final_suggestion_order_calculated" IS 'Set to TRUE, when "proportional_order" of suggestions has been calculated the last time';
945 COMMENT ON COLUMN "initiative"."first_preference_votes" IS 'Number of direct and delegating voters who ranked this initiative as their first choice';
946 COMMENT ON COLUMN "initiative"."positive_votes" IS 'Number of direct and delegating voters who ranked this initiative better than the status quo';
947 COMMENT ON COLUMN "initiative"."negative_votes" IS 'Number of direct and delegating voters who ranked this initiative worse than the status quo';
948 COMMENT ON COLUMN "initiative"."direct_majority" IS 'TRUE, if "positive_votes"/("positive_votes"+"negative_votes") is strictly greater or greater-equal than "direct_majority_num"/"direct_majority_den", and "positive_votes" is greater-equal than "direct_majority_positive", and ("positive_votes"+abstentions) is greater-equal than "direct_majority_non_negative"';
949 COMMENT ON COLUMN "initiative"."indirect_majority" IS 'Same as "direct_majority", but also considering indirect beat paths';
950 COMMENT ON COLUMN "initiative"."schulze_rank" IS 'Schulze-Ranking';
951 COMMENT ON COLUMN "initiative"."better_than_status_quo" IS 'TRUE, if initiative has a schulze-ranking better than the status quo';
952 COMMENT ON COLUMN "initiative"."worse_than_status_quo" IS 'TRUE, if initiative has a schulze-ranking worse than the status quo (DEPRECATED, since schulze-ranking is unique per issue; use "better_than_status_quo"=FALSE)';
953 COMMENT ON COLUMN "initiative"."reverse_beat_path" IS 'TRUE, if there is a beat path (may include ties) from this initiative to the status quo; set to NULL if "policy"."defeat_strength" is set to ''simple''';
954 COMMENT ON COLUMN "initiative"."multistage_majority" IS 'TRUE, if either (a) this initiative has no better rank than the status quo, or (b) there exists a better ranked initiative X, which directly beats this initiative, and either more voters prefer X to this initiative than voters preferring X to the status quo or less voters prefer this initiative to X than voters preferring the status quo to X';
955 COMMENT ON COLUMN "initiative"."eligible" IS 'Initiative has a "direct_majority" and an "indirect_majority", is "better_than_status_quo" and depending on selected policy the initiative has no "reverse_beat_path" or "multistage_majority"';
956 COMMENT ON COLUMN "initiative"."winner" IS 'Winner is the "eligible" initiative with best "schulze_rank"';
957 COMMENT ON COLUMN "initiative"."rank" IS 'Unique ranking for all "admitted" initiatives per issue; lower rank is better; a winner always has rank 1, but rank 1 does not imply that an initiative is winner; initiatives with "direct_majority" AND "indirect_majority" always have a better (lower) rank than other initiatives';
960 CREATE TABLE "battle" (
961 "issue_id" INT4 NOT NULL,
962 "winning_initiative_id" INT4,
963 FOREIGN KEY ("issue_id", "winning_initiative_id") REFERENCES "initiative" ("issue_id", "id") ON DELETE CASCADE ON UPDATE CASCADE,
964 "losing_initiative_id" INT4,
965 FOREIGN KEY ("issue_id", "losing_initiative_id") REFERENCES "initiative" ("issue_id", "id") ON DELETE CASCADE ON UPDATE CASCADE,
966 "count" INT4 NOT NULL,
967 CONSTRAINT "initiative_ids_not_equal" CHECK (
968 "winning_initiative_id" != "losing_initiative_id" AND
969 ("winning_initiative_id" NOTNULL OR "losing_initiative_id" NOTNULL) ) );
970 CREATE UNIQUE INDEX "battle_winning_losing_idx" ON "battle" ("issue_id", "winning_initiative_id", "losing_initiative_id");
971 CREATE UNIQUE INDEX "battle_winning_null_idx" ON "battle" ("issue_id", "winning_initiative_id") WHERE "losing_initiative_id" ISNULL;
972 CREATE UNIQUE INDEX "battle_null_losing_idx" ON "battle" ("issue_id", "losing_initiative_id") WHERE "winning_initiative_id" ISNULL;
974 COMMENT ON TABLE "battle" IS 'Number of members preferring one initiative to another; Filled by "battle_view" when closing an issue; NULL as initiative_id denotes virtual "status-quo" initiative';
977 CREATE TABLE "ignored_initiative" (
978 PRIMARY KEY ("member_id", "initiative_id"),
979 "member_id" INT4 REFERENCES "member" ("id") ON DELETE CASCADE ON UPDATE CASCADE,
980 "initiative_id" INT4 REFERENCES "initiative" ("id") ON DELETE CASCADE ON UPDATE CASCADE );
981 CREATE INDEX "ignored_initiative_initiative_id_idx" ON "ignored_initiative" ("initiative_id");
983 COMMENT ON TABLE "ignored_initiative" IS 'An entry in this table denotes that the member does not wish to receive notifications for the given initiative';
986 CREATE TABLE "draft" (
987 UNIQUE ("initiative_id", "id"), -- index needed for foreign-key on table "supporter"
988 "initiative_id" INT4 NOT NULL REFERENCES "initiative" ("id") ON DELETE CASCADE ON UPDATE CASCADE,
989 "id" SERIAL8 PRIMARY KEY,
990 "created" TIMESTAMPTZ NOT NULL DEFAULT now(),
991 "author_id" INT4 NOT NULL REFERENCES "member" ("id") ON DELETE RESTRICT ON UPDATE CASCADE,
992 "formatting_engine" TEXT,
993 "content" TEXT NOT NULL, -- full text search
994 "location" JSONB,
995 "external_reference" TEXT );
996 CREATE INDEX "draft_created_idx" ON "draft" ("created");
997 CREATE INDEX "draft_author_id_created_idx" ON "draft" ("author_id", "created");
998 CREATE INDEX "draft_location_idx" ON "draft" USING gist ((GeoJSON_to_ecluster("location")));
1000 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.';
1002 COMMENT ON COLUMN "draft"."formatting_engine" IS 'Allows different formatting engines (i.e. wiki formats) to be used';
1003 COMMENT ON COLUMN "draft"."content" IS 'Text of the draft in a format depending on the field "formatting_engine"';
1004 COMMENT ON COLUMN "draft"."location" IS 'Geographic location of initiative as GeoJSON object (automatically copied to "initiative" table if draft is most recent)';
1005 COMMENT ON COLUMN "draft"."external_reference" IS 'Opaque data field to store an external reference';
1008 CREATE TABLE "rendered_draft" (
1009 PRIMARY KEY ("draft_id", "format"),
1010 "draft_id" INT8 REFERENCES "draft" ("id") ON DELETE CASCADE ON UPDATE CASCADE,
1011 "format" TEXT,
1012 "content" TEXT NOT NULL );
1014 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)';
1017 CREATE TABLE "draft_attachment" (
1018 "id" SERIAL8 PRIMARY KEY,
1019 "draft_id" INT8 REFERENCES "draft" ("id") ON DELETE CASCADE ON UPDATE CASCADE,
1020 "file_id" INT8 REFERENCES "file" ("id") ON DELETE RESTRICT ON UPDATE CASCADE,
1021 "content_type" TEXT,
1022 "title" TEXT,
1023 "description" TEXT );
1025 COMMENT ON TABLE "draft_attachment" IS 'Binary attachments for a draft (images, PDF file, etc.); Implicitly ordered through ''id'' column';
1028 CREATE TABLE "suggestion" (
1029 UNIQUE ("initiative_id", "id"), -- index needed for foreign-key on table "opinion"
1030 "initiative_id" INT4 NOT NULL REFERENCES "initiative" ("id") ON DELETE CASCADE ON UPDATE CASCADE,
1031 "id" SERIAL8 PRIMARY KEY,
1032 "draft_id" INT8 NOT NULL,
1033 FOREIGN KEY ("initiative_id", "draft_id") REFERENCES "draft" ("initiative_id", "id") ON DELETE NO ACTION ON UPDATE CASCADE,
1034 "created" TIMESTAMPTZ NOT NULL DEFAULT now(),
1035 "author_id" INT4 NOT NULL REFERENCES "member" ("id") ON DELETE RESTRICT ON UPDATE CASCADE,
1036 "name" TEXT NOT NULL, -- full text search
1037 "formatting_engine" TEXT,
1038 "content" TEXT NOT NULL DEFAULT '', -- full text search
1039 "location" JSONB,
1040 "external_reference" TEXT,
1041 "minus2_unfulfilled_count" INT4,
1042 "minus2_fulfilled_count" INT4,
1043 "minus1_unfulfilled_count" INT4,
1044 "minus1_fulfilled_count" INT4,
1045 "plus1_unfulfilled_count" INT4,
1046 "plus1_fulfilled_count" INT4,
1047 "plus2_unfulfilled_count" INT4,
1048 "plus2_fulfilled_count" INT4,
1049 "proportional_order" INT4 );
1050 CREATE INDEX "suggestion_created_idx" ON "suggestion" ("created");
1051 CREATE INDEX "suggestion_author_id_created_idx" ON "suggestion" ("author_id", "created");
1052 CREATE INDEX "suggestion_location_idx" ON "suggestion" USING gist ((GeoJSON_to_ecluster("location")));
1054 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';
1056 COMMENT ON COLUMN "suggestion"."draft_id" IS 'Draft, which the author has seen when composing the suggestion; should always be set by a frontend, but defaults to current draft of the initiative (implemented by trigger "default_for_draft_id")';
1057 COMMENT ON COLUMN "suggestion"."location" IS 'Geographic location of suggestion as GeoJSON object';
1058 COMMENT ON COLUMN "suggestion"."external_reference" IS 'Opaque data field to store an external reference';
1059 COMMENT ON COLUMN "suggestion"."minus2_unfulfilled_count" IS 'Calculated from table "direct_supporter_snapshot", not requiring informed supporters';
1060 COMMENT ON COLUMN "suggestion"."minus2_fulfilled_count" IS 'Calculated from table "direct_supporter_snapshot", not requiring informed supporters';
1061 COMMENT ON COLUMN "suggestion"."minus1_unfulfilled_count" IS 'Calculated from table "direct_supporter_snapshot", not requiring informed supporters';
1062 COMMENT ON COLUMN "suggestion"."minus1_fulfilled_count" IS 'Calculated from table "direct_supporter_snapshot", not requiring informed supporters';
1063 COMMENT ON COLUMN "suggestion"."plus1_unfulfilled_count" IS 'Calculated from table "direct_supporter_snapshot", not requiring informed supporters';
1064 COMMENT ON COLUMN "suggestion"."plus1_fulfilled_count" IS 'Calculated from table "direct_supporter_snapshot", not requiring informed supporters';
1065 COMMENT ON COLUMN "suggestion"."plus2_unfulfilled_count" IS 'Calculated from table "direct_supporter_snapshot", not requiring informed supporters';
1066 COMMENT ON COLUMN "suggestion"."plus2_fulfilled_count" IS 'Calculated from table "direct_supporter_snapshot", not requiring informed supporters';
1067 COMMENT ON COLUMN "suggestion"."proportional_order" IS 'To be used for sorting suggestions within an initiative; NULL values sort last; updated by "lf_update_suggestion_order"';
1070 CREATE TABLE "rendered_suggestion" (
1071 PRIMARY KEY ("suggestion_id", "format"),
1072 "suggestion_id" INT8 REFERENCES "suggestion" ("id") ON DELETE CASCADE ON UPDATE CASCADE,
1073 "format" TEXT,
1074 "content" TEXT NOT NULL );
1076 COMMENT ON TABLE "rendered_suggestion" IS 'This table may be used by frontends to cache "rendered" drafts (e.g. HTML output generated from wiki text)';
1079 CREATE TABLE "temporary_suggestion_counts" (
1080 "id" INT8 PRIMARY KEY, -- NOTE: no referential integrity due to performance/locking issues; REFERENCES "suggestion" ("id") ON DELETE CASCADE ON UPDATE CASCADE,
1081 "minus2_unfulfilled_count" INT4 NOT NULL,
1082 "minus2_fulfilled_count" INT4 NOT NULL,
1083 "minus1_unfulfilled_count" INT4 NOT NULL,
1084 "minus1_fulfilled_count" INT4 NOT NULL,
1085 "plus1_unfulfilled_count" INT4 NOT NULL,
1086 "plus1_fulfilled_count" INT4 NOT NULL,
1087 "plus2_unfulfilled_count" INT4 NOT NULL,
1088 "plus2_fulfilled_count" INT4 NOT NULL );
1090 COMMENT ON TABLE "temporary_suggestion_counts" IS 'Holds certain calculated values (suggestion counts) temporarily until they can be copied into table "suggestion"';
1092 COMMENT ON COLUMN "temporary_suggestion_counts"."id" IS 'References "suggestion" ("id") but has no referential integrity trigger associated, due to performance/locking issues';
1095 CREATE TABLE "privilege" (
1096 PRIMARY KEY ("unit_id", "member_id"),
1097 "unit_id" INT4 REFERENCES "unit" ("id") ON DELETE CASCADE ON UPDATE CASCADE,
1098 "member_id" INT4 REFERENCES "member" ("id") ON DELETE CASCADE ON UPDATE CASCADE,
1099 "admin_manager" BOOLEAN NOT NULL DEFAULT FALSE,
1100 "unit_manager" BOOLEAN NOT NULL DEFAULT FALSE,
1101 "area_manager" BOOLEAN NOT NULL DEFAULT FALSE,
1102 "member_manager" BOOLEAN NOT NULL DEFAULT FALSE,
1103 "initiative_right" BOOLEAN NOT NULL DEFAULT TRUE,
1104 "voting_right" BOOLEAN NOT NULL DEFAULT TRUE,
1105 "polling_right" BOOLEAN NOT NULL DEFAULT FALSE );
1107 COMMENT ON TABLE "privilege" IS 'Members rights related to each unit';
1109 COMMENT ON COLUMN "privilege"."admin_manager" IS 'Grant/revoke any privileges to/from other members';
1110 COMMENT ON COLUMN "privilege"."unit_manager" IS 'Create and disable sub units';
1111 COMMENT ON COLUMN "privilege"."area_manager" IS 'Create and disable areas and set area parameters';
1112 COMMENT ON COLUMN "privilege"."member_manager" IS 'Adding/removing members from the unit, granting or revoking "initiative_right" and "voting_right"';
1113 COMMENT ON COLUMN "privilege"."initiative_right" IS 'Right to create an initiative';
1114 COMMENT ON COLUMN "privilege"."voting_right" IS 'Right to support initiatives, create and rate suggestions, and to vote';
1115 COMMENT ON COLUMN "privilege"."polling_right" IS 'Right to create issues with policies having the "policy"."polling" flag set, and to add initiatives having the "initiative"."polling" flag set to those issues';
1118 CREATE TABLE "interest" (
1119 PRIMARY KEY ("issue_id", "member_id"),
1120 "issue_id" INT4 REFERENCES "issue" ("id") ON DELETE CASCADE ON UPDATE CASCADE,
1121 "member_id" INT4 REFERENCES "member" ("id") ON DELETE RESTRICT ON UPDATE CASCADE );
1122 CREATE INDEX "interest_member_id_idx" ON "interest" ("member_id");
1124 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.';
1127 CREATE TABLE "initiator" (
1128 PRIMARY KEY ("initiative_id", "member_id"),
1129 "initiative_id" INT4 REFERENCES "initiative" ("id") ON DELETE CASCADE ON UPDATE CASCADE,
1130 "member_id" INT4 REFERENCES "member" ("id") ON DELETE RESTRICT ON UPDATE CASCADE,
1131 "accepted" BOOLEAN );
1132 CREATE INDEX "initiator_member_id_idx" ON "initiator" ("member_id");
1134 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.';
1136 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.';
1139 CREATE TABLE "supporter" (
1140 "issue_id" INT4 NOT NULL,
1141 PRIMARY KEY ("initiative_id", "member_id"),
1142 "initiative_id" INT4,
1143 "member_id" INT4,
1144 "draft_id" INT8 NOT NULL,
1145 FOREIGN KEY ("issue_id", "member_id") REFERENCES "interest" ("issue_id", "member_id") ON DELETE CASCADE ON UPDATE CASCADE,
1146 FOREIGN KEY ("initiative_id", "draft_id") REFERENCES "draft" ("initiative_id", "id") ON DELETE NO ACTION ON UPDATE CASCADE );
1147 CREATE INDEX "supporter_member_id_idx" ON "supporter" ("member_id");
1149 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.';
1151 COMMENT ON COLUMN "supporter"."issue_id" IS 'WARNING: No index: For selections use column "initiative_id" and join via table "initiative" where neccessary';
1152 COMMENT ON COLUMN "supporter"."draft_id" IS 'Latest seen draft; should always be set by a frontend, but defaults to current draft of the initiative (implemented by trigger "default_for_draft_id")';
1155 CREATE TABLE "opinion" (
1156 "initiative_id" INT4 NOT NULL,
1157 PRIMARY KEY ("suggestion_id", "member_id"),
1158 "suggestion_id" INT8,
1159 "member_id" INT4,
1160 "degree" INT2 NOT NULL CHECK ("degree" >= -2 AND "degree" <= 2 AND "degree" != 0),
1161 "fulfilled" BOOLEAN NOT NULL DEFAULT FALSE,
1162 FOREIGN KEY ("initiative_id", "suggestion_id") REFERENCES "suggestion" ("initiative_id", "id") ON DELETE CASCADE ON UPDATE CASCADE,
1163 FOREIGN KEY ("initiative_id", "member_id") REFERENCES "supporter" ("initiative_id", "member_id") ON DELETE CASCADE ON UPDATE CASCADE );
1164 CREATE INDEX "opinion_member_id_initiative_id_idx" ON "opinion" ("member_id", "initiative_id");
1166 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.';
1168 COMMENT ON COLUMN "opinion"."degree" IS '2 = fulfillment required for support; 1 = fulfillment desired; -1 = fulfillment unwanted; -2 = fulfillment cancels support';
1171 CREATE TYPE "delegation_scope" AS ENUM ('unit', 'area', 'issue');
1173 COMMENT ON TYPE "delegation_scope" IS 'Scope for delegations: ''unit'', ''area'', or ''issue'' (order is relevant)';
1176 CREATE TABLE "delegation" (
1177 "id" SERIAL8 PRIMARY KEY,
1178 "truster_id" INT4 NOT NULL REFERENCES "member" ("id") ON DELETE CASCADE ON UPDATE CASCADE,
1179 "trustee_id" INT4 REFERENCES "member" ("id") ON DELETE RESTRICT ON UPDATE CASCADE,
1180 "scope" "delegation_scope" NOT NULL,
1181 "unit_id" INT4 REFERENCES "unit" ("id") ON DELETE CASCADE ON UPDATE CASCADE,
1182 "area_id" INT4 REFERENCES "area" ("id") ON DELETE CASCADE ON UPDATE CASCADE,
1183 "issue_id" INT4 REFERENCES "issue" ("id") ON DELETE CASCADE ON UPDATE CASCADE,
1184 CONSTRAINT "cant_delegate_to_yourself" CHECK ("truster_id" != "trustee_id"),
1185 CONSTRAINT "no_unit_delegation_to_null"
1186 CHECK ("trustee_id" NOTNULL OR "scope" != 'unit'),
1187 CONSTRAINT "area_id_and_issue_id_set_according_to_scope" CHECK (
1188 ("scope" = 'unit' AND "unit_id" NOTNULL AND "area_id" ISNULL AND "issue_id" ISNULL ) OR
1189 ("scope" = 'area' AND "unit_id" ISNULL AND "area_id" NOTNULL AND "issue_id" ISNULL ) OR
1190 ("scope" = 'issue' AND "unit_id" ISNULL AND "area_id" ISNULL AND "issue_id" NOTNULL) ),
1191 UNIQUE ("unit_id", "truster_id"),
1192 UNIQUE ("area_id", "truster_id"),
1193 UNIQUE ("issue_id", "truster_id") );
1194 CREATE INDEX "delegation_truster_id_idx" ON "delegation" ("truster_id");
1195 CREATE INDEX "delegation_trustee_id_idx" ON "delegation" ("trustee_id");
1197 COMMENT ON TABLE "delegation" IS 'Delegation of vote-weight to other members';
1199 COMMENT ON COLUMN "delegation"."unit_id" IS 'Reference to unit, if delegation is unit-wide, otherwise NULL';
1200 COMMENT ON COLUMN "delegation"."area_id" IS 'Reference to area, if delegation is area-wide, otherwise NULL';
1201 COMMENT ON COLUMN "delegation"."issue_id" IS 'Reference to issue, if delegation is issue-wide, otherwise NULL';
1204 CREATE TABLE "snapshot_issue" (
1205 PRIMARY KEY ("snapshot_id", "issue_id"),
1206 "snapshot_id" INT8 REFERENCES "snapshot" ("id") ON DELETE CASCADE ON UPDATE CASCADE,
1207 "issue_id" INT4 REFERENCES "issue" ("id") ON DELETE CASCADE ON UPDATE CASCADE ); -- NOTE: trigger "delete_snapshot_on_partial_delete" will delete whole "snapshot"
1208 CREATE INDEX "snapshot_issue_issue_id_idx" ON "snapshot_issue" ("issue_id");
1210 COMMENT ON TABLE "snapshot_issue" IS 'List of issues included in a snapshot';
1212 COMMENT ON COLUMN "snapshot_issue"."issue_id" IS 'Issue being part of the snapshot; Trigger "delete_snapshot_on_partial_delete" on "snapshot_issue" table will delete snapshot if an issue of the snapshot is deleted.';
1215 CREATE TABLE "direct_interest_snapshot" (
1216 PRIMARY KEY ("snapshot_id", "issue_id", "member_id"),
1217 "snapshot_id" INT8,
1218 "issue_id" INT4,
1219 FOREIGN KEY ("snapshot_id", "issue_id")
1220 REFERENCES "snapshot_issue" ("snapshot_id", "issue_id") ON DELETE CASCADE ON UPDATE CASCADE,
1221 "member_id" INT4 REFERENCES "member" ("id") ON DELETE RESTRICT ON UPDATE RESTRICT,
1222 "weight" INT4 );
1223 CREATE INDEX "direct_interest_snapshot_member_id_idx" ON "direct_interest_snapshot" ("member_id");
1225 COMMENT ON TABLE "direct_interest_snapshot" IS 'Snapshot of active members having an "interest" in the "issue"; for corrections refer to column "issue_notice" of "issue" table';
1227 COMMENT ON COLUMN "direct_interest_snapshot"."weight" IS 'Weight of member (1 or higher) according to "delegating_interest_snapshot"';
1230 CREATE TABLE "delegating_interest_snapshot" (
1231 PRIMARY KEY ("snapshot_id", "issue_id", "member_id"),
1232 "snapshot_id" INT8,
1233 "issue_id" INT4,
1234 FOREIGN KEY ("snapshot_id", "issue_id")
1235 REFERENCES "snapshot_issue" ("snapshot_id", "issue_id") ON DELETE CASCADE ON UPDATE CASCADE,
1236 "member_id" INT4 REFERENCES "member" ("id") ON DELETE RESTRICT ON UPDATE RESTRICT,
1237 "weight" INT4,
1238 "scope" "delegation_scope" NOT NULL,
1239 "delegate_member_ids" INT4[] NOT NULL );
1240 CREATE INDEX "delegating_interest_snapshot_member_id_idx" ON "delegating_interest_snapshot" ("member_id");
1242 COMMENT ON TABLE "delegating_interest_snapshot" IS 'Delegations increasing the weight of entries in the "direct_interest_snapshot" table; for corrections refer to column "issue_notice" of "issue" table';
1244 COMMENT ON COLUMN "delegating_interest_snapshot"."member_id" IS 'Delegating member';
1245 COMMENT ON COLUMN "delegating_interest_snapshot"."weight" IS 'Intermediate weight';
1246 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"';
1249 CREATE TABLE "direct_supporter_snapshot" (
1250 PRIMARY KEY ("snapshot_id", "initiative_id", "member_id"),
1251 "snapshot_id" INT8,
1252 "issue_id" INT4 NOT NULL,
1253 FOREIGN KEY ("snapshot_id", "issue_id")
1254 REFERENCES "snapshot_issue" ("snapshot_id", "issue_id") ON DELETE CASCADE ON UPDATE CASCADE,
1255 "initiative_id" INT4,
1256 "member_id" INT4 REFERENCES "member" ("id") ON DELETE RESTRICT ON UPDATE RESTRICT,
1257 "draft_id" INT8 NOT NULL,
1258 "informed" BOOLEAN NOT NULL,
1259 "satisfied" BOOLEAN NOT NULL,
1260 FOREIGN KEY ("issue_id", "initiative_id") REFERENCES "initiative" ("issue_id", "id") ON DELETE CASCADE ON UPDATE CASCADE,
1261 FOREIGN KEY ("initiative_id", "draft_id") REFERENCES "draft" ("initiative_id", "id") ON DELETE NO ACTION ON UPDATE CASCADE,
1262 FOREIGN KEY ("snapshot_id", "issue_id", "member_id") REFERENCES "direct_interest_snapshot" ("snapshot_id", "issue_id", "member_id") ON DELETE CASCADE ON UPDATE CASCADE );
1263 CREATE INDEX "direct_supporter_snapshot_member_id_idx" ON "direct_supporter_snapshot" ("member_id");
1265 COMMENT ON TABLE "direct_supporter_snapshot" IS 'Snapshot of supporters of initiatives (weight is stored in "direct_interest_snapshot"); for corrections refer to column "issue_notice" of "issue" table';
1267 COMMENT ON COLUMN "direct_supporter_snapshot"."issue_id" IS 'WARNING: No index: For selections use column "initiative_id" and join via table "initiative" where neccessary';
1268 COMMENT ON COLUMN "direct_supporter_snapshot"."informed" IS 'Supporter has seen the latest draft of the initiative';
1269 COMMENT ON COLUMN "direct_supporter_snapshot"."satisfied" IS 'Supporter has no "critical_opinion"s';
1272 CREATE TABLE "non_voter" (
1273 PRIMARY KEY ("member_id", "issue_id"),
1274 "member_id" INT4 REFERENCES "member" ("id") ON DELETE CASCADE ON UPDATE CASCADE,
1275 "issue_id" INT4 REFERENCES "issue" ("id") ON DELETE CASCADE ON UPDATE CASCADE );
1276 CREATE INDEX "non_voter_issue_id_idx" ON "non_voter" ("issue_id");
1278 COMMENT ON TABLE "non_voter" IS 'Members who decided to not vote directly on an issue';
1281 CREATE TABLE "direct_voter" (
1282 PRIMARY KEY ("issue_id", "member_id"),
1283 "issue_id" INT4 REFERENCES "issue" ("id") ON DELETE CASCADE ON UPDATE CASCADE,
1284 "member_id" INT4 REFERENCES "member" ("id") ON DELETE RESTRICT ON UPDATE RESTRICT,
1285 "weight" INT4,
1286 "comment_changed" TIMESTAMPTZ,
1287 "formatting_engine" TEXT,
1288 "comment" TEXT ); -- full text index
1289 CREATE INDEX "direct_voter_member_id_idx" ON "direct_voter" ("member_id");
1291 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; for corrections refer to column "issue_notice" of "issue" table';
1293 COMMENT ON COLUMN "direct_voter"."weight" IS 'Weight of member (1 or higher) according to "delegating_voter" table';
1294 COMMENT ON COLUMN "direct_voter"."comment_changed" IS 'Shall be set on comment change, to indicate a comment being modified after voting has been finished; Automatically set to NULL after voting phase; Automatically set to NULL by trigger, if "comment" is set to NULL';
1295 COMMENT ON COLUMN "direct_voter"."formatting_engine" IS 'Allows different formatting engines (i.e. wiki formats) to be used for "direct_voter"."comment"; Automatically set to NULL by trigger, if "comment" is set to NULL';
1296 COMMENT ON COLUMN "direct_voter"."comment" IS 'Is to be set or updated by the frontend, if comment was inserted or updated AFTER the issue has been closed. Otherwise it shall be set to NULL.';
1299 CREATE TABLE "rendered_voter_comment" (
1300 PRIMARY KEY ("issue_id", "member_id", "format"),
1301 FOREIGN KEY ("issue_id", "member_id")
1302 REFERENCES "direct_voter" ("issue_id", "member_id")
1303 ON DELETE CASCADE ON UPDATE CASCADE,
1304 "issue_id" INT4,
1305 "member_id" INT4,
1306 "format" TEXT,
1307 "content" TEXT NOT NULL );
1309 COMMENT ON TABLE "rendered_voter_comment" IS 'This table may be used by frontends to cache "rendered" voter comments (e.g. HTML output generated from wiki text)';
1312 CREATE TABLE "delegating_voter" (
1313 PRIMARY KEY ("issue_id", "member_id"),
1314 "issue_id" INT4 REFERENCES "issue" ("id") ON DELETE CASCADE ON UPDATE CASCADE,
1315 "member_id" INT4 REFERENCES "member" ("id") ON DELETE RESTRICT ON UPDATE RESTRICT,
1316 "weight" INT4,
1317 "scope" "delegation_scope" NOT NULL,
1318 "delegate_member_ids" INT4[] NOT NULL );
1319 CREATE INDEX "delegating_voter_member_id_idx" ON "delegating_voter" ("member_id");
1321 COMMENT ON TABLE "delegating_voter" IS 'Delegations increasing the weight of entries in the "direct_voter" table; for corrections refer to column "issue_notice" of "issue" table';
1323 COMMENT ON COLUMN "delegating_voter"."member_id" IS 'Delegating member';
1324 COMMENT ON COLUMN "delegating_voter"."weight" IS 'Intermediate weight';
1325 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"';
1328 CREATE TABLE "vote" (
1329 "issue_id" INT4 NOT NULL,
1330 PRIMARY KEY ("initiative_id", "member_id"),
1331 "initiative_id" INT4,
1332 "member_id" INT4,
1333 "grade" INT4 NOT NULL,
1334 "first_preference" BOOLEAN,
1335 FOREIGN KEY ("issue_id", "initiative_id") REFERENCES "initiative" ("issue_id", "id") ON DELETE CASCADE ON UPDATE CASCADE,
1336 FOREIGN KEY ("issue_id", "member_id") REFERENCES "direct_voter" ("issue_id", "member_id") ON DELETE CASCADE ON UPDATE CASCADE,
1337 CONSTRAINT "first_preference_flag_only_set_on_positive_grades"
1338 CHECK ("grade" > 0 OR "first_preference" ISNULL) );
1339 CREATE INDEX "vote_member_id_idx" ON "vote" ("member_id");
1341 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; for corrections refer to column "issue_notice" of "issue" table';
1343 COMMENT ON COLUMN "vote"."issue_id" IS 'WARNING: No index: For selections use column "initiative_id" and join via table "initiative" where neccessary';
1344 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.';
1345 COMMENT ON COLUMN "vote"."first_preference" IS 'Value is automatically set after voting is finished. For positive grades, this value is set to true for the highest (i.e. best) grade.';
1348 CREATE TABLE "posting" (
1349 UNIQUE ("author_id", "id"), -- index needed for foreign-key on table "posting_lexeme"
1350 "id" SERIAL8 PRIMARY KEY,
1351 "author_id" INT4 NOT NULL REFERENCES "member" ("id") ON DELETE RESTRICT ON UPDATE CASCADE,
1352 "created" TIMESTAMPTZ NOT NULL DEFAULT now(),
1353 "message" TEXT NOT NULL,
1354 "unit_id" INT4 REFERENCES "unit" ("id") ON DELETE CASCADE ON UPDATE CASCADE,
1355 "area_id" INT4,
1356 FOREIGN KEY ("unit_id", "area_id") REFERENCES "area" ("unit_id", "id") ON DELETE CASCADE ON UPDATE CASCADE,
1357 "policy_id" INT4 REFERENCES "policy" ("id") ON DELETE CASCADE ON UPDATE CASCADE,
1358 "issue_id" INT4 REFERENCES "issue" ("id") ON DELETE CASCADE ON UPDATE CASCADE,
1359 FOREIGN KEY ("area_id", "issue_id") REFERENCES "issue" ("area_id", "id") ON DELETE CASCADE ON UPDATE CASCADE,
1360 FOREIGN KEY ("policy_id", "issue_id") REFERENCES "issue" ("policy_id", "id") ON DELETE CASCADE ON UPDATE CASCADE,
1361 "initiative_id" INT4,
1362 "suggestion_id" INT8,
1363 -- NOTE: no referential integrity for suggestions because those are
1364 -- actually deleted
1365 -- FOREIGN KEY ("initiative_id", "suggestion_id")
1366 -- REFERENCES "suggestion" ("initiative_id", "id")
1367 -- ON DELETE CASCADE ON UPDATE CASCADE,
1368 CONSTRAINT "area_requires_unit" CHECK (
1369 "area_id" ISNULL OR "unit_id" NOTNULL ),
1370 CONSTRAINT "policy_set_when_issue_set" CHECK (
1371 ("policy_id" NOTNULL) = ("issue_id" NOTNULL) ),
1372 CONSTRAINT "issue_requires_area" CHECK (
1373 "issue_id" ISNULL OR "area_id" NOTNULL ),
1374 CONSTRAINT "initiative_requires_issue" CHECK (
1375 "initiative_id" ISNULL OR "issue_id" NOTNULL ),
1376 CONSTRAINT "suggestion_requires_initiative" CHECK (
1377 "suggestion_id" ISNULL OR "initiative_id" NOTNULL ) );
1378 CREATE INDEX "posting_global_idx" ON "posting" USING gist ((pstamp("author_id", "id")));
1379 CREATE INDEX "posting_unit_idx" ON "posting" USING gist ("unit_id", (pstamp("author_id", "id"))) WHERE "unit_id" NOTNULL;
1380 CREATE INDEX "posting_area_idx" ON "posting" USING gist ("area_id", (pstamp("author_id", "id"))) WHERE "area_id" NOTNULL;
1381 CREATE INDEX "posting_policy_idx" ON "posting" USING gist ("policy_id", (pstamp("author_id", "id"))) WHERE "policy_id" NOTNULL;
1382 CREATE INDEX "posting_issue_idx" ON "posting" USING gist ("issue_id", (pstamp("author_id", "id"))) WHERE "issue_id" NOTNULL;
1383 CREATE INDEX "posting_initiative_idx" ON "posting" USING gist ("initiative_id", (pstamp("author_id", "id"))) WHERE "initiative_id" NOTNULL;
1384 CREATE INDEX "posting_suggestion_idx" ON "posting" USING gist ("suggestion_id", (pstamp("author_id", "id"))) WHERE "suggestion_id" NOTNULL;
1386 COMMENT ON TABLE "posting" IS 'Text postings of members; a text posting may optionally be associated to a unit, area, policy, issue, initiative, or suggestion';
1389 CREATE TABLE "posting_lexeme" (
1390 PRIMARY KEY ("posting_id", "lexeme"),
1391 FOREIGN KEY ("posting_id", "author_id") REFERENCES "posting" ("id", "author_id") ON DELETE CASCADE ON UPDATE CASCADE,
1392 "posting_id" INT8,
1393 "lexeme" TEXT,
1394 "author_id" INT4 );
1395 CREATE INDEX "posting_lexeme_idx" ON "posting_lexeme" USING gist ("lexeme", (pstamp("author_id", "posting_id")));
1397 COMMENT ON TABLE "posting_lexeme" IS 'Helper table to allow searches for hashtags.';
1400 CREATE TYPE "event_type" AS ENUM (
1401 'unit_created',
1402 'unit_updated',
1403 'area_created',
1404 'area_updated',
1405 'policy_created',
1406 'policy_updated',
1407 'issue_state_changed',
1408 'initiative_created_in_new_issue',
1409 'initiative_created_in_existing_issue',
1410 'initiative_revoked',
1411 'new_draft_created',
1412 'suggestion_created',
1413 'suggestion_deleted',
1414 'member_activated',
1415 'member_deleted',
1416 'member_active',
1417 'member_name_updated',
1418 'member_profile_updated',
1419 'member_image_updated',
1420 'interest',
1421 'initiator',
1422 'support',
1423 'support_updated',
1424 'suggestion_rated',
1425 'delegation',
1426 'contact',
1427 'posting_created' );
1429 COMMENT ON TYPE "event_type" IS 'Type used for column "event" of table "event"';
1432 CREATE TABLE "event" (
1433 "id" SERIAL8 PRIMARY KEY,
1434 "occurrence" TIMESTAMPTZ NOT NULL DEFAULT now(),
1435 "event" "event_type" NOT NULL,
1436 "posting_id" INT8 REFERENCES "posting" ("id") ON DELETE RESTRICT ON UPDATE CASCADE,
1437 "member_id" INT4 REFERENCES "member" ("id") ON DELETE RESTRICT ON UPDATE CASCADE,
1438 "other_member_id" INT4 REFERENCES "member" ("id") ON DELETE RESTRICT ON UPDATE CASCADE,
1439 "scope" "delegation_scope",
1440 "unit_id" INT4 REFERENCES "unit" ("id") ON DELETE CASCADE ON UPDATE CASCADE,
1441 "area_id" INT4,
1442 FOREIGN KEY ("unit_id", "area_id") REFERENCES "area" ("unit_id", "id") ON DELETE CASCADE ON UPDATE CASCADE,
1443 "policy_id" INT4 REFERENCES "policy" ("id") ON DELETE CASCADE ON UPDATE CASCADE,
1444 "issue_id" INT4 REFERENCES "issue" ("id") ON DELETE CASCADE ON UPDATE CASCADE,
1445 FOREIGN KEY ("area_id", "issue_id") REFERENCES "issue" ("area_id", "id") ON DELETE CASCADE ON UPDATE CASCADE,
1446 FOREIGN KEY ("policy_id", "issue_id") REFERENCES "issue" ("policy_id", "id") ON DELETE CASCADE ON UPDATE CASCADE,
1447 "state" "issue_state",
1448 "initiative_id" INT4,
1449 "draft_id" INT8,
1450 "suggestion_id" INT8,
1451 "boolean_value" BOOLEAN,
1452 "numeric_value" INT4,
1453 "text_value" TEXT,
1454 "old_text_value" TEXT,
1455 FOREIGN KEY ("issue_id", "initiative_id")
1456 REFERENCES "initiative" ("issue_id", "id")
1457 ON DELETE CASCADE ON UPDATE CASCADE,
1458 FOREIGN KEY ("initiative_id", "draft_id")
1459 REFERENCES "draft" ("initiative_id", "id")
1460 ON DELETE CASCADE ON UPDATE CASCADE,
1461 -- NOTE: no referential integrity for suggestions because those are
1462 -- actually deleted
1463 -- FOREIGN KEY ("initiative_id", "suggestion_id")
1464 -- REFERENCES "suggestion" ("initiative_id", "id")
1465 -- ON DELETE CASCADE ON UPDATE CASCADE,
1466 CONSTRAINT "constr_for_issue_state_changed" CHECK (
1467 "event" != 'issue_state_changed' OR (
1468 "posting_id" ISNULL AND
1469 "member_id" ISNULL AND
1470 "other_member_id" ISNULL AND
1471 "scope" ISNULL AND
1472 "unit_id" NOTNULL AND
1473 "area_id" NOTNULL AND
1474 "policy_id" NOTNULL AND
1475 "issue_id" NOTNULL AND
1476 "state" NOTNULL AND
1477 "initiative_id" ISNULL AND
1478 "draft_id" ISNULL AND
1479 "suggestion_id" ISNULL AND
1480 "boolean_value" ISNULL AND
1481 "numeric_value" ISNULL AND
1482 "text_value" ISNULL AND
1483 "old_text_value" ISNULL )),
1484 CONSTRAINT "constr_for_initiative_creation_or_revocation_or_new_draft" CHECK (
1485 "event" NOT IN (
1486 'initiative_created_in_new_issue',
1487 'initiative_created_in_existing_issue',
1488 'initiative_revoked',
1489 'new_draft_created'
1490 ) OR (
1491 "posting_id" ISNULL AND
1492 "member_id" NOTNULL AND
1493 "other_member_id" ISNULL AND
1494 "scope" ISNULL AND
1495 "unit_id" NOTNULL AND
1496 "area_id" NOTNULL AND
1497 "policy_id" NOTNULL AND
1498 "issue_id" NOTNULL AND
1499 "state" NOTNULL AND
1500 "initiative_id" NOTNULL AND
1501 "draft_id" NOTNULL AND
1502 "suggestion_id" ISNULL AND
1503 "boolean_value" ISNULL AND
1504 "numeric_value" ISNULL AND
1505 "text_value" ISNULL AND
1506 "old_text_value" ISNULL )),
1507 CONSTRAINT "constr_for_suggestion_creation" CHECK (
1508 "event" != 'suggestion_created' OR (
1509 "posting_id" ISNULL AND
1510 "member_id" NOTNULL AND
1511 "other_member_id" ISNULL AND
1512 "scope" ISNULL AND
1513 "unit_id" NOTNULL AND
1514 "area_id" NOTNULL AND
1515 "policy_id" NOTNULL AND
1516 "issue_id" NOTNULL AND
1517 "state" NOTNULL AND
1518 "initiative_id" NOTNULL AND
1519 "draft_id" ISNULL AND
1520 "suggestion_id" NOTNULL AND
1521 "boolean_value" ISNULL AND
1522 "numeric_value" ISNULL AND
1523 "text_value" ISNULL AND
1524 "old_text_value" ISNULL )),
1525 CONSTRAINT "constr_for_suggestion_removal" CHECK (
1526 "event" != 'suggestion_deleted' OR (
1527 "posting_id" ISNULL AND
1528 "member_id" ISNULL AND
1529 "other_member_id" ISNULL AND
1530 "scope" ISNULL AND
1531 "unit_id" NOTNULL AND
1532 "area_id" NOTNULL AND
1533 "policy_id" NOTNULL AND
1534 "issue_id" NOTNULL AND
1535 "state" NOTNULL AND
1536 "initiative_id" NOTNULL AND
1537 "draft_id" ISNULL AND
1538 "suggestion_id" NOTNULL AND
1539 "boolean_value" ISNULL AND
1540 "numeric_value" ISNULL AND
1541 "text_value" ISNULL AND
1542 "old_text_value" ISNULL )),
1543 CONSTRAINT "constr_for_value_less_member_event" CHECK (
1544 "event" NOT IN (
1545 'member_activated',
1546 'member_deleted',
1547 'member_profile_updated',
1548 'member_image_updated'
1549 ) OR (
1550 "posting_id" ISNULL AND
1551 "member_id" NOTNULL AND
1552 "other_member_id" ISNULL AND
1553 "scope" ISNULL AND
1554 "unit_id" ISNULL AND
1555 "area_id" ISNULL AND
1556 "policy_id" ISNULL AND
1557 "issue_id" ISNULL AND
1558 "state" ISNULL AND
1559 "initiative_id" ISNULL AND
1560 "draft_id" ISNULL AND
1561 "suggestion_id" ISNULL AND
1562 "boolean_value" ISNULL AND
1563 "numeric_value" ISNULL AND
1564 "text_value" ISNULL AND
1565 "old_text_value" ISNULL )),
1566 CONSTRAINT "constr_for_member_active" CHECK (
1567 "event" != 'member_active' OR (
1568 "posting_id" ISNULL AND
1569 "member_id" NOTNULL AND
1570 "other_member_id" ISNULL AND
1571 "scope" ISNULL AND
1572 "unit_id" ISNULL AND
1573 "area_id" ISNULL AND
1574 "policy_id" ISNULL AND
1575 "issue_id" ISNULL AND
1576 "state" ISNULL AND
1577 "initiative_id" ISNULL AND
1578 "draft_id" ISNULL AND
1579 "suggestion_id" ISNULL AND
1580 "boolean_value" NOTNULL AND
1581 "numeric_value" ISNULL AND
1582 "text_value" ISNULL AND
1583 "old_text_value" ISNULL )),
1584 CONSTRAINT "constr_for_member_name_updated" CHECK (
1585 "event" != 'member_name_updated' OR (
1586 "posting_id" ISNULL AND
1587 "member_id" NOTNULL AND
1588 "other_member_id" ISNULL AND
1589 "scope" ISNULL AND
1590 "unit_id" ISNULL AND
1591 "area_id" ISNULL AND
1592 "policy_id" ISNULL AND
1593 "issue_id" ISNULL AND
1594 "state" ISNULL AND
1595 "initiative_id" ISNULL AND
1596 "draft_id" ISNULL AND
1597 "suggestion_id" ISNULL AND
1598 "boolean_value" ISNULL AND
1599 "numeric_value" ISNULL AND
1600 "text_value" NOTNULL AND
1601 "old_text_value" NOTNULL )),
1602 CONSTRAINT "constr_for_interest" CHECK (
1603 "event" != 'interest' OR (
1604 "posting_id" ISNULL AND
1605 "member_id" NOTNULL AND
1606 "other_member_id" ISNULL AND
1607 "scope" ISNULL AND
1608 "unit_id" NOTNULL AND
1609 "area_id" NOTNULL AND
1610 "policy_id" NOTNULL AND
1611 "issue_id" NOTNULL AND
1612 "state" NOTNULL AND
1613 "initiative_id" ISNULL AND
1614 "draft_id" ISNULL AND
1615 "suggestion_id" ISNULL AND
1616 "boolean_value" NOTNULL AND
1617 "numeric_value" ISNULL AND
1618 "text_value" ISNULL AND
1619 "old_text_value" ISNULL )),
1620 CONSTRAINT "constr_for_initiator" CHECK (
1621 "event" != 'initiator' OR (
1622 "posting_id" ISNULL AND
1623 "member_id" NOTNULL AND
1624 "other_member_id" ISNULL AND
1625 "scope" ISNULL AND
1626 "unit_id" NOTNULL AND
1627 "area_id" NOTNULL AND
1628 "policy_id" NOTNULL AND
1629 "issue_id" NOTNULL AND
1630 "state" NOTNULL AND
1631 "initiative_id" NOTNULL AND
1632 "draft_id" ISNULL AND
1633 "suggestion_id" ISNULL AND
1634 "boolean_value" NOTNULL AND
1635 "numeric_value" ISNULL AND
1636 "text_value" ISNULL AND
1637 "old_text_value" ISNULL )),
1638 CONSTRAINT "constr_for_support" CHECK (
1639 "event" != 'support' OR (
1640 "posting_id" ISNULL AND
1641 "member_id" NOTNULL AND
1642 "other_member_id" ISNULL AND
1643 "scope" ISNULL AND
1644 "unit_id" NOTNULL AND
1645 "area_id" NOTNULL AND
1646 "policy_id" NOTNULL AND
1647 "issue_id" NOTNULL AND
1648 "state" NOTNULL AND
1649 "initiative_id" NOTNULL AND
1650 ("draft_id" NOTNULL) = ("boolean_value" = TRUE) AND
1651 "suggestion_id" ISNULL AND
1652 "boolean_value" NOTNULL AND
1653 "numeric_value" ISNULL AND
1654 "text_value" ISNULL AND
1655 "old_text_value" ISNULL )),
1656 CONSTRAINT "constr_for_support_updated" CHECK (
1657 "event" != 'support_updated' OR (
1658 "posting_id" ISNULL AND
1659 "member_id" NOTNULL AND
1660 "other_member_id" ISNULL AND
1661 "scope" ISNULL AND
1662 "unit_id" NOTNULL AND
1663 "area_id" NOTNULL AND
1664 "policy_id" NOTNULL AND
1665 "issue_id" NOTNULL AND
1666 "state" NOTNULL AND
1667 "initiative_id" NOTNULL AND
1668 "draft_id" NOTNULL AND
1669 "suggestion_id" ISNULL AND
1670 "boolean_value" ISNULL AND
1671 "numeric_value" ISNULL AND
1672 "text_value" ISNULL AND
1673 "old_text_value" ISNULL )),
1674 CONSTRAINT "constr_for_suggestion_rated" CHECK (
1675 "event" != 'suggestion_rated' OR (
1676 "posting_id" ISNULL AND
1677 "member_id" NOTNULL AND
1678 "other_member_id" ISNULL AND
1679 "scope" ISNULL AND
1680 "unit_id" NOTNULL AND
1681 "area_id" NOTNULL AND
1682 "policy_id" NOTNULL AND
1683 "issue_id" NOTNULL AND
1684 "state" NOTNULL AND
1685 "initiative_id" NOTNULL AND
1686 "draft_id" ISNULL AND
1687 "suggestion_id" NOTNULL AND
1688 ("boolean_value" NOTNULL) = ("numeric_value" != 0) AND
1689 "numeric_value" NOTNULL AND
1690 "numeric_value" IN (-2, -1, 0, 1, 2) AND
1691 "text_value" ISNULL AND
1692 "old_text_value" ISNULL )),
1693 CONSTRAINT "constr_for_delegation" CHECK (
1694 "event" != 'delegation' OR (
1695 "posting_id" ISNULL AND
1696 "member_id" NOTNULL AND
1697 (("other_member_id" ISNULL) OR ("boolean_value" = TRUE)) AND
1698 "scope" NOTNULL AND
1699 "unit_id" NOTNULL AND
1700 ("area_id" NOTNULL) = ("scope" != 'unit'::"delegation_scope") AND
1701 "policy_id" ISNULL AND
1702 ("issue_id" NOTNULL) = ("scope" = 'issue'::"delegation_scope") AND
1703 ("state" NOTNULL) = ("scope" = 'issue'::"delegation_scope") AND
1704 "initiative_id" ISNULL AND
1705 "draft_id" ISNULL AND
1706 "suggestion_id" ISNULL AND
1707 "boolean_value" NOTNULL AND
1708 "numeric_value" ISNULL AND
1709 "text_value" ISNULL AND
1710 "old_text_value" ISNULL )),
1711 CONSTRAINT "constr_for_contact" CHECK (
1712 "event" != 'contact' OR (
1713 "posting_id" ISNULL AND
1714 "member_id" NOTNULL AND
1715 "other_member_id" NOTNULL AND
1716 "scope" ISNULL AND
1717 "unit_id" ISNULL AND
1718 "area_id" ISNULL AND
1719 "policy_id" ISNULL AND
1720 "issue_id" ISNULL AND
1721 "state" ISNULL AND
1722 "initiative_id" ISNULL AND
1723 "draft_id" ISNULL AND
1724 "suggestion_id" ISNULL AND
1725 "boolean_value" NOTNULL AND
1726 "numeric_value" ISNULL AND
1727 "text_value" ISNULL AND
1728 "old_text_value" ISNULL )),
1729 CONSTRAINT "constr_for_posting_created" CHECK (
1730 "event" != 'posting_created' OR (
1731 "posting_id" NOTNULL AND
1732 "member_id" NOTNULL AND
1733 "other_member_id" ISNULL AND
1734 "scope" ISNULL AND
1735 "state" ISNULL AND
1736 ("area_id" ISNULL OR "unit_id" NOTNULL) AND
1737 ("policy_id" NOTNULL) = ("issue_id" NOTNULL) AND
1738 ("issue_id" ISNULL OR "area_id" NOTNULL) AND
1739 ("state" NOTNULL) = ("issue_id" NOTNULL) AND
1740 ("initiative_id" ISNULL OR "issue_id" NOTNULL) AND
1741 "draft_id" ISNULL AND
1742 ("suggestion_id" ISNULL OR "initiative_id" NOTNULL) AND
1743 "boolean_value" ISNULL AND
1744 "numeric_value" ISNULL AND
1745 "text_value" ISNULL AND
1746 "old_text_value" ISNULL )) );
1747 CREATE INDEX "event_occurrence_idx" ON "event" ("occurrence");
1748 CREATE INDEX "event_tl_global_idx" ON "event" USING gist ((pstamp("member_id", "id")));
1749 CREATE INDEX "event_tl_unit_idx" ON "event" USING gist ("unit_id", (pstamp("member_id", "id"))) WHERE "unit_id" NOTNULL;
1750 CREATE INDEX "event_tl_area_idx" ON "event" USING gist ("area_id", (pstamp("member_id", "id"))) WHERE "area_id" NOTNULL;
1751 CREATE INDEX "event_tl_policy_idx" ON "event" USING gist ("policy_id", (pstamp("member_id", "id"))) WHERE "policy_id" NOTNULL;
1752 CREATE INDEX "event_tl_issue_idx" ON "event" USING gist ("issue_id", (pstamp("member_id", "id"))) WHERE "issue_id" NOTNULL;
1753 CREATE INDEX "event_tl_initiative_idx" ON "event" USING gist ("initiative_id", (pstamp("member_id", "id"))) WHERE "initiative_id" NOTNULL;
1754 CREATE INDEX "event_tl_suggestion_idx" ON "event" USING gist ("suggestion_id", (pstamp("member_id", "id"))) WHERE "suggestion_id" NOTNULL;
1757 COMMENT ON TABLE "event" IS 'Event table, automatically filled by triggers';
1759 COMMENT ON COLUMN "event"."occurrence" IS 'Point in time, when event occurred';
1760 COMMENT ON COLUMN "event"."event" IS 'Type of event (see TYPE "event_type")';
1761 COMMENT ON COLUMN "event"."member_id" IS 'Member who caused the event, if applicable';
1762 COMMENT ON COLUMN "event"."state" IS 'If issue_id is set: state of affected issue; If state changed: new state';
1765 CREATE TABLE "event_processed" (
1766 "event_id" INT8 NOT NULL );
1767 CREATE UNIQUE INDEX "event_processed_singleton_idx" ON "event_processed" ((1));
1769 COMMENT ON TABLE "event_processed" IS 'This table stores one row with the last event_id, for which event handlers have been executed (e.g. notifications having been sent out)';
1770 COMMENT ON INDEX "event_processed_singleton_idx" IS 'This index ensures that "event_processed" only contains one row maximum.';
1773 CREATE TABLE "notification_initiative_sent" (
1774 PRIMARY KEY ("member_id", "initiative_id"),
1775 "member_id" INT4 REFERENCES "member" ("id") ON DELETE CASCADE ON UPDATE CASCADE,
1776 "initiative_id" INT4 REFERENCES "initiative" ("id") ON DELETE CASCADE ON UPDATE CASCADE,
1777 "last_draft_id" INT8 NOT NULL,
1778 "last_suggestion_id" INT8 );
1779 CREATE INDEX "notification_initiative_sent_initiative_idx" ON "notification_initiative_sent" ("initiative_id");
1781 COMMENT ON TABLE "notification_initiative_sent" IS 'Information which initiatives have been promoted to a member in a scheduled notification mail';
1783 COMMENT ON COLUMN "notification_initiative_sent"."last_draft_id" IS 'Current (i.e. last) draft_id when initiative had been promoted';
1784 COMMENT ON COLUMN "notification_initiative_sent"."last_suggestion_id" IS 'Current (i.e. last) draft_id when initiative had been promoted';
1787 CREATE TABLE "newsletter" (
1788 "id" SERIAL4 PRIMARY KEY,
1789 "published" TIMESTAMPTZ NOT NULL,
1790 "unit_id" INT4 REFERENCES "unit" ("id") ON DELETE CASCADE ON UPDATE CASCADE,
1791 "include_all_members" BOOLEAN NOT NULL,
1792 "sent" TIMESTAMPTZ,
1793 "subject" TEXT NOT NULL,
1794 "content" TEXT NOT NULL );
1795 CREATE INDEX "newsletter_unit_id_idx" ON "newsletter" ("unit_id", "published");
1796 CREATE INDEX "newsletter_all_units_published_idx" ON "newsletter" ("published") WHERE "unit_id" ISNULL;
1797 CREATE INDEX "newsletter_published_idx" ON "newsletter" ("published");
1799 COMMENT ON TABLE "newsletter" IS 'Contains newsletters created by administrators to be sent out and for further reference';
1801 COMMENT ON COLUMN "newsletter"."published" IS 'Timestamp when the newsletter is to be sent out (and made available in the frontend)';
1802 COMMENT ON COLUMN "newsletter"."unit_id" IS 'If set, only members with voting right in the given unit are considered to be recipients';
1803 COMMENT ON COLUMN "newsletter"."include_all_members" IS 'TRUE = include all members regardless of their ''disable_notifications'' setting';
1804 COMMENT ON COLUMN "newsletter"."sent" IS 'Timestamp when the newsletter has been mailed out';
1805 COMMENT ON COLUMN "newsletter"."subject" IS 'Subject line (e.g. to be used for the email)';
1806 COMMENT ON COLUMN "newsletter"."content" IS 'Plain text content of the newsletter';
1810 ----------------------
1811 -- Full text search --
1812 ----------------------
1815 CREATE FUNCTION "highlight"
1816 ( "body_p" TEXT,
1817 "query_text_p" TEXT )
1818 RETURNS TEXT
1819 LANGUAGE 'plpgsql' IMMUTABLE AS $$
1820 BEGIN
1821 RETURN ts_headline(
1822 replace(replace("body_p", e'\\', e'\\\\'), '*', e'\\*'),
1823 "plainto_tsquery"("query_text_p"),
1824 'StartSel=* StopSel=* HighlightAll=TRUE' );
1825 END;
1826 $$;
1828 COMMENT ON FUNCTION "highlight"
1829 ( "body_p" TEXT,
1830 "query_text_p" TEXT )
1831 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.';
1834 CREATE FUNCTION "to_tsvector"("member") RETURNS TSVECTOR
1835 LANGUAGE SQL IMMUTABLE AS $$ SELECT to_tsvector(concat_ws(' ',
1836 $1."name",
1837 $1."identification"
1838 )) $$;
1839 CREATE INDEX "member_to_tsvector_idx" ON "member" USING gin
1840 (("to_tsvector"("member".*)));
1842 CREATE FUNCTION "to_tsvector"("member_profile") RETURNS TSVECTOR
1843 LANGUAGE SQL IMMUTABLE AS $$ SELECT to_tsvector(concat_ws(' ',
1844 $1."statement",
1845 $1."profile_text_data"
1846 )) $$;
1847 CREATE INDEX "member_profile_to_tsvector_idx" ON "member_profile" USING gin
1848 (("to_tsvector"("member_profile".*)));
1850 CREATE FUNCTION "to_tsvector"("unit") RETURNS TSVECTOR
1851 LANGUAGE SQL IMMUTABLE AS $$ SELECT to_tsvector(concat_ws(' ',
1852 $1."name",
1853 $1."description"
1854 )) $$;
1855 CREATE INDEX "unit_to_tsvector_idx" ON "unit" USING gin
1856 (("to_tsvector"("unit".*)));
1858 CREATE FUNCTION "to_tsvector"("area") RETURNS TSVECTOR
1859 LANGUAGE SQL IMMUTABLE AS $$ SELECT to_tsvector(concat_ws(' ',
1860 $1."name",
1861 $1."description"
1862 )) $$;
1863 CREATE INDEX "area_to_tsvector_idx" ON "area" USING gin
1864 (("to_tsvector"("area".*)));
1866 CREATE FUNCTION "to_tsvector"("initiative") RETURNS TSVECTOR
1867 LANGUAGE SQL IMMUTABLE AS $$ SELECT to_tsvector(concat_ws(' ',
1868 $1."name",
1869 $1."content"
1870 )) $$;
1871 CREATE INDEX "initiative_to_tsvector_idx" ON "initiative" USING gin
1872 (("to_tsvector"("initiative".*)));
1874 CREATE FUNCTION "to_tsvector"("draft") RETURNS TSVECTOR
1875 LANGUAGE SQL IMMUTABLE AS $$ SELECT to_tsvector(concat_ws(' ',
1876 $1."content"
1877 )) $$;
1878 CREATE INDEX "draft_to_tsvector_idx" ON "draft" USING gin
1879 (("to_tsvector"("draft".*)));
1881 CREATE FUNCTION "to_tsvector"("suggestion") RETURNS TSVECTOR
1882 LANGUAGE SQL IMMUTABLE AS $$ SELECT to_tsvector(concat_ws(' ',
1883 $1."name",
1884 $1."content"
1885 )) $$;
1886 CREATE INDEX "suggestion_to_tsvector_idx" ON "suggestion" USING gin
1887 (("to_tsvector"("suggestion".*)));
1889 CREATE FUNCTION "to_tsvector"("direct_voter") RETURNS TSVECTOR
1890 LANGUAGE SQL IMMUTABLE AS $$ SELECT to_tsvector(concat_ws(' ',
1891 $1."comment"
1892 )) $$;
1893 CREATE INDEX "direct_voter_to_tsvector_idx" ON "direct_voter" USING gin
1894 (("to_tsvector"("direct_voter".*)));
1897 CREATE FUNCTION "update_posting_lexeme_trigger"()
1898 RETURNS TRIGGER
1899 LANGUAGE 'plpgsql' VOLATILE AS $$
1900 DECLARE
1901 "lexeme_v" TEXT;
1902 BEGIN
1903 IF TG_OP = 'DELETE' OR TG_OP = 'UPDATE' THEN
1904 DELETE FROM "posting_lexeme" WHERE "posting_id" = OLD."id";
1905 END IF;
1906 IF TG_OP = 'INSERT' OR TG_OP = 'UPDATE' THEN
1907 FOR "lexeme_v" IN
1908 SELECT regexp_matches[1]
1909 FROM regexp_matches(NEW."message", '#[^\s.,;:]+')
1910 LOOP
1911 INSERT INTO "posting_lexeme" ("posting_id", "author_id", "lexeme")
1912 VALUES (
1913 NEW."id",
1914 NEW."author_id",
1915 "lexeme_v" )
1916 ON CONFLICT ("posting_id", "lexeme") DO NOTHING;
1917 END LOOP;
1918 END IF;
1919 RETURN NULL;
1920 END;
1921 $$;
1923 CREATE TRIGGER "update_posting_lexeme"
1924 AFTER INSERT OR UPDATE OR DELETE ON "posting"
1925 FOR EACH ROW EXECUTE PROCEDURE "update_posting_lexeme_trigger"();
1927 COMMENT ON FUNCTION "update_posting_lexeme_trigger"() IS 'Implementation of trigger "update_posting_lexeme" on table "posting"';
1928 COMMENT ON TRIGGER "update_posting_lexeme" ON "posting" IS 'Keeps table "posting_lexeme" up to date';
1932 ----------------------------------------------
1933 -- Writing of history entries and event log --
1934 ----------------------------------------------
1937 CREATE FUNCTION "write_member_history_trigger"()
1938 RETURNS TRIGGER
1939 LANGUAGE 'plpgsql' VOLATILE AS $$
1940 BEGIN
1941 IF
1942 ( NEW."active" != OLD."active" OR
1943 NEW."name" != OLD."name" ) AND
1944 OLD."activated" NOTNULL
1945 THEN
1946 INSERT INTO "member_history"
1947 ("member_id", "active", "name")
1948 VALUES (NEW."id", OLD."active", OLD."name");
1949 END IF;
1950 RETURN NULL;
1951 END;
1952 $$;
1954 CREATE TRIGGER "write_member_history"
1955 AFTER UPDATE ON "member" FOR EACH ROW EXECUTE PROCEDURE
1956 "write_member_history_trigger"();
1958 COMMENT ON FUNCTION "write_member_history_trigger"() IS 'Implementation of trigger "write_member_history" on table "member"';
1959 COMMENT ON TRIGGER "write_member_history" ON "member" IS 'When changing certain fields of a member, create a history entry in "member_history" table';
1962 CREATE FUNCTION "write_event_unit_trigger"()
1963 RETURNS TRIGGER
1964 LANGUAGE 'plpgsql' VOLATILE AS $$
1965 DECLARE
1966 "event_v" "event_type";
1967 BEGIN
1968 IF TG_OP = 'UPDATE' THEN
1969 IF OLD."active" = FALSE AND NEW."active" = FALSE THEN
1970 RETURN NULL;
1971 --ELSIF OLD."active" = FALSE AND NEW."active" = TRUE THEN
1972 -- "event_v" := 'unit_created';
1973 --ELSIF OLD."active" = TRUE AND NEW."active" = FALSE THEN
1974 -- "event_v" := 'unit_deleted';
1975 ELSIF OLD != NEW THEN
1976 "event_v" := 'unit_updated';
1977 ELSE
1978 RETURN NULL;
1979 END IF;
1980 ELSE
1981 "event_v" := 'unit_created';
1982 END IF;
1983 INSERT INTO "event" ("event", "unit_id") VALUES ("event_v", NEW."id");
1984 RETURN NULL;
1985 END;
1986 $$;
1988 CREATE TRIGGER "write_event_unit" AFTER INSERT OR UPDATE ON "unit"
1989 FOR EACH ROW EXECUTE PROCEDURE "write_event_unit_trigger"();
1991 COMMENT ON FUNCTION "write_event_unit_trigger"() IS 'Implementation of trigger "write_event_unit" on table "unit"';
1992 COMMENT ON TRIGGER "write_event_unit" ON "unit" IS 'Create entry in "event" table on new or changed/disabled units';
1995 CREATE FUNCTION "write_event_area_trigger"()
1996 RETURNS TRIGGER
1997 LANGUAGE 'plpgsql' VOLATILE AS $$
1998 DECLARE
1999 "event_v" "event_type";
2000 BEGIN
2001 IF TG_OP = 'UPDATE' THEN
2002 IF OLD."active" = FALSE AND NEW."active" = FALSE THEN
2003 RETURN NULL;
2004 --ELSIF OLD."active" = FALSE AND NEW."active" = TRUE THEN
2005 -- "event_v" := 'area_created';
2006 --ELSIF OLD."active" = TRUE AND NEW."active" = FALSE THEN
2007 -- "event_v" := 'area_deleted';
2008 ELSIF OLD != NEW THEN
2009 "event_v" := 'area_updated';
2010 ELSE
2011 RETURN NULL;
2012 END IF;
2013 ELSE
2014 "event_v" := 'area_created';
2015 END IF;
2016 INSERT INTO "event" ("event", "area_id") VALUES ("event_v", NEW."id");
2017 RETURN NULL;
2018 END;
2019 $$;
2021 CREATE TRIGGER "write_event_area" AFTER INSERT OR UPDATE ON "area"
2022 FOR EACH ROW EXECUTE PROCEDURE "write_event_area_trigger"();
2024 COMMENT ON FUNCTION "write_event_area_trigger"() IS 'Implementation of trigger "write_event_area" on table "area"';
2025 COMMENT ON TRIGGER "write_event_area" ON "area" IS 'Create entry in "event" table on new or changed/disabled areas';
2028 CREATE FUNCTION "write_event_policy_trigger"()
2029 RETURNS TRIGGER
2030 LANGUAGE 'plpgsql' VOLATILE AS $$
2031 DECLARE
2032 "event_v" "event_type";
2033 BEGIN
2034 IF TG_OP = 'UPDATE' THEN
2035 IF OLD."active" = FALSE AND NEW."active" = FALSE THEN
2036 RETURN NULL;
2037 --ELSIF OLD."active" = FALSE AND NEW."active" = TRUE THEN
2038 -- "event_v" := 'policy_created';
2039 --ELSIF OLD."active" = TRUE AND NEW."active" = FALSE THEN
2040 -- "event_v" := 'policy_deleted';
2041 ELSIF OLD != NEW THEN
2042 "event_v" := 'policy_updated';
2043 ELSE
2044 RETURN NULL;
2045 END IF;
2046 ELSE
2047 "event_v" := 'policy_created';
2048 END IF;
2049 INSERT INTO "event" ("event", "policy_id") VALUES ("event_v", NEW."id");
2050 RETURN NULL;
2051 END;
2052 $$;
2054 CREATE TRIGGER "write_event_policy" AFTER INSERT OR UPDATE ON "policy"
2055 FOR EACH ROW EXECUTE PROCEDURE "write_event_policy_trigger"();
2057 COMMENT ON FUNCTION "write_event_policy_trigger"() IS 'Implementation of trigger "write_event_policy" on table "policy"';
2058 COMMENT ON TRIGGER "write_event_policy" ON "policy" IS 'Create entry in "event" table on new or changed/disabled policies';
2061 CREATE FUNCTION "write_event_issue_state_changed_trigger"()
2062 RETURNS TRIGGER
2063 LANGUAGE 'plpgsql' VOLATILE AS $$
2064 DECLARE
2065 "area_row" "area"%ROWTYPE;
2066 BEGIN
2067 IF NEW."state" != OLD."state" THEN
2068 SELECT * INTO "area_row" FROM "area" WHERE "id" = NEW."area_id"
2069 FOR SHARE;
2070 INSERT INTO "event" (
2071 "event",
2072 "unit_id", "area_id", "policy_id", "issue_id", "state"
2073 ) VALUES (
2074 'issue_state_changed',
2075 "area_row"."unit_id", NEW."area_id", NEW."policy_id",
2076 NEW."id", NEW."state"
2077 );
2078 END IF;
2079 RETURN NULL;
2080 END;
2081 $$;
2083 CREATE TRIGGER "write_event_issue_state_changed"
2084 AFTER UPDATE ON "issue" FOR EACH ROW EXECUTE PROCEDURE
2085 "write_event_issue_state_changed_trigger"();
2087 COMMENT ON FUNCTION "write_event_issue_state_changed_trigger"() IS 'Implementation of trigger "write_event_issue_state_changed" on table "issue"';
2088 COMMENT ON TRIGGER "write_event_issue_state_changed" ON "issue" IS 'Create entry in "event" table on "state" change';
2091 CREATE FUNCTION "write_event_initiative_or_draft_created_trigger"()
2092 RETURNS TRIGGER
2093 LANGUAGE 'plpgsql' VOLATILE AS $$
2094 DECLARE
2095 "initiative_row" "initiative"%ROWTYPE;
2096 "issue_row" "issue"%ROWTYPE;
2097 "area_row" "area"%ROWTYPE;
2098 "event_v" "event_type";
2099 BEGIN
2100 SELECT * INTO "initiative_row" FROM "initiative"
2101 WHERE "id" = NEW."initiative_id" FOR SHARE;
2102 SELECT * INTO "issue_row" FROM "issue"
2103 WHERE "id" = "initiative_row"."issue_id" FOR SHARE;
2104 SELECT * INTO "area_row" FROM "area"
2105 WHERE "id" = "issue_row"."area_id" FOR SHARE;
2106 IF EXISTS (
2107 SELECT NULL FROM "draft"
2108 WHERE "initiative_id" = NEW."initiative_id" AND "id" != NEW."id"
2109 FOR SHARE
2110 ) THEN
2111 "event_v" := 'new_draft_created';
2112 ELSE
2113 IF EXISTS (
2114 SELECT NULL FROM "initiative"
2115 WHERE "issue_id" = "initiative_row"."issue_id"
2116 AND "id" != "initiative_row"."id"
2117 FOR SHARE
2118 ) THEN
2119 "event_v" := 'initiative_created_in_existing_issue';
2120 ELSE
2121 "event_v" := 'initiative_created_in_new_issue';
2122 END IF;
2123 END IF;
2124 INSERT INTO "event" (
2125 "event", "member_id",
2126 "unit_id", "area_id", "policy_id", "issue_id", "state",
2127 "initiative_id", "draft_id"
2128 ) VALUES (
2129 "event_v", NEW."author_id",
2130 "area_row"."unit_id", "issue_row"."area_id", "issue_row"."policy_id",
2131 "initiative_row"."issue_id", "issue_row"."state",
2132 NEW."initiative_id", NEW."id"
2133 );
2134 RETURN NULL;
2135 END;
2136 $$;
2138 CREATE TRIGGER "write_event_initiative_or_draft_created"
2139 AFTER INSERT ON "draft" FOR EACH ROW EXECUTE PROCEDURE
2140 "write_event_initiative_or_draft_created_trigger"();
2142 COMMENT ON FUNCTION "write_event_initiative_or_draft_created_trigger"() IS 'Implementation of trigger "write_event_initiative_or_draft_created" on table "issue"';
2143 COMMENT ON TRIGGER "write_event_initiative_or_draft_created" ON "draft" IS 'Create entry in "event" table on draft creation';
2146 CREATE FUNCTION "write_event_initiative_revoked_trigger"()
2147 RETURNS TRIGGER
2148 LANGUAGE 'plpgsql' VOLATILE AS $$
2149 DECLARE
2150 "issue_row" "issue"%ROWTYPE;
2151 "area_row" "area"%ROWTYPE;
2152 "draft_id_v" "draft"."id"%TYPE;
2153 BEGIN
2154 IF OLD."revoked" ISNULL AND NEW."revoked" NOTNULL THEN
2155 -- NOTE: lock for primary key update to avoid new drafts
2156 PERFORM NULL FROM "initiative" WHERE "id" = NEW."id" FOR UPDATE;
2157 SELECT * INTO "issue_row" FROM "issue"
2158 WHERE "id" = NEW."issue_id" FOR SHARE;
2159 SELECT * INTO "area_row" FROM "area"
2160 WHERE "id" = "issue_row"."area_id" FOR SHARE;
2161 -- NOTE: FOR SHARE cannot be used with DISTINCT in view "current_draft"
2162 PERFORM NULL FROM "draft" WHERE "initiative_id" = NEW."id" FOR SHARE;
2163 SELECT "id" INTO "draft_id_v" FROM "current_draft"
2164 WHERE "initiative_id" = NEW."id";
2165 INSERT INTO "event" (
2166 "event", "member_id",
2167 "unit_id", "area_id", "policy_id", "issue_id", "state",
2168 "initiative_id", "draft_id"
2169 ) VALUES (
2170 'initiative_revoked', NEW."revoked_by_member_id",
2171 "area_row"."unit_id", "issue_row"."area_id",
2172 "issue_row"."policy_id",
2173 NEW."issue_id", "issue_row"."state",
2174 NEW."id", "draft_id_v"
2175 );
2176 END IF;
2177 RETURN NULL;
2178 END;
2179 $$;
2181 CREATE TRIGGER "write_event_initiative_revoked"
2182 AFTER UPDATE ON "initiative" FOR EACH ROW EXECUTE PROCEDURE
2183 "write_event_initiative_revoked_trigger"();
2185 COMMENT ON FUNCTION "write_event_initiative_revoked_trigger"() IS 'Implementation of trigger "write_event_initiative_revoked" on table "issue"';
2186 COMMENT ON TRIGGER "write_event_initiative_revoked" ON "initiative" IS 'Create entry in "event" table, when an initiative is revoked';
2189 CREATE FUNCTION "write_event_suggestion_created_trigger"()
2190 RETURNS TRIGGER
2191 LANGUAGE 'plpgsql' VOLATILE AS $$
2192 DECLARE
2193 "initiative_row" "initiative"%ROWTYPE;
2194 "issue_row" "issue"%ROWTYPE;
2195 "area_row" "area"%ROWTYPE;
2196 BEGIN
2197 SELECT * INTO "initiative_row" FROM "initiative"
2198 WHERE "id" = NEW."initiative_id" FOR SHARE;
2199 SELECT * INTO "issue_row" FROM "issue"
2200 WHERE "id" = "initiative_row"."issue_id" FOR SHARE;
2201 SELECT * INTO "area_row" FROM "area"
2202 WHERE "id" = "issue_row"."area_id" FOR SHARE;
2203 INSERT INTO "event" (
2204 "event", "member_id",
2205 "unit_id", "area_id", "policy_id", "issue_id", "state",
2206 "initiative_id", "suggestion_id"
2207 ) VALUES (
2208 'suggestion_created', NEW."author_id",
2209 "area_row"."unit_id", "issue_row"."area_id", "issue_row"."policy_id",
2210 "initiative_row"."issue_id", "issue_row"."state",
2211 NEW."initiative_id", NEW."id"
2212 );
2213 RETURN NULL;
2214 END;
2215 $$;
2217 CREATE TRIGGER "write_event_suggestion_created"
2218 AFTER INSERT ON "suggestion" FOR EACH ROW EXECUTE PROCEDURE
2219 "write_event_suggestion_created_trigger"();
2221 COMMENT ON FUNCTION "write_event_suggestion_created_trigger"() IS 'Implementation of trigger "write_event_suggestion_created" on table "issue"';
2222 COMMENT ON TRIGGER "write_event_suggestion_created" ON "suggestion" IS 'Create entry in "event" table on suggestion creation';
2225 CREATE FUNCTION "write_event_suggestion_removed_trigger"()
2226 RETURNS TRIGGER
2227 LANGUAGE 'plpgsql' VOLATILE AS $$
2228 DECLARE
2229 "initiative_row" "initiative"%ROWTYPE;
2230 "issue_row" "issue"%ROWTYPE;
2231 "area_row" "area"%ROWTYPE;
2232 BEGIN
2233 SELECT * INTO "initiative_row" FROM "initiative"
2234 WHERE "id" = OLD."initiative_id" FOR SHARE;
2235 IF "initiative_row"."id" NOTNULL THEN
2236 SELECT * INTO "issue_row" FROM "issue"
2237 WHERE "id" = "initiative_row"."issue_id" FOR SHARE;
2238 SELECT * INTO "area_row" FROM "area"
2239 WHERE "id" = "issue_row"."area_id" FOR SHARE;
2240 INSERT INTO "event" (
2241 "event",
2242 "unit_id", "area_id", "policy_id", "issue_id", "state",
2243 "initiative_id", "suggestion_id"
2244 ) VALUES (
2245 'suggestion_deleted',
2246 "area_row"."unit_id", "issue_row"."area_id",
2247 "issue_row"."policy_id",
2248 "initiative_row"."issue_id", "issue_row"."state",
2249 OLD."initiative_id", OLD."id"
2250 );
2251 END IF;
2252 RETURN NULL;
2253 END;
2254 $$;
2256 CREATE TRIGGER "write_event_suggestion_removed"
2257 AFTER DELETE ON "suggestion" FOR EACH ROW EXECUTE PROCEDURE
2258 "write_event_suggestion_removed_trigger"();
2260 COMMENT ON FUNCTION "write_event_suggestion_removed_trigger"() IS 'Implementation of trigger "write_event_suggestion_removed" on table "issue"';
2261 COMMENT ON TRIGGER "write_event_suggestion_removed" ON "suggestion" IS 'Create entry in "event" table on suggestion creation';
2264 CREATE FUNCTION "write_event_member_trigger"()
2265 RETURNS TRIGGER
2266 LANGUAGE 'plpgsql' VOLATILE AS $$
2267 BEGIN
2268 IF TG_OP = 'INSERT' THEN
2269 IF NEW."activated" NOTNULL AND NEW."deleted" ISNULL THEN
2270 INSERT INTO "event" ("event", "member_id")
2271 VALUES ('member_activated', NEW."id");
2272 END IF;
2273 IF NEW."active" THEN
2274 INSERT INTO "event" ("event", "member_id", "boolean_value")
2275 VALUES ('member_active', NEW."id", TRUE);
2276 END IF;
2277 ELSIF TG_OP = 'UPDATE' THEN
2278 IF OLD."id" != NEW."id" THEN
2279 RAISE EXCEPTION 'Cannot change member ID';
2280 END IF;
2281 IF
2282 (OLD."activated" ISNULL OR OLD."deleted" NOTNULL) AND
2283 NEW."activated" NOTNULL AND NEW."deleted" ISNULL
2284 THEN
2285 INSERT INTO "event" ("event", "member_id")
2286 VALUES ('member_activated', NEW."id");
2287 END IF;
2288 IF OLD."active" != NEW."active" THEN
2289 INSERT INTO "event" ("event", "member_id", "boolean_value") VALUES (
2290 'member_active', NEW."id", NEW."active"
2291 );
2292 END IF;
2293 IF OLD."name" != NEW."name" THEN
2294 INSERT INTO "event" (
2295 "event", "member_id", "text_value", "old_text_value"
2296 ) VALUES (
2297 'member_name_updated', NEW."id", NEW."name", OLD."name"
2298 );
2299 END IF;
2300 IF
2301 OLD."activated" NOTNULL AND OLD."deleted" ISNULL AND
2302 (NEW."activated" ISNULL OR NEW."deleted" NOTNULL)
2303 THEN
2304 INSERT INTO "event" ("event", "member_id")
2305 VALUES ('member_deleted', NEW."id");
2306 END IF;
2307 END IF;
2308 RETURN NULL;
2309 END;
2310 $$;
2312 CREATE TRIGGER "write_event_member"
2313 AFTER INSERT OR UPDATE ON "member" FOR EACH ROW EXECUTE PROCEDURE
2314 "write_event_member_trigger"();
2316 COMMENT ON FUNCTION "write_event_member_trigger"() IS 'Implementation of trigger "write_event_member" on table "member"';
2317 COMMENT ON TRIGGER "write_event_member" ON "member" IS 'Create entries in "event" table on insertion to member table';
2320 CREATE FUNCTION "write_event_member_profile_updated_trigger"()
2321 RETURNS TRIGGER
2322 LANGUAGE 'plpgsql' VOLATILE AS $$
2323 BEGIN
2324 IF TG_OP = 'DELETE' OR TG_OP = 'UPDATE' THEN
2325 IF EXISTS (SELECT NULL FROM "member" WHERE "id" = OLD."member_id") THEN
2326 INSERT INTO "event" ("event", "member_id") VALUES (
2327 'member_profile_updated', OLD."member_id"
2328 );
2329 END IF;
2330 END IF;
2331 IF TG_OP = 'UPDATE' THEN
2332 IF OLD."member_id" = NEW."member_id" THEN
2333 RETURN NULL;
2334 END IF;
2335 END IF;
2336 IF TG_OP = 'INSERT' OR TG_OP = 'UPDATE' THEN
2337 INSERT INTO "event" ("event", "member_id") VALUES (
2338 'member_profile_updated', NEW."member_id"
2339 );
2340 END IF;
2341 RETURN NULL;
2342 END;
2343 $$;
2345 CREATE TRIGGER "write_event_member_profile_updated"
2346 AFTER INSERT OR UPDATE OR DELETE ON "member_profile"
2347 FOR EACH ROW EXECUTE PROCEDURE
2348 "write_event_member_profile_updated_trigger"();
2350 COMMENT ON FUNCTION "write_event_member_profile_updated_trigger"() IS 'Implementation of trigger "write_event_member_profile_updated" on table "member_profile"';
2351 COMMENT ON TRIGGER "write_event_member_profile_updated" ON "member_profile" IS 'Creates entries in "event" table on member profile update';
2354 CREATE FUNCTION "write_event_member_image_updated_trigger"()
2355 RETURNS TRIGGER
2356 LANGUAGE 'plpgsql' VOLATILE AS $$
2357 BEGIN
2358 IF TG_OP = 'DELETE' OR TG_OP = 'UPDATE' THEN
2359 IF NOT OLD."scaled" THEN
2360 IF EXISTS (SELECT NULL FROM "member" WHERE "id" = OLD."member_id") THEN
2361 INSERT INTO "event" ("event", "member_id") VALUES (
2362 'member_image_updated', OLD."member_id"
2363 );
2364 END IF;
2365 END IF;
2366 END IF;
2367 IF TG_OP = 'UPDATE' THEN
2368 IF
2369 OLD."member_id" = NEW."member_id" AND
2370 OLD."scaled" = NEW."scaled"
2371 THEN
2372 RETURN NULL;
2373 END IF;
2374 END IF;
2375 IF TG_OP = 'INSERT' OR TG_OP = 'UPDATE' THEN
2376 IF NOT NEW."scaled" THEN
2377 INSERT INTO "event" ("event", "member_id") VALUES (
2378 'member_image_updated', NEW."member_id"
2379 );
2380 END IF;
2381 END IF;
2382 RETURN NULL;
2383 END;
2384 $$;
2386 CREATE TRIGGER "write_event_member_image_updated"
2387 AFTER INSERT OR UPDATE OR DELETE ON "member_image"
2388 FOR EACH ROW EXECUTE PROCEDURE
2389 "write_event_member_image_updated_trigger"();
2391 COMMENT ON FUNCTION "write_event_member_image_updated_trigger"() IS 'Implementation of trigger "write_event_member_image_updated" on table "member_image"';
2392 COMMENT ON TRIGGER "write_event_member_image_updated" ON "member_image" IS 'Creates entries in "event" table on member image update';
2395 CREATE FUNCTION "write_event_interest_trigger"()
2396 RETURNS TRIGGER
2397 LANGUAGE 'plpgsql' VOLATILE AS $$
2398 DECLARE
2399 "issue_row" "issue"%ROWTYPE;
2400 "area_row" "area"%ROWTYPE;
2401 BEGIN
2402 IF TG_OP = 'UPDATE' THEN
2403 IF OLD = NEW THEN
2404 RETURN NULL;
2405 END IF;
2406 END IF;
2407 IF TG_OP = 'DELETE' OR TG_OP = 'UPDATE' THEN
2408 SELECT * INTO "issue_row" FROM "issue"
2409 WHERE "id" = OLD."issue_id" FOR SHARE;
2410 SELECT * INTO "area_row" FROM "area"
2411 WHERE "id" = "issue_row"."area_id" FOR SHARE;
2412 IF "issue_row"."id" NOTNULL THEN
2413 INSERT INTO "event" (
2414 "event", "member_id",
2415 "unit_id", "area_id", "policy_id", "issue_id", "state",
2416 "boolean_value"
2417 ) VALUES (
2418 'interest', OLD."member_id",
2419 "area_row"."unit_id", "issue_row"."area_id",
2420 "issue_row"."policy_id",
2421 OLD."issue_id", "issue_row"."state",
2422 FALSE
2423 );
2424 END IF;
2425 END IF;
2426 IF TG_OP = 'INSERT' OR TG_OP = 'UPDATE' THEN
2427 SELECT * INTO "issue_row" FROM "issue"
2428 WHERE "id" = NEW."issue_id" FOR SHARE;
2429 SELECT * INTO "area_row" FROM "area"
2430 WHERE "id" = "issue_row"."area_id" FOR SHARE;
2431 INSERT INTO "event" (
2432 "event", "member_id",
2433 "unit_id", "area_id", "policy_id", "issue_id", "state",
2434 "boolean_value"
2435 ) VALUES (
2436 'interest', NEW."member_id",
2437 "area_row"."unit_id", "issue_row"."area_id",
2438 "issue_row"."policy_id",
2439 NEW."issue_id", "issue_row"."state",
2440 TRUE
2441 );
2442 END IF;
2443 RETURN NULL;
2444 END;
2445 $$;
2447 CREATE TRIGGER "write_event_interest"
2448 AFTER INSERT OR UPDATE OR DELETE ON "interest" FOR EACH ROW EXECUTE PROCEDURE
2449 "write_event_interest_trigger"();
2451 COMMENT ON FUNCTION "write_event_interest_trigger"() IS 'Implementation of trigger "write_event_interest_inserted" on table "interest"';
2452 COMMENT ON TRIGGER "write_event_interest" ON "interest" IS 'Create entry in "event" table on adding or removing interest';
2455 CREATE FUNCTION "write_event_initiator_trigger"()
2456 RETURNS TRIGGER
2457 LANGUAGE 'plpgsql' VOLATILE AS $$
2458 DECLARE
2459 "initiative_row" "initiative"%ROWTYPE;
2460 "issue_row" "issue"%ROWTYPE;
2461 "area_row" "area"%ROWTYPE;
2462 "accepted_v" BOOLEAN = FALSE;
2463 "rejected_v" BOOLEAN = FALSE;
2464 BEGIN
2465 IF TG_OP = 'UPDATE' THEN
2466 IF
2467 OLD."initiative_id" = NEW."initiative_id" AND
2468 OLD."member_id" = NEW."member_id"
2469 THEN
2470 IF
2471 coalesce(OLD."accepted", FALSE) = coalesce(NEW."accepted", FALSE)
2472 THEN
2473 RETURN NULL;
2474 END IF;
2475 IF coalesce(NEW."accepted", FALSE) = TRUE THEN
2476 "accepted_v" := TRUE;
2477 ELSE
2478 "rejected_v" := TRUE;
2479 END IF;
2480 END IF;
2481 END IF;
2482 IF (TG_OP = 'DELETE' OR TG_OP = 'UPDATE') AND NOT "accepted_v" THEN
2483 IF coalesce(OLD."accepted", FALSE) = TRUE THEN
2484 SELECT * INTO "initiative_row" FROM "initiative"
2485 WHERE "id" = OLD."initiative_id" FOR SHARE;
2486 IF "initiative_row"."id" NOTNULL THEN
2487 SELECT * INTO "issue_row" FROM "issue"
2488 WHERE "id" = "initiative_row"."issue_id" FOR SHARE;
2489 SELECT * INTO "area_row" FROM "area"
2490 WHERE "id" = "issue_row"."area_id" FOR SHARE;
2491 INSERT INTO "event" (
2492 "event", "member_id",
2493 "unit_id", "area_id", "policy_id", "issue_id", "state",
2494 "initiative_id", "boolean_value"
2495 ) VALUES (
2496 'initiator', OLD."member_id",
2497 "area_row"."unit_id", "issue_row"."area_id",
2498 "issue_row"."policy_id",
2499 "issue_row"."id", "issue_row"."state",
2500 OLD."initiative_id", FALSE
2501 );
2502 END IF;
2503 END IF;
2504 END IF;
2505 IF TG_OP = 'UPDATE' AND NOT "rejected_v" THEN
2506 IF coalesce(NEW."accepted", FALSE) = TRUE THEN
2507 SELECT * INTO "initiative_row" FROM "initiative"
2508 WHERE "id" = NEW."initiative_id" FOR SHARE;
2509 SELECT * INTO "issue_row" FROM "issue"
2510 WHERE "id" = "initiative_row"."issue_id" FOR SHARE;
2511 SELECT * INTO "area_row" FROM "area"
2512 WHERE "id" = "issue_row"."area_id" FOR SHARE;
2513 INSERT INTO "event" (
2514 "event", "member_id",
2515 "unit_id", "area_id", "policy_id", "issue_id", "state",
2516 "initiative_id", "boolean_value"
2517 ) VALUES (
2518 'initiator', NEW."member_id",
2519 "area_row"."unit_id", "issue_row"."area_id",
2520 "issue_row"."policy_id",
2521 "issue_row"."id", "issue_row"."state",
2522 NEW."initiative_id", TRUE
2523 );
2524 END IF;
2525 END IF;
2526 RETURN NULL;
2527 END;
2528 $$;
2530 CREATE TRIGGER "write_event_initiator"
2531 AFTER UPDATE OR DELETE ON "initiator" FOR EACH ROW EXECUTE PROCEDURE
2532 "write_event_initiator_trigger"();
2534 COMMENT ON FUNCTION "write_event_initiator_trigger"() IS 'Implementation of trigger "write_event_initiator" on table "initiator"';
2535 COMMENT ON TRIGGER "write_event_initiator" ON "initiator" IS 'Create entry in "event" table when accepting or removing initiatorship (NOTE: trigger does not fire on INSERT to avoid events on initiative creation)';
2538 CREATE FUNCTION "write_event_support_trigger"()
2539 RETURNS TRIGGER
2540 LANGUAGE 'plpgsql' VOLATILE AS $$
2541 DECLARE
2542 "issue_row" "issue"%ROWTYPE;
2543 "area_row" "area"%ROWTYPE;
2544 BEGIN
2545 IF TG_OP = 'UPDATE' THEN
2546 IF
2547 OLD."initiative_id" = NEW."initiative_id" AND
2548 OLD."member_id" = NEW."member_id"
2549 THEN
2550 IF OLD."draft_id" != NEW."draft_id" THEN
2551 SELECT * INTO "issue_row" FROM "issue"
2552 WHERE "id" = NEW."issue_id" FOR SHARE;
2553 SELECT * INTO "area_row" FROM "area"
2554 WHERE "id" = "issue_row"."area_id" FOR SHARE;
2555 INSERT INTO "event" (
2556 "event", "member_id",
2557 "unit_id", "area_id", "policy_id", "issue_id", "state",
2558 "initiative_id", "draft_id"
2559 ) VALUES (
2560 'support_updated', NEW."member_id",
2561 "area_row"."unit_id", "issue_row"."area_id",
2562 "issue_row"."policy_id",
2563 "issue_row"."id", "issue_row"."state",
2564 NEW."initiative_id", NEW."draft_id"
2565 );
2566 END IF;
2567 RETURN NULL;
2568 END IF;
2569 END IF;
2570 IF TG_OP = 'DELETE' OR TG_OP = 'UPDATE' THEN
2571 IF EXISTS (
2572 SELECT NULL FROM "initiative" WHERE "id" = OLD."initiative_id"
2573 FOR SHARE
2574 ) THEN
2575 SELECT * INTO "issue_row" FROM "issue"
2576 WHERE "id" = OLD."issue_id" FOR SHARE;
2577 SELECT * INTO "area_row" FROM "area"
2578 WHERE "id" = "issue_row"."area_id" FOR SHARE;
2579 INSERT INTO "event" (
2580 "event", "member_id",
2581 "unit_id", "area_id", "policy_id", "issue_id", "state",
2582 "initiative_id", "boolean_value"
2583 ) VALUES (
2584 'support', OLD."member_id",
2585 "area_row"."unit_id", "issue_row"."area_id",
2586 "issue_row"."policy_id",
2587 "issue_row"."id", "issue_row"."state",
2588 OLD."initiative_id", FALSE
2589 );
2590 END IF;
2591 END IF;
2592 IF TG_OP = 'INSERT' OR TG_OP = 'UPDATE' THEN
2593 SELECT * INTO "issue_row" FROM "issue"
2594 WHERE "id" = NEW."issue_id" FOR SHARE;
2595 SELECT * INTO "area_row" FROM "area"
2596 WHERE "id" = "issue_row"."area_id" FOR SHARE;
2597 INSERT INTO "event" (
2598 "event", "member_id",
2599 "unit_id", "area_id", "policy_id", "issue_id", "state",
2600 "initiative_id", "draft_id", "boolean_value"
2601 ) VALUES (
2602 'support', NEW."member_id",
2603 "area_row"."unit_id", "issue_row"."area_id",
2604 "issue_row"."policy_id",
2605 "issue_row"."id", "issue_row"."state",
2606 NEW."initiative_id", NEW."draft_id", TRUE
2607 );
2608 END IF;
2609 RETURN NULL;
2610 END;
2611 $$;
2613 CREATE TRIGGER "write_event_support"
2614 AFTER INSERT OR UPDATE OR DELETE ON "supporter" FOR EACH ROW EXECUTE PROCEDURE
2615 "write_event_support_trigger"();
2617 COMMENT ON FUNCTION "write_event_support_trigger"() IS 'Implementation of trigger "write_event_support" on table "supporter"';
2618 COMMENT ON TRIGGER "write_event_support" ON "supporter" IS 'Create entry in "event" table when adding, updating, or removing support';
2621 CREATE FUNCTION "write_event_suggestion_rated_trigger"()
2622 RETURNS TRIGGER
2623 LANGUAGE 'plpgsql' VOLATILE AS $$
2624 DECLARE
2625 "same_pkey_v" BOOLEAN = FALSE;
2626 "initiative_row" "initiative"%ROWTYPE;
2627 "issue_row" "issue"%ROWTYPE;
2628 "area_row" "area"%ROWTYPE;
2629 BEGIN
2630 IF TG_OP = 'UPDATE' THEN
2631 IF
2632 OLD."suggestion_id" = NEW."suggestion_id" AND
2633 OLD."member_id" = NEW."member_id"
2634 THEN
2635 IF
2636 OLD."degree" = NEW."degree" AND
2637 OLD."fulfilled" = NEW."fulfilled"
2638 THEN
2639 RETURN NULL;
2640 END IF;
2641 "same_pkey_v" := TRUE;
2642 END IF;
2643 END IF;
2644 IF (TG_OP = 'DELETE' OR TG_OP = 'UPDATE') AND NOT "same_pkey_v" THEN
2645 IF EXISTS (
2646 SELECT NULL FROM "suggestion" WHERE "id" = OLD."suggestion_id"
2647 FOR SHARE
2648 ) THEN
2649 SELECT * INTO "initiative_row" FROM "initiative"
2650 WHERE "id" = OLD."initiative_id" FOR SHARE;
2651 SELECT * INTO "issue_row" FROM "issue"
2652 WHERE "id" = "initiative_row"."issue_id" FOR SHARE;
2653 SELECT * INTO "area_row" FROM "area"
2654 WHERE "id" = "issue_row"."area_id" FOR SHARE;
2655 INSERT INTO "event" (
2656 "event", "member_id",
2657 "unit_id", "area_id", "policy_id", "issue_id", "state",
2658 "initiative_id", "suggestion_id",
2659 "boolean_value", "numeric_value"
2660 ) VALUES (
2661 'suggestion_rated', OLD."member_id",
2662 "area_row"."unit_id", "issue_row"."area_id",
2663 "issue_row"."policy_id",
2664 "initiative_row"."issue_id", "issue_row"."state",
2665 OLD."initiative_id", OLD."suggestion_id",
2666 NULL, 0
2667 );
2668 END IF;
2669 END IF;
2670 IF TG_OP = 'INSERT' OR TG_OP = 'UPDATE' THEN
2671 SELECT * INTO "initiative_row" FROM "initiative"
2672 WHERE "id" = NEW."initiative_id" FOR SHARE;
2673 SELECT * INTO "issue_row" FROM "issue"
2674 WHERE "id" = "initiative_row"."issue_id" FOR SHARE;
2675 SELECT * INTO "area_row" FROM "area"
2676 WHERE "id" = "issue_row"."area_id" FOR SHARE;
2677 INSERT INTO "event" (
2678 "event", "member_id",
2679 "unit_id", "area_id", "policy_id", "issue_id", "state",
2680 "initiative_id", "suggestion_id",
2681 "boolean_value", "numeric_value"
2682 ) VALUES (
2683 'suggestion_rated', NEW."member_id",
2684 "area_row"."unit_id", "issue_row"."area_id",
2685 "issue_row"."policy_id",
2686 "initiative_row"."issue_id", "issue_row"."state",
2687 NEW."initiative_id", NEW."suggestion_id",
2688 NEW."fulfilled", NEW."degree"
2689 );
2690 END IF;
2691 RETURN NULL;
2692 END;
2693 $$;
2695 CREATE TRIGGER "write_event_suggestion_rated"
2696 AFTER INSERT OR UPDATE OR DELETE ON "opinion" FOR EACH ROW EXECUTE PROCEDURE
2697 "write_event_suggestion_rated_trigger"();
2699 COMMENT ON FUNCTION "write_event_suggestion_rated_trigger"() IS 'Implementation of trigger "write_event_suggestion_rated" on table "opinion"';
2700 COMMENT ON TRIGGER "write_event_suggestion_rated" ON "opinion" IS 'Create entry in "event" table when adding, updating, or removing support';
2703 CREATE FUNCTION "write_event_delegation_trigger"()
2704 RETURNS TRIGGER
2705 LANGUAGE 'plpgsql' VOLATILE AS $$
2706 DECLARE
2707 "issue_row" "issue"%ROWTYPE;
2708 "area_row" "area"%ROWTYPE;
2709 BEGIN
2710 IF TG_OP = 'DELETE' THEN
2711 IF EXISTS (
2712 SELECT NULL FROM "member" WHERE "id" = OLD."truster_id"
2713 ) AND (CASE OLD."scope"
2714 WHEN 'unit'::"delegation_scope" THEN EXISTS (
2715 SELECT NULL FROM "unit" WHERE "id" = OLD."unit_id"
2717 WHEN 'area'::"delegation_scope" THEN EXISTS (
2718 SELECT NULL FROM "area" WHERE "id" = OLD."area_id"
2720 WHEN 'issue'::"delegation_scope" THEN EXISTS (
2721 SELECT NULL FROM "issue" WHERE "id" = OLD."issue_id"
2723 END) THEN
2724 SELECT * INTO "issue_row" FROM "issue"
2725 WHERE "id" = OLD."issue_id" FOR SHARE;
2726 SELECT * INTO "area_row" FROM "area"
2727 WHERE "id" = COALESCE(OLD."area_id", "issue_row"."area_id")
2728 FOR SHARE;
2729 INSERT INTO "event" (
2730 "event", "member_id", "scope",
2731 "unit_id", "area_id", "issue_id", "state",
2732 "boolean_value"
2733 ) VALUES (
2734 'delegation', OLD."truster_id", OLD."scope",
2735 COALESCE(OLD."unit_id", "area_row"."unit_id"), "area_row"."id",
2736 OLD."issue_id", "issue_row"."state",
2737 FALSE
2738 );
2739 END IF;
2740 ELSE
2741 SELECT * INTO "issue_row" FROM "issue"
2742 WHERE "id" = NEW."issue_id" FOR SHARE;
2743 SELECT * INTO "area_row" FROM "area"
2744 WHERE "id" = COALESCE(NEW."area_id", "issue_row"."area_id")
2745 FOR SHARE;
2746 INSERT INTO "event" (
2747 "event", "member_id", "other_member_id", "scope",
2748 "unit_id", "area_id", "issue_id", "state",
2749 "boolean_value"
2750 ) VALUES (
2751 'delegation', NEW."truster_id", NEW."trustee_id", NEW."scope",
2752 COALESCE(NEW."unit_id", "area_row"."unit_id"), "area_row"."id",
2753 NEW."issue_id", "issue_row"."state",
2754 TRUE
2755 );
2756 END IF;
2757 RETURN NULL;
2758 END;
2759 $$;
2761 CREATE TRIGGER "write_event_delegation"
2762 AFTER INSERT OR UPDATE OR DELETE ON "delegation" FOR EACH ROW EXECUTE PROCEDURE
2763 "write_event_delegation_trigger"();
2765 COMMENT ON FUNCTION "write_event_delegation_trigger"() IS 'Implementation of trigger "write_event_delegation" on table "delegation"';
2766 COMMENT ON TRIGGER "write_event_delegation" ON "delegation" IS 'Create entry in "event" table when adding, updating, or removing a delegation';
2769 CREATE FUNCTION "write_event_contact_trigger"()
2770 RETURNS TRIGGER
2771 LANGUAGE 'plpgsql' VOLATILE AS $$
2772 BEGIN
2773 IF TG_OP = 'UPDATE' THEN
2774 IF
2775 OLD."member_id" = NEW."member_id" AND
2776 OLD."other_member_id" = NEW."other_member_id" AND
2777 OLD."public" = NEW."public"
2778 THEN
2779 RETURN NULL;
2780 END IF;
2781 END IF;
2782 IF TG_OP = 'DELETE' OR TG_OP = 'UPDATE' THEN
2783 IF OLD."public" THEN
2784 IF EXISTS (
2785 SELECT NULL FROM "member" WHERE "id" = OLD."member_id"
2786 FOR SHARE
2787 ) AND EXISTS (
2788 SELECT NULL FROM "member" WHERE "id" = OLD."other_member_id"
2789 FOR SHARE
2790 ) THEN
2791 INSERT INTO "event" (
2792 "event", "member_id", "other_member_id", "boolean_value"
2793 ) VALUES (
2794 'contact', OLD."member_id", OLD."other_member_id", FALSE
2795 );
2796 END IF;
2797 END IF;
2798 END IF;
2799 IF TG_OP = 'INSERT' OR TG_OP = 'UPDATE' THEN
2800 IF NEW."public" THEN
2801 INSERT INTO "event" (
2802 "event", "member_id", "other_member_id", "boolean_value"
2803 ) VALUES (
2804 'contact', NEW."member_id", NEW."other_member_id", TRUE
2805 );
2806 END IF;
2807 END IF;
2808 RETURN NULL;
2809 END;
2810 $$;
2812 CREATE TRIGGER "write_event_contact"
2813 AFTER INSERT OR UPDATE OR DELETE ON "contact" FOR EACH ROW EXECUTE PROCEDURE
2814 "write_event_contact_trigger"();
2816 COMMENT ON FUNCTION "write_event_contact_trigger"() IS 'Implementation of trigger "write_event_contact" on table "contact"';
2817 COMMENT ON TRIGGER "write_event_contact" ON "contact" IS 'Create entry in "event" table when adding or removing public contacts';
2820 CREATE FUNCTION "write_event_posting_trigger"()
2821 RETURNS TRIGGER
2822 LANGUAGE 'plpgsql' VOLATILE AS $$
2823 BEGIN
2824 INSERT INTO "event" (
2825 "event", "posting_id", "member_id",
2826 "unit_id", "area_id", "policy_id",
2827 "issue_id", "initiative_id", "suggestion_id"
2828 ) VALUES (
2829 'posting_created', NEW."id", NEW."author_id",
2830 NEW."unit_id", NEW."area_id", NEW."policy_id",
2831 NEW."issue_id", NEW."initiative_id", NEW."suggestion_id"
2832 );
2833 RETURN NULL;
2834 END;
2835 $$;
2837 CREATE TRIGGER "write_event_posting"
2838 AFTER INSERT ON "posting" FOR EACH ROW EXECUTE PROCEDURE
2839 "write_event_posting_trigger"();
2841 COMMENT ON FUNCTION "write_event_posting_trigger"() IS 'Implementation of trigger "write_event_posting" on table "posting"';
2842 COMMENT ON TRIGGER "write_event_posting" ON "posting" IS 'Create entry in "event" table when creating a new posting';
2845 CREATE FUNCTION "send_event_notify_trigger"()
2846 RETURNS TRIGGER
2847 LANGUAGE 'plpgsql' VOLATILE AS $$
2848 BEGIN
2849 EXECUTE 'NOTIFY "event", ''' || NEW."event" || '''';
2850 RETURN NULL;
2851 END;
2852 $$;
2854 CREATE TRIGGER "send_notify"
2855 AFTER INSERT OR UPDATE ON "event" FOR EACH ROW EXECUTE PROCEDURE
2856 "send_event_notify_trigger"();
2860 ----------------------------
2861 -- Additional constraints --
2862 ----------------------------
2865 CREATE FUNCTION "delete_extended_scope_tokens_trigger"()
2866 RETURNS TRIGGER
2867 LANGUAGE 'plpgsql' VOLATILE AS $$
2868 DECLARE
2869 "system_application_row" "system_application"%ROWTYPE;
2870 BEGIN
2871 IF OLD."system_application_id" NOTNULL THEN
2872 SELECT * FROM "system_application" INTO "system_application_row"
2873 WHERE "id" = OLD."system_application_id";
2874 DELETE FROM "token"
2875 WHERE "member_id" = OLD."member_id"
2876 AND "system_application_id" = OLD."system_application_id"
2877 AND NOT COALESCE(
2878 regexp_split_to_array("scope", E'\\s+') <@
2879 regexp_split_to_array(
2880 "system_application_row"."automatic_scope", E'\\s+'
2881 ),
2882 FALSE
2883 );
2884 END IF;
2885 RETURN OLD;
2886 END;
2887 $$;
2889 CREATE TRIGGER "delete_extended_scope_tokens"
2890 BEFORE DELETE ON "member_application" FOR EACH ROW EXECUTE PROCEDURE
2891 "delete_extended_scope_tokens_trigger"();
2894 CREATE FUNCTION "detach_token_from_session_trigger"()
2895 RETURNS TRIGGER
2896 LANGUAGE 'plpgsql' VOLATILE AS $$
2897 BEGIN
2898 UPDATE "token" SET "session_id" = NULL
2899 WHERE "session_id" = OLD."id";
2900 RETURN OLD;
2901 END;
2902 $$;
2904 CREATE TRIGGER "detach_token_from_session"
2905 BEFORE DELETE ON "session" FOR EACH ROW EXECUTE PROCEDURE
2906 "detach_token_from_session_trigger"();
2909 CREATE FUNCTION "delete_non_detached_scope_with_session_trigger"()
2910 RETURNS TRIGGER
2911 LANGUAGE 'plpgsql' VOLATILE AS $$
2912 BEGIN
2913 IF NEW."session_id" ISNULL THEN
2914 SELECT coalesce(string_agg("element", ' '), '') INTO NEW."scope"
2915 FROM unnest(regexp_split_to_array(NEW."scope", E'\\s+')) AS "element"
2916 WHERE "element" LIKE '%_detached';
2917 END IF;
2918 RETURN NEW;
2919 END;
2920 $$;
2922 CREATE TRIGGER "delete_non_detached_scope_with_session"
2923 BEFORE INSERT OR UPDATE ON "token" FOR EACH ROW EXECUTE PROCEDURE
2924 "delete_non_detached_scope_with_session_trigger"();
2927 CREATE FUNCTION "delete_token_with_empty_scope_trigger"()
2928 RETURNS TRIGGER
2929 LANGUAGE 'plpgsql' VOLATILE AS $$
2930 BEGIN
2931 IF NEW."scope" = '' THEN
2932 DELETE FROM "token" WHERE "id" = NEW."id";
2933 END IF;
2934 RETURN NULL;
2935 END;
2936 $$;
2938 CREATE TRIGGER "delete_token_with_empty_scope"
2939 AFTER INSERT OR UPDATE ON "token" FOR EACH ROW EXECUTE PROCEDURE
2940 "delete_token_with_empty_scope_trigger"();
2943 CREATE FUNCTION "issue_requires_first_initiative_trigger"()
2944 RETURNS TRIGGER
2945 LANGUAGE 'plpgsql' VOLATILE AS $$
2946 BEGIN
2947 IF NOT EXISTS (
2948 SELECT NULL FROM "initiative" WHERE "issue_id" = NEW."id"
2949 ) THEN
2950 RAISE EXCEPTION 'Cannot create issue without an initial initiative.' USING
2951 ERRCODE = 'integrity_constraint_violation',
2952 HINT = 'Create issue, initiative, and draft within the same transaction.';
2953 END IF;
2954 RETURN NULL;
2955 END;
2956 $$;
2958 CREATE CONSTRAINT TRIGGER "issue_requires_first_initiative"
2959 AFTER INSERT OR UPDATE ON "issue" DEFERRABLE INITIALLY DEFERRED
2960 FOR EACH ROW EXECUTE PROCEDURE
2961 "issue_requires_first_initiative_trigger"();
2963 COMMENT ON FUNCTION "issue_requires_first_initiative_trigger"() IS 'Implementation of trigger "issue_requires_first_initiative" on table "issue"';
2964 COMMENT ON TRIGGER "issue_requires_first_initiative" ON "issue" IS 'Ensure that new issues have at least one initiative';
2967 CREATE FUNCTION "last_initiative_deletes_issue_trigger"()
2968 RETURNS TRIGGER
2969 LANGUAGE 'plpgsql' VOLATILE AS $$
2970 DECLARE
2971 "reference_lost" BOOLEAN;
2972 BEGIN
2973 IF TG_OP = 'DELETE' THEN
2974 "reference_lost" := TRUE;
2975 ELSE
2976 "reference_lost" := NEW."issue_id" != OLD."issue_id";
2977 END IF;
2978 IF
2979 "reference_lost" AND NOT EXISTS (
2980 SELECT NULL FROM "initiative" WHERE "issue_id" = OLD."issue_id"
2982 THEN
2983 DELETE FROM "issue" WHERE "id" = OLD."issue_id";
2984 END IF;
2985 RETURN NULL;
2986 END;
2987 $$;
2989 CREATE CONSTRAINT TRIGGER "last_initiative_deletes_issue"
2990 AFTER UPDATE OR DELETE ON "initiative" DEFERRABLE INITIALLY DEFERRED
2991 FOR EACH ROW EXECUTE PROCEDURE
2992 "last_initiative_deletes_issue_trigger"();
2994 COMMENT ON FUNCTION "last_initiative_deletes_issue_trigger"() IS 'Implementation of trigger "last_initiative_deletes_issue" on table "initiative"';
2995 COMMENT ON TRIGGER "last_initiative_deletes_issue" ON "initiative" IS 'Removing the last initiative of an issue deletes the issue';
2998 CREATE FUNCTION "initiative_requires_first_draft_trigger"()
2999 RETURNS TRIGGER
3000 LANGUAGE 'plpgsql' VOLATILE AS $$
3001 BEGIN
3002 IF NOT EXISTS (
3003 SELECT NULL FROM "draft" WHERE "initiative_id" = NEW."id"
3004 ) THEN
3005 RAISE EXCEPTION 'Cannot create initiative without an initial draft.' USING
3006 ERRCODE = 'integrity_constraint_violation',
3007 HINT = 'Create issue, initiative and draft within the same transaction.';
3008 END IF;
3009 RETURN NULL;
3010 END;
3011 $$;
3013 CREATE CONSTRAINT TRIGGER "initiative_requires_first_draft"
3014 AFTER INSERT OR UPDATE ON "initiative" DEFERRABLE INITIALLY DEFERRED
3015 FOR EACH ROW EXECUTE PROCEDURE
3016 "initiative_requires_first_draft_trigger"();
3018 COMMENT ON FUNCTION "initiative_requires_first_draft_trigger"() IS 'Implementation of trigger "initiative_requires_first_draft" on table "initiative"';
3019 COMMENT ON TRIGGER "initiative_requires_first_draft" ON "initiative" IS 'Ensure that new initiatives have at least one draft';
3022 CREATE FUNCTION "last_draft_deletes_initiative_trigger"()
3023 RETURNS TRIGGER
3024 LANGUAGE 'plpgsql' VOLATILE AS $$
3025 DECLARE
3026 "reference_lost" BOOLEAN;
3027 BEGIN
3028 IF TG_OP = 'DELETE' THEN
3029 "reference_lost" := TRUE;
3030 ELSE
3031 "reference_lost" := NEW."initiative_id" != OLD."initiative_id";
3032 END IF;
3033 IF
3034 "reference_lost" AND NOT EXISTS (
3035 SELECT NULL FROM "draft" WHERE "initiative_id" = OLD."initiative_id"
3037 THEN
3038 DELETE FROM "initiative" WHERE "id" = OLD."initiative_id";
3039 END IF;
3040 RETURN NULL;
3041 END;
3042 $$;
3044 CREATE CONSTRAINT TRIGGER "last_draft_deletes_initiative"
3045 AFTER UPDATE OR DELETE ON "draft" DEFERRABLE INITIALLY DEFERRED
3046 FOR EACH ROW EXECUTE PROCEDURE
3047 "last_draft_deletes_initiative_trigger"();
3049 COMMENT ON FUNCTION "last_draft_deletes_initiative_trigger"() IS 'Implementation of trigger "last_draft_deletes_initiative" on table "draft"';
3050 COMMENT ON TRIGGER "last_draft_deletes_initiative" ON "draft" IS 'Removing the last draft of an initiative deletes the initiative';
3053 CREATE FUNCTION "suggestion_requires_first_opinion_trigger"()
3054 RETURNS TRIGGER
3055 LANGUAGE 'plpgsql' VOLATILE AS $$
3056 BEGIN
3057 IF NOT EXISTS (
3058 SELECT NULL FROM "opinion" WHERE "suggestion_id" = NEW."id"
3059 ) THEN
3060 RAISE EXCEPTION 'Cannot create a suggestion without an opinion.' USING
3061 ERRCODE = 'integrity_constraint_violation',
3062 HINT = 'Create suggestion and opinion within the same transaction.';
3063 END IF;
3064 RETURN NULL;
3065 END;
3066 $$;
3068 CREATE CONSTRAINT TRIGGER "suggestion_requires_first_opinion"
3069 AFTER INSERT OR UPDATE ON "suggestion" DEFERRABLE INITIALLY DEFERRED
3070 FOR EACH ROW EXECUTE PROCEDURE
3071 "suggestion_requires_first_opinion_trigger"();
3073 COMMENT ON FUNCTION "suggestion_requires_first_opinion_trigger"() IS 'Implementation of trigger "suggestion_requires_first_opinion" on table "suggestion"';
3074 COMMENT ON TRIGGER "suggestion_requires_first_opinion" ON "suggestion" IS 'Ensure that new suggestions have at least one opinion';
3077 CREATE FUNCTION "last_opinion_deletes_suggestion_trigger"()
3078 RETURNS TRIGGER
3079 LANGUAGE 'plpgsql' VOLATILE AS $$
3080 DECLARE
3081 "reference_lost" BOOLEAN;
3082 BEGIN
3083 IF TG_OP = 'DELETE' THEN
3084 "reference_lost" := TRUE;
3085 ELSE
3086 "reference_lost" := NEW."suggestion_id" != OLD."suggestion_id";
3087 END IF;
3088 IF
3089 "reference_lost" AND NOT EXISTS (
3090 SELECT NULL FROM "opinion" WHERE "suggestion_id" = OLD."suggestion_id"
3092 THEN
3093 DELETE FROM "suggestion" WHERE "id" = OLD."suggestion_id";
3094 END IF;
3095 RETURN NULL;
3096 END;
3097 $$;
3099 CREATE CONSTRAINT TRIGGER "last_opinion_deletes_suggestion"
3100 AFTER UPDATE OR DELETE ON "opinion" DEFERRABLE INITIALLY DEFERRED
3101 FOR EACH ROW EXECUTE PROCEDURE
3102 "last_opinion_deletes_suggestion_trigger"();
3104 COMMENT ON FUNCTION "last_opinion_deletes_suggestion_trigger"() IS 'Implementation of trigger "last_opinion_deletes_suggestion" on table "opinion"';
3105 COMMENT ON TRIGGER "last_opinion_deletes_suggestion" ON "opinion" IS 'Removing the last opinion of a suggestion deletes the suggestion';
3108 CREATE FUNCTION "non_voter_deletes_direct_voter_trigger"()
3109 RETURNS TRIGGER
3110 LANGUAGE 'plpgsql' VOLATILE AS $$
3111 BEGIN
3112 DELETE FROM "direct_voter"
3113 WHERE "issue_id" = NEW."issue_id" AND "member_id" = NEW."member_id";
3114 RETURN NULL;
3115 END;
3116 $$;
3118 CREATE TRIGGER "non_voter_deletes_direct_voter"
3119 AFTER INSERT OR UPDATE ON "non_voter"
3120 FOR EACH ROW EXECUTE PROCEDURE
3121 "non_voter_deletes_direct_voter_trigger"();
3123 COMMENT ON FUNCTION "non_voter_deletes_direct_voter_trigger"() IS 'Implementation of trigger "non_voter_deletes_direct_voter" on table "non_voter"';
3124 COMMENT ON TRIGGER "non_voter_deletes_direct_voter" ON "non_voter" IS 'An entry in the "non_voter" table deletes an entry in the "direct_voter" table (and vice versa due to trigger "direct_voter_deletes_non_voter" on table "direct_voter")';
3127 CREATE FUNCTION "direct_voter_deletes_non_voter_trigger"()
3128 RETURNS TRIGGER
3129 LANGUAGE 'plpgsql' VOLATILE AS $$
3130 BEGIN
3131 DELETE FROM "non_voter"
3132 WHERE "issue_id" = NEW."issue_id" AND "member_id" = NEW."member_id";
3133 RETURN NULL;
3134 END;
3135 $$;
3137 CREATE TRIGGER "direct_voter_deletes_non_voter"
3138 AFTER INSERT OR UPDATE ON "direct_voter"
3139 FOR EACH ROW EXECUTE PROCEDURE
3140 "direct_voter_deletes_non_voter_trigger"();
3142 COMMENT ON FUNCTION "direct_voter_deletes_non_voter_trigger"() IS 'Implementation of trigger "direct_voter_deletes_non_voter" on table "direct_voter"';
3143 COMMENT ON TRIGGER "direct_voter_deletes_non_voter" ON "direct_voter" IS 'An entry in the "direct_voter" table deletes an entry in the "non_voter" table (and vice versa due to trigger "non_voter_deletes_direct_voter" on table "non_voter")';
3146 CREATE FUNCTION "voter_comment_fields_only_set_when_voter_comment_is_set_trigger"()
3147 RETURNS TRIGGER
3148 LANGUAGE 'plpgsql' VOLATILE AS $$
3149 BEGIN
3150 IF NEW."comment" ISNULL THEN
3151 NEW."comment_changed" := NULL;
3152 NEW."formatting_engine" := NULL;
3153 END IF;
3154 RETURN NEW;
3155 END;
3156 $$;
3158 CREATE TRIGGER "voter_comment_fields_only_set_when_voter_comment_is_set"
3159 BEFORE INSERT OR UPDATE ON "direct_voter"
3160 FOR EACH ROW EXECUTE PROCEDURE
3161 "voter_comment_fields_only_set_when_voter_comment_is_set_trigger"();
3163 COMMENT ON FUNCTION "voter_comment_fields_only_set_when_voter_comment_is_set_trigger"() IS 'Implementation of trigger "voter_comment_fields_only_set_when_voter_comment_is_set" ON table "direct_voter"';
3164 COMMENT ON TRIGGER "voter_comment_fields_only_set_when_voter_comment_is_set" ON "direct_voter" IS 'If "comment" is set to NULL, then other comment related fields are also set to NULL.';
3167 CREATE FUNCTION "file_requires_reference_trigger"()
3168 RETURNS TRIGGER
3169 LANGUAGE 'plpgsql' VOLATILE AS $$
3170 BEGIN
3171 IF NOT EXISTS (
3172 SELECT NULL FROM "draft_attachment" WHERE "file_id" = NEW."id"
3173 ) THEN
3174 RAISE EXCEPTION 'Cannot create an unreferenced file.' USING
3175 ERRCODE = 'integrity_constraint_violation',
3176 HINT = 'Create file and its reference in another table within the same transaction.';
3177 END IF;
3178 RETURN NULL;
3179 END;
3180 $$;
3182 CREATE CONSTRAINT TRIGGER "file_requires_reference"
3183 AFTER INSERT OR UPDATE ON "file" DEFERRABLE INITIALLY DEFERRED
3184 FOR EACH ROW EXECUTE PROCEDURE
3185 "file_requires_reference_trigger"();
3187 COMMENT ON FUNCTION "file_requires_reference_trigger"() IS 'Implementation of trigger "file_requires_reference" on table "file"';
3188 COMMENT ON TRIGGER "file_requires_reference" ON "file" IS 'Ensure that files are always referenced';
3191 CREATE FUNCTION "last_reference_deletes_file_trigger"()
3192 RETURNS TRIGGER
3193 LANGUAGE 'plpgsql' VOLATILE AS $$
3194 DECLARE
3195 "reference_lost" BOOLEAN;
3196 BEGIN
3197 IF TG_OP = 'DELETE' THEN
3198 "reference_lost" := TRUE;
3199 ELSE
3200 "reference_lost" := NEW."file_id" != OLD."file_id";
3201 END IF;
3202 IF
3203 "reference_lost" AND NOT EXISTS (
3204 SELECT NULL FROM "draft_attachment" WHERE "file_id" = OLD."file_id"
3206 THEN
3207 DELETE FROM "file" WHERE "id" = OLD."file_id";
3208 END IF;
3209 RETURN NULL;
3210 END;
3211 $$;
3213 CREATE CONSTRAINT TRIGGER "last_reference_deletes_file"
3214 AFTER UPDATE OR DELETE ON "draft_attachment" DEFERRABLE INITIALLY DEFERRED
3215 FOR EACH ROW EXECUTE PROCEDURE
3216 "last_reference_deletes_file_trigger"();
3218 COMMENT ON FUNCTION "last_reference_deletes_file_trigger"() IS 'Implementation of trigger "last_reference_deletes_file" on table "draft_attachment"';
3219 COMMENT ON TRIGGER "last_reference_deletes_file" ON "draft_attachment" IS 'Removing the last reference to a file deletes the file';
3223 ---------------------------------
3224 -- Delete incomplete snapshots --
3225 ---------------------------------
3228 CREATE FUNCTION "delete_snapshot_on_partial_delete_trigger"()
3229 RETURNS TRIGGER
3230 LANGUAGE 'plpgsql' VOLATILE AS $$
3231 BEGIN
3232 IF TG_OP = 'UPDATE' THEN
3233 IF
3234 OLD."snapshot_id" = NEW."snapshot_id" AND
3235 OLD."issue_id" = NEW."issue_id"
3236 THEN
3237 RETURN NULL;
3238 END IF;
3239 END IF;
3240 DELETE FROM "snapshot" WHERE "id" = OLD."snapshot_id";
3241 RETURN NULL;
3242 END;
3243 $$;
3245 CREATE TRIGGER "delete_snapshot_on_partial_delete"
3246 AFTER UPDATE OR DELETE ON "snapshot_issue"
3247 FOR EACH ROW EXECUTE PROCEDURE
3248 "delete_snapshot_on_partial_delete_trigger"();
3250 COMMENT ON FUNCTION "delete_snapshot_on_partial_delete_trigger"() IS 'Implementation of trigger "delete_snapshot_on_partial_delete" on table "snapshot_issue"';
3251 COMMENT ON TRIGGER "delete_snapshot_on_partial_delete" ON "snapshot_issue" IS 'Deletes whole snapshot if one issue is deleted from the snapshot';
3255 ---------------------------------------------------------------
3256 -- Ensure that votes are not modified when issues are closed --
3257 ---------------------------------------------------------------
3259 -- NOTE: Frontends should ensure this anyway, but in case of programming
3260 -- errors the following triggers ensure data integrity.
3263 CREATE FUNCTION "forbid_changes_on_closed_issue_trigger"()
3264 RETURNS TRIGGER
3265 LANGUAGE 'plpgsql' VOLATILE AS $$
3266 DECLARE
3267 "issue_id_v" "issue"."id"%TYPE;
3268 "issue_row" "issue"%ROWTYPE;
3269 BEGIN
3270 IF EXISTS (
3271 SELECT NULL FROM "temporary_transaction_data"
3272 WHERE "txid" = txid_current()
3273 AND "key" = 'override_protection_triggers'
3274 AND "value" = TRUE::TEXT
3275 ) THEN
3276 RETURN NULL;
3277 END IF;
3278 IF TG_OP = 'DELETE' THEN
3279 "issue_id_v" := OLD."issue_id";
3280 ELSE
3281 "issue_id_v" := NEW."issue_id";
3282 END IF;
3283 SELECT INTO "issue_row" * FROM "issue"
3284 WHERE "id" = "issue_id_v" FOR SHARE;
3285 IF (
3286 "issue_row"."closed" NOTNULL OR (
3287 "issue_row"."state" = 'voting' AND
3288 "issue_row"."phase_finished" NOTNULL
3290 ) THEN
3291 IF
3292 TG_RELID = 'direct_voter'::regclass AND
3293 TG_OP = 'UPDATE'
3294 THEN
3295 IF
3296 OLD."issue_id" = NEW."issue_id" AND
3297 OLD."member_id" = NEW."member_id" AND
3298 OLD."weight" = NEW."weight"
3299 THEN
3300 RETURN NULL; -- allows changing of voter comment
3301 END IF;
3302 END IF;
3303 RAISE EXCEPTION 'Tried to modify data after voting has been closed.' USING
3304 ERRCODE = 'integrity_constraint_violation';
3305 END IF;
3306 RETURN NULL;
3307 END;
3308 $$;
3310 CREATE TRIGGER "forbid_changes_on_closed_issue"
3311 AFTER INSERT OR UPDATE OR DELETE ON "direct_voter"
3312 FOR EACH ROW EXECUTE PROCEDURE
3313 "forbid_changes_on_closed_issue_trigger"();
3315 CREATE TRIGGER "forbid_changes_on_closed_issue"
3316 AFTER INSERT OR UPDATE OR DELETE ON "delegating_voter"
3317 FOR EACH ROW EXECUTE PROCEDURE
3318 "forbid_changes_on_closed_issue_trigger"();
3320 CREATE TRIGGER "forbid_changes_on_closed_issue"
3321 AFTER INSERT OR UPDATE OR DELETE ON "vote"
3322 FOR EACH ROW EXECUTE PROCEDURE
3323 "forbid_changes_on_closed_issue_trigger"();
3325 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"';
3326 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';
3327 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';
3328 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';
3332 --------------------------------------------------------------------
3333 -- Auto-retrieval of fields only needed for referential integrity --
3334 --------------------------------------------------------------------
3337 CREATE FUNCTION "autofill_issue_id_trigger"()
3338 RETURNS TRIGGER
3339 LANGUAGE 'plpgsql' VOLATILE AS $$
3340 BEGIN
3341 IF NEW."issue_id" ISNULL THEN
3342 SELECT "issue_id" INTO NEW."issue_id"
3343 FROM "initiative" WHERE "id" = NEW."initiative_id";
3344 END IF;
3345 RETURN NEW;
3346 END;
3347 $$;
3349 CREATE TRIGGER "autofill_issue_id" BEFORE INSERT ON "supporter"
3350 FOR EACH ROW EXECUTE PROCEDURE "autofill_issue_id_trigger"();
3352 CREATE TRIGGER "autofill_issue_id" BEFORE INSERT ON "vote"
3353 FOR EACH ROW EXECUTE PROCEDURE "autofill_issue_id_trigger"();
3355 COMMENT ON FUNCTION "autofill_issue_id_trigger"() IS 'Implementation of triggers "autofill_issue_id" on tables "supporter" and "vote"';
3356 COMMENT ON TRIGGER "autofill_issue_id" ON "supporter" IS 'Set "issue_id" field automatically, if NULL';
3357 COMMENT ON TRIGGER "autofill_issue_id" ON "vote" IS 'Set "issue_id" field automatically, if NULL';
3360 CREATE FUNCTION "autofill_initiative_id_trigger"()
3361 RETURNS TRIGGER
3362 LANGUAGE 'plpgsql' VOLATILE AS $$
3363 BEGIN
3364 IF NEW."initiative_id" ISNULL THEN
3365 SELECT "initiative_id" INTO NEW."initiative_id"
3366 FROM "suggestion" WHERE "id" = NEW."suggestion_id";
3367 END IF;
3368 RETURN NEW;
3369 END;
3370 $$;
3372 CREATE TRIGGER "autofill_initiative_id" BEFORE INSERT ON "opinion"
3373 FOR EACH ROW EXECUTE PROCEDURE "autofill_initiative_id_trigger"();
3375 COMMENT ON FUNCTION "autofill_initiative_id_trigger"() IS 'Implementation of trigger "autofill_initiative_id" on table "opinion"';
3376 COMMENT ON TRIGGER "autofill_initiative_id" ON "opinion" IS 'Set "initiative_id" field automatically, if NULL';
3380 -------------------------------------------------------
3381 -- Automatic copying of values for indexing purposes --
3382 -------------------------------------------------------
3385 CREATE FUNCTION "copy_current_draft_data"
3386 ("initiative_id_p" "initiative"."id"%TYPE )
3387 RETURNS VOID
3388 LANGUAGE 'plpgsql' VOLATILE AS $$
3389 BEGIN
3390 PERFORM NULL FROM "initiative" WHERE "id" = "initiative_id_p"
3391 FOR UPDATE;
3392 UPDATE "initiative" SET
3393 "location" = "draft"."location",
3394 "content" = "draft"."content"
3395 FROM "current_draft" AS "draft"
3396 WHERE "initiative"."id" = "initiative_id_p"
3397 AND "draft"."initiative_id" = "initiative_id_p";
3398 END;
3399 $$;
3401 COMMENT ON FUNCTION "copy_current_draft_data"
3402 ( "initiative"."id"%TYPE )
3403 IS 'Helper function for function "copy_current_draft_data_trigger"';
3406 CREATE FUNCTION "copy_current_draft_data_trigger"()
3407 RETURNS TRIGGER
3408 LANGUAGE 'plpgsql' VOLATILE AS $$
3409 BEGIN
3410 IF TG_OP='DELETE' THEN
3411 PERFORM "copy_current_draft_data"(OLD."initiative_id");
3412 ELSE
3413 IF TG_OP='UPDATE' THEN
3414 IF COALESCE(OLD."inititiave_id" != NEW."initiative_id", TRUE) THEN
3415 PERFORM "copy_current_draft_data"(OLD."initiative_id");
3416 END IF;
3417 END IF;
3418 PERFORM "copy_current_draft_data"(NEW."initiative_id");
3419 END IF;
3420 RETURN NULL;
3421 END;
3422 $$;
3424 CREATE TRIGGER "copy_current_draft_data"
3425 AFTER INSERT OR UPDATE OR DELETE ON "draft"
3426 FOR EACH ROW EXECUTE PROCEDURE
3427 "copy_current_draft_data_trigger"();
3429 COMMENT ON FUNCTION "copy_current_draft_data_trigger"() IS 'Implementation of trigger "copy_current_draft_data" on table "draft"';
3430 COMMENT ON TRIGGER "copy_current_draft_data" ON "draft" IS 'Copy certain fields from most recent "draft" to "initiative"';
3434 -----------------------------------------------------
3435 -- Automatic calculation of certain default values --
3436 -----------------------------------------------------
3439 CREATE FUNCTION "copy_timings_trigger"()
3440 RETURNS TRIGGER
3441 LANGUAGE 'plpgsql' VOLATILE AS $$
3442 DECLARE
3443 "policy_row" "policy"%ROWTYPE;
3444 BEGIN
3445 SELECT * INTO "policy_row" FROM "policy"
3446 WHERE "id" = NEW."policy_id";
3447 IF NEW."min_admission_time" ISNULL THEN
3448 NEW."min_admission_time" := "policy_row"."min_admission_time";
3449 END IF;
3450 IF NEW."max_admission_time" ISNULL THEN
3451 NEW."max_admission_time" := "policy_row"."max_admission_time";
3452 END IF;
3453 IF NEW."discussion_time" ISNULL THEN
3454 NEW."discussion_time" := "policy_row"."discussion_time";
3455 END IF;
3456 IF NEW."verification_time" ISNULL THEN
3457 NEW."verification_time" := "policy_row"."verification_time";
3458 END IF;
3459 IF NEW."voting_time" ISNULL THEN
3460 NEW."voting_time" := "policy_row"."voting_time";
3461 END IF;
3462 RETURN NEW;
3463 END;
3464 $$;
3466 CREATE TRIGGER "copy_timings" BEFORE INSERT OR UPDATE ON "issue"
3467 FOR EACH ROW EXECUTE PROCEDURE "copy_timings_trigger"();
3469 COMMENT ON FUNCTION "copy_timings_trigger"() IS 'Implementation of trigger "copy_timings" on table "issue"';
3470 COMMENT ON TRIGGER "copy_timings" ON "issue" IS 'If timing fields are NULL, copy values from policy.';
3473 CREATE FUNCTION "default_for_draft_id_trigger"()
3474 RETURNS TRIGGER
3475 LANGUAGE 'plpgsql' VOLATILE AS $$
3476 BEGIN
3477 IF NEW."draft_id" ISNULL THEN
3478 SELECT "id" INTO NEW."draft_id" FROM "current_draft"
3479 WHERE "initiative_id" = NEW."initiative_id";
3480 END IF;
3481 RETURN NEW;
3482 END;
3483 $$;
3485 CREATE TRIGGER "default_for_draft_id" BEFORE INSERT OR UPDATE ON "suggestion"
3486 FOR EACH ROW EXECUTE PROCEDURE "default_for_draft_id_trigger"();
3487 CREATE TRIGGER "default_for_draft_id" BEFORE INSERT OR UPDATE ON "supporter"
3488 FOR EACH ROW EXECUTE PROCEDURE "default_for_draft_id_trigger"();
3490 COMMENT ON FUNCTION "default_for_draft_id_trigger"() IS 'Implementation of trigger "default_for_draft" on tables "supporter" and "suggestion"';
3491 COMMENT ON TRIGGER "default_for_draft_id" ON "suggestion" IS 'If "draft_id" is NULL, then use the current draft of the initiative as default';
3492 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';
3496 ----------------------------------------
3497 -- Automatic creation of dependencies --
3498 ----------------------------------------
3501 CREATE FUNCTION "autocreate_interest_trigger"()
3502 RETURNS TRIGGER
3503 LANGUAGE 'plpgsql' VOLATILE AS $$
3504 BEGIN
3505 IF NOT EXISTS (
3506 SELECT NULL FROM "initiative" JOIN "interest"
3507 ON "initiative"."issue_id" = "interest"."issue_id"
3508 WHERE "initiative"."id" = NEW."initiative_id"
3509 AND "interest"."member_id" = NEW."member_id"
3510 ) THEN
3511 BEGIN
3512 INSERT INTO "interest" ("issue_id", "member_id")
3513 SELECT "issue_id", NEW."member_id"
3514 FROM "initiative" WHERE "id" = NEW."initiative_id";
3515 EXCEPTION WHEN unique_violation THEN END;
3516 END IF;
3517 RETURN NEW;
3518 END;
3519 $$;
3521 CREATE TRIGGER "autocreate_interest" BEFORE INSERT ON "supporter"
3522 FOR EACH ROW EXECUTE PROCEDURE "autocreate_interest_trigger"();
3524 COMMENT ON FUNCTION "autocreate_interest_trigger"() IS 'Implementation of trigger "autocreate_interest" on table "supporter"';
3525 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';
3528 CREATE FUNCTION "autocreate_supporter_trigger"()
3529 RETURNS TRIGGER
3530 LANGUAGE 'plpgsql' VOLATILE AS $$
3531 BEGIN
3532 IF NOT EXISTS (
3533 SELECT NULL FROM "suggestion" JOIN "supporter"
3534 ON "suggestion"."initiative_id" = "supporter"."initiative_id"
3535 WHERE "suggestion"."id" = NEW."suggestion_id"
3536 AND "supporter"."member_id" = NEW."member_id"
3537 ) THEN
3538 BEGIN
3539 INSERT INTO "supporter" ("initiative_id", "member_id")
3540 SELECT "initiative_id", NEW."member_id"
3541 FROM "suggestion" WHERE "id" = NEW."suggestion_id";
3542 EXCEPTION WHEN unique_violation THEN END;
3543 END IF;
3544 RETURN NEW;
3545 END;
3546 $$;
3548 CREATE TRIGGER "autocreate_supporter" BEFORE INSERT ON "opinion"
3549 FOR EACH ROW EXECUTE PROCEDURE "autocreate_supporter_trigger"();
3551 COMMENT ON FUNCTION "autocreate_supporter_trigger"() IS 'Implementation of trigger "autocreate_supporter" on table "opinion"';
3552 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.';
3556 ------------------------------------------
3557 -- Views and helper functions for views --
3558 ------------------------------------------
3561 CREATE VIEW "member_eligible_to_be_notified" AS
3562 SELECT * FROM "member"
3563 WHERE "activated" NOTNULL AND "locked" = FALSE;
3565 COMMENT ON VIEW "member_eligible_to_be_notified" IS 'Filtered "member" table containing only activated and non-locked members (used as helper view for "member_to_notify" and "newsletter_to_send")';
3568 CREATE VIEW "member_to_notify" AS
3569 SELECT * FROM "member_eligible_to_be_notified"
3570 WHERE "disable_notifications" = FALSE;
3572 COMMENT ON VIEW "member_to_notify" IS 'Filtered "member" table containing only members that are eligible to and wish to receive notifications; NOTE: "notify_email" may still be NULL and might need to be checked by frontend (this allows other means of messaging)';
3575 CREATE VIEW "follower" AS
3576 SELECT
3577 "id" AS "follower_id",
3578 ( SELECT ARRAY["member"."id"] || array_agg("contact"."other_member_id")
3579 FROM "contact"
3580 WHERE "contact"."member_id" = "member"."id" AND "contact"."following" )
3581 AS "following_ids"
3582 FROM "member";
3584 COMMENT ON VIEW "follower" IS 'Provides the contacts of each member that are being followed (including the member itself) as an array of IDs';
3587 CREATE VIEW "area_quorum" AS
3588 SELECT
3589 "area"."id" AS "area_id",
3590 ceil(
3591 "area"."quorum_standard"::FLOAT8 * "quorum_factor"::FLOAT8 ^ (
3592 coalesce(
3593 ( SELECT sum(
3594 ( extract(epoch from "area"."quorum_time")::FLOAT8 /
3595 extract(epoch from
3596 ("issue"."accepted"-"issue"."created") +
3597 "issue"."discussion_time" +
3598 "issue"."verification_time" +
3599 "issue"."voting_time"
3600 )::FLOAT8
3601 ) ^ "area"."quorum_exponent"::FLOAT8
3603 FROM "issue" JOIN "policy"
3604 ON "issue"."policy_id" = "policy"."id"
3605 WHERE "issue"."area_id" = "area"."id"
3606 AND "issue"."accepted" NOTNULL
3607 AND "issue"."closed" ISNULL
3608 AND "policy"."polling" = FALSE
3609 )::FLOAT8, 0::FLOAT8
3610 ) / "area"."quorum_issues"::FLOAT8 - 1::FLOAT8
3611 ) * CASE WHEN "area"."quorum_den" ISNULL THEN 1 ELSE (
3612 SELECT "snapshot"."population"
3613 FROM "snapshot"
3614 WHERE "snapshot"."area_id" = "area"."id"
3615 AND "snapshot"."issue_id" ISNULL
3616 ORDER BY "snapshot"."id" DESC
3617 LIMIT 1
3618 ) END / coalesce("area"."quorum_den", 1)
3620 )::INT4 AS "issue_quorum"
3621 FROM "area";
3623 COMMENT ON VIEW "area_quorum" IS 'Area-based quorum considering number of open (accepted) issues';
3626 CREATE VIEW "issue_quorum" AS
3627 SELECT DISTINCT ON ("issue_id")
3628 "issue"."id" AS "issue_id",
3629 "subquery"."issue_quorum"
3630 FROM "issue"
3631 CROSS JOIN LATERAL (
3632 SELECT "area_quorum"."issue_quorum"
3633 FROM "area_quorum" WHERE "area_quorum"."area_id" = "issue"."area_id"
3634 UNION ALL
3635 SELECT "policy"."issue_quorum"
3636 FROM "policy" WHERE "policy"."id" = "issue"."policy_id"
3637 UNION ALL
3638 SELECT
3639 ceil(
3640 ("issue"."population"::INT8 * "policy"."issue_quorum_num"::INT8) /
3641 "policy"."issue_quorum_den"::FLOAT8
3642 )::INT4
3643 FROM "policy" WHERE "policy"."id" = "issue"."policy_id"
3644 ) AS "subquery"
3645 ORDER BY "issue_id", "issue_quorum" DESC;
3647 COMMENT ON VIEW "issue_quorum" IS 'Effective quorum for issue admission';
3650 CREATE VIEW "area_with_unaccepted_issues" AS
3651 SELECT DISTINCT ON ("area"."id") "area".*
3652 FROM "area" JOIN "issue" ON "area"."id" = "issue"."area_id"
3653 WHERE "issue"."state" = 'admission';
3655 COMMENT ON VIEW "area_with_unaccepted_issues" IS 'All areas with unaccepted open issues (needed for issue admission system)';
3658 CREATE VIEW "issue_for_admission" AS
3659 SELECT DISTINCT ON ("issue"."area_id")
3660 "issue".*,
3661 max("initiative"."supporter_count") AS "max_supporter_count"
3662 FROM "issue"
3663 JOIN "policy" ON "issue"."policy_id" = "policy"."id"
3664 JOIN "initiative" ON "issue"."id" = "initiative"."issue_id"
3665 JOIN "area" ON "issue"."area_id" = "area"."id"
3666 WHERE "issue"."state" = 'admission'::"issue_state"
3667 AND now() >= "issue"."created" + "issue"."min_admission_time"
3668 AND "initiative"."supporter_count" >= "policy"."issue_quorum"
3669 AND "initiative"."supporter_count" * "policy"."issue_quorum_den" >=
3670 "issue"."population" * "policy"."issue_quorum_num"
3671 AND "initiative"."supporter_count" >= "area"."issue_quorum"
3672 AND "initiative"."revoked" ISNULL
3673 GROUP BY "issue"."id"
3674 ORDER BY "issue"."area_id", "max_supporter_count" DESC, "issue"."id";
3676 COMMENT ON VIEW "issue_for_admission" IS 'Contains up to 1 issue per area eligible to pass from ''admission'' to ''discussion'' state; needs to be recalculated after admitting the issue in this view';
3679 CREATE VIEW "unit_delegation" AS
3680 SELECT
3681 "unit"."id" AS "unit_id",
3682 "delegation"."id",
3683 "delegation"."truster_id",
3684 "delegation"."trustee_id",
3685 "delegation"."scope"
3686 FROM "unit"
3687 JOIN "delegation"
3688 ON "delegation"."unit_id" = "unit"."id"
3689 JOIN "member"
3690 ON "delegation"."truster_id" = "member"."id"
3691 JOIN "privilege"
3692 ON "delegation"."unit_id" = "privilege"."unit_id"
3693 AND "delegation"."truster_id" = "privilege"."member_id"
3694 WHERE "member"."active" AND "privilege"."voting_right";
3696 COMMENT ON VIEW "unit_delegation" IS 'Unit delegations where trusters are active and have voting right';
3699 CREATE VIEW "area_delegation" AS
3700 SELECT DISTINCT ON ("area"."id", "delegation"."truster_id")
3701 "area"."id" AS "area_id",
3702 "delegation"."id",
3703 "delegation"."truster_id",
3704 "delegation"."trustee_id",
3705 "delegation"."scope"
3706 FROM "area"
3707 JOIN "delegation"
3708 ON "delegation"."unit_id" = "area"."unit_id"
3709 OR "delegation"."area_id" = "area"."id"
3710 JOIN "member"
3711 ON "delegation"."truster_id" = "member"."id"
3712 JOIN "privilege"
3713 ON "area"."unit_id" = "privilege"."unit_id"
3714 AND "delegation"."truster_id" = "privilege"."member_id"
3715 WHERE "member"."active" AND "privilege"."voting_right"
3716 ORDER BY
3717 "area"."id",
3718 "delegation"."truster_id",
3719 "delegation"."scope" DESC;
3721 COMMENT ON VIEW "area_delegation" IS 'Area delegations where trusters are active and have voting right';
3724 CREATE VIEW "issue_delegation" AS
3725 SELECT DISTINCT ON ("issue"."id", "delegation"."truster_id")
3726 "issue"."id" AS "issue_id",
3727 "delegation"."id",
3728 "delegation"."truster_id",
3729 "delegation"."trustee_id",
3730 "delegation"."scope"
3731 FROM "issue"
3732 JOIN "area"
3733 ON "area"."id" = "issue"."area_id"
3734 JOIN "delegation"
3735 ON "delegation"."unit_id" = "area"."unit_id"
3736 OR "delegation"."area_id" = "area"."id"
3737 OR "delegation"."issue_id" = "issue"."id"
3738 JOIN "member"
3739 ON "delegation"."truster_id" = "member"."id"
3740 JOIN "privilege"
3741 ON "area"."unit_id" = "privilege"."unit_id"
3742 AND "delegation"."truster_id" = "privilege"."member_id"
3743 WHERE "member"."active" AND "privilege"."voting_right"
3744 ORDER BY
3745 "issue"."id",
3746 "delegation"."truster_id",
3747 "delegation"."scope" DESC;
3749 COMMENT ON VIEW "issue_delegation" IS 'Issue delegations where trusters are active and have voting right';
3752 CREATE VIEW "member_count_view" AS
3753 SELECT count(1) AS "total_count" FROM "member" WHERE "active";
3755 COMMENT ON VIEW "member_count_view" IS 'View used to update "member_count" table';
3758 CREATE VIEW "unit_member" AS
3759 SELECT
3760 "unit"."id" AS "unit_id",
3761 "member"."id" AS "member_id"
3762 FROM "privilege"
3763 JOIN "unit" ON "unit"."id" = "privilege"."unit_id"
3764 JOIN "member" ON "member"."id" = "privilege"."member_id"
3765 WHERE "privilege"."voting_right" AND "member"."active";
3767 COMMENT ON VIEW "unit_member" IS 'Active members with voting right in a unit';
3770 CREATE VIEW "unit_member_count" AS
3771 SELECT
3772 "unit"."id" AS "unit_id",
3773 count("unit_member"."member_id") AS "member_count"
3774 FROM "unit" LEFT JOIN "unit_member"
3775 ON "unit"."id" = "unit_member"."unit_id"
3776 GROUP BY "unit"."id";
3778 COMMENT ON VIEW "unit_member_count" IS 'View used to update "member_count" column of "unit" table';
3781 CREATE VIEW "opening_draft" AS
3782 SELECT DISTINCT ON ("initiative_id") * FROM "draft"
3783 ORDER BY "initiative_id", "id";
3785 COMMENT ON VIEW "opening_draft" IS 'First drafts of all initiatives';
3788 CREATE VIEW "current_draft" AS
3789 SELECT DISTINCT ON ("initiative_id") * FROM "draft"
3790 ORDER BY "initiative_id", "id" DESC;
3792 COMMENT ON VIEW "current_draft" IS 'All latest drafts for each initiative';
3795 CREATE VIEW "critical_opinion" AS
3796 SELECT * FROM "opinion"
3797 WHERE ("degree" = 2 AND "fulfilled" = FALSE)
3798 OR ("degree" = -2 AND "fulfilled" = TRUE);
3800 COMMENT ON VIEW "critical_opinion" IS 'Opinions currently causing dissatisfaction';
3803 CREATE VIEW "issue_supporter_in_admission_state" AS
3804 SELECT
3805 "area"."unit_id",
3806 "issue"."area_id",
3807 "issue"."id" AS "issue_id",
3808 "supporter"."member_id",
3809 "direct_interest_snapshot"."weight"
3810 FROM "issue"
3811 JOIN "area" ON "area"."id" = "issue"."area_id"
3812 JOIN "supporter" ON "supporter"."issue_id" = "issue"."id"
3813 JOIN "direct_interest_snapshot"
3814 ON "direct_interest_snapshot"."snapshot_id" = "issue"."latest_snapshot_id"
3815 AND "direct_interest_snapshot"."issue_id" = "issue"."id"
3816 AND "direct_interest_snapshot"."member_id" = "supporter"."member_id"
3817 WHERE "issue"."state" = 'admission'::"issue_state";
3819 COMMENT ON VIEW "issue_supporter_in_admission_state" IS 'Helper view for "lf_update_issue_order" to allow a (proportional) ordering of issues within an area';
3822 CREATE VIEW "initiative_suggestion_order_calculation" AS
3823 SELECT
3824 "initiative"."id" AS "initiative_id",
3825 ("issue"."closed" NOTNULL OR "issue"."fully_frozen" NOTNULL) AS "final"
3826 FROM "initiative" JOIN "issue"
3827 ON "initiative"."issue_id" = "issue"."id"
3828 WHERE ("issue"."closed" ISNULL AND "issue"."fully_frozen" ISNULL)
3829 OR ("initiative"."final_suggestion_order_calculated" = FALSE);
3831 COMMENT ON VIEW "initiative_suggestion_order_calculation" IS 'Initiatives, where the "proportional_order" of its suggestions has to be calculated';
3833 COMMENT ON COLUMN "initiative_suggestion_order_calculation"."final" IS 'Set to TRUE, if the issue is fully frozen or closed, and the calculation has to be done only once for one last time';
3836 CREATE VIEW "individual_suggestion_ranking" AS
3837 SELECT
3838 "opinion"."initiative_id",
3839 "opinion"."member_id",
3840 "direct_interest_snapshot"."weight",
3841 CASE WHEN
3842 ("opinion"."degree" = 2 AND "opinion"."fulfilled" = FALSE) OR
3843 ("opinion"."degree" = -2 AND "opinion"."fulfilled" = TRUE)
3844 THEN 1 ELSE
3845 CASE WHEN
3846 ("opinion"."degree" = 1 AND "opinion"."fulfilled" = FALSE) OR
3847 ("opinion"."degree" = -1 AND "opinion"."fulfilled" = TRUE)
3848 THEN 2 ELSE
3849 CASE WHEN
3850 ("opinion"."degree" = 2 AND "opinion"."fulfilled" = TRUE) OR
3851 ("opinion"."degree" = -2 AND "opinion"."fulfilled" = FALSE)
3852 THEN 3 ELSE 4 END
3853 END
3854 END AS "preference",
3855 "opinion"."suggestion_id"
3856 FROM "opinion"
3857 JOIN "initiative" ON "initiative"."id" = "opinion"."initiative_id"
3858 JOIN "issue" ON "issue"."id" = "initiative"."issue_id"
3859 JOIN "direct_interest_snapshot"
3860 ON "direct_interest_snapshot"."snapshot_id" = "issue"."latest_snapshot_id"
3861 AND "direct_interest_snapshot"."issue_id" = "issue"."id"
3862 AND "direct_interest_snapshot"."member_id" = "opinion"."member_id";
3864 COMMENT ON VIEW "individual_suggestion_ranking" IS 'Helper view for "lf_update_suggestion_order" to allow a proportional ordering of suggestions within an initiative';
3867 CREATE VIEW "battle_participant" AS
3868 SELECT "initiative"."id", "initiative"."issue_id"
3869 FROM "issue" JOIN "initiative"
3870 ON "issue"."id" = "initiative"."issue_id"
3871 WHERE "initiative"."admitted"
3872 UNION ALL
3873 SELECT NULL, "id" AS "issue_id"
3874 FROM "issue";
3876 COMMENT ON VIEW "battle_participant" IS 'Helper view for "battle_view" containing admitted initiatives plus virtual "status-quo" initiative denoted by NULL reference';
3879 CREATE VIEW "battle_view" AS
3880 SELECT
3881 "issue"."id" AS "issue_id",
3882 "winning_initiative"."id" AS "winning_initiative_id",
3883 "losing_initiative"."id" AS "losing_initiative_id",
3884 sum(
3885 CASE WHEN
3886 coalesce("better_vote"."grade", 0) >
3887 coalesce("worse_vote"."grade", 0)
3888 THEN "direct_voter"."weight" ELSE 0 END
3889 ) AS "count"
3890 FROM "issue"
3891 LEFT JOIN "direct_voter"
3892 ON "issue"."id" = "direct_voter"."issue_id"
3893 JOIN "battle_participant" AS "winning_initiative"
3894 ON "issue"."id" = "winning_initiative"."issue_id"
3895 JOIN "battle_participant" AS "losing_initiative"
3896 ON "issue"."id" = "losing_initiative"."issue_id"
3897 LEFT JOIN "vote" AS "better_vote"
3898 ON "direct_voter"."member_id" = "better_vote"."member_id"
3899 AND "winning_initiative"."id" = "better_vote"."initiative_id"
3900 LEFT JOIN "vote" AS "worse_vote"
3901 ON "direct_voter"."member_id" = "worse_vote"."member_id"
3902 AND "losing_initiative"."id" = "worse_vote"."initiative_id"
3903 WHERE "issue"."state" = 'voting'
3904 AND "issue"."phase_finished" NOTNULL
3905 AND (
3906 "winning_initiative"."id" != "losing_initiative"."id" OR
3907 ( ("winning_initiative"."id" NOTNULL AND "losing_initiative"."id" ISNULL) OR
3908 ("winning_initiative"."id" ISNULL AND "losing_initiative"."id" NOTNULL) ) )
3909 GROUP BY
3910 "issue"."id",
3911 "winning_initiative"."id",
3912 "losing_initiative"."id";
3914 COMMENT ON VIEW "battle_view" IS 'Number of members preferring one initiative (or status-quo) to another initiative (or status-quo); Used to fill "battle" table';
3917 CREATE VIEW "expired_session" AS
3918 SELECT * FROM "session" WHERE now() > "expiry";
3920 CREATE RULE "delete" AS ON DELETE TO "expired_session" DO INSTEAD
3921 DELETE FROM "session" WHERE "id" = OLD."id";
3923 COMMENT ON VIEW "expired_session" IS 'View containing all expired sessions where DELETE is possible';
3924 COMMENT ON RULE "delete" ON "expired_session" IS 'Rule allowing DELETE on rows in "expired_session" view, i.e. DELETE FROM "expired_session"';
3927 CREATE VIEW "expired_token" AS
3928 SELECT * FROM "token" WHERE now() > "expiry" AND NOT (
3929 "token_type" = 'authorization' AND "used" AND EXISTS (
3930 SELECT NULL FROM "token" AS "other"
3931 WHERE "other"."authorization_token_id" = "token"."id" ) );
3933 CREATE RULE "delete" AS ON DELETE TO "expired_token" DO INSTEAD
3934 DELETE FROM "token" WHERE "id" = OLD."id";
3936 COMMENT ON VIEW "expired_token" IS 'View containing all expired tokens where DELETE is possible; Note that used authorization codes must not be deleted if still referred to by other tokens';
3939 CREATE VIEW "unused_snapshot" AS
3940 SELECT "snapshot".* FROM "snapshot"
3941 LEFT JOIN "issue"
3942 ON "snapshot"."id" = "issue"."latest_snapshot_id"
3943 OR "snapshot"."id" = "issue"."admission_snapshot_id"
3944 OR "snapshot"."id" = "issue"."half_freeze_snapshot_id"
3945 OR "snapshot"."id" = "issue"."full_freeze_snapshot_id"
3946 WHERE "issue"."id" ISNULL;
3948 CREATE RULE "delete" AS ON DELETE TO "unused_snapshot" DO INSTEAD
3949 DELETE FROM "snapshot" WHERE "id" = OLD."id";
3951 COMMENT ON VIEW "unused_snapshot" IS 'Snapshots that are not referenced by any issue (either as latest snapshot or as snapshot at phase/state change)';
3954 CREATE VIEW "open_issue" AS
3955 SELECT * FROM "issue" WHERE "closed" ISNULL;
3957 COMMENT ON VIEW "open_issue" IS 'All open issues';
3960 CREATE VIEW "member_contingent" AS
3961 SELECT
3962 "member"."id" AS "member_id",
3963 "contingent"."polling",
3964 "contingent"."time_frame",
3965 CASE WHEN "contingent"."text_entry_limit" NOTNULL THEN
3967 SELECT count(1) FROM "draft"
3968 JOIN "initiative" ON "initiative"."id" = "draft"."initiative_id"
3969 WHERE "draft"."author_id" = "member"."id"
3970 AND "initiative"."polling" = "contingent"."polling"
3971 AND "draft"."created" > now() - "contingent"."time_frame"
3972 ) + (
3973 SELECT count(1) FROM "suggestion"
3974 JOIN "initiative" ON "initiative"."id" = "suggestion"."initiative_id"
3975 WHERE "suggestion"."author_id" = "member"."id"
3976 AND "contingent"."polling" = FALSE
3977 AND "suggestion"."created" > now() - "contingent"."time_frame"
3979 ELSE NULL END AS "text_entry_count",
3980 "contingent"."text_entry_limit",
3981 CASE WHEN "contingent"."initiative_limit" NOTNULL THEN (
3982 SELECT count(1) FROM "opening_draft" AS "draft"
3983 JOIN "initiative" ON "initiative"."id" = "draft"."initiative_id"
3984 WHERE "draft"."author_id" = "member"."id"
3985 AND "initiative"."polling" = "contingent"."polling"
3986 AND "draft"."created" > now() - "contingent"."time_frame"
3987 ) ELSE NULL END AS "initiative_count",
3988 "contingent"."initiative_limit"
3989 FROM "member" CROSS JOIN "contingent";
3991 COMMENT ON VIEW "member_contingent" IS 'Actual counts of text entries and initiatives are calculated per member for each limit in the "contingent" table.';
3993 COMMENT ON COLUMN "member_contingent"."text_entry_count" IS 'Only calculated when "text_entry_limit" is not null in the same row';
3994 COMMENT ON COLUMN "member_contingent"."initiative_count" IS 'Only calculated when "initiative_limit" is not null in the same row';
3997 CREATE VIEW "member_contingent_left" AS
3998 SELECT
3999 "member_id",
4000 "polling",
4001 max("text_entry_limit" - "text_entry_count") AS "text_entries_left",
4002 max("initiative_limit" - "initiative_count") AS "initiatives_left"
4003 FROM "member_contingent" GROUP BY "member_id", "polling";
4005 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.';
4008 CREATE VIEW "event_for_notification" AS
4009 SELECT
4010 "member"."id" AS "recipient_id",
4011 "event".*
4012 FROM "member" CROSS JOIN "event"
4013 JOIN "issue" ON "issue"."id" = "event"."issue_id"
4014 JOIN "area" ON "area"."id" = "issue"."area_id"
4015 LEFT JOIN "privilege" ON
4016 "privilege"."member_id" = "member"."id" AND
4017 "privilege"."unit_id" = "area"."unit_id" AND
4018 "privilege"."voting_right" = TRUE
4019 LEFT JOIN "subscription" ON
4020 "subscription"."member_id" = "member"."id" AND
4021 "subscription"."unit_id" = "area"."unit_id"
4022 LEFT JOIN "ignored_area" ON
4023 "ignored_area"."member_id" = "member"."id" AND
4024 "ignored_area"."area_id" = "issue"."area_id"
4025 LEFT JOIN "interest" ON
4026 "interest"."member_id" = "member"."id" AND
4027 "interest"."issue_id" = "event"."issue_id"
4028 LEFT JOIN "supporter" ON
4029 "supporter"."member_id" = "member"."id" AND
4030 "supporter"."initiative_id" = "event"."initiative_id"
4031 WHERE ("privilege"."member_id" NOTNULL OR "subscription"."member_id" NOTNULL)
4032 AND ("ignored_area"."member_id" ISNULL OR "interest"."member_id" NOTNULL)
4033 AND (
4034 "event"."event" = 'issue_state_changed'::"event_type" OR
4035 ( "event"."event" = 'initiative_revoked'::"event_type" AND
4036 "supporter"."member_id" NOTNULL ) );
4038 COMMENT ON VIEW "event_for_notification" IS 'Entries of the "event" table which are of interest for a particular notification mail recipient';
4040 COMMENT ON COLUMN "event_for_notification"."recipient_id" IS 'member_id of the recipient of a notification mail';
4043 CREATE VIEW "updated_initiative" AS
4044 SELECT
4045 "supporter"."member_id" AS "recipient_id",
4046 FALSE AS "featured",
4047 "supporter"."initiative_id"
4048 FROM "supporter"
4049 JOIN "initiative" ON "supporter"."initiative_id" = "initiative"."id"
4050 JOIN "issue" ON "issue"."id" = "initiative"."issue_id"
4051 LEFT JOIN "notification_initiative_sent" AS "sent" ON
4052 "sent"."member_id" = "supporter"."member_id" AND
4053 "sent"."initiative_id" = "supporter"."initiative_id"
4054 LEFT JOIN "ignored_initiative" ON
4055 "ignored_initiative"."member_id" = "supporter"."member_id" AND
4056 "ignored_initiative"."initiative_id" = "supporter"."initiative_id"
4057 WHERE "issue"."state" IN ('admission', 'discussion')
4058 AND "initiative"."revoked" ISNULL
4059 AND "ignored_initiative"."member_id" ISNULL
4060 AND (
4061 EXISTS (
4062 SELECT NULL FROM "draft"
4063 LEFT JOIN "ignored_member" ON
4064 "ignored_member"."member_id" = "supporter"."member_id" AND
4065 "ignored_member"."other_member_id" = "draft"."author_id"
4066 WHERE "draft"."initiative_id" = "supporter"."initiative_id"
4067 AND "draft"."id" > "supporter"."draft_id"
4068 AND "ignored_member"."member_id" ISNULL
4069 ) OR EXISTS (
4070 SELECT NULL FROM "suggestion"
4071 LEFT JOIN "opinion" ON
4072 "opinion"."member_id" = "supporter"."member_id" AND
4073 "opinion"."suggestion_id" = "suggestion"."id"
4074 LEFT JOIN "ignored_member" ON
4075 "ignored_member"."member_id" = "supporter"."member_id" AND
4076 "ignored_member"."other_member_id" = "suggestion"."author_id"
4077 WHERE "suggestion"."initiative_id" = "supporter"."initiative_id"
4078 AND "opinion"."member_id" ISNULL
4079 AND COALESCE("suggestion"."id" > "sent"."last_suggestion_id", TRUE)
4080 AND "ignored_member"."member_id" ISNULL
4082 );
4084 COMMENT ON VIEW "updated_initiative" IS 'Helper view for view "updated_or_featured_initiative"';
4087 CREATE FUNCTION "featured_initiative"
4088 ( "recipient_id_p" "member"."id"%TYPE,
4089 "area_id_p" "area"."id"%TYPE )
4090 RETURNS SETOF "initiative"."id"%TYPE
4091 LANGUAGE 'plpgsql' STABLE AS $$
4092 DECLARE
4093 "counter_v" "member"."notification_counter"%TYPE;
4094 "sample_size_v" "member"."notification_sample_size"%TYPE;
4095 "initiative_id_ary" INT4[]; --"initiative"."id"%TYPE[]
4096 "match_v" BOOLEAN;
4097 "member_id_v" "member"."id"%TYPE;
4098 "seed_v" TEXT;
4099 "initiative_id_v" "initiative"."id"%TYPE;
4100 BEGIN
4101 SELECT "notification_counter", "notification_sample_size"
4102 INTO "counter_v", "sample_size_v"
4103 FROM "member" WHERE "id" = "recipient_id_p";
4104 IF COALESCE("sample_size_v" <= 0, TRUE) THEN
4105 RETURN;
4106 END IF;
4107 "initiative_id_ary" := '{}';
4108 LOOP
4109 "match_v" := FALSE;
4110 FOR "member_id_v", "seed_v" IN
4111 SELECT * FROM (
4112 SELECT DISTINCT
4113 "supporter"."member_id",
4114 md5(
4115 "recipient_id_p" || '-' ||
4116 "counter_v" || '-' ||
4117 "area_id_p" || '-' ||
4118 "supporter"."member_id"
4119 ) AS "seed"
4120 FROM "supporter"
4121 JOIN "initiative" ON "initiative"."id" = "supporter"."initiative_id"
4122 JOIN "issue" ON "issue"."id" = "initiative"."issue_id"
4123 WHERE "supporter"."member_id" != "recipient_id_p"
4124 AND "issue"."area_id" = "area_id_p"
4125 AND "issue"."state" IN ('admission', 'discussion', 'verification')
4126 ) AS "subquery"
4127 ORDER BY "seed"
4128 LOOP
4129 SELECT "initiative"."id" INTO "initiative_id_v"
4130 FROM "initiative"
4131 JOIN "issue" ON "issue"."id" = "initiative"."issue_id"
4132 JOIN "area" ON "area"."id" = "issue"."area_id"
4133 JOIN "supporter" ON "supporter"."initiative_id" = "initiative"."id"
4134 LEFT JOIN "supporter" AS "self_support" ON
4135 "self_support"."initiative_id" = "initiative"."id" AND
4136 "self_support"."member_id" = "recipient_id_p"
4137 LEFT JOIN "privilege" ON
4138 "privilege"."member_id" = "recipient_id_p" AND
4139 "privilege"."unit_id" = "area"."unit_id" AND
4140 "privilege"."voting_right" = TRUE
4141 LEFT JOIN "subscription" ON
4142 "subscription"."member_id" = "recipient_id_p" AND
4143 "subscription"."unit_id" = "area"."unit_id"
4144 LEFT JOIN "ignored_initiative" ON
4145 "ignored_initiative"."member_id" = "recipient_id_p" AND
4146 "ignored_initiative"."initiative_id" = "initiative"."id"
4147 WHERE "supporter"."member_id" = "member_id_v"
4148 AND "issue"."area_id" = "area_id_p"
4149 AND "issue"."state" IN ('admission', 'discussion', 'verification')
4150 AND "initiative"."revoked" ISNULL
4151 AND "self_support"."member_id" ISNULL
4152 AND NOT "initiative_id_ary" @> ARRAY["initiative"."id"]
4153 AND (
4154 "privilege"."member_id" NOTNULL OR
4155 "subscription"."member_id" NOTNULL )
4156 AND "ignored_initiative"."member_id" ISNULL
4157 AND NOT EXISTS (
4158 SELECT NULL FROM "draft"
4159 JOIN "ignored_member" ON
4160 "ignored_member"."member_id" = "recipient_id_p" AND
4161 "ignored_member"."other_member_id" = "draft"."author_id"
4162 WHERE "draft"."initiative_id" = "initiative"."id"
4164 ORDER BY md5("seed_v" || '-' || "initiative"."id")
4165 LIMIT 1;
4166 IF FOUND THEN
4167 "match_v" := TRUE;
4168 RETURN NEXT "initiative_id_v";
4169 IF array_length("initiative_id_ary", 1) + 1 >= "sample_size_v" THEN
4170 RETURN;
4171 END IF;
4172 "initiative_id_ary" := "initiative_id_ary" || "initiative_id_v";
4173 END IF;
4174 END LOOP;
4175 EXIT WHEN NOT "match_v";
4176 END LOOP;
4177 RETURN;
4178 END;
4179 $$;
4181 COMMENT ON FUNCTION "featured_initiative"
4182 ( "recipient_id_p" "member"."id"%TYPE,
4183 "area_id_p" "area"."id"%TYPE )
4184 IS 'Helper function for view "updated_or_featured_initiative"';
4187 CREATE VIEW "updated_or_featured_initiative" AS
4188 SELECT
4189 "subquery".*,
4190 NOT EXISTS (
4191 SELECT NULL FROM "initiative" AS "better_initiative"
4192 WHERE "better_initiative"."issue_id" = "initiative"."issue_id"
4193 AND
4194 ( COALESCE("better_initiative"."supporter_count", -1),
4195 -"better_initiative"."id" ) >
4196 ( COALESCE("initiative"."supporter_count", -1),
4197 -"initiative"."id" )
4198 ) AS "leading"
4199 FROM (
4200 SELECT * FROM "updated_initiative"
4201 UNION ALL
4202 SELECT
4203 "member"."id" AS "recipient_id",
4204 TRUE AS "featured",
4205 "featured_initiative_id" AS "initiative_id"
4206 FROM "member" CROSS JOIN "area"
4207 CROSS JOIN LATERAL
4208 "featured_initiative"("member"."id", "area"."id") AS "featured_initiative_id"
4209 JOIN "initiative" ON "initiative"."id" = "featured_initiative_id"
4210 ) AS "subquery"
4211 JOIN "initiative" ON "initiative"."id" = "subquery"."initiative_id";
4213 COMMENT ON VIEW "updated_or_featured_initiative" IS 'Initiatives to be included in a scheduled notification mail because (a) they have been updated or (b) they are featured';
4215 COMMENT ON COLUMN "updated_or_featured_initiative"."recipient_id" IS '"id" of the member who receives the notification mail';
4216 COMMENT ON COLUMN "updated_or_featured_initiative"."featured" IS 'TRUE if the initiative has been included because it was selected by the "featured_initiative" algorithm (see source of function "featured_initiative")';
4217 COMMENT ON COLUMN "updated_or_featured_initiative"."initiative_id" IS '"id" of the initiative to be included in the notification mail';
4218 COMMENT ON COLUMN "updated_or_featured_initiative"."leading" IS 'TRUE if the initiative has the highest "supporter_count" in the issue';
4221 CREATE VIEW "leading_complement_initiative" AS
4222 SELECT * FROM (
4223 SELECT DISTINCT ON ("uf_initiative"."recipient_id", "initiative"."issue_id")
4224 "uf_initiative"."recipient_id",
4225 FALSE AS "featured",
4226 "uf_initiative"."initiative_id",
4227 TRUE AS "leading"
4228 FROM "updated_or_featured_initiative" AS "uf_initiative"
4229 JOIN "initiative" AS "uf_initiative_full" ON
4230 "uf_initiative_full"."id" = "uf_initiative"."initiative_id"
4231 JOIN "initiative" ON
4232 "initiative"."issue_id" = "uf_initiative_full"."issue_id"
4233 WHERE "initiative"."revoked" ISNULL
4234 ORDER BY
4235 "uf_initiative"."recipient_id",
4236 "initiative"."issue_id",
4237 "initiative"."supporter_count" DESC,
4238 "initiative"."id"
4239 ) AS "subquery"
4240 WHERE NOT EXISTS (
4241 SELECT NULL FROM "updated_or_featured_initiative" AS "other"
4242 WHERE "other"."recipient_id" = "subquery"."recipient_id"
4243 AND "other"."initiative_id" = "subquery"."initiative_id"
4244 );
4246 COMMENT ON VIEW "leading_complement_initiative" IS 'Helper view for view "unfiltered_initiative_for_notification" in order to always include the most supported initiative of an issue';
4247 COMMENT ON COLUMN "leading_complement_initiative"."featured" IS 'Always FALSE in this view';
4248 COMMENT ON COLUMN "leading_complement_initiative"."initiative_id" IS '"id" of the initiative to be included in the notification mail';
4249 COMMENT ON COLUMN "leading_complement_initiative"."leading" IS 'Always TRUE in this view';
4252 CREATE VIEW "unfiltered_initiative_for_notification" AS
4253 SELECT
4254 "subquery".*,
4255 "supporter"."member_id" NOTNULL AS "supported",
4256 CASE WHEN "supporter"."member_id" NOTNULL THEN
4257 EXISTS (
4258 SELECT NULL FROM "draft"
4259 WHERE "draft"."initiative_id" = "subquery"."initiative_id"
4260 AND "draft"."id" > "supporter"."draft_id"
4262 ELSE
4263 EXISTS (
4264 SELECT NULL FROM "draft"
4265 WHERE "draft"."initiative_id" = "subquery"."initiative_id"
4266 AND COALESCE("draft"."id" > "sent"."last_draft_id", TRUE)
4268 END AS "new_draft",
4269 CASE WHEN "supporter"."member_id" NOTNULL THEN
4270 ( SELECT count(1) FROM "suggestion"
4271 LEFT JOIN "opinion" ON
4272 "opinion"."member_id" = "supporter"."member_id" AND
4273 "opinion"."suggestion_id" = "suggestion"."id"
4274 WHERE "suggestion"."initiative_id" = "subquery"."initiative_id"
4275 AND "opinion"."member_id" ISNULL
4276 AND COALESCE("suggestion"."id" > "sent"."last_suggestion_id", TRUE)
4278 ELSE
4279 ( SELECT count(1) FROM "suggestion"
4280 WHERE "suggestion"."initiative_id" = "subquery"."initiative_id"
4281 AND COALESCE("suggestion"."id" > "sent"."last_suggestion_id", TRUE)
4283 END AS "new_suggestion_count"
4284 FROM (
4285 SELECT * FROM "updated_or_featured_initiative"
4286 UNION ALL
4287 SELECT * FROM "leading_complement_initiative"
4288 ) AS "subquery"
4289 LEFT JOIN "supporter" ON
4290 "supporter"."member_id" = "subquery"."recipient_id" AND
4291 "supporter"."initiative_id" = "subquery"."initiative_id"
4292 LEFT JOIN "notification_initiative_sent" AS "sent" ON
4293 "sent"."member_id" = "subquery"."recipient_id" AND
4294 "sent"."initiative_id" = "subquery"."initiative_id";
4296 COMMENT ON VIEW "unfiltered_initiative_for_notification" IS 'Helper view which simply combines the views "updated_or_featured_initiative" and "leading_complement_initiative" and adds columns "supported", "new_draft", and "new_suggestion_count';
4298 COMMENT ON COLUMN "unfiltered_initiative_for_notification"."supported" IS 'TRUE if initiative is supported by the recipient';
4299 COMMENT ON COLUMN "unfiltered_initiative_for_notification"."new_draft" IS 'TRUE if a new draft exists (using the "draft_id" column of the "supporter" table in case of "supported" initiatives and the "last_draft_id" column of the "notification_initiative_sent" table in all other cases)';
4300 COMMENT ON COLUMN "unfiltered_initiative_for_notification"."new_suggestion_count" IS 'Number of new suggestions (using the "last_suggestion_id" column of the "notification_initiative_sent" table while ignoring suggestions with an "opinion")';
4303 CREATE VIEW "initiative_for_notification" AS
4304 SELECT "unfiltered1".*
4305 FROM "unfiltered_initiative_for_notification" "unfiltered1"
4306 JOIN "initiative" AS "initiative1" ON
4307 "initiative1"."id" = "unfiltered1"."initiative_id"
4308 JOIN "issue" AS "issue1" ON "issue1"."id" = "initiative1"."issue_id"
4309 WHERE EXISTS (
4310 SELECT NULL
4311 FROM "unfiltered_initiative_for_notification" "unfiltered2"
4312 JOIN "initiative" AS "initiative2" ON
4313 "initiative2"."id" = "unfiltered2"."initiative_id"
4314 JOIN "issue" AS "issue2" ON "issue2"."id" = "initiative2"."issue_id"
4315 WHERE "unfiltered1"."recipient_id" = "unfiltered2"."recipient_id"
4316 AND "issue1"."area_id" = "issue2"."area_id"
4317 AND ("unfiltered2"."new_draft" OR "unfiltered2"."new_suggestion_count" > 0 )
4318 );
4320 COMMENT ON VIEW "initiative_for_notification" IS 'Initiatives to be included in a scheduled notification mail';
4322 COMMENT ON COLUMN "initiative_for_notification"."recipient_id" IS '"id" of the member who receives the notification mail';
4323 COMMENT ON COLUMN "initiative_for_notification"."featured" IS 'TRUE if the initiative has been included because it was selected by the "featured_initiative" algorithm (see source of function "featured_initiative")';
4324 COMMENT ON COLUMN "initiative_for_notification"."initiative_id" IS '"id" of the initiative to be included in the notification mail';
4325 COMMENT ON COLUMN "initiative_for_notification"."leading" IS 'TRUE if the initiative has the highest "supporter_count" in the issue';
4326 COMMENT ON COLUMN "initiative_for_notification"."supported" IS 'TRUE if initiative is supported by the recipient';
4327 COMMENT ON COLUMN "initiative_for_notification"."new_draft" IS 'TRUE if a new draft exists (using the "draft_id" column of the "supporter" table in case of "supported" initiatives and the "last_draft_id" column of the "notification_initiative_sent" table in all other cases)';
4328 COMMENT ON COLUMN "initiative_for_notification"."new_suggestion_count" IS 'Number of new suggestions (using the "last_suggestion_id" column of the "notification_initiative_sent" table while ignoring suggestions with an "opinion")';
4331 CREATE VIEW "scheduled_notification_to_send" AS
4332 SELECT * FROM (
4333 SELECT
4334 "id" AS "recipient_id",
4335 now() - CASE WHEN "notification_dow" ISNULL THEN
4336 ( "notification_sent"::DATE + CASE
4337 WHEN EXTRACT(HOUR FROM "notification_sent") < "notification_hour"
4338 THEN 0 ELSE 1 END
4339 )::TIMESTAMP + '1 hour'::INTERVAL * "notification_hour"
4340 ELSE
4341 ( "notification_sent"::DATE +
4342 ( 7 + "notification_dow" -
4343 EXTRACT(DOW FROM
4344 ( "notification_sent"::DATE + CASE
4345 WHEN EXTRACT(HOUR FROM "notification_sent") < "notification_hour"
4346 THEN 0 ELSE 1 END
4347 )::TIMESTAMP + '1 hour'::INTERVAL * "notification_hour"
4348 )::INTEGER
4349 ) % 7 +
4350 CASE
4351 WHEN EXTRACT(HOUR FROM "notification_sent") < "notification_hour"
4352 THEN 0 ELSE 1
4353 END
4354 )::TIMESTAMP + '1 hour'::INTERVAL * "notification_hour"
4355 END AS "pending"
4356 FROM (
4357 SELECT
4358 "id",
4359 COALESCE("notification_sent", "activated") AS "notification_sent",
4360 "notification_dow",
4361 "notification_hour"
4362 FROM "member_to_notify"
4363 WHERE "notification_hour" NOTNULL
4364 ) AS "subquery1"
4365 ) AS "subquery2"
4366 WHERE "pending" > '0'::INTERVAL;
4368 COMMENT ON VIEW "scheduled_notification_to_send" IS 'Set of members where a scheduled notification mail is pending';
4370 COMMENT ON COLUMN "scheduled_notification_to_send"."recipient_id" IS '"id" of the member who needs to receive a notification mail';
4371 COMMENT ON COLUMN "scheduled_notification_to_send"."pending" IS 'Duration for which the notification mail has already been pending';
4374 CREATE VIEW "newsletter_to_send" AS
4375 SELECT
4376 "member"."id" AS "recipient_id",
4377 "newsletter"."id" AS "newsletter_id",
4378 "newsletter"."published"
4379 FROM "newsletter" CROSS JOIN "member_eligible_to_be_notified" AS "member"
4380 LEFT JOIN "privilege" ON
4381 "privilege"."member_id" = "member"."id" AND
4382 "privilege"."unit_id" = "newsletter"."unit_id" AND
4383 "privilege"."voting_right" = TRUE
4384 LEFT JOIN "subscription" ON
4385 "subscription"."member_id" = "member"."id" AND
4386 "subscription"."unit_id" = "newsletter"."unit_id"
4387 WHERE "newsletter"."published" <= now()
4388 AND "newsletter"."sent" ISNULL
4389 AND (
4390 "member"."disable_notifications" = FALSE OR
4391 "newsletter"."include_all_members" = TRUE )
4392 AND (
4393 "newsletter"."unit_id" ISNULL OR
4394 "privilege"."member_id" NOTNULL OR
4395 "subscription"."member_id" NOTNULL );
4397 COMMENT ON VIEW "newsletter_to_send" IS 'List of "newsletter_id"s for each member that are due to be sent out';
4399 COMMENT ON COLUMN "newsletter"."published" IS 'Timestamp when the newsletter was supposed to be sent out (can be used for ordering)';
4403 ------------------------------------------------------
4404 -- Row set returning function for delegation chains --
4405 ------------------------------------------------------
4408 CREATE TYPE "delegation_chain_loop_tag" AS ENUM
4409 ('first', 'intermediate', 'last', 'repetition');
4411 COMMENT ON TYPE "delegation_chain_loop_tag" IS 'Type for loop tags in "delegation_chain_row" type';
4414 CREATE TYPE "delegation_chain_row" AS (
4415 "index" INT4,
4416 "member_id" INT4,
4417 "member_valid" BOOLEAN,
4418 "participation" BOOLEAN,
4419 "overridden" BOOLEAN,
4420 "scope_in" "delegation_scope",
4421 "scope_out" "delegation_scope",
4422 "disabled_out" BOOLEAN,
4423 "loop" "delegation_chain_loop_tag" );
4425 COMMENT ON TYPE "delegation_chain_row" IS 'Type of rows returned by "delegation_chain" function';
4427 COMMENT ON COLUMN "delegation_chain_row"."index" IS 'Index starting with 0 and counting up';
4428 COMMENT ON COLUMN "delegation_chain_row"."participation" IS 'In case of delegation chains for issues: interest; for area and global delegation chains: always null';
4429 COMMENT ON COLUMN "delegation_chain_row"."overridden" IS 'True, if an entry with lower index has "participation" set to true';
4430 COMMENT ON COLUMN "delegation_chain_row"."scope_in" IS 'Scope of used incoming delegation';
4431 COMMENT ON COLUMN "delegation_chain_row"."scope_out" IS 'Scope of used outgoing delegation';
4432 COMMENT ON COLUMN "delegation_chain_row"."disabled_out" IS 'Outgoing delegation is explicitly disabled by a delegation with trustee_id set to NULL';
4433 COMMENT ON COLUMN "delegation_chain_row"."loop" IS 'Not null, if member is part of a loop, see "delegation_chain_loop_tag" type';
4436 CREATE FUNCTION "delegation_chain_for_closed_issue"
4437 ( "member_id_p" "member"."id"%TYPE,
4438 "issue_id_p" "issue"."id"%TYPE )
4439 RETURNS SETOF "delegation_chain_row"
4440 LANGUAGE 'plpgsql' STABLE AS $$
4441 DECLARE
4442 "output_row" "delegation_chain_row";
4443 "direct_voter_row" "direct_voter"%ROWTYPE;
4444 "delegating_voter_row" "delegating_voter"%ROWTYPE;
4445 BEGIN
4446 "output_row"."index" := 0;
4447 "output_row"."member_id" := "member_id_p";
4448 "output_row"."member_valid" := TRUE;
4449 "output_row"."participation" := FALSE;
4450 "output_row"."overridden" := FALSE;
4451 "output_row"."disabled_out" := FALSE;
4452 LOOP
4453 SELECT INTO "direct_voter_row" * FROM "direct_voter"
4454 WHERE "issue_id" = "issue_id_p"
4455 AND "member_id" = "output_row"."member_id";
4456 IF "direct_voter_row"."member_id" NOTNULL THEN
4457 "output_row"."participation" := TRUE;
4458 "output_row"."scope_out" := NULL;
4459 "output_row"."disabled_out" := NULL;
4460 RETURN NEXT "output_row";
4461 RETURN;
4462 END IF;
4463 SELECT INTO "delegating_voter_row" * FROM "delegating_voter"
4464 WHERE "issue_id" = "issue_id_p"
4465 AND "member_id" = "output_row"."member_id";
4466 IF "delegating_voter_row"."member_id" ISNULL THEN
4467 RETURN;
4468 END IF;
4469 "output_row"."scope_out" := "delegating_voter_row"."scope";
4470 RETURN NEXT "output_row";
4471 "output_row"."member_id" := "delegating_voter_row"."delegate_member_ids"[1];
4472 "output_row"."scope_in" := "output_row"."scope_out";
4473 END LOOP;
4474 END;
4475 $$;
4477 COMMENT ON FUNCTION "delegation_chain_for_closed_issue"
4478 ( "member"."id"%TYPE,
4479 "member"."id"%TYPE )
4480 IS 'Helper function for "delegation_chain" function, handling the special case of closed issues after voting';
4483 CREATE FUNCTION "delegation_chain"
4484 ( "member_id_p" "member"."id"%TYPE,
4485 "unit_id_p" "unit"."id"%TYPE,
4486 "area_id_p" "area"."id"%TYPE,
4487 "issue_id_p" "issue"."id"%TYPE,
4488 "simulate_trustee_id_p" "member"."id"%TYPE DEFAULT NULL,
4489 "simulate_default_p" BOOLEAN DEFAULT FALSE )
4490 RETURNS SETOF "delegation_chain_row"
4491 LANGUAGE 'plpgsql' STABLE AS $$
4492 DECLARE
4493 "scope_v" "delegation_scope";
4494 "unit_id_v" "unit"."id"%TYPE;
4495 "area_id_v" "area"."id"%TYPE;
4496 "issue_row" "issue"%ROWTYPE;
4497 "visited_member_ids" INT4[]; -- "member"."id"%TYPE[]
4498 "loop_member_id_v" "member"."id"%TYPE;
4499 "output_row" "delegation_chain_row";
4500 "output_rows" "delegation_chain_row"[];
4501 "simulate_v" BOOLEAN;
4502 "simulate_here_v" BOOLEAN;
4503 "delegation_row" "delegation"%ROWTYPE;
4504 "row_count" INT4;
4505 "i" INT4;
4506 "loop_v" BOOLEAN;
4507 BEGIN
4508 IF "simulate_trustee_id_p" NOTNULL AND "simulate_default_p" THEN
4509 RAISE EXCEPTION 'Both "simulate_trustee_id_p" is set, and "simulate_default_p" is true';
4510 END IF;
4511 IF "simulate_trustee_id_p" NOTNULL OR "simulate_default_p" THEN
4512 "simulate_v" := TRUE;
4513 ELSE
4514 "simulate_v" := FALSE;
4515 END IF;
4516 IF
4517 "unit_id_p" NOTNULL AND
4518 "area_id_p" ISNULL AND
4519 "issue_id_p" ISNULL
4520 THEN
4521 "scope_v" := 'unit';
4522 "unit_id_v" := "unit_id_p";
4523 ELSIF
4524 "unit_id_p" ISNULL AND
4525 "area_id_p" NOTNULL AND
4526 "issue_id_p" ISNULL
4527 THEN
4528 "scope_v" := 'area';
4529 "area_id_v" := "area_id_p";
4530 SELECT "unit_id" INTO "unit_id_v"
4531 FROM "area" WHERE "id" = "area_id_v";
4532 ELSIF
4533 "unit_id_p" ISNULL AND
4534 "area_id_p" ISNULL AND
4535 "issue_id_p" NOTNULL
4536 THEN
4537 SELECT INTO "issue_row" * FROM "issue" WHERE "id" = "issue_id_p";
4538 IF "issue_row"."id" ISNULL THEN
4539 RETURN;
4540 END IF;
4541 IF "issue_row"."closed" NOTNULL THEN
4542 IF "simulate_v" THEN
4543 RAISE EXCEPTION 'Tried to simulate delegation chain for closed issue.';
4544 END IF;
4545 FOR "output_row" IN
4546 SELECT * FROM
4547 "delegation_chain_for_closed_issue"("member_id_p", "issue_id_p")
4548 LOOP
4549 RETURN NEXT "output_row";
4550 END LOOP;
4551 RETURN;
4552 END IF;
4553 "scope_v" := 'issue';
4554 SELECT "area_id" INTO "area_id_v"
4555 FROM "issue" WHERE "id" = "issue_id_p";
4556 SELECT "unit_id" INTO "unit_id_v"
4557 FROM "area" WHERE "id" = "area_id_v";
4558 ELSE
4559 RAISE EXCEPTION 'Exactly one of unit_id_p, area_id_p, or issue_id_p must be NOTNULL.';
4560 END IF;
4561 "visited_member_ids" := '{}';
4562 "loop_member_id_v" := NULL;
4563 "output_rows" := '{}';
4564 "output_row"."index" := 0;
4565 "output_row"."member_id" := "member_id_p";
4566 "output_row"."member_valid" := TRUE;
4567 "output_row"."participation" := FALSE;
4568 "output_row"."overridden" := FALSE;
4569 "output_row"."disabled_out" := FALSE;
4570 "output_row"."scope_out" := NULL;
4571 LOOP
4572 IF "visited_member_ids" @> ARRAY["output_row"."member_id"] THEN
4573 "loop_member_id_v" := "output_row"."member_id";
4574 ELSE
4575 "visited_member_ids" :=
4576 "visited_member_ids" || "output_row"."member_id";
4577 END IF;
4578 IF "output_row"."participation" ISNULL THEN
4579 "output_row"."overridden" := NULL;
4580 ELSIF "output_row"."participation" THEN
4581 "output_row"."overridden" := TRUE;
4582 END IF;
4583 "output_row"."scope_in" := "output_row"."scope_out";
4584 "output_row"."member_valid" := EXISTS (
4585 SELECT NULL FROM "member" JOIN "privilege"
4586 ON "privilege"."member_id" = "member"."id"
4587 AND "privilege"."unit_id" = "unit_id_v"
4588 WHERE "id" = "output_row"."member_id"
4589 AND "member"."active" AND "privilege"."voting_right"
4590 );
4591 "simulate_here_v" := (
4592 "simulate_v" AND
4593 "output_row"."member_id" = "member_id_p"
4594 );
4595 "delegation_row" := ROW(NULL);
4596 IF "output_row"."member_valid" OR "simulate_here_v" THEN
4597 IF "scope_v" = 'unit' THEN
4598 IF NOT "simulate_here_v" THEN
4599 SELECT * INTO "delegation_row" FROM "delegation"
4600 WHERE "truster_id" = "output_row"."member_id"
4601 AND "unit_id" = "unit_id_v";
4602 END IF;
4603 ELSIF "scope_v" = 'area' THEN
4604 IF "simulate_here_v" THEN
4605 IF "simulate_trustee_id_p" ISNULL THEN
4606 SELECT * INTO "delegation_row" FROM "delegation"
4607 WHERE "truster_id" = "output_row"."member_id"
4608 AND "unit_id" = "unit_id_v";
4609 END IF;
4610 ELSE
4611 SELECT * INTO "delegation_row" FROM "delegation"
4612 WHERE "truster_id" = "output_row"."member_id"
4613 AND (
4614 "unit_id" = "unit_id_v" OR
4615 "area_id" = "area_id_v"
4617 ORDER BY "scope" DESC;
4618 END IF;
4619 ELSIF "scope_v" = 'issue' THEN
4620 IF "issue_row"."fully_frozen" ISNULL THEN
4621 "output_row"."participation" := EXISTS (
4622 SELECT NULL FROM "interest"
4623 WHERE "issue_id" = "issue_id_p"
4624 AND "member_id" = "output_row"."member_id"
4625 );
4626 ELSE
4627 IF "output_row"."member_id" = "member_id_p" THEN
4628 "output_row"."participation" := EXISTS (
4629 SELECT NULL FROM "direct_voter"
4630 WHERE "issue_id" = "issue_id_p"
4631 AND "member_id" = "output_row"."member_id"
4632 );
4633 ELSE
4634 "output_row"."participation" := NULL;
4635 END IF;
4636 END IF;
4637 IF "simulate_here_v" THEN
4638 IF "simulate_trustee_id_p" ISNULL THEN
4639 SELECT * INTO "delegation_row" FROM "delegation"
4640 WHERE "truster_id" = "output_row"."member_id"
4641 AND (
4642 "unit_id" = "unit_id_v" OR
4643 "area_id" = "area_id_v"
4645 ORDER BY "scope" DESC;
4646 END IF;
4647 ELSE
4648 SELECT * INTO "delegation_row" FROM "delegation"
4649 WHERE "truster_id" = "output_row"."member_id"
4650 AND (
4651 "unit_id" = "unit_id_v" OR
4652 "area_id" = "area_id_v" OR
4653 "issue_id" = "issue_id_p"
4655 ORDER BY "scope" DESC;
4656 END IF;
4657 END IF;
4658 ELSE
4659 "output_row"."participation" := FALSE;
4660 END IF;
4661 IF "simulate_here_v" AND "simulate_trustee_id_p" NOTNULL THEN
4662 "output_row"."scope_out" := "scope_v";
4663 "output_rows" := "output_rows" || "output_row";
4664 "output_row"."member_id" := "simulate_trustee_id_p";
4665 ELSIF "delegation_row"."trustee_id" NOTNULL THEN
4666 "output_row"."scope_out" := "delegation_row"."scope";
4667 "output_rows" := "output_rows" || "output_row";
4668 "output_row"."member_id" := "delegation_row"."trustee_id";
4669 ELSIF "delegation_row"."scope" NOTNULL THEN
4670 "output_row"."scope_out" := "delegation_row"."scope";
4671 "output_row"."disabled_out" := TRUE;
4672 "output_rows" := "output_rows" || "output_row";
4673 EXIT;
4674 ELSE
4675 "output_row"."scope_out" := NULL;
4676 "output_rows" := "output_rows" || "output_row";
4677 EXIT;
4678 END IF;
4679 EXIT WHEN "loop_member_id_v" NOTNULL;
4680 "output_row"."index" := "output_row"."index" + 1;
4681 END LOOP;
4682 "row_count" := array_upper("output_rows", 1);
4683 "i" := 1;
4684 "loop_v" := FALSE;
4685 LOOP
4686 "output_row" := "output_rows"["i"];
4687 EXIT WHEN "output_row" ISNULL; -- NOTE: ISNULL and NOT ... NOTNULL produce different results!
4688 IF "loop_v" THEN
4689 IF "i" + 1 = "row_count" THEN
4690 "output_row"."loop" := 'last';
4691 ELSIF "i" = "row_count" THEN
4692 "output_row"."loop" := 'repetition';
4693 ELSE
4694 "output_row"."loop" := 'intermediate';
4695 END IF;
4696 ELSIF "output_row"."member_id" = "loop_member_id_v" THEN
4697 "output_row"."loop" := 'first';
4698 "loop_v" := TRUE;
4699 END IF;
4700 IF "scope_v" = 'unit' THEN
4701 "output_row"."participation" := NULL;
4702 END IF;
4703 RETURN NEXT "output_row";
4704 "i" := "i" + 1;
4705 END LOOP;
4706 RETURN;
4707 END;
4708 $$;
4710 COMMENT ON FUNCTION "delegation_chain"
4711 ( "member"."id"%TYPE,
4712 "unit"."id"%TYPE,
4713 "area"."id"%TYPE,
4714 "issue"."id"%TYPE,
4715 "member"."id"%TYPE,
4716 BOOLEAN )
4717 IS 'Shows a delegation chain for unit, area, or issue; See "delegation_chain_row" type for more information';
4721 ---------------------------------------------------------
4722 -- Single row returning function for delegation chains --
4723 ---------------------------------------------------------
4726 CREATE TYPE "delegation_info_loop_type" AS ENUM
4727 ('own', 'first', 'first_ellipsis', 'other', 'other_ellipsis');
4729 COMMENT ON TYPE "delegation_info_loop_type" IS 'Type of "delegation_loop" in "delegation_info_type"; ''own'' means loop to self, ''first'' means loop to first trustee, ''first_ellipsis'' means loop to ellipsis after first trustee, ''other'' means loop to other trustee, ''other_ellipsis'' means loop to ellipsis after other trustee''';
4732 CREATE TYPE "delegation_info_type" AS (
4733 "own_participation" BOOLEAN,
4734 "own_delegation_scope" "delegation_scope",
4735 "first_trustee_id" INT4,
4736 "first_trustee_participation" BOOLEAN,
4737 "first_trustee_ellipsis" BOOLEAN,
4738 "other_trustee_id" INT4,
4739 "other_trustee_participation" BOOLEAN,
4740 "other_trustee_ellipsis" BOOLEAN,
4741 "delegation_loop" "delegation_info_loop_type",
4742 "participating_member_id" INT4 );
4744 COMMENT ON TYPE "delegation_info_type" IS 'Type of result returned by "delegation_info" function; For meaning of "participation" check comment on "delegation_chain_row" type';
4746 COMMENT ON COLUMN "delegation_info_type"."own_participation" IS 'Member is directly participating';
4747 COMMENT ON COLUMN "delegation_info_type"."own_delegation_scope" IS 'Delegation scope of member';
4748 COMMENT ON COLUMN "delegation_info_type"."first_trustee_id" IS 'Direct trustee of member';
4749 COMMENT ON COLUMN "delegation_info_type"."first_trustee_participation" IS 'Direct trustee of member is participating';
4750 COMMENT ON COLUMN "delegation_info_type"."first_trustee_ellipsis" IS 'Ellipsis in delegation chain after "first_trustee"';
4751 COMMENT ON COLUMN "delegation_info_type"."other_trustee_id" IS 'Another relevant trustee (due to participation)';
4752 COMMENT ON COLUMN "delegation_info_type"."other_trustee_participation" IS 'Another trustee is participating (redundant field: if "other_trustee_id" is set, then "other_trustee_participation" is always TRUE, else "other_trustee_participation" is NULL)';
4753 COMMENT ON COLUMN "delegation_info_type"."other_trustee_ellipsis" IS 'Ellipsis in delegation chain after "other_trustee"';
4754 COMMENT ON COLUMN "delegation_info_type"."delegation_loop" IS 'Non-NULL value, if delegation chain contains a circle; See comment on "delegation_info_loop_type" for details';
4755 COMMENT ON COLUMN "delegation_info_type"."participating_member_id" IS 'First participating member in delegation chain';
4758 CREATE FUNCTION "delegation_info"
4759 ( "member_id_p" "member"."id"%TYPE,
4760 "unit_id_p" "unit"."id"%TYPE,
4761 "area_id_p" "area"."id"%TYPE,
4762 "issue_id_p" "issue"."id"%TYPE,
4763 "simulate_trustee_id_p" "member"."id"%TYPE DEFAULT NULL,
4764 "simulate_default_p" BOOLEAN DEFAULT FALSE )
4765 RETURNS "delegation_info_type"
4766 LANGUAGE 'plpgsql' STABLE AS $$
4767 DECLARE
4768 "current_row" "delegation_chain_row";
4769 "result" "delegation_info_type";
4770 BEGIN
4771 "result"."own_participation" := FALSE;
4772 FOR "current_row" IN
4773 SELECT * FROM "delegation_chain"(
4774 "member_id_p",
4775 "unit_id_p", "area_id_p", "issue_id_p",
4776 "simulate_trustee_id_p", "simulate_default_p")
4777 LOOP
4778 IF
4779 "result"."participating_member_id" ISNULL AND
4780 "current_row"."participation"
4781 THEN
4782 "result"."participating_member_id" := "current_row"."member_id";
4783 END IF;
4784 IF "current_row"."member_id" = "member_id_p" THEN
4785 "result"."own_participation" := "current_row"."participation";
4786 "result"."own_delegation_scope" := "current_row"."scope_out";
4787 IF "current_row"."loop" = 'first' THEN
4788 "result"."delegation_loop" := 'own';
4789 END IF;
4790 ELSIF
4791 "current_row"."member_valid" AND
4792 ( "current_row"."loop" ISNULL OR
4793 "current_row"."loop" != 'repetition' )
4794 THEN
4795 IF "result"."first_trustee_id" ISNULL THEN
4796 "result"."first_trustee_id" := "current_row"."member_id";
4797 "result"."first_trustee_participation" := "current_row"."participation";
4798 "result"."first_trustee_ellipsis" := FALSE;
4799 IF "current_row"."loop" = 'first' THEN
4800 "result"."delegation_loop" := 'first';
4801 END IF;
4802 ELSIF "result"."other_trustee_id" ISNULL THEN
4803 IF "current_row"."participation" AND NOT "current_row"."overridden" THEN
4804 "result"."other_trustee_id" := "current_row"."member_id";
4805 "result"."other_trustee_participation" := TRUE;
4806 "result"."other_trustee_ellipsis" := FALSE;
4807 IF "current_row"."loop" = 'first' THEN
4808 "result"."delegation_loop" := 'other';
4809 END IF;
4810 ELSE
4811 "result"."first_trustee_ellipsis" := TRUE;
4812 IF "current_row"."loop" = 'first' THEN
4813 "result"."delegation_loop" := 'first_ellipsis';
4814 END IF;
4815 END IF;
4816 ELSE
4817 "result"."other_trustee_ellipsis" := TRUE;
4818 IF "current_row"."loop" = 'first' THEN
4819 "result"."delegation_loop" := 'other_ellipsis';
4820 END IF;
4821 END IF;
4822 END IF;
4823 END LOOP;
4824 RETURN "result";
4825 END;
4826 $$;
4828 COMMENT ON FUNCTION "delegation_info"
4829 ( "member"."id"%TYPE,
4830 "unit"."id"%TYPE,
4831 "area"."id"%TYPE,
4832 "issue"."id"%TYPE,
4833 "member"."id"%TYPE,
4834 BOOLEAN )
4835 IS 'Notable information about a delegation chain for unit, area, or issue; See "delegation_info_type" for more information';
4839 ------------------------
4840 -- Geospatial lookups --
4841 ------------------------
4843 /*
4844 CREATE FUNCTION "closed_initiatives_in_bounding_box"
4845 ( "bounding_box_p" EBOX,
4846 "limit_p" INT4 )
4847 RETURNS SETOF "initiative"
4848 LANGUAGE 'plpgsql' STABLE AS $$
4849 DECLARE
4850 "limit_v" INT4;
4851 "count_v" INT4;
4852 BEGIN
4853 "limit_v" := "limit_p" + 1;
4854 LOOP
4855 SELECT count(1) INTO "count_v"
4856 FROM "initiative"
4857 JOIN "issue" ON "issue"."id" = "initiative"."issue_id"
4858 WHERE "issue"."closed" NOTNULL
4859 AND GeoJSON_to_ecluster("initiative"."location") && "bounding_box_p"
4860 LIMIT "limit_v";
4861 IF "count_v" < "limit_v" THEN
4862 RETURN QUERY SELECT "initiative".*
4863 FROM (
4864 SELECT
4865 "initiative"."id" AS "initiative_id",
4866 "issue"."closed"
4867 FROM "initiative"
4868 JOIN "issue" ON "issue"."id" = "initiative"."issue_id"
4869 WHERE "issue"."closed" NOTNULL
4870 AND GeoJSON_to_ecluster("initiative"."location") && "bounding_box_p"
4871 ) AS "subquery"
4872 JOIN "initiative" ON "initiative"."id" = "subquery"."initiative_id"
4873 ORDER BY "subquery"."closed" DESC
4874 LIMIT "limit_p";
4875 RETURN;
4876 END IF;
4877 SELECT count(1) INTO "count_v"
4878 FROM (
4879 SELECT "initiative"."id" AS "initiative_id"
4880 FROM "initiative"
4881 JOIN "issue" ON "issue"."id" = "initiative"."issue_id"
4882 WHERE "issue"."closed" NOTNULL
4883 ORDER BY "closed" DESC
4884 LIMIT "limit_v"
4885 ) AS "subquery"
4886 JOIN "initiative" ON "initiative"."id" = "subquery"."initiative_id"
4887 WHERE GeoJSON_to_ecluster("initiative"."location") && "bounding_box_p"
4888 LIMIT "limit_p";
4889 IF "count_v" >= "limit_p" THEN
4890 RETURN QUERY SELECT "initiative".*
4891 FROM (
4892 SELECT
4893 "initiative"."id" AS "initiative_id",
4894 "issue"."closed"
4895 FROM "initiative"
4896 JOIN "issue" ON "issue"."id" = "initiative"."issue_id"
4897 WHERE "issue"."closed" NOTNULL
4898 ORDER BY "closed" DESC
4899 LIMIT "limit_v"
4900 ) AS "subquery"
4901 JOIN "initiative" ON "initiative"."id" = "subquery"."initiative_id"
4902 WHERE GeoJSON_to_ecluster("initiative"."location") && "bounding_box_p"
4903 ORDER BY "subquery"."closed" DESC
4904 LIMIT "limit_p";
4905 RETURN;
4906 END IF;
4907 "limit_v" := "limit_v" * 2;
4908 END LOOP;
4909 END;
4910 $$;
4912 COMMENT ON FUNCTION "closed_initiatives_in_bounding_box"
4913 ( EBOX, INT4 )
4914 IS 'TODO';
4915 */
4919 ---------------------------
4920 -- Transaction isolation --
4921 ---------------------------
4924 CREATE FUNCTION "require_transaction_isolation"()
4925 RETURNS VOID
4926 LANGUAGE 'plpgsql' VOLATILE AS $$
4927 BEGIN
4928 IF
4929 current_setting('transaction_isolation') NOT IN
4930 ('repeatable read', 'serializable')
4931 THEN
4932 RAISE EXCEPTION 'Insufficient transaction isolation level' USING
4933 HINT = 'Consider using SET TRANSACTION ISOLATION LEVEL REPEATABLE READ.';
4934 END IF;
4935 RETURN;
4936 END;
4937 $$;
4939 COMMENT ON FUNCTION "require_transaction_isolation"() IS 'Throws an exception, if transaction isolation level is too low to provide a consistent snapshot';
4942 CREATE FUNCTION "dont_require_transaction_isolation"()
4943 RETURNS VOID
4944 LANGUAGE 'plpgsql' VOLATILE AS $$
4945 BEGIN
4946 IF
4947 current_setting('transaction_isolation') IN
4948 ('repeatable read', 'serializable')
4949 THEN
4950 RAISE WARNING 'Unneccessary transaction isolation level: %',
4951 current_setting('transaction_isolation');
4952 END IF;
4953 RETURN;
4954 END;
4955 $$;
4957 COMMENT ON FUNCTION "dont_require_transaction_isolation"() IS 'Raises a warning, if transaction isolation level is higher than READ COMMITTED';
4961 -------------------------
4962 -- Notification system --
4963 -------------------------
4965 CREATE FUNCTION "get_initiatives_for_notification"
4966 ( "recipient_id_p" "member"."id"%TYPE )
4967 RETURNS SETOF "initiative_for_notification"
4968 LANGUAGE 'plpgsql' VOLATILE AS $$
4969 DECLARE
4970 "result_row" "initiative_for_notification"%ROWTYPE;
4971 "last_draft_id_v" "draft"."id"%TYPE;
4972 "last_suggestion_id_v" "suggestion"."id"%TYPE;
4973 BEGIN
4974 PERFORM "require_transaction_isolation"();
4975 PERFORM NULL FROM "member" WHERE "id" = "recipient_id_p" FOR UPDATE;
4976 FOR "result_row" IN
4977 SELECT * FROM "initiative_for_notification"
4978 WHERE "recipient_id" = "recipient_id_p"
4979 LOOP
4980 SELECT "id" INTO "last_draft_id_v" FROM "draft"
4981 WHERE "draft"."initiative_id" = "result_row"."initiative_id"
4982 ORDER BY "id" DESC LIMIT 1;
4983 SELECT "id" INTO "last_suggestion_id_v" FROM "suggestion"
4984 WHERE "suggestion"."initiative_id" = "result_row"."initiative_id"
4985 ORDER BY "id" DESC LIMIT 1;
4986 INSERT INTO "notification_initiative_sent"
4987 ("member_id", "initiative_id", "last_draft_id", "last_suggestion_id")
4988 VALUES (
4989 "recipient_id_p",
4990 "result_row"."initiative_id",
4991 "last_draft_id_v",
4992 "last_suggestion_id_v" )
4993 ON CONFLICT ("member_id", "initiative_id") DO UPDATE SET
4994 "last_draft_id" = "last_draft_id_v",
4995 "last_suggestion_id" = "last_suggestion_id_v";
4996 RETURN NEXT "result_row";
4997 END LOOP;
4998 DELETE FROM "notification_initiative_sent"
4999 USING "initiative", "issue"
5000 WHERE "notification_initiative_sent"."member_id" = "recipient_id_p"
5001 AND "initiative"."id" = "notification_initiative_sent"."initiative_id"
5002 AND "issue"."id" = "initiative"."issue_id"
5003 AND ( "issue"."closed" NOTNULL OR "issue"."fully_frozen" NOTNULL );
5004 UPDATE "member" SET
5005 "notification_counter" = "notification_counter" + 1,
5006 "notification_sent" = now()
5007 WHERE "id" = "recipient_id_p";
5008 RETURN;
5009 END;
5010 $$;
5012 COMMENT ON FUNCTION "get_initiatives_for_notification"
5013 ( "member"."id"%TYPE )
5014 IS 'Returns rows from view "initiative_for_notification" for a given recipient while updating table "notification_initiative_sent" and columns "notification_counter" and "notification_sent" of "member" table';
5018 ------------------------------------------------------------------------
5019 -- Regular tasks, except calculcation of snapshots and voting results --
5020 ------------------------------------------------------------------------
5023 CREATE FUNCTION "check_activity"()
5024 RETURNS VOID
5025 LANGUAGE 'plpgsql' VOLATILE AS $$
5026 DECLARE
5027 "system_setting_row" "system_setting"%ROWTYPE;
5028 BEGIN
5029 PERFORM "dont_require_transaction_isolation"();
5030 SELECT * INTO "system_setting_row" FROM "system_setting";
5031 IF "system_setting_row"."member_ttl" NOTNULL THEN
5032 UPDATE "member" SET "active" = FALSE
5033 WHERE "active" = TRUE
5034 AND "last_activity" < (now() - "system_setting_row"."member_ttl")::DATE;
5035 END IF;
5036 RETURN;
5037 END;
5038 $$;
5040 COMMENT ON FUNCTION "check_activity"() IS 'Deactivates members when "last_activity" is older than "system_setting"."member_ttl".';
5043 CREATE FUNCTION "calculate_member_counts"()
5044 RETURNS VOID
5045 LANGUAGE 'plpgsql' VOLATILE AS $$
5046 BEGIN
5047 PERFORM "require_transaction_isolation"();
5048 DELETE FROM "member_count";
5049 INSERT INTO "member_count" ("total_count")
5050 SELECT "total_count" FROM "member_count_view";
5051 UPDATE "unit" SET "member_count" = "view"."member_count"
5052 FROM "unit_member_count" AS "view"
5053 WHERE "view"."unit_id" = "unit"."id";
5054 RETURN;
5055 END;
5056 $$;
5058 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 "unit_member_count"';
5062 ------------------------------------
5063 -- Calculation of harmonic weight --
5064 ------------------------------------
5067 CREATE VIEW "remaining_harmonic_supporter_weight" AS
5068 SELECT
5069 "direct_interest_snapshot"."snapshot_id",
5070 "direct_interest_snapshot"."issue_id",
5071 "direct_interest_snapshot"."member_id",
5072 "direct_interest_snapshot"."weight" AS "weight_num",
5073 count("initiative"."id") AS "weight_den"
5074 FROM "issue"
5075 JOIN "direct_interest_snapshot"
5076 ON "issue"."latest_snapshot_id" = "direct_interest_snapshot"."snapshot_id"
5077 AND "issue"."id" = "direct_interest_snapshot"."issue_id"
5078 JOIN "initiative"
5079 ON "issue"."id" = "initiative"."issue_id"
5080 AND "initiative"."harmonic_weight" ISNULL
5081 JOIN "direct_supporter_snapshot"
5082 ON "issue"."latest_snapshot_id" = "direct_supporter_snapshot"."snapshot_id"
5083 AND "initiative"."id" = "direct_supporter_snapshot"."initiative_id"
5084 AND "direct_interest_snapshot"."member_id" = "direct_supporter_snapshot"."member_id"
5085 AND (
5086 "direct_supporter_snapshot"."satisfied" = TRUE OR
5087 coalesce("initiative"."admitted", FALSE) = FALSE
5089 GROUP BY
5090 "direct_interest_snapshot"."snapshot_id",
5091 "direct_interest_snapshot"."issue_id",
5092 "direct_interest_snapshot"."member_id",
5093 "direct_interest_snapshot"."weight";
5095 COMMENT ON VIEW "remaining_harmonic_supporter_weight" IS 'Helper view for function "set_harmonic_initiative_weights"';
5098 CREATE VIEW "remaining_harmonic_initiative_weight_summands" AS
5099 SELECT
5100 "initiative"."issue_id",
5101 "initiative"."id" AS "initiative_id",
5102 "initiative"."admitted",
5103 sum("remaining_harmonic_supporter_weight"."weight_num") AS "weight_num",
5104 "remaining_harmonic_supporter_weight"."weight_den"
5105 FROM "remaining_harmonic_supporter_weight"
5106 JOIN "initiative"
5107 ON "remaining_harmonic_supporter_weight"."issue_id" = "initiative"."issue_id"
5108 AND "initiative"."harmonic_weight" ISNULL
5109 JOIN "direct_supporter_snapshot"
5110 ON "remaining_harmonic_supporter_weight"."snapshot_id" = "direct_supporter_snapshot"."snapshot_id"
5111 AND "initiative"."id" = "direct_supporter_snapshot"."initiative_id"
5112 AND "remaining_harmonic_supporter_weight"."member_id" = "direct_supporter_snapshot"."member_id"
5113 AND (
5114 "direct_supporter_snapshot"."satisfied" = TRUE OR
5115 coalesce("initiative"."admitted", FALSE) = FALSE
5117 GROUP BY
5118 "initiative"."issue_id",
5119 "initiative"."id",
5120 "initiative"."admitted",
5121 "remaining_harmonic_supporter_weight"."weight_den";
5123 COMMENT ON VIEW "remaining_harmonic_initiative_weight_summands" IS 'Helper view for function "set_harmonic_initiative_weights"';
5126 CREATE VIEW "remaining_harmonic_initiative_weight_dummies" AS
5127 SELECT
5128 "issue_id",
5129 "id" AS "initiative_id",
5130 "admitted",
5131 0 AS "weight_num",
5132 1 AS "weight_den"
5133 FROM "initiative"
5134 WHERE "harmonic_weight" ISNULL;
5136 COMMENT ON VIEW "remaining_harmonic_initiative_weight_dummies" IS 'Helper view for function "set_harmonic_initiative_weights" providing dummy weights of zero value, which are needed for corner cases where there are no supporters for an initiative at all';
5139 CREATE FUNCTION "set_harmonic_initiative_weights"
5140 ( "issue_id_p" "issue"."id"%TYPE )
5141 RETURNS VOID
5142 LANGUAGE 'plpgsql' VOLATILE AS $$
5143 DECLARE
5144 "weight_row" "remaining_harmonic_initiative_weight_summands"%ROWTYPE;
5145 "i" INT4;
5146 "count_v" INT4;
5147 "summand_v" FLOAT;
5148 "id_ary" INT4[];
5149 "weight_ary" FLOAT[];
5150 "min_weight_v" FLOAT;
5151 BEGIN
5152 PERFORM "require_transaction_isolation"();
5153 UPDATE "initiative" SET "harmonic_weight" = NULL
5154 WHERE "issue_id" = "issue_id_p";
5155 LOOP
5156 "min_weight_v" := NULL;
5157 "i" := 0;
5158 "count_v" := 0;
5159 FOR "weight_row" IN
5160 SELECT * FROM "remaining_harmonic_initiative_weight_summands"
5161 WHERE "issue_id" = "issue_id_p"
5162 AND (
5163 coalesce("admitted", FALSE) = FALSE OR NOT EXISTS (
5164 SELECT NULL FROM "initiative"
5165 WHERE "issue_id" = "issue_id_p"
5166 AND "harmonic_weight" ISNULL
5167 AND coalesce("admitted", FALSE) = FALSE
5170 UNION ALL -- needed for corner cases
5171 SELECT * FROM "remaining_harmonic_initiative_weight_dummies"
5172 WHERE "issue_id" = "issue_id_p"
5173 AND (
5174 coalesce("admitted", FALSE) = FALSE OR NOT EXISTS (
5175 SELECT NULL FROM "initiative"
5176 WHERE "issue_id" = "issue_id_p"
5177 AND "harmonic_weight" ISNULL
5178 AND coalesce("admitted", FALSE) = FALSE
5181 ORDER BY "initiative_id" DESC, "weight_den" DESC
5182 -- NOTE: non-admitted initiatives placed first (at last positions),
5183 -- latest initiatives treated worse in case of tie
5184 LOOP
5185 "summand_v" := "weight_row"."weight_num"::FLOAT / "weight_row"."weight_den"::FLOAT;
5186 IF "i" = 0 OR "weight_row"."initiative_id" != "id_ary"["i"] THEN
5187 "i" := "i" + 1;
5188 "count_v" := "i";
5189 "id_ary"["i"] := "weight_row"."initiative_id";
5190 "weight_ary"["i"] := "summand_v";
5191 ELSE
5192 "weight_ary"["i"] := "weight_ary"["i"] + "summand_v";
5193 END IF;
5194 END LOOP;
5195 EXIT WHEN "count_v" = 0;
5196 "i" := 1;
5197 LOOP
5198 "weight_ary"["i"] := "weight_ary"["i"]::NUMERIC(18,9)::NUMERIC(12,3);
5199 IF "min_weight_v" ISNULL OR "weight_ary"["i"] < "min_weight_v" THEN
5200 "min_weight_v" := "weight_ary"["i"];
5201 END IF;
5202 "i" := "i" + 1;
5203 EXIT WHEN "i" > "count_v";
5204 END LOOP;
5205 "i" := 1;
5206 LOOP
5207 IF "weight_ary"["i"] = "min_weight_v" THEN
5208 UPDATE "initiative" SET "harmonic_weight" = "min_weight_v"
5209 WHERE "id" = "id_ary"["i"];
5210 EXIT;
5211 END IF;
5212 "i" := "i" + 1;
5213 END LOOP;
5214 END LOOP;
5215 UPDATE "initiative" SET "harmonic_weight" = 0
5216 WHERE "issue_id" = "issue_id_p" AND "harmonic_weight" ISNULL;
5217 END;
5218 $$;
5220 COMMENT ON FUNCTION "set_harmonic_initiative_weights"
5221 ( "issue"."id"%TYPE )
5222 IS 'Calculates and sets "harmonic_weight" of initiatives in a given issue';
5226 ------------------------------
5227 -- Calculation of snapshots --
5228 ------------------------------
5231 CREATE FUNCTION "weight_of_added_delegations_for_snapshot"
5232 ( "snapshot_id_p" "snapshot"."id"%TYPE,
5233 "issue_id_p" "issue"."id"%TYPE,
5234 "member_id_p" "member"."id"%TYPE,
5235 "delegate_member_ids_p" "delegating_interest_snapshot"."delegate_member_ids"%TYPE )
5236 RETURNS "direct_interest_snapshot"."weight"%TYPE
5237 LANGUAGE 'plpgsql' VOLATILE AS $$
5238 DECLARE
5239 "issue_delegation_row" "issue_delegation"%ROWTYPE;
5240 "delegate_member_ids_v" "delegating_interest_snapshot"."delegate_member_ids"%TYPE;
5241 "weight_v" INT4;
5242 "sub_weight_v" INT4;
5243 BEGIN
5244 PERFORM "require_transaction_isolation"();
5245 "weight_v" := 0;
5246 FOR "issue_delegation_row" IN
5247 SELECT * FROM "issue_delegation"
5248 WHERE "trustee_id" = "member_id_p"
5249 AND "issue_id" = "issue_id_p"
5250 LOOP
5251 IF NOT EXISTS (
5252 SELECT NULL FROM "direct_interest_snapshot"
5253 WHERE "snapshot_id" = "snapshot_id_p"
5254 AND "issue_id" = "issue_id_p"
5255 AND "member_id" = "issue_delegation_row"."truster_id"
5256 ) AND NOT EXISTS (
5257 SELECT NULL FROM "delegating_interest_snapshot"
5258 WHERE "snapshot_id" = "snapshot_id_p"
5259 AND "issue_id" = "issue_id_p"
5260 AND "member_id" = "issue_delegation_row"."truster_id"
5261 ) THEN
5262 "delegate_member_ids_v" :=
5263 "member_id_p" || "delegate_member_ids_p";
5264 INSERT INTO "delegating_interest_snapshot" (
5265 "snapshot_id",
5266 "issue_id",
5267 "member_id",
5268 "scope",
5269 "delegate_member_ids"
5270 ) VALUES (
5271 "snapshot_id_p",
5272 "issue_id_p",
5273 "issue_delegation_row"."truster_id",
5274 "issue_delegation_row"."scope",
5275 "delegate_member_ids_v"
5276 );
5277 "sub_weight_v" := 1 +
5278 "weight_of_added_delegations_for_snapshot"(
5279 "snapshot_id_p",
5280 "issue_id_p",
5281 "issue_delegation_row"."truster_id",
5282 "delegate_member_ids_v"
5283 );
5284 UPDATE "delegating_interest_snapshot"
5285 SET "weight" = "sub_weight_v"
5286 WHERE "snapshot_id" = "snapshot_id_p"
5287 AND "issue_id" = "issue_id_p"
5288 AND "member_id" = "issue_delegation_row"."truster_id";
5289 "weight_v" := "weight_v" + "sub_weight_v";
5290 END IF;
5291 END LOOP;
5292 RETURN "weight_v";
5293 END;
5294 $$;
5296 COMMENT ON FUNCTION "weight_of_added_delegations_for_snapshot"
5297 ( "snapshot"."id"%TYPE,
5298 "issue"."id"%TYPE,
5299 "member"."id"%TYPE,
5300 "delegating_interest_snapshot"."delegate_member_ids"%TYPE )
5301 IS 'Helper function for "fill_snapshot" function';
5304 CREATE FUNCTION "take_snapshot"
5305 ( "issue_id_p" "issue"."id"%TYPE,
5306 "area_id_p" "area"."id"%TYPE = NULL )
5307 RETURNS "snapshot"."id"%TYPE
5308 LANGUAGE 'plpgsql' VOLATILE AS $$
5309 DECLARE
5310 "area_id_v" "area"."id"%TYPE;
5311 "unit_id_v" "unit"."id"%TYPE;
5312 "snapshot_id_v" "snapshot"."id"%TYPE;
5313 "issue_id_v" "issue"."id"%TYPE;
5314 "member_id_v" "member"."id"%TYPE;
5315 BEGIN
5316 IF "issue_id_p" NOTNULL AND "area_id_p" NOTNULL THEN
5317 RAISE EXCEPTION 'One of "issue_id_p" and "area_id_p" must be NULL';
5318 END IF;
5319 PERFORM "require_transaction_isolation"();
5320 IF "issue_id_p" ISNULL THEN
5321 "area_id_v" := "area_id_p";
5322 ELSE
5323 SELECT "area_id" INTO "area_id_v"
5324 FROM "issue" WHERE "id" = "issue_id_p";
5325 END IF;
5326 SELECT "unit_id" INTO "unit_id_v" FROM "area" WHERE "id" = "area_id_v";
5327 INSERT INTO "snapshot" ("area_id", "issue_id")
5328 VALUES ("area_id_v", "issue_id_p")
5329 RETURNING "id" INTO "snapshot_id_v";
5330 INSERT INTO "snapshot_population" ("snapshot_id", "member_id")
5331 SELECT "snapshot_id_v", "member_id"
5332 FROM "unit_member" WHERE "unit_id" = "unit_id_v";
5333 UPDATE "snapshot" SET
5334 "population" = (
5335 SELECT count(1) FROM "snapshot_population"
5336 WHERE "snapshot_id" = "snapshot_id_v"
5337 ) WHERE "id" = "snapshot_id_v";
5338 FOR "issue_id_v" IN
5339 SELECT "id" FROM "issue"
5340 WHERE CASE WHEN "issue_id_p" ISNULL THEN
5341 "area_id" = "area_id_p" AND
5342 "state" = 'admission'
5343 ELSE
5344 "id" = "issue_id_p"
5345 END
5346 LOOP
5347 INSERT INTO "snapshot_issue" ("snapshot_id", "issue_id")
5348 VALUES ("snapshot_id_v", "issue_id_v");
5349 INSERT INTO "direct_interest_snapshot"
5350 ("snapshot_id", "issue_id", "member_id")
5351 SELECT
5352 "snapshot_id_v" AS "snapshot_id",
5353 "issue_id_v" AS "issue_id",
5354 "member"."id" AS "member_id"
5355 FROM "issue"
5356 JOIN "area" ON "issue"."area_id" = "area"."id"
5357 JOIN "interest" ON "issue"."id" = "interest"."issue_id"
5358 JOIN "member" ON "interest"."member_id" = "member"."id"
5359 JOIN "privilege"
5360 ON "privilege"."unit_id" = "area"."unit_id"
5361 AND "privilege"."member_id" = "member"."id"
5362 WHERE "issue"."id" = "issue_id_v"
5363 AND "member"."active" AND "privilege"."voting_right";
5364 FOR "member_id_v" IN
5365 SELECT "member_id" FROM "direct_interest_snapshot"
5366 WHERE "snapshot_id" = "snapshot_id_v"
5367 AND "issue_id" = "issue_id_v"
5368 LOOP
5369 UPDATE "direct_interest_snapshot" SET
5370 "weight" = 1 +
5371 "weight_of_added_delegations_for_snapshot"(
5372 "snapshot_id_v",
5373 "issue_id_v",
5374 "member_id_v",
5375 '{}'
5377 WHERE "snapshot_id" = "snapshot_id_v"
5378 AND "issue_id" = "issue_id_v"
5379 AND "member_id" = "member_id_v";
5380 END LOOP;
5381 INSERT INTO "direct_supporter_snapshot"
5382 ( "snapshot_id", "issue_id", "initiative_id", "member_id",
5383 "draft_id", "informed", "satisfied" )
5384 SELECT
5385 "snapshot_id_v" AS "snapshot_id",
5386 "issue_id_v" AS "issue_id",
5387 "initiative"."id" AS "initiative_id",
5388 "supporter"."member_id" AS "member_id",
5389 "supporter"."draft_id" AS "draft_id",
5390 "supporter"."draft_id" = "current_draft"."id" AS "informed",
5391 NOT EXISTS (
5392 SELECT NULL FROM "critical_opinion"
5393 WHERE "initiative_id" = "initiative"."id"
5394 AND "member_id" = "supporter"."member_id"
5395 ) AS "satisfied"
5396 FROM "initiative"
5397 JOIN "supporter"
5398 ON "supporter"."initiative_id" = "initiative"."id"
5399 JOIN "current_draft"
5400 ON "initiative"."id" = "current_draft"."initiative_id"
5401 JOIN "direct_interest_snapshot"
5402 ON "snapshot_id_v" = "direct_interest_snapshot"."snapshot_id"
5403 AND "supporter"."member_id" = "direct_interest_snapshot"."member_id"
5404 AND "initiative"."issue_id" = "direct_interest_snapshot"."issue_id"
5405 WHERE "initiative"."issue_id" = "issue_id_v";
5406 DELETE FROM "temporary_suggestion_counts";
5407 INSERT INTO "temporary_suggestion_counts"
5408 ( "id",
5409 "minus2_unfulfilled_count", "minus2_fulfilled_count",
5410 "minus1_unfulfilled_count", "minus1_fulfilled_count",
5411 "plus1_unfulfilled_count", "plus1_fulfilled_count",
5412 "plus2_unfulfilled_count", "plus2_fulfilled_count" )
5413 SELECT
5414 "suggestion"."id",
5415 ( SELECT coalesce(sum("di"."weight"), 0)
5416 FROM "opinion" JOIN "direct_interest_snapshot" AS "di"
5417 ON "di"."snapshot_id" = "snapshot_id_v"
5418 AND "di"."issue_id" = "issue_id_v"
5419 AND "di"."member_id" = "opinion"."member_id"
5420 WHERE "opinion"."suggestion_id" = "suggestion"."id"
5421 AND "opinion"."degree" = -2
5422 AND "opinion"."fulfilled" = FALSE
5423 ) AS "minus2_unfulfilled_count",
5424 ( SELECT coalesce(sum("di"."weight"), 0)
5425 FROM "opinion" JOIN "direct_interest_snapshot" AS "di"
5426 ON "di"."snapshot_id" = "snapshot_id_v"
5427 AND "di"."issue_id" = "issue_id_v"
5428 AND "di"."member_id" = "opinion"."member_id"
5429 WHERE "opinion"."suggestion_id" = "suggestion"."id"
5430 AND "opinion"."degree" = -2
5431 AND "opinion"."fulfilled" = TRUE
5432 ) AS "minus2_fulfilled_count",
5433 ( SELECT coalesce(sum("di"."weight"), 0)
5434 FROM "opinion" JOIN "direct_interest_snapshot" AS "di"
5435 ON "di"."snapshot_id" = "snapshot_id_v"
5436 AND "di"."issue_id" = "issue_id_v"
5437 AND "di"."member_id" = "opinion"."member_id"
5438 WHERE "opinion"."suggestion_id" = "suggestion"."id"
5439 AND "opinion"."degree" = -1
5440 AND "opinion"."fulfilled" = FALSE
5441 ) AS "minus1_unfulfilled_count",
5442 ( SELECT coalesce(sum("di"."weight"), 0)
5443 FROM "opinion" JOIN "direct_interest_snapshot" AS "di"
5444 ON "di"."snapshot_id" = "snapshot_id_v"
5445 AND "di"."issue_id" = "issue_id_v"
5446 AND "di"."member_id" = "opinion"."member_id"
5447 WHERE "opinion"."suggestion_id" = "suggestion"."id"
5448 AND "opinion"."degree" = -1
5449 AND "opinion"."fulfilled" = TRUE
5450 ) AS "minus1_fulfilled_count",
5451 ( SELECT coalesce(sum("di"."weight"), 0)
5452 FROM "opinion" JOIN "direct_interest_snapshot" AS "di"
5453 ON "di"."snapshot_id" = "snapshot_id_v"
5454 AND "di"."issue_id" = "issue_id_v"
5455 AND "di"."member_id" = "opinion"."member_id"
5456 WHERE "opinion"."suggestion_id" = "suggestion"."id"
5457 AND "opinion"."degree" = 1
5458 AND "opinion"."fulfilled" = FALSE
5459 ) AS "plus1_unfulfilled_count",
5460 ( SELECT coalesce(sum("di"."weight"), 0)
5461 FROM "opinion" JOIN "direct_interest_snapshot" AS "di"
5462 ON "di"."snapshot_id" = "snapshot_id_v"
5463 AND "di"."issue_id" = "issue_id_v"
5464 AND "di"."member_id" = "opinion"."member_id"
5465 WHERE "opinion"."suggestion_id" = "suggestion"."id"
5466 AND "opinion"."degree" = 1
5467 AND "opinion"."fulfilled" = TRUE
5468 ) AS "plus1_fulfilled_count",
5469 ( SELECT coalesce(sum("di"."weight"), 0)
5470 FROM "opinion" JOIN "direct_interest_snapshot" AS "di"
5471 ON "di"."snapshot_id" = "snapshot_id_v"
5472 AND "di"."issue_id" = "issue_id_v"
5473 AND "di"."member_id" = "opinion"."member_id"
5474 WHERE "opinion"."suggestion_id" = "suggestion"."id"
5475 AND "opinion"."degree" = 2
5476 AND "opinion"."fulfilled" = FALSE
5477 ) AS "plus2_unfulfilled_count",
5478 ( SELECT coalesce(sum("di"."weight"), 0)
5479 FROM "opinion" JOIN "direct_interest_snapshot" AS "di"
5480 ON "di"."snapshot_id" = "snapshot_id_v"
5481 AND "di"."issue_id" = "issue_id_v"
5482 AND "di"."member_id" = "opinion"."member_id"
5483 WHERE "opinion"."suggestion_id" = "suggestion"."id"
5484 AND "opinion"."degree" = 2
5485 AND "opinion"."fulfilled" = TRUE
5486 ) AS "plus2_fulfilled_count"
5487 FROM "suggestion" JOIN "initiative"
5488 ON "suggestion"."initiative_id" = "initiative"."id"
5489 WHERE "initiative"."issue_id" = "issue_id_v";
5490 END LOOP;
5491 RETURN "snapshot_id_v";
5492 END;
5493 $$;
5495 COMMENT ON FUNCTION "take_snapshot"
5496 ( "issue"."id"%TYPE,
5497 "area"."id"%TYPE )
5498 IS 'This function creates a new interest/supporter snapshot of a particular issue, or, if the first argument is NULL, for all issues in ''admission'' phase of the area given as second argument. It must be executed with TRANSACTION ISOLATION LEVEL REPEATABLE READ. The snapshot must later be finished by calling "finish_snapshot" for every issue.';
5501 CREATE FUNCTION "finish_snapshot"
5502 ( "issue_id_p" "issue"."id"%TYPE )
5503 RETURNS VOID
5504 LANGUAGE 'plpgsql' VOLATILE AS $$
5505 DECLARE
5506 "snapshot_id_v" "snapshot"."id"%TYPE;
5507 BEGIN
5508 -- NOTE: function does not require snapshot isolation but we don't call
5509 -- "dont_require_snapshot_isolation" here because this function is
5510 -- also invoked by "check_issue"
5511 LOCK TABLE "snapshot" IN EXCLUSIVE MODE;
5512 SELECT "id" INTO "snapshot_id_v" FROM "snapshot"
5513 ORDER BY "id" DESC LIMIT 1;
5514 UPDATE "issue" SET
5515 "calculated" = "snapshot"."calculated",
5516 "latest_snapshot_id" = "snapshot_id_v",
5517 "population" = "snapshot"."population",
5518 "initiative_quorum" = CASE WHEN
5519 "policy"."initiative_quorum" > ceil(
5520 ( "issue"."population"::INT8 *
5521 "policy"."initiative_quorum_num"::INT8 ) /
5522 "policy"."initiative_quorum_den"::FLOAT8
5523 )::INT4
5524 THEN
5525 "policy"."initiative_quorum"
5526 ELSE
5527 ceil(
5528 ( "issue"."population"::INT8 *
5529 "policy"."initiative_quorum_num"::INT8 ) /
5530 "policy"."initiative_quorum_den"::FLOAT8
5531 )::INT4
5532 END
5533 FROM "snapshot", "policy"
5534 WHERE "issue"."id" = "issue_id_p"
5535 AND "snapshot"."id" = "snapshot_id_v"
5536 AND "policy"."id" = "issue"."policy_id";
5537 UPDATE "initiative" SET
5538 "supporter_count" = (
5539 SELECT coalesce(sum("di"."weight"), 0)
5540 FROM "direct_interest_snapshot" AS "di"
5541 JOIN "direct_supporter_snapshot" AS "ds"
5542 ON "di"."member_id" = "ds"."member_id"
5543 WHERE "di"."snapshot_id" = "snapshot_id_v"
5544 AND "di"."issue_id" = "issue_id_p"
5545 AND "ds"."snapshot_id" = "snapshot_id_v"
5546 AND "ds"."initiative_id" = "initiative"."id"
5547 ),
5548 "informed_supporter_count" = (
5549 SELECT coalesce(sum("di"."weight"), 0)
5550 FROM "direct_interest_snapshot" AS "di"
5551 JOIN "direct_supporter_snapshot" AS "ds"
5552 ON "di"."member_id" = "ds"."member_id"
5553 WHERE "di"."snapshot_id" = "snapshot_id_v"
5554 AND "di"."issue_id" = "issue_id_p"
5555 AND "ds"."snapshot_id" = "snapshot_id_v"
5556 AND "ds"."initiative_id" = "initiative"."id"
5557 AND "ds"."informed"
5558 ),
5559 "satisfied_supporter_count" = (
5560 SELECT coalesce(sum("di"."weight"), 0)
5561 FROM "direct_interest_snapshot" AS "di"
5562 JOIN "direct_supporter_snapshot" AS "ds"
5563 ON "di"."member_id" = "ds"."member_id"
5564 WHERE "di"."snapshot_id" = "snapshot_id_v"
5565 AND "di"."issue_id" = "issue_id_p"
5566 AND "ds"."snapshot_id" = "snapshot_id_v"
5567 AND "ds"."initiative_id" = "initiative"."id"
5568 AND "ds"."satisfied"
5569 ),
5570 "satisfied_informed_supporter_count" = (
5571 SELECT coalesce(sum("di"."weight"), 0)
5572 FROM "direct_interest_snapshot" AS "di"
5573 JOIN "direct_supporter_snapshot" AS "ds"
5574 ON "di"."member_id" = "ds"."member_id"
5575 WHERE "di"."snapshot_id" = "snapshot_id_v"
5576 AND "di"."issue_id" = "issue_id_p"
5577 AND "ds"."snapshot_id" = "snapshot_id_v"
5578 AND "ds"."initiative_id" = "initiative"."id"
5579 AND "ds"."informed"
5580 AND "ds"."satisfied"
5582 WHERE "issue_id" = "issue_id_p";
5583 UPDATE "suggestion" SET
5584 "minus2_unfulfilled_count" = "temp"."minus2_unfulfilled_count",
5585 "minus2_fulfilled_count" = "temp"."minus2_fulfilled_count",
5586 "minus1_unfulfilled_count" = "temp"."minus1_unfulfilled_count",
5587 "minus1_fulfilled_count" = "temp"."minus1_fulfilled_count",
5588 "plus1_unfulfilled_count" = "temp"."plus1_unfulfilled_count",
5589 "plus1_fulfilled_count" = "temp"."plus1_fulfilled_count",
5590 "plus2_unfulfilled_count" = "temp"."plus2_unfulfilled_count",
5591 "plus2_fulfilled_count" = "temp"."plus2_fulfilled_count"
5592 FROM "temporary_suggestion_counts" AS "temp", "initiative"
5593 WHERE "temp"."id" = "suggestion"."id"
5594 AND "initiative"."issue_id" = "issue_id_p"
5595 AND "suggestion"."initiative_id" = "initiative"."id";
5596 DELETE FROM "temporary_suggestion_counts";
5597 RETURN;
5598 END;
5599 $$;
5601 COMMENT ON FUNCTION "finish_snapshot"
5602 ( "issue"."id"%TYPE )
5603 IS 'After calling "take_snapshot", this function "finish_snapshot" needs to be called for every issue in the snapshot (separate function calls keep locking time minimal)';
5607 -----------------------
5608 -- Counting of votes --
5609 -----------------------
5612 CREATE FUNCTION "weight_of_added_vote_delegations"
5613 ( "issue_id_p" "issue"."id"%TYPE,
5614 "member_id_p" "member"."id"%TYPE,
5615 "delegate_member_ids_p" "delegating_voter"."delegate_member_ids"%TYPE )
5616 RETURNS "direct_voter"."weight"%TYPE
5617 LANGUAGE 'plpgsql' VOLATILE AS $$
5618 DECLARE
5619 "issue_delegation_row" "issue_delegation"%ROWTYPE;
5620 "delegate_member_ids_v" "delegating_voter"."delegate_member_ids"%TYPE;
5621 "weight_v" INT4;
5622 "sub_weight_v" INT4;
5623 BEGIN
5624 PERFORM "require_transaction_isolation"();
5625 "weight_v" := 0;
5626 FOR "issue_delegation_row" IN
5627 SELECT * FROM "issue_delegation"
5628 WHERE "trustee_id" = "member_id_p"
5629 AND "issue_id" = "issue_id_p"
5630 LOOP
5631 IF NOT EXISTS (
5632 SELECT NULL FROM "direct_voter"
5633 WHERE "member_id" = "issue_delegation_row"."truster_id"
5634 AND "issue_id" = "issue_id_p"
5635 ) AND NOT EXISTS (
5636 SELECT NULL FROM "delegating_voter"
5637 WHERE "member_id" = "issue_delegation_row"."truster_id"
5638 AND "issue_id" = "issue_id_p"
5639 ) THEN
5640 "delegate_member_ids_v" :=
5641 "member_id_p" || "delegate_member_ids_p";
5642 INSERT INTO "delegating_voter" (
5643 "issue_id",
5644 "member_id",
5645 "scope",
5646 "delegate_member_ids"
5647 ) VALUES (
5648 "issue_id_p",
5649 "issue_delegation_row"."truster_id",
5650 "issue_delegation_row"."scope",
5651 "delegate_member_ids_v"
5652 );
5653 "sub_weight_v" := 1 +
5654 "weight_of_added_vote_delegations"(
5655 "issue_id_p",
5656 "issue_delegation_row"."truster_id",
5657 "delegate_member_ids_v"
5658 );
5659 UPDATE "delegating_voter"
5660 SET "weight" = "sub_weight_v"
5661 WHERE "issue_id" = "issue_id_p"
5662 AND "member_id" = "issue_delegation_row"."truster_id";
5663 "weight_v" := "weight_v" + "sub_weight_v";
5664 END IF;
5665 END LOOP;
5666 RETURN "weight_v";
5667 END;
5668 $$;
5670 COMMENT ON FUNCTION "weight_of_added_vote_delegations"
5671 ( "issue"."id"%TYPE,
5672 "member"."id"%TYPE,
5673 "delegating_voter"."delegate_member_ids"%TYPE )
5674 IS 'Helper function for "add_vote_delegations" function';
5677 CREATE FUNCTION "add_vote_delegations"
5678 ( "issue_id_p" "issue"."id"%TYPE )
5679 RETURNS VOID
5680 LANGUAGE 'plpgsql' VOLATILE AS $$
5681 DECLARE
5682 "member_id_v" "member"."id"%TYPE;
5683 BEGIN
5684 PERFORM "require_transaction_isolation"();
5685 FOR "member_id_v" IN
5686 SELECT "member_id" FROM "direct_voter"
5687 WHERE "issue_id" = "issue_id_p"
5688 LOOP
5689 UPDATE "direct_voter" SET
5690 "weight" = "weight" + "weight_of_added_vote_delegations"(
5691 "issue_id_p",
5692 "member_id_v",
5693 '{}'
5695 WHERE "member_id" = "member_id_v"
5696 AND "issue_id" = "issue_id_p";
5697 END LOOP;
5698 RETURN;
5699 END;
5700 $$;
5702 COMMENT ON FUNCTION "add_vote_delegations"
5703 ( "issue_id_p" "issue"."id"%TYPE )
5704 IS 'Helper function for "close_voting" function';
5707 CREATE FUNCTION "close_voting"("issue_id_p" "issue"."id"%TYPE)
5708 RETURNS VOID
5709 LANGUAGE 'plpgsql' VOLATILE AS $$
5710 DECLARE
5711 "area_id_v" "area"."id"%TYPE;
5712 "unit_id_v" "unit"."id"%TYPE;
5713 "member_id_v" "member"."id"%TYPE;
5714 BEGIN
5715 PERFORM "require_transaction_isolation"();
5716 SELECT "area_id" INTO "area_id_v" FROM "issue" WHERE "id" = "issue_id_p";
5717 SELECT "unit_id" INTO "unit_id_v" FROM "area" WHERE "id" = "area_id_v";
5718 -- override protection triggers:
5719 INSERT INTO "temporary_transaction_data" ("key", "value")
5720 VALUES ('override_protection_triggers', TRUE::TEXT);
5721 -- delete timestamp of voting comment:
5722 UPDATE "direct_voter" SET "comment_changed" = NULL
5723 WHERE "issue_id" = "issue_id_p";
5724 -- delete delegating votes (in cases of manual reset of issue state):
5725 DELETE FROM "delegating_voter"
5726 WHERE "issue_id" = "issue_id_p";
5727 -- delete votes from non-privileged voters:
5728 DELETE FROM "direct_voter"
5729 USING (
5730 SELECT
5731 "direct_voter"."member_id"
5732 FROM "direct_voter"
5733 JOIN "member" ON "direct_voter"."member_id" = "member"."id"
5734 LEFT JOIN "privilege"
5735 ON "privilege"."unit_id" = "unit_id_v"
5736 AND "privilege"."member_id" = "direct_voter"."member_id"
5737 WHERE "direct_voter"."issue_id" = "issue_id_p" AND (
5738 "member"."active" = FALSE OR
5739 "privilege"."voting_right" ISNULL OR
5740 "privilege"."voting_right" = FALSE
5742 ) AS "subquery"
5743 WHERE "direct_voter"."issue_id" = "issue_id_p"
5744 AND "direct_voter"."member_id" = "subquery"."member_id";
5745 -- consider delegations:
5746 UPDATE "direct_voter" SET "weight" = 1
5747 WHERE "issue_id" = "issue_id_p";
5748 PERFORM "add_vote_delegations"("issue_id_p");
5749 -- mark first preferences:
5750 UPDATE "vote" SET "first_preference" = "subquery"."first_preference"
5751 FROM (
5752 SELECT
5753 "vote"."initiative_id",
5754 "vote"."member_id",
5755 CASE WHEN "vote"."grade" > 0 THEN
5756 CASE WHEN "vote"."grade" = max("agg"."grade") THEN TRUE ELSE FALSE END
5757 ELSE NULL
5758 END AS "first_preference"
5759 FROM "vote"
5760 JOIN "initiative" -- NOTE: due to missing index on issue_id
5761 ON "vote"."issue_id" = "initiative"."issue_id"
5762 JOIN "vote" AS "agg"
5763 ON "initiative"."id" = "agg"."initiative_id"
5764 AND "vote"."member_id" = "agg"."member_id"
5765 GROUP BY "vote"."initiative_id", "vote"."member_id", "vote"."grade"
5766 ) AS "subquery"
5767 WHERE "vote"."issue_id" = "issue_id_p"
5768 AND "vote"."initiative_id" = "subquery"."initiative_id"
5769 AND "vote"."member_id" = "subquery"."member_id";
5770 -- finish overriding protection triggers (avoids garbage):
5771 DELETE FROM "temporary_transaction_data"
5772 WHERE "key" = 'override_protection_triggers';
5773 -- materialize battle_view:
5774 -- NOTE: "closed" column of issue must be set at this point
5775 DELETE FROM "battle" WHERE "issue_id" = "issue_id_p";
5776 INSERT INTO "battle" (
5777 "issue_id",
5778 "winning_initiative_id", "losing_initiative_id",
5779 "count"
5780 ) SELECT
5781 "issue_id",
5782 "winning_initiative_id", "losing_initiative_id",
5783 "count"
5784 FROM "battle_view" WHERE "issue_id" = "issue_id_p";
5785 -- set voter count:
5786 UPDATE "issue" SET
5787 "voter_count" = (
5788 SELECT coalesce(sum("weight"), 0)
5789 FROM "direct_voter" WHERE "issue_id" = "issue_id_p"
5791 WHERE "id" = "issue_id_p";
5792 -- copy "positive_votes" and "negative_votes" from "battle" table:
5793 -- NOTE: "first_preference_votes" is set to a default of 0 at this step
5794 UPDATE "initiative" SET
5795 "first_preference_votes" = 0,
5796 "positive_votes" = "battle_win"."count",
5797 "negative_votes" = "battle_lose"."count"
5798 FROM "battle" AS "battle_win", "battle" AS "battle_lose"
5799 WHERE
5800 "battle_win"."issue_id" = "issue_id_p" AND
5801 "battle_win"."winning_initiative_id" = "initiative"."id" AND
5802 "battle_win"."losing_initiative_id" ISNULL AND
5803 "battle_lose"."issue_id" = "issue_id_p" AND
5804 "battle_lose"."losing_initiative_id" = "initiative"."id" AND
5805 "battle_lose"."winning_initiative_id" ISNULL;
5806 -- calculate "first_preference_votes":
5807 -- NOTE: will only set values not equal to zero
5808 UPDATE "initiative" SET "first_preference_votes" = "subquery"."sum"
5809 FROM (
5810 SELECT "vote"."initiative_id", sum("direct_voter"."weight")
5811 FROM "vote" JOIN "direct_voter"
5812 ON "vote"."issue_id" = "direct_voter"."issue_id"
5813 AND "vote"."member_id" = "direct_voter"."member_id"
5814 WHERE "vote"."first_preference"
5815 GROUP BY "vote"."initiative_id"
5816 ) AS "subquery"
5817 WHERE "initiative"."issue_id" = "issue_id_p"
5818 AND "initiative"."admitted"
5819 AND "initiative"."id" = "subquery"."initiative_id";
5820 END;
5821 $$;
5823 COMMENT ON FUNCTION "close_voting"
5824 ( "issue"."id"%TYPE )
5825 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.';
5828 CREATE FUNCTION "defeat_strength"
5829 ( "positive_votes_p" INT4,
5830 "negative_votes_p" INT4,
5831 "defeat_strength_p" "defeat_strength" )
5832 RETURNS INT8
5833 LANGUAGE 'plpgsql' IMMUTABLE AS $$
5834 BEGIN
5835 IF "defeat_strength_p" = 'simple'::"defeat_strength" THEN
5836 IF "positive_votes_p" > "negative_votes_p" THEN
5837 RETURN "positive_votes_p";
5838 ELSE
5839 RETURN 0;
5840 END IF;
5841 ELSE
5842 IF "positive_votes_p" > "negative_votes_p" THEN
5843 RETURN ("positive_votes_p"::INT8 << 31) - "negative_votes_p"::INT8;
5844 ELSIF "positive_votes_p" = "negative_votes_p" THEN
5845 RETURN 0;
5846 ELSE
5847 RETURN -1;
5848 END IF;
5849 END IF;
5850 END;
5851 $$;
5853 COMMENT ON FUNCTION "defeat_strength"(INT4, INT4, "defeat_strength") IS 'Calculates defeat strength (INT8!) according to the "defeat_strength" option (see comment on type "defeat_strength")';
5856 CREATE FUNCTION "secondary_link_strength"
5857 ( "initiative1_ord_p" INT4,
5858 "initiative2_ord_p" INT4,
5859 "tie_breaking_p" "tie_breaking" )
5860 RETURNS INT8
5861 LANGUAGE 'plpgsql' IMMUTABLE AS $$
5862 BEGIN
5863 IF "initiative1_ord_p" = "initiative2_ord_p" THEN
5864 RAISE EXCEPTION 'Identical initiative ids passed to "secondary_link_strength" function (should not happen)';
5865 END IF;
5866 RETURN (
5867 CASE WHEN "tie_breaking_p" = 'simple'::"tie_breaking" THEN
5869 ELSE
5870 CASE WHEN "initiative1_ord_p" < "initiative2_ord_p" THEN
5871 1::INT8 << 62
5872 ELSE 0 END
5874 CASE WHEN "tie_breaking_p" = 'variant2'::"tie_breaking" THEN
5875 ("initiative2_ord_p"::INT8 << 31) - "initiative1_ord_p"::INT8
5876 ELSE
5877 "initiative2_ord_p"::INT8 - ("initiative1_ord_p"::INT8 << 31)
5878 END
5879 END
5880 );
5881 END;
5882 $$;
5884 COMMENT ON FUNCTION "secondary_link_strength"(INT4, INT4, "tie_breaking") IS 'Calculates a secondary criterion for the defeat strength (tie-breaking of the links)';
5887 CREATE TYPE "link_strength" AS (
5888 "primary" INT8,
5889 "secondary" INT8 );
5891 COMMENT ON TYPE "link_strength" IS 'Type to store the defeat strength of a link between two candidates plus a secondary criterion to create unique link strengths between the candidates (needed for tie-breaking ''variant1'' and ''variant2'')';
5894 CREATE FUNCTION "find_best_paths"("matrix_d" "link_strength"[][])
5895 RETURNS "link_strength"[][]
5896 LANGUAGE 'plpgsql' IMMUTABLE AS $$
5897 DECLARE
5898 "dimension_v" INT4;
5899 "matrix_p" "link_strength"[][];
5900 "i" INT4;
5901 "j" INT4;
5902 "k" INT4;
5903 BEGIN
5904 "dimension_v" := array_upper("matrix_d", 1);
5905 "matrix_p" := "matrix_d";
5906 "i" := 1;
5907 LOOP
5908 "j" := 1;
5909 LOOP
5910 IF "i" != "j" THEN
5911 "k" := 1;
5912 LOOP
5913 IF "i" != "k" AND "j" != "k" THEN
5914 IF "matrix_p"["j"]["i"] < "matrix_p"["i"]["k"] THEN
5915 IF "matrix_p"["j"]["i"] > "matrix_p"["j"]["k"] THEN
5916 "matrix_p"["j"]["k"] := "matrix_p"["j"]["i"];
5917 END IF;
5918 ELSE
5919 IF "matrix_p"["i"]["k"] > "matrix_p"["j"]["k"] THEN
5920 "matrix_p"["j"]["k"] := "matrix_p"["i"]["k"];
5921 END IF;
5922 END IF;
5923 END IF;
5924 EXIT WHEN "k" = "dimension_v";
5925 "k" := "k" + 1;
5926 END LOOP;
5927 END IF;
5928 EXIT WHEN "j" = "dimension_v";
5929 "j" := "j" + 1;
5930 END LOOP;
5931 EXIT WHEN "i" = "dimension_v";
5932 "i" := "i" + 1;
5933 END LOOP;
5934 RETURN "matrix_p";
5935 END;
5936 $$;
5938 COMMENT ON FUNCTION "find_best_paths"("link_strength"[][]) IS 'Computes the strengths of the best beat-paths from a square matrix';
5941 CREATE FUNCTION "calculate_ranks"("issue_id_p" "issue"."id"%TYPE)
5942 RETURNS VOID
5943 LANGUAGE 'plpgsql' VOLATILE AS $$
5944 DECLARE
5945 "issue_row" "issue"%ROWTYPE;
5946 "policy_row" "policy"%ROWTYPE;
5947 "dimension_v" INT4;
5948 "matrix_a" INT4[][]; -- absolute votes
5949 "matrix_d" "link_strength"[][]; -- defeat strength (direct)
5950 "matrix_p" "link_strength"[][]; -- defeat strength (best path)
5951 "matrix_t" "link_strength"[][]; -- defeat strength (tie-breaking)
5952 "matrix_f" BOOLEAN[][]; -- forbidden link (tie-breaking)
5953 "matrix_b" BOOLEAN[][]; -- final order (who beats who)
5954 "i" INT4;
5955 "j" INT4;
5956 "m" INT4;
5957 "n" INT4;
5958 "battle_row" "battle"%ROWTYPE;
5959 "rank_ary" INT4[];
5960 "rank_v" INT4;
5961 "initiative_id_v" "initiative"."id"%TYPE;
5962 BEGIN
5963 PERFORM "require_transaction_isolation"();
5964 SELECT * INTO "issue_row"
5965 FROM "issue" WHERE "id" = "issue_id_p";
5966 SELECT * INTO "policy_row"
5967 FROM "policy" WHERE "id" = "issue_row"."policy_id";
5968 SELECT count(1) INTO "dimension_v"
5969 FROM "battle_participant" WHERE "issue_id" = "issue_id_p";
5970 -- create "matrix_a" with absolute number of votes in pairwise
5971 -- comparison:
5972 "matrix_a" := array_fill(NULL::INT4, ARRAY["dimension_v", "dimension_v"]);
5973 "i" := 1;
5974 "j" := 2;
5975 FOR "battle_row" IN
5976 SELECT * FROM "battle" WHERE "issue_id" = "issue_id_p"
5977 ORDER BY
5978 "winning_initiative_id" NULLS FIRST,
5979 "losing_initiative_id" NULLS FIRST
5980 LOOP
5981 "matrix_a"["i"]["j"] := "battle_row"."count";
5982 IF "j" = "dimension_v" THEN
5983 "i" := "i" + 1;
5984 "j" := 1;
5985 ELSE
5986 "j" := "j" + 1;
5987 IF "j" = "i" THEN
5988 "j" := "j" + 1;
5989 END IF;
5990 END IF;
5991 END LOOP;
5992 IF "i" != "dimension_v" OR "j" != "dimension_v" + 1 THEN
5993 RAISE EXCEPTION 'Wrong battle count (should not happen)';
5994 END IF;
5995 -- store direct defeat strengths in "matrix_d" using "defeat_strength"
5996 -- and "secondary_link_strength" functions:
5997 "matrix_d" := array_fill(NULL::INT8, ARRAY["dimension_v", "dimension_v"]);
5998 "i" := 1;
5999 LOOP
6000 "j" := 1;
6001 LOOP
6002 IF "i" != "j" THEN
6003 "matrix_d"["i"]["j"] := (
6004 "defeat_strength"(
6005 "matrix_a"["i"]["j"],
6006 "matrix_a"["j"]["i"],
6007 "policy_row"."defeat_strength"
6008 ),
6009 "secondary_link_strength"(
6010 "i",
6011 "j",
6012 "policy_row"."tie_breaking"
6014 )::"link_strength";
6015 END IF;
6016 EXIT WHEN "j" = "dimension_v";
6017 "j" := "j" + 1;
6018 END LOOP;
6019 EXIT WHEN "i" = "dimension_v";
6020 "i" := "i" + 1;
6021 END LOOP;
6022 -- find best paths:
6023 "matrix_p" := "find_best_paths"("matrix_d");
6024 -- create partial order:
6025 "matrix_b" := array_fill(NULL::BOOLEAN, ARRAY["dimension_v", "dimension_v"]);
6026 "i" := 1;
6027 LOOP
6028 "j" := "i" + 1;
6029 LOOP
6030 IF "i" != "j" THEN
6031 IF "matrix_p"["i"]["j"] > "matrix_p"["j"]["i"] THEN
6032 "matrix_b"["i"]["j"] := TRUE;
6033 "matrix_b"["j"]["i"] := FALSE;
6034 ELSIF "matrix_p"["i"]["j"] < "matrix_p"["j"]["i"] THEN
6035 "matrix_b"["i"]["j"] := FALSE;
6036 "matrix_b"["j"]["i"] := TRUE;
6037 END IF;
6038 END IF;
6039 EXIT WHEN "j" = "dimension_v";
6040 "j" := "j" + 1;
6041 END LOOP;
6042 EXIT WHEN "i" = "dimension_v" - 1;
6043 "i" := "i" + 1;
6044 END LOOP;
6045 -- tie-breaking by forbidding shared weakest links in beat-paths
6046 -- (unless "tie_breaking" is set to 'simple', in which case tie-breaking
6047 -- is performed later by initiative id):
6048 IF "policy_row"."tie_breaking" != 'simple'::"tie_breaking" THEN
6049 "m" := 1;
6050 LOOP
6051 "n" := "m" + 1;
6052 LOOP
6053 -- only process those candidates m and n, which are tied:
6054 IF "matrix_b"["m"]["n"] ISNULL THEN
6055 -- start with beat-paths prior tie-breaking:
6056 "matrix_t" := "matrix_p";
6057 -- start with all links allowed:
6058 "matrix_f" := array_fill(FALSE, ARRAY["dimension_v", "dimension_v"]);
6059 LOOP
6060 -- determine (and forbid) that link that is the weakest link
6061 -- in both the best path from candidate m to candidate n and
6062 -- from candidate n to candidate m:
6063 "i" := 1;
6064 <<forbid_one_link>>
6065 LOOP
6066 "j" := 1;
6067 LOOP
6068 IF "i" != "j" THEN
6069 IF "matrix_d"["i"]["j"] = "matrix_t"["m"]["n"] THEN
6070 "matrix_f"["i"]["j"] := TRUE;
6071 -- exit for performance reasons,
6072 -- as exactly one link will be found:
6073 EXIT forbid_one_link;
6074 END IF;
6075 END IF;
6076 EXIT WHEN "j" = "dimension_v";
6077 "j" := "j" + 1;
6078 END LOOP;
6079 IF "i" = "dimension_v" THEN
6080 RAISE EXCEPTION 'Did not find shared weakest link for tie-breaking (should not happen)';
6081 END IF;
6082 "i" := "i" + 1;
6083 END LOOP;
6084 -- calculate best beat-paths while ignoring forbidden links:
6085 "i" := 1;
6086 LOOP
6087 "j" := 1;
6088 LOOP
6089 IF "i" != "j" THEN
6090 "matrix_t"["i"]["j"] := CASE
6091 WHEN "matrix_f"["i"]["j"]
6092 THEN ((-1::INT8) << 63, 0)::"link_strength" -- worst possible value
6093 ELSE "matrix_d"["i"]["j"] END;
6094 END IF;
6095 EXIT WHEN "j" = "dimension_v";
6096 "j" := "j" + 1;
6097 END LOOP;
6098 EXIT WHEN "i" = "dimension_v";
6099 "i" := "i" + 1;
6100 END LOOP;
6101 "matrix_t" := "find_best_paths"("matrix_t");
6102 -- extend partial order, if tie-breaking was successful:
6103 IF "matrix_t"["m"]["n"] > "matrix_t"["n"]["m"] THEN
6104 "matrix_b"["m"]["n"] := TRUE;
6105 "matrix_b"["n"]["m"] := FALSE;
6106 EXIT;
6107 ELSIF "matrix_t"["m"]["n"] < "matrix_t"["n"]["m"] THEN
6108 "matrix_b"["m"]["n"] := FALSE;
6109 "matrix_b"["n"]["m"] := TRUE;
6110 EXIT;
6111 END IF;
6112 END LOOP;
6113 END IF;
6114 EXIT WHEN "n" = "dimension_v";
6115 "n" := "n" + 1;
6116 END LOOP;
6117 EXIT WHEN "m" = "dimension_v" - 1;
6118 "m" := "m" + 1;
6119 END LOOP;
6120 END IF;
6121 -- store a unique ranking in "rank_ary":
6122 "rank_ary" := array_fill(NULL::INT4, ARRAY["dimension_v"]);
6123 "rank_v" := 1;
6124 LOOP
6125 "i" := 1;
6126 <<assign_next_rank>>
6127 LOOP
6128 IF "rank_ary"["i"] ISNULL THEN
6129 "j" := 1;
6130 LOOP
6131 IF
6132 "i" != "j" AND
6133 "rank_ary"["j"] ISNULL AND
6134 ( "matrix_b"["j"]["i"] OR
6135 -- tie-breaking by "id"
6136 ( "matrix_b"["j"]["i"] ISNULL AND
6137 "j" < "i" ) )
6138 THEN
6139 -- someone else is better
6140 EXIT;
6141 END IF;
6142 IF "j" = "dimension_v" THEN
6143 -- noone is better
6144 "rank_ary"["i"] := "rank_v";
6145 EXIT assign_next_rank;
6146 END IF;
6147 "j" := "j" + 1;
6148 END LOOP;
6149 END IF;
6150 "i" := "i" + 1;
6151 IF "i" > "dimension_v" THEN
6152 RAISE EXCEPTION 'Schulze ranking does not compute (should not happen)';
6153 END IF;
6154 END LOOP;
6155 EXIT WHEN "rank_v" = "dimension_v";
6156 "rank_v" := "rank_v" + 1;
6157 END LOOP;
6158 -- write preliminary results:
6159 "i" := 2; -- omit status quo with "i" = 1
6160 FOR "initiative_id_v" IN
6161 SELECT "id" FROM "initiative"
6162 WHERE "issue_id" = "issue_id_p" AND "admitted"
6163 ORDER BY "id"
6164 LOOP
6165 UPDATE "initiative" SET
6166 "direct_majority" =
6167 CASE WHEN "policy_row"."direct_majority_strict" THEN
6168 "positive_votes" * "policy_row"."direct_majority_den" >
6169 "policy_row"."direct_majority_num" * ("positive_votes"+"negative_votes")
6170 ELSE
6171 "positive_votes" * "policy_row"."direct_majority_den" >=
6172 "policy_row"."direct_majority_num" * ("positive_votes"+"negative_votes")
6173 END
6174 AND "positive_votes" >= "policy_row"."direct_majority_positive"
6175 AND "issue_row"."voter_count"-"negative_votes" >=
6176 "policy_row"."direct_majority_non_negative",
6177 "indirect_majority" =
6178 CASE WHEN "policy_row"."indirect_majority_strict" THEN
6179 "positive_votes" * "policy_row"."indirect_majority_den" >
6180 "policy_row"."indirect_majority_num" * ("positive_votes"+"negative_votes")
6181 ELSE
6182 "positive_votes" * "policy_row"."indirect_majority_den" >=
6183 "policy_row"."indirect_majority_num" * ("positive_votes"+"negative_votes")
6184 END
6185 AND "positive_votes" >= "policy_row"."indirect_majority_positive"
6186 AND "issue_row"."voter_count"-"negative_votes" >=
6187 "policy_row"."indirect_majority_non_negative",
6188 "schulze_rank" = "rank_ary"["i"],
6189 "better_than_status_quo" = "rank_ary"["i"] < "rank_ary"[1],
6190 "worse_than_status_quo" = "rank_ary"["i"] > "rank_ary"[1],
6191 "multistage_majority" = "rank_ary"["i"] >= "rank_ary"[1],
6192 "reverse_beat_path" = CASE WHEN "policy_row"."defeat_strength" = 'simple'::"defeat_strength"
6193 THEN NULL
6194 ELSE "matrix_p"[1]["i"]."primary" >= 0 END,
6195 "eligible" = FALSE,
6196 "winner" = FALSE,
6197 "rank" = NULL -- NOTE: in cases of manual reset of issue state
6198 WHERE "id" = "initiative_id_v";
6199 "i" := "i" + 1;
6200 END LOOP;
6201 IF "i" != "dimension_v" + 1 THEN
6202 RAISE EXCEPTION 'Wrong winner count (should not happen)';
6203 END IF;
6204 -- take indirect majorities into account:
6205 LOOP
6206 UPDATE "initiative" SET "indirect_majority" = TRUE
6207 FROM (
6208 SELECT "new_initiative"."id" AS "initiative_id"
6209 FROM "initiative" "old_initiative"
6210 JOIN "initiative" "new_initiative"
6211 ON "new_initiative"."issue_id" = "issue_id_p"
6212 AND "new_initiative"."indirect_majority" = FALSE
6213 JOIN "battle" "battle_win"
6214 ON "battle_win"."issue_id" = "issue_id_p"
6215 AND "battle_win"."winning_initiative_id" = "new_initiative"."id"
6216 AND "battle_win"."losing_initiative_id" = "old_initiative"."id"
6217 JOIN "battle" "battle_lose"
6218 ON "battle_lose"."issue_id" = "issue_id_p"
6219 AND "battle_lose"."losing_initiative_id" = "new_initiative"."id"
6220 AND "battle_lose"."winning_initiative_id" = "old_initiative"."id"
6221 WHERE "old_initiative"."issue_id" = "issue_id_p"
6222 AND "old_initiative"."indirect_majority" = TRUE
6223 AND CASE WHEN "policy_row"."indirect_majority_strict" THEN
6224 "battle_win"."count" * "policy_row"."indirect_majority_den" >
6225 "policy_row"."indirect_majority_num" *
6226 ("battle_win"."count"+"battle_lose"."count")
6227 ELSE
6228 "battle_win"."count" * "policy_row"."indirect_majority_den" >=
6229 "policy_row"."indirect_majority_num" *
6230 ("battle_win"."count"+"battle_lose"."count")
6231 END
6232 AND "battle_win"."count" >= "policy_row"."indirect_majority_positive"
6233 AND "issue_row"."voter_count"-"battle_lose"."count" >=
6234 "policy_row"."indirect_majority_non_negative"
6235 ) AS "subquery"
6236 WHERE "id" = "subquery"."initiative_id";
6237 EXIT WHEN NOT FOUND;
6238 END LOOP;
6239 -- set "multistage_majority" for remaining matching initiatives:
6240 UPDATE "initiative" SET "multistage_majority" = TRUE
6241 FROM (
6242 SELECT "losing_initiative"."id" AS "initiative_id"
6243 FROM "initiative" "losing_initiative"
6244 JOIN "initiative" "winning_initiative"
6245 ON "winning_initiative"."issue_id" = "issue_id_p"
6246 AND "winning_initiative"."admitted"
6247 JOIN "battle" "battle_win"
6248 ON "battle_win"."issue_id" = "issue_id_p"
6249 AND "battle_win"."winning_initiative_id" = "winning_initiative"."id"
6250 AND "battle_win"."losing_initiative_id" = "losing_initiative"."id"
6251 JOIN "battle" "battle_lose"
6252 ON "battle_lose"."issue_id" = "issue_id_p"
6253 AND "battle_lose"."losing_initiative_id" = "winning_initiative"."id"
6254 AND "battle_lose"."winning_initiative_id" = "losing_initiative"."id"
6255 WHERE "losing_initiative"."issue_id" = "issue_id_p"
6256 AND "losing_initiative"."admitted"
6257 AND "winning_initiative"."schulze_rank" <
6258 "losing_initiative"."schulze_rank"
6259 AND "battle_win"."count" > "battle_lose"."count"
6260 AND (
6261 "battle_win"."count" > "winning_initiative"."positive_votes" OR
6262 "battle_lose"."count" < "losing_initiative"."negative_votes" )
6263 ) AS "subquery"
6264 WHERE "id" = "subquery"."initiative_id";
6265 -- mark eligible initiatives:
6266 UPDATE "initiative" SET "eligible" = TRUE
6267 WHERE "issue_id" = "issue_id_p"
6268 AND "initiative"."direct_majority"
6269 AND "initiative"."indirect_majority"
6270 AND "initiative"."better_than_status_quo"
6271 AND (
6272 "policy_row"."no_multistage_majority" = FALSE OR
6273 "initiative"."multistage_majority" = FALSE )
6274 AND (
6275 "policy_row"."no_reverse_beat_path" = FALSE OR
6276 coalesce("initiative"."reverse_beat_path", FALSE) = FALSE );
6277 -- mark final winner:
6278 UPDATE "initiative" SET "winner" = TRUE
6279 FROM (
6280 SELECT "id" AS "initiative_id"
6281 FROM "initiative"
6282 WHERE "issue_id" = "issue_id_p" AND "eligible"
6283 ORDER BY
6284 "schulze_rank",
6285 "id"
6286 LIMIT 1
6287 ) AS "subquery"
6288 WHERE "id" = "subquery"."initiative_id";
6289 -- write (final) ranks:
6290 "rank_v" := 1;
6291 FOR "initiative_id_v" IN
6292 SELECT "id"
6293 FROM "initiative"
6294 WHERE "issue_id" = "issue_id_p" AND "admitted"
6295 ORDER BY
6296 "winner" DESC,
6297 "eligible" DESC,
6298 "schulze_rank",
6299 "id"
6300 LOOP
6301 UPDATE "initiative" SET "rank" = "rank_v"
6302 WHERE "id" = "initiative_id_v";
6303 "rank_v" := "rank_v" + 1;
6304 END LOOP;
6305 -- set schulze rank of status quo and mark issue as finished:
6306 UPDATE "issue" SET
6307 "status_quo_schulze_rank" = "rank_ary"[1],
6308 "state" =
6309 CASE WHEN EXISTS (
6310 SELECT NULL FROM "initiative"
6311 WHERE "issue_id" = "issue_id_p" AND "winner"
6312 ) THEN
6313 'finished_with_winner'::"issue_state"
6314 ELSE
6315 'finished_without_winner'::"issue_state"
6316 END,
6317 "closed" = "phase_finished",
6318 "phase_finished" = NULL
6319 WHERE "id" = "issue_id_p";
6320 RETURN;
6321 END;
6322 $$;
6324 COMMENT ON FUNCTION "calculate_ranks"
6325 ( "issue"."id"%TYPE )
6326 IS 'Determine ranking (Votes have to be counted first)';
6330 -----------------------------
6331 -- Automatic state changes --
6332 -----------------------------
6335 CREATE FUNCTION "issue_admission"
6336 ( "area_id_p" "area"."id"%TYPE )
6337 RETURNS BOOLEAN
6338 LANGUAGE 'plpgsql' VOLATILE AS $$
6339 DECLARE
6340 "issue_id_v" "issue"."id"%TYPE;
6341 BEGIN
6342 PERFORM "dont_require_transaction_isolation"();
6343 LOCK TABLE "snapshot" IN EXCLUSIVE MODE;
6344 UPDATE "area" SET "issue_quorum" = "view"."issue_quorum"
6345 FROM "area_quorum" AS "view"
6346 WHERE "area"."id" = "view"."area_id"
6347 AND "area"."id" = "area_id_p";
6348 SELECT "id" INTO "issue_id_v" FROM "issue_for_admission"
6349 WHERE "area_id" = "area_id_p";
6350 IF "issue_id_v" ISNULL THEN RETURN FALSE; END IF;
6351 UPDATE "issue" SET
6352 "admission_snapshot_id" = "latest_snapshot_id",
6353 "state" = 'discussion',
6354 "accepted" = now(),
6355 "phase_finished" = NULL,
6356 "issue_quorum" = "issue_quorum"."issue_quorum"
6357 FROM "issue_quorum"
6358 WHERE "id" = "issue_id_v"
6359 AND "issue_quorum"."issue_id" = "issue_id_v";
6360 RETURN TRUE;
6361 END;
6362 $$;
6364 COMMENT ON FUNCTION "issue_admission"
6365 ( "area"."id"%TYPE )
6366 IS 'Checks if an issue in the area can be admitted for further discussion; returns TRUE on success in which case the function must be called again until it returns FALSE';
6369 CREATE TYPE "check_issue_persistence" AS (
6370 "state" "issue_state",
6371 "phase_finished" BOOLEAN,
6372 "issue_revoked" BOOLEAN,
6373 "snapshot_created" BOOLEAN,
6374 "harmonic_weights_set" BOOLEAN,
6375 "closed_voting" BOOLEAN );
6377 COMMENT ON TYPE "check_issue_persistence" IS 'Type of data returned by "check_issue" function, to be passed to subsequent calls of the same function';
6380 CREATE FUNCTION "check_issue"
6381 ( "issue_id_p" "issue"."id"%TYPE,
6382 "persist" "check_issue_persistence" )
6383 RETURNS "check_issue_persistence"
6384 LANGUAGE 'plpgsql' VOLATILE AS $$
6385 DECLARE
6386 "issue_row" "issue"%ROWTYPE;
6387 "last_calculated_v" "snapshot"."calculated"%TYPE;
6388 "policy_row" "policy"%ROWTYPE;
6389 "initiative_row" "initiative"%ROWTYPE;
6390 "state_v" "issue_state";
6391 BEGIN
6392 PERFORM "require_transaction_isolation"();
6393 IF "persist" ISNULL THEN
6394 SELECT * INTO "issue_row" FROM "issue" WHERE "id" = "issue_id_p"
6395 FOR UPDATE;
6396 SELECT "calculated" INTO "last_calculated_v"
6397 FROM "snapshot" JOIN "snapshot_issue"
6398 ON "snapshot"."id" = "snapshot_issue"."snapshot_id"
6399 WHERE "snapshot_issue"."issue_id" = "issue_id_p"
6400 ORDER BY "snapshot"."id" DESC;
6401 IF "issue_row"."closed" NOTNULL THEN
6402 RETURN NULL;
6403 END IF;
6404 "persist"."state" := "issue_row"."state";
6405 IF
6406 ( "issue_row"."state" = 'admission' AND "last_calculated_v" >=
6407 "issue_row"."created" + "issue_row"."max_admission_time" ) OR
6408 ( "issue_row"."state" = 'discussion' AND now() >=
6409 "issue_row"."accepted" + "issue_row"."discussion_time" ) OR
6410 ( "issue_row"."state" = 'verification' AND now() >=
6411 "issue_row"."half_frozen" + "issue_row"."verification_time" ) OR
6412 ( "issue_row"."state" = 'voting' AND now() >=
6413 "issue_row"."fully_frozen" + "issue_row"."voting_time" )
6414 THEN
6415 "persist"."phase_finished" := TRUE;
6416 ELSE
6417 "persist"."phase_finished" := FALSE;
6418 END IF;
6419 IF
6420 NOT EXISTS (
6421 -- all initiatives are revoked
6422 SELECT NULL FROM "initiative"
6423 WHERE "issue_id" = "issue_id_p" AND "revoked" ISNULL
6424 ) AND (
6425 -- and issue has not been accepted yet
6426 "persist"."state" = 'admission' OR
6427 -- or verification time has elapsed
6428 ( "persist"."state" = 'verification' AND
6429 "persist"."phase_finished" ) OR
6430 -- or no initiatives have been revoked lately
6431 NOT EXISTS (
6432 SELECT NULL FROM "initiative"
6433 WHERE "issue_id" = "issue_id_p"
6434 AND now() < "revoked" + "issue_row"."verification_time"
6437 THEN
6438 "persist"."issue_revoked" := TRUE;
6439 ELSE
6440 "persist"."issue_revoked" := FALSE;
6441 END IF;
6442 IF "persist"."phase_finished" OR "persist"."issue_revoked" THEN
6443 UPDATE "issue" SET "phase_finished" = now()
6444 WHERE "id" = "issue_row"."id";
6445 RETURN "persist";
6446 ELSIF
6447 "persist"."state" IN ('admission', 'discussion', 'verification')
6448 THEN
6449 RETURN "persist";
6450 ELSE
6451 RETURN NULL;
6452 END IF;
6453 END IF;
6454 IF
6455 "persist"."state" IN ('admission', 'discussion', 'verification') AND
6456 coalesce("persist"."snapshot_created", FALSE) = FALSE
6457 THEN
6458 IF "persist"."state" != 'admission' THEN
6459 PERFORM "take_snapshot"("issue_id_p");
6460 PERFORM "finish_snapshot"("issue_id_p");
6461 ELSE
6462 UPDATE "issue" SET "issue_quorum" = "issue_quorum"."issue_quorum"
6463 FROM "issue_quorum"
6464 WHERE "id" = "issue_id_p"
6465 AND "issue_quorum"."issue_id" = "issue_id_p";
6466 END IF;
6467 "persist"."snapshot_created" = TRUE;
6468 IF "persist"."phase_finished" THEN
6469 IF "persist"."state" = 'admission' THEN
6470 UPDATE "issue" SET "admission_snapshot_id" = "latest_snapshot_id"
6471 WHERE "id" = "issue_id_p";
6472 ELSIF "persist"."state" = 'discussion' THEN
6473 UPDATE "issue" SET "half_freeze_snapshot_id" = "latest_snapshot_id"
6474 WHERE "id" = "issue_id_p";
6475 ELSIF "persist"."state" = 'verification' THEN
6476 UPDATE "issue" SET "full_freeze_snapshot_id" = "latest_snapshot_id"
6477 WHERE "id" = "issue_id_p";
6478 SELECT * INTO "issue_row" FROM "issue" WHERE "id" = "issue_id_p";
6479 FOR "initiative_row" IN
6480 SELECT * FROM "initiative"
6481 WHERE "issue_id" = "issue_id_p" AND "revoked" ISNULL
6482 FOR UPDATE
6483 LOOP
6484 IF
6485 "initiative_row"."polling" OR
6486 "initiative_row"."satisfied_supporter_count" >=
6487 "issue_row"."initiative_quorum"
6488 THEN
6489 UPDATE "initiative" SET "admitted" = TRUE
6490 WHERE "id" = "initiative_row"."id";
6491 ELSE
6492 UPDATE "initiative" SET "admitted" = FALSE
6493 WHERE "id" = "initiative_row"."id";
6494 END IF;
6495 END LOOP;
6496 END IF;
6497 END IF;
6498 RETURN "persist";
6499 END IF;
6500 IF
6501 "persist"."state" IN ('admission', 'discussion', 'verification') AND
6502 coalesce("persist"."harmonic_weights_set", FALSE) = FALSE
6503 THEN
6504 PERFORM "set_harmonic_initiative_weights"("issue_id_p");
6505 "persist"."harmonic_weights_set" = TRUE;
6506 IF
6507 "persist"."phase_finished" OR
6508 "persist"."issue_revoked" OR
6509 "persist"."state" = 'admission'
6510 THEN
6511 RETURN "persist";
6512 ELSE
6513 RETURN NULL;
6514 END IF;
6515 END IF;
6516 IF "persist"."issue_revoked" THEN
6517 IF "persist"."state" = 'admission' THEN
6518 "state_v" := 'canceled_revoked_before_accepted';
6519 ELSIF "persist"."state" = 'discussion' THEN
6520 "state_v" := 'canceled_after_revocation_during_discussion';
6521 ELSIF "persist"."state" = 'verification' THEN
6522 "state_v" := 'canceled_after_revocation_during_verification';
6523 END IF;
6524 UPDATE "issue" SET
6525 "state" = "state_v",
6526 "closed" = "phase_finished",
6527 "phase_finished" = NULL
6528 WHERE "id" = "issue_id_p";
6529 RETURN NULL;
6530 END IF;
6531 IF "persist"."state" = 'admission' THEN
6532 SELECT * INTO "issue_row" FROM "issue" WHERE "id" = "issue_id_p"
6533 FOR UPDATE;
6534 IF "issue_row"."phase_finished" NOTNULL THEN
6535 UPDATE "issue" SET
6536 "state" = 'canceled_issue_not_accepted',
6537 "closed" = "phase_finished",
6538 "phase_finished" = NULL
6539 WHERE "id" = "issue_id_p";
6540 END IF;
6541 RETURN NULL;
6542 END IF;
6543 IF "persist"."phase_finished" THEN
6544 IF "persist"."state" = 'discussion' THEN
6545 UPDATE "issue" SET
6546 "state" = 'verification',
6547 "half_frozen" = "phase_finished",
6548 "phase_finished" = NULL
6549 WHERE "id" = "issue_id_p";
6550 RETURN NULL;
6551 END IF;
6552 IF "persist"."state" = 'verification' THEN
6553 SELECT * INTO "issue_row" FROM "issue" WHERE "id" = "issue_id_p"
6554 FOR UPDATE;
6555 SELECT * INTO "policy_row" FROM "policy"
6556 WHERE "id" = "issue_row"."policy_id";
6557 IF EXISTS (
6558 SELECT NULL FROM "initiative"
6559 WHERE "issue_id" = "issue_id_p" AND "admitted" = TRUE
6560 ) THEN
6561 UPDATE "issue" SET
6562 "state" = 'voting',
6563 "fully_frozen" = "phase_finished",
6564 "phase_finished" = NULL
6565 WHERE "id" = "issue_id_p";
6566 ELSE
6567 UPDATE "issue" SET
6568 "state" = 'canceled_no_initiative_admitted',
6569 "fully_frozen" = "phase_finished",
6570 "closed" = "phase_finished",
6571 "phase_finished" = NULL
6572 WHERE "id" = "issue_id_p";
6573 -- NOTE: The following DELETE statements have effect only when
6574 -- issue state has been manipulated
6575 DELETE FROM "direct_voter" WHERE "issue_id" = "issue_id_p";
6576 DELETE FROM "delegating_voter" WHERE "issue_id" = "issue_id_p";
6577 DELETE FROM "battle" WHERE "issue_id" = "issue_id_p";
6578 END IF;
6579 RETURN NULL;
6580 END IF;
6581 IF "persist"."state" = 'voting' THEN
6582 IF coalesce("persist"."closed_voting", FALSE) = FALSE THEN
6583 PERFORM "close_voting"("issue_id_p");
6584 "persist"."closed_voting" = TRUE;
6585 RETURN "persist";
6586 END IF;
6587 PERFORM "calculate_ranks"("issue_id_p");
6588 RETURN NULL;
6589 END IF;
6590 END IF;
6591 RAISE WARNING 'should not happen';
6592 RETURN NULL;
6593 END;
6594 $$;
6596 COMMENT ON FUNCTION "check_issue"
6597 ( "issue"."id"%TYPE,
6598 "check_issue_persistence" )
6599 IS 'Precalculate supporter counts etc. for a given issue, and check, if status change is required, and perform the status change when necessary; Function must be called multiple times with the previous result as second parameter, until the result is NULL (see source code of function "check_everything")';
6602 CREATE FUNCTION "check_everything"()
6603 RETURNS VOID
6604 LANGUAGE 'plpgsql' VOLATILE AS $$
6605 DECLARE
6606 "area_id_v" "area"."id"%TYPE;
6607 "snapshot_id_v" "snapshot"."id"%TYPE;
6608 "issue_id_v" "issue"."id"%TYPE;
6609 "persist_v" "check_issue_persistence";
6610 BEGIN
6611 RAISE WARNING 'Function "check_everything" should only be used for development and debugging purposes';
6612 DELETE FROM "expired_session";
6613 DELETE FROM "expired_token";
6614 DELETE FROM "unused_snapshot";
6615 PERFORM "check_activity"();
6616 PERFORM "calculate_member_counts"();
6617 FOR "area_id_v" IN SELECT "id" FROM "area_with_unaccepted_issues" LOOP
6618 SELECT "take_snapshot"(NULL, "area_id_v") INTO "snapshot_id_v";
6619 PERFORM "finish_snapshot"("issue_id") FROM "snapshot_issue"
6620 WHERE "snapshot_id" = "snapshot_id_v";
6621 LOOP
6622 EXIT WHEN "issue_admission"("area_id_v") = FALSE;
6623 END LOOP;
6624 END LOOP;
6625 FOR "issue_id_v" IN SELECT "id" FROM "open_issue" LOOP
6626 "persist_v" := NULL;
6627 LOOP
6628 "persist_v" := "check_issue"("issue_id_v", "persist_v");
6629 EXIT WHEN "persist_v" ISNULL;
6630 END LOOP;
6631 END LOOP;
6632 DELETE FROM "unused_snapshot";
6633 RETURN;
6634 END;
6635 $$;
6637 COMMENT ON FUNCTION "check_everything"() IS 'Amongst other regular tasks, this function performs "check_issue" for every open issue. Use this function only for development and debugging purposes, as you may run into locking and/or serialization problems in productive environments. For production, use lf_update binary instead';
6641 ----------------------
6642 -- Deletion of data --
6643 ----------------------
6646 CREATE FUNCTION "clean_issue"("issue_id_p" "issue"."id"%TYPE)
6647 RETURNS VOID
6648 LANGUAGE 'plpgsql' VOLATILE AS $$
6649 BEGIN
6650 IF EXISTS (
6651 SELECT NULL FROM "issue" WHERE "id" = "issue_id_p" AND "cleaned" ISNULL
6652 ) THEN
6653 -- override protection triggers:
6654 INSERT INTO "temporary_transaction_data" ("key", "value")
6655 VALUES ('override_protection_triggers', TRUE::TEXT);
6656 -- clean data:
6657 DELETE FROM "delegating_voter"
6658 WHERE "issue_id" = "issue_id_p";
6659 DELETE FROM "direct_voter"
6660 WHERE "issue_id" = "issue_id_p";
6661 DELETE FROM "delegating_interest_snapshot"
6662 WHERE "issue_id" = "issue_id_p";
6663 DELETE FROM "direct_interest_snapshot"
6664 WHERE "issue_id" = "issue_id_p";
6665 DELETE FROM "non_voter"
6666 WHERE "issue_id" = "issue_id_p";
6667 DELETE FROM "delegation"
6668 WHERE "issue_id" = "issue_id_p";
6669 DELETE FROM "supporter"
6670 USING "initiative" -- NOTE: due to missing index on issue_id
6671 WHERE "initiative"."issue_id" = "issue_id_p"
6672 AND "supporter"."initiative_id" = "initiative_id";
6673 -- mark issue as cleaned:
6674 UPDATE "issue" SET "cleaned" = now() WHERE "id" = "issue_id_p";
6675 -- finish overriding protection triggers (avoids garbage):
6676 DELETE FROM "temporary_transaction_data"
6677 WHERE "key" = 'override_protection_triggers';
6678 END IF;
6679 RETURN;
6680 END;
6681 $$;
6683 COMMENT ON FUNCTION "clean_issue"("issue"."id"%TYPE) IS 'Delete discussion data and votes belonging to an issue';
6686 CREATE FUNCTION "delete_member"("member_id_p" "member"."id"%TYPE)
6687 RETURNS VOID
6688 LANGUAGE 'plpgsql' VOLATILE AS $$
6689 BEGIN
6690 UPDATE "member" SET
6691 "last_login" = NULL,
6692 "last_delegation_check" = NULL,
6693 "login" = NULL,
6694 "password" = NULL,
6695 "authority" = NULL,
6696 "authority_uid" = NULL,
6697 "authority_login" = NULL,
6698 "deleted" = coalesce("deleted", now()),
6699 "locked" = TRUE,
6700 "active" = FALSE,
6701 "notify_email" = NULL,
6702 "notify_email_unconfirmed" = NULL,
6703 "notify_email_secret" = NULL,
6704 "notify_email_secret_expiry" = NULL,
6705 "notify_email_lock_expiry" = NULL,
6706 "disable_notifications" = TRUE,
6707 "notification_counter" = DEFAULT,
6708 "notification_sample_size" = 0,
6709 "notification_dow" = NULL,
6710 "notification_hour" = NULL,
6711 "notification_sent" = NULL,
6712 "login_recovery_expiry" = NULL,
6713 "password_reset_secret" = NULL,
6714 "password_reset_secret_expiry" = NULL,
6715 "location" = NULL
6716 WHERE "id" = "member_id_p";
6717 DELETE FROM "member_settings" WHERE "member_id" = "member_id_p";
6718 DELETE FROM "member_profile" WHERE "member_id" = "member_id_p";
6719 DELETE FROM "rendered_member_statement" WHERE "member_id" = "member_id_p";
6720 DELETE FROM "member_image" WHERE "member_id" = "member_id_p";
6721 DELETE FROM "contact" WHERE "member_id" = "member_id_p";
6722 DELETE FROM "ignored_member" WHERE "member_id" = "member_id_p";
6723 DELETE FROM "session" WHERE "member_id" = "member_id_p";
6724 DELETE FROM "member_application" WHERE "member_id" = "member_id_p";
6725 DELETE FROM "token" WHERE "member_id" = "member_id_p";
6726 DELETE FROM "subscription" WHERE "member_id" = "member_id_p";
6727 DELETE FROM "ignored_area" WHERE "member_id" = "member_id_p";
6728 DELETE FROM "ignored_initiative" WHERE "member_id" = "member_id_p";
6729 DELETE FROM "delegation" WHERE "truster_id" = "member_id_p";
6730 DELETE FROM "non_voter" WHERE "member_id" = "member_id_p";
6731 DELETE FROM "direct_voter" USING "issue"
6732 WHERE "direct_voter"."issue_id" = "issue"."id"
6733 AND "issue"."closed" ISNULL
6734 AND "member_id" = "member_id_p";
6735 DELETE FROM "notification_initiative_sent" WHERE "member_id" = "member_id_p";
6736 RETURN;
6737 END;
6738 $$;
6740 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)';
6743 CREATE FUNCTION "delete_private_data"()
6744 RETURNS VOID
6745 LANGUAGE 'plpgsql' VOLATILE AS $$
6746 BEGIN
6747 DELETE FROM "temporary_transaction_data";
6748 DELETE FROM "temporary_suggestion_counts";
6749 DELETE FROM "member" WHERE "activated" ISNULL;
6750 UPDATE "member" SET
6751 "invite_code" = NULL,
6752 "invite_code_expiry" = NULL,
6753 "admin_comment" = NULL,
6754 "last_login" = NULL,
6755 "last_delegation_check" = NULL,
6756 "login" = NULL,
6757 "password" = NULL,
6758 "authority" = NULL,
6759 "authority_uid" = NULL,
6760 "authority_login" = NULL,
6761 "lang" = NULL,
6762 "notify_email" = NULL,
6763 "notify_email_unconfirmed" = NULL,
6764 "notify_email_secret" = NULL,
6765 "notify_email_secret_expiry" = NULL,
6766 "notify_email_lock_expiry" = NULL,
6767 "disable_notifications" = TRUE,
6768 "notification_counter" = DEFAULT,
6769 "notification_sample_size" = 0,
6770 "notification_dow" = NULL,
6771 "notification_hour" = NULL,
6772 "notification_sent" = NULL,
6773 "login_recovery_expiry" = NULL,
6774 "password_reset_secret" = NULL,
6775 "password_reset_secret_expiry" = NULL,
6776 "location" = NULL;
6777 DELETE FROM "verification";
6778 DELETE FROM "member_settings";
6779 DELETE FROM "member_useterms";
6780 DELETE FROM "member_profile";
6781 DELETE FROM "rendered_member_statement";
6782 DELETE FROM "member_image";
6783 DELETE FROM "contact";
6784 DELETE FROM "ignored_member";
6785 DELETE FROM "session";
6786 DELETE FROM "system_application";
6787 DELETE FROM "system_application_redirect_uri";
6788 DELETE FROM "dynamic_application_scope";
6789 DELETE FROM "member_application";
6790 DELETE FROM "token";
6791 DELETE FROM "subscription";
6792 DELETE FROM "ignored_area";
6793 DELETE FROM "ignored_initiative";
6794 DELETE FROM "non_voter";
6795 DELETE FROM "direct_voter" USING "issue"
6796 WHERE "direct_voter"."issue_id" = "issue"."id"
6797 AND "issue"."closed" ISNULL;
6798 DELETE FROM "event_processed";
6799 DELETE FROM "notification_initiative_sent";
6800 DELETE FROM "newsletter";
6801 RETURN;
6802 END;
6803 $$;
6805 COMMENT ON FUNCTION "delete_private_data"() IS 'Used by lf_export script. DO NOT USE on productive database, but only on a copy! This function deletes all data which should not be publicly available, and can be used to create a database dump for publication. See source code to see which data is deleted. If you need a different behaviour, copy this function and modify lf_export accordingly, to avoid data-leaks after updating.';
6809 COMMIT;

Impressum / About Us