Реализация counter() для SQLIte

В заметке Счетчики в SQLite я уже упоминал про функцию counter(), позволяющую генерировать последовательные номера для возвращаемых запросом записей. В апстрим эта функция не включена и поныне, потому полагаю небесполезным привести здесь соответствующий патч. Полагаю описание функции в комментарии к коду исчерпывающим.


--- sqlite3-3.6.19.orig/src/func.c
+++ sqlite3-3.6.19/src/func.c
@@ -1397,6 +1397,35 @@
}

/*
+** Implementation of the counter(X) function. If X is an integer
+** constant, then the first invocation will return X. The second X+1.
+** and so forth. Can be used (for example) to provide a sequence number
+** in a result set.
+*/
+static void counterFunc(
+ sqlite3_context *pCtx, /* Function context */
+ int nArg, /* Number of function arguments */
+ sqlite3_value **argv /* Values for all function arguments */
+){
+ int i;
+ int *pCounter;
+
+ pCounter = (int*)sqlite3_get_auxdata(pCtx, 0);
+ if( pCounter==0 ){
+ pCounter = sqlite3_malloc( sizeof(*pCounter) );
+ if( pCounter==0 ){
+ sqlite3_result_error_nomem(pCtx);
+ return;
+ }
+ *pCounter = sqlite3_value_int(argv[0]);
+ sqlite3_set_auxdata(pCtx, 0, pCounter, sqlite3_free);
+ }else{
+ ++*pCounter;
+ }
+ sqlite3_result_int(pCtx, *pCounter);
+}
+
+/*
** All all of the FuncDef structures in the aBuiltinFunc[] array above
** to the global function hash table. This occurs at start-time (as
** a consequence of calling sqlite3_initialize()).
@@ -1476,6 +1505,7 @@
LIKEFUNC(like, 2, &likeInfoNorm, SQLITE_FUNC_LIKE),
LIKEFUNC(like, 3, &likeInfoNorm, SQLITE_FUNC_LIKE),
#endif
+ FUNCTION(counter, 1, 0, 0, counterFunc ),
};

int i;

Comments

Popular posts from this blog

Открытый софт для научных расчетов

Счетчики в SQLite

Модем Huawei E1550 в debian