Created
January 16, 2016 07:29
-
-
Save proprietary/edff60a48aa3d4a362e6 to your computer and use it in GitHub Desktop.
sqlite3 how to get column index by column name
This file contains hidden or 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
#include <stdlib.h> | |
#include "../sqlite3/sqlite3.h" | |
#include "domain.h" | |
/* okay this function is stolen; the rest are MINE */ | |
unsigned long | |
djb2Hash(unsigned char *str) | |
{ | |
unsigned long hash = 5381; | |
int c; | |
while (c = *str++) | |
hash = ((hash << 5) + hash) + c; /* hash * 33 + c */ | |
return hash; | |
} | |
const char **getColumnNames(sqlite3_stmt *stmt) { | |
/* | |
* Caller must free() the return value | |
*/ | |
int columnCount = sqlite3_column_count(stmt); | |
const char **ret = malloc(sizeof(const char *) * columnCount + 1); | |
//const char **iter = ret; | |
int i = 0; | |
for(; i < columnCount; i++) { | |
//*(iter++) = sqlite3_column_name(stmt, i); | |
ret[i] = sqlite3_column_name(stmt, i); | |
} | |
//iter = NULL; | |
ret[i] = NULL; | |
return ret; | |
} | |
unsigned long *hashStringArray(const char **arr) { | |
/* | |
* Returns a new array of integer hash values | |
* | |
* Caller must free return value | |
*/ | |
//Find length of arr | |
int len = 0; | |
for(const char **it = arr; it != NULL; it++) { | |
++len; | |
} | |
//Make the hashes | |
unsigned long *ret = malloc(sizeof(unsigned long) * len + 1); | |
int k = 0; | |
for(const char **it = arr; it != NULL; it++) { | |
ret[k++] = djb2Hash((unsigned char *) *it); | |
} | |
ret[k] = 0; | |
return ret; | |
} | |
unsigned long *getHashedColumnNames(sqlite3_stmt *stmt) { | |
/* | |
* Caller must free return value | |
*/ | |
const char **columnNames = getColumnNames(stmt); | |
unsigned long *ret = hashStringArray(columnNames); | |
free(columnNames); | |
return ret; | |
} | |
int getColumnIndexByName(sqlite3_stmt *stmt, const char *columnName) { | |
/* | |
* High level function to get the integer | |
* column index from a string that's the | |
* column name | |
*/ | |
unsigned long *const hashedColumnNames = getHashedColumnNames(stmt); | |
unsigned long hashedColumnName = djb2Hash((unsigned char *) columnName); | |
int columnIndex = 0; | |
for(unsigned long *it = hashedColumnNames; | |
*it; it++, columnIndex++) { | |
if(*it == hashedColumnName) { | |
free(hashedColumnNames); | |
return columnIndex; | |
} | |
} | |
free(hashedColumnNames); | |
return -1; //failure | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment