Created
December 19, 2022 03:03
-
-
Save rtldg/0bfa5e63490a609e1264f6cd0d08be34 to your computer and use it in GitHub Desktop.
Test sqlite extension for bhoptimer's GetWeightedPoints
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// SPDX-License-Identifier: CC0 | |
/* vim: set ts=2 : */ | |
/* | |
This is basically: | |
SELECT SUM(p2) | |
FROM ( | |
SELECT (points * POW(?, ROW_NUMBER() OVER (ORDER BY points DESC) -1)) AS p2 | |
FROM playertimes WHERE auth = ? ORDER BY points DESC LIMIT ?; | |
); | |
*/ | |
#include "sqlite/sqlite3ext.h" | |
SQLITE_EXTENSION_INIT1 | |
// GetWeightedPoints(auth, "%splayertimes", weightingLimit, weightingMultiplier) | |
static void GetWeightedPointsFunc( | |
sqlite3_context *context, | |
int argc, | |
sqlite3_value **argv | |
){ | |
sqlite3 *db = sqlite3_context_db_handle(context); | |
sqlite3_stmt *getPoints; | |
// I would've preferred to cache the getPoints stmt. | |
// But it makes closing the database messy and throw errors. | |
// xDestroy isn't called soon enough to finalize it... | |
// There's no extension de-init function to finalize it in... | |
// Well, fuck me. | |
char query[256]; | |
sqlite3_snprintf(sizeof(query), query, | |
"SELECT points FROM `%s` WHERE auth = ? AND points > 0 ORDER BY points DESC LIMIT %d;", | |
sqlite3_value_text(argv[1]), sqlite3_value_int(argv[2])); | |
if (SQLITE_OK != sqlite3_prepare_v2(db, query, -1, &getPoints, 0)) { | |
sqlite3_result_double(context, 0.0); | |
return; | |
} | |
sqlite3_bind_int(getPoints, 1, sqlite3_value_int(argv[0])); // auth/steamid | |
double weightingMultiplier = sqlite3_value_double(argv[3]); | |
double total = 0.0, mult = 1.0; | |
while (SQLITE_ROW == sqlite3_step(getPoints)) { | |
double points = sqlite3_column_double(getPoints, 0); | |
total += (points * mult); | |
mult *= weightingMultiplier; | |
} | |
sqlite3_finalize(getPoints); | |
sqlite3_result_double(context, total); | |
} | |
#ifdef _WIN32 | |
__declspec(dllexport) | |
#endif | |
int sqlite3_sqlitebhoptimerweightedpoints_init( | |
sqlite3 *db, | |
char **pzErrMsg, | |
const sqlite3_api_routines *pApi | |
){ | |
int rc = SQLITE_OK; | |
SQLITE_EXTENSION_INIT2(pApi); | |
rc = sqlite3_create_function_v2(db, "GetWeightedPoints", 4, | |
SQLITE_UTF8, 0, GetWeightedPointsFunc, 0, 0, 0); | |
return rc; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment