Skip to content

Commit bb6c128

Browse files
authored
Merge pull request #68 from GeneralMagicio/add-quadraticWeights-to-Vote
add quadraticWeights to Vote
2 parents 767ca02 + 4ca950f commit bb6c128

File tree

3 files changed

+35
-0
lines changed

3 files changed

+35
-0
lines changed

package.json

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,7 @@
1313
"start:dev": "nest start --watch",
1414
"start:debug": "nest start --debug --watch",
1515
"start:prod": "node dist/main",
16+
"migration:local": "npx prisma migrate dev --create-only",
1617
"migration:prod": "npx prisma migrate deploy",
1718
"lint": "eslint \"{src,apps,libs,test}/**/*.ts\" --fix",
1819
"test": "jest",
Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,33 @@
1+
-- Create a function to calculate quadratic weights from the weight distribution
2+
CREATE OR REPLACE FUNCTION calculate_quadratic_weights(weight_dist JSONB)
3+
RETURNS JSONB AS $$
4+
DECLARE
5+
result JSONB := '{}'::JSONB;
6+
option_key TEXT;
7+
weight_value NUMERIC;
8+
BEGIN
9+
-- Check if weight_dist is NULL or not an object
10+
IF weight_dist IS NULL OR jsonb_typeof(weight_dist) != 'object' THEN
11+
RETURN '{}'::JSONB;
12+
END IF;
13+
14+
FOR option_key, weight_value IN
15+
SELECT key, (value::text)::NUMERIC
16+
FROM jsonb_each(weight_dist)
17+
LOOP
18+
-- Handle potential non-numeric values
19+
BEGIN
20+
result := result || jsonb_build_object(option_key, SQRT(weight_value));
21+
EXCEPTION WHEN others THEN
22+
-- If conversion fails, skip this entry
23+
CONTINUE;
24+
END;
25+
END LOOP;
26+
27+
RETURN result;
28+
END;
29+
$$ LANGUAGE plpgsql IMMUTABLE;
30+
31+
-- Add the generated column to the Vote table
32+
ALTER TABLE "Vote" ADD COLUMN "quadraticWeights" JSONB
33+
GENERATED ALWAYS AS (calculate_quadratic_weights("weightDistribution"::JSONB)) STORED;

prisma/schema.prisma

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -60,6 +60,7 @@ model Vote {
6060
pollId Int
6161
votingPower Int
6262
weightDistribution Json
63+
quadraticWeights Json? // DO NOT INSERT INTO THIS, THIS IS A GENERATED COLUMN
6364
proof String
6465
user User @relation(fields: [userId], references: [id])
6566
poll Poll @relation(fields: [pollId], references: [pollId], onDelete: Cascade)

0 commit comments

Comments
 (0)